text:
# AmqpMathToolIntegration

## License

**MIT license. Please make sure to read and understand the file [LICENSE](./LICENSE)!**

## Author

Petri Kannisto, Tampere University, Finland

## Introduction

This application enables you to communicate via AMQP/RabbitMQ with Matlab.
It can be included as such in Matlab, because it is a Java library.
The reception of messages is synchronous, that is, you must poll for new messages.
Whenever one or more messages appear, they remain in a message queue in the
AMQP broker until you retrieve them.

If you want to retrieve messages as events as soon as they arrive in the queue, please look at [https://github.com/kannisto/Cocop.AmqpMathToolConnector](https://github.com/kannisto/Cocop.AmqpMathToolConnector).

While AMQP provides multiple messaging modes, this application only uses topic-based communication.

This repository contains an entire Eclipse workspace. The included applications are as follows:

* AmqpMathToolIntegration: the actual connector application
* AmqpMathToolIntegrationTest: console application to test connecting with the message bus
* AmqpPropsManagerUnitTest: JUnit unit test for the AmqpPropsManager class

## Environment and Libraries

For execution, the following should do it:

* Java: JDK/JRE 8 or newer
* Matlab: 2017 or newer

The following libraries were utilised in development:

* amqp-client-4.2.2.jar
    * see https://www.rabbitmq.com/download.html
* amqp-client-4.2.2-javadoc.jar
* commons-logging-1.2.jar
* slf4j-api-1.7.25.jar
* slf4j-nop-1.7.25.jar

## Known Limitations

The software always assumes '/' as the vhost on AMQP server, which is the
default.
Therefore, you cannot presumably connect to CloudAMQP that forces you to use
another vhost.

## Usage in Matlab

To utilise the AMQP connector in Matlab, you can follow these instructions.

* If you are new to RabbitMQ, you should first try it without Matlab
    * Matlab adds more difficulty to the first experiments
    * For tutorials, see https://www.rabbitmq.com/getstarted.html
* To debug your code, it is advisable to implement a simple publisher and subscriber in another environment

Once you have established a connection, you communicate in Matlab as follows:

* To publish (or send) a message, you simply call the respective function
* To receive messages
    * you listen to one or more topics
    * you call the dedicated function to check if any messages have arrived

### Adding JAR libraries to classpath

Matlab must have an access to the required JAR libraries. Steps:

1. Retrieve "AmqpMathToolIntegration" as a JAR file
    * alternatively, you can build your own JAR from source code
2. Retrieve the following libraries as JAR files (it is unclear if the versions can be different):
    * amqp-client-4.2.2.jar
        * see https://www.rabbitmq.com/download.html
    * commons-logging-1.2.jar
    * slf4j-api-1.7.25.jar
    * slf4j-nop-1.7.25.jar
3. Copy the JAR files to whatever folder you want to (such as 'C:\\myclasspath')
    * please avoid a filepath with spaces
4. In your Matlab preferences folder, create a file called 'javaclasspath.txt'
    * to locate this folder, use the 'prefdir' command
        * see https://se.mathworks.com/help/matlab/ref/prefdir.html
    * in the classpath file, add the full path of each JAR file
        * e.g., ```C:\myclasspath\procemplus_amqpmathtoolintegration.jar```

### Receiving messages with message queue

The following code creates an object that will receive messages from the specified topic to a message queue.
The message queue is located in the broker server, and any received messages remain there until you ask
to receive them.

* You can listen to as many topics as needed
    * you must specify all topics as a constructor parameter
* Replace the parameters ('myhost.com', etc.) with the ones relevant to you

```
% Specifying topics to listen to
topicIn1 = 'topic.in.1';
topicIn2 = 'topic.in.2';

% Specify AMQP properties
amqpProps = fi.procemplus.amqp2math.AmqpPropsManager('myhost.com', 'my.exchange', 'user-x', 'my-password');

% If using a non-secure connection (i.e., no encryption with TLS):
amqpProps.setSecure(false);

% If you need to enable "durable" and "auto delete" flags for the exchange:
amqpProps.setExchangeDurable(true);
amqpProps.setExchangeAutoDelete(true);

% Specify topics to listen to
topicsIn = javaArray('java.lang.String', 2);
topicsIn(1) = java.lang.String(topicIn1);
topicsIn(2) = java.lang.String(topicIn2);

% Set up AMQP connector
amqpConnector = fi.procemplus.amqp2math.AmqpTopicConnectorSync(amqpProps, topicsIn);

% Check if any messages have been received from the topics.
% This will return null/empty if there is currently nothing in the queue.
% If there are multiple messages, these are returned with First In First Out (FIFO).
message = amqpConnector.getMessage();
routingKey = message.getRoutingKey();
messageBodyBytes = message.getBody();
```

### Publishing (sending) to AMQP

The following code sends a string encoded in UTF-8.

```
myStringOut = java.lang.String('Hello 5');
myBytesOut = myStringOut.getBytes(java.nio.charset.Charset.forName('UTF-8'));
amqpConnector.sendMessage('my.topic.Out', myBytesOut);
```

### Cleanup

It is important to clean up resources after use. Call this when you end execution:

```
amqpConnector.close();
```

repository: simcesplatform/AmqpMathToolIntegration

repo_name: simcesplatform/AmqpMathToolIntegration


text:
# README

Scrapes the messages in the current Olark conversation and sends the messages to a specified API.
This assumes you have made a backend that responds to `/documents?document=Conversational%20messages%20between%20people`.
Response object should be like the following:

```
[
  {
    url: 'https://olark.com/transcripts/show/123hnth4hobuatmntmaonteush',
    Cosine similarity: 0.345566,
    Conversation: [
      {
        message: 'I need some help',
        author: 'Jenny'
      },
      {
        message: 'Hello, Jenny. Thanks for reaching out.',
        author: 'Edderic'
      },
      {
        message: 'My name is Edderic. How may I help you today?',
        author: 'Edderic'
      },
      {
        message: 'I am not quite sure when my item will arrive...',
        author: 'Jenny'
      },
    ]
  },
  {
    url: 'https://olark.com/transcripts/show/totog1902309hntoeuthsatheu',
    Cosine similarity: 0.123456,
    Conversation: [
      {
        message: 'Hi there',
        author: 'Elizabeth'
      },
      {
        message: 'Hello, Elizabeth. Thanks for reaching out.',
        author: 'Edderic'
      },
      {
        message: 'My name is Edderic. How may I help you today?',
        author: 'Edderic'
      },
      {
        message: 'It seems that this device is broken.',
        author: 'Elizabeth'
      },
    ]
  }
]
```

## Installation

1. Download the folder
2. Open up Google Chrome
3. Visit `chrome://extensions`
4. Hit `Load unpacked extension...` You should see the extension displayed on the top right part of chrome.
5. Select the folder.
6. Visit `https://chat.olark.com`
7. Press on the extension button.
8. Type the URL of the endpoint.
9. Click on the extension button again, and wait for the response from the server.
10. Make sure you have a live conversation with someone, and that there exists at least a message.
11. You should see five of the most relevant chats.

license: MIT

repository: Edderic/olark-chrome-extension

branch_name: refs/heads/master

extension: markdown

license_type: permissive

repo_name: Edderic/olark-chrome-extension


text:
# Spark Remote Shuffle Plugin

Remote Shuffle is a Spark ShuffleManager plugin, shuffling data through a remote Hadoop-compatible file system, as opposed to vanilla Spark's local-disks.

This is an essential part of enabling Spark on disaggregated compute and storage architecture.

## Build and Deploy

Build the project using the following command or download the pre-built jar: remote-shuffle-\<version\>.jar. This file needs to
be deployed on every compute node that runs Spark. Manually place it on all nodes or let resource manager do the work.

```
    mvn -DskipTests clean package
```

## Enable Remote Shuffle

Add the jar files to the classpath of Spark driver and executors: Put the
following configurations in spark-defaults.conf or Spark submit command line arguments.

Note: For DAOS users, DAOS Hadoop/Java API jars should also be included in the classpath as we leverage DAOS Hadoop filesystem.

```
    spark.executor.extraClassPath              /path/to/remote-shuffle-dir/remote-shuffle-<version>.jar
    spark.driver.extraClassPath                /path/to/remote-shuffle-dir/remote-shuffle-<version>.jar
```

Enable the remote shuffle manager and specify the Hadoop storage system URI holding shuffle data.

```
    spark.shuffle.manager                      org.apache.spark.shuffle.remote.RemoteShuffleManager
    spark.shuffle.remote.storageMasterUri      daos://default:1 # Or hdfs://namenode:port, file:///my/shuffle/dir
```

## Configurations

Configurations and tuning parameters that change the behavior of remote shuffle. Most of them should work well under default values.

### Shuffle Root Directory

This is to configure the root directory holding remote shuffle files. For each Spark application, a
directory named after application ID is created under this root directory.

```
    spark.shuffle.remote.filesRootDirectory     /shuffle
```

### Index Cache Size

This is to configure the cache size for shuffle index files per executor. Shuffle data includes data files and
index files. An index file is small but will be read many (the number of reducers) times. On a large scale, constantly
reading these small index files from Hadoop Filesystem implementation(i.e. HDFS) is going to cause much overhead and latency. In addition, the shuffle files’
transfer completely relies on the network between compute nodes and storage nodes. But the network inside compute nodes are
not fully utilized. The index cache can eliminate the overhead of reading index files from storage cluster multiple times. By
enabling index file cache, a reduce task fetches them from the remote executors who write them instead of reading from
storage. If the remote executor doesn’t have a desired index file in its cache, it will read the file from storage and cache
it locally. The feature can also be disabled by setting the value to zero.

```
    spark.shuffle.remote.index.cache.size        30m
```

### Number of Threads Reading Data Files

This is one of the parameters influencing shuffle read performance. It is to determine number of threads per executor reading shuffle data files from storage.

```
    spark.shuffle.remote.numReadThreads           5
```

### Number of Threads Transitioning Index Files (when index cache is enabled)

This is one of the parameters influencing shuffle read performance. It is to determine the number of client and server threads that transmit index information from another executor’s cache. It is only valid when the index cache feature is enabled.

```
    spark.shuffle.remote.numIndexReadThreads      3
```

### Bypass-merge-sort Threshold

This threshold is used to decide using bypass-merge(hash-based) shuffle or not. By default we disable(by setting it to -1)
hash-based shuffle writer in remote shuffle, because when memory is relatively sufficient, sort-based shuffle writer is often more efficient than the hash-based one.
Hash-based shuffle writer entails a merging process, performing 3x I/Os than total shuffle size: 1 time for read I/Os and 2 times for write I/Os, this can be an even larger overhead under remote shuffle:
the 3x shuffle size is gone through network, arriving at a remote storage system.

```
    spark.shuffle.remote.bypassMergeThreshold     -1
```

### Configurations fetching port for HDFS

When the backend storage is HDFS, we contact http://$host:$port/conf to fetch configurations. They were not locally loaded because we assume absence of local storage.

```
    spark.shuffle.remote.hdfs.storageMasterUIPort  50070
```

### Inherited Spark Shuffle Configurations

These configurations are inherited from upstream Spark, they are still supported in remote shuffle. More explanations can be found in [Spark core docs](https://spark.apache.org/docs/3.0.0/configuration.html#shuffle-behavior) and [Spark SQL docs](https://spark.apache.org/docs/3.0.0/sql-performance-tuning.html).
```
    spark.reducer.maxSizeInFlight
    spark.reducer.maxReqsInFlight
    spark.reducer.maxBlocksInFlightPerAddress
    spark.shuffle.compress
    spark.shuffle.file.buffer
    spark.shuffle.io.maxRetries
    spark.shuffle.io.numConnectionsPerPeer
    spark.shuffle.io.preferDirectBufs
    spark.shuffle.io.retryWait
    spark.shuffle.io.backLog
    spark.shuffle.spill.compress
    spark.shuffle.accurateBlockThreshold
    spark.sql.shuffle.partitions
```

### Deprecated Spark Shuffle Configurations

These configurations are deprecated and will not take effect.
```
    spark.shuffle.sort.bypassMergeThreshold        # Replaced by spark.shuffle.remote.bypassMergeThreshold
    spark.maxRemoteBlockSizeFetchToMem             # As we assume no local disks on compute nodes, shuffle blocks are all fetched to memory

    spark.shuffle.service.enabled                  # All following configurations are related to External Shuffle Service. ESS & remote shuffle cannot be enabled at the same time, as this remote shuffle facility takes over almost all functionalities of ESS.
    spark.shuffle.service.port
    spark.shuffle.service.index.cache.size
    spark.shuffle.maxChunksBeingTransferred
    spark.shuffle.registration.timeout
    spark.shuffle.registration.maxAttempts
```

repository: JkSelf/OAP

extension: md

repo_name: JkSelf/OAP


text:
# ImageNet-Utils
Utils to help download images, crop bounding box, GUI tool to annotate image in XML file etc.

Grap the source

`$ git clone --recursive https://github.com/tzutalin/ImageNet_Utils.git`

## Get All image classes shuffled, prallel download
#Not required
`awk '{print $1}' fall11_urls.txt | rev |cut -d '_' -f 2 |rev | uniq | shuf > image_classes.txt`

`for j  in $(awk 'NR<=5000 {print $0}' image_classes_shuffled); do ./downloadutils.py --downloadImages --wnid $j & done`

### Requirements
If you would like to download the original images, you should signup [ImageNet](http://www.image-net.org/)

### Usage - Download images:
Get the urls of wnid and download all of them. E.g., download [Dog images from ImageNet](http://www.image-net.org/synset?wnid=n02084071) and save images to ./n02084071/url_images/*.jpg

`$ ./downloadutils.py --downloadImages --wnid n02084071`

Download all original images. E.g., download the original images about [person](http://www.image-net.org/synset?wnid=n00007846) and save to ./n00007846/n00007846_original_images/*.JPEG

`$ ./downloadutils.py --downloadOriginalImages --wnid n00007846`

Download the boundingbox xml of wnid. E.g., download  bounding boxes of original images about [person](http://www.image-net.org/synset?wnid=n00007846)

`$ ./downloadutils.py --downloadBoundingBox --wnid n00007846`

### Usage - Label images into text files:
Utils to create train.txt, val.txt, and test.txt

Format: [FilePath] [id]

Use the bellow cmd, and you can get image path and its label in train.txt and test.txt

`$ ./labelcreator.py --size_of_train 1400 --size_of_test 200  --label 11 --dir ./car`

Auto assign a label to each folder containing images under the dir. Create train.txt, val.txt, and test.txt. Size is 1200, 300, and 300

`$ ./labelcreator.py --size_of_train 1200 --size_of_val 300 --size_of_test 300`

### Usage - Crop the image by annotation XML:
Search the specified image according to its boudingbox's xml, so-called annotation file. If found, it will crop and save as ./boundingbox/*.JPEG

`$ ./bbox_helper.py --save_boundingbox --bxmlpath n00007846/Annotation/n00007846/n00007846_23985.xml `

Output:

    ./n00007846/n00007846_original_images/n00007846_23985.JPEG

    [[227, 25, 323, 91]]
    save to n00007846/bounding_box_imgs/n00007846_23985_box1.JPEG

Specify a directory and crop the images according its annotation file

`$ ./bbox_helper.py --save_boundingbox --bxmldir n00007846/`

Output:

    ./n00007846/n00007846_original_images/n00007846_35737.JPEG
    [[46, 99, 165, 290]]
    save to n00007846/bounding_box_imgs/n00007846_35737_box1.JPEG
    ./n00007846/n00007846_original_images/n00007846_132010.JPEG
    [[101, 57, 330, 497]]
    save to n00007846/bounding_box_imgs/n00007846_132010_box1.JPEG
    ./n00007846/n00007846_original_images/n00007846_158081.JPEG
    [[55, 85, 249, 498]]
    .....

### Usage - Use a GUI tool to create a annotation XML:

![](demo/demo.png)

`$ git submodule init`

`$ git submodule update --recursive`

`$ sudo apt-get install pyqt4-dev-tools`

`$ cd labelImgGUI`

`$ make all`

`$ ./labelImg.py`

More Info:
 [labelImg](https://github.com/tzutalin/labelImg)

 [Video demo](https://www.youtube.com/watch?v=p0nR2YsCY_U)

### Usage - Convert Pascal Bounding Boxes to Dlib format:
Script to convert bounding boxes in Pascal format (e.g., demo/pascalBoxes/) to bounding boxes in Dlib format (e.g., demo/dlibDetBoxes.xml).

`./boxesCvtPascaltoDlib.py <path/to/pascal/boxes> <path/to/img/folder> --out out.xml`

### LICENSE
Copyright (C) <2015-2016> TzuTa Lin and Will Kao

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

gha_license_id: MIT


text:
# Deployments
Now. We provide three ways to test the ovs-cni plugin.
1. The single host vagrantfile, you can use the docker/namespace to try the ovs-cni plugin.
2. We also provide the vagrantfile for kubernetes cluster, the vagrantfile will create two virtual machines and form a kubernetes cluster and you can use ovs-cni plugin as your kubernetes network.
3. The kubespray script to setup a simple kubernetes cluster with Multus-cni and ovs-cni. The kubespray is a git submodule and you should sync first before you start to use it. After you clone the kubespray project, just type `vagrant up` in that directory and you can use the `vagrant ssh k8s-01` to the k8s master after the installation has completed.

Go into each directory to learn how to use those vagrantfile.

repository: John-Lin/ovs-cni

gha_language: Go

repo_name: John-Lin/ovs-cni


text:
---
layout: tutorials
title: Publish/Subscribe
summary: Learn how to pub/sub using OpenMAMA with the Solace middleware bridge.
icon: I_dev_P+S.svg
links:
    - label: mama.properties
      link: /blob/master/src/pubsub/mama.properties
    - label: topicSubscriber.c
      link: blob/master/src/pubsub/topicSubscriber.c
    - label: topicPublisher.c
      link: /blob/master/src/pubsub/topicPublisher.c
    - label: feedback
      link: https://github.com/SolaceDev/solace-dev-tutorials/blob/master/src/pages/tutorials/openmama/publish-subscribe.md
---

## Assumptions

This tutorial assumes the following:

*   You are familiar with OpenMAMA [core concepts](https://docs.solace.com/Solace-OpenMama/Solace-OpenMAMA-Overview.htm).
    *   If not, see [this OpenMAMA guide](https://openmama.finos.org/quickstart) and [Solace OpenMAMA “Hello World” tutorial](../hello-world/).
*   You are familiar with Solace [core concepts](https://docs.solace.com/PubSub-Basics/Core-Concepts.htm).
*   You have access to a properly installed OpenMAMA [release](https://github.com/OpenMAMA/OpenMAMA/releases).
    *   Solace middleware bridge with its dependencies is also installed
*   You have access to Solace messaging with the following configuration details:
    *   Connectivity information for a Solace message-VPN
    *   Enabled client username and password

One simple way to get access to Solace messaging quickly is to create a messaging service in Solace Cloud [as outlined here](https://www.solace.com/cloud/). You can find other ways to get access to Solace messaging below.

## Goals

The goal of this tutorial is to demonstrate basic messaging interactions using OpenMAMA with the **Solace middleware bridge**. This tutorial’s samples are similar to the OpenMAMA’s [mamapublisherc.c](https://github.com/OpenMAMA/OpenMAMA/blob/master/mama/c_cpp/src/examples/c/mamapublisherc.c) and [mamasubscriberc.c](https://github.com/OpenMAMA/OpenMAMA/blob/master/mama/c_cpp/src/examples/c/mamasubscriberc.c), but with a distinct focus on configuring OpenMAMA with **Solace messaging**. See the [Resources](#resources) section below for some further links to other OpenMAMA tutorials and examples.

This tutorial will show you how to publish a message with one string field to a specific topic on Solace messaging using OpenMAMA C API.

This tutorial will show you how to use OpenMAMA C API:

*   to build and send a message on a topic
*   to subscribe to a topic and receive a message

## Installation

Installation instructions for OpenMAMA can be found on [OpenMAMA Wiki](https://openmama.finos.org/quickstart#main).

Simplified installation instructions for OpenMAMA with Solace middleware bridge [are available](../installation-linux/).

For building OpenMAMA from source see [OpenMAMA Wiki](https://github.com/OpenMAMA/OpenMAMA/wiki/Build-Instructions).

`markdown:solaceMessaging-part1.md`
![Screenshot: Messaging Connectivity Information](../../../images/screenshots/connectivity-info.png)
`markdown:solaceMessaging-part2.md`

Example of specifying these properties [see here](https://github.com/SolaceSamples/solace-samples-openmama/blob/master/src/pubsub/mama.properties) and detailed explanation of them is in the [Solace OpenMAMA “Hello World” tutorial](../hello-world/).

## Receiving Message

Before everything else, as you already know from the [Solace OpenMAMA “Hello World” tutorial](../hello-world/), we need to [initialize](../hello-world/#initialize) the **Solace middleware bridge** and [create a transport](../hello-world/#create-transport).

To learn more about how to initialize and configure **Solace middleware bridge as an OpenMAMA transport** see [Solace OpenMAMA User Guide](https://docs.solace.com/Solace-OpenMama/Configuring-Solace-OpenMAMA-Bridges.htm).

Now we can implement receiving a message.

First, let’s express interest in messages by subscribing to a topic. Then you can look at publishing a matching message and see it received.

In OpenMAMA subscribing to a topic means _creating a subscription_. When creating a subscription, we need to refer to a _transport_, a _receiver_ and to an _event queue_.

You already know what the **transport** is.

For details of the **event queue** see [OpenMAMA Developer’s Guide for C](https://docplayer.net/5669811-Openmama-developer-s-guide-for-c.html).

When multi-threading is not required it is recommended to use the _default internal event queue_ as an _event queue_:

```cpp
mamaQueue defaultQueue;
mama_getDefaultEventQueue(global.bridge, &defaultQueue))
```

The **receiver** is a data structure with function pointers that are invoked by OpenMAMA when certain events happen.

It has a type of `mamaMsgCallbacks` and it is expected to have, as a minimum, the following function pointers:

*   `onCreate` that is invoked when a subscription is created
*   `onError` that is invoked when an error occurs
*   `onMsg` that is invoked when a message arrives on the subscribed topic

This is how the routine for creating a subscription is implemented:

```cpp
void subscribeToTopic(const char * topicName)
{
    global.subscription = NULL;
    mama_status status;
    if ((status = mamaSubscription_allocate(&global.subscription)) == MAMA_STATUS_OK)
    {
        // initialize functions called by MAMA on different subscription events
        memset(&global.receiver, 0, sizeof(global.receiver));
        global.receiver.onCreate = onCreate;
        global.receiver.onError = onError;
        global.receiver.onMsg = onMessage;

        mamaQueue defaultQueue;
        if (((status = mama_getDefaultEventQueue(global.bridge, &defaultQueue)) == MAMA_STATUS_OK) &&
            ((status = mamaSubscription_createBasic(global.subscription, global.transport,
                                                    defaultQueue,
                                                    &global.receiver,
                                                    topicName,
                                                    NULL)) == MAMA_STATUS_OK))
        {
            // normal exit
            return;
        }
    }
    // error exit
    printf("Error subscribing to topic %s, error code: %s\n", topicName,
            mamaStatus_stringForStatus(status));
    mama_close();
    exit(status);
}
```

Notice that `global.receiver` is assigned with pointers to functions we want to be invoked by OpenMAMA when corresponding events happen.

When a subscription is created, we want to see its topic name on the console:

```cpp
void onCreate(mamaSubscription subscription, void * closure)
{
    const char * topicName = NULL;
    if (mamaSubscription_getSymbol(subscription, &topicName) == MAMA_STATUS_OK)
    {
        printf("Created subscription to topic \"%s\"\n", topicName);
    }
}
```

When an error occurs, we want to see on the console the error code:

```cpp
void onError(mamaSubscription subscription, mama_status status,
        void * platformError, const char * subject, void * closure)
{
    const char * topicName = NULL;
    if (mamaSubscription_getSymbol(subscription, &topicName) == MAMA_STATUS_OK)
    printf("Error occured with subscription to topic \"%s\", error code: %s\n",
            topicName, mamaStatus_stringForStatus(status));
}
```

When a message arrives, we extract from the message the topic name and a custom string field we know was added to that message:

```cpp
void onMessage(mamaSubscription subscription, mamaMsg message, void * closure, void * itemClosure)
{
    const char * topicName = NULL;
    if (mamaSubscription_getSymbol(subscription, &topicName) == MAMA_STATUS_OK)
    {
        printf("Message of type %s received on topic \"%s\"\n", mamaMsgType_stringForMsg(message), topicName);
    }
    // extract from the message our own custom field
    const char * const MY_FIELD_NAME = "MdMyTimestamp";
    const int MY_FIELD_ID = 99, BUFFER_SIZE = 32;
    char buffer[BUFFER_SIZE];
    if (mamaMsg_getFieldAsString(message, MY_FIELD_NAME, MY_FIELD_ID, buffer, BUFFER_SIZE)
            == MAMA_STATUS_OK)
    {
        printf("This message has a field \"%s\" with value: %s", MY_FIELD_NAME, buffer);
    }
}
```

Now we can start receiving messages:

```cpp
mama_start(global.bridge);
```

This `mama_start` call blocks execution of the current thread until `mama_stop` is called, that is why we need to implement a handler for stopping our program by pressing `Ctrl-C` from console.

```cpp
void stopHandler(int value)
{
    signal(value, SIG_IGN);
    printf(" Do you want to stop the program? [y/n]: ");
    char answer = getchar();
    if (answer == 'y')
        stopAll();
    else
        signal(SIGINT, stopHandler);
    getchar();
}
```

The `stopAll` routine has `destroy` calls for the created transport and subscription.

Order of calls in that routine is very important and the very first one must be `mama_stop`:

```cpp
void stopAll()
{
    mama_stop(global.bridge);
    if (global.subscription)
    {
        mamaSubscription_destroy(global.subscription);
        global.subscription = NULL;
    }
    if (global.transport)
    {
        mamaTransport_destroy(global.transport);
        global.transport = NULL;
    }
}
```

## Sending Message

As usual, before everything else, we need to [initialize](../hello-world/#initialize) the **Solace middleware bridge** and [create a transport](../hello-world/#create-transport).

Now we can implement sending a message, and as you already know from the [Solace OpenMAMA “Hello World” tutorial](../hello-world/#create-publisher), to publish a message we need to create a _publisher_.

A _publisher_ is created for a specific topic and refers to already created _transport_:

```c
global.publisher = NULL;
mamaPublisher_create(&global.publisher, global.transport, publishTopicName, NULL, NULL)
```

We want our program to publish messages periodically, until we stop it (by pressing `Ctrl-C` from console).

OpenMAMA provides a very convenient mechanism for a periodic event in a forms of _mamaTimer_. Such timers created with a reference to an _event queue_ and we can use the _default internal event queue_ for it:

```cpp
global.publishTimer = NULL;
mamaTimer_create(&global.publishTimer, defaultQueue, timerCallback, intervalSeconds, NULL);
```

The `timerCallback` parameter is a pointer to a function that will be invoked by OpenMAMA when the timer expires.

We’re going to implement this function to send one message with three different fields, one of them is a custom field with the message timestamp as a string:

```cpp
void timerCallback(mamaTimer timer, void* closure)
{
    // generate a timestamp as one of the message fields
    char buffer[32];
    time_t currTime = time(NULL);
    sprintf(buffer, "%s", asctime(localtime(&currTime)));
    // create message and add three fields to it
    mamaMsg message = NULL;
    mama_status status;
    if (((status = mamaMsg_create(&message)) == MAMA_STATUS_OK) &&
        ((status = mamaMsg_addI32(message, MamaFieldMsgType.mName, MamaFieldMsgType.mFid,
                                  MAMA_MSG_TYPE_INITIAL)) == MAMA_STATUS_OK) &&
        ((status = mamaMsg_addI32(message, MamaFieldMsgStatus.mName, MamaFieldMsgStatus.mFid,
                                  MAMA_MSG_STATUS_OK)) == MAMA_STATUS_OK) &&
        ((status = mamaMsg_addString(message, "MdMyTimestamp", 99,
                                     buffer)) == MAMA_STATUS_OK))
    {
        if ((status = mamaPublisher_send(global.publisher, message)) == MAMA_STATUS_OK)
        {
            printf("Message published: %s", buffer);
            mamaMsg_destroy(message);
            // normal exit
            return;
        }
    }
    // error exit
    printf("Error publishing message: %s\n", mamaStatus_stringForStatus(status));
}
```

Now we can start sending messages:

```cpp
mama_start(global.bridge);
```

Because `mama_start` call blocks execution of the current thread until `mama_stop` is called, we’re going to use the handler mechanism for stopping our program by pressing `Ctrl-C` from console.

That handler calls `stopAll`. As you already know, order of calls in `stopAll` routine is very important and the very first one must be `mama_stop`:

```cpp
void stopAll()
{
    mama_stop(global.bridge);
    // order is important
    if (global.publishTimer)
    {
        mamaTimer_destroy(global.publishTimer);
        global.publishTimer = NULL;
    }
    if (global.publisher)
    {
        mamaPublisher_destroy(global.publisher);
        global.publisher = NULL;
    }
    if (global.transport)
    {
        mamaTransport_destroy(global.transport);
        global.transport = NULL;
    }
}
```

## Summarizing

Our application consists of two executables: _topicSubscriber_ and _topicPublisher_.

If you combine the example source code shown above and split them into the two mentioned executables, it results in the source that is available for download:

* [mama.properties](https://github.com/SolaceSamples/solace-samples-openmama/blob/master/src/pubsub/mama.properties)
* [topicSubscriber.c](https://github.com/SolaceSamples/solace-samples-openmama/blob/master/src/pubsub/topicSubscriber.c)
* [topicPublisher.c](https://github.com/SolaceSamples/solace-samples-openmama/blob/master/src/pubsub/topicPublisher.c)

### Building

To build on **Linux**, assuming OpenMAMA installed into `/opt/openmama`:

```
$ gcc -o topicSubscriber topicSubscriber.c -I/opt/openmama/include -L/opt/openmama/lib -lmama
$ gcc -o topicPublisher topicPublisher.c -I/opt/openmama/include -L/opt/openmama/lib -lmama
```

### Running the Application

First, start the _topicSubscriber_:

```
$ ./topicSubscriber
Solace OpenMAMA tutorial.
Receiving messages with OpenMAMA.
2016-07-14 14:22:38:
********************************************************************************
Note: This build of the MAMA API is not enforcing entitlement checks.
Please see the Licensing file for details
**********************************************************************************
2016-07-14 14:22:38: mamaTransport_create(): No entitlement bridge specified for transport vmr. Defaulting to noop.
Created subscription to topic "tutorial.topic"
```

Now in a separate console start the _topicPublisher_ that begins publishing messages periodically:

```
$ ./topicPublisher
Solace OpenMAMA tutorial.
Publishing messages with OpenMAMA.
2016-07-14 14:22:48:
********************************************************************************
Note: This build of the MAMA API is not enforcing entitlement checks.
Please see the Licensing file for details
**********************************************************************************
2016-07-14 14:22:48: mamaTransport_create(): No entitlement bridge specified for transport vmr. Defaulting to noop.
Message published: Thu Jul 14 14:22:51 2016
Message published: Thu Jul 14 14:22:54 2016
Message published: Thu Jul 14 14:22:57 2016
Message published: Thu Jul 14 14:23:00 2016
```

You will see the _topicSubscriber_ receiving messages and logging them to the connsole:

```
$ ./topicSubscriber
Solace OpenMAMA tutorial.
Receiving messages with OpenMAMA.
2016-07-14 14:22:38:
********************************************************************************
Note: This build of the MAMA API is not enforcing entitlement checks.
Please see the Licensing file for details
**********************************************************************************
2016-07-14 14:22:38: mamaTransport_create(): No entitlement bridge specified for transport vmr. Defaulting to noop.
Created subscription to topic "tutorial.topic"
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:22:51 2016
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:22:54 2016
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:22:57 2016
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:23:00 2016
```

To stop the application press `Ctrl-C` and then `y` on each console. First, stop the publisher:

```
$ ./topicPublisher
Solace OpenMAMA tutorial.
Publishing messages with OpenMAMA.
2016-07-14 14:22:48: Failed to open properties file.

2016-07-14 14:22:48:
********************************************************************************
Note: This build of the MAMA API is not enforcing entitlement checks.
Please see the Licensing file for details
**********************************************************************************
2016-07-14 14:22:48: mamaTransport_create(): No entitlement bridge specified for transport vmr. Defaulting to noop.
Message published: Thu Jul 14 14:22:51 2016
Message published: Thu Jul 14 14:22:54 2016
Message published: Thu Jul 14 14:22:57 2016
Message published: Thu Jul 14 14:23:00 2016
^C Do you want to stop the program? [y/n]: y
Closing Solace middleware bridge.
```

Now we can stop the subscriber:

```
$ ./topicSubscriber
Solace OpenMAMA tutorial.
Receiving messages with OpenMAMA.
2016-07-14 14:22:38:
********************************************************************************
Note: This build of the MAMA API is not enforcing entitlement checks.
Please see the Licensing file for details
**********************************************************************************
2016-07-14 14:22:38: mamaTransport_create(): No entitlement bridge specified for transport vmr. Defaulting to noop.
Created subscription to topic "tutorial.topic"
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:22:51 2016
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:22:54 2016
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:22:57 2016
Message of type INITIAL received on topic "tutorial.topic"
This message has a field "MdMyTimestamp" with value: Thu Jul 14 14:23:00 2016
^C Do you want to stop the program? [y/n]: y
Closing Solace middleware bridge.
```

Congratulations! You have now successfully subscribed to a topic and exchanged messages using this topic on using OpenMAMA with the Solace middleware bridge.

## Resources

For more information about OpenMAMA:

*   The OpenMAMA [website](http://www.openmama.org/)
*   The OpenMAMA code repository on [GitHub](https://github.com/OpenMAMA/OpenMAMA)
*   Chat with OpenMAMA developers and users at [Gitter OpenMAMA room](https://gitter.im/OpenMAMA/OpenMAMA)

For more information about Solace technology:

*   The [Solace Developer Portal website](https://www.solace.dev)
*   Get a better understanding of [Solace technology](https://solace.com/products/tech/)
*   Ask the [Solace community](https://solace.community)

Other tutorials and related links:

*   [OpenMAMA Quick Start Guide](https://openmama.finos.org/quickstart)
*   [OpenMAMA Wiki Quick Start Guide](https://github.com/OpenMAMA/OpenMAMA/wiki/Quick-Start-Guide)
*   [OpenMAMA Example Walk Through](https://openmama.finos.org/quickstart)
*   [OpenMAMA Code Examples](https://github.com/OpenMAMA/OpenMAMA/tree/master/mama/c_cpp/src/examples)
*   [OpenMAMA Wiki](https://github.com/OpenMAMA/OpenMAMA/wiki)
*   [OpenMAMA Documentation and Developers Guides](https://openmama.finos.org/documentation.html)
*   [Solace’s Solution for OpenMAMA](https://solace.com/products/tech/)


text:
# JavaProperties

[![Build Status](https://github.com/jnbt/java-properties/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/jnbt/java-properties/actions?query=branch%3Amaster)
[![Code Climate maintainability](https://img.shields.io/codeclimate/maintainability/jnbt/java-properties)](https://codeclimate.com/github/jnbt/java-properties)
[![Coverage Status](https://coveralls.io/repos/github/jnbt/java-properties/badge.svg?branch=master)](https://coveralls.io/github/java-properties/linr?branch=master)
[![RubyGems](http://img.shields.io/gem/v/java-properties)](http://rubygems.org/gems/java-properties)
[![Inline docs](http://inch-ci.org/github/jnbt/java-properties.svg?style=shields)](http://inch-ci.org/github/jnbt/java-properties)

A ruby library to read and write [Java properties files](http://en.wikipedia.org/wiki/.properties).

## Installation

Install via Rubygems

```bash
$ gem install java-properties
```

... or add to your Gemfile

```ruby
gem "java-properties"
```

## Loading files

You can load a valid Java properties file from the file system using a path:

```ruby
properties = JavaProperties.load("path/to/my.properties")
properties[:foo] # => "bar"
```

If have already the content of the properties file at hand than parse the content as:

```ruby
properties = JavaProperties.parse("foo=bar")
properties[:foo] # => "bar"
```

## Writing files

You can write any Hash-like structure as a properties file:

```ruby
hash = {:foo => "bar"}
JavaProperties.write(hash, "path/to/my.properties")
```

Or if you want to omit the file you can receive the content directly:

```ruby
hash = {:foo => "bar"}
JavaProperties.generate(hash)  # => "foo=bar"
```

## Encodings and special chars

As Java properties files normally hold UTF-8 chars in their escaped representation this tool tries to convert them:

```
"ה" <=> "\u05d4"
"𪀯"  <=> "\ud868\udc2f"
```

The tool also escaped every '=', ' ' and ':' in the name part of a property line:

```ruby
JavaProperties.generate({"i : like=strange" => "bar"})
# => "i\ \:\ like\=strange=bar"
```

## Multi line and line breaks

In Java properties files a string can be multi line but line breaks have to be escaped.

Assume the following input:

```ini
my=This is a multi \
   line content with only \n one line break
```

The parses would read:

```ruby
{:my => "This is a multi line content which only \n one line break"}
```

In the opposite direction line breaks will be correctly escaped but the generator will never use multi line values.

## Contributing

1. [Fork it!](https://github.com/jnbt/java-properties/fork)
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Author

Jonas Thiel (@jonasthiel)

## References

For more information about the properties file format have a look at the [Java Plattform documenation](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html).

## License

This gem is released under the MIT License. See the LICENSE file for further details.

repository: jnbt/java-properties

gha_language: Ruby

repo_name: jnbt/java-properties


text:
### [CVE-2014-0980](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0980)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

Buffer overflow in Poster Software PUBLISH-iT 3.6d allows remote attackers to execute arbitrary code via a crafted PUI file.

### POC

#### Reference
- http://packetstormsecurity.com/files/125089
- http://seclists.org/fulldisclosure/2014/Feb/34
- http://www.coresecurity.com/advisories/publish-it-buffer-overflow-vulnerability
- http://www.exploit-db.com/exploits/31461

#### Github
No PoCs found on GitHub currently.

repository: trickest/cve

branch_name: refs/heads/main

gha_language: HTML

repo_name: trickest/cve


text:
# MyIMDB        [![Build Status](https://travis-ci.org/deepak1725/myimdb.svg?branch=master)](https://travis-ci.org/deepak1725/myimdb)

My IMDB is a collection of API endpoints, build to fetch movie records from an endpoint.

## What it Does..??
1. It is API Endpoints, Used to Fetch Movie records
2. Admin can able to add/edit/delete Records.

## What is Used to build ..??
1. Django 2.0 in Backend, with Django Rest Framework
2. Project is Deployed on Heroku.
3. API Collection and docs in POSTMAN.

## Installation:

1. `git clone`
2. Activate Python Virtual Environment, and run `pip install -r requirements.txt` from Base project folder.
3. Import endpoints Collections into POSTMAN client from [Here](https://www.getpostman.com/collections/2a6083082af6539b297e/)
4. Install Requiremnts. `pip install -r requirements.txt`
4. Run Migrations `python manage.py migrate`

## Misc:
1. The Project is also hosted on Heroku and live Demo is available at [Live Demo](https://myownimdb.herokuapp.com/)
2. API Documentation is available [Here](https://documenter.getpostman.com/view/1293069/RWEiLHvG#d5330d6c-96d4-4cdc-9601-deab35f47019)
3. API Collections is available [Here](https://www.getpostman.com/collections/2a6083082af6539b297e/)

### Enjoy!! Do Star it. :)


text:
# GCOS Survey

### Overview

This tool offers an assessment of your General Causality Orientation, using [Deci & Ryan's General Causality Orientation Scale (GCOS) (1985).](https://selfdeterminationtheory.org/SDT/documents/1985_DeciRyan_GCOS.pdf)

It provides you with scores representing your orientation on three different scales of Causality Orientation:

- Autonomous
- Controlled
- Impersonal

A PDF version of the survey can be downloaded from [here](https://selfdeterminationtheory.org/general-causality-orientations-scale/) (after registration).

This tool uses the 51 question version of the survey (GCOS-17).  The PDF also includes a 36 question survey (GCOS-12).

At the end of the survey, this tool shows your results in three forms:

- As normalized scores, where the mean score is 100, and each Standard Deviation from the mean is +/-15 points.
- As percentile scores
- As a single color, representing the 3-dimensional GCOS score, with green for autonomy, red for controlled and blue for impersonal.

These scores are computed using:

- The "coding" of responses into the Autonomous, Controlled & Impersonal scales.
- Data about the general population distribution of GCOS scores (taken from [Deci & Ryan's 1985 GCOS paper](https://selfdeterminationtheory.org/SDT/documents/1985_DeciRyan_GCOS.pdf))

See "detailed notes" below for some of the specifics.

The tool does not display the raw scores for each scale, because they are not directly meaningful or comparable (e.g. the average score for Autonomy is much higher than the average score for Controlled or Impersonal).

### Data Privacy

All processing of the answers you provide is exclusively within your browser.  This site does not collect any data from you.

### What do my GCOS Scores Mean?

A person's General Causality Orientation influences their likelihood of interpreting interactions as autonomy-supporting, controlling, or amotivating, which in turn predicts a wide range of other outcomes.

Each of these is influenced by the respective scale (Autonomy, Controlled or Impersonal) on the GCOS.

Causality Orientation Theory (COT) is part of Self-Determination Theory, a contemporary theory in empirical psychology.

COT predicts that a person's General Causality Orientation has a significant impact on several important aspects of their life.  In particular:

- A high autonomy orientation is strongly associated with the healthiest development and best overall psychological well-being.
- A high controlled orientation is often associated with success, but this success often comes at a cost in terms of psychological well-being.
- A high impersonal orientation is associated with a lack of motivation, and the lowest well-being.

You can find (much) more detail on Causality Orientation Theory this [in this article](https://diarmidmackenzie.github.io/sdt-condensed/COT.html).

### Detailed Notes

The data on GCOS distribution in the population comes from this data in [Deci & Ryan's 1985 paper](https://selfdeterminationtheory.org/SDT/documents/1985_DeciRyan_GCOS.pdf).

![image-20210729132332856](GCOS-Distribution.png)

This data comes from a sample of 636 undergraduate students, so may not be representative of the overall population.

The tool uses the combined data.  Showing different scores for men & women is a potential future enhancement.

The data was collected from GCOS-12, with 36 questions.  Therefore to compare with this data, the scores from GCOS-17 are scaled by a factor of 12/17.

The calculations do not model skew or curtosis.  They just compute the number of standard deviations that a score lies from the mean, and then compute percentiles assuming a normal distribution.

The "normalized" scores presented follow the same model as IQ scores: 100 points is the average, and a standard deviation is represented by 15 points, so a score of 130 is 2 standard deviations above the mean.

The 3-dimensional GCOS score is also translated into a single color, with red representing the controlled orientation, green representing the autonomy orientation, and blue representing the impersonal orientation.

For this color mapping, the values 40 to 160 on the normalized scale are mapped linearly to RGB values from 0 to 255.

### Source Code

The source code for this tool is available under the MIT license.

https://github.com/diarmidmackenzie/gcos

repository: diarmidmackenzie/gcos

gha_language: JavaScript

repo_name: diarmidmackenzie/gcos


text:
# Sgemu rendering engine
Rendering engine in pure python. In development.

## Features
- Pure Python + GLSL, using OpenGL 4.3
- Both Blinn-Phong and PBR (Physically-Based Rendering) lighting
- Point lights, Area lights (using Linearly transformed cosines method)
- HDR, Bump mapping, Volumetric fog (cone-shaped primitives)
- Bloom, DOF (Depth Of Field)
- Spatial audio, using OpenAL
- UI library for HUD displays (not used in main.py, shown in gui_t.py)

## Running
```bash
git clone https://github.com/alexcher-im/sgemu
cd sgemu
pip install -r requirements.txt
git clone https://github.com/KhronosGroup/glTF-Sample-Models
python3 main.py
```

There may be a pyassimp bug with ctypes structure size (pyassimp v4.1.4), it is already fixed, but still not in PyPi repos. If so, you need to fix this manually or use older assimp dll.
To fix you need to find class `String`, field `length` (file `structs.py`, line 79) and change `c_size_t` to `c_uint32` in pyassimp source code.

## Controls for main.py
`WASD` to move forward, left, backwards and right

`arrow up` and `arrow down` to move up and down

`shift`, `ctrl`, `ctrl+shift` to increase moving or DOF cutoff change speed by 10, 100 and 1000 respectively

`Q` and `R` to roll the camera

`T` and `Y` to change Depth Of Field cutoff length

license: Zlib

repository: alexcher-im/sgemu

repo_name: alexcher-im/sgemu


text:
---
description: >-
  How package telemetry data collected from Umbraco installations is used to order packages
---

# Package Telemetry Data

Umbraco installations that have opted into providing basic or detailed telemetry data will indicate which packages are installed. We use that information to order packages by "Most Active Installs".

## Package Popularity

We have two measures that we can use to rank packages by popularity:

- **Total Number of NuGet Downloads** (obtained from nuget.org)
- **Number of Active Installs** (obtained from CMS package telemetry over the past 14 days)

Both of these are available for website users to select when filtering the list of packages they are reviewing.

"Number of Active Installs" is used as the measure for "Most popular" packages shown on the Marketplace home page.

## How Number of Active Installs is Collected

Umbraco installations that have opted into sending telemetry data will send information periodically to a central collection service. This may include information about packages that are installed.

On a regular basis this information is aggregated and stored in the database that serves the Marketplace API and website.

## Package Identification

Packages are identified in the telemetry service based on one of the following:

- The package NuGet ID provided in a [package manifest file or manifest filter](https://docs.umbraco.com/umbraco-cms/extending/property-editors/package-manifest).
- The package name provided in a package manifest file or manifest filter.
- The name of the folder within `/App_Plugins/` that the package creates.

The most reliable way of matching up a package between the Marketplace and the telemetry data is if the package NuGet Id is provided. This can be included in your manifest file or filter if your package depends on Umbraco 12 or above.

{% hint style="info" %}
If you use a manifest filter and take a dependency on a lower version of Umbraco, the `PackageManifest.PackageId` isn't available. You can still have set it for Umbraco installations that run Umbraco 12 using reflection. An example of this technique can be found within the open-source [Umbraco AuthorizedServices package](https://github.com/umbraco/Umbraco.AuthorizedServices/blob/287f284662d16cd9ae7218bae6512c7d86b36563/src/Umbraco.AuthorizedServices/Manifests/AuthorizedServicesManifestFilter.cs#L30).
{% endhint %}

Even if the package Id is provided in your package manifest, only installations of Umbraco 12 and up will use it for telemetry reporting. Older versions will use the package name or folder.

If the package name or folder is used, this may not be the same as the NuGet package ID. If not, we need to ensure your package is stored along with the alternate name that is used in the CMS and telemetry data.

It's no longer possible to supply this via the `umbraco-marketplace.json` file. The field by which this was supplied has been deprecated in the schema and if provided will no be longer imported. This was due to the risks of two package developers providing the same alternate names.

Instead we maintain this list at HQ. You may own a package that appears to not rank as expected via the "most active installs" measure. If you suspect it's due to the telemetry data not being correctly allocated, please let us know. We can make the necessary updates such that it's popularity is properly reflected. You can reach us at [packages<EMAIL_ADDRESS>and tell us the name used for your package in the package manifest or folder.

### What if I don't have a client-side component?

Some packages may not have either a `package.manifest.json` file nor create a folder in `/App_Plugins/`. This would normally be the case if the package is providing only server-side functionality, and is written purely in C#.

For these cases there's an option to add and register a manifest filter that ensures the name and Id is set.

An example is shown here:

```csharp
using System.Collections.Generic;
using Umbraco.Cms.Core.Manifest;

namespace Umbraco.Community.MyPackage
{
    internal sealed class PackageManifestFilter : IManifestFilter
    {
        public void Filter(List<PackageManifest> manifests) =>
            manifests.Add(new PackageManifest
            {
                PackageId = "MyPackage",
                PackageName = "My Package",
            });
    }
}
```

The class needs to be registered as part of the application startup, via a composer or an extension method as shown here:

```csharp
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Extensions;

namespace Umbraco.Community.MyPackage
{
    public static class UmbracoBuilderExtensions
    {
        public static IUmbracoBuilder AddMyPackage(this IUmbracoBuilder builder)
        {
            builder.ManifestFilters().Append<PackageManifestFilter>();
            return builder;
        }
    }
}
```

repository: umbraco/UmbracoDocs

repo_name: umbraco/UmbracoDocs


text:
# GlobalizeCurrentTranslation
Short description and motivation.

## Usage

Install the gem on your models like this:
```ruby
class Category < ApplicationRecord
  translates :name
  include GlobalizeCurrentTranslation::Scope
end
```

Now you can use the new relationship to order a collection by its current locale but fall back to another locale:
```ruby
Category.left_joins(:current_translation).order("category_translations.name")
```

## Installation
Add this line to your application's Gemfile:

```ruby
gem 'globalize_current_translation', git: 'https://github.com/kaspernj/globalize_current_translation.git'
```

And then execute:
```bash
$ bundle
```

Or install it yourself as:
```bash
$ gem install globalize_current_translation
```

## Contributing
Contribution directions go here.

## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).


text:
---
lang: en
slug: with-a-little-help-from-json-spec-and-rack-test
originalPath: https://www.belighted.com/blog/with-a-little-help-from-json-spec-and-rack-test
title: With a little help from Json_spec and Rack::Test
author: Yannick S.
description: How to use Sinatra, to design a json API in a few days. Discover a
  small example.
image: null
date: 2012-08-15
tags:
  - label: Under the hood
    value: under-the-hood
status: published
---
Last week, I had to design a little json API. It had to be fast and furious. For that purpose, we made it with Sinatra.

The point was we didn’t want to make a single file Sinatra app. We made a **[small reusable skeleton](https://github.com/ys/sinatra-skeleton)** of a Sinatra app using ActiveRecord to store the small amount of objects.

It had to be full stack tested. For that we used Rspec and **[Rack Test](https://github.com/brynary/rack-test/)** for the API testing part.

You can easily check the response payload with something like **[json\_spec](https://github.com/collectiveidea/json_spec/)**. It’s so easy to use.

Here is a small example:

1
2
3
4
5
6
7

 ...
 it 'get the greeting' do
 get "/api/#{person.name}"
 last_response.should be_ok
 last_json.should have_json_path 'name'
 end
 ...

The `last_json` object is simply a method defined into the spec\_helper.rb file which looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

ENV['RACK_ENV'] = 'test'
# Load the Sinatra app
require File.join( File.dirname( __FILE__ ), '..', 'server' )

require 'rspec'
require 'rack/test'
require 'json_spec'

set :environment, :test

RSpec.configure do |conf|
 conf.include Rack::Test::Methods
 conf.include JsonSpec::Helpers
 #all your others informations
end

def last_json
 last_response.body
end

def app
 App
end

With json\_spec, you have access to some great matchers like `be_json_eq`, `have_json_path` or`have_json_size` which help a lot doing things like `have_json_size(0).at_path("friends")`. The doc is really helpful for that.

With Rack::Test, you have a lot of helpers like the classic http methods. And access to an object `last_response` which contains the http response of the last request.

All that helped to get a working API in a couple of days. For more information about the sinatra skeleton, I recommend you another **[blog post](https://blog.yannick.io/blog/2012/07/28/sinatra-skeleton/)** I wrote on my own blog or don’t hesitate to ask as many questions as you want!

[![New Call-to-action](/content/images/legacy/UPTtKvQU_5rjKfQJ1Qjwk.png)](https://cta-redirect.hubspot.com/cta/redirect/1684659/fb3606cc-cc1b-47d0-ae85-2c9f69837fe2)

repository: belighted/website

repo_name: belighted/website


text:
---
title: Getting started
eleventyNavigation:
  key: Getting started
  parent: Auth
---

## Using AngularFireAuth

`AngularFireAuth.user` provides you an `Observable<User|null>` to monitor your application's authentication State.

`AngularFireAuth` promise proxies an initialized
`firebase.auth.Auth` instance, allowing you to log users in, out, etc. [See
the Firebase docs for more information on what methods are available.](https://firebase.google.com/docs/reference/js/firebase.auth.Auth)

**Example app:**

```ts
import { Component } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import firebase from 'firebase/app';

@Component({
  selector: 'app-root',
  template: `{%raw%}
    <div *ngIf="auth.user | async as user; else showLogin">
      <h1>Hello {{ user.displayName }}!</h1>
      <button (click)="logout()">Logout</button>
    </div>
    <ng-template #showLogin>
      <p>Please login.</p>
      <button (click)="login()">Login with Google</button>
    </ng-template>
  {%endraw%}`,
})
export class AppComponent {
  constructor(public auth: AngularFireAuth) {
  }
  login() {
    this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }
  logout() {
    this.auth.signOut();
  }
}
```

## UI Libraries

- Material Design : [ngx-auth-firebaseui](https://github.com/AnthonyNahas/ngx-auth-firebaseui)
- Bootstrap : [@firebaseui/ng-bootstrap](https://github.com/firebaseui/ng-bootstrap)

## Cordova

Learn how to [setup Firebase Authentication with Cordova](https://firebase.google.com/docs/auth/web/cordova) in the Firebase Guides.

repository: angular/angularfire

gha_language: TypeScript

repo_name: angular/angularfire


text:
inject-then [![Build Status](https://travis-ci.org/bendrucker/inject-then.svg?branch=master)](https://travis-ci.org/bendrucker/inject-then) [![NPM version](https://badge.fury.io/js/inject-then.svg)](http://badge.fury.io/js/inject-then)
==========

Promise wrapper for [Hapi](https://github.com/spumko/hapi)'s server.inject. When [registering](https://github.com/spumko/hapi/blob/master/docs/Reference.md#packregisterplugin-options-callback) the plugin, you can use the `Promise` option to specify promise constructor. [Bluebird](https://github.com/petkaantonov/bluebird) is used if no constructor is specified.

```js
pack.register(require('injectThen'));
```

```js
pack.register(require('injectThen'), {
  Promise: require('rsvp')
});
```

The plugin register an `injectThen` method on all servers in the pack, which wraps `server.inject` in a promise and resolves with the `response`.

```js
server.injectThen('/posts').then(function (response) {
  // do things with the response
});
```

repository: yonjah/inject-then

repo_name: yonjah/inject-then


text:
# xyz2top
_Generation of GROMACS topology from a .xyz file using a GAFF forcefield_

Run with
```bash
python xyz2top.py test.xyz
```

If the charge and mutipliciy are not 0 and 1 respectively they may be specified with `-c` amd `-m` flags respectively
```bash
python xyz2top.py test.xyz -c 0 -m 1
```


text:
# @hutson/conventional-changelog-config

> Standard conventional-changelog configuration as used by projects maintained by Hutson Betts (@hutson).

Configuration package for tools within the [`conventional-changelog`](https://www.npmjs.com/package/conventional-changelog) ecosystem, or those that leverage the ecosystem, such as `semantic-release-gitlab`, that support [loading `conventional-changelog` presets](https://www.npmjs.com/package/semantic-release-gitlab#preset).

## Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Security Disclosure Policy](#security-disclosure-policy)
- [Professional Support](#professional-support)
- [Debugging](#debugging)
- [Node Support Policy](#node-support-policy)
- [Contributing](#contributing)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Features

* [x] If not specified below, this package defaults to [`conventional-changelog-angular`](https://www.npmjs.com/package/conventional-changelog-angular).

**Recommended Bump Options**

* [x] Returns level `2` for fixes, `1` for features, `0` for breaking changes and `null` for all other changes.

## Installation

To install the `@hutson/conventional-changelog-config` configuration package for use in your project please run the following command:

```bash
yarn add --dev @hutson/conventional-changelog-config
```

## Usage

Each tool capable of using a `conventional-changelog` configuration package has its own API for consuming the configuration. Please refer to those tools for the appropriate documentation.

However, as an example, if you are using `semantic-release-gitlab` or `semantic-release-github`, you can pass this configuration package to those tools like so:

```bash
$(yarn bin)/semantic-release-gitlab --preset @hutson/config
```

## Security Disclosure Policy

To report a security vulnerability in this package, or one of it's dependencies, please use the [Tidelift security contact](https://tidelift.com/security) page. Tidelift will coordinate the process to address the vulnerability and disclose the incident to our users.

## Professional Support

[Professional support for `@hutson/conventional-changelog-config` is available with a Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-hutson-conventional-changelog-config?utm_source=npm--hutson-conventional-changelog-config&utm_medium=referral&utm_campaign=readme).

Tidelift helps make open source sustainable for maintainers while giving companies assurances about security, maintenance, and licensing for their dependencies.

## Debugging

To assist users of `@hutson/conventional-changelog-config` with debugging the behavior of this module we use the [debug](https://www.npmjs.com/package/debug) utility package to print information to the console. To enable debug message printing, the environment variable `DEBUG`, which is the variable used by the `debug` package, must be set to a value configured by the package containing the debug messages to be printed.

To print debug messages on a unix system set the environment variable `DEBUG` with the name of this package prior to executing a tool that invokes this module:

```bash
DEBUG=@hutson/conventional-changelog-config [CONSUMING TOOL]
```

On the Windows command line you may do:

```bash
set DEBUG=@hutson/conventional-changelog-config
[CONSUMING TOOL]
```

## Node Support Policy

We only support [Long-Term Support](https://github.com/nodejs/LTS) versions of Node.

We specifically limit our support to LTS versions of Node, not because this package won't work on other versions, but because we have a limited amount of time, and supporting LTS offers the greatest return on that investment.

It's possible this package will work correctly on newer versions of Node. It may even be possible to use this package on older versions of Node, though that's more unlikely as we'll make every effort to take advantage of features available in the oldest LTS version we support.

As each Node LTS version reaches its end-of-life we will remove that version from the `node` `engines` property of our package's `package.json` file. Removing a Node version is considered a breaking change and will entail the publishing of a new major version of this package. We will not accept any requests to support an end-of-life version of Node. Any merge requests or issues supporting an end-of-life version of Node will be closed.

We will accept code that allows this package to run on newer, non-LTS, versions of Node. Furthermore, we will attempt to ensure our own changes work on the latest version of Node. To help in that commitment, our continuous integration setup runs against all LTS versions of Node in addition the most recent Node release; called _current_.

JavaScript package managers should allow you to install this package with any version of Node, with, at most, a warning if your version of Node does not fall within the range specified by our `node` `engines` property. If you encounter issues installing this package, please report the issue to your package manager.

## Contributing

Please read our [contributing guide](https://github.com/hyper-expanse/conventional-changelog-config/blob/master/contributing.md) to see how you may contribute to this project.


text:
Protocol
==============
1. Client send plaintext string 'PUBKEY' to bank
2. Bank send public key (PUB-B) to client
3. Client sends public key (PUB-C) to bank.
 Bank Send E(PUB-C, 'MAC.') to client.
5. Client takes its MAC key and hashes a random message using [HMAC](https://www.openssl.org/docs/manmaster/crypto/hmac.html)
and [EVP_sha256](https://www.openssl.org/docs/manmaster/crypto/EVP_DigestInit.html) (MAC-C) it then sends a the message concatenated with the
result of HMAC. (sends E(PUB-B, MSG + ':' + HASH-C))
6. The bank checks the MAC by taking the message and using its stored version
of the client's MAC key and running HMAC/EVP_sha256 on it. If the HMAC/ECP_sha256
message that the bank received matches the HMAC/EVP_sha256, proceed.
7. Steps 5 and 6 are repeated with the bank authenticating with the client.
sends E(PUB-C, MSG + ':' + HASH-B)
WE NOW HAVE A SECURE/TRUSTED CONNECTION
8. The client waits for the user to login.
9. When the user logs in, client sends E(PUB-B, USERNAME + ':' + PIN)
10. Iff the login credentials are correct, bank sends E(PUB-C, 'OK.')
USER CAN NOW USE BANK
11. Client presents user with command shell in which to do transactions.
12. Client sends transaction to Bank
13. Iff transaction is successful bank send OK to client along with changes.
14. User logs out of terminal.
15. bank/client close connection

NOTES
-------
* all connection closures do not notify the other party
* if client fails steps #6 or #9 bank closes connection.
* if bank fails step #7 client closes connection.
* if any decryption fails (message tampering) bank/client closes connection.
* if there are three login failures to client, client locks account.
* if there are three login failures to bank, bank locks account.
* if a client is inactive at the terminal for more than 15 seconds bank
locks account.
* if client fails #13, simply ignore the transaction,
 bring them back to main menu with a failure message.


text:
---
layout: post
title: "Quick electric skateboard build"
description: ""
category:
tags: [Prototyping]
image: /assets/images/skate/skateboard.jpg
---
{% include JB/setup %}

<!--![](/assets/images/skate/skateboard.jpg)-->

A friend and I recently decided to get electric longboards.

We figured maybe the DIY route wouldn't be too hard and we could make something
pretty sweet.

I wanted to make mine by converting an existing longboard that I already had.
That way I'd only need to get the electronics and figure out a way to connect
the motor to the wheel.  I also kind of optimized for making things easy and
didn't want to spend a ton of time on this.

# The electronics

The electronics are the easy part.  You just need a motor, battery, speed
controller, RF receiver, and remote.  All of these are commodity RC "vehicle"
components.  I choose the following parts.

* [Motor](https://hobbyking.com/en_us/propdrive-v2-5060-380kv-brushless-outrunner-motor.html)
    * This has turned out pretty well, very powerful and robust.  I chose a 380
      KV motor which works out to a 20-30 miles/hr top speed at a 3:1 gear
      reduction.  It's also small enough to fit under the skateboard deck.
* [Speed
  controller](https://www.ebay.com/itm/BoldClash-2S-6S-120A-LiPo-Waterproof-ESC-with-BEC-6-1V-3A-Switch-Mode-for-1-8/252978407842)
    * Works fine and doesn't come close to overheating.  Don't need the fan the
      comes with it.  Can source up to 120A which is important to keep up with
      the motor's capability.  I wish the programming options for the
      controller were better.  There's just a [simple programming
      card](https://www.ebay.com/itm/BoldClash-LED-Program-Card-for-25-35-45-60-80-120A-ESC-Motor-Set-Lightweight/262993218951).
* RF receiver + remote
    * [I choose the cheapest
      thing](https://hobbyking.com/en_us/quanum-2-4ghz-3ch-pistol-grip-tx-rx-system.html).
      I couldn't really find a good "small" RF/TX remote kit.  I'll probably
      redo the case/handle form factor at some point.
* [Battery](https://www.amazon.com/gp/product/B06XKRWD4Z/)
    * Large capacity and discharge capability. Also thin enough for skateboard.

# The mechanics

This was definitely the hard part.  At first I thought it would be easy if I
just used a "all in one" [hardware kit on
Ebay](https://www.ebay.com/itm/Electric-Skateboard-Longboard-Kit-Pulley-And-Motor-Mount-for-70-72mm-Wheel-OS915/232390643041).
But they didn't really fit my skateboard trucks well and were really hard to
get aligned with the wheel correctly.  It was also really tough to get the
custom pulley centered on the wheel and bolted in.  And when I did get it bolted
in, it wasn't perfectly centered and it was non-trivial to fix.

I decided to custom make the parts to fit my trucks and wheels.  I'd
need a custom bracket to fit the motor onto the trucks and a custom pulley to
attach to the wheel.  I'm not experienced with machining and don't have easy
access to machining equipment but I do have a 3D printer.  I decided to try
making 3D printed nylon parts.  Nylon is really tough, so maybe it'll work
well.

It took some iterations to get right, but here they are.

![](/assets/images/skate/bracket.jpg)

![](/assets/images/skate/pully.jpg)

The pulley pictured is in PLA but the final version was in nylon.  It fits to
my wheel nicely and I also printed a small dowel to temporarily connect
it to the wheel's bearing hole, which keeps it centered while I drill holes for
the bolts.  I also got [new
trucks](https://www.amazon.com/gp/product/B00NY3Q5P4/) solely because the axle
was relatively square which made it *much* easier to mount the bracket too.

Here's everything put together.

![](/assets/images/skate/trucks.jpg)

![](/assets/images/skate/all.jpg)

![](/assets/images/skate/wheel.jpg)

After riding it for a while, I haven't noticed any problems with the nylon
parts.  I use the same [timing
belts](https://www.amazon.com/Boosted-Board-V2-Belts-Set/dp/B071JWW326) that
the Boosted Board uses and they fit snug in the custom pulley.  The parts were
printed at about 95% infill to get maximum strength.

#### Nuts and bolts used

The nylon motor bracket is held in place using 4-5 [set screws](https://www.mcmaster.com/#90251a165/=19uz2v4).  I left
a ~5.7 mm hole in the 3D printed part and then tapped the hole by hand using a
[M6
tap](https://www.amazon.com/gp/product/B00WI6EKBY/ref=oh_aui_search_detailpage).
The set screws hold up surprisingly well in tapped nylon.  (As a side-note, I've found that Kodiak is a pretty good brand to use on Amazon
for taps, bits, endmills, etc.).

The pulley was bolted to the wheel using these
[nuts](https://www.mcmaster.com/#94205a220/=19uz4lt) and
[bolts](https://www.mcmaster.com/#91292a267/=19uz4kb).  It's important to use
nylon insert lock nuts or they'll definitely come loose.  Also should be
corrosion resistant.

# Improvements

The board works pretty well but there are some definite improvements to make.

#### Belt slippage

The current 15mm wide, 3mm pitch timing belt isn't enough to transfer the full
torque of the motor.  So if you apply enough throttle, the belt will slip.
This isn't too much of a problem and these belts are designed to slip.  It also
acts as a torque limit to protect you from applying too much torque by accident
and falling off.

But sometimes it's annoying when you're not accelerating as much as you'd like.
And hills can sometimes be tough.  I think the best way to solve this is to use
two speed controllers and two motors for the two back wheels.  Twice as much
torque would be plenty.  The boosted board also uses two motors.

#### Battery management

Battery management and protection is really important.  Namely, you need to
ensure none of the cells over discharge, which can happen before the speed
controller can detect the overall battery voltage going low.  Over-current
isn't as much of a problem since the speed controller will limit the overall current.  But redundant
protections isn't a bad thing to have.

It would also be
nice to have a proper charging circuit.  Right now I'm just using a special
Li-ion battery charger that will charge and balance the cells.  If I added a circuit to
handle charging, I could just use a regular barrel jack or even a USB cable to
charge it.

When I get around to this, I'll make another post.

# DIY

If you're interested in making a similar build, hit me up!  I'm happy to answer
questions or share designs.

{% include JB/mytwitter %}


text:
SPADE-FB
========

Facebook Reporter for [SPADE](http://code.google.com/p/data-provenance/). It accesses Facebook data using [FBConsole](https://github.com/facebook/fbconsole) running using the Jython interpreter and connects to SPADE's DSL reporter using pipes.

Usage
=====

First run SPADE and [add DSL reporter](https://code.google.com/p/data-provenance/wiki/ControlClient). Then run `./run.sh` to start collecting data from Facebook and feed to SPADE.

You can view the collected data by [exporting it in Graphviz format](https://code.google.com/p/data-provenance/wiki/Graphviz) or by using [SPADE's query client](https://code.google.com/p/data-provenance/wiki/QueryClient).


text:
# W4Parser - Java HTML/XML to POJO parser

W4Parser - is a Java library for working with real-world HTML data and transform required part of data to simple java object(POJO). It provides a very convenient API for extracting data and based on popular java parser Jsoup.

##  W4Parser repo
```java
<dependency>
    <groupId>com.github.w4p</groupId>
    <artifactId>w4parser</artifactId>
    <version>1.0.1</version>
</dependency>
```

## Example

Quick steps to parse HTML data to java object.

1) Prepare java object
```java
    public class BBC {

        @W4Parse(select = "li[class=media-list__item media-list__item--1]")
        private BBCNews mainNews;

        public static class BBCNews {

            @W4Parse(select = "h3.media__title/a")
            private String title;

            @W4Parse(select = "p.media__summary")
            private String desc;
        }
    }
```
2) Run parser

```java
BBC bbc = W4Parser.url("http://www.bbc.com/", BBC.class).get();
```
Well done! We already fetched data from BBC website and got BBC class object. It is very simple.

For supported "select" options in W4Parser annotation please read the jsoup [docs](https://jsoup.org/cookbook/extracting-data/selector-syntax).

## Open source
W4Parser is an open source project distributed under the liberal MIT license.

## Status
W4Parser now under active development and has release status.

## Advanced usage

For example we want to fetch additional data from external url. In this case we can use W4Fetch annotation. For example:

```java
public class BBC {

    @W4Fetch(href = @W4Parse(select = "//section.module--promo//li[class='media-list__item media-list__item--1']//a.media__link/@href"))
    private BBCNews mainNews;

    public static class BBCNews {

        @W4Parse(select = "h1.story-body__h1")
        private String title;

        @W4Parse(select = "div.story-body__inner")
        private String fulltext;
    }
}
///.......
BBC bbc = W4Parser.url("http://www.bbc.com/", BBC.class).get();
```
In this case W4Parser parse the top page and find all links with selected rules ``` @W4Parse(select = "//section.module--promo//li[class='media-list__item media-list__item--1']//a.media__link/@href")``` . Then fetch data from this link and parse page with BBCNews class.

#### or we can fecth the list of remote pages
```java
public class BBC {

    @W4Fetch(href = @W4Parse(select = "//section.module--promo//a.media__link/@href"),
            maxFetch = 5)
    private List<BBCNews> mainNews;

    public static class BBCNews {

        @W4Parse(select = "h1.story-body__h1")
        private String title;

        @W4Parse(select = "div.story-body__inner")
        private String fulltext;
    }
}
///.......
BBC bbc = W4Parser.url("http://www.bbc.com/", BBC.class).get();
```
where ```maxFetch``` - is limit for W4Parser

#### W4Parser support for predefined remote url too
```java
public class BBC {

    @W4Fetch(url="http://www.bbc.com/news/world-australia-40822310")
    private BBCNews mainNews;

    public static class BBCNews {

        @W4Parse(select = "h1.story-body__h1")
        private String title;

        @W4Parse(select = "div.story-body__inner")
        private String fulltext;
    }
}
///.......
BBC bbc = W4Parser.url("http://www.bbc.com/", BBC.class).get();
```

### Also with W4Parser we can fetch remote & parse remote pages asynchronously

```java
W4QueueResult result = W4Parser
                .url("http://www.bbc.com/", BBC.class)
                .url("http://www.cnn.com/", CNN.class)
                .run();

```

or fully async implementation with promise
```java
W4Parser
    .url("http://www.bbc.com/", BBC.class)
    .url("http://www.cnn.com/", CNN.class)
    .run((result) -> {
        //Process W4Parser results.
    });
```

and what about progress of our task queue. No problem
```java
W4Parser
    .url("http://www.bbc.com/", BBC.class)
    .url("http://www.cnn.com/", CNN.class)
    .onProgress((taskResult) -> {
        //Here we can manipulate with completed task results
    })
    .run((result) -> {
         //Process W4Parser results.
     });
```

### Used by
[4weiver](http://www.4weiver.com)

### Author
Vadim Dobroskok

gha_language: Java


text:
---
path: "/learn-godot-tutorial-2-introduction-to-2d-physic"
date: "2019-08-06T12:00:00.962Z"
title: "Learn Godot > Tutorial 2 - Introduction to 2D physic"
description: "How to simulate that good old 2D retro physic"
keywords: "Godot, GDScript, tutorial, action, adventure, platformer, pixel art, physic, kinematic"
draft: false
---

2D physic is certainly the most confusing concept I had to work with. Not because I ain't good at math (pretty average) but because I never knew how to apply it to the video game concept.

 Just like in the old Mario game.

![super mario bros jump example](./super_mario_bros.png)

I found theses concepts difficult to implement for the following reasons

- like every newcomer, I barely understand the engine I was working with ([Unity](https://unity.com) at the time).
- I don't like maths and it doesn't like me.
- Lack of experience and clues to follow

My biggest question was "**Where should I start** ?". I saw a lot of code examples and tutorials, but I never felt to understand the good part. I just copy-paste without being confident about it and hoping it's gonna work as intended.

Just to be more playful and add some context to this article, I created mister Dogwar, our fantastic main character for a 2D platformer (don't be rude, I'm still new to drawing). This brave soldier gonna be used in for our example.

![dogwar](./dogwar.png)

## Godot's axis behaviour

Let first take a look at the Godot's editor view. Since we work on a 2D platformer, everything is computed from a Cartesian plane. Here how it looks on Godot's 2D view:

![godot_editor](./godot_editor.png)

- For the X-axis, the number goes, from left to right, negative to positive.
- For the Y-axis, the number for, from top to bottom, negative to positive.

Alright, this can be a little bit confusing, here a more simple representation.

![workspace](./workspace.jpg)

The Y axes are simply inverted if you're used to some other engine like Unity (where the Y axes go from positive to negative instead). The more you scroll down, the more the Y axis's value will increase and the more you scroll up, the more it will decrease.

## Gravity

Now that we understand Godot's 2D view, we can now begin the **maths** part. We gonna implement world's gravity. Don't worry, it's pretty simple. It will look like this.

![gravity_fall](./gravity_fall.png)

We need to increase the Y-axis value to let our character Dogwar fall if he is not colliding with anything. Gravity is a value that we change over each frame.

```c
# physics
export (float) var GRAVITY:= 900

func compute_gravity(host, delta: float) -> void:
	if host.gravity_enable:
		host.velocity.y += GRAVITY * delta
		if host.velocity.y > GRAVITY:
			host.velocity.y = GRAVITY
```

Let's explain this a little bit further. `compute_gravity` is called in the `_physics_process(delta: float):` method. `_physics_process` give us **delta**, it represented the time between each frame that our computer render. We multiply our gravity (here 900 px/sec) by it to ensure that our gravity will work the same on different hardware. Because if our game is rendered at 60 fps on a high PC and 30 fps on low-end hardware, we want to be sure that our falling speed stays coherent.

This code needs to be called every time since like gravity in the real world, it applies to us even when we do nothing.

![gravity_stay](./gravity_stay.png)

## Moving with velocity

If you look closely at the code, you saw a variable called velocity. For those who are not aware of this concept, the velocity of an object is

> the rate of change of its position with respect to a frame of reference, and is a function of time.
>
> Source [wikipedia](https://en.wikipedia.org/wiki/Velocity)

So our actual gravity is our current velocity where a force on the Y axes is always applied to simulate gravity. We simply need to change this velocity to let our character move or jump and whatever we need to do.

If we increase or decrease the X-axis value, the character will move left or right.

![gravity_move](./gravity_move.png)

On code, it looks like this

```c
func move(host, input_direction: Vector2, speed: float, acceleration: float) -> void:
	host.velocity.x = lerp(host.velocity.x, host.look_direction.x * speed, acceleration) if input_direction else 0
```

I check witch input is used to check if I need to increase or decrease the X value (computed through look_direction where his value can be 1 or -1) and use the lerp function to make the movement smoother. That's pretty much all.

## Jumping with velocity

Alright, here the last thing to cover all the basic features. How to make the character jump. If I refer to the gravity equation, if at each frame we apply a force to make the character fall, if we want to make our character going up, we need to made the opposite of the gravity.

Just read the following jump script used in my state machine:

```c

export (float) var MAX_JUMP_FORCE:= 550.0
export (float) var MIN_JUMP_FORCE:= 350.0

func enter(host: Player) -> void:
	host.get_node('AnimationPlayer').play('Jump')
	host.snap_enable = false
	host.velocity.y = -MAX_JUMP_FORCE

func handle_input(host: Player, event: InputEvent) -> InputEvent:
	if event.is_action_released('jump'):
		if abs(host.velocity.y) > MIN_JUMP_FORCE:
			host.velocity.y = -MIN_JUMP_FORCE

	return .handle_input(host, event)

#warning-ignore:unused_argument
func update(host: Player, delta: float) -> void:
	var input_direction: Vector2 = get_input_direction()
	update_look_direction(host, input_direction)

	if host.speed == 0 and input_direction:
		host.speed = SPEED
		host.acceleration = ACCELERATION

	move(host, input_direction, host.speed, host.acceleration)
	if host.velocity.y > 0:
		emit_signal('finished', 'JumpMidAir')
```

This script has 4 functions

- Play the jump animation
- Apply a jump force for a single frame (enter function)
- Manage a max/min jump force based on the time we pressed the jump input (handle input function)
- Let the player control the character when he jump (update function)

With my poor drawing skill, we can convert the code like this

![jump](./jump.png)

By setting a negative force to our Y axes, we make Dogwar going up. But since our gravity is also applied, that force will decrease the force at every frame and after X frames, the Y velocity will be positive and will make our character going down. And if we want to make our character move while jumping, just like the move behaviour, we just need to change our X value.

## Conclusion

You can get more context by taking a look at those scripts for my 2D platformer demo created especially for theses articles

- [Physics 2D](https://github.com/Levrault/godot-2d-action-adventure-platformer-demo/blob/master/demo/engine/Physics2D.gd)
- [Character motion state machine](https://github.com/Levrault/godot-2d-action-adventure-platformer-demo/tree/master/demo/characters/player/states/motion)

### More references

[Godot Engine 3 - Platform Game Tutorial by HeartBeast](https://www.youtube.com/watch?v=wETY5_9kFtA&t=1393s)

[Godot 3 - Platformer Tutorial - Part 1 - Getting Started by UmaiPixel](https://www.youtube.com/watch?v=MMsMtPVUtUE&t=1s)

[Unity Creating a 2D Platformer (E01. set-up) by Sebastian Lague](https://www.youtube.com/watch?v=MbWK8bCAU2w&t=2s)


text:
# SlackNet Examples
This folder contains several example projects:
- [SlackNetDemo](./SlackNetDemo) - the main example project, demonstrating some of the things you can do with a Slack app written with the help of SlackNet.
  - This project also serves as the example for integrating with Microsoft.Extensions.DependencyInjection.
- [AspNetCoreExample](./AspNetCoreExample) - an example of integrating SlackNet with ASP.NET Core.
- [AutofacExample](./AutofacExample) - an example of integrating SlackNet with Autofac.
- [SimpleInjectorExample](./SimpleInjectorExample) - an example of integrating SlackNet with Simple Injector.
- [NoContainerExample](./NoContainerExample) - an example of using SlackNet without a DI container.

repository: soxtoby/SlackNet

gha_language: C#

repo_name: soxtoby/SlackNet


text:
## [Unreleased]

## [19.10.2] - 2019-10-29
Added a task to save the reporter email address in an incident field, so it can be displayed on the summary page.

## [19.10.0] - 2019-10-03
Fixed an issue where the email authenticity check task failed to find the relevant script.

## [19.9.1] - 2019-09-18
  - Improved the Calculate Severity - Generic v2 playbook to evaluate the severity of an incident more accurately.
  - Added check for email authenticity using SPF, DKIM and DMARC. The verdict will also appear on the summary page of phishing incidents.

repository: cloudshark/content

repo_name: cloudshark/content


text:
---
title: How To Fix License File Related Errors
description: Find out tips and tricks on fixing License File (licenses.licx) related errors
type: troubleshooting
page_title: How To Fix License File Related Errors
slug: common-how-to-fix-license-file-related-errors
res_type: kb
---

Sometimes when upgrading a Web Site or Web App project to a newer version of Telerik.Web.UI.dll assembly, you may experience license file (licenses.licx) errors like the ones below, which may prevent the compiler to build the solution:

 * [LC : error LC0000: 'Could not load file or assembly 'Telerik.Web.UI, Version=20xx.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)' or Could not load file or assembly 'Telerik.Web.UI, Version=20xx.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4' or one of its dependencies. Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))'](#could-not-load-file-or-assembly)
 * [licenses.licx (1): Unable to resolve type 'Telerik.Web.UI.Rad<control_name>, Telerik.Web.UI, Version=201x.x.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4'](#could-not-load-file-or-assembly)
 * [Processing complist 'Properties\licenses.licx'...
12>C:\Projects\<Project Name>\Properties\licenses.licx(3): error LC0004: Exception occurred creating type 'Telerik.Web.UI.<Control_Name>, Telerik.Web.UI, Version=201x.x.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4' System.MissingMethodException: Constructor on type 'Telerik.Web.UI.<Control_Name>' not found](#could-not-load-file-or-assembly)
 * [Alternative NuGet solution](#alternative-nuget-solution)
 * [License file is missing](#missing-licenses-licx-file)
 * [License file is not updated and contains information for older versions of the controls](#license-file-is-not-updated-and-contains-information-for-older-versions-of-the-controls)
 * [Task could not find "LC.exe" using the SdkToolsPath](#task-could-not-find-lcexe-using-the-sdktoolspath)
 * [Could not transform licenses file into a binary resource](#could-not-transform-licenses-file-into-a-binary-resource)
 * [Source controls issues](#source-control-issues)
 * ["Thank you for using the Trial Version of Telerik UI for ASP.NET Ajax to build more powerful applications faster" error message in the browser](#getting-a-trial-error-message-when-refreshing-the-page)

## DESCRIPTION
As of Q1 2015, the Telerik ASP.NET AJAX uses the standard .NET licensing mechanism, which when adding the Telerik controls in design-time causes Visual Studio to add a license.licx file to the solution. Its purpose is to:
 * combat copyright infringement.
 * provide license holders in the company with statistics on the use of the available licenses.
 * send anonymous statistics about the controls usage.
The structure of the Licenses.licx file is similar to:

````ASP.NET
Telerik.Web.UI.Rad<Control_Name>, Telerik.Web.UI, Version=<Version_of_Telerik.Web.UI.dll_Assembly>, Culture=neutral, PublicKeyToken=121fae78165ba3d4
...
Telerik.Web.UI.RadGrid, Telerik.Web.UI, Version=2015.1.401.40, Culture=neutral, PublicKeyToken=121fae78165ba3d4
Telerik.Web.UI.RadCalendar, Telerik.Web.UI, Version=2015.1.401.40, Culture=neutral, PublicKeyToken=121fae78165ba3d4
````

and enlists the Telerik ASP.NET AJAX components used in the application and their fully qualified names.

The default location of the LicenseFile.licx is:

 * Web Sites - in the root of the site
 * Web Applications - in the Properties folder of the project

If your project build fails with errors pointing to the license file, follow the instructions in the section below to resolve them.

## SOLUTION
If you get errors related to the LC.exe (License compiler) as

### Could not load file or assembly
LC : error LC0000: 'Could not load file or assembly 'Telerik.Web.UI, Version=201x.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)'
licenses.licx (1): Unable to resolve type 'Telerik.Web.UI.Rad<control_name>, Telerik.Web.UI, Version=201x.x.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4'
Processing complist 'Properties\licenses.licx'...
12>C:\Projects\<Project Name>\Properties\licenses.licx(3): error LC0004: Exception occurred creating type 'Telerik.Web.UI.<Control_Name>, Telerik.Web.UI, Version=201x.x.xxxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4' System.MissingMethodException: Constructor on type 'Telerik.Web.UI.<Control_Name>' not found

or

Could not load file or assembly 'Telerik.Web.UI, Version=20xx.x.xxx.xx, Culture=neutral, PublicKeyToken=121fae78165ba3d4' or one of its dependencies. Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))'

you can solve them by:
 * Since the error could happen if the installed .NET Runtime assemblies are different than the project's configured .NET Runtime (targetFramework), make sure that the targetFramework of the app matches the .NET version of the Telerik Web UI assemblies. If the app is built against .NET 4.0, use the Telerik assemblies built for .NET 4.0 (in the manual installation they reside inside the Bin40 folder, for NET 4.5 and above, use the assemblies in the Bin45 folder). One way to test if this is the cause of the issue is to double-click on the error in the Visual Studio Output window which will open the file with the error. Upon opening the file, Visual Studio will then do some thinking and then the error will disappear.
 * Another reason for the error is the existence of old versions of the Telerik assemblies declared inside the licenses.licx file. Open the file and Delete the contents of the license.licx and making it read only.
 * Alternatively, you can also delete the whole license.licx file and rebuild
 * Or right-click the Telerik.Web.UI.dll file in Windows Explorer, select Properties, and then click the 'Unblock' button on the General tab near the bottom.
 * Or if your app is under the source control to make it ignore the license file so any changes on a developer machine won't make it into the build machine or anywhere elsewhere.

A customer report indicates that if the reference errors persist after following these steps, the solution was to re-install the NuGet package microsoft.bcl.build.

If the above does not help:

 * remove the reference to Telerik.Web.UI.dll in Visual Studio and re-add it.
 * [clean the Temporary ASP.NET Files folder and Visual Studio cache]({%slug common-cleanup-asp-vs-cache-and-temp%})
 * restart the PC
 * and test again the project

### Alternative NuGet solution

The [EmptyLicensesLicx](https://github.com/augustoproiete/EmptyLicensesLicx) is a third-party NuGet Package solution which ensures that the empty license.licx is present and working in Visual Studio.

For details of why the error occurs see the readme on the GitHub project. The [developer](https://github.com/augustoproiete) behind the project does a wonderful job of breaking down the [problem](https://github.com/augustoproiete/EmptyLicensesLicx#the-problem) and [solution](https://github.com/augustoproiete/EmptyLicensesLicx#the-solution).

### Missing Licenses licx file
If for some reason the license.licx file is missing and you are getting build errors because of it, you can rebuild the application and it should be recreated.
Another approach is to create an empty license.licx file in the root of your Web Site or in the /ProjectName/Properties folder, if you are developing a Web Application project.

### License file is not updated and contains information for older versions of the controls
If for some reason the licenses.licx file is not updated properly, you can delete its contents and rebuild the application.

### Task could not find LC.exe using the SdkToolsPath

If you get the Task could not find "LC.exe" using the SdkToolsPath error during automated MS Build tasks, review the [Telerik MSBuild Task could not find “LC.exe” using the SdkToolsPath](http://www.msigman.com/telerik-msbuild-task-find-lc-exe-sdktoolspath/) blog post by Matthew Sigman. Essentially, you should either install [Windows SDK](https://www.microsoft.com/en-us/download/details.aspx?id=82790) on the build machine, or add the /p:GenerateSerializationAssemblies=Off flag to the build arguments.

### Could not transform licenses file into a binary resource

The issue is discussed in the following MSDN article: [Could not transform licenses file 'file' into a binary resource. <reason>.](https://msdn.microsoft.com/en-us/library/caey6t0z.aspx)

### Source Control Issues

 * Unwanted check out of the project and solution files - After opening the Visual Studio designer, the licx file checks out the proj/sln file from source control, which may be annoying.
  * Preventing .NET from properly updating the file - the source control integration could prevent .NET to properly update the licenses.file (e.g., it may be read-only)

The solution for the above issues is to:
 * Delete the contents of the license.licx
 * Check in the file
 * Make the source control ignore the license file so any changes on a developer machine won't make it into the build machine or anywhere elsewhere.

### Getting a trial error message when refreshing the page

The "Thank you for using the Trial Version of Telerik® UI for ASP.NET Ajax to build more powerful applications faster. Purchase the Commercial Version now to get access to all product updates and the Telerik expert support." error is not directly related to the Licenses.licx file functionality, but to that the Telerik.Web.UI.dll is a trial build for demonstration and trial purposes only. You can check the articles below to see how to remove the trial error:
 * [Trial License Limitations](https://docs.telerik.com/devtools/aspnet-ajax/licensing/trial-license-limitations)
 * [Getting tired of seeing trial messages in your ASP.NET AJAX application?](https://www.telerik.com/blogs/getting-tired-of-seeing-trial-messages-in-your-asp-net-ajax-application)

repository: telerik/ajax-docs

repo_name: telerik/ajax-docs