text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2011-2020 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime.util;

import android.content.Context;
import android.util.Base64;
import android.util.Log;

import com.google.appinventor.components.runtime.Form;
import com.google.appinventor.components.runtime.errors.YailRuntimeError;

import gnu.lists.FString;

import gnu.math.IntFraction;

import java.io.File;
import java.io.FileOutputStream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Provides utility functions to convert between Java object and JSON.
 *
 *
 */
public class JsonUtil {

  private static final String BINFILE_DIR = "/AppInventorBinaries";
  private static final String LOG_TAG = "JsonUtil";

  /**
   * Prevent instantiation.
   */
  private JsonUtil() {
  }

  /**
   * Returns a list of String objects from a JSONArray. This
   * does not do any kind of recursive unpacking of the array.
   * Thus, if the array includes other JSON arrays or JSON objects
   * their string representation will be a single item in the
   * returned list.
   *
   * @param jArray The JSONArray to convert.
   * @return A List of the String representation of each item in
   * the JSON array.
   * @throws JSONException if an element of jArray cannot be
   * converted to a String.
   */
  public static List<String> getStringListFromJsonArray(JSONArray jArray) throws JSONException {
    List<String> returnList = new ArrayList<String>();
    for (int i = 0; i < jArray.length(); i++) {
      String val = jArray.getString(i);
      returnList.add(val);
    }
    return returnList;
  }

  @Deprecated
  public static List<Object> getListFromJsonArray(JSONArray jsonArray) throws JSONException {
    return getListFromJsonArray(jsonArray, false);
  }

  /**
   * Returns a Java Object list of a JSONArray with each item in
   * the array converted using convertJsonItem().
   *
   * @param jsonArray The JSONArray to convert.
   * @return A List of Strings and more Object lists.
   * @throws JSONException if an element in jsonArray cannot be
   * converted properly.
   */
  public static List<Object> getListFromJsonArray(JSONArray jsonArray, boolean useDicts)
      throws JSONException {
    List<Object> returnList = new ArrayList<Object>();
    for (int i = 0; i < jsonArray.length(); i++) {
      returnList.add(convertJsonItem(jsonArray.get(i), useDicts));
    }
    return returnList;
  }

  /**
   * Returns a list containing one two item list per key in jObject.
   * Each two item list has the key String as its first element and
   * the result of calling convertJsonItem() on its value as the
   * second element. The sub-lists in the returned list will appear
   * in alphabetical order by key.
   *
   * @param jObject The JSONObject to convert.
   * @return A list of two item lists: [String key, Object value].
   * @throws JSONException if an element in jObject cannot be
   * converted properly.
   */
  // TODO(hal): If we implement dictionaries, we'll need to decode Json
  // objects to dictionaires instead.
  public static List<Object> getListFromJsonObject(JSONObject jObject) throws JSONException {
    List<Object> returnList = new ArrayList<Object>();
    Iterator<String> keys = jObject.keys();

    List<String> keysList = new ArrayList<String>();
    while (keys.hasNext()) {
      keysList.add(keys.next());
    }
    Collections.sort(keysList);

    for (String key : keysList) {
      List<Object> nestedList = new ArrayList<Object>();
      nestedList.add(key);
      nestedList.add(convertJsonItem(jObject.get(key), false));
      returnList.add(nestedList);
    }

    return returnList;
  }

  /**
   * Returns a list containing one two item list per key in jsonObject.
   * Each two item list has the key String as its first element and
   * the result of calling convertJsonItem() on its value as the
   * second element. The sub-lists in the returned list will appear
   * in alphabetical order by key.
   *
   * @param jsonObject The JSONObject to convert.
   * @return A dictionary mapping the JSON keys to processed JSON values
   * @throws JSONException if an element in jsonObject cannot be
   *     converted properly.
   */
  public static YailDictionary getDictionaryFromJsonObject(JSONObject jsonObject)
      throws JSONException {
    YailDictionary result = new YailDictionary();

    // Step 1. Sort the keys
    TreeSet<String> keys = new TreeSet<String>();
    Iterator<String> it = jsonObject.keys();
    while (it.hasNext()) {
      keys.add(it.next());
    }

    // Step 2. Populate the dictionary
    for (String key : keys) {
      result.put(key, convertJsonItem(jsonObject.get(key), true));
    }

    return result;
  }

  /**
   * Returns a Java object representation of objects that are
   * encountered inside of JSON created using the org.json package.
   * JSON arrays and objects are transformed into their list
   * representations using getListFromJsonArray and
   * getListFromJsonObject respectively.
   *
   * Java Boolean values and the Strings "true" and "false" (case
   * insensitive) are inserted as Booleans. Java Numbers are
   * inserted without modification and all other values are inserted
   * as their toString(). value.
   *
   * This method is deprecated. Extension developers should migrate
   * their code to use {@link #getObjectFromJson(String, boolean)}
   * to get better performance using YailDictionary.
   *
   * @param o An item in a JSON array or JSON object to convert.
   * @return A Java Object representing o or the String "null"
   * if o is null.
   * @throws JSONException if o fails to parse.
   */
  @Deprecated
  public static Object convertJsonItem(Object o) throws JSONException {
    return convertJsonItem(o, false);
  }

  /**
   * Returns a Java object representation of objects that are
   * encountered inside of JSON created using the org.json package.
   * JSON arrays and objects are transformed into their list
   * representations using getListFromJsonArray and
   * getListFromJsonObject respectively.
   *
   * Java Boolean values and the Strings "true" and "false" (case
   * insensitive) are inserted as Booleans. Java Numbers are
   * inserted without modification and all other values are inserted
   * as their toString(). value.
   *
   * @param o An item in a JSON array or JSON object to convert.
   * @param useDicts true if YailDictionary should be used to represent JSON objects,
   *     false if associative lists should be used
   * @return A Java Object representing o or the String "null"
   *     if o is null.
   * @throws JSONException if o fails to parse.
   */
  public static Object convertJsonItem(Object o, boolean useDicts) throws JSONException {
    if (o == null) {
      return "null";
    }

    if (o instanceof JSONObject) {
      if (useDicts) {
        return getDictionaryFromJsonObject((JSONObject) o);
      } else {
        return getListFromJsonObject((JSONObject) o);
      }
    }

    if (o instanceof JSONArray) {
      List<Object> array = getListFromJsonArray((JSONArray) o, useDicts);
      if (useDicts) {
        return YailList.makeList(array);
      } else  {
        return array;
      }
    }

    if (o.equals(Boolean.FALSE) || (o instanceof String &&
        ((String) o).equalsIgnoreCase("false"))) {
      return false;
    }

    if (o.equals(Boolean.TRUE) || (o instanceof String && ((String) o).equalsIgnoreCase("true"))) {
      return true;
    }

    if (o instanceof Number) {
      return o;
    }

    return o.toString();
  }

  public static String getJsonRepresentation(Object value) throws JSONException {
    if (value == null || value.equals(null)) {
      return "null";
    }
    if (value instanceof FString) {
      return JSONObject.quote(value.toString());
    }
    if (value instanceof YailList) {
      return ((YailList) value).toJSONString();
    }
    // The Json tokener used in getObjectFromJson cannot handle
    // fractions.  So we Json encode fractions by first converting
    // them to doubles. This is an example of value with Kawa type any
    // being exposed to the rest of App Inventor by the value being
    // passed to a component method, in this case TinyDB or TinyWebDB
    // StoreValue.  See the "warning" comment in runtime.scm at
    // call-component-method.
    if (value instanceof IntFraction) {
      return JSONObject.numberToString((Number) ((IntFraction)value).doubleValue());
    }
    if (value instanceof Number) {
      return JSONObject.numberToString((Number) value);
    }
    if (value instanceof Boolean) {
      return value.toString();
    }
    if (value instanceof List) {
      value = ((List)value).toArray();
    }
    if (value instanceof YailDictionary) {
      StringBuilder sb = new StringBuilder();
      YailDictionary dict = (YailDictionary) value;
      String sep = "";
      sb.append('{');
      for (Entry<Object, Object> entry : (Set<Entry<Object, Object>>) dict.entrySet()) {
        sb.append(sep);
        sb.append(JSONObject.quote(entry.getKey().toString()));
        sb.append(':');
        sb.append(getJsonRepresentation(entry.getValue()));
        sep = ",";
      }
      sb.append('}');
      return sb.toString();
    }
    if (value.getClass().isArray()) {
      StringBuilder sb = new StringBuilder();
      sb.append("[");
      String separator = "";
      for (Object o: (Object[]) value) {
        sb.append(separator).append(getJsonRepresentation(o));
        separator = ",";
      }
      sb.append("]");
      return sb.toString();
    }
    return JSONObject.quote(value.toString());
  }

  /**
   * Parses the JSON content represented by {@code jsonString} into a YAIL object.
   *
   * This version uses associative lists for representing JSON objects. It is recommended that
   * developers migrate to using {@link #getObjectFromJson(String, boolean)} and make use of
   * dictionaries for better performance.
   *
   * @see #getObjectFromJson(String, boolean)
   * @param jsonString the JSON text to parse
   * @return the parsed object
   * @throws JSONException if the JSON is malformed
   */
  @Deprecated
  public static Object getObjectFromJson(String jsonString) throws JSONException {
    return getObjectFromJson(jsonString, false);
  }

  /**
   * Parses the JSON content represented by {@code jsonString} into a YAIL object. The
   * {@code useDicts} flag controls whether JSON objects are parsed as YailDictionary (true) or
   * associative YailList (false).
   *
   * @param jsonString the JSON text to parse
   * @param useDicts true if YailDictionary should be used for JSON objects,
   *                 false for associative lists
   * @return the parsed object
   * @throws JSONException if the JSON is malformed
   */
  public static Object getObjectFromJson(String jsonString, boolean useDicts) throws JSONException {
    if ((jsonString == null) || jsonString.equals("")) {
      // We'd like the empty string to decode to the empty string.  Form.java
      // relies on this for the case where there's an activity result with no intent data.
      // We handle this case explicitly since nextValue() appears to throw an error
      // when given the empty string.
      return "";
    } else {
      final Object value = (new JSONTokener(jsonString)).nextValue();
      // Note that the JSONTokener may return a value equals() to null.
      if (value == null || value.equals(JSONObject.NULL)) {
        return null;
      } else if ((value instanceof String) ||
          (value instanceof Number) ||
          (value instanceof Boolean)) {
        return value;
      } else if (value instanceof JSONArray) {
        return getListFromJsonArray((JSONArray)value, useDicts);
      } else if (value instanceof JSONObject) {
        if (useDicts) {
          return getDictionaryFromJsonObject((JSONObject) value);
        } else {
          return getListFromJsonObject((JSONObject) value);
        }
      }
      throw new JSONException("Invalid JSON string.");
    }
  }

  /**
   * This method converts a file path to a JSON representation.
   * The code in the method was part of GetValue. For better modularity and reusability
   * the logic is now part of this method, which can be invoked from wherever and
   * whenever required.
   *
   * <p>
   * This function is deprecated. Developers should use
   * {@link #getJsonRepresentationIfValueFileName(Context, Object)} instead.
   * </p>
   *
   * @param value value to be serialized into JSON
   * @return JSON representation
   */
  @Deprecated
  public static String getJsonRepresentationIfValueFileName(Object value) {
    Log.w(LOG_TAG, "Calling deprecated function getJsonRepresentationIfValueFileName",
        new IllegalAccessException());
    return getJsonRepresentationIfValueFileName(Form.getActiveForm(), value);
  }

  /**
   * Written by joymitro@gmail.com (Joydeep Mitra)
   * This method converts a file path to a JSON representation.
   * The code in the method was part of GetValue. For better modularity and reusability
   * the logic is now part of this method, which can be invoked from wherever and
   * whenever required.
   *
   * 07/06/2018 (jis): Currently this routine is called by the CloudDB component
   *                   When called from GetValue, it is handed a String (the raw
   *                   data from Jedis) to parse. When called from the
   *                   CloudDBJedisListener it is handed an input that has
   *                   already been converted into a List (because the
   *                   CloudDBJedisListener is processing a list of changes,
   *                   not just one. Rather then having two versions of
   *                   this function, we just do the initial JSON parsing
   *                   if we are handed a string.
   *
   * @param context the Android context to use for placing files, if needed.
   * @param value value to be serialized into JSON
   * @return JSON representation
   */
  public static String getJsonRepresentationIfValueFileName(Context context, Object value) {
    try {
      List<String> valueList;
      if (value instanceof String) {
        JSONArray valueJsonList = new JSONArray((String)value);
        valueList = getStringListFromJsonArray(valueJsonList);
      } else if (value instanceof List) {
        valueList = (List<String>) value;
      } else {
        throw new YailRuntimeError("getJsonRepresentationIfValueFileName called on unknown type",
          value.getClass().getName());
      }
      if (valueList.size() == 2) {
        if (valueList.get(0).startsWith(".")) {
          String filename = writeFile(context, valueList.get(1), valueList.get(0).substring(1));
          System.out.println("Filename Written: " + filename);
          filename = filename.replace("file:/", "file:///");
          return getJsonRepresentation(filename);
        } else {
          return null;
        }
      } else {
        return null;
      }
    } catch(JSONException e) {
      Log.e(LOG_TAG, "JSONException", e);
      return null;
    }
  }

  /**
   * Accepts a base64 encoded string and a file extension (which must be three characters).
   * Decodes the string into a binary and saves it to a file on external storage and returns
   * the filename assigned.
   *
   * Written by Jeff Schiller (jis) for the BinFile Extension
   *
   * @param context The Android context to use for placing the file in the file system
   * @param input Base64 input string
   * @param fileExtension three character file extension
   * @return the name of the created file
   */
  private static String writeFile(Context context, String input, String fileExtension) {
    FileOutputStream outStream = null;
    try {
      if (fileExtension.length() != 3 && fileExtension.length() != 4) {
        throw new YailRuntimeError("File Extension must be three or four characters", "Write Error");
      }
      byte [] content = Base64.decode(input, Base64.DEFAULT);
      String fullDirName = QUtil.getExternalStoragePath(context) + BINFILE_DIR;
      File destDirectory = new File(fullDirName);
      destDirectory.mkdirs();
      File dest = File.createTempFile("BinFile", "." + fileExtension, destDirectory);
      outStream = new FileOutputStream(dest);
      outStream.write(content);
      String retval = dest.toURI().toASCIIString();
      trimDirectory(20, destDirectory);
      return retval;
    } catch (Exception e) {
      throw new YailRuntimeError(e.getMessage(), "Write");
    } finally {
      IOUtils.closeQuietly(LOG_TAG, outStream);
    }
  }

  // keep only the last N files, where N = maxSavedFiles
  // Written by Jeff Schiller (jis) for the BinFile Extension
  private static void trimDirectory(int maxSavedFiles, File directory) {

    File [] files = directory.listFiles();

    Arrays.sort(files, new Comparator<File>(){
      public int compare(File f1, File f2)
      {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
      } });

    int excess = files.length - maxSavedFiles;
    for (int i = 0; i < excess; i++) {
      files[i].delete();
    }
  }

  /**
   * Encodes the given JSON object to a JSON string
   *
   * @param jsonObject the JSON object to encode
   * @return the encoded string
   * @throws IllegalArgumentException if the JSON object can't be encoded
   */
  public static String encodeJsonObject(Object jsonObject) throws IllegalArgumentException {
    try {
      return getJsonRepresentation(jsonObject);
    } catch (JSONException e) {
      throw new IllegalArgumentException("jsonObject is not a legal JSON object");
    }
  }
}


text:
<?php

namespace BetterReflectionTest;

class TestListener extends \PHPUnit_Framework_BaseTestListener
{
    /**
     * @var \PHPUnit_Framework_TestSuite|null
     */
    private $currentSuite;

    /**
     * Determine the "full" test name (including the suite name if it is set)
     *
     * @param \PHPUnit_Framework_TestCase $test
     * @return string
     */
    private function getCurrentTestName(\PHPUnit_Framework_TestCase $test)
    {
        if (null === $this->currentSuite) {
            return $test->getName(true);
        }
        return $this->currentSuite->getName() . '::' . $test->getName(true);
    }

    /**
     * Create an additional assertion to ensure the specified class is not
     * loaded when executing a test
     *
     * @param string $className
     * @param \PHPUnit_Framework_TestCase $test
     */
    private function assertClassNotLoaded($className, \PHPUnit_Framework_TestCase $test)
    {
        $test->assertFalse(
            class_exists($className, false),
            'Class ' . $className . ' was loaded during test ' . $this->getCurrentTestName($test)
        );
    }

    /**
     * Ensure the fixture classes have not actually been loaded (where applicable)
     *
     * @param \PHPUnit_Framework_Test $test
     * @param float $time
     */
    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        // Only test PHPUnit tests (i.e. no .phpt tests or anything else unexpected)
        if (!($test instanceof \PHPUnit_Framework_TestCase)) {
            return;
        }

        $this->assertClassNotLoaded(\BetterReflectionTest\Fixture\ExampleClass::class, $test);
        $this->assertClassNotLoaded(\BetterReflectionTest\FixtureOther\AnotherClass::class, $test);
        $this->assertClassNotLoaded(\ClassWithExplicitGlobalNamespace::class, $test);
        $this->assertClassNotLoaded(\ClassWithNoNamespace::class, $test);
        $this->assertClassNotLoaded(\BetterReflectionTest\Fixture\Methods::class, $test);
    }

    /**
     * Simply record the "current" test suite being run
     * Used by getCurrentTestName().
     *
     * @param \PHPUnit_Framework_TestSuite $suite
     */
    public function startTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        $this->currentSuite = $suite;
    }

    /**
     * Unset the "current" test suite being run at the end.
     * Used by getCurrentTestName().
     *
     * @param \PHPUnit_Framework_TestSuite $suite
     */
    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        $this->currentSuite = null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package sparqles.paper.objects;

import java.util.Date;

public class AvailJson {
	private boolean isAvailable = false;
	private EndpointResult endpointResult;

	public AvailJson(){}

	public boolean isAvailable() {
		return isAvailable;
	}
	public void setAvailable(boolean isAvailable) {
		this.isAvailable = isAvailable;
	}
	public EndpointResult getEndpointResult() {
		return endpointResult;
	}
	public void setEndpointResult(EndpointResult endpointResult) {
		this.endpointResult = endpointResult;
	}

	public String getSPARQLURI(){
		if(endpointResult!=null&& endpointResult.getEndpoint()!=null)return endpointResult.getEndpoint().getUri();
		return null;
	}

	public Date getStartDate(){
		if(endpointResult!=null)return new Date(endpointResult.getStart());
		return null;
	}
	public Date getEndDate(){
		if(endpointResult!=null)return new Date(endpointResult.getEnd());
		return null;
	}

	public class EndpointResult{
		private long start;
		private long end;
		private Endpoint endpoint;

		public long getStart() {
			return start;
		}

		public void setStart(long start) {
			this.start = start;
		}

		public long getEnd() {
			return end;
		}

		public void setEnd(long end) {
			this.end = end;
		}

		public Endpoint getEndpoint() {
			return endpoint;
		}

		public void setEndpoint(Endpoint endpoint) {
			this.endpoint = endpoint;
		}

		public EndpointResult(){}
	}

	public class Endpoint{
		private String uri;

		public Endpoint(){}

		public String getUri() {
			return uri;
		}

		public void setUri(String uri) {
			this.uri = uri;
		}
	}
}


text:
*sas_orchestration.py* module
=============================

Contains classes relevant to Service Adaptation Sublayer functionality.

Classes of the module:

.. inheritance-diagram::
   escape.service.sas_orchestration
   :parts: 1

Module contents
---------------

.. automodule:: escape.service.sas_orchestration
   :members:
   :private-members:
   :special-members:
   :exclude-members: __dict__,__weakref__,__module__
   :undoc-members:
   :show-inheritance:


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';

import todoApp from './reducers/reducers';
import App from './components/App';

let store = createStore(todoApp);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);


text:
package com.idugalic.apigateway.services.reviews;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Review {
	private String productId;
	private String userName;
	private String name;
	private String review;
	private int rating;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getReview() {
		return review;
	}

	public void setReview(String review) {
		this.review = review;
	}

	public int getRating() {
		return rating;
	}

	public void setRating(int rating) {
		this.rating = rating;
	}
}


text:
/*global require */
var $ = require('jquery');
var _ = require('underscore');
var ScribbleMenu = require('./scribbler-menu.js');
var ScribbleEditor = require('./scribbler-editor.js');

$(document).ready(function () {
    var editor = new ScribbleEditor(),
        menu = new ScribbleMenu();
    editor.bind("open", menu.close, menu);
    editor.render();
    menu.render();
});


text:
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace ProApiLibrary.Data.Entities
{
	/// <summary>
	/// The data class encapsulating <seealso cref="IEntity"/> IDs.
	/// </summary>
	/// <remarks>
	/// In addition to being used as an opaque ID, this class
	/// presents methods for extracting metadata about the ID.
	///
	/// <seealso cref="IEntity"/>
	/// </remarks>
	[DataContract]
	public class EntityId
	{
		public enum EntityType
		{
			Person,
			Business,
			Location,
			Phone,
		}

		public EntityId(EntityType type, Guid guid, Durability durability)
		{
			this.Type = type;
			this.Guid = guid;
			this.Durability = durability;
		}

		[DataMember(Name = "key")]
		public string Key { get; set; }

		[DataMember(Name = "type")]
		public EntityType Type { get; set; }

		[DataMember(Name = "uuid")]
		public Guid Guid { get; set; }

		[DataMember(Name = "durability")]
		public Durability Durability { get; set; }

		public static EntityId FromString(string key)
		{
			var pieces = key.Split(new[] { '.' });
			if (pieces.Length != 3)
			{
				throw new ArgumentException(@"EntityId string expected to be in format ""<type>.<uuid>.<durability>""");
			}
			var entityType = (EntityType)Enum.Parse(typeof(EntityType), pieces[0], true);
			var guid = new Guid(pieces[1]);
			var durability = (Durability)Enum.Parse(typeof(Durability), pieces[2], true);

			return new EntityId(entityType, guid, durability)
				{
					Key = key
				};
		}

		public bool Equals(EntityId id)
		{
			if (this == id)
			{
				return true;
			}
			if ((id == null) || this.GetType() != id.GetType())
			{
				return false;
			}

			if ((this.Type != id.Type) || (this.Guid != id.Guid))
			{
				return false;
			}

			return true;

		}

		public override int GetHashCode()
		{
			var result = this.Type.GetHashCode();
			result = 31 * result + this.Guid.GetHashCode();
			return result;
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}

			var other = obj as EntityId;
			if (other == null)
			{
				return false;
			}

			return (other.Type == this.Type && other.Guid == this.Guid);
		}

		public static bool operator ==(EntityId a, EntityId b)
		{
			if (ReferenceEquals(a, b))
			{
				return true;
			}

			if (((object)a == null) || ((object)b == null))
			{
				return false;
			}

			return a.Type == b.Type && a.Guid == b.Guid;
		}

		public static bool operator !=(EntityId a, EntityId b)
		{
			if (ReferenceEquals(a, b))
			{
				return false;
			}
			if (((object)a == null) || ((object)b == null))
			{
				return true;
			}

			return a.Type != b.Type || a.Guid != b.Guid;
		}

		public override string ToString()
		{
			return String.Format("{0}.{1}.{2}", this.Type, this.Guid, this.Durability);
		}

		public bool IsPerson
		{
			get { return this.Key.StartsWith("Person"); }
		}

		public bool IsBusiness
		{
			get { return this.Key.StartsWith("Business"); }
		}

		public bool IsLocation
		{
			get { return this.Key.StartsWith("Location"); }
		}

		public bool IsPhone
		{
			get { return this.Key.StartsWith("Phone"); }
		}
	}
}


text:
package RC.Framework.Network;

import RC.Framework.Extension.System.Marshal.BitConverter;
import RC.Framework.Extension.System.Int16;
import RC.Framework.RException.ArgumentOutOfRangeException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ArchBoxWriter extends ArchBox implements IArchBoxWriter
{
	protected ArchBoxWriter() throws IOException
	{
		super();
	}
	@Override
	public byte[] GetAll()
	{
		return Writer.toByteArray();
	}
	@Override
	public void wString(String value) throws ArgumentOutOfRangeException
	{
		if (value.length() > Int16.toShort(Int16.MaxValue) - 1)
			throw new ArgumentOutOfRangeException("Length > short.MaxValue");
		byte[] byteArray = value.getBytes(StandardCharsets.UTF_8);
		this.wShort((short) byteArray.length);
		Writer.write(byteArray, 0, byteArray.length);
	}
	@Override
	public void wShort(short value)
	{
		byte[] byteArray = BitConverter.getBytes(value);
		Writer.write(byteArray, 0, byteArray.length);
	}
	@Override
	public void wFloat(float value)
	{
		byte[] byteArray = BitConverter.getBytes(value);
		Writer.write(byteArray, 0, byteArray.length);
	}
	@Override
	public void wLong(long value)
	{
		byte[] byteArray = BitConverter.getBytes(value);
		Writer.write(byteArray, 0, byteArray.length);
	}
	@Override
	public void wInt(int value)
	{
		byte[] byteArray = BitConverter.getBytes(value);
		Writer.write(byteArray, 0, byteArray.length);
	}
	@Override
	public void wBool(boolean value)
	{
		byte[] byteArray = BitConverter.getBytes(value);
		Writer.write(byteArray, 0, byteArray.length);
	}
}


text:
Manage Contributions and Interests. Based on Firebase.

## Development

### Installation

Make sure you have the following commands installed:

```sh
brew install node
```

After cloning the repository, install all dependencies:

```sh
npm install
```

### Develop

Run the following command to start the server on localhost:

```sh
npm start
```

### Deploy

To build the application, run the following command:

```sh
npm run build
```


text:
var Prism = require('Prism');
var React = require('React');
var Site = require('Site');

var index = React.createClass({
  render: function() {
    return (
      <Site>

React Native

              A framework for building native apps using React

            React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and
            {' '}React{'. '}
            The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere.
            Facebook uses React Native in multiple production apps and will continue investing in React Native.

            Get started with React Native

Native Components

            With React Native, you can use the standard platform components such as UITabBar on iOS and Drawer on Android.  This gives your app a consistent look and feel with the rest of the platform ecosystem, and keeps the quality bar high.  These components are easily incorporated into your app using their React component counterparts, such as TabBarIOS and DrawerLayoutAndroid.

          <Prism>
{`// iOS

var React = require('react-native');
var { TabBarIOS, NavigatorIOS } = React;

var App = React.createClass({
  render: function() {
    return (
      <TabBarIOS>
        <TabBarIOS.Item title="React Native" selected={true}>
          <NavigatorIOS initialRoute={{ title: 'React Native' }} />
        </TabBarIOS.Item>
      </TabBarIOS>
    );
  },
});`}
          </Prism>

<Prism>
{`// Android

var React = require('react-native');
var { DrawerLayoutAndroid, ProgressBarAndroid } = React;

var App = React.createClass({
  render: function() {
    return (
      <DrawerLayoutAndroid
        renderNavigationView={() => <Text>React Native</Text>}>
        <ProgressBarAndroid />
      </DrawerLayoutAndroid>
    );
  },
});`}
          </Prism>

Asynchronous Execution

            All operations between the JavaScript application code and the native platform are performed asynchronously, and the native modules can also make use of additional threads as well.  This means we can decode images off of the main thread, save to disk in the background, measure text and compute layouts without blocking the UI, and more.  As a result, React Native apps are naturally fluid and responsive.  The communication is also fully serializable, which allows us to leverage Chrome Developer Tools to debug the JavaScript while running the complete app, either in the simulator or on a physical device.

            See Debugging.

Touch Handling

            React Native implements a powerful system to negotiate touches in complex view hierarchies and provides high level components such as TouchableHighlight that integrate properly with scroll views and other elements without any additional configuration.

          <Prism>
{`// iOS & Android

var React = require('react-native');
var { ScrollView, TouchableHighlight, Text } = React;

var TouchDemo = React.createClass({
  render: function() {
    return (
      <ScrollView>
        <TouchableHighlight onPress={() => console.log('pressed')}>
          <Text>Proper Touch Handling</Text>
        </TouchableHighlight>
      </ScrollView>
    );
  },
});`}
          </Prism>

Flexbox and Styling

            Laying out views should be easy, which is why we brought the flexbox layout model from the web to React Native.  Flexbox makes it simple to build the most common UI layouts, such as stacked and nested boxes with margin and padding.  React Native also supports common web styles, such as fontWeight, and the StyleSheet abstraction provides an optimized mechanism to declare all your styles and layout right along with the components that use them and apply them inline.

          <Prism>
{`// iOS & Android

var React = require('react-native');
var { Image, StyleSheet, Text, View } = React;

var ReactNative = React.createClass({
  render: function() {
    return (
      <View style={styles.row}>
        <Image
          source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
          style={styles.image}
        />
        <View style={styles.text}>
          <Text style={styles.title}>
            React Native
          </Text>
          <Text style={styles.subtitle}>
            Build high quality mobile apps using React
          </Text>
        </View>
      </View>
    );
  },
});
var styles = StyleSheet.create({
  row: { flexDirection: 'row', margin: 40 },
  image: { width: 40, height: 40, marginRight: 10 },
  text: { flex: 1, justifyContent: 'center'},
  title: { fontSize: 11, fontWeight: 'bold' },
  subtitle: { fontSize: 10 },
});`}
          </Prism>

Polyfills

            React Native is focused on changing the way view code is written.  For the rest, we look to the web for universal standards and polyfill those APIs where appropriate. You can use npm to install JavaScript libraries that work on top of the functionality baked into React Native, such as XMLHttpRequest, window.requestAnimationFrame, and navigator.geolocation.  We are working on expanding the available APIs, and are excited for the Open Source community to contribute as well.

          <Prism>
{`// iOS (Android support for geolocation coming)

var React = require('react-native');
var { Text } = React;

var GeoInfo = React.createClass({
  getInitialState: function() {
    return { position: 'unknown' };
  },
  componentDidMount: function() {
    navigator.geolocation.getCurrentPosition(
      (position) => this.setState({position}),
      (error) => console.error(error)
    );
  },
  render: function() {
    return (
      <Text>
        Position: {JSON.stringify(this.state.position)}
      </Text>
    );
  },
});`}
          </Prism>

Extensibility

            It is certainly possible to create a great app using React Native without writing a single line of native code, but React Native is also designed to be easily extended with custom native views and modules - that means you can reuse anything you{"'"}ve already built, and can import and use your favorite native libraries.

Creating iOS modules

            To create a simple iOS module, create a new class that implements the RCTBridgeModule protocol, and wrap the function that you want to make available to JavaScript in RCT_EXPORT_METHOD. Additionally, the class itself must be explicitly exported with RCT_EXPORT_MODULE();.

          <Prism>
{`// Objective-C

#import "RCTBridgeModule.h"

@interface MyCustomModule : NSObject <RCTBridgeModule>
@end

@implementation MyCustomModule

RCT_EXPORT_MODULE();

// Available as NativeModules.MyCustomModule.processString
RCT_EXPORT_METHOD(processString:(NSString *)input callback:(RCTResponseSenderBlock)callback)
{
  callback(@[[input stringByReplacingOccurrencesOfString:@"Goodbye" withString:@"Hello"]]);
}
@end`}
          </Prism>
          <Prism>
{`// JavaScript

var React = require('react-native');
var { NativeModules, Text } = React;

var Message = React.createClass({
  getInitialState() {
    return { text: 'Goodbye World.' };
  },
  componentDidMount() {
    NativeModules.MyCustomModule.processString(this.state.text, (text) => {
      this.setState({text});
    });
  },
  render: function() {
    return (
      <Text>{this.state.text}</Text>
    );
  }
});`}
          </Prism>

Creating iOS views

            Custom iOS views can be exposed by subclassing RCTViewManager, implementing a -(UIView *)view method, and exporting properties with the RCT_EXPORT_VIEW_PROPERTY macro.  Then a simple JavaScript file connects the dots.

          <Prism>
{`// Objective-C

#import "RCTViewManager.h"

@interface MyCustomViewManager : RCTViewManager
@end

@implementation MyCustomViewManager

RCT_EXPORT_MODULE()

- (UIView *)view
{
  return [[MyCustomView alloc] init];
}

RCT_EXPORT_VIEW_PROPERTY(myCustomProperty, NSString);
@end`}
          </Prism>
          <Prism>
{`// JavaScript

var React = require('react-native');
var { requireNativeComponent } = React;

class MyCustomView extends React.Component {
  render() {
    return <NativeMyCustomView {...this.props} />;
  }
}
MyCustomView.propTypes = {
  myCustomProperty: React.PropTypes.oneOf(['a', 'b']),
};

var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView);
module.exports = MyCustomView;`}
          </Prism>

Creating Android modules

            Likewise, Android also supports custom extensions, the methods are just slightly different.

            To create a simple module in Android, create a new class that extends the ReactContextBaseJavaModule class, and annotate the function that you want to make available to JavaScript with @ReactMethod. Additionally, the class itself must be registered in the ReactPackage of your React Native application.

          <Prism>
{`// Java

public class MyCustomModule extends ReactContextBaseJavaModule {

// Available as NativeModules.MyCustomModule.processString
  @ReactMethod
  public void processString(String input, Callback callback) {
    callback.invoke(input.replace("Goodbye", "Hello"));
  }
}
`}
</Prism>

<Prism>
{`// JavaScript

var React = require('react-native');
var { NativeModules, Text } = React;
var Message = React.createClass({
  getInitialState() {
    return { text: 'Goodbye World.' };
  },
  componentDidMount() {
    NativeModules.MyCustomModule.processString(this.state.text, (text) => {
      this.setState({text});
    });
  },
  render: function() {
    return (
      <Text>{this.state.text}</Text>
    );
  }
});
`}
          </Prism>

Creating Android views

          Custom Android views can be exposed by extending SimpleViewManager, implementing a createViewInstance and getName methods, and exporting properties with the @UIProp annotation. Then a simple JavaScript file connects the dots.

          <Prism>
{`// Java

public class MyCustomViewManager extends SimpleViewManager<MyCustomView> {

  private static final String REACT_CLASS = "MyCustomView";

  @UIProp(UIProp.Type.STRING)
  public static final String PROP_MY_CUSTOM_PROPERTY = "myCustomProperty";

  @Override
  public String getName() {
    return REACT_CLASS;
  }

  @Override
  protected MyCustomView createViewInstance(ThemedReactContext reactContext) {
    return new MyCustomView(reactContext)
  }

  @Override
  public void updateView(MyCustomView view, CatalystStylesDiffMap props) {
    super.updateView(view, props);

    if (props.hasKey(PROP_MY_CUSTOM_PROPERTY)) {
      view.setMyCustomProperty(props.getString(PROP_MY_CUSTOM_PROPERTY));
    }
  }
}
`}
          </Prism>
          <Prism>
{`// JavaScript

var React = require('react-native');
var { requireNativeComponent } = React;

class MyCustomView extends React.Component {
  render() {
    return <NativeMyCustomView {...this.props} />;
  }
}
MyCustomView.propTypes = {
  myCustomProperty: React.PropTypes.oneOf(['a', 'b']),
};

var NativeMyCustomView = requireNativeComponent('MyCustomView', MyCustomView);
module.exports = MyCustomView;
`}
          </Prism>

              Get started with React Native

      </Site>
    );
  }
});

module.exports = index;


text:
import { Component, OnInit } from '@angular/core';

import { Monitor } from '../models/monitor';

@Component({
  selector: 'app-new-monitor',
  templateUrl: './new-monitor.component.html',
  styleUrls: ['./new-monitor.component.scss']
})
export class NewMonitorComponent implements OnInit {

  monitor: Monitor;

  constructor() {
    this.monitor = new Monitor();
    this.monitor.isActive = true;
  }

  ngOnInit() {
  }

}


text:
/**
 * Created by strawmanbobi
 * 2016-11-27
 */

var app = require('../irext_console.js');
var intService = require('../services/code_manage_service.js');

app.post('/irext/int/list_provinces', intService.listProvinces);
app.post('/irext/int/list_cities', intService.listCities);
app.post('/irext/int/list_operators', intService.listOperators);
app.post('/irext/int/list_categories', intService.listCategories);
app.post('/irext/int/list_brands', intService.listBrands);
app.post('/irext/int/list_indexes', intService.listIndexes);
app.post('/irext/int/list_ir_protocols', intService.listIRProtocols);
app.post('/irext/int/download_bin', intService.downloadIndex);

app.post('/irext/int/list_unpublished_brands', intService.listUnpublishedBrands);
app.post('/irext/int/list_unpublished_remote_indexes', intService.listUnpublishedRemoteIndexes);

app.post('/irext/int/create_remote_index', intService.createRemoteIndex);
app.post('/irext/int/delete_remote_index', intService.deleteRemoteIndex);
app.post('/irext/int/verify_remote_index', intService.verifyRemoteIndex);
app.post('/irext/int/fallback_remote_index', intService.fallbackRemoteIndex);

app.post('/irext/int/publish_remote_index', intService.publishRemoteIndex);

app.post('/irext/int/create_brand', intService.createBrand);
app.post('/irext/int/publish_brands', intService.publishBrands);

app.post('/irext/int/create_protocol', intService.createProtocol);

app.get('/irext/int/list_remote_indexes', intService.listRemoteIndexes);
app.get('/irext/int/search_remote_indexes', intService.searchRemoteIndexes);

app.get('/irext/int/download_remote_index', intService.downloadRemoteIndex);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:easemob="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent" android:background="@color/common_bg"
    android:orientation="vertical">

    <com.easemob.easeui.widget.EaseTitleBar android:id="@+id/title_bar"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        easemob:titleBarRightImage="@drawable/em_add"
        easemob:titleBarTitle="@string/address_book" />

    <include android:id="@+id/search_bar_view" layout="@layout/em_search_bar_with_padding" />

    <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent">

        <com.easemob.easeui.widget.EaseContactList android:id="@+id/contact_list"
            android:layout_width="match_parent" android:layout_height="match_parent" />
        <!-- easemob:ctsListInitialLetterBg="#abc" -->

        <LinearLayout android:id="@+id/progress_bar" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_gravity="center"
            android:orientation="vertical" android:visibility="gone">

            <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal" />

            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="@string/now_refresh_list" />
        </LinearLayout>
    </FrameLayout>

</LinearLayout><!-- From: file:/Users/Logan/development/android/as_workspace/EaseChatDemo/app/src/main/res/layout/em_fragment_contact_list.xml -->


text:
Node.js 4.x has ES6 and some ES7 support.

Cheshmak backend Node 4.6.1 --> 4.9.9 --> 6

Node 5.x: recommended not to be used in production

Node 6:

CommonJS: require, module.export
JS Module Loader: import, export

## 1. Promise

```javascript
// Promise
// Q
function getUsersList()
    var deferred = Q.defer();

    deferred.resolve()
    deferred.reject();

    return deferred.promise;
}

function getUsersList(){
    return Q.fcall(function(){
      var myVar = 12;
      //
      //
      //
      //
      throw new Error();//reject
    })
    .then()
    .then()
    .catch(function(){

    });
}

function getUsersList(param){
    if(!param){
      //throw new Error()
       return Q.reject(new Error());
    }
    return Q.fcall(function(){

        var deferred = Q.defer();

        deferred.resolve()
        deferred.reject();

        return deferred.promise;

    })
    .then()
    .then()
    .catch(function(){

    });
}

function getUsersList(){
    // Bad practice
    // throw new Error()
    return new Promise(function(resolve, reject){

        setTimeout(function(){
            if(window.myVar){
               resolve(myVar);
            } else {
               reject(-1);
            }
        }, 1000);

        // throw new Error()

    });
}

```

## 2. Arrow Function

```javascript

var array = [{x:1},{x:2}];

var self = this;
_.map(array, function(item){
  return item.x + 5;
});

var self = this;
_.map(array, (item) => {
  return item.x + 5;
});

_.map(array,(item) => item.x + 5);

```

## 3. Yield keyword

```javascript

function fn(){

}

fn();

// pause

function * func(){
   yield 12;

   yield 13;

   return 15;
}

var generator = func();

// Function generator
// Iterable/Generator/yield

```


text:
  In cases where the content of a nav element represents
  a list of items, use list markup to aid understanding and navigation.


text:
/**
 */
package CIM.IEC61970.Informative.InfOperations;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'Switching Step Status Kind',
 * and utility methods for working with them.
 *
 * @see CIM.IEC61970.Informative.InfOperations.InfOperationsPackage#getSwitchingStepStatusKind()
 * @model
 * @generated
 */
public enum SwitchingStepStatusKind implements Enumerator {
	/**
	 * The 'Skipped' literal object.
	 *
	 *
	 * @see #SKIPPED_VALUE
	 * @generated
	 * @ordered
	 */
	SKIPPED(0, "skipped", "skipped"),

	/**
	 * The 'Proposed' literal object.
	 *
	 *
	 * @see #PROPOSED_VALUE
	 * @generated
	 * @ordered
	 */
	PROPOSED(1, "proposed", "proposed"),

	/**
	 * The 'Confirmed' literal object.
	 *
	 *
	 * @see #CONFIRMED_VALUE
	 * @generated
	 * @ordered
	 */
	CONFIRMED(2, "confirmed", "confirmed"),

	/**
	 * The 'Aborted' literal object.
	 *
	 *
	 * @see #ABORTED_VALUE
	 * @generated
	 * @ordered
	 */
	ABORTED(3, "aborted", "aborted"),

	/**
	 * The 'Instructed' literal object.
	 *
	 *
	 * @see #INSTRUCTED_VALUE
	 * @generated
	 * @ordered
	 */
	INSTRUCTED(4, "instructed", "instructed");

	/**
	 * The 'Skipped' literal value.
	 *
	 *

	 * If the meaning of 'Skipped' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #SKIPPED
	 * @model name="skipped"
	 * @generated
	 * @ordered
	 */
	public static final int SKIPPED_VALUE = 0;

	/**
	 * The 'Proposed' literal value.
	 *
	 *

	 * If the meaning of 'Proposed' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PROPOSED
	 * @model name="proposed"
	 * @generated
	 * @ordered
	 */
	public static final int PROPOSED_VALUE = 1;

	/**
	 * The 'Confirmed' literal value.
	 *
	 *

	 * If the meaning of 'Confirmed' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #CONFIRMED
	 * @model name="confirmed"
	 * @generated
	 * @ordered
	 */
	public static final int CONFIRMED_VALUE = 2;

	/**
	 * The 'Aborted' literal value.
	 *
	 *

	 * If the meaning of 'Aborted' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #ABORTED
	 * @model name="aborted"
	 * @generated
	 * @ordered
	 */
	public static final int ABORTED_VALUE = 3;

	/**
	 * The 'Instructed' literal value.
	 *
	 *

	 * If the meaning of 'Instructed' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #INSTRUCTED
	 * @model name="instructed"
	 * @generated
	 * @ordered
	 */
	public static final int INSTRUCTED_VALUE = 4;

	/**
	 * An array of all the 'Switching Step Status Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final SwitchingStepStatusKind[] VALUES_ARRAY =
		new SwitchingStepStatusKind[] {
			SKIPPED,
			PROPOSED,
			CONFIRMED,
			ABORTED,
			INSTRUCTED,
		};

	/**
	 * A public read-only list of all the 'Switching Step Status Kind' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<SwitchingStepStatusKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'Switching Step Status Kind' literal with the specified literal value.
	 *
	 *
	 * @param literal the literal.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static SwitchingStepStatusKind get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			SwitchingStepStatusKind result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Switching Step Status Kind' literal with the specified name.
	 *
	 *
	 * @param name the name.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static SwitchingStepStatusKind getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			SwitchingStepStatusKind result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Switching Step Status Kind' literal with the specified integer value.
	 *
	 *
	 * @param value the integer value.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static SwitchingStepStatusKind get(int value) {
		switch (value) {
			case SKIPPED_VALUE: return SKIPPED;
			case PROPOSED_VALUE: return PROPOSED;
			case CONFIRMED_VALUE: return CONFIRMED;
			case ABORTED_VALUE: return ABORTED;
			case INSTRUCTED_VALUE: return INSTRUCTED;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private SwitchingStepStatusKind(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //SwitchingStepStatusKind


text:
import traceback
import config_import as ci
import log_control as log
import smtplib
from email.mime.text import MIMEText

class MailSend:
    def __init__(self):
        # Read config
        try:
            self.smtp_host = ci.smtp_host
            self.smtp_port = ci.smtp_port
            self.local_host = ci.local_host
            self.auth_id = ci.smtpauth_id
            self.auth_pass = ci.smtpauth_pass
            self.from_addr = ci.from_addr
            self.to_addr = ci.to_addr
            self.mail_title = ci.mail_title
            self.mail_body = ci.mail_body
            self.item_url = ci.item_url
        except:
            log.logging.error(traceback.format_exc())
            raise

    def mail_send(self, now):

        self.mail_body = now + "\n" + self.mail_body + "\n" + self.item_url

        # Establish SMTP connection.(with SMTPAUTH)
        smtp = smtplib.SMTP(self.smtp_host, self.smtp_port)
        smtp.ehlo(self.local_host)
        smtp.login(self.auth_id, self.auth_pass)
        mail_body = MIMEText(self.mail_body)
        mail_body['Subject'] = self.mail_title

        try:
            smtp.sendmail(self.from_addr, self.to_addr, mail_body.as_string())
            smtp.quit()
            return
        except:
            smtp.quit()
            log.logging.error(
                "Sending mail has failed. ")
            raise


text:
package christophedelory.playlist.asx;

/**
 * A text container.
 * @version $Revision: 92 $
 * @author Christophe Delory
 * @castor.class xml="textElement"
 */
public class TextElement extends Child
{
    /**
     * The text itself.
     */
    private String _text = "";

    /**
     * Returns the text itself.
     * @return a text. Shall not be null.
     * @see #setText
     * @castor.field
     *  get-method="getText"
     *  set-method="setText"
     *  required="true"
     * @castor.field-xml
     *  node="text"
     */
    public String getText()
    {
        return _text;
    }

    /**
     * Initializes the text itself.
     * @param text a text. Shall not be null.
     * @throws NullPointerException if text is null.
     * @see #getText
     */
    public void setText(final String text)
    {
        _text = text.trim(); // Throws NullPointerException if text is null.
    }
}


text:
using System.Collections.Generic;
using Newtonsoft.Json;

namespace QuantConnect.Api
{
    /// <summary>
    /// Node class built for API endpoints nodes/read and nodes/create.
    /// Converts JSON properties from API response into data members for the class.
    /// Contains all relevant information on a Node to interact through API endpoints.
    /// </summary>
    public class Node
    {
        /// <summary>
        /// The nodes cpu clock speed in GHz
        /// </summary>
        [JsonProperty(PropertyName = "speed")]
        public decimal Speed { get; set; }

        /// <summary>
        /// The monthly and yearly prices of the node in US dollars,
        /// see <see cref="NodePrices"/> for type.
        /// </summary>
        [JsonProperty(PropertyName = "price")]
        public NodePrices Prices { get; set; }

        /// <summary>
        /// CPU core count of node
        /// </summary>
        [JsonProperty(PropertyName = "cpu")]
        public int CpuCount { get; set; }

        /// <summary>
        /// Size of RAM in Gigabytes
        /// </summary>
        [JsonProperty(PropertyName = "ram")]
        public decimal Ram { get; set; }

        /// <summary>
        /// Name of the node
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Node type identifier for configuration
        /// </summary>
        [JsonProperty(PropertyName = "sku")]
        public string SKU { get; set; }

        /// <summary>
        /// String description of the node
        /// </summary>
        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        /// <summary>
        /// User currently using the node
        /// </summary>
        [JsonProperty(PropertyName = "usedBy")]
        public string UsedBy { get; set; }

        /// <summary>
        /// Project the node is being used for
        /// </summary>
        [JsonProperty(PropertyName = "projectName")]
        public string ProjectName { get; set; }

        /// <summary>
        /// Boolean if the node is currently busy
        /// </summary>
        [JsonProperty(PropertyName = "busy")]
        public bool Busy { get; set; }

        /// <summary>
        /// Full ID of node
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
    }

    /// <summary>
    /// Rest api response wrapper for node/read, contains sets of node lists for each
    /// target environment. List are composed of <see cref="Node"/> objects.
    /// </summary>
    public class NodeList : RestResponse
    {
        /// <summary>
        /// Collection of backtest nodes
        /// </summary>
        [JsonProperty(PropertyName = "backtest")]
        public List<Node> BacktestNodes { get; set; }

        /// <summary>
        /// Collection of research nodes
        /// </summary>
        [JsonProperty(PropertyName = "research")]
        public List<Node> ResearchNodes { get; set; }

        /// <summary>
        /// Collection of live nodes
        /// </summary>
        [JsonProperty(PropertyName = "live")]
        public List<Node> LiveNodes { get; set; }
    }

    /// <summary>
    /// Rest api response wrapper for node/create, reads in the nodes information into a
    /// node object
    /// </summary>
    public class CreatedNode : RestResponse
    {
        /// <summary>
        /// The created node from node/create
        /// </summary>
        [JsonProperty("node")]
        public Node Node { get; set; }
    }

    /// <summary>
    /// Class for generating a SKU for a node with a given configuration
    /// Every SKU is made up of 3 variables:
    /// - Target environment (L for live, B for Backtest, R for Research)
    /// - CPU core count
    /// - Dedicated RAM (GB)
    /// </summary>
    public class SKU
    {
        /// <summary>
        /// The number of CPU cores in the node
        /// </summary>
        public int Cores { get; set; }

        /// <summary>
        /// Size of RAM in GB of the Node
        /// </summary>
        public int Memory { get; set; }

        /// <summary>
        /// Target environment for the node
        /// </summary>
        public NodeType Target { get; set; }

        /// <summary>
        /// Constructs a SKU object out of the provided node configuration
        /// </summary>
        /// <param name="cores">Number of cores</param>
        /// <param name="memory">Size of RAM in GBs</param>
        /// <param name="target">Target Environment Live/Backtest/Research</param>
        public SKU(int cores, int memory, NodeType target)
        {
            Cores = cores;
            Memory = memory;
            Target = target;
        }

        /// <summary>
        /// Generates the SKU string for API calls based on the specifications of the node
        /// </summary>
        /// <returns>String representation of the SKU</returns>
        public override string ToString()
        {
            string result = "";

            switch (Target)
            {
                case NodeType.Backtest:
                    result += "B";
                    break;
                case NodeType.Research:
                    result += "R";
                    break;
                case NodeType.Live:
                    result += "L";
                    break;
            }

            if (Cores == 0)
            {
                result += "-MICRO";
            }
            else
            {
                result += Cores + "-" + Memory;
            }

            return result;
        }
    }

    /// <summary>
    /// NodeTypes enum for all possible options of target environments
    /// Used in conjuction with SKU class as a NodeType is a required parameter for SKU
    /// </summary>
    public enum NodeType
    {
        /// A node for running backtests
        Backtest,   //0
        /// A node for running research
        Research,   //1
        /// A node for live trading
        Live        //2
    }

    /// <summary>
    /// Class for deserializing node prices from node object
    /// </summary>
    public class NodePrices
    {
        /// <summary>
        /// The monthly price of the node in US dollars
        /// </summary>
        [JsonProperty(PropertyName = "monthly")]
        public int Monthly { get; set; }

        /// <summary>
        /// The yearly prices of the node in US dollars
        /// </summary>
        [JsonProperty(PropertyName = "yearly")]
        public int Yearly { get; set; }
    }

    /// <summary>
    /// Supported optimization nodes
    /// </summary>
    public static class OptimizationNodes
    {
        /// <summary>
        /// 2 CPUs 8 GB ram
        /// </summary>
        public static string O2_8 => "O2-8";

        /// <summary>
        /// 4 CPUs 12 GB ram
        /// </summary>
        public static string O4_12 => "O4-12";

        /// <summary>
        /// 8 CPUs 16 GB ram
        /// </summary>
        public static string O8_16 => "O8-16";
    }
}


text:
// <copyright file="CIExyYTriple.cs" company="Shkyrockett" >
//     Copyright © 2013 - 2020 Shkyrockett. All rights reserved.
// </copyright>
// <author id="shkyrockett">Shkyrockett</author>
// <license>
//     Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </license>
// <summary></summary>
// <remarks></remarks>

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Engine.Colorspace
{
    /// <summary>
    /// The CI exy y triple struct.
    /// </summary>
    /// <seealso cref="IColor" />
    /// <seealso cref="IEquatable{T}" />
    public struct CIExyYTriple
        : IColor, IEquatable<CIExyYTriple>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CIExyYTriple" /> class.
        /// </summary>
        /// <param name="red">The red.</param>
        /// <param name="green">The green.</param>
        /// <param name="blue">The blue.</param>
        public CIExyYTriple(CIExyY red, CIExyY green, CIExyY blue)
        {
            Red = red;
            Green = green;
            Blue = blue;
        }

        /// <summary>
        /// Gets or sets the red.
        /// </summary>
        /// <value>
        /// The red.
        /// </value>
        public CIExyY Red { get; set; }

        /// <summary>
        /// Gets or sets the green.
        /// </summary>
        /// <value>
        /// The green.
        /// </value>
        public CIExyY Green { get; set; }

        /// <summary>
        /// Gets or sets the blue.
        /// </summary>
        /// <value>
        /// The blue.
        /// </value>
        public CIExyY Blue { get; set; }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>
        /// The result of the operator.
        /// </returns>
        public static bool operator ==(CIExyYTriple left, CIExyYTriple right) => left.Equals(right);

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>
        /// The result of the operator.
        /// </returns>
        public static bool operator !=(CIExyYTriple left, CIExyYTriple right) => !(left == right);

        /// <summary>
        /// Determines whether the specified <see cref="object" />, is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="object" /> to compare with this instance.</param>
        /// <returns>
        ///   <see langword="true"/> if the specified <see cref="object" /> is equal to this instance; otherwise, <see langword="false"/>.
        /// </returns>
        public override bool Equals(object obj) => obj is CIExyYTriple triple && Equals(triple);

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        ///   <see langword="true" /> if the current object is equal to the <paramref name="other" /> parameter; otherwise, <see langword="false" />.
        /// </returns>
        public bool Equals([AllowNull] CIExyYTriple other) => EqualityComparer<CIExyY>.Default.Equals(Red, other.Red) && EqualityComparer<CIExyY>.Default.Equals(Green, other.Green) && EqualityComparer<CIExyY>.Default.Equals(Blue, other.Blue);

        /// <summary>
        /// The equals.
        /// </summary>
        /// <param name="other">The other.</param>
        /// <returns>
        /// The <see cref="bool" />.
        /// </returns>
        public bool Equals(IColor other)
        {
            var (r0, g0, b0, a0) = ToRGBATuple();
            var (r1, g1, b1, a1) = (other?.ToRGBATuple()).Value;
            return r0 == r1 && g0 == g1 && b0 == b1 && a0 == a1;
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
        /// </returns>
        public override int GetHashCode() => HashCode.Combine(Red, Green, Blue);

        /// <summary>
        /// The to RGBA tuple.
        /// </summary>
        /// <returns>
        /// The <see cref="ValueTuple{T1, T2, T3, T4}" />.
        /// </returns>
        /// <exception cref="NotImplementedException"></exception>
        public (byte Red, byte Green, byte Blue, byte Alpha) ToRGBATuple() => throw new NotImplementedException();

        /// <summary>
        /// The to string.
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="formatProvider">The formatProvider.</param>
        /// <returns>
        /// The <see cref="string" />.
        /// </returns>
        /// <exception cref="NotImplementedException"></exception>
        public string ToString(string format, IFormatProvider formatProvider) => throw new NotImplementedException();
    }
}


text:
@implementation UIDevice (System)

#pragma mark - Version

+ (BOOL) isDeviceRunningiOS7OrAbove
{
    return [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0;
}

+ (BOOL) isDeviceRunningiOS6OrAbove
{
    return [[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0;
}

+ (BOOL) isDeviceRunningiOS5OrAbove
{
    return [[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0;
}

@end