text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Tm_di_market_visit extends Root_Controller
{
    private $message;
    public $permissions;
    public $controller_url;
    public $locations;
    public function __construct()
    {
        parent::__construct();
        $this->message="";
        $this->permissions=User_helper::get_permission('Tm_di_market_visit');
        $this->locations=User_helper::get_locations();
        if(!is_array($this->locations))
        {
            if($this->locations=='wrong')
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line('MSG_LOCATION_INVALID');
                $this->jsonReturn($ajax);
            }
            else
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line('MSG_LOCATION_NOT_ASSIGNED');
                $this->jsonReturn($ajax);
            }

        }
        $this->controller_url='tm_di_market_visit';
    }

    public function index($action="list",$id=0)
    {
        if($action=="list")
        {
            $this->system_list($id);
        }
        elseif($action=="add")
        {
            $this->system_add();
        }
        elseif($action=="edit")
        {
            $this->system_edit($id);
        }
        elseif($action=="details")
        {
            $this->system_details($id);
        }
        elseif($action=="save")
        {
            $this->system_save();
        }
        else
        {
            $this->system_list($id);
        }
    }

    private function system_list()
    {
        if(isset($this->permissions['view'])&&($this->permissions['view']==1))
        {
            $data['title']="Visit List";
            $ajax['status']=true;
            $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("tm_di_market_visit/list",$data,true));
            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $ajax['system_page_url']=site_url($this->controller_url);
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }

    }
    public function get_items()
    {
        $this->db->from($this->config->item('table_tm_market_visit_di').' mvdi');

        $this->db->select('mvdi.*');
        $this->db->select('CONCAT(cus.customer_code," - ",cus.name) cus_name');
        $this->db->select('d.name district_name');
        $this->db->select('t.name territory_name');
        $this->db->select('zone.name zone_name');
        $this->db->select('division.name division_name');

        $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = mvdi.district_id','INNER');
        $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
        $this->db->join($this->config->item('table_setup_location_zones').' zone','zone.id = t.zone_id','INNER');
        $this->db->join($this->config->item('table_setup_location_divisions').' division','division.id = mvdi.division_id','INNER');

        $this->db->join($this->config->item('table_csetup_customers').' cus','cus.id = mvdi.customer_id','LEFT');
        if($this->locations['division_id']>0)
        {
            $this->db->where('division.id',$this->locations['division_id']);
        }
        $this->db->order_by('mvdi.id DESC');
        $items=$this->db->get()->result_array();
        foreach($items as &$item)
        {
            $item['date']=System_helper::display_date($item['date']);
            $item['locations']=$item['division_name'].'
'.$item['zone_name'].'
'.$item['territory_name'].'
'.$item['district_name'].'
';
            if($item['customer_id']>0)
            {
                $item['locations'].=$item['cus_name'];
            }
            else
            {
                $item['locations'].=$item['customer_name'];
            }
        }
        $this->jsonReturn($items);

    }
    private function system_add()
    {
        if(isset($this->permissions['add'])&&($this->permissions['add']==1))
        {
            $data['title']="New DI Visit";
            $data["visit"] = Array(
                'id'=>0,
                'date'=>time(),
                'division_id'=>$this->locations['division_id'],
                'zone_id'=>$this->locations['zone_id'],
                'territory_id'=>$this->locations['territory_id'],
                'district_id'=>$this->locations['district_id'],
                'customer_id'=>'',
                'activities'=>'',
                'picture_url_activities'=>'',
                'problem'=>'',
                'picture_url_problem'=>'',
                'recommendation'=>'',
                'customer_name'=>'',
            );
            $data['divisions']=Query_helper::get_info($this->config->item('table_setup_location_divisions'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'));
            $data['zones']=array();
            $data['territories']=array();
            $data['districts']=array();
            $data['customers']=array();
            if($this->locations['division_id']>0)
            {
                $data['zones']=Query_helper::get_info($this->config->item('table_setup_location_zones'),array('id value','name text'),array('division_id ='.$this->locations['division_id']));
                if($this->locations['zone_id']>0)
                {
                    $data['territories']=Query_helper::get_info($this->config->item('table_setup_location_territories'),array('id value','name text'),array('zone_id ='.$this->locations['zone_id']));
                    if($this->locations['territory_id']>0)
                    {
                        $data['districts']=Query_helper::get_info($this->config->item('table_setup_location_districts'),array('id value','name text'),array('territory_id ='.$this->locations['territory_id']));
                        if($this->locations['district_id']>0)
                        {
                            $data['customers']=Query_helper::get_info($this->config->item('table_csetup_customers'),array('id value','CONCAT(customer_code," - ",name) text'),array('district_id ='.$this->locations['district_id'],'status ="'.$this->config->item('system_status_active').'"'));
                        }
                    }
                }
            }
            $ajax['system_page_url']=site_url($this->controller_url."/index/add");

            $ajax['status']=true;
            $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("tm_di_market_visit/add_edit",$data,true));
            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }
    private function system_edit($id)
    {
        if(isset($this->permissions['edit'])&&($this->permissions['edit']==1))
        {
            if(($this->input->post('id')))
            {
                $visit_id=$this->input->post('id');
            }
            else
            {
                $visit_id=$id;
            }
            $this->db->from($this->config->item('table_tm_market_visit_di').' mvdi');
            $this->db->select('mvdi.*');
            $this->db->select('t.id territory_id');
            $this->db->select('t.zone_id zone_id');
            $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = mvdi.district_id','INNER');
            $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
            $this->db->where('mvdi.id',$visit_id);
            $data['visit']=$this->db->get()->row_array();
            if(!$data['visit'])
            {
                System_helper::invalid_try("Invalid try at edit",$visit_id);
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
                $this->jsonReturn($ajax);
            }
            $data['title']='Edit Visit';
            $data['divisions']=Query_helper::get_info($this->config->item('table_setup_location_divisions'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'));
            $data['zones']=Query_helper::get_info($this->config->item('table_setup_location_zones'),array('id value','name text'),array('division_id ='.$data['visit']['division_id']));
            $data['territories']=Query_helper::get_info($this->config->item('table_setup_location_territories'),array('id value','name text'),array('zone_id ='.$data['visit']['zone_id']));
            $data['districts']=Query_helper::get_info($this->config->item('table_setup_location_districts'),array('id value','name text'),array('territory_id ='.$data['visit']['territory_id']));
            $data['customers']=Query_helper::get_info($this->config->item('table_csetup_customers'),array('id value','CONCAT(customer_code," - ",name) text'),array('district_id ='.$data['visit']['district_id'],'status ="'.$this->config->item('system_status_active').'"'));

            $ajax['status']=true;
            $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("tm_di_market_visit/add_edit",$data,true));
            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $ajax['system_page_url']=site_url($this->controller_url.'/index/edit/'.$visit_id);
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }

    private function system_save()
    {
        $visit = $this->input->post("visit");
        $id=$this->input->post("id");
        $user = User_helper::get_user();
        if($id>0)
        {
            if(!(isset($this->permissions['edit'])&&($this->permissions['edit']==1)))
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
                $this->jsonReturn($ajax);
                die();
            }
        }
        else
        {
            if(!(isset($this->permissions['add'])&&($this->permissions['add']==1)))
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
                $this->jsonReturn($ajax);
                die();

            }
        }
        if(!$this->check_validation())
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->message;
            $this->jsonReturn($ajax);
        }
        else
        {
            $visit['date']=System_helper::get_time($visit['date']);
            $file_folder='images/di_market_visit/'.$visit['division_id'];
            $dir=(FCPATH).$file_folder;
            if(!is_dir($dir))
            {
                mkdir($dir, 0777);
            }
            $uploaded_files = System_helper::upload_file($file_folder);
            if(array_key_exists('image_activities',$uploaded_files))
            {
                if($uploaded_files['image_activities']['status'])
                {
                    $visit['picture_url_activities']=base_url().$file_folder.'/'.$uploaded_files['image_activities']['info']['file_name'];
                    $visit['picture_file_full_activities']=$file_folder.'/'.$uploaded_files['image_activities']['info']['file_name'];
                    $visit['picture_file_name_activities']=$uploaded_files['image_activities']['info']['file_name'];
                }
                else
                {

                    $ajax['status']=false;
                    $ajax['system_message']=$uploaded_files['image_activities']['message'];
                    $this->jsonReturn($ajax);
                    die();
                }
            }
            if(array_key_exists('image_problem',$uploaded_files))
            {
                if($uploaded_files['image_problem']['status'])
                {
                    $visit['picture_url_problem']=base_url().$file_folder.'/'.$uploaded_files['image_problem']['info']['file_name'];
                    $visit['picture_file_full_problem']=$file_folder.'/'.$uploaded_files['image_problem']['info']['file_name'];
                    $visit['picture_file_name_problem']=$uploaded_files['image_problem']['info']['file_name'];
                }
                else
                {

                    $ajax['status']=false;
                    $ajax['system_message']=$uploaded_files['image_problem']['message'];
                    $this->jsonReturn($ajax);
                    die();
                }
            }
            $this->db->trans_start();  //DB Transaction Handle START
            if($id>0)
            {
                $visit['user_updated'] = $user->user_id;
                $visit['date_updated'] = time();
                Query_helper::update($this->config->item('table_tm_market_visit_di'),$visit,array("id = ".$id));

            }
            else
            {

                $visit['user_created'] = $user->user_id;
                $visit['date_created'] = time();
                Query_helper::add($this->config->item('table_tm_market_visit_di'),$visit);
            }
            $this->db->trans_complete();   //DB Transaction Handle END
            if ($this->db->trans_status() === TRUE)
            {
                $this->message=$this->lang->line("MSG_SAVED_SUCCESS");
                $this->system_list();
            }
            else
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line("MSG_SAVED_FAIL");
                $this->jsonReturn($ajax);
            }
        }
    }
    private function system_details($id)
    {
        if(isset($this->permissions['view'])&&($this->permissions['view']==1))
        {
            if(($this->input->post('id')))
            {
                $visit_id=$this->input->post('id');
            }
            else
            {
                $visit_id=$id;
            }
            $this->db->from($this->config->item('table_tm_market_visit_di').' mvdi');

            $this->db->select('mvdi.*');
            $this->db->select('CONCAT(cus.customer_code," - ",cus.name) cus_name');
            $this->db->select('d.name district_name');
            $this->db->select('t.name territory_name');
            $this->db->select('zone.name zone_name');
            $this->db->select('division.name division_name');

            $this->db->select('count(mvsdi.id) total_solution',false);

            $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = mvdi.district_id','INNER');
            $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
            $this->db->join($this->config->item('table_setup_location_zones').' zone','zone.id = t.zone_id','INNER');
            $this->db->join($this->config->item('table_setup_location_divisions').' division','division.id = mvdi.division_id','INNER');
            $this->db->join($this->config->item('table_tm_market_visit_solution_di').' mvsdi','mvdi.id = mvsdi.visit_id','LEFT');
            $this->db->join($this->config->item('table_csetup_customers').' cus','cus.id = mvdi.customer_id','LEFT');
            $this->db->where('mvdi.id',$visit_id);
            $data['visit']=$this->db->get()->row_array();
            if(!$data['visit'])
            {
                System_helper::invalid_try("Invalid try at edit",$visit_id);
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
                $this->jsonReturn($ajax);
            }
            $data['title']='DI Market Visit Solution Details';
            $user_ids=array();
            $user_ids[$data['visit']['user_created']]=$data['visit']['user_created'];
            $data['previous_solutions']=Query_helper::get_info($this->config->item('table_tm_market_visit_solution_di'),'*',array('visit_id ='.$visit_id),0,0,array('date_created DESC'));
            foreach($data['previous_solutions'] as $solution)
            {
                $user_ids[$solution['user_created']]=$solution['user_created'];
            }
            $data['users']=System_helper::get_users_info($user_ids);
            $ajax['status']=true;
            $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("tm_di_market_visit/details",$data,true));
            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $ajax['system_page_url']=site_url($this->controller_url.'/index/details/'.$visit_id);
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }
    private function check_validation()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('visit[date]',$this->lang->line('LABEL_DATE'),'required');
        $this->form_validation->set_rules('visit[division_id]',$this->lang->line('LABEL_DIVISION_NAME'),'required|numeric');
        $this->form_validation->set_rules('visit[district_id]',$this->lang->line('LABEL_DISTRICT_NAME'),'required|numeric');
        $this->form_validation->set_rules('visit[recommendation]','Recommendation','required');
        if($this->form_validation->run() == FALSE)
        {
            $this->message=validation_errors();
            return false;
        }
        if(!(($this->input->post('visit[customer_id]')>0)||(strlen($this->input->post('visit[customer_name]'))>0)))
        {
            $this->message='Select or Type Customer Name';
            return false;
        }
        return true;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/pageView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">

  <RelativeLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:background="@drawable/cast_player_bg_gradient_light">

    <RelativeLayout
        android:id="@+id/controllers"
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:visibility="invisible">

      <ImageView
          android:id="@+id/imageView1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:src="@drawable/ic_av_pause_dark"/>

      <TextView
          android:id="@+id/startText"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_marginLeft="5dp"
          android:layout_toRightOf="@+id/imageView1"
          android:gravity="center_vertical"
          android:maxLines="1"
          android:text="00:00"
          android:textColor="@color/white"/>

      <TextView
          android:id="@+id/endText"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_alignParentRight="true"
          android:layout_marginRight="16dp"
          android:gravity="center_vertical"
          android:maxLines="1"
          android:text="0:00"
          android:textColor="@color/white"/>

      <SeekBar
          android:id="@+id/seekBar1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_centerVertical="true"
          android:layout_gravity="center"
          android:layout_marginLeft="5dp"
          android:layout_marginRight="5dp"
          android:layout_toLeftOf="@+id/endText"
          android:layout_toRightOf="@+id/startText"/>
    </RelativeLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:ellipsize="end"
        android:gravity="center_horizontal"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#E5FFFFFF"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/controllers"
        android:ellipsize="end"
        android:fontFamily="sans-serif-light"
        android:gravity="center_horizontal"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#E5AAAAAA"/>
  </RelativeLayout>

  <ProgressBar
      android:id="@+id/progressBar1"
      style="?android:attr/progressBarStyleLarge"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:visibility="gone"/>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
namespace PatchKit.Unity.Patcher.UI.Dialogs
{
    public interface ILicenseDialog
    {
        LicenseDialogResult Display(LicenseDialogMessageType messageType);
    }
}


text:
package com.readlearncode;

import org.junit.Test;

import javax.json.*;

import static org.assertj.core.api.Java6Assertions.assertThat;

/**
 * Source code github.com/readlearncode
 *
 * @author Alex Theedom www.readlearncode.com
 * @version 1.0
 */
public class JsonPatchExampleTest {

    @Test
    public void ifValueIsMoved_shouldNotAmendOriginalJSON() {
        JsonPatchExample jsonPatchExample = new JsonPatchExample();
        JsonObject jsonObject = jsonPatchExample.toJsonArray();

        JsonPointer pointer = Json.createPointer("/series/0");
        JsonString jsonString = (JsonString) pointer.getValue(jsonObject);
        assertThat(jsonString.getString()).isEqualToIgnoringCase("Cognitive");
    }

    @Test
    public void ifValueExists_moveItToDestination() {
        JsonPatchExample jsonPatchExample = new JsonPatchExample();
        JsonObject jsonObject = jsonPatchExample.test();

        JsonPointer pointer = Json.createPointer("/series/2");
        JsonString jsonString = (JsonString) pointer.getValue(jsonObject);
        assertThat(jsonString.getString()).isEqualToIgnoringCase("Data");
    }

    @Test
    public void givenPath_copyToTargetPath() throws Exception {
        JsonPatchExample jsonPatchExample = new JsonPatchExample();
        JsonObject jsonObject = jsonPatchExample.copy();

        JsonPointer pointer = Json.createPointer("/series/0");
        JsonString jsonString = (JsonString) pointer.getValue(jsonObject);
        assertThat(jsonString.getString()).isEqualToIgnoringCase("Cognitive");
    }

    @Test
    public void givenPath_moveToTargetPath() throws Exception {
        JsonPatchExample jsonPatchExample = new JsonPatchExample();
        JsonObject jsonObject = jsonPatchExample.move();

        JsonPointer pointer = Json.createPointer("/series/0");
        JsonString jsonString = (JsonString) pointer.getValue(jsonObject);
        assertThat(jsonString.getString()).isEqualToIgnoringCase("Cognitive");
    }

    @Test
    public void givenPatchPath_shouldRemoveAndAdd() {
        JsonPatchExample jsonPatchExample = new JsonPatchExample();
        JsonObject jsonObject = jsonPatchExample.addAndRemove();

        // Assert that "comments" property was added with value "Very Good!"
        JsonPointer pointer = Json.createPointer("/comments");
        JsonValue jsonValue = pointer.getValue(jsonObject);
        assertThat(jsonValue.getValueType()).isEqualTo(JsonValue.ValueType.ARRAY);
        assertThat(jsonValue.asJsonArray().contains(Json.createValue("Very Good!"))).isTrue();
        assertThat(jsonValue.asJsonArray().contains(Json.createValue("Excellent"))).isTrue();

        // Assert that "notes" property was removed
        pointer = Json.createPointer("/notes");
        boolean contains = pointer.containsValue(jsonObject);
        assertThat(contains).isFalse();
    }

    @Test
    public void givenPatchPath_shouldReplaceElement() {
        JsonPatchExample jsonPatchExample = new JsonPatchExample();
        String series = jsonPatchExample.replace();
        assertThat(series).isEqualToIgnoringCase("Spring 5");
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.drip.sample.stretch Class Hierarchy</title>
<meta name="date" content="2014-01-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.drip.sample.stretch

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.drip.sample.stretch.CustomCurveBuilder

org.drip.sample.stretch.PenalizedCurvatureFit

org.drip.sample.stretch.PenalizedCurvatureLengthFit

org.drip.sample.stretch.RegressionSplineEstimator

org.drip.sample.stretch.StretchAdjuster

org.drip.sample.stretch.StretchEstimation

org.drip.sample.stretch.TensionStretchEstimation

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.miguelgaeta.easyprefs;

import android.util.Pair;

import com.google.gson.Gson;
import com.miguelgaeta.easyprefs.typetoken.GenericsToken;

import java.util.Arrays;

import rx.Observable;
import rx.Subscription;
import rx.schedulers.Schedulers;

/**
 * Created by Miguel Gaeta on 3/9/15.
 */
@SuppressWarnings("unchecked")
class EasyPrefsMetaData<T> {

    // A memory cache of the preference value
    // so we do not have to go into the native
    // android preferences every fetch.
    private T locallyCachedValue;

    // Default value of this item.
    private T defaultValue;

    // The key used by the android preferences
    // underlying system (should be unique).
    private final String key;
    private final String keyTypeToken;

    // Gson serializer.
    private final Gson gson;

    // Holds any active serialization subscription.
    private Subscription serializationSubscription;

    /**
     * Creates a new preference object that is backed
     * by the android shared preferences object.
     */
    EasyPrefsMetaData(Gson gson, String key, T defaultValue, boolean cacheBreaker) {

        if (cacheBreaker) {

            // Append cache breaker.
            key += "_" + EasyPrefsConfig.getApplicationVersionCode();
        }

        this.gson = gson;

        this.key = key;
        this.keyTypeToken = key + "_TYPE_TOKEN";

        this.defaultValue = defaultValue;
    }

    /**
     * Clear out any value stored.
     */
    void clear() {

        EasyPrefsSharedPreferences.removeString(key);

        locallyCachedValue = null;
    }

    /**
     * Get the preference value.
     */
    T get() {

        if (locallyCachedValue == null) {

            // First fetch complex type token for preference.
            String typeTokenJson = EasyPrefsSharedPreferences.getString(keyTypeToken);

            if (typeTokenJson != null) {

                // Fetch raw json associated with this preference key.
                String keyJson = EasyPrefsSharedPreferences.getString(key);

                if (keyJson != null) {

                    // Deserialize with type token and update local cache.
                    locallyCachedValue = (T)GenericsToken.deserialize(GenericsToken.deserializeToken(typeTokenJson), gson, keyJson);
                }
            }
        }

        if (locallyCachedValue == null && defaultValue != null) {

            return defaultValue;
        }

        return locallyCachedValue;
    }

    /**
     * Set the preference value.
     */
    void set(T value) {

        if (value == null) {

            clear();

        } else {

            // Locally cache value.
            locallyCachedValue = value;

            if (serializationSubscription != null) {
                serializationSubscription.unsubscribe();
            }

            // Create an observable that serializes the value and generates its type token.
            Observable<Pair<String, String>> serializationObservable = Observable.create(subscriber -> {

                subscriber.onNext(Pair.create(gson.toJson(value), GenericsToken.serializeToken(GenericsToken.create(value))));
                subscriber.onCompleted();
            });

            serializationSubscription = serializationObservable.subscribeOn(Schedulers.computation()).subscribe(keyTypeTokenPair -> {

                EasyPrefsSharedPreferences.setString(Arrays.asList(

                    Pair.create(key, keyTypeTokenPair.first),
                    Pair.create(keyTypeToken, keyTypeTokenPair.second)));
            });
        }
    }
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Created by Leslie on 2017/5/9.
 */
var core_1 = require("@angular/core");
var GoodsComponent = (function () {
    function GoodsComponent() {
        this.title = '商品清单';
        this.onSelected = new core_1.EventEmitter();
        /**
         * // changed = new EventEmitter(); // 创建事件对象
         * // this.changed.emit(good); // 注意这里触发的是父组件的onchange事件
         * // outputs: ['changed'] //调用父组件的onchanged方法
         */
    }
    GoodsComponent.prototype.onSelect = function (good) {
        this.selectedGood = good;
        this.onSelected.emit(good); //注意这里触发的是父组件的onSelected事件
    };
    return GoodsComponent;
}());
__decorate([
    core_1.Input(),
    __metadata("design:type", Array)
], GoodsComponent.prototype, "goods", void 0);
__decorate([
    core_1.Output(),
    __metadata("design:type", Object)
], GoodsComponent.prototype, "onSelected", void 0);
GoodsComponent = __decorate([
    core_1.Component({
        selector: 'my-goods',
        templateUrl: 'app/goods/goods.component.html',
        styleUrls: ['app/goods/goods.component.css'],
    })
], GoodsComponent);
exports.GoodsComponent = GoodsComponent;
//# sourceMappingURL=goods.component.js.map


text:
<?php
/**
 * [PHPFOX_HEADER]
 */

defined('PHPFOX') or exit('NO DICE!');

/**
 *
 *
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author  		Raymond Benc
 * @package 		Phpfox_Service
 * @version 		$Id: process.class.php 4497 2012-07-11 10:27:33Z Miguel_Espinoza $
 */
class User_Service_Group_Process extends Phpfox_Service
{
	/**
	 * Class constructor
	 */
	public function __construct()
	{
		$this->_sTable = Phpfox::getT('user_group');
	}

	public function add($aVals)
	{
		$iId = ($this->database()->select('user_group_id')
			->from($this->_sTable)
			->order('user_group_id DESC')
			->execute('getField') + 1);

		$aForm = array(
			'title' => array(
				'type' => 'string:required',
				'message' => Phpfox::getPhrase('user.provide_a_name_for_the_user_group')
			),
			'prefix' => array(
				'type' => 'string'
			),
			'suffix' => array(
				'type' => 'string'
			),
			'inherit_id' => array(
				'type' => 'int:required',
				'message' => Phpfox::getPhrase('user.select_an_inherit_user_group')
			)
		);

		$aVals = $this->validator()->process($aForm, $aVals);

		if (!Phpfox_Error::isPassed())
		{
			return false;
		}

		$aVals['user_group_id'] = $iId;
		$aVals['title'] = $this->preParse()->clean($aVals['title'], 255);

		if (($aVals['icon_ext'] = $this->_uploadImage($iId)) === false)
		{
			return false;
		}

		if (is_bool($aVals['icon_ext']))
		{
			$aVals['icon_ext'] = null;
		}

		$this->database()->insert($this->_sTable, $aVals);

		// Add the language phrase for this new user group
		$aLanguages = Phpfox::getService('language')->getAll();
		$sPhraseVar = 'user.' . str_replace(' ', '_', strtolower($aVals['title']));
		$aToAdd = array('module' => 'user|user', 'product_id' => 'phpfox', 'text' => array(), 'var_name' => $sPhraseVar);
		foreach ($aLanguages as $aLang)
		{
			$aToAdd['text'][$aLang['language_id']] = $aVals['title'];
		}
		Phpfox::getService('language.phrase.process')->add($aToAdd);

		$aMenus = $this->database()->select('menu_id, disallow_access')
			->from(Phpfox::getT('menu'))
			->execute('getRows');

		$aCache = array();
		$aGroupRows = $this->database()->select('user_group_id')
			->from($this->_sTable)
			->execute('getRows');
		foreach ($aGroupRows as $aGroupRow)
		{
			$aCache[] = $aGroupRow['user_group_id'];
		}

		switch($aVals['inherit_id'])
		{
			case ADMIN_USER_ID:
				$sVar = 'default_admin';
				break;
			case GUEST_USER_ID:
				$sVar = 'default_guest';
				break;
			case STAFF_USER_ID:
				$sVar = 'default_staff';
				break;
			case NORMAL_USER_ID:
				$sVar = 'default_user';
				break;
			default:

				break;
		}

		if (empty($sVar))
		{
			$aGroupSettings = $this->database()->select('ugs.setting_id, ugc.module_id, ugc.name, ugc.default_value')
				->from(Phpfox::getT('user_group_custom'), 'ugc')
				->join(Phpfox::getT('user_group_setting'), 'ugs', 'ugc.name = ugs.name')
				->where('ugc.user_group_id = ' . (int) $aVals['inherit_id'])
				->execute('getRows');
		}
		else
		{
			$aGroupSettings = $this->database()->select('setting_id, module_id, name, ' . $sVar)
				->from(Phpfox::getT('user_group_setting'))
				->execute('getRows');
		}

		$aActualSettings = $this->database()->select('setting_id, value_actual')
			->from(Phpfox::getT('user_setting'))
			->where('user_group_id = ' . (int) $aVals['inherit_id'])
			->execute('getRows');

		$aCacheSettings = array();
		foreach ($aActualSettings as $aActualSetting)
		{
			$aCacheSettings[$aActualSetting['setting_id']] = $aActualSetting['value_actual'];
		}

		foreach ($aGroupSettings as $aGroupSetting)
		{
			$sDefaultValue = (isset($aCacheSettings[$aGroupSetting['setting_id']]) ? $aCacheSettings[$aGroupSetting['setting_id']] : $aGroupSetting[(empty($sVar) ? 'default_value' : $sVar)]);
			if ($aGroupSetting['name'] == 'has_special_custom_fields')
			{
				$sDefaultValue = 0;
			}

			$this->database()->insert(Phpfox::getT('user_group_custom'), array(
					'user_group_id' => $iId,
					'module_id' => $aGroupSetting['module_id'],
					'name' => $aGroupSetting['name'],
					'default_value' => $sDefaultValue
				)
			);
		}

		foreach ($aMenus as $aMenu)
		{
			if (empty($aMenu['disallow_access']))
			{
				continue;
			}

			$aGroups = unserialize($aMenu['disallow_access']);

			foreach ($aGroups as $iKey => $iGroup)
			{
				if (!in_array($iGroup, $aCache))
				{
					unset($aGroups[$iKey]);
				}
			}

			if (in_array($aVals['inherit_id'], $aGroups))
			{
				array_push($aGroups, $iId);

				$this->database()->update(Phpfox::getT('menu'), array('disallow_access' => serialize($aGroups)), 'menu_id = ' . $aMenu['menu_id']);
			}
		}

		$this->cache()->remove();

		return $iId;
	}

	public function delete($aVals)
	{
		$aGroup = Phpfox::getService('user.group')->getGroup($aVals['delete_id']);

		if (!isset($aGroup['user_group_id']))
		{
			return Phpfox_Error::display(Phpfox::getPhrase('user.unable_to_find_the_user_group_you_want_to_delete'));
		}

		if ($aGroup['is_special'])
		{
			return Phpfox_Error::display(Phpfox::getPhrase('user.not_allowed_to_delete_this_user_group'));
		}

		$aMenus = $this->database()->select('menu_id, disallow_access')
			->from(Phpfox::getT('menu'))
			->execute('getRows');

		foreach ($aMenus as $aMenu)
		{
			if (empty($aMenu['disallow_access']))
			{
				continue;
			}

			$aGroups = unserialize($aMenu['disallow_access']);

			foreach ($aGroups as $iKey => $iGroup)
			{
				if ($iGroup == $aGroup['user_group_id'])
				{
					unset($aGroups[$iKey]);
				}
			}

			$this->database()->update(Phpfox::getT('menu'), array('disallow_access' => serialize($aGroups)), 'menu_id = ' . $aMenu['menu_id']);
		}
		$bHasCustom = $this->database()->select('s.value_actual')
				->from(Phpfox::getT('user_setting'), 's')
				->join(Phpfox::getT('user_group_custom'), 'v', 'v.setting_id = s.setting_id')
				->where('s.user_group_id = ' . $aGroup['user_group_id'] . ' AND v.name= "has_special_custom_fields"')
				->execute('getSlaveField');
		if ($bHasCustom)
		{
			$sTableName = Phpfox::getParam(array('db','prefix')) . 'user_group_custom_' . str_replace(' ', '_', strtolower($aGroup['title']));
			if ($this->database()->tableExists($sTableName) != false)
			{
				$this->database()->dropTables($sTableName);
			}
			if ($this->database()->tableExists($sTableName .'_value') != false)
			{
				$this->database()->dropTables($sTableName.'_value');
			}
		}
		$this->deleteIcon($aGroup['user_group_id']);

		$this->database()->delete(Phpfox::getT('user_group_custom'), 'user_group_id = ' . $aGroup['user_group_id']);
		$this->database()->delete(Phpfox::getT('user_setting'), 'user_group_id = ' . $aGroup['user_group_id']);
		$this->database()->delete(Phpfox::getT('user_group'), 'user_group_id = ' . $aGroup['user_group_id']);
		$this->database()->update(Phpfox::getT('user'), array('user_group_id' => $aVals['user_group_id']), 'user_group_id = ' . $aGroup['user_group_id']);

		$this->database()->update(Phpfox::getT('subscribe_package'), array('is_active' => 0), 'user_group_id = ' . $aGroup['user_group_id']);
		$this->cache()->remove();

		return true;
	}

	public function update($iGroupId, $aVals)
	{
		$aForm = array(
			'title' => array(
				'type' => 'string:required',
				'message' => Phpfox::getPhrase('user.provide_a_name_for_the_user_group')
			),
			'prefix' => array(
				'type' => 'string'
			),
			'suffix' => array(
				'type' => 'string'
			)
		);

		$aVals = $this->validator()->process($aForm, $aVals);

		if (!Phpfox_Error::isPassed())
		{
			return false;
		}

		$aVals['title'] = $this->preParse()->clean($aVals['title'], 255);

		if (($aVals['icon_ext'] = $this->_uploadImage($iGroupId)) === false)
		{
			return false;
		}

		if (is_bool($aVals['icon_ext']))
		{
			$aVals['icon_ext'] = null;
		}

		$this->database()->update(Phpfox::getT('user_group'), $aVals, 'user_group_id = ' . (int) $iGroupId);

		$this->cache()->remove();

		return true;
	}

	public function deleteIcon($iId)
	{
		$aGroup = Phpfox::getService('user.group')->getGroup($iId);
		if (!empty($aGroup['icon_ext']))
		{
			if (file_exists(Phpfox::getParam('core.dir_icon') . $aGroup['icon_ext']))
			{
				unlink(Phpfox::getParam('core.dir_icon') . $aGroup['icon_ext']);
			}
		}

		return true;
	}

	/**
	 * If a call is made to an unknown method attempt to connect
	 * it to a specific plug-in with the same name thus allowing
	 * plug-in developers the ability to extend classes.
	 *
	 * @param string $sMethod is the name of the method
	 * @param array $aArguments is the array of arguments of being passed
	 */
	public function __call($sMethod, $aArguments)
	{
		/**
		 * Check if such a plug-in exists and if it does call it.
		 */
		if ($sPlugin = Phpfox_Plugin::get('user.service_group_process__call'))
		{
			return eval($sPlugin);
		}

		/**
		 * No method or plug-in found we must throw a error.
		 */
		Phpfox_Error::trigger('Call to undefined method ' . __CLASS__ . '::' . $sMethod . '()', E_USER_ERROR);
	}

	private function _uploadImage($iId)
	{
		if (!empty($_FILES['icon']['name']))
		{
			$aImage = Phpfox::getLib('file')->load('icon', array('jpg', 'gif', 'png'));
			if ($aImage === false)
			{
				return false;
			}

			$aGroup = Phpfox::getService('user.group')->getGroup($iId);
			if (!empty($aGroup['icon_ext']))
			{
				if (file_exists(Phpfox::getParam('core.dir_icon') . $aGroup['icon_ext']))
				{
					unlink(Phpfox::getParam('core.dir_icon') . $aGroup['icon_ext']);
				}
			}

			return Phpfox::getLib('file')->upload('icon', Phpfox::getParam('core.dir_icon'), $iId, false, 0644, false);
		}

		return true;
	}
}

?>


text:
from django.conf.urls import url, include
from rest_framework import routers
import views

API_VERSION = 'v1'

router = routers.DefaultRouter()
router.register(r'%s/sessions_status' % API_VERSION, views.SessionStatusList)
router.register(r'%s/sessions' % API_VERSION, views.SessionList)
router.register(r'%s/sessions/([0-9]+)/steps' % API_VERSION, views.SessionSteps)
router.register(r'%s/sessions/([0-9]+)/steps/([0-9]+)/substeps' % API_VERSION, views.SessionSubSteps)

urlpatterns = [
    url(r'^%s/platforms$' % API_VERSION, views.Platforms.as_view()),
    url(r'^%s/dc' % API_VERSION, views.Dc.as_view()),
    url(r'^%s/user/token' % API_VERSION, views.GetToken.as_view()),
    url(r'^%s/user/generate_token' % API_VERSION, views.GenerateToken.as_view()),
    url(r'^%s/endpoints' % API_VERSION, views.get_endpoints, name='get_endpoints'),
    url(r'^', include(router.urls))
]


text:
import React from 'react';
import PropTypes from 'prop-types';
import injectSheet from 'react-jss';
import classNames from 'classnames';
import Link from '../../utils/Link';
import { Icon } from '../icon';

const styles = {
  root: {
    display: 'flex',
    zIndex: 500,
    width: '100%',
    backgroundColor: props => props.backgroundColor,
    borderTop: props => `.01rem solid ${props.topLineColor}`,

  },

  item: {
    display: 'block',
    flex: 1,
    padding: '.12rem 0 0',
    fontSize: 0,
    color: props => props.colorNormal,
    textAlign: 'center',
    // .setTapColor(),
  },
  link: {
    fontWeight: 'normal',
    textDecoration: 'none',
    border: 0,
  },
  item_on: {
    color: props => props.colorOn,
    backgroundColor: props => props.backgroundColorOn,
  },

  icon: {
    display: 'inline-block',
    width: props => props.iconWidth,
    height: props => props.iconHeight,
    fontSize: props => props.iconFontSize,
  },

  icon_font: {
    color: props => props.colorNormal,
  },
  icon_img: {
    width: '100%',
    height: '100%',
  },

  label: {
    textAlign: 'center',
    color: props => props.colorNormal,
    fontSize: props => props.labelFontSize,
    lineHeight: props => props.labelLineHeight,
    margin: 0,
  },
};

class NavBar extends React.Component {
    static propTypes = {
      backgroundColor: PropTypes.string,
      topLineColor: PropTypes.string,
      colorNormal: PropTypes.string,
      colorOn: PropTypes.string,
      backgroundColorOn: PropTypes.string,
      iconWidth: PropTypes.string,
      iconHeight: PropTypes.string,
      iconFontSize: PropTypes.string,
      labelFontSize: PropTypes.string,
      labelLineHeight: PropTypes.string,
      items: PropTypes.array,
      selected: PropTypes.number,
    };
    static defaultProps = { // return a object
      backgroundColor: '#F7F7FA',
      topLineColor: '#C0BFC4',
      colorNormal: '#999999',
      colorOn: '#09BB07',
      backgroundColorOn: '#C0BFC4',
      iconWidth: '.48rem',
      iconHeight: '.48rem',
      iconFontSize: '.48rem',
      labelFontSize: '0.24rem',
      labelLineHeight: '0.40rem',
      items: [],
      selected: 0,
    };

    icon(content) {
      return (
        <Icon fontName={this.props.iconFont} content={content} fixedWidth color={this.props.color} />
      );
    }

    render() {
      const { classes } = this.props;
      const that = this;
      return (

          {
                    this.props.items.map((item, index) => {
                        const itemClassName = classNames(classes.item, classes.link, { [classes.item_on]: that.props.selected === index });
                        const iconClassName = classNames(classes.icon, { [classes.icon_font]: item.icon, [classes.icon_img]: item.image });
                        const labelClassName = classNames(classes.label, { [classes.item_on]: that.props.selected === index });
                        return (
                          <Link className={itemClassName} key={index} to={item.to} onClick={item.onClick}>
                            {item.image ?  : null}
                            {item.icon ?  : null}

{item.label}

                          </Link>
                        );
                    })
                }

      );
    }
}

export default injectSheet(styles)(NavBar);


text:
static void translation_processLine(translation_module_t *translation_modules, FILE *out, csafestring_t *output, char *line);
static void translation_createSourceHeader(FILE *file);
static void translation_closeSourceFile(FILE *file);

void translation_processTemplate(translation_module_t *translation_modules, char *templatePath, char *sourcePath, char *libraryPath) {
	char buffer[BUFFER_SIZE + 1];
	FILE *in = fopen(templatePath, "r");
	FILE *out = fopen(sourcePath, "w");
	csafestring_t *output = safe_create(NULL);

	translation_createSourceHeader(out);

	while ( !feof(in) ) {
		memset(buffer, '\0', BUFFER_SIZE + 1);
		fgets(buffer, BUFFER_SIZE, in);
		translation_processLine(translation_modules, out, output, buffer);
	}
	translation_processLine(translation_modules, out, output, NULL);

	safe_destroy(output);
	fclose(in);
	translation_closeSourceFile(out);
	compiler_compileCode(sourcePath, libraryPath);
}

static void translation_createSourceHeader(FILE *file) {
	fprintf(file, "#include <stdio.h>\n");
	fprintf(file, "#include <stdlib.h>\n");
	fprintf(file, "#include <string.h>\n");
	fprintf(file, "#define EXPR_STRING_LENGTH 255\n\n");

	fprintf(file, "typedef struct {\n");
	fprintf(file, "	void * (* createMap)();\n");
	fprintf(file, "	void (* destroyMap)(void *);\n");
	fprintf(file, "	char * (* get)(void *, char *);\n");
	fprintf(file, "	void (* set)(void *, char *, char *);\n");
	fprintf(file, "	void (* unset)(void *, char *);\n");
	fprintf(file, " void (* parseJson)(void (* set)(void *, char *, char *), void *, char *, char *);\n");
	fprintf(file, "} ctemplate_functions_t;\n\n");

	fprintf(file, "typedef struct {\n");
	fprintf(file, "	char *(* intToString)(char *, size_t, int);\n");
	fprintf(file, "	char *(* floatToString)(char *, size_t, float);\n");
	fprintf(file, "	char *(* safe_strcat)(void *, const char *);\n");
	fprintf(file, "} ctemplate_utilities_t;\n\n");

	fprintf(file, "void setVariable(ctemplate_functions_t *mfunctions, void *map, char *varName, char *jsonString) {\n");
	fprintf(file, "	char *objName = calloc(sizeof(char), strlen(varName) + 4 );\n");
	fprintf(file, "	strcpy(objName, varName);\n");
	fprintf(file, "	strcat(objName, \"[o]\");\n");
	fprintf(file, "	mfunctions->set(map, objName, jsonString);\n");
	fprintf(file, "	mfunctions->parseJson(mfunctions->set, map, varName, jsonString);\n");
	fprintf(file, "	free(objName);\n");
	fprintf(file, "}\n\n");

	fprintf(file, "char *getVariable(ctemplate_functions_t *mfunctions, void *map, char *varName) {\n");
	fprintf(file, " char *tmp = mfunctions->get(map, varName);\n");
	fprintf(file, " if ( tmp != NULL ) {\n");
	fprintf(file, " 	return tmp;\n");
	fprintf(file, " }\n");
	fprintf(file, "	char *objName = calloc(sizeof(char), strlen(varName) + 4 );\n");
	fprintf(file, "	strcpy(objName, varName);\n");
	fprintf(file, "	strcat(objName, \"[o]\");\n");
	fprintf(file, " tmp = mfunctions->get(map, objName);\n");
	fprintf(file, " if ( tmp != NULL ) {\n");
	fprintf(file, "	 free(objName);\n");
	fprintf(file, "	 return tmp;\n");
	fprintf(file, " }\n");
	fprintf(file, "	strcpy(objName, varName);\n");
	fprintf(file, "	strcat(objName, \"[x]\");\n");
	fprintf(file, " tmp = mfunctions->get(map, objName);\n");
	fprintf(file, "	free(objName);\n");
	fprintf(file, "	return tmp;\n");
	fprintf(file, "}\n\n");

	fprintf(file, "void %s(void *__internal_string, ctemplate_functions_t *__internal_mfunction, ctemplate_utilities_t *__internal_hfunction, char *__internal_jsonString) {\n",
	        MODULE_EXEC_METHOD);
	fprintf(file, "char __internal_expressionString[EXPR_STRING_LENGTH];\n");
	fprintf(file, "char *__internal_tmp;\n");
	fprintf(file, "void *__internal_root = __internal_mfunction->createMap();\n");
	fprintf(file, "setVariable(__internal_mfunction, __internal_root, \"request\", __internal_jsonString);\n\n");
}

static void translation_processLine(translation_module_t *translation_modules, FILE *out, csafestring_t *output, char *line) {
	void *method;

	if ( line == NULL ) {
		if ( output->data[0] != '\0' ) {
			fprintf(out, "__internal_hfunction->safe_strcat(__internal_string, \"%s\");\n", output->data);
			safe_emptyBuffer(output);
		}
		return;
	}

	while ( *line != '\0' ) {
		if ( *line == '\n' && *( line + 1 ) == '\0' ) {
			safe_strchrappend(output, '\0');
			line++;
		} else if ( *line == '\n' ) {
			line++;
		} else if ( ( *line == ' ' || *line == '\t' ) && ( *( line + 1 ) == ' ' || *( line + 1 ) == '\t' ) ) {
			line++;
		} else if ( *line == '\t' ) {
			safe_strchrappend(output, ' ');
			line++;
		} else if ( *line == '\"' ) {
			safe_strcat(output, "\\\"");
			line++;
		} else {
			method = modules_matches(translation_modules, line);
			if ( method != NULL ) {
				if ( output->data[0] != '\0' ) {
					fprintf(out, "__internal_hfunction->safe_strcat(__internal_string, \"%s\");\n", output->data);
					safe_emptyBuffer(output);
				}
				line = modules_execute(out, method, line);
			} else {
				safe_strchrappend(output, *line);
				line++;
			}
		}
	}
}

static void translation_closeSourceFile(FILE *file) {
	fprintf(file, "__internal_mfunction->destroyMap(__internal_root);\n");
	fprintf(file, "}\n");
	fclose(file);
}


text:
class Jlab2b6

// Student Name : 		Daniel Hayden
// Student Id Number : 	C00137009
// Date :				03/10/14
// Purpose : 			6.	Write a simple menu driven program that will present the user with the following conversion menu (look up conversion rates on the internet):
////////////////

/*
1.	Fahrenheit to celcius
2.	Celcius to Fahrenheit
3.	Inches to centimetres
4.	Centimetres to inches
5.	Pounds to Kilograms
*/

{

    public static void main(String[] args)
	{

		int selectedOption;
		double fahrenheit;
		double cent;
		double inches;
		double centimetres;
		double kilos;
		double pounds;

		System.out.println("Enter the number of the menu option that you would like to use: \n \n 1. Fahrenheit to celcius \n 2.	Celcius to Fahrenheit \n 3.	Inches to centimetres \n 4.	Centimetres to inches \n 5.	Pounds to Kilograms \n");
		selectedOption = EasyIn.getInt();

		switch (selectedOption )
		{
			// Fahrenheit to celcius
			case 1:

					System.out.println("Enter the tempature in Fahrenheit ->  ");
					fahrenheit = EasyIn.getDouble();

					cent = (fahrenheit - 32) * 5 / 9;

			   		System.out.println("The tempature converted to degrees is: " + cent);

			break;

			// Celcius to Fahrenheit
			case 2:

					System.out.println("Enter the tempature in Degrees Cent ->  ");
					cent = EasyIn.getDouble();

					fahrenheit = (cent * 9 / 5) + 32;

			   		System.out.println("The tempature converted to Fahrenheit is: " + cent);

			break;

			// Inches to centimetres
			case 3:

					System.out.print("Enter the size in inches ->  ");
					inches = EasyIn.getDouble();

					centimetres = inches  * 2.54;

			  		System.out.println( inches + "inches converts to  " + centimetres + " centimetres");

			break;

			// Centimetres to inches
			case 4:

				    System.out.print("Enter the size in centimetres ->  ");
					centimetres = EasyIn.getDouble();

					inches = centimetres  / 2.54;

			  		System.out.println( centimetres + "centimetres converts to  " + inches + " inches");

			break;

			// Pounds to Kilograms
			case 5:

				    System.out.print("Enter the size in pounds ->  ");
					pounds = EasyIn.getDouble();

					kilos = pounds  / 2.2;

			  		System.out.println( pounds + "pounds converts to  " + kilos + " kilograms");

			break;
		}
	}
}


text:
package info.bitrich.xchangestream.binance.dto;

import static org.junit.Assert.assertEquals;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map.Entry;
import org.junit.BeforeClass;
import org.junit.Test;
import org.knowm.xchange.binance.dto.marketdata.BinanceOrderbook;

public class DepthBinanceWebSocketTransactionTest {
  private static ObjectMapper mapper;

  @BeforeClass
  public static void setupClass() {
    JsonFactory jf = new JsonFactory();
    jf.enable(JsonParser.Feature.ALLOW_COMMENTS);
    mapper = new ObjectMapper(jf);
  }

  @Test
  public void testMapping() throws Exception {
    InputStream stream = this.getClass().getResourceAsStream("testDepthEvent.json");
    DepthBinanceWebSocketTransaction transaction =
        mapper.readValue(stream, DepthBinanceWebSocketTransaction.class);
    assertEquals(
        BaseBinanceWebSocketTransaction.BinanceWebSocketTypes.DEPTH_UPDATE,
        transaction.getEventType());

    BinanceOrderbook orderBook = transaction.getOrderBook();

    Iterator<Entry<BigDecimal, BigDecimal>> bidIterator = orderBook.bids.entrySet().iterator();
    assertOrderBookEntry(bidIterator, 0.10376590, 59.15767010);

    Iterator<Entry<BigDecimal, BigDecimal>> askIterator = orderBook.asks.entrySet().iterator();
    assertOrderBookEntry(askIterator, 0.10376586, 159.15767010);
    assertOrderBookEntry(askIterator, 0.10383109, 345.86845230);
    assertOrderBookEntry(askIterator, 0.10490700, 0.00000000);
  }

  private void assertOrderBookEntry(
      Iterator<Entry<BigDecimal, BigDecimal>> entryIterator, double price, double volume) {
    Entry<BigDecimal, BigDecimal> firstAskEntry = entryIterator.next();
    assertEquals(price, firstAskEntry.getKey().doubleValue(), 0.0);
    assertEquals(volume, firstAskEntry.getValue().doubleValue(), 0.0);
  }
}


text:
A `vGraph Node` in the underlying graph. Inherits from [Element](element.md).

## ID
[See Element](element.md).

## Label
[See Element](element.md).

## Properties
[See Element](element.md).

### __repo
A repository identifier marking this Node as a boundary Node.

**Value:** [Repo](../definitions/repo.md).

**Note:** Set on creation if this `vGraph Node` is a boundary Node.

**Note:** This may not be the same repository identifier used for this vGraph instance.

### __origRepo
The value of `__repo` before it was modified.

**Value:** [Repo](../definitions/repo.md).

**Note:** This is set when `__status` is changed from `0` to `2`.

### Other Node Properties
[See Element](element.md).

**Note:** If `__repo` is set, no Element Properties are allowed to be set. Boundary Nodes have no local properties.


text:
package com.example.common.service;

import com.example.common.bean.ContentBean;

public interface CommonService {

    ContentBean sayHello();

}


text:
module Refinery::WordPress::SpecHelpers
  def test_dump
    file_name = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/wordpress_dump.xml'))
    Refinery::WordPress::Dump.new(file_name)
  end
end

RSpec.configure do |config|
  config.include Refinery::WordPress::SpecHelpers
end


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{

    protected $fillable = ['name'];

    //
    public function posts()
    {
        return $this->belongsToMany('App\Post');
    }
}


text:
GPs can often diagnose scarlet fever by looking at the tongue and rash.
Sometimes they may:

- wipe a cotton bud around the back of the throat to test for bacteria
- arrange a blood test

## Treating scarlet fever

Your GP will prescribe antibiotics. They don't cure scarlet fever, but will
help you get better quicker. They also reduce the risk of serious illnesses,
such as pneumonia.

It's important to keep taking antibiotics until they're finished, even when you
feel better.

### Things you can do yourself

You can relieve symptoms of scarlet fever by:

- drinking cool fluids
- eating soft foods to ease a sore throat
- taking painkillers like paracetamol to bring down a temperature (don't give
  aspirin to children under 16)
- using calamine lotion or antihistamine tablets to stop itching

## How long scarlet fever lasts

Scarlet fever lasts around a week.

You're infectious from up to 7 days before the symptoms start, until:

-  24 hours after you take the first antibiotic tablet
-  2 weeks after symptoms start - if you don't take antibiotics

## Is scarlet fever dangerous?

In the past scarlet fever was a serious illness, but antibiotics now mean
it's less common and easily treated.

Cases of scarlet fever have increased in recent years. Public Health England
records the [number of scarlet fever infections each year](https://www.gov.uk/government/publications/group-a-streptococcal-infections-activity-during-the-2016-to-2017-season).

Complications are rare but can include:

- ear infection
- throat abscess
- pneumonia
- meningitis
- rheumatic fever

People with the skin condition impetigo are more prone to complications.

## How to avoid spreading scarlet fever

Scarlet fever is very infectious and easily spread to other people.

To reduce the risk of spreading scarlet fever:

- wash hands often with warm water and soap
- use tissues to trap germs from coughs or sneezes
- bin used tissues as quickly as possible
- avoid sharing cutlery, cups towels, baths, clothes or bedding


text:
package org.iidp.ostmap.commons.accumulo;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.flink.util.Collector;
import org.iidp.ostmap.stream_processing.functions.TermExtraction;
import org.iidp.ostmap.commons.tokenizer.*;
import org.iidp.ostmap.stream_processing.types.RawTwitterDataKey;
import org.iidp.ostmap.stream_processing.types.TermIndexKey;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.Tuple2;

import java.io.IOException;
import java.util.ArrayList;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Testclass for TermExtraction
 * Tests extraction of all tokens
 */

public class TermExtractionTest {

    private static String tweet;
    private static ArrayList<String> listOfTokens;

    @BeforeClass
    public static void prepareData() throws AccumuloException, AccumuloSecurityException, InterruptedException, IOException {
        tweet = "{\"created_at\":\"Fri Apr 29 09:05:55 +0000 2016\",\"id\":725974381906804738,\"id_str\":\"725974381906804738\",\"text\":\"Das sage ich dir gleich, das funktioniert doch nie! #haselnuss\",\"user\":{\"id\":179905182,\"name\":\"Peter Tosh\",\"screen_name\":\"PeTo\",}}";
        String tweet_text = "Das sage ich dir gleich, das funktioniert doch nie! #haselnuss";
        Tokenizer t = new Tokenizer();
        listOfTokens = (ArrayList<String>) t.tokenizeString(tweet_text);
    }

    @Test
    public void testSomething() throws Exception {

        TermExtraction tE = new TermExtraction();
        RawTwitterDataKey rtdKey = new RawTwitterDataKey();
        Tuple2<RawTwitterDataKey, String> input = new Tuple2<>(rtdKey, tweet);

        Collector collector = new Collector<Tuple2<TermIndexKey, Integer>>() {
            @Override
            public void collect(Tuple2<TermIndexKey, Integer> record) {
                assertTrue(listOfTokens.contains(record._1.term));
                assertEquals(record._1.source, TermIndexKey.SOURCE_TYPE_TEXT);
                listOfTokens.remove(record._1.term);
            }

            @Override
            public void close() {
                assertTrue(listOfTokens.size()==0);
            }
        };

        tE.flatMap(input, collector);

    }
}


text:
package org.apache.drill.exec.store.easy.json.loader;

import org.apache.drill.exec.vector.accessor.ScalarWriter;

/**
 * Value listener for JSON string values. Allows conversion from
 * other scalar types using the Java {@code toString()} semantics.
 * Use the "text-mode" hint in a provided schema to get the literal
 * JSON value.
 */
public class VarCharListener extends ScalarListener {

  private final boolean classicArrayNulls;

  public VarCharListener(JsonLoaderImpl loader, ScalarWriter writer) {
    super(loader, writer);
    classicArrayNulls = isArray ? loader.options().classicArrayNulls : false;
  }

  @Override
  public void onBoolean(boolean value) {
    writer.setString(Boolean.toString(value));
  }

  @Override
  public void onInt(long value) {
    writer.setString(Long.toString(value));
  }

  @Override
  public void onFloat(double value) {
    writer.setString(Double.toString(value));
  }

  @Override
  public void onString(String value) {
    writer.setString(value);
  }

  @Override
  protected void setArrayNull() {
    writer.setString(classicArrayNulls ? "null" : "");
  }
}


text:
if defined?(RailsAdmin)
  RailsAdmin.config do |config|
    config.excluded_models << [
        'AckRocketCmsCatalog::ItemImage', 'AckRocketCmsCatalog::ItemCategoryImage'
    ]
    config.excluded_models.flatten!
  end
end


text:
@import EAN13BarcodeGenerator;

static const CGRect kLabelFrame = {{0.0, 120.0},{320.0, 30.0}};
static const CGRect kBarCodeFrame = {{103.0, 155.0},{250.0, 100.0}};
static const CGRect kButtonFrame = {{85.0, 320.0},{150.0, 30.0}};
static const CGRect kTextFieldFrame = {{60.0, 270.0},{200.0, 30.0}};

@interface EAN13ViewControllerWithoutIB () <UITextFieldDelegate>
{
    BarCodeView *barCodeView;
    UIButton *button;
    UITextField *textField;
}
@end

@implementation EAN13ViewControllerWithoutIB

-(void)loadView
{
    CGFloat h =  [UIApplication sharedApplication].statusBarHidden ? 0 :
    [UIApplication sharedApplication].statusBarFrame.size.height;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, h,
                                                            [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - h)];
    view.backgroundColor = [UIColor lightGrayColor];

    barCodeView = [[BarCodeView alloc] initWithFrame:kBarCodeFrame];
    [view addSubview:barCodeView];

    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = kButtonFrame;
    [button addTarget:self action:@selector(generate)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Generate" forState:UIControlStateNormal];
    [view addSubview:button];

    textField = [[UITextField alloc] initWithFrame:kTextFieldFrame];
    textField.keyboardType = UIKeyboardTypeDecimalPad;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.delegate = self;
    [view addSubview:textField];

    UILabel *label = [[UILabel alloc] initWithFrame:kLabelFrame];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:20.0f];
    label.text = @"EAN-13";
    [view addSubview:label];

    self.view = view;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self generate];
}

- (void)setNumber:(NSString*)newNum
{
    [barCodeView setBarCode:newNum];
}

- (void)generate
{
    if (textField.text.length == 13)
    {
        [self setNumber:textField.text];
        return;
    }
    else if (textField.text.length > 0)
    {
        [textField lockAnimation];
        return;
    }
    [self setNumber:GetNewRandomEAN13BarCode()];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)aTextField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\u200B"] || [string isEqualToString:@""])
    {
        return YES; // detect backspase/delete
    }

    NSCharacterSet *set = [NSCharacterSet decimalDigitCharacterSet];
    if ([string rangeOfCharacterFromSet:set].location == NSNotFound)  return NO; //disallow any other except digits

    NSString *result = [aTextField.text stringByAppendingString:string];
    return result.length <= 13;
}

@end


text:
import { EvilRoleComponent } from "./EvilRoleComponent";
import { Roles, GameData } from "../../../../../shared/constants";
import { Game, GamePlayData, Role, Faction } from "../../../../../shared/models";

export class AssassinRoleComponent extends EvilRoleComponent {
    constructor() {
        super();
    }

    setupGame(game: Game, gamePlayData: GamePlayData) {
        let evilGenericPlayers: string[] = [];

        for (let playerName in gamePlayData.assignedRoles) {
            let role = gamePlayData.assignedRoles[playerName];
            if (role.faction === Faction.Evil && role.name === Roles.GenericEvil.name)
                evilGenericPlayers.push(playerName);
        }

        if (evilGenericPlayers.length > 0) {
            let random: number = Math.floor(Math.random() * evilGenericPlayers.length);
            gamePlayData.assignedRoles[evilGenericPlayers[random]] = Roles.Assassin;
        }

        return gamePlayData;
    }

}


text:
namespace crash_keys {

// The maximum lengths specified by breakpad include the trailing NULL, so
// the actual length of the string is one less.
#if defined(OS_MACOSX)
static const size_t kSingleChunkLength =
    google_breakpad::SimpleStringDictionary::value_size - 1;
#elif defined(OS_WIN)
static const size_t kSingleChunkLength =
    google_breakpad::CustomInfoEntry::kValueMaxLength - 1;
#else
static const size_t kSingleChunkLength = 63;
#endif

// Guarantees for crash key sizes.
static_assert(kSmallSize <= kSingleChunkLength,
              "crash key chunk size too small");
#if defined(OS_MACOSX)
static_assert(kMediumSize <= kSingleChunkLength,
              "mac has medium size crash key chunks");
#endif

const char kActiveURL[] = "url-chunk";

const char kFontKeyName[] = "font_key_name";

const char kSwitch[] = "switch-%" PRIuS;
const char kNumSwitches[] = "num-switches";

const char kExtensionID[] = "extension-%" PRIuS;
const char kNumExtensionsCount[] = "num-extensions";

const char kShutdownType[] = "shutdown-type";

#if !defined(OS_ANDROID)
const char kGPUVendorID[] = "gpu-venid";
const char kGPUDeviceID[] = "gpu-devid";
#endif
const char kGPUDriverVersion[] = "gpu-driver";
const char kGPUPixelShaderVersion[] = "gpu-psver";
const char kGPUVertexShaderVersion[] = "gpu-vsver";
#if defined(OS_MACOSX)
const char kGPUGLVersion[] = "gpu-glver";
#elif defined(OS_POSIX)
const char kGPUVendor[] = "gpu-gl-vendor";
const char kGPURenderer[] = "gpu-gl-renderer";
#endif

const char kPrinterInfo[] = "prn-info-%" PRIuS;

#if defined(OS_CHROMEOS)
const char kNumberOfUsers[] = "num-users";
#endif

#if defined(OS_MACOSX)
namespace mac {

const char kFirstNSException[] = "firstexception";
const char kFirstNSExceptionTrace[] = "firstexception_bt";

const char kLastNSException[] = "lastexception";
const char kLastNSExceptionTrace[] = "lastexception_bt";

const char kNSException[] = "nsexception";
const char kNSExceptionTrace[] = "nsexception_bt";

const char kSendAction[] = "sendaction";

}  // namespace mac
#endif

#if defined(KASKO)
const char kKaskoGuid[] = "kasko-guid";
const char kKaskoEquivalentGuid[] = "kasko-equivalent-guid";
#endif

const char kViewCount[] = "view-count";

size_t RegisterChromeCrashKeys() {
  // The following keys may be chunked by the underlying crash logging system,
  // but ultimately constitute a single key-value pair.
  base::debug::CrashKey fixed_keys[] = {
#if defined(OS_MACOSX)
    { kMetricsClientId, kSmallSize },
#else
    { kClientId, kSmallSize },
#endif
    { kChannel, kSmallSize },
    { kActiveURL, kLargeSize },
    { kNumSwitches, kSmallSize },
    { kNumVariations, kSmallSize },
    { kVariations, kLargeSize },
    { kNumExtensionsCount, kSmallSize },
    { kShutdownType, kSmallSize },
#if !defined(OS_ANDROID)
    { kGPUVendorID, kSmallSize },
    { kGPUDeviceID, kSmallSize },
#endif
    { kGPUDriverVersion, kSmallSize },
    { kGPUPixelShaderVersion, kSmallSize },
    { kGPUVertexShaderVersion, kSmallSize },
#if defined(OS_MACOSX)
    { kGPUGLVersion, kSmallSize },
#elif defined(OS_POSIX)
    { kGPUVendor, kSmallSize },
    { kGPURenderer, kSmallSize },
#endif

    // content/:
    { "discardable-memory-allocated", kSmallSize },
    { "discardable-memory-free", kSmallSize },
    { kFontKeyName, kSmallSize},
    { "ppapi_path", kMediumSize },
    { "subresource_url", kLargeSize },
    { "total-discardable-memory-allocated", kSmallSize },
#if defined(OS_CHROMEOS)
    { kNumberOfUsers, kSmallSize },
#endif
#if defined(OS_MACOSX)
    { mac::kFirstNSException, kMediumSize },
    { mac::kFirstNSExceptionTrace, kMediumSize },
    { mac::kLastNSException, kMediumSize },
    { mac::kLastNSExceptionTrace, kMediumSize },
    { mac::kNSException, kMediumSize },
    { mac::kNSExceptionTrace, kMediumSize },
    { mac::kSendAction, kMediumSize },
    { mac::kZombie, kMediumSize },
    { mac::kZombieTrace, kMediumSize },
    // content/:
    { "channel_error_bt", kMediumSize },
    { "remove_route_bt", kMediumSize },
    { "rwhvm_window", kMediumSize },
    // media/:
    { "VideoCaptureDeviceQTKit", kSmallSize },
#endif
#if defined(KASKO)
    { kKaskoGuid, kSmallSize },
    { kKaskoEquivalentGuid, kSmallSize },
#endif
    { kBug464926CrashKey, kSmallSize },
    { kViewCount, kSmallSize },
  };

  // This dynamic set of keys is used for sets of key value pairs when gathering
  // a collection of data, like command line switches or extension IDs.
  std::vector<base::debug::CrashKey> keys(
      fixed_keys, fixed_keys + arraysize(fixed_keys));

  // Register the switches.
  {
    // The fixed_keys names are string constants. Use static storage for
    // formatted key names as well, since they will persist for the duration of
    // the program.
    static char formatted_keys[kSwitchesMaxCount][sizeof(kSwitch) + 1] =
        {{ 0 }};
    const size_t formatted_key_len = sizeof(formatted_keys[0]);
    for (size_t i = 0; i < kSwitchesMaxCount; ++i) {
      // Name the keys using 1-based indexing.
      int n = base::snprintf(
          formatted_keys[i], formatted_key_len, kSwitch, i + 1);
      DCHECK_GT(n, 0);
      base::debug::CrashKey crash_key = { formatted_keys[i], kSmallSize };
      keys.push_back(crash_key);
    }
  }

  // Register the extension IDs.
  {
    static char formatted_keys[kExtensionIDMaxCount][sizeof(kExtensionID) + 1] =
        {{ 0 }};
    const size_t formatted_key_len = sizeof(formatted_keys[0]);
    for (size_t i = 0; i < kExtensionIDMaxCount; ++i) {
      int n = base::snprintf(
          formatted_keys[i], formatted_key_len, kExtensionID, i + 1);
      DCHECK_GT(n, 0);
      base::debug::CrashKey crash_key = { formatted_keys[i], kSmallSize };
      keys.push_back(crash_key);
    }
  }

  // Register the printer info.
  {
    static char formatted_keys[kPrinterInfoCount][sizeof(kPrinterInfo) + 1] =
        {{ 0 }};
    const size_t formatted_key_len = sizeof(formatted_keys[0]);
    for (size_t i = 0; i < kPrinterInfoCount; ++i) {
      // Key names are 1-indexed.
      int n = base::snprintf(
          formatted_keys[i], formatted_key_len, kPrinterInfo, i + 1);
      DCHECK_GT(n, 0);
      base::debug::CrashKey crash_key = { formatted_keys[i], kSmallSize };
      keys.push_back(crash_key);
    }
  }

  return base::debug::InitCrashKeys(&keys.at(0), keys.size(),
                                    kSingleChunkLength);
}

static bool IsBoringSwitch(const std::string& flag) {
  static const char* const kIgnoreSwitches[] = {
    switches::kEnableLogging,
    switches::kFlagSwitchesBegin,
    switches::kFlagSwitchesEnd,
    switches::kLoggingLevel,
#if defined(OS_WIN)
    // This file is linked into both chrome.dll and chrome.exe. However //ipc
    // is only in the .dll, so this needs to be a literal rather than the
    // constant.
    "channel",  // switches::kProcessChannelID
#else
    switches::kProcessChannelID,
#endif
    switches::kProcessType,
    switches::kV,
    switches::kVModule,
#if defined(OS_WIN)
    switches::kForceFieldTrials,
    switches::kPluginPath,
#elif defined(OS_MACOSX)
    switches::kMetricsClientID,
#elif defined(OS_CHROMEOS)
    switches::kPpapiFlashArgs,
    switches::kPpapiFlashPath,
    switches::kRegisterPepperPlugins,
    switches::kUIPrioritizeInGpuProcess,
    switches::kUseGL,
    switches::kUserDataDir,
    // Cros/CC flags are specified as raw strings to avoid dependency.
    "child-wallpaper-large",
    "child-wallpaper-small",
    "default-wallpaper-large",
    "default-wallpaper-small",
    "guest-wallpaper-large",
    "guest-wallpaper-small",
    "enterprise-enable-forced-re-enrollment",
    "enterprise-enrollment-initial-modulus",
    "enterprise-enrollment-modulus-limit",
    "login-profile",
    "login-user",
    "max-unused-resource-memory-usage-percentage",
    "termination-message-file",
    "use-cras",
#endif
  };

#if defined(OS_WIN)
  // Just about everything has this, don't bother.
  if (base::StartsWith(flag, "/prefetch:", base::CompareCase::SENSITIVE))
    return true;
#endif

  if (!base::StartsWith(flag, "--", base::CompareCase::SENSITIVE))
    return false;
  size_t end = flag.find("=");
  size_t len = (end == std::string::npos) ? flag.length() - 2 : end - 2;
  for (size_t i = 0; i < arraysize(kIgnoreSwitches); ++i) {
    if (flag.compare(2, len, kIgnoreSwitches[i]) == 0)
      return true;
  }
  return false;
}

void SetSwitchesFromCommandLine(const base::CommandLine* command_line) {
  DCHECK(command_line);
  if (!command_line)
    return;

  const base::CommandLine::StringVector& argv = command_line->argv();

  // Set the number of switches in case size > kNumSwitches.
  base::debug::SetCrashKeyValue(kNumSwitches,
      base::StringPrintf("%" PRIuS, argv.size() - 1));

  size_t key_i = 1;  // Key names are 1-indexed.

  // Go through the argv, skipping the exec path.
  for (size_t i = 1; i < argv.size(); ++i) {
#if defined(OS_WIN)
    std::string switch_str = base::WideToUTF8(argv[i]);
#else
    std::string switch_str = argv[i];
#endif

    // Skip uninteresting switches.
    if (IsBoringSwitch(switch_str))
      continue;

    // Stop if there are too many switches.
    if (i > crash_keys::kSwitchesMaxCount)
      break;

    std::string key = base::StringPrintf(kSwitch, key_i++);
    base::debug::SetCrashKeyValue(key, switch_str);
  }

  // Clear any remaining switches.
  for (; key_i <= kSwitchesMaxCount; ++key_i) {
    base::debug::ClearCrashKey(base::StringPrintf(kSwitch, key_i));
  }
}

void SetActiveExtensions(const std::set<std::string>& extensions) {
  base::debug::SetCrashKeyValue(kNumExtensionsCount,
      base::StringPrintf("%" PRIuS, extensions.size()));

  std::set<std::string>::const_iterator it = extensions.begin();
  for (size_t i = 0; i < kExtensionIDMaxCount; ++i) {
    std::string key = base::StringPrintf(kExtensionID, i + 1);
    if (it == extensions.end()) {
      base::debug::ClearCrashKey(key);
    } else {
      base::debug::SetCrashKeyValue(key, *it);
      ++it;
    }
  }
}

ScopedPrinterInfo::ScopedPrinterInfo(const base::StringPiece& data) {
  std::vector<std::string> info = base::SplitString(
      data.as_string(), ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  for (size_t i = 0; i < kPrinterInfoCount; ++i) {
    std::string key = base::StringPrintf(kPrinterInfo, i + 1);
    std::string value;
    if (i < info.size())
      value = info[i];
    base::debug::SetCrashKeyValue(key, value);
  }
}

ScopedPrinterInfo::~ScopedPrinterInfo() {
  for (size_t i = 0; i < kPrinterInfoCount; ++i) {
    std::string key = base::StringPrintf(kPrinterInfo, i + 1);
    base::debug::ClearCrashKey(key);
  }
}

}  // namespace crash_keys


text:
from django.contrib import admin

from libs import admin
from .models import Business, Praxis, JobPosting
from . import strings

class BusinessAdmin(admin.ModelAdmin):
    list_display = ('get_email', 'number_offices', 'is_mso',
        'number_employees',)
    search_fields = ('user__email', 'user__userregistration__first_name',
        'user__userregistration__last_name',
        'user__userregistration__personal_address',
        'user__userregistration__personal_zip_code',
        'user__userregistration__personal_city',
        'user__userregistration__personal_state',
        'number_offices', 'is_mso', 'number_employees',)
    list_filter = ('number_offices', 'is_mso', 'number_employees',)

class PraxisAdmin(admin.ModelAdmin):
    list_display = ('get_email', 'company_name',)
    search_fields = ('company_name', 'contact_first_name', 'contact_last_name',
        'address', 'zip_code', 'city', 'state', 'solo_practitioner',
        'multi_practitioner', 'corporate', 'fee_for_service', 'insurance',
        'capitation_medicaid',)
    list_filter = ('solo_practitioner', 'multi_practitioner', 'corporate',
        'fee_for_service', 'insurance', 'capitation_medicaid',)
    fieldsets = (
        (None, {
            'fields': ('business', 'is_active',)
        }),
        (strings.ADMIN_CONTACT_INFO, {
            'fields': ('company_name', 'contact_first_name',
            'contact_last_name',)
        }),
        (strings.ADMIN_PRAXIS_LOCATION, {
            'fields': ('address', 'zip_code', 'city', 'state',)
        }),
        (strings.ADMIN_PRACTICE_TYPE, {
            'fields': ('solo_practitioner', 'multi_practitioner', 'corporate',)
        }),
        (strings.ADMIN_PATIENTS_PAYMENT_METHOD, {
            'fields': ('fee_for_service', 'insurance', 'capitation_medicaid',)
        }),
    )

class JobPostingAdmin(admin.ModelAdmin):
    list_display = ('position_name', 'posting_title',)
    search_fields = ('position_name', 'posting_title', 'job_position',
        'schedule_type', 'monday_daytime', 'monday_evening', 'tuesday_daytime',
        'tuesday_evening', 'wednesday_daytime', 'wednesday_evening',
        'thursday_daytime', 'thursday_evening', 'friday_daytime',
        'friday_evening', 'saturday_daytime', 'saturday_evening',
        'sunday_daytime', 'sunday_evening', 'compensation_type', 'hourly_wage',
        'annualy_wage', 'experience_years', 'benefit_1', 'benefit_2',
        'benefit_3', 'benefit_4', 'benefit_5', 'benefit_6', 'benefit_other',
        'benefit_other_text', 'additional_comments', 'is_posted',)
    list_filter = ('schedule_type', 'monday_daytime', 'monday_evening',
        'tuesday_daytime', 'tuesday_evening', 'wednesday_daytime',
        'wednesday_evening', 'thursday_daytime', 'thursday_evening',
        'friday_daytime', 'friday_evening', 'saturday_daytime',
        'saturday_evening', 'sunday_daytime', 'sunday_evening',
        'compensation_type', 'hourly_wage', 'annualy_wage', 'experience_years',
        'benefit_1', 'benefit_2', 'benefit_3', 'benefit_4', 'benefit_5',
        'benefit_6', 'benefit_other',)
    fieldsets = (
        (None, {
            'fields': ('praxis', 'is_posted', 'is_active',)
        }),
        (strings.ADMIN_GENERAL_INFO, {
            'fields': ('position_name', 'posting_title',)
        }),
        (strings.ADMIN_JOB_POSTING_OFFERED, {
            'fields': ('job_position',)
        }),
        (strings.ADMIN_SCHEDULE_TYPE, {
            'fields': ('schedule_type', 'monday_daytime', 'monday_evening',
            'tuesday_daytime', 'tuesday_evening', 'wednesday_daytime',
            'wednesday_evening', 'thursday_daytime', 'thursday_evening',
            'friday_daytime', 'friday_evening', 'saturday_daytime',
            'saturday_evening', 'sunday_daytime', 'sunday_evening',)
        }),
        (strings.ADMIN_COMPENSATION, {
            'fields': ('compensation_type', 'hourly_wage', 'annualy_wage',
            'production', 'collection',)
        }),
        (strings.ADMIN_EXPERIENCE_REQUIRED, {
            'fields': ('experience_years',)
        }),
        (strings.ADMIN_BENEFITS_BEING_OFFERED, {
            'fields': ('benefit_1', 'benefit_2', 'benefit_3', 'benefit_4',
            'benefit_5', 'benefit_6', 'benefit_other', 'benefit_other_text',)
        }),
    )

admin.site.add_callbacks(
    lambda sender, request, **kwargs: Praxis.show_inactive(),
    lambda sender, request, **kwargs: JobPosting.show_inactive())
admin.site.register(Business, BusinessAdmin)
admin.site.register(Praxis, PraxisAdmin)
admin.site.register(JobPosting, JobPostingAdmin)


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Titus 3 (ASV)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />

American Standard VersionTitus 3<
=
>

3

1 Put them in mind to be in subjection to rulers, to authorities, to be obedient, to be ready unto every good work,
2 to speak evil of no man, not to be contentious, to be gentle, showing all meekness toward all men.
3 For we also once were foolish, disobedient, deceived, serving divers lusts and pleasures, living in malice and envy, hateful, hating one another.
4 But when the kindness of God our Saviour, and his love toward man, appeared,
5 not by works done in righteousness, which we did ourselves, but according to his mercy he saved us, through the washing of regeneration and renewing of the Holy Spirit,
6 which he poured out upon us richly, through Jesus Christ our Saviour;
7 that, being justified by his grace, we might be made heirs according to the hope of eternal life.
8 Faithful is the saying, and concerning these things I desire that thou affirm confidently, to the end that they who have believed God may be careful to maintain good works. These things are good and profitable unto men:
9 but shun foolish questionings, and genealogies, and strifes, and fightings about the law; for they are unprofitable and vain.
10 A factious man after a first and second admonition refuse;
11 knowing that such a one is perverted, and sinneth, being self-condemned.
12 When I shall send Artemas unto thee, or Tychicus, give diligence to come unto me to Nicopolis: for there I have determined to winter.
13 Set forward Zenas the lawyer and Apollos on their journey diligently, that nothing be wanting unto them.
14 And let our people also learn to maintain good works for necessary uses, that they be not unfruitful.
15 All that are with me salute thee. Salute them that love us in faith. Grace be with you all.

<
=
>


text:
import collections
import unittest
import six
import imath

import IECore

import Gaffer
import GafferTest

class RandomChoiceTest( GafferTest.TestCase ) :

	def testSetup( self ) :

		for plugType, valuesPlugType in [
			( Gaffer.BoolPlug, Gaffer.BoolVectorDataPlug ),
			( Gaffer.IntPlug, Gaffer.IntVectorDataPlug ),
			( Gaffer.FloatPlug, Gaffer.FloatVectorDataPlug ),
			( Gaffer.StringPlug, Gaffer.StringVectorDataPlug ),
			( Gaffer.V2iPlug, Gaffer.V2iVectorDataPlug ),
			( Gaffer.V3fPlug, Gaffer.V3fVectorDataPlug ),
			( Gaffer.Color3fPlug, Gaffer.Color3fVectorDataPlug ),
		] :

			examplePlug = plugType()
			self.assertTrue( Gaffer.RandomChoice.canSetup( examplePlug ) )

			node = Gaffer.RandomChoice()
			node.setup( examplePlug )
			self.assertIsInstance( node["out"], plugType )
			self.assertFalse( node["out"].isSame( examplePlug ) )
			self.assertIsNone( examplePlug.getInput() )
			self.assertEqual( node["out"].defaultValue(), examplePlug.defaultValue() )

			self.assertIsInstance( node["choices"]["values"], valuesPlugType )
			self.assertEqual( len( node["choices"]["values"].getValue() ), 0 )

			with six.assertRaisesRegex( self, Exception, "Already set up" ) :
				node.setup( examplePlug )

		for unsupportedPlug in [
			Gaffer.CompoundDataPlug(),
			Gaffer.CompoundObjectPlug( defaultValue = IECore.CompoundObject() ),
		] :
			self.assertFalse( Gaffer.RandomChoice.canSetup( unsupportedPlug ) )
			node = Gaffer.RandomChoice()
			with six.assertRaisesRegex( self, RuntimeError, "Unsupported plug type" ) :
				node.setup( unsupportedPlug )

	def testChoice( self ) :

		node = Gaffer.RandomChoice()

		node.setup( Gaffer.StringPlug() )
		node["choices"]["values"].setValue( IECore.StringVectorData( [ "apple", "pear", "hat" ] ) )
		node["choices"]["weights"].setValue( IECore.FloatVectorData( [ 0.25, 0.5, 0.25 ] ) )

		iterations = 100000

		count = collections.Counter()
		for seed in range( 0, iterations ) :
			node["seed"].setValue( seed )
			count[node["out"].getValue()] += 1

		for choice, weight in zip( node["choices"]["values"].getValue(), node["choices"]["weights"].getValue() ) :
			self.assertAlmostEqual(
				count[choice] / float( iterations ), weight,
				places = 2
			)

	def testSeedVariable( self ) :

		node = Gaffer.RandomChoice()

		node.setup( Gaffer.StringPlug() )
		node["seedVariable"].setValue( "seed" )
		node["choices"]["values"].setValue( IECore.StringVectorData( [ "apple", "pear", "hat" ] ) )
		node["choices"]["weights"].setValue( IECore.FloatVectorData( [ 0.25, 0.5, 0.25 ] ) )

		iterations = 100000

		count = collections.Counter()
		with Gaffer.Context() as context :
			for seed in range( 0, iterations ) :
				context["seed"] = seed
				count[node["out"].getValue()] += 1

		for choice, weight in zip( node["choices"]["values"].getValue(), node["choices"]["weights"].getValue() ) :
			self.assertAlmostEqual(
				count[choice] / float( iterations ), weight,
				places = 2
			)

	def testNoChoices( self ) :

		for defaultValue in range( 0, 10 ) :

			# Empty list of choices. Expect the default value
			# the node was set up with.
			node = Gaffer.RandomChoice()
			node.setup( Gaffer.IntPlug( defaultValue = defaultValue ) )
			self.assertEqual( node["out"].getValue(), defaultValue )

			# Choices, but all with 0 weight. As above.
			node["choices"]["values"].setValue( IECore.IntVectorData( [ 1, 2, 3 ] ) )
			node["choices"]["weights"].setValue( IECore.FloatVectorData( [ 0, 0, 0 ] ) )
			self.assertEqual( node["out"].getValue(), defaultValue )

	def testSerialisation( self ) :

		script = Gaffer.ScriptNode()
		script["uninitialised"] = Gaffer.RandomChoice()
		script["initialised"] = Gaffer.RandomChoice()

		script["initialised"].setup( Gaffer.StringPlug( defaultValue = "default" )  )
		script["initialised"]["choices"]["values"].setValue( IECore.StringVectorData( [ "one", "two" ] ) )
		script["initialised"]["choices"]["weights"].setValue( IECore.FloatVectorData( [ 1.0, 2.0 ] ) )

		script2 = Gaffer.ScriptNode()
		script2.execute( script.serialise() )

		self.assertNotIn( "out", script2["uninitialised"] )
		self.assertNotIn( "values", script2["uninitialised"]["choices"] )

		self.assertEqual( script2["initialised"]["choices"]["values"].getValue(), script["initialised"]["choices"]["values"].getValue() )
		self.assertEqual( script2["initialised"]["out"].defaultValue(), script["initialised"]["out"].defaultValue() )

	def testCompoundNumericPlugs( self ) :

		node = Gaffer.RandomChoice()
		node.setup( Gaffer.V3fPlug() )
		node["choices"]["values"].setValue(
			IECore.V3fVectorData( [ imath.V3f( 1, 2, 3 ), imath.V3f( 4, 5, 6 ) ] )
		)
		node["choices"]["weights"].setValue(
			IECore.FloatVectorData( [ 0, 1.0 ] )
		)

		self.assertEqual( node["out"].getValue(), imath.V3f( 4, 5,6 ) )

	def testMismatchedLengths( self ) :

		node = Gaffer.RandomChoice()
		node.setup( Gaffer.StringPlug() )
		node["choices"]["values"].setValue(
			IECore.StringVectorData( [ "a", "b", "c" ] )
		)

		with six.assertRaisesRegex(
			self, Gaffer.ProcessException,
			r".*Length of `choices.weights` does not match length of `choices.values` \(0 but should be 3\).*"
		) :
			node["out"].getValue()

	@GafferTest.TestRunner.PerformanceTestMethod()
	def testPerformance( self ) :

		node = Gaffer.RandomChoice()
		node.setup( Gaffer.IntPlug() )
		node["seedVariable"].setValue( "seed" )
		node["choices"]["values"].setValue( IECore.IntVectorData( range( 0, 100000 ) ) )
		node["choices"]["weights"].setValue( IECore.FloatVectorData( [ 1 ] * 100000 ) )

		with GafferTest.TestRunner.PerformanceScope() :
			GafferTest.parallelGetValue( node["out"], 100000, "seed" )

if __name__ == "__main__":
	unittest.main()


text:
import React, { Component, PropTypes } from 'react'
import DesktopProductContainer from './DesktopProductContainer'
import MobileProductContainer from './MobileProductContainer'
import './Product.css'
import '../../public/vendor/css/font-awesome.min.css'

var MediaQuery = require('react-responsive')

class Product extends Component {
  componentDidMount() {
    this.props.actions.fetchProductIfNeeded(123654)
  }
  render() {
    return (

          {this.props.hasErrored &&

 {this.props.error}

          }

        <MediaQuery query='(min-device-width: 1224px)'>
          {this.props.isFetching ?
 Loading ...
 :
            <DesktopProductContainer product={this.props} />
          }
        </MediaQuery>
        <MediaQuery query='(max-device-width: 1224px)'>
          {this.props.isFetching ?
 Loading ...
 :
            <MobileProductContainer product={this.props} />
          }
        </MediaQuery>

    )
  }
}

Product.propTypes = {
  productData: PropTypes.object,
  title: PropTypes.string,
  images: PropTypes.array,
  price: PropTypes.string,
  pickupInStore: PropTypes.bool,
  availableOnline: PropTypes.bool,
  reviewData: PropTypes.object,
  promotions: PropTypes.array,
  returnPolicy: PropTypes.object,
  isFetching: PropTypes.bool.isRequired,
  hasErrored: PropTypes.bool,
  error: PropTypes.string,
  lastUpdated: PropTypes.number,
  dispatch: PropTypes.func,
  amountSelected: PropTypes.number,
  highlights: PropTypes.array,
  actions: PropTypes.object.isRequired
}

export default Product


text: A webapp to view and manage data of a LoopBack backend


text:
import { platformNativeScriptDynamic } from "nativescript-angular/platform";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    imports: [NativeScriptModule],
})
class AppComponentModule {}

platformNativeScriptDynamic().bootstrapModule(AppComponentModule);


text:
NSString * const UserDidLoginNotification = @"UserDidLoginNotification";
NSString * const UserDidLogoutNotification = @"UserDidLogoutNotification";
NSString * const kCurrentUserKey = @"kCurrentUserKey";

@implementation User

static User *_currentUser = nil;

+ (User *)currentUser {
    if (!_currentUser) {
        NSDictionary *userData = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrentUserKey];
        if (userData) {
            _currentUser = [[User alloc] initWithDictionary:userData];
        }
    }

    return _currentUser;
}

+ (void)setCurrentUser:(User *)currentUser {
    if (currentUser) {
        NSData *userData = [NSJSONSerialization dataWithJSONObject:currentUser.data options:NSJSONWritingPrettyPrinted error:nil];
        [[NSUserDefaults standardUserDefaults] setObject:userData forKey:kCurrentUserKey];
    } else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCurrentUserKey];
        [[TwitterClient instance] deauthorize];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];

    if (!_currentUser && currentUser) {
        _currentUser = currentUser; // Needs to be set before firing the notification
        [[NSNotificationCenter defaultCenter] postNotificationName:UserDidLoginNotification object:nil];
    } else if (_currentUser && !currentUser) {
        _currentUser = currentUser; // Needs to be set before firing the notification
        [[NSNotificationCenter defaultCenter] postNotificationName:UserDidLogoutNotification object:nil];
    }

}

@end