text:
#Building an Upload Plugin for RMUploadKit

###Requirements

This document assumes a knowledge of programming in Objective-C and with the Cocoa frameworks. Experience in working with frameworks and plugins, although not required, will certainly help.

In order to build plugins for the RMUploadKit framework you will need the following:

- A 64-bit Intel Mac
- Mac OS X Snow Leopard
- Xcode Developer Tools 3.2 or later
 	- This is the build found on the Snow Leopard install disk, or from the [Apple Developer Connection][] website.
- The RMUploadKit SDK

Uploader plugins are 64-bit only and require Garbage Collection.

This documentation has been put together using Xcode 3.2 therefore if using a later version screenshots may differ from your version of Xcode.

###Dynamic Environment

Your plugins will be loaded into a very dynamic environment and you must take precautions to prevent any issues. Be sure to prefix all your classes with a shared prefix.

**NB:** This applies to any third-party frameworks or classes that you may use in your uploader.

###Framework Assumptions

The upload kit framework makes two critical assumptions.

- Your bundle identifier must never, ever change.
- Your preset, credentials and plugin classes all reside within that bundle.
- Your preset and credential class names are persisted, and expected to be found in future revisions of your bundle.

###Bundle Format

Your plugin bundle must have the file extension ‘uploader’.

Your plugin bundle identifier (the value for `CFBundleIdentifier` in the Info.plist) must be unique, and must not be prefixed ‘com.realmacsoftware’; that prefix is reserved.

Your bundle’s Info.plist file must also have a ‘RMUploadPluginBundleMinimumFrameworkBundleVersion’ key, the value for this key must be `<string>1</string>` or the plugin will not be loaded.

###Bundle Install Location

Double clicking a plugin bundle will launch Courier and install the plugin for your users. Should you need to install an uploader manually, copy it to `~/Library/Application Support/Courier/Plugins`.

###Getting Started

To install the SDK open the installer package included with this document.

This installs the SDK in `~/Library/Application Support/Developer/Shared/Xcode/SDKs/RMUploadKit.sdk`. You can put the SDK anywhere, though the ‘RMUploadKit Plugin’ project template is configured to look for the SDK in this location. If you do move the SDK, make sure you adjust the `ADDITIONAL_SDKS` build setting accordingly.

You should now be able to find the project template under “User Templates” in Xcode’s New Project window:
￼
The template should build out of the box and includes a plugin, preset and upload task - as well as pre-configured build settings for 64-bit Intel and Garbage Collection.

It also sets the `RMUploadPluginDestinationTypes` key for your template preset and links against RMUploadKit.framework. All of these steps can, of course, be done manually.

Assuming you have chosen to use the template, choose a name for your project (in this case we will be creating a plugin for [Ember][]) and Xcode will present you with a project setup similar to the one shown below:

The project should build successfully, and you are now ready to start coding.

**NB:** Your first build may be slower than usual - however this is expected as Xcode first creates a Composite SDK from the Base SDK (your platform, which will be Mac OS 10.6) plus the RMUploadKit SDK.

##Plugin Structure Overview

###Upload Plugin

The plugin object is the go-between for the framework and your plugin’s UI. There is one instance per plugin bundle and it provides view controllers to the framework.

The plugin must be the bundle’s `NSPrincipleClass`.

It is worth mentioning that one plugin bundle can contain support for as many services as you like. As long as there is one `RMUploadPreset` class for each, the plugin loader knows what your plugin contains by looking in the Info.plist for the `RMUploadPluginDestinationTypes` key, which is discussed later in this document.

###Upload Presets

Upload presets are a way of describing the intended destination of uploads in a way that can be persisted to avoid users entering details every time they wish to perform an upload. This means that depending on the service, presets can contain completely different information. For example, if we were writing a plugin that would just take a file and publish it to a location on disk, the preset would just need to store the target folder’s path.

However, if we were creating a plugin for the Ember image service the preset should store what collection the user wants to upload to along with a privacy level and any categories the user wishes to upload to.

###Upload Credentials

In some cases a preset will hold authentication information, however in cases where the user will benefit from being able to have multiple presets for a single account we have a credentials object.

An example to demonstrate this difference is an FTP account versus a Facebook account. With FTP there is no real benefit to having more than one preset per account so the preset can take charge of the login credentials. However, with Facebook as there could be any number of photo albums to upload an image to it is beneficial to keep the login details separate from the preset - this is where we use a credentials object.

###Upload Tasks

The framework deals with the creation and queueing of tasks, however it is the task’s responsibility to know how to upload the file it has been given to the requested destination.

Unlike other background task APIs, a run loop is available and serviced on the thread that upload is called on. You are discouraged from scheduling your network connections on another thread, and you must not recursively service the run loop yourself.

##Building the Preset

Our Ember plugin is going to support multiple presets for each account, so we don’t need to worry about authorisation in the preset - instead we'll add a credentials object a little later on. What we are going to store however is a target collection, category and privacy level for any uploaded images.

`RMUploadPreset` objects are really just model objects - a bundle of properties - however they must know how to write those properties out to a plist and read them in from one.

The first step is to add some properties to the object, declaring them in the header file first:

	#import <Cocoa/Cocoa.h>

	@interface EmberPreset : RMUploadPreset

	@property (assign) NSString *privacyLevel;
	@property (retain) NSDictionary *targetCollection;
	@property (retain) NSDictionary *targetCategory;

	@end

You can see that we haven’t declared any instance variables - this takes advantage of the modern runtime that allows us to use synthesized instance variables.

Open up the implementation file and you will notice that we have a lot of boilerplate code from the template. The `localisedName` and `uploadTaskClass` have been implemented for us, customise them if you need to.

The methods of interest here are `propertyListRepresentation` and `initWithPropertyListRepresentation:`. This is how we save and load presets respectively.

Essentially we are serialising the object but as we know that it is going into a plist we must be careful to only use objects that can be represented correctly. These are `NSString`, `NSData`, `NSNumber` and `NSDate` along with `NSDictionary` and `NSArray` as containers of those classes. Therefore the implementation of those methods for our EmberPreset would look something like this:

	- (id)initWithPropertyListRepresentation:(id)values
	{
		id superRepresentation = [values objectForKey:@"super"];
		self = [super initWithPropertyListRepresentation:superRepresentation];
		if (self == nil) return nil;

		self.privacyLevel = [values valueForKey:RMEmberPresetPrivacyKey];

		if ([values valueForKey:RMEmberPresetCollectionKey] != nil)
			self.targetCollection = [values valueForKey:RMEmberPresetCollectionKey];

		if ([values valueForKey:RMEmberPresetCategoryKey] != nil)
			self.targetCategory = [values valueForKey:RMEmberPresetCategoryKey];

		return self;
	}

	- (id)propertyListRepresentation
	{
		id superRepresentation = [super propertyListRepresentation];

		NSMutableDictionary *plist = [NSMutableDictionary dictionary];
		[plist setObject:superRepresentation forKey:@"super"];
		[plist setValue:self.privacyLevel] forKey:RMEmberPresetPrivacyKey];

		if (self.targetCollection != nil)
			[plist setObject:self.targetCollection
				    forKey:RMEmberPresetCollectionKey];

		if (self.targetCategory != nil)
			[plist setObject:self.targetCategory
				    forKey:RMEmberPresetCategoryKey];

		return plist;
	}

There are a few things to note in these implementations. The first is the name-spacing of the super’s representation. We do not guarantee the depth of the class tree for your instance, therefore you should be sure to pass the relevant data up the class hierarchy to ensure a proper initialisation.

In this example we do that by asking for the super’s plist representation and storing that keyed against “super” in the dictionary that we return.

It is also worth noting that we do not make any guarantees about the initialisation environment of the plugins, as they could be initialised on any thread.

As more of a coding best-practice, there are no string literals used for keys. Instead we have declared constants (not visible in the chunk above) as these avoid the runtime headaches that typos can cause.

So now our `EmberPreset` object can save and load itself correctly and stores the information that we need, but we need to be able to tell it when to persist its data. Rather than having a method to save we use Key-Value Observing in the framework to trigger saving of presets. Each preset has an `RMUploadPresetDirtyKey`, which when set to YES will trigger a save.

The key can either be set manually or by overriding `keyPathsForValuesAffectingValueForKey:` to fake a Key-Value Observing notification on the ‘dirty’ property to trigger a save. For our EmberPreset it looks like this:

	+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
	{
		NSMutableSet *keyPaths = [[super keyPathsForValuesAffectingValueForKey:key] mutableCopy];

		if ([key isEqualToString:RMUploadPresetDirtyKey]) {
			[keyPaths addObjectsFromArray:[NSArray arrayWithObjects:
							      RMEmberPresetPrivacyKey,
							      RMEmberPresetCollectionKey,
							      RMEmberPresetCategoryKey,
							      nil]
			 ];
		}

		return keyPaths;
	}

So any time a change is made to the privacy, collection or category the framework will observe it and the preset is saved to disk.

To tell the framework what file types you support you must override `-acceptedTypes` and append to the set of accepted UTIs:

	- (NSSet *)acceptedTypes
	{
		NSMutableSet *acceptedTypes = [[super acceptedTypes] mutableCopy];
		[acceptedTypes addObject:(id)kUTTypeJPEG];
		[acceptedTypes addObject:(id)kUTTypeGIF];
		[acceptedTypes addObject:(id)kUTTypePNG];
		return acceptedTypes;
	}

You can see that Ember supports JPEG, GIF and PNG. Use the constants in `<LaunchServices/UTType.h>` for common types, or any of your own custom UTIs.

Finally, a preset must declare the top-most URL of the service it uploads to. This can different per-preset by overriding `-serviceURL`, or the same across all instances of your preset by overriding `+serviceURL`.

`RMUploadPreset` has a default implementation of `+serviceURL` which constructs the result from your `Info.plist`. If you use the default implementation you must include values in your Info.plist for the `RMUploadPluginServiceHost` and `RMUploadPluginServiceUseSSL` keys.

##Using Credentials

As we have chosen to keep login details separate to the preset we will need a credentials object and, just like presets, these are really just model objects (containers of data).

**NB:** When it comes to login credentials it is more likely that you will be storing information in the keychain or another secure location, so the credentials object just needs to know how to retrieve that information.

If you’re working with a webservice, it’s highly likely that you’ll be working with more than just login credentials. From an Ember account (for example) we can get all sorts of information such as the user’s avatar, full name, date registered etc, and by also storing this information we can provide a much nicer view to the user when choosing which account to use for a new preset. In the case of our Ember uploader we settled with storing these properties:

	@interface RMEmberCredentials : RMUploadCredentials

	@property (copy) NSString *userName;
	@property (copy) NSString *fullName;
	@property (copy) NSString *token;
	@property (copy) NSURL *avatarLocation;
	@property (retain) NSDate *dateRegistered;
	@property (assign) NSUInteger totalImagesUploaded;
	@property (retain) NSArray *collections;
	@property (assign) NSUInteger followerCount;

	@end

We then implemented the property-list methods as with the preset, and the credentials class is now pretty much complete.

There is, however, one other method that a credentials class must implement:

	- (NSString *)userIdentifier
	{
		return [self userName];
	}

You should ensure this property is should be Key-Value Observable, using dependent key paths as appropriate.

As we manage the credentials with no real user input the class must provide the framework with a user-displayable identifier, which will be displayed to the user when selecting from a list of already configured credential objects.

In this case we have decided that the username should be an obvious way of choosing between credentials.

The credentials class is now written but we need to tell the framework when to use it, to do this we simply implement another method on the preset class:

	+ (Class)credentialsClass
	{
		return [RMEmberCredentials class];
	}

When this method is implemented the framework will look for any stored credentials of this class and if it cannot find any prompt the user to create one before starting preset configuration.

##Writing an Upload Task

Now we have our persistence set up it’s time to write the core of the plugin’s functionality: the code that actually deals with uploading our files.

The framework class is incredibly simple, consisting of just three methods `- initWithPreset:uploadInfo:`, `upload` and `cancel` - and the lifecycle of the object is pretty much explained in those methods. The object is initialised with any information needed, we then call upload on the object and if the user wishes to cancel then cancel is called.

Throughout the lifecycle of the object it keeps the framework informed with what is happening using notifications. During the upload process the task posts `RMUploadTaskDidReceiveProgressNotificationName` notifications so the framework can keep the user informed of the progress of the upload. When the task has received a response from the upload, it posts a `RMUploadTaskDidFinishTransactionNotificationName` notification. On completion, when the task has completed any bookkeeping, the task posts an `RMUploadTaskCompletedNotificationName` notification. Should any of the tasks’ operations fail, such as uploading, or adding a photo to an album; the error should be returned to the framework using the `RMUploadTaskErrorKey` key in the `RMUploadTaskDidFinishTransactionNotificationName` notification.

Taking a look at task initialisation first, the job here is to store any information we are going to require for the upload. The uploadInfo parameter is a key-value container for any metadata being provided for the upload. There is a set of pre-defined keys that it may contain or you may inject your own by using a custom metadata view, which will be elaborated on later. The important thing to remember is that it may or may not contain any of the keys and no key’s presence is guaranteed.

The predefined keys are as follows:

- `RMUploadFileURLKey` : The location of the file on disk.
- `RMUploadFileTitleKey` : The title the user has given for the file.
- `RMUploadFileOriginalDateKey` : The date the file was originally created in its current form.
- `RMUploadFileOriginalURLKey` : If the file represents a website, this is the URL it represents.
- `RMUploadFileDescriptionKey` : The description the user has given when setting metadata.
- `RMUploadFileTagsKey` : An array of strings which the user has tagged the image.

As opposed to pulling out just the information we need in this method we will store the whole uploadInfo and preset objects and worry about what we need in the upload method later on. This makes for easier code maintenance as if something changes in your preset or the uploadInfo you only have to make changes in the upload method.

Therefore our initialisation method is pretty barebones:

	- (id)initWithPreset:(RMEmberPreset *)preset uploadInfo:(id)info
	{
		self = [super initWithPreset:preset uploadInfo:info];
		if (self == nil) return nil;

		// Note: add anything else you need to setup

		return self;
	}

This means that all information is available to us when writing the upload method. As a result, the upload method is fairly hefty and certainly wouldn’t sit well in this document - however the Ember plugin is open-source for you to look at how it works.

Below we’ve simplified the upload method using pseudo code:

	(void)upload
	{
		// Note: pull out any keys required from the uploadInfo and build an instance of RMUploadURLConnection or NSURLConnection
		// ... create URL connection
		newConnection.delegate = self;
		self.uploadConnection = newConnection;
		// ... create URL request
		[self.uploadConnection sendURLRequest:request];
	}

In simple terms, all we are doing is setting up an instance of `RMUploadURLConnection` to do our upload work and sending it on its way. Most of the code in the class can be found in the delegate callbacks for `RMUploadURLConnection`, parsing the returned XML from Ember and posting the relevant notifications:

	- (void)connection:(RMUploadURLConnection *)connection uploadProgressed:(float)currentProgress
	{
		NSDictionary *progressDict = [NSDictionary dictionaryWithObjectsAndKeys:
						    [NSNumber numberWithFloat:currentProgress], RMUploadTaskProgressCurrentKey,
						    [NSNumber numberWithFloat:1.0], RMUploadTaskProgressTotalKey,
						    nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:RMUploadTaskDidReceiveProgressNotificationName object:self userInfo:progressDict];
	}

When our upload progresses we pass along a notification along with its relevant progress keys to keep the framework informed, as returns progress between 0.0 and 1.0, we say 1.0 as the total upload possible and whatever the connection just passed us as the current progress.

	- (void)connection:(RMUploadURLConnection *)connection didFailWithError:(NSError *)error
	{
		NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsForKeys:
								  error, RMUploadTaskErrorKey
								  nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:RMUploadTaskDidFinishTransactionNotificationName object:self userInfo:userInfo];

		[self _postCompletionNotification];
	}

If the connection fails we set the error key in the user info and then post the `RMUploadTaskDidFinishTransactionNotificationName` notification.

The completion method is similar:

	- (void)connection:(RMUploadURLConnection *)connection didCompleteWithData:(NSData *)data
	{
		NSError *documentError = nil;
		NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:0 error:&documentError];

		if (document == nil) {
			NSDictionary *errorInfo = [NSDictionary dictionaryWithObjectsAndKeys:
									   RMLocalizedStringInSelfBundle(@"The server returned an invalid response."), NSLocalizedDescriptionKey,
									   nil];
			NSError *error = [NSError errorWithDomain:RMEmberBundleIdentifier code:0 userInfo:errorInfo];

			NSDictionary *notificationInfo = [NSDictionary dictionaryWithObjectsAndKeys:
								    		  error, RMUploadTaskErrorKey,
								    		  nil];
			[[NSNotification defaultCenter] postNotificationName:RMUploadTaskDidFinishTransactionNotificationName object:self userInfo:notificationInfo];

			[self _postCompletionNotification];
			return;
		}

		// Parse XML for errors…

		NSError *locationXPathError = nil;
		NSString *imageLocation = [document stringValueForXPath:@"/response/item/permalink" error:&locationXPathError];

		NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
		[userInfo setObject:document forKey:RMEmberXMLDocumentKey];

		if (imageLocation != nil) {
			[userInfo setObject:[NSURL URLWithString:imageLocation] forKey:RMUploadTaskResourceLocationKey];
		}

		if (self.destination.targetCollection != nil)
			[self addToCollectionFromDocument:document];

		if (self.destination.targetCategory != nil)
			[self submitImageToCategoryFromDocument:document];

		// Completed notification is only sent when all metadata is also set.
	}

In this code chunk we can see some basic parsing to find the resultant location of the uploaded image and we set that against the `RMUploadTaskResourceLocationKey` key. We also set a custom key in the user-info of the completion notification and this is passed on to our completion view UI so we will be able to access it.

We also deal with setting some additional metadata that was configured in the preset - however the implementation details are unimportant as they are just simple calls to the Ember API.

At this point all we have to do is add a basic cancel method to complete the upload task:

	- (void)cancel
	{
		[self.uploadConnection cancel];
		[[NSNotificationCenter defaultCenter] postNotificationName:RMUploadTaskDidCompleteNotificationName object:self];
	}

As we have kept a reference to the connection as a property it is easy to cancel the upload and tell the framework that the cancelling has completed. You should post the completed notification as soon as possible after being sent cancel.

##Adding the User Interface

###The Plugin

The framework requests user interface components, in the form of `NSViewController` objects through the the `RMUploadPlugin` subclass instance and there are three possible opportunities for plugins to inject their own views into an application using the framework.

- The preset configuration view
- The credentials configuration view
- The view displayed to configure upload metadata

Your plugin is only required to provide a view for the preset configuration, unless you provide credentials in which case a credential configuration view is also required.

In our Ember plugin we will return user interface at all possible opportunities, here is the implementation of our EmberPlugin class:

	@implementation EmberPlugin

	- (RMUploadPresetConfigurationViewController *)credentialsConfigurationViewControllerForCredentials:(RMUploadCredentials *)credentials;
	{
		RMEmberCredentialsViewController *controller = [[RMEmberCredentialsViewController alloc] initWithNibName:@"CredentialsConfigurationView" bundle:[NSBundle bundleWithIdentifier:RMEmberBundleIdentifier]];
		return controller;
	}

	- (RMUploadPresetConfigurationViewController *)presetConfigurationViewControllerForPreset:(RMUploadPreset *)preset
	{
		RMEmberPresetConfigurationViewController *controller = [[RMEmberPresetConfigurationViewController alloc] initWithNibName:@"PresetConfigurationView" bundle:[NSBundle bundleWithIdentifier:RMEmberBundleIdentifier]];
		return controller;
	}

	- (NSViewController *)additionalMetadataViewControllerForPresetClass:(Class)presetClass
	{
		return [[NSViewController alloc] initWithNibName:@"MetadataView" bundle: [NSBundle bundleWithIdentifier:RMEmberBundleIdentifier]];
	}

	@end

Although you must provide a preset, not all plugins need to provide a preset configuration view controller.

If your preset uses a credentials object, you can return nil for your preset configuration view controller to skip any preset setup. This allows you to provide credentials with the possibility of adding preset options later.As you can see we have chosen to create custom view controllers for all but one of the views and are returning them. For the last however, because the view is so simple the entire UI is handled by binding controls directly to the `representedObject`.

In each case, the relevant object is set as the `representedObject` for each view controller:

- The `RMUploadPreset` instance for the preset configuration view
- The `RMUploadCredentials` instance for the credentials configuration view
- The `uploadInfo` KVC container for the additional metadata view

It is also worth noting that the relevant objects are passed to the methods so if your plugin supports multiple services you can return the appropriate view controller for that service.

###The Preset Configuration View

The preset configuration view is the UI displayed when a user is either creating or editing a preset, and this is required for any upload plugin. You are expected to provide a view and controller that allow the user to specify any information that is stored as part of a preset.

Taking our Ember preset configuration view as an example we have got quite a simple looking form, but beneath the hood there are some complexities that make the user’s life extremely simple when setting up presets.

As you can return a custom view controller you have the flexibility to achieve pretty much anything you like with any of the views returned to the framework. Although as the `representedObject` is set on the view controller for you, you can get away with most of the UI work by binding controls directly to it.

###The Credentials Configuration View

Similar to the preset configuration, this view is required if you support credentials in your plugin and is used to configure those credentials.

###The Additional Metadata View

The framework allows plugins to request additional information about items to upload from the user. This is achieved by allowing a plugin to inject a view where the user configures the upload’s metadata. Through that UI the plugin can add key/value pairs to the `uploadInfo` object. Ensure any keys you use are namespaced to your plugin to avoid conflicts.

There are a few things to keep in mind when returning your additional metadata view. Firstly, the view will be placed in a scroll view, secondly the uploadInfo object is the `representedObject` of the returned controller, therefore you can bind values on your interface easily. Also try and keep the view as small and simple as possible, it is going to be presented stacked with other metadata views, anything too complex will notably degrade the user experience.

##Common Gotchas

If your plugin fails to load, first check these points:

###Check your Binary
- Check that your plugin is compiled for 64-bit Intel.
- Check that your plugin is compiling with Garbage Collection set to required.
- Confirm that your bundle extension is ‘uploader’

###Check your Info.plist
- Check that the `RMUploadPluginBundleMinimumFrameworkBundleVersion` key is present and has the correct value.
- Check that the principal class is correct.
- Check that your preset class names are correct.

If your bundle still doesn’t load, please contact [Realmac Software Developer Technical Support][], attaching your bundle and providing as much information as possible.

##Appendix - Embedding Envelope Themes

**NB:** this is a Courier only API and doesn’t affect your plugin’s functionality.

It’s possible to embed envelope themes and autosuggest a theme on a per-preset basis. For more information on this, see the ‘Courier Envelope SDK’ and simply include the relevant keys in your Info.plist.

If your plugin bundle provides an envelope theme for a preset, the envelope key should be returned from `+[RMUploadPreset autoselectTrayImageKey]`.

[Ember]: http://emberapp.com
[Apple Developer Connection]: http://developer.apple.com
[Realmac Software Developer Technical Support]: http://www.realmacsoftware.com

repository: tocheskey/RMUploadKit-SDK

path: /Building an Upload Plugin.md

filename: Building an Upload Plugin.md

repo_name: tocheskey/RMUploadKit-SDK


text:
# AR50

[![StackShare](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](https://stackshare.io/aaryarajoju/ar50)

## Introduction

AR50 is a discord bot built using [Discord.JS](https://discord.js.org/#/), capable of doing a lot of miscellaneous tasks, like showing the current weather, getting stock details, and some mathematical functions.

## Add it to your server

[NOTE: the bot won't be up 24/7]

[Invite the bot to your server](https://discord.com/api/oauth2/authorize?client_id=786238151509016628&permissions=182336&scope=bot)

(You need to have the `Manage Server` permission for the server you want to add the bot to)

## Commands

`50!-` is the command prefix for the bot

The list of commands are as follows:

* `50!-help` - shows all of the available commands.

* `50!-weather` - gets the weather details of a location using the [Weather API](https://www.weatherapi.com/) and displays the current weather condition, the current temperature, the temperature it feels like, and a picture of the weather condition.

* `50!-stock` - gets the stock details of a publically traded entity, using the [Alpha Vantage API](https://www.alphavantage.co/), and shows the current stock price, along with the net change and net change percentage.

* `50!-factorial` - calculates the factorial of a number

* `50!-power` - calculates the value of raising a number to the power of a second number

* `50!-square`, and `50!-sqrt` - calculates the square and square root of a number, respectively

* `50!-sq_area`, `50!-rect_area`, and `50!-circle_area` - calculates the area of a square, rectangle and a circle, respectively

* `50!-sq_perimeter`, `50!-rect_perimeter`, and `50!-circle_perimeter` - calculates the perimeter of a square, rectangle and a circle, respectively

* `50!-add`, `50!-multiply`, `50!-difference`, `50!-subtract`, and `50!-divide`

---

## The v1.0

* [x] Stock Figures
* [x] Weather
* [x] Basic Mathematical functions

---

## Run it for yourself

Prerequisites: [Node.JS](https://nodejs.org/en/) (and [npm](https://www.npmjs.com/)), your bot's token, an api key from [Alpha Vantage](https://www.alphavantage.co/), and an api key from [Weather API](https://www.weatherapi.com/).

Fork [the repository](https://github.com/aaryarajoju/AR50), and then clone it to your local device.

In that directory, install [Discord.JS](https://discord.js.org/#/) with the command `npm install discord.js`.

And then, add a file called `config.json` in the same directory, which should contain the following code:

````json
{
    "prefix": "50!-",
    "token": "<the bot token>",
    "stockApiKey": "<the api key from Alpha Vantage>",
    "weatherApiKey": "<the api key from Weather API>"
}
````

(*You can change the prefix, if you wish*)

For running the program, use the command `node index.js` in the same directory.

---

Note: The program is [licensed under the MIT open source license](https://github.com/aaryarajoju/AR50/blob/main/LICENSE).

---

## For Contributors

If you wish to contribute to the project, you can create an issue and also send pull requests.

For any suggestions, please contact<EMAIL_ADDRESS>
---

license: MIT

branch_name: refs/heads/main

extension: md

license_type: permissive


text:
# ruby-mws [DEPRECATED]

by Erik Lyngved

ruby-mws is a Ruby gem that wraps the Amazon Marketplace Web Service (MWS) API.

I made this gem a few years ago for my own purposes with the intention of open sourcing it. It's not fully featured as I only implemented what I needed at the time. I've moved on to other projects and **I am no longer maintaining this gem.**

Feel free to use this gem in any capacity and check out the Pull Requests others have submitted to introduce functionality for other endpoints. If you are still evaluating different MWS gems, you may want to check out [Peddler](https://github.com/hakanensari/peddler) which is currently being maintained and is more fully featured.

Quick Start
-----------

To quickly test your connection to the service without credentials, you can ping the server, which returns server time in UTC:

    MWS::Base.server_time

### Initialization

Pass in your developer account credentials. All four params below are required.

    mws = MWS.new (:aws_access_key_id => "<REDACTED_AWS_ACCESS_KEY>",
      :secret_access_key => "abc123def456/SECRET/+ghi789jkl",
      :seller_id => "A27WEXAMPLEBXY",
      :marketplace_id => "ATVPDKIKX0DER")

### Requests

We'll use the Orders API to retrieve recently updated orders.

    # Retrieve all orders updated within the last 4 hours
    response = mws.orders.list_orders :last_updated_after => 4.hours.ago   # ActiveSupport time helper

(All datetime fields accept Time or DateTime objects, as well as strings in iso8601 format.)

### Responses

Response objects inherit [Hashie](http://github.com/intridea/hashie) for easy access and [Rash](http://github.com/tcocca/rash) to convert Amazon's CamelCase convention to underscore. So you're just left with plain ol' Ruby goodness.

Let's parse our response to view the orders and any other data returned.

    response.orders.first   # => { "amazon_order_id" => "002-EXAMPLE-0031387",
                            #      "purchase_date" => "2012-01-13T19:11:46.000Z",
                            #      ... }

Response objects are accessible in Hash or method notation.

    response.orders == response[:orders]   # => true

Use `keys` and `has_key?` to discover what's in the response.

    response.keys   # => ["last_updated_before", "orders"]
    response.has_key? :last_updated_before   # => true

### NextToken requests

For responses with long lists of data, results are returned from the service in pages (usually 100 per page). Example:

    response = mws.orders.list_orders :last_updated_after => 1.week.ago   # returns 100 orders & next_token

Here, there are more orders to be returned. You can call `has_next?` on the same API instance to see if the last response returned has a next page. If so, calling `next` will make the request for the next page.

    mws.orders.has_next?   # => true
    next_response = mws.orders.next   # returns next page of orders

Repeat as necessary. You can keep calling `next` on the API instance as long as `has_next?` returns true.

Or if you need to, you can save `next_token` and go about the manual way as per Amazon's docs:

    next_response = mws.orders.list_orders_by_next_token :next_token => response.next_token

***

API
---

    @mws = MWS.new(authentication_hash)   # initialize the connection object (see above)

This object can be used to access all API services. Below are examples on how to make the different requests that are available so far. Refer to the [Amazon MWS Reference Docs](https://developer.amazonservices.com/) for available fields for each request.

### Orders API

* ListOrders - Gets orders by time range and other parameters

<EMAIL_ADDRESS>:last_updated_after => Time.now-4.hours, :order_status => 'Shipped'`

* GetOrder - Gets orders by Amazon order ID

<EMAIL_ADDRESS>:amazon_order_id => "002-EXAMPLE-0031387"`

    `:amazon_order_id` can be an array to retrieve multiple orders.

* ListOrderItems - Gets order items for one order ID (only one order at a time here)

<EMAIL_ADDRESS>:amazon_order_id => "002-EXAMPLE-0031387"`

### Fulfillment Inventory API

* ListInventorySupply - Returns availability of inventory, only returns items based on list of SKUs or last change date

<EMAIL_ADDRESS>:seller_skus => ['PF-5VZN-04XR', 'V4-03EY-LAL1', 'OC-TUKC-031P']`
<EMAIL_ADDRESS>:query_start_date_time => Time.now-1.day`

### Reports API

* RequestReport - Used to submit a request for a report by [report type](http://docs.developer.amazonservices.com/en_US/reports/Reports_ReportType.html). Returns report request info.

<EMAIL_ADDRESS>:report_type => "_GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA_", :start_date => 1.day.ago, :end_date => Time.now`

* GetReportRequestList - Returns a list of the most recently requested reports. Use `report_request_id` to find the status of your report. Once `report_processing_status` for your request is "_DONE_", use `generated_report_id` to get your results.

<EMAIL_ADDRESS>
* GetReport - Used to request a report by report ID. All reports are currently returned as a flat file string.

<EMAIL_ADDRESS>:report_id => '11223344'`

repository: elyngved/ruby-mws

branch_name: refs/heads/master

extension: markdown

gha_language: Ruby

repo_name: elyngved/ruby-mws


text:
# IEC Pressure Endurance Test Fixture
This document will describe the steps for basic usage of the fixture
## Physical Setup
The physical setup of the test fixture.
| ![Drawing of Front Face of Fixture](./images/image5.png) |
| :---: |
| _Front Face of Fixture_ |

| ![Drawing of Back Face of Fixture](./images/image4.png) |
| :---: |
| _Back Face of Fixture_ |


text:
---
layout: post
title: "The value of Apps"
date: 2012-07-24 08:37
comments: true
categories: [Software]
---

The online conversation on the Sparrow sale continues unabated. But in amongst all the vitriol, I found some amazing articles written long before the sale pretty much predicting how it is now. Here are some great quotes and links.

Guy English, in [Software Sea Change](http://kickingbear.com/blog/archives/67):

{% blockquote %}
An Application represents the developer’s best effort at creating software that applies the capabilities of the device to solving a specific problem. Making people laugh is not a problem an Application can solve; it’s not about the device it’s about the person using it.
{% endblockquote %}

and

{% blockquote %}
Apps are not Applications – they are their own things. They are smaller. They are more fun. Apps are treats atop your technological sundae. They are not potential time sinks. They are neither burden nor investment. They each represent a nugget of fun, of fleeting amusement. Apps are gobbled up in the millions by people who would never rush so willy nilly to buy desktop software. Apps are Pop Software writ large in blinking neon lights.

Are Apps good business? No, they’re not. From a small developer’s perspective the App Store is a total disaster.
{% endblockquote %}

Kyle Baxter, in [Entitlement and Acquisition](http://tightwind.net/2012/07/entitlement-and-acquisition/):

{% blockquote %}
There’s something important to learn here: since the App Store’s primary customers are mass-market, they don’t yet value apps very much, and are therefore only willing to pay a pittance for apps. For them, apps are simply entertainment, sometimes a bit more, but not much more.
{% endblockquote %}

Faruk Ates states what the customer’s perception is in [When Selling Out is, In Fact, A Dirty Choice](http://farukat.es/journal/2012/07/661-selling-out-is-dirty):

{% blockquote %}
There is an implicit promise in the act of doing business. It is a promise of respect and mutual trust, where the business offers the customer something of value, for which the customer pays money. The free-but-paid-with-advertising model has made this promise blurry, but not absent. When a company sells itself to a bigger company as a talent acquisition, leaving the product—and, consequently, its customers—out in the cold as a result of this acquisition, it is a reneging on that implicit promise.
{% endblockquote %}

Kyle Baxter, responds to Faruk in [In Response to When Selling Out is, In Fact, A Dirty Choice](http://tightwind.net/2012/07/ates-response-to-gemmell/):

{% blockquote %}
That doesn’t mean, though, that it’s a good situation. It isn’t at all. It sucks for customers that an application they like and have come to rely on will, at some indefinite point in the future, stop working for them and will not improve. This problem, though, has to do with the App Store’s structure. The fact is when charging for upgrades isn’t possible and isn’t expected, it’s difficult to make an application like Sparrow and succeed. Very difficult. We should spend our time trying to solve that problem, so more small developers can make a living building well-made, useful, focused applications on these new devices.
{% endblockquote %}

Rian van der Merwe nails it in [The real reason we’re upset about Sparrow’s acquisition](http://www.elezea.com/2012/07/sparrow-google-acquisition/) talking about how we tried to switch to a paid model, and it still was not enough:

{% blockquote %}
The real issue is the sudden vulnerability we feel now that one of our theories about independent app development has failed.
{% endblockquote %}

Jim Harvey, commenting in [Hacker News](http://news.ycombinator.com/item?id=4284088) on AppCubby’s [The Sparrow Problem](http://appcubby.com/blog/the-sparrow-problem/) incorrectly assumes the barrier to being an indie developer is getting lower, but I hope he’s not right in:

{% blockquote %}
Indie developers may well go the way of indie journalists: while a few flourish, most wind up working for beer money.
{% endblockquote %}

*#OpensAHeineken*

gha_language: JavaScript


text:
# Theming

## Bootstrap grid
React Dash uses bootstrap responsive grid.
Full docs are [here](https://v4-alpha.getbootstrap.com/layout/grid/)

Layout is defined as an array of regions. Each region represents a bootstrap row, as follows:

```javascript

regions: [
    {
      className: 'row',
      children: [
        {
          type: 'Metric',
          value: 'A',
          className: 'col-4-md'
        },
        {,
          type: 'Metric',
          value: 'B',
          className: 'col-4-md'
        },
        {
          type: 'Metric',
          value: 'B',
          className: 'col-4-md'
        }
      ]
    }
]
```

Note that we're just using the bootstrap classes to define the responsive grid.

## cards
Component are rendered inside of the [Card component](../components/Card).

The Card component exposes a number of regions which can be targeted as props:

## custom css
The `index.html` file in the examples project loads `static/custom.css`. Add custom css here.

## inline styles
Define a style object in `settings.js`:
```javascript
{
  type: 'yourComponentType',
  style: {height: '100%', maxWidth: '60%', fontFamily: '"Times New Roman", Georgia, Serif'}
}
```

repository: blynchNDI/react-dash

gha_license_id: MIT

repo_name: blynchNDI/react-dash


text:
# Change Log

## [1.2.0] - 2022-06-27

### Changed

- Improved (clearer) code for Parameterized Test Case example.
- Changed default compiler to `mpifort` when using `make` with the MPI example.

## [1.1.0] - 2022-06-20

### Added

 - Introduced directory to show how to construct parameterized tests with pFunit.

## [1.0.0] - 2019-12-19
- Improved Make example to find the lastest installed version of pFUnit.

gha_language: Fortran


text:
# pywrdgen
[![PyPI version shields.io](https://img.shields.io/pypi/v/pywrdgen.svg)](https://pypi.python.org/pypi/pywrdgen/) [![PyPI pyversions](https://img.shields.io/pypi/pyversions/pywrdgen.svg)](https://pypi.python.org/pypi/pywrdgen/) [![MIT license](https://img.shields.io/badge/License-MIT-blue.svg)](https://lbesson.mit-license.org/) [![made-with-vim](https://img.shields.io/badge/Made%20with-Vim-1f425f.svg)](https://www.vim.org/) [![Awesome Badges](https://img.shields.io/badge/badges-awesome-green.svg)](https://github.com/Naereen/badges)

Generate (possibly) secure passwords.

Just a little project to toy around with. I don't intend this to be anything
ground-breaking and exciting. Just a little utility to generate password(s).

# use
From inside your virtual environment of choice, install the requirements. Then
run the module or source file directly. This might be done as..

```bash
pip install -r requirements.txt    # Install requirements
python -m pywrdgen                 # Run as a module
python pywrdgen/__main__.py        # Run the source file directly

python -m pywrdgen --help          # Display global flags help
python -m pywrdgen gen --help      # Display generator flags help
```

# ideas
- Pronouncable passwords
- Password strength checking
- Batch check password strength from file

# contributing
Any, and all contributions are welcome. Be it issues, suggestions, thanks. I
appreciate all of it. Feel free to submit a pull request, or write an issue
with what's on your mind.

repository: ncdulo/pywrdgen

gha_language: Python

repo_name: ncdulo/pywrdgen


text:
# Ecommerce-backend (object-relational mapping)
---
# Descripition
This project is an ecommerce backend project for an ecommerce site. It uses MySQL database, Express.js Api and sequilize. The api routes are linked with the models and the seeds were provided to create the schema database.
---

# Table of Contents
* Description
* Installation
* Usage
* Contributing
* Lincense
* Question
---

# Installation
Run npm install to install the packages for the application. Create a .env file and npm install dotenv to store DB_NAME, DB_USER, and DB_PW
---

# Usage
Run NPM start in terminal to launch and Insomnia to test the Routes
---

# Contributing
Read the installation section
---

# License
MIT
---

# Questions
* Github Page: Benmuchemi15
* Email: bensonmuchemi70@gmail.com


text:
# Easy Shops

## Description

The app is a platform for Movie Shops, where their customers can see their new products

## Setup/Installation Requirements

* You clone the repository
* create a virtual env
* install Requirements.txt
* make migrations `./manage.py makemigrations`, `./manage.py migrate`
* run `./manage.py runserver`
## Specifications for the BDD
* Movie shop should create an account
* Movie shop should have unique url and their own followers
* Movie shop should update their products for everyone to see
* Movie shop should have a profile
* Users should see all shops near them on a map
* Users should see profile of a movie shop
* User should subscribe to a movie shop
* User should like a movie shop

## Technologies Used

* Python
* django
* postgresql
* google maps

### License

*MIT*

Copyright (c) 2017 **David Njoroge**

repository: DavidNjoroge/easy-shop

gha_language: HTML

repo_name: DavidNjoroge/easy-shop


text:
# AvMon - HTTP endpoint availability monitor

A microservice-based HTTP endpoint monitor using [Python](https://python.org/) for the actual code, [Apache Kafka](https://kafka.apache.org/) for combining multi-writer events into a single queue and [PostgreSQL](https://www.postgresql.org/) for long-term data storage.

![Architecture diagram](docs/architecture.svg)

The project is dockerized using a single container, which is switched to perform different functions with the `AVMON_ROLE` environment variable. Collector components are configured using a mounted config file.

## Running

A minimal local system (one of each component) can be started with:

```bash
make create-dotenv docker-up
```

or even smaller system without dockerizing the application itself, running all Python services in a single process (requires Python >= 3.8):

```bash
make create-dotenv install-deps docker-dbs run-all
```

In either case, navigate to https://localhost:8080/ for the visualization. Then proceed to tweak the [configuration file](avmon.cfg.toml) to include sites you would like to monitor.

### Using external databases

If you are going to use external non-dockerized database, such as a cloud-hosted one, then the authentication must be configured using either a `.env` file or actual environment variables:

```
POSTGRES_HOST=host.example.org
POSTGRES_PORT=5432
POSTGRES_USER=avmon
POSTGRES_PASSWORD=PASSWORD_HERE
POSTGRES_DB=avmon

AVMON_KAFKA=host.example.org:9092
AVMON_KAFKA_SSL=1
```

Moreover, with `AVMON_KAFKA_SSL=1` you must pass the actual SSL keys and certificates. They should be placed in a folder named `keys` and the filenames should be `access-key`, `access-cert`, `ca-cert`.

Remote databases must also be set up properly. Usually that means at least that PostgreSQL user and database must be created. Kafka should require no special setup, but make sure that it is configured to automatically create topics (`kafka.auto_create_topics_enable=1`) or manually create a topic called `messages`.

## Project structure

Most important project files are:

* [`avmon/`](avmon/) - Python modules
    * [`collector.py`](avmon/collector.py) - Polls the sites and pushes the results to Kafka. Has own config, parallelizes well.
    * [`backend.py`](avmon/backend.py) - Receives events from Kafka and writes them to a Postgres database.
    * [`frontend.py`](avmon/frontend.py) - Simple visualization frentend
    * [`frontend.html`](avmon/frontend.html) - Frontend HTML template
* [`tests/`](tests/) - Integration / E2E tests
* [`requirements.txt`](requirements.txt) - Runtime Python package dependencies
* [`requirements-dev.txt`](requirements-dev.txt) - Development Python package dependencies
* [`docker-compose.yml`](docker-compose.yml) - Docker-compose-file for running the project normally
* [`docker-compose-dbs.yml`](docker-compose-dbs.yml) - Docker-compose-file for running only the databases in Docker
* [`Dockerfile`](Dockerfile) - Dockerfile to containerize this project
* [`Makefile`](Makefile) - Convenient shortcut commands
* [`avmon.cfg.toml`](avmon.cfg.toml) - Example configuration file
* [`docs/`](docs/) - Auxiliary documentation files

## Development

Requireds Python (>= 3.8), and Docker + Docker-compose. Most of the commands are rather \*nix-specific, so Linux or macOS is recommended.

### Setup

```bash
make dev-setup
```

Installs the dev dependencies locally. It also creates git hooks that make sure you will not commit unformatted code or push untested code.

### Formatter

The project uses [Black](https://github.com/psf/black) for code formatting to ensure uniform style. To automatically format code, run `make format`.

### Type checking

[Mypy](http://mypy-lang.org/) is used for type checking. To make sure you have not introduced type errors, run `make type-check`.

### Tests

`make test` runs the whole test suite, which takes quite some time. Use `python -m pytest -k testname` to run one test at a time. `python -m pytest -s` can be used to see test output while the test is still running. Please note that the E2E tests use docker-compose to manage environment and cannot be ran if the system is already running.

## License

MIT

repository: Dentosal/avmon

repo_name: Dentosal/avmon


text:
# Security Policy

## Reporting a Vulnerability

The images created by CardboardCI are provided "as is", without warranty of any kind, express or implied as per the license. Any vulnerabilities that exist should be resolved can be resolved in an individuals clone of the repository.

repository: cardboardci/dockerfiles

gha_language: Starlark

repo_name: cardboardci/dockerfiles


text:
# Generative Adversarial Networks

(Review by [Max Strakhov](https://github.com/monnoroch), with images taken from the paper)

Generative Adversarial Networks (GAN) is a framework for generating realistic samples from random noise first
introduced by Goodfellow et al in 2014. At a high level, a GAN works by staging a battle between two neural networks.
The first one generates samples. In parallel, the second network tries to discriminate those samples from samples from
the real data.
We’ll first describe why we would want to do this and give some intuition behind what inspired GANs.
We’ll then describe how they work, detail some disadvantages, and close with recent and future directions.

  Here are a set of faces generated purely from random noise.

  Source: http://torch.ch/blog/2015/11/13/gan.html.

So far deep generative models have had much less success than deep discriminative models.
This is partly due to difficulty in approximating intractable probabilistic posteriors that arise in their
optimization algorithms, which forces practitioners to use techniques like
[Markov Chain Monte Carlo](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo).
It’s also because many of the methods that help train discriminative models do not work as well when applied to
generative models.
The adversarial framework in this paper can be trained purely with back propagation and helps solve some of
these problems.

GANs are an idea rooted in Game Theory.
Two models compete against each other.
The first, the generator, generates examples that it thinks are real.
The second, the discriminator, tries to discriminate between examples from the dataset and examples drawn
from the pool generated by the generator.
The discriminator is trained in a supervised manner with two labels - Real and Generated.
The generator is trained to maximize the discriminator’s error on generated examples
and consequently learns how to generate examples that approximate the real data distribution.
Overall, we are optimizing the adversarial loss,

Those familiar with game theory might appreciate the insight that the optimization of this objective is like finding
a Nash equilibrium of a minimax game between the generator and the discriminator.
The loss has two components.
The first one, , makes the discriminator  better at
discriminating real examples from fake ones, and the second one, , makes the generator
 generate samples that the discriminator considers real.
The input, , is a noise vector with distribution .
This is usually an N-dimensional normal or uniform distribution and serves as input to the network.

Both parts can be independently optimized with gradient based methods.
First, do an optimization step for the discriminator to maximize , then do
an optimization step for the generator to make it better at fooling this new discriminator by minimizing
.
If  is very low, which is the case early in training,
 is very close to zero and the generator cannot learn quickly.
This can be fixed by maximizing  instead, which converges to the same solution, but
provides strong gradients when  is low.

Here’s a visual explanation of how the learning happens.

 Training a GAN to fit a data distribution.

Imagine that the real data is represented by some distribution, drawn as a dotted black line on the figure.
Real examples then are obtained by sampling from it.
The domain of the model's input is .
Fake examples are obtained by sampling from some distribution on domain .
The generator maps this  to , which results in fake examples
that are distributed according to the green line on the figure.
The dashed blue line represents the discriminator, which gives each example from  a probability
of being from the real data distribution.

The generator and the discriminator are each initialized randomly (see Figure (a)), and then we train the discriminator to
distinguish real examples from fake examples produced by the generator (see Figure (b)).
Once trained, we fix the discriminator and train the generator to maximize the discriminator’s error (Figure (c)).
Then we train the discriminator again, and so forth, until convergence.
At this point, the generator has learned a true data distribution which matches the black dotted line exactly.
Therefore the discriminator has no way of telling whether an example is real or fake, so it consistently returns ½ (Figure (d)).

Under certain conditions, this process reaches a fixed point where the generator has learned the true
data distribution, and hence the discriminator cannot classify real examples from generated ones.
The original paper’s model is capable of generating great results on simple tasks such as MNIST.
Recent advances have made it possible to get high quality examples on more complicated problems, like generating faces and CIFAR
images.

## Experiments.

To evaluate model performance quantitatively, it is possible to calculate the likelihood of the real examples that the model induces.
Given the distribution induced by a trained GAN, real data from the MNIST dataset has an approximated log likelihood of 225
(with standard error of 2).
In the same setting, a Deep Belief Network (DBN) gives an approximated log likelihood of 138 with a similar standard error.
On the Toronto Face Dataset, which is a much harder problem, GANs can achieve a log likelihood of 2057 ± 26 on selected real examples.
In contrast, the best DBN results are 1909 ± 66.

## Disadvantages
GANs are difficult to optimize.
The two networks have to be kept in sync.
If the discriminator wins by too big a margin, then the generator can’t learn as the discriminator error is too small.
However, if the generator wins by too much, it will have trouble learning because the discriminator is too weak
to teach it.
A degenerate case is when the generator collapses and produces a single example, which is badly classified by
the discriminator.
This is a deep problem, because it shows that in practice the generator doesn’t necessarily converge to the
data distribution.
Solving these problems is a topic of further research, but there already are some new techniques for training GANs
that mitigate these negative effects.
Here are a few:

  - Make the discriminator much less expressive by using a smaller model.
  Generation is a much harder task and requires more parameters, so the generator should be significantly bigger.
  - Use dropout in the discriminator, which makes it less prone to mistakes the generator can exploit instead of learning
  the data distribution.
  - Use adaptive L2 regularization on the discriminator.
  By increasing the L2 regularization coefficient, the discriminator becomes weaker.
  It’s a good idea to do this when the discriminator is very strong and then decrease it again when the generator has
  caught up.

Related work
------------

- [LAPGAN](http://arxiv.org/pdf/1506.05751v1.pdf), generating images using Laplacian pyramid.
- [RCGAN](http://arxiv.org/pdf/1602.05110v2.pdf), generating images as a sum of layers with an RNN.
- [Conditional GANs](https://arxiv.org/pdf/1411.1784v1.pdf), which generate examples conditioned on labels.
- [InfoGAN](https://arxiv.org/pdf/1606.03657v1.pdf), using meaningful input noise instead of just a source of randomness.
- [Improved Techniques for Training GANs](https://arxiv.org/pdf/1606.03498v1.pdf).
- [BiGAN](https://arxiv.org/pdf/1605.09782v1.pdf), with a way to project from the example space back to the latent space.
- [Adversarial autoencoders](http://arxiv.org/pdf/1511.05644v2.pdf), VAE, which uses adversarial loss to compare latent
space of a VAE to some prior distribution.

repository: magenta/magenta

repo_name: magenta/magenta


text:
---
title: "Release 0.18.0"
linkTitle: "Release 0.18.0"
date: 2019-03-29
description: >
  VSCode Extension Release 0.18.0
github_repo: "" # Disable the edit commands
---

### Added

- ([GH-494](https://github.com/lingua-pupuli/puppet-vscode/issues/494)) Add Progress Bar for long lived operations
- ([GH-489](https://github.com/lingua-pupuli/puppet-vscode/issues/489)) Allow users to change puppet version used by editor services in PDK

### Changed

- ([Commit](https://github.com/lingua-pupuli/puppet-vscode/commit/8b2815ad06f7b3f82574c44684387007c5213f5d)) Update puppet-editor-syntax to [1.3.1](https://github.com/lingua-pupuli/puppet-editor-syntax/releases/tag/1.3.1)
- ([GH-489](https://github.com/lingua-pupuli/puppet-vscode/issues/489)) Update puppet-editor-services to [0.19.0](https://github.com/lingua-pupuli/puppet-editor-services/blob/master/CHANGELOG.md#0190---2019-03-24)


text:
# crm_flutter_app

A new Flutter application.

## Getting Started

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

- [Lab: Write your first Flutter app](https://flutter.io/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.io/docs/cookbook)

For help getting started with Flutter, view our
[online documentation](https://flutter.io/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.

## 设计出完整的flutter 项目架构，并实现简单的功能，

## 效果图

![image](https://github.com/alvin198761/flutter_franchisee/blob/master/flutter.gif?raw=true)

## 模拟数据启动
1. 需要安装nodejs
2. 进入mockserver
3. 执行 npm install 安装并等待安装完成
4. npm run mock 启动模拟服务器
5. 修改数据需要重写启动才生效，不过重启很快的


text:
# CustomDiscord

Custom Discord is a Discord Client modification that allows you to inject custom CSS and Javascript right into the discord client.

[![Discord](https://img.shields.io/discord/396365477942657030.svg?style=for-the-badge&label=Discord&logo=discord)](https://discord.gg/MkQ6Cpw)

## Getting Started

**TODO:** _Better_ Instructions

1. Install `npm` or `yarn`.
2. `git clone` the repo.
3. `npm i` or `yarn install` the dependencies.

Currently, you will have to set the file manually.
You need to find your discord installation directory

It should be located here:
Linux `/usr/opt/discord-canary/resources/app`
Windows `%localappdata%\discordcanary\resources\app`
OSX `?`

the `app` directory will most likely not exist so you will have to create it. Inside that directory you will need to put two files

package.json

```json
{
  "name": "customdiscord-loader",
  "version": "0.1.0",
  "description": "Advanced Discord client injection mod",
  "main": "index.js",
  "scripts": {},
  "author": "Nightmare",
  "license": "MIT",
  "dependencies": {},
  "private": true
}
```

index.js

```js
require('/path/to/CustomDiscord/index.js').inject(__dirname);
```

## Credits

Heavily influenced by [Discord Injections v4](https://github.com/DiscordInjections/DiscordInjections/tree/v4)

repository: CustomDiscord/Engine

repo_name: CustomDiscord/Engine


text:
Michael Herman (Toronto) - Yesterday at 9:55 PM
I have to thank again for the discussion Fabian.  Coupled with the long drive home, it was very liberating for me in terms of "seeing the path ahead" for what've embarked on and where it's headed. ...I just arrived back in Toronto.  I'll elaborate on this tomorrow.  Thk u.
March 4, 2018

fabwa - Today at 5:56 AM
Great to hear!

Michael Herman (Toronto) - Today at 7:35 AM
I hope you still feel that way after I explain :smiley:

fabwa - Today at 8:16 AM
Go ahead :smiley:

Michael Herman (Toronto) - Today at 8:34 AM
The first thought that ran through my mind was what to do with the code/content/community I've created for C#.NEO developers?  Easy.  Create an umbrella project:
NEO Blockchain C# Developer Center of Excellence (neo-csharpcoe) https://github.com/mwherman2000/neo-csharpcoe/blob/master/README.md
I was working towards this on CoZ.  In fact, I created an open issue for it: https://github.com/CityOfZion/awesome-neo/issues/64 ...but now that my contributions are neither appreciated nor valued.  I've been completely cut of from even submitting contribution reports as a non-CoZ developer.(edited)
But this is the liberating part ...why worry about a group that does appreciate or value my contributions ...when it is actually easier to build code, content and community on my own.
Which brings me to the second directly connected thought that (perhaps) CoZ should have considered.   Fabio's action to completely 100% remove me from CoZ to the point where I can't submit my weekly contribution report has had the effect of creating two parallel streams of effort in the NEO developer community.  Fabio has triggered a #hardfolk.  A #hardfolk in terms of code, content and community.   This is why I said yesterday (before I fully understood it myself) that it's going to be hard to come back into CoZ at a later date.(edited)
This was my drive home last night in a nutshell.(edited)
CoZ started with one person who had a great vision and mission ...neo-csharpcoe is starting out the same way.

repository: NeoBlockchainTurkey/neo-windocs

repo_name: NeoBlockchainTurkey/neo-windocs


text:
# captain-drone

## Setup

Run in bash:

```bash
mkdir ~/.dav
touch ~/.dav/wallet
```

Open and edit `~/.dav/wallet` and save with following content:

```json
{
  "private": "0x<<YOUR WALLET PRIVATE KEY>>",
  "address": "0x<<YOUR WALLET ADDRESS>>",
  "nodeUrl": "https://<<A NETWORK NODE URL>>",
  "networkType": "<<ropsten/...>>",
  "apiSecret": "<<SOME SECRET PHRASE>>"
}
```

This wallet should have enough balance to perform the necessary transactions.
Then run:

```bash
npm i
npm run gen-n-reg
```

Copy the new DAV Identity Address which is printed if all goes well.

## Ropsten Faucet

```bash
curl -X POST  -H "Content-Type: application/json" -d '{"toWhom":"<<ADDRESS>>"}' https://ropsten.faucet.b9lab.com/tap
```

## Usage

Follow [these instructions](https://github.com/DAVFoundation/missioncontrol) to have a locally running DAVNN cluster using Minikube.
After that you should have a port-forwarding setup for the DAVNN server.
These are required for the captain-drone server to communicate with captain-charger server.

Run:

```bash
npm run start-server
```

In another terminal:

```bash
npm run start-ui
```

## API

### Register

Register a new drone to find a charging mission.
The returned token must be kept for future interactions with the API.

- Method: **POST**
- Path: **/register**
- Body (json):

```json
{
  "address": "" /* Drone DAV ID */,
  "lat": "" /* Search location latitude */,
  "lon": "" /* Search location longitude */
}
```

- Response (text): **drone token**

### Status

Access current status for drone. Use the token returned by `/register` to authenticate.

- Method: **GET**
- Path: **/status**
- Headers:
  - **Authorization: Bearer `[drone token]`**
- Response (text): **Waiting/Moving/Charging/Complete**
  - **Waiting**: Drone is waiting for a charging mission.
  - **Moving**: Drone is committed to a mission and need to arrive at charger.
  - **Charging**: Drone is charging.
  - **Complete**: Drone has completed charging and needs to take-off.

### Bids

Access current list of available bids for drone. Use the token returned by `/register` to authenticate.

- Method: **GET**
- Path: **/bids**
- Headers:
  - **Authorization: Bearer `[drone token]`**
- Response (json):

```json
{
  "status": "",
  "bids": [
    {
      /* BidParams incl. id */
    }
  ]
}
```

### Accept

Accept the specified bid. Use the token returned by `/register` to authenticate.

- Method: **POST**
- Path: **/accept/`[bidId]`**
- Headers:
  - **Authorization: Bearer `[drone token]`**
- Response: **(200 Ok)**

### Arrived

Notify that drone has arrived at charger and is ready for charging. Use the token returned by `/register` to authenticate.

- Method: **POST**
- Path: **/arrived**
- Headers:
  - **Authorization: Bearer `[drone token]`**
- Response: **(200 Ok)**

### Clear

Notify that drone has left the charger. Use the token returned by `/register` to authenticate.

- Method: **POST**
- Path: **/clear**
- Headers:
  - **Authorization: Bearer `[drone token]`**
- Response: **(200 Ok)**

### Example

Register a drone charging need:

```bash
curl -w "\n" -X POST localhost:3001/register -H"Content-Type:application/json" -d'{"address":"0x96De2B9394bA1894A3a717a75536E9e2d0d1Ec22","lat":"32.050382","lon":"34.766149"}'
```

Store returned token into environment:

```bash
export DRONE_TOKEN=<<TOKEN>>
```

Get available bids:

```bash
curl -w "\n" -X GET localhost:3001/bids -H"Authorization: Bearer ${DRONE_TOKEN}"
```

Get drone status:

```bash
curl -w "\n" -X GET localhost:3001/status -H"Authorization: Bearer ${DRONE_TOKEN}"
```

Choose an appropriate bid and copy the bid `id` (E.g. `ca0ab3cc-02c7-40f2-bb0d-d96b07081b89`):

```bash
curl -w "\n" -X POST localhost:3001/accept/<<BID-ID>> -H"Authorization: Bearer ${DRONE_TOKEN}"
```

When status becomes `Moving` and drone arrived at destination:

```bash
curl -w "\n" -X POST localhost:3001/arrived -H"Authorization: Bearer ${DRONE_TOKEN}"
```

When status becomes `Complete` and drone has taken-off / cleared the charger:

```bash
curl -w "\n" -X POST localhost:3001/clear -H"Authorization: Bearer ${DRONE_TOKEN}"
```

repository: DAVFoundation/captain-drone

gha_language: TypeScript

repo_name: DAVFoundation/captain-drone


text:
Python Face Detection
([Pre-requisites](https://github.com/Dotmole/face-detection-algorithms/blob/master/README.md) | [Wiki](https://github.com/Dotmole/face-detection-algorithms/wiki/Python))

1. MTCCN
 - The model is adapted from the Facenet's MTCNN implementation
 - The detector returns a list of JSON objects. Each JSON object contains three main keys: 'box', 'confidence' and 'keypoints'
 - Each of P-Net, R-Net and O-Net implementation can be found as methods of class [NetworkFactory](https://github.com/ipazc/mtcnn/blob/master/mtcnn/network/factory.py)
 ![MTCNN parts](creatives/mtcnndistribution.png)

repository: Dotmole/face-detection-algorithms

gha_language: Jupyter Notebook

repo_name: Dotmole/face-detection-algorithms


text:
# slides

This repository holds my (probably mostly Go) talks. You can view them
using the [Go presentation tool][1]:

```bash
go install golang.org/x/tools/cmd/present
```

```bash
$ present
2020/01/28 09:46:30 Open your web browser and visit http://<IP_ADDRESS>:3999
```

[1]: https://godoc.org/golang.org/x/tools/present

Here, have some quotes:

> "People think that the purpose of memory is to remember the past, and
> that's not the purpose of memory. The purpose of memory is to extract
> out from the past lessons to structure the future."
> -- Jordan B. Peterson

> "Organizations which design systems ... are constrained to produce
> designs which are copies of the communication structures of these
> organizations.”
> -- Melvin Conway

> “Perfection is achieved, not when there is nothing more to add, but
> when there is nothing left to take away.”
> -- Antoine de Saint-Exupery

> "I just think it's a profound mistake in programming language design
> to have your semantics depend on invisible characters."
> -- Rob Pike, GopherCon 2014 Opening Keynote

> "There are people who disagree with that, I respect their opinion and
> I move on."
> -- Rob Pike, GopherCon 2014 Opening Keynote

> "The person who says he knows what he thinks but cannot express it
> usually does not know what he thinks.”
> -- Mortimer Adler

> "He who has a why can bear almost any how."
> -- Friedrich Nietzsche

repository: mrkanister/slides

repo_name: mrkanister/slides


text:
# ReactRailsWebpack

[![Gem Version](https://badge.fury.io/rb/react_rails_webpack.svg)](https://badge.fury.io/rb/react_rails_webpack)

> Warning: If you are upgrading across major versions, please read the [release notes in the changelog](CHANGELOG.md).

Ruby gem for quickly creating highly customizable react/rails integrations using webpack and npm.

## Key Features

1. One-command setup
2. Use any packages from the [npm](https://www.npmjs.com) ecosystem
3. [Built-in examples](#demo-page) of plain and [redux](http://redux.js.org)-backed React components
4. The [webpack](https://webpack.github.io) development server for React components will live update your changes to any device on your local network (including phones) (gif demo of this feature [here](images/rrw_demo_short.gif))

[more features...](FEATURES.md)

## Demo Page

> Generate this page after installation with [the create_example_page command](#set-up-an-example-page-in-your-rails-app)

![Image of main demo page with two example React components on it](images/demo_page.png "Image of main demo page with two example React components on it")

## Install

> Video demo of setup and use on a new Rails app [here](https://vimeo.com/180349372)

1. Make sure you have the [requirements](#requirements) installed
2. Add `gem 'react_rails_webpack'` to your Gemfile
3. Run `bundle install`
4. Run `rails g react_rails_webpack:install` ([further explanation of what this does](#how-does-this-work))

## Requirements

- **[Rails](http://rubyonrails.org/)** version **4 or greater** (check version with `rails -v`)
- **[node](https://nodejs.org)** version **4 or greater** (check version with `node -v`)
- **[npm](https://www.npmjs.com/)** version **3 or greater** (check version with `npm -v`)

## Contents

- **[Key features](#key-features)**
- **[Demo Page](#demo-page)**
- **[Install](#install)**
- **[Requirements](#requirements)**
- **[About](#about)**
  - [Pros](#pros)
  - [Cons](#cons)
- **[See the demo components in action](#see-the-demo-components-in-action)**
  - [On webpack dev server](#on-webpack-dev-server)
  - [On your Rails app](#on-your-rails-app)
- **[Commands](#commands)**
  - [To set up the integration](#set-up-the-integration)
  - [To set up an example page in your Rails app](#set-up-an-example-page-in-your-rails-app)
  - [To configure a new clone of your repo](#configure-react_rails_webpack-on-a-new-clone-of-your-repo)
  - [To see the url of your webpack development server](#see-the-url-of-your-webpack-development-server)
  - [Integrate with Trailblazer](#generate-react-component-trailblazer-cell)
- **[Suggested development workflow](#suggested-development-workflow)**
- **[Creating and using your own components](#creating-and-using-your-own-components)**
- **[How does this work?](#how-does-this-work)**
- **[Gotchas](#gotchas)**
  - [Forgetting to run npm run build](#forgetting-to-run-npm-run-build)
  - [Forgetting to add components to the availableComponents file](#forgetting-to-add-components-to-the-clientsrcappavailablecomponentsjs-file)
  - [Forgetting to run rails g react_rails_webpack:new_fork when cloning your repo on a new machine](#forgetting-to-run-rails-g-react_rails_webpacknew_fork-when-cloning-your-repo-on-a-new-machine)
  - [npm install vs. npm run install](#npm-install-vs-npm-run-install)
- **[Development](#development)**
- **[Contributing](#contributing)**
- **[License](#license)**

## About

When I looked over the available gems for react/rails integrations, none of them were as customizable as I wanted, so I decided to build my own. Since I wanted it to be as customizable as possible, I made my gem a set of generators, instead of a bunch of under-the-hood gem code. You can customize the inner workings of this integration to your heart's content, since all the files used for the integration will be added directly to your app. You can edit them, delete them, and add or remove any npm packages you like, because this integration allows you to use any npm packages you could use in a static front-end react app.

### Pros:

- [Webpack](https://webpack.github.io/) integration
- Hot-reloading webpack development server
- Ability to see dev server output on any computer (or mobile device) on your network
- Built-in [redux](http://redux.js.org/) integration
- Generators provide example code for basic react components and react-redux components
- Highly customizable
- Ability to use any [npm](https://www.npmjs.com/) packages that you could use on a static front-end app

### Cons:

- This gem does not do server-side rendering. I don't find this makes much of a difference for my apps in practice, but if it does for you, best avoid. [This post by Henrik Joreteg](https://blog.andyet.com/2015/05/18/lazymorphic-apps-bringing-back-static-web) covers some of the reasons I like just doing it this way.

## See the demo components in action

### On webpack dev server

1. Run the webpack dev server with `npm run start`
2. Go to the url specified by the `rake react_rails_webpack:print_server_info` command

### On your rails app

1. Generate an example page in rails with the `rails g react_rails_webpack:create_example_page` command
2. Start your Rails server with `rails s`
3.

### Set up an example page in your Rails app

`rails g react_rails_webpack:create_example_page`

Sets up an example page in your Rails app at [localhost:3000/greeting](http://localhost:3000/greeting) that displays the two example components.

### Configure react_rails_webpack on a new clone of your repo

`rails g react_rails_webpack:new_fork`

**You must run this whenever you clone a repo with a react_rails_webpack integration setup**. It generates [the environment.json file](lib/react_rails_webpack/client/environment.json) based on your computer's network name. Since the network name will be different for most computers, this file is gitignored and needs to be regenerated for each new computer the project is cloned on.

### See the url of your webpack development server

`rake react_rails_webpack:print_server_info`

This command will tell you the url of your webpack development server on your local network.

### Generate react component Trailblazer cell

`rails g react_rails_webpack:trailblazer_integration`

If you use [the Trailblazer gem](https://github.com/apotonick/trailblazer), use this command to add a trailblazer cell for react components to your `lib` folder.

## Suggested Development Workflow

1. Write the code for your React components in the [client/src/components](lib/react_rails_webpack/client/src/components) directory
2. Test your new components with live reloading by running the webpack dev server with the command `npm run start` (note: the base html page for the webpack dev server is based on the html provided to `context.defaultTemplate` in [the webpack.config.js file](lib/react_rails_webpack/client/webpack.config.js))
3. Add any components you want to spin up with the `react_component` helper in Rails to [the available components file](lib/react_rails_webpack/client/src/app/availableComponents.js) ([further explanation](#creating-and-using-your-own-components))
4. Run the `npm run build` command to compile your javascript files and add them to the Rails assets folder
5. Add calls to the `react_component` helper method in your Rails app to render your React components in views
6. Make sure they still work, repeat steps 1-5 until satisfied

## Creating and using your own components

Let's say you want to make a checkout form component with react. Here's what you'd need to do to use it from Rails:

- Create the component in the [client/src/components](lib/react_rails_webpack/client/src/components) directory
- Add the component to the list of components in the [client/src/app/availableComponents.js](lib/react_rails_webpack/client/src/app/availableComponents.js) file (this file is what makes components available to Rails)

For example, if you called your component `CheckoutForm`, your `client/src/app/availableComponents.js` file might look like this:

```javascript
import CheckoutForm from '../components/CheckoutForm'

export default {
  CheckoutForm: {
    class: CheckoutForm
  }
}
```

Or like this if it's a component that uses redux:

```javascript
import {CheckoutFormContainer} from '../components/CheckoutForm'

export default {
  CheckoutForm: {
    redux: true,
    class: CheckoutFormContainer
  }
}
```

- Wherever you want this component to render in your view, put a call to the `react_component` helper method with the components name and props, like so:

```ruby
render_component :CheckoutForm, { customerName: 'Harper' }
```

NOTE: Unless you're sure you know what you're doing, do not edit anything in the [client/app](lib/react_rails_webpack/client/src/app) folder except [the availableComponents file](lib/react_rails_webpack/client/src/app/availableComponents.js)). Those files are where the integration works it's magic (though of course feel free to read the files to check out how everything works).

## Working with the Webpack Dev Server

`npm run start` will start a webpack development server with hot reloading that is completely independent of your Rails app. You can see the output of this server on any computer or mobile device on your local network by going to the appropriate url (which you can find by running `rake react_rails_webpack:print_server_info`). Any changes you make to your component files will be pushed immediately to all devices looking at the page.

## How does this work?

When you run the install generator like this:

    $ rails g react_rails_webpack:install

This gem will setup a basic react integration with some example components (one standard react component and one using react with redux) under [a client folder](lib/react_rails_webpack/client) in your project's root.

The meat of the integration with Rails is in [the client/app folder](lib/react_rails_webpack/client/src/app), and [the app.js file](lib/react_rails_webpack/client/src/app.js). When your page loads in Rails, if you call the `react_component` method like this:

```ruby
react_component :ComponentName, {myProp: 'some value'}
```

It will create a div that looks like this:

```html
<div class="react-component-target" data-componentname="ComponentName" data-componentprops="{myProp: 'some value'}">
  <script>renderLastComponentDiv()</script>
</div>
```

When your browser hits that `renderLastComponentDiv()` call, it grabs the component name (which is `ComponentName` in this example) from the parent div, then looks it up in [the availableComponents.js file](lib/react_rails_webpack/client/src/app/availableComponents.js).

In our example, your available components file might look like this:

```javascript
import MyComponent from '../components/MyComponent'
import SomeOtherComponent from '../components/SomeOtherComponent'

export default {
  ComponentName: {
    class: MyComponent
  },
  OtherName: {
    class: SomeOtherComponent
  }
}
```

If it looked like that, you would render your `MyComponent` React component with `react_component :ComponentName`, and you would render your `SomeOtherComponent` React component with `react_component :OtherName`. Using `react_component :MyComponent` would NOT work. The `react_component` method is looking for the javascript object keys from [availableComponents.js](lib/react_rails_webpack/client/src/app/availableComponents.js) (e.g. `ComponentName`, `OtherName` ), NOT the actual component class names (e.g. `MyComponent`, `SomeOtherComponent`). It's usually fine to make the object key the same as the class name, though. They're just different in this example for clarity.

Assuming `react_component` finds a key in [availableComponents.js](lib/react_rails_webpack/client/src/app/availableComponents.js) that matches the name it's given, it will immediately render that component within that div, passing in props from the `data-componentprops` attribute. As the page loads, each successive div generated by `react_component` renders this way.

## Gotchas

### Forgetting to run `npm run build`

Remember, while your changes to components will hot reload when you use the webpack dev server, they will not show up at all in your Rails app until you run the `npm run build` command. And they do NOT hot-reload when run in the context of your Rails app.

### Forgetting to add components to the [client/src/app/availableComponents.js](lib/react_rails_webpack/client/src/app/availableComponents.js) file

Components will not be accessible from Rails if you forget to add them here.

### Forgetting to run `rails g react_rails_webpack:new_fork` when cloning your repo on a new machine

`rails g react_rails_webpack:new_fork` sets up [the environment.json file](lib/react_rails_webpack/client/environment.json), which is NOT included in your repo, because it contains information specific to each computer it is generated on.

### npm install vs. npm run install

Usually to install new npm packages, you run the `npm install` command. This will work fine if you do it from the client folder, but it won't work from your project's root, since your package.json file with your project's requirements is in the client folder and not the project's root. However, as a convenience, the project's root has the command `npm run install` which is essentially the same as hopping in and out of the client folder to run `npm install` (it's basically like running `cd client && npm install && cd ..`).

More succinctly: if you're in your project's root folder, use `npm run install` instead of `npm install` to install any new npm package dependencies you've added to the `client/package.json` file.

## Development

After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/neurodynamic/react_rails_webpack. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

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