text:
Problème
--------
Glisser et déposer un élément sur la page web

Solution
--------

Brython implémente une API basée sur la spécification du HTML5 pour le glisser-déposer. Dans la forme basique présentée dans cet exemple, elle consiste à définir des fonctions de rappel pour 3 événements :
- _dragstart_ sur l'élément déplaçable (quand l'utilisateur commence à le faire glisser)
- _dragover_ sur la zone de destination (quand l'objet déplacé se positionne dessus)
- _drop_ sur la zone de destination (quand l'utilisateur relâche le bouton de la souris)

Pour attacher une fonction _rappel_ à un _evenement_ sur un _element_, on utiliser la méthode _element_.bind(_evenement,rappel_)

Les fonctions de rappel prennent un seul argument, une instance de `DOMEvent`. Pour communiquer des informations pendant l'opération de glisser-déposer, cette instance possède un attribut _data_ qui reçoit une valeur dans la fonction de rappel associée à _dragstart_ ; cette valeur est exploitée par la fonction de rappel associée à _drop_ pour identifier l'élement qui est en train d'être déposé

Dans l'exemple, quand l'objet déplaçable a été déposé, on ne peut plus le déplacer ; pour cela, nous supprimons les fonctions associées à un _evenement_ sur cet objet par la méthode _element_.unbind(_evenement_)

zone de destination

objet déplaçable

    from browser import document as doc

    panel = doc["panel"] # zone jaune

    source = doc["source"] # zone rouge
    # on la place à (10,10) du bord supérieur gauche du panel
    source.style.top = "%spx" %(10+panel.top)
    source.style.left = "%spx" %(10+panel.left)
    # rend la zone rouge déplaçable
    source.draggable = True

    dest = doc["dest"] # zone verte
    # on la place à (10,150) du bord supérieur gauche du panel
    dest.style.top = "%spx" %(10+panel.top)
    dest.style.left = "%spx" %(150+panel.left)

    # quand la souris passe sur l'objet déplaçable, changer le curseur
    def mouse_over(ev):
        print('voilà la souris !')
        ev.target.style.cursor = "pointer"

    # coordonnées de la souris relativement au bord supérieur gauche de l'objet
    # déplacé quand le glissement commence
    m0 = [None,None]

    # fonction appelée quand l'utilisateur commence à déplacer l'objet
    def drag_start(ev):
        global m0
        # calcul des coordonnées de la souris
        # ev.x et ev.y sont les coordonnées de la souris quand l'événement est déclenché
        # ev.target est l'objet déplacé. Ses attributs "left" et "top" sont des entiers,
        # la distance par rapport aux bords gauche et supérieur du document
        m0 = [ev.x-ev.target.left,ev.y-ev.target.top]
        # associer une donnée au processus de glissement
        ev.dataTransfer.setData('text',ev.target.id)
        # permet à l'object d'être déplacé dans l'objet destination
        ev.dataTransfer.effectAllowed = 'move'

    # fonction appelée quand l'objet déplaçable vient au-dessus de la zone de destination
    def drag_over(ev):
        ev.dataTransfer.dropEffect = 'move'
        # il faut désactiver le comportement par défaut pour ce genre d'événement
        ev.preventDefault()

    # fonction attachée à la zone de destination
    # Elle définit ce qui se passe quand l'objet est déposé, c'est-à-dire
    # quand l'utilisateur relâche la souris alors que l'objet est au-dessus de la zone
    def drop(ev):
        # récupère les données stockées dans drag_start (l'id de l'objet déplacé)
        src_id = ev.dataTransfer.getData('text')
        elt = doc[src_id]
        # définit les nouvelles coordonnées de l'objet déplacé
        elt.style.left = "%spx" %(ev.x-m0[0])
        elt.style.top = "%spx" %(ev.y-m0[1])
        # ne plus déplacer l'objet
        elt.draggable = False
        # enlever la fonction associée à mouseover
        elt.unbind('mouseover')
        elt.style.cursor = "auto"
        ev.preventDefault()

    # attache des fonctions aux événements sur l'objet déplaçable
    source.bind('mouseover',mouse_over)
    source.bind('dragstart',drag_start)

    # attache des fonctions aux événement sur la zone de destination
    dest.bind('dragover',drag_over)
    dest.bind('drop',drop)


text:
require 'rails_helper'

RSpec.describe User, :type => :model do
  it "is invalid if the first name is empty" do
    user = User.new
    user.first_name = "ng"
    user.save

    expect(user).to be_invalid
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>WinPcap: pcap_file_header Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="style.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Modules

Data Structures

Files

Data Structures

Data Fields

pcap_file_header Struct Reference

[Definitions]

Header of a libpcap dump file.
More...

#include <pcap.h>

Data Fields

bpf_u_int32 	magic

u_short 	version_major

 	Libpcap major version.

u_short 	version_minor

 	Libpcap minor version.

bpf_int32 	thiszone

 	gmt to local correction

bpf_u_int32 	sigfigs

 	accuracy of timestamps

bpf_u_int32 	snaplen

 	max length saved portion of each pkt

bpf_u_int32 	linktype

 	data link type (LINKTYPE_*)

Detailed Description

Header of a libpcap dump file.

The first record in the file contains saved values for some of the flags used in the printout phases of tcpdump. Many fields here are 32 bit ints so compilers won't insert unwanted padding; these files need to be interchangeable across architectures.

Do not change the layout of this structure, in any way (this includes changes that only affect the length of fields in this structure).

Also, do not change the interpretation of any of the members of this structure, in any way (this includes using values other than LINKTYPE_ values, as defined in "savefile.c", in the "linktype" field).

Instead:

introduce a new structure for the new format, if the layout of the structure changed;

send mail to "tcpdump-workers@tcpdump.org", requesting a new magic number for your new capture file format, and, when you get the new magic number, put it in "savefile.c";

use that magic number for save files with the changed file header;

make the code in "savefile.c" capable of reading files with the old file header as well as files with the new file header (using the magic number to determine the header format).

Then supply the changes to "patches@tcpdump.org", so that future versions of libpcap and programs that use it (such as tcpdump) will be able to read your new capture file format.

Definition at line 110 of file incs/pcap.h.

Field Documentation

          bpf_u_int32 linktype

data link type (LINKTYPE_*)

Definition at line 117 of file incs/pcap.h.

          bpf_u_int32 magic

Definition at line 111 of file incs/pcap.h.

          bpf_u_int32 sigfigs

accuracy of timestamps

Definition at line 115 of file incs/pcap.h.

          bpf_u_int32 snaplen

max length saved portion of each pkt

Definition at line 116 of file incs/pcap.h.

          bpf_int32 thiszone

gmt to local correction

Definition at line 114 of file incs/pcap.h.

          u_short version_major

Libpcap major version.

Definition at line 112 of file incs/pcap.h.

          u_short version_minor

Libpcap minor version.

Definition at line 113 of file incs/pcap.h.

The documentation for this struct was generated from the following file:

incs/pcap.h

documentation. Copyright (c) 2002-2005 Politecnico di Torino. Copyright (c) 2005-2009
CACE Technologies. All rights reserved.


text:
require 'spec_helper'

# Construct dummy classes
class Company
  include KingPlaceholder
  attr_accessor :name
  attr_accessor :clients    # has_many
  attr_accessor :user       # belongs_to
  has_placeholders :name
end

class User
  include KingPlaceholder
  attr_accessor :email
  attr_accessor :company
  has_placeholders :email
end

class Client
  include KingPlaceholder
  attr_accessor :number, :money_field, :secret_field, :currency
  attr_accessor :company
  has_placeholders :number, :money_field
end

describe 'Class with placeholders' do

  before :each do
    @client = Client.new
    @client.number = 1002
    @client.money_field = 12.333
  end

  it 'should have native values' do
    @client.number.should == 1002
    @client.money_field.should == 12.333
  end

  it 'should have placeholder value' do
    @client.expand_placeholders('[number]').should == '1002'
    @client.expand_placeholders('[money_field]').should == '12.333'
  end
  it 'should expand placeholders in an array' do
    @client.expand_placeholders(['[number]', '[money_field]', 'static']).should == ['1002', '12.333', 'static']
  end

  it 'should expand placeholders in a hash' do
    @client.expand_placeholders( :key1 => '[number]',
                                 :key2 => '[money_field]',
                                 :key3 => 'static'
                                ).should ==
                                 { :key1 => '1002',
                                   :key2 => '12.333',
                                   :key3 => 'static' }
  end
end

describe 'Placeholder substitution' do

  before :each do
    I18n.locale = :en
    @user = User.new
    @user.email = 'a@b.com'
    @company = Company.new
    @company.name = 'BigMoney Inc.'
    @company.user = @user
    @user.company = @company

    @client = Client.new
    @client.number = 1001
    @client.money_field = 12.34
    @client.secret_field = 'top-secret'
    @client.company = @company

    @client_1 = Client.new
    @client_1.number = 1002
    @client_1.money_field = 45.67
    @client_1.secret_field = 'little secret'
    @client_1.company = @company
    @company.clients = [@client, @client_1]
  end

  context 'with direct lookup' do

    it 'should return without placeholders' do
      @client.expand_placeholders('without placeholder').should == 'without placeholder'
      @client.expand_placeholders('[]').should == '[]'
      @client.expand_placeholders('').should == ''
      @client.expand_placeholders(nil).should == nil
      @client.expand_placeholders("\n").should == "\n"
    end

    it 'should expand with simple fieldname' do
      @client.expand_placeholders('[number]').should == '1001'
      @client.expand_placeholders("[number]\n").should == "1001\n"
      @client.expand_placeholders('[number]---[number]--[money_field]').should == '1001---1001--12.34'
    end

    it 'should not parse unknown field' do
      @client.expand_placeholders('[secret_field]').should == 'UNKNOWN for Client: secret_field'
    end

    it 'should expand placeholder with not existing namespaces' do
      @client.expand_placeholders('[nothing.name]').should == 'UNKNOWN for Client: nothing.name'
    end

    it 'should expand placeholder with wrong namespaces' do
      @client.expand_placeholders('[company.this.are.too.much.namespaces]').should == 'UNKNOWN for Company: this.are.too.much.namespaces'
      @client.expand_placeholders('[this.are.too.much.namespaces]').should == 'UNKNOWN for Client: this.are.too.much.namespaces'
      @client.expand_placeholders('[...]').should == 'UNKNOWN for Client: ...'
      @client.expand_placeholders('[unknown]').should == 'UNKNOWN for Client: unknown'
    end
  end

  context 'with namespace' do

    it 'should parse referenced object fields' do
      @client.expand_placeholders('[company.name]').should == 'BigMoney Inc.'
      @client.expand_placeholders('[company.name] [number]').should == 'BigMoney Inc. 1001'
    end

    it 'should parse self referenced field' do
      @client.expand_placeholders('[client.number]').should == '1001'
      @client.expand_placeholders('[client.company.name] [client.number]').should == 'BigMoney Inc. 1001'
    end

    it 'should parse multiple steps' do
      @client.expand_placeholders('[company.user.email]').should == 'a@b.com'
    end

  end

  context 'with empty fields' do

    it 'should parse valid but empty placeholder group with empty string' do
      company = Company.new
      company.clients = []
      company.expand_placeholders('[clients][number][/clients]').should == ''
    end

    it 'should parse single item group with empty string' do
      @company.expand_placeholders('[clients.10.number]').should == ''
    end

    it 'should parse related object email with empty string' do
      @company.name = nil
      @client.expand_placeholders('[company.name]').should == ''
    end

    it 'should parse empty related object with empty string' do
      @client.company = nil
      @client.expand_placeholders('[company.name]').should == ''
      @client.expand_placeholders('[client.company.name]').should == ''
    end

  end

  context 'with collection' do
    it 'should expand' do
      @company.expand_placeholders('[clients][number]\n[/clients]').should == '1001\n1002\n'
      @company.expand_placeholders('[clients]Test:[number][/clients]').should == 'Test:1001Test:1002'
      @company.expand_placeholders("[clients][number]\n[/clients]").should == "1001\n1002\n"
      @company.expand_placeholders('[clients][foo][/clients]').should == 'UNKNOWN for Client: fooUNKNOWN for Client: foo'
    end

    it 'should expand single item ' do
      @company.expand_placeholders('[clients.1.number]').should == '1001'
      @company.expand_placeholders('[clients.2.number]').should == '1002'
    end

    it 'should show error for missing closing' do
      @company.expand_placeholders('[clients][number]').should == 'END MISSING FOR clientsUNKNOWN for Company: number'
    end
  end

  context 'with custom formatter' do
    before :each do
      I18n.locale = :en_company
    #    Thread.current[:default_currency_format] = I18n.t(:'number.currency.format')
    end

    xit 'should format money' do
      @client.expand_placeholders('[money_field]').should == '$12.34'
    end
  end

end


text:
#ifndef _REGISTER_CPU_FEATURES_H_
#define _REGISTER_CPU_FEATURES_H_
#include <PiPei.h>
#include <PiDxe.h>
#include <Ppi/MpServices.h>
#include <Protocol/MpService.h>

#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/PcdLib.h>
#include <Library/RegisterCpuFeaturesLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/SynchronizationLib.h>
#include <Library/IoLib.h>
#include <Library/LocalApicLib.h>

#include <AcpiCpuData.h>

#define CPU_FEATURE_ENTRY_SIGNATURE  SIGNATURE_32 ('C', 'F', 'E', 'S')

#define CPU_FEATURE_NAME_SIZE        128

typedef struct {
  REGISTER_CPU_FEATURE_INFORMATION     CpuInfo;
  UINT8                                *FeaturesSupportedMask;
  LIST_ENTRY                           OrderList;
} CPU_FEATURES_INIT_ORDER;

typedef struct {
  UINT32                       Signature;
  LIST_ENTRY                   Link;
  UINT8                        *FeatureMask;
  CHAR8                        *FeatureName;
  CPU_FEATURE_GET_CONFIG_DATA  GetConfigDataFunc;
  CPU_FEATURE_SUPPORT          SupportFunc;
  CPU_FEATURE_INITIALIZE       InitializeFunc;
  UINT8                        *BeforeFeatureBitMask;
  UINT8                        *AfterFeatureBitMask;
  UINT8                        *CoreBeforeFeatureBitMask;
  UINT8                        *CoreAfterFeatureBitMask;
  UINT8                        *PackageBeforeFeatureBitMask;
  UINT8                        *PackageAfterFeatureBitMask;
  VOID                         *ConfigData;
  BOOLEAN                      BeforeAll;
  BOOLEAN                      AfterAll;
} CPU_FEATURES_ENTRY;

//
// Flags used when program the register.
//
typedef struct {
  volatile UINTN           ConsoleLogLock;          // Spinlock used to control console.
  volatile UINTN           MemoryMappedLock;        // Spinlock used to program mmio
  volatile UINT32          *CoreSemaphoreCount;     // Semaphore containers used to program Core semaphore.
  volatile UINT32          *PackageSemaphoreCount;  // Semaphore containers used to program Package semaphore.
} PROGRAM_CPU_REGISTER_FLAGS;

typedef union {
  EFI_MP_SERVICES_PROTOCOL  *Protocol;
  EFI_PEI_MP_SERVICES_PPI   *Ppi;
} MP_SERVICES;

typedef struct {
  UINTN                    FeaturesCount;
  UINT32                   BitMaskSize;
  LIST_ENTRY               FeatureList;

  CPU_FEATURES_INIT_ORDER  *InitOrder;
  UINT8                    *SupportPcd;
  UINT8                    *CapabilityPcd;
  UINT8                    *ConfigurationPcd;
  UINT8                    *SettingPcd;

  UINT32                   NumberOfCpus;
  ACPI_CPU_DATA            *AcpiCpuData;

  CPU_REGISTER_TABLE       *RegisterTable;
  CPU_REGISTER_TABLE       *PreSmmRegisterTable;
  UINTN                    BspNumber;

  PROGRAM_CPU_REGISTER_FLAGS  CpuFlags;

  MP_SERVICES              MpService;
} CPU_FEATURES_DATA;

#define CPU_FEATURE_ENTRY_FROM_LINK(a) \
  CR ( \
  (a), \
  CPU_FEATURES_ENTRY, \
  Link, \
  CPU_FEATURE_ENTRY_SIGNATURE \
  )

/**
  Worker function to get CPU_FEATURES_DATA pointer.

  @return Pointer to CPU_FEATURES_DATA.
**/
CPU_FEATURES_DATA *
GetCpuFeaturesData (
  VOID
  );

/**
  Worker function to return processor index.

  @param  CpuFeaturesData    Cpu Feature Data structure.

  @return  The processor index.
**/
UINTN
GetProcessorIndex (
  IN CPU_FEATURES_DATA        *CpuFeaturesData
  );

/**
  Gets detailed MP-related information on the requested processor at the
  instant this call is made.

  @param[in]  ProcessorNumber       The handle number of processor.
  @param[out] ProcessorInfoBuffer   A pointer to the buffer where information for
                                    the requested processor is deposited.

  @return Status of MpServices->GetProcessorInfo().
**/
EFI_STATUS
GetProcessorInformation (
  IN  UINTN                            ProcessorNumber,
  OUT EFI_PROCESSOR_INFORMATION        *ProcessorInfoBuffer
  );

/**
  Worker function to execute a caller provided function on all enabled APs.

  @param[in]  Procedure               A pointer to the function to be run on
                                      enabled APs of the system.
  @param[in]  MpEvent                 A pointer to the event to be used later
                                      to check whether procedure has done.
**/
VOID
StartupAPsWorker (
  IN  EFI_AP_PROCEDURE                 Procedure,
  IN  EFI_EVENT                        MpEvent
  );

/**
  Worker function to retrieve the number of logical processor in the platform.

  @param[out] NumberOfCpus                Pointer to the total number of logical
                                          processors in the system, including the BSP
                                          and disabled APs.
  @param[out] NumberOfEnabledProcessors   Pointer to the number of enabled logical
                                          processors that exist in system, including
                                          the BSP.
**/
VOID
GetNumberOfProcessor (
  OUT UINTN                            *NumberOfCpus,
  OUT UINTN                            *NumberOfEnabledProcessors
  );

/**
  Worker function to switch the requested AP to be the BSP from that point onward.

  @param[in] ProcessorNumber   The handle number of AP that is to become the new BSP.
**/
VOID
SwitchNewBsp (
  IN  UINTN                            ProcessorNumber
  );

/**
  Function that uses DEBUG() macros to display the contents of a a CPU feature bit mask.

  @param[in]  FeatureMask  A pointer to the CPU feature bit mask.
**/
VOID
DumpCpuFeatureMask (
  IN UINT8               *FeatureMask
  );

/**
  Dump CPU feature name or CPU feature bit mask.

  @param[in]  CpuFeature   Pointer to CPU_FEATURES_ENTRY
**/
VOID
DumpCpuFeature (
  IN CPU_FEATURES_ENTRY  *CpuFeature
  );

/**
  Return feature dependence result.

  @param[in]  CpuFeature            Pointer to CPU feature.
  @param[in]  Before                Check before dependence or after.
  @param[in]  NextCpuFeatureMask    Pointer to next CPU feature Mask.

  @retval     return the dependence result.
**/
CPU_FEATURE_DEPENDENCE_TYPE
DetectFeatureScope (
  IN CPU_FEATURES_ENTRY         *CpuFeature,
  IN BOOLEAN                    Before,
  IN UINT8                      *NextCpuFeatureMask
  );

/**
  Return feature dependence result.

  @param[in]  CpuFeature            Pointer to CPU feature.
  @param[in]  Before                Check before dependence or after.
  @param[in]  FeatureList           Pointer to CPU feature list.

  @retval     return the dependence result.
**/
CPU_FEATURE_DEPENDENCE_TYPE
DetectNoneNeighborhoodFeatureScope (
  IN CPU_FEATURES_ENTRY         *CpuFeature,
  IN BOOLEAN                    Before,
  IN LIST_ENTRY                 *FeatureList
  );

/**
  Programs registers for the calling processor.

  @param[in,out] Buffer  The pointer to private data buffer.

**/
VOID
EFIAPI
SetProcessorRegister (
  IN OUT VOID            *Buffer
  );

/**
  Return ACPI_CPU_DATA data.

  @return  Pointer to ACPI_CPU_DATA data.
**/
ACPI_CPU_DATA *
GetAcpiCpuData (
  VOID
  );

/**
  Worker function to get MP service pointer.

  @return MP_SERVICES variable.
**/
MP_SERVICES
GetMpService (
  VOID
  );

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center"
              android:orientation="vertical">

  <ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminateDrawable="@drawable/progress"/>

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dip"
    android:text="@string/progress_wait_message"
    android:textColor="@color/snooper_blue"
    android:textStyle="italic"/>
</LinearLayout>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.subsystems;

import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.StopLauncher;

/**
 *
 * @author Developer
 */

public class Launcher extends Subsystem {
    // Put methods for controlling this subsystem
    // here. Call these from Commands.

    Talon launcherTalon = new Talon(RobotMap.Launcher_Talon);
    Timer timer = new Timer();
    double launcherSpeed = -.8;
    double runTime = .65;
    boolean init = true;

    public boolean launch(){
        if(init){
            timer.start();
            timer.reset();
            init = false;
        }

        launcherTalon.set(launcherSpeed);

        if(timer.get()>=runTime){
            launcherTalon.set(0);
            timer.stop();
            timer.reset();
            init = true;
            return true;
        }
        return false;
    }

    public void nudge(){
        launcherTalon.set(launcherSpeed);
    }

    public void stop(){
        launcherTalon.set(0);
    }

    public void initDefaultCommand() {
        // Set the default command for a subsystem here.
        //setDefaultCommand(new MySpecialCommand());
        setDefaultCommand(new StopLauncher());

        }

}


text:
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>JwHung - Product Designer</title>
	<meta name="description" content="A Rising Product Designer.">
	<meta name="keywords" content="JwHung,Eduardo,Product Manager,Product Designer,UX,UI">
	<meta name="author" content="JwHung,jw@jwhung.cn">
	<link rel="shortcut icon" href="img/favicon.ico">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	<link rel="stylesheet" type="text/css" href="style/css/style.css">
	<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/animate.css/3.4.0/animate.css">
	<link rel="stylesheet" type="text/css" href="style/css/fonts.css">
	<link rel="stylesheet" type="text/css" href="style/css/nav.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

Jw Hung

Product Designer

						Work
						About
						Photo
						Blog
						Email

Scan and Add me.:)


text:
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
    http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
    version="1.0">
    <persistence-unit-metadata>
        <persistence-unit-defaults>
            <schema>INVERSIONES</schema>
        </persistence-unit-defaults>
    </persistence-unit-metadata>
</entity-mappings>


text:
//-- standard headers ----------------------------------------------------
#include <iostream>
#include <iomanip>
#include <vector>

//-- private headers -----------------------------------------------------
#include "logger.h"

//-- source control system ID (if needed)---------------------------------

//-- exported global variables - definitions (should be empty) -----------

//-- private constants ---------------------------------------------------
static const std::vector<std::string>
LogSeverityLevelMessage =
{"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"};

//-- private types -------------------------------------------------------

//-- private functions --------- declarations ----------------------------

//-- private global variables -- definitions (should be empty) -----------

//-- exported functions -------- definitions -----------------------------
// default constructor
logger::logger
(

) : m_stream(std::cout)
{

}

// construct using output stream
logger::logger
(
	std::ostream& outStream
) : m_stream(outStream)
{

}

// virtual destructor
logger::~logger()
{
	m_stream.flush();
}

// Copy constructor
logger::logger
(
	const logger& object
) : m_stream(object.m_stream)
{

}

// Assignment operator
const logger&
logger::operator=
(
	const logger& rhs
)
{
	m_stream.flush();
	m_stream.rdbuf(rhs.m_stream.rdbuf());
	return *this;
}

// append entry to log
void
logger::log
(
	const LogSeverityLevel lvl,
	std::string message
)
{
	// We dont't know target of m_stream, better be thread safe
	std::lock_guard<std::mutex> guard(m_mutex);
	m_stream << ""
			 << LogSeverityLevelMessage[lvl]
			 << " | " << message << std::endl;

}

//-- private functions --------- definitions -----------------------------


text:
package com.cody.xf.utils.http;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cody.yi on 2016/7/22.
 * 表单文件上传
 */
public class MultipartRequest<T> extends BaseRequest<T> {

    private final String twoHyphens = "--";
    private final String lineEnd = "\r\n";
    private final String boundary = "apiclient-" + System.currentTimeMillis();
    private final OnUploadListener mOnUploadListener;
    private Map<String, DataPart> mByteData = new HashMap<>();
    private int mProgress;
    private int mMax;

    /**
     * Default constructor with predefined header and post method.
     *
     * @param url           request destination
     * @param params        predefined custom header
     * @param listener      on success achieved 200 code from request
     * @param errorListener on error http or library timeout
     */
    public MultipartRequest(String url, Map<String, String> headers, Map<String, String> params, Map<String, DataPart>
            byteData, Type type, Response.Listener<T> listener, Response.ErrorListener errorListener, OnUploadListener onUploadListener) {
        super(Method.POST, url, headers, params, null, type, listener, errorListener, null);
        this.mByteData = byteData;
        this.mOnUploadListener = onUploadListener;
    }

    @Override
    public String getBodyContentType() {
        return "multipart/form-data; boundary=" + boundary;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        try {
            // populate text payload
            Map<String, String> params = getParams();
            if (params != null && params.size() > 0) {
                textParse(dos, params, getParamsEncoding());
            }

            // populate data byte payload
            Map<String, DataPart> data = getByteData();
            if (data != null && data.size() > 0) {
                dataParse(dos, data);
            }

            // close multipart form data after text and file data
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Custom method handle data payload.
     *
     * @return Map data part label with data byte
     * @throws AuthFailureError
     */
    protected Map<String, DataPart> getByteData() throws AuthFailureError {
        return mByteData;
    }

    /**
     * Parse string map into data output stream by key and value.
     *
     * @param dataOutputStream data output stream handle string parsing
     * @param params           string inputs collection
     * @param encoding         encode the inputs, default UTF-8
     * @throws IOException
     */
    private void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws
            IOException {
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
            }
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + encoding, uee);
        }
    }

    /**
     * Parse data into data output stream.
     *
     * @param dataOutputStream data output stream handle file attachment
     * @param data             loop through data
     * @throws IOException
     */
    private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException {
        mProgress = 0;
        mMax = data.size() * 10;
        for (Map.Entry<String, DataPart> entry : data.entrySet()) {
            if (mOnUploadListener != null) {
                mOnUploadListener.onProgress(mProgress, mMax);
            }
            buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
        }
        if (mOnUploadListener != null) {
            mOnUploadListener.onProgress(mMax, mMax);
        }
    }

    /**
     * Write string data into header and data output stream.
     *
     * @param dataOutputStream data output stream handle string parsing
     * @param parameterName    name of input
     * @param parameterValue   value of input
     * @throws IOException
     */
    private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws
            IOException {
        dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"");
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.write(parameterValue.getBytes());
        dataOutputStream.writeBytes(lineEnd);
    }

    /**
     * Write data file into header and data output stream.
     *
     * @param dataOutputStream data output stream handle data parsing
     * @param dataFile         data byte as DataPart from collection
     * @param fileName         name of data input
     * @throws IOException
     */
    private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String fileName) throws
            IOException {
        dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
                dataFile.getName() + "\"; filename=\"" + fileName + "\"" + lineEnd);
        if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {
            dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
        }
        dataOutputStream.writeBytes(lineEnd);

        ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
        int bytesAvailable = fileInputStream.available();
        int max = bytesAvailable;
        int progress = 0;

        int maxBufferSize = 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            progress = progress + bytesRead;
            mProgress = mProgress + progress * 10 / max;
            if (mOnUploadListener != null) {
                mOnUploadListener.onProgress(mProgress, mMax);
            }

            dataOutputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        dataOutputStream.writeBytes(lineEnd);
    }
}


text:
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/mman.h>

#include <rte_eal.h>

#include <rte_log.h>
#include <rte_memzone.h>
#include <rte_ring.h>

#include <cmdline_rdline.h>
#include <cmdline_parse.h>
#include <cmdline_socket.h>
#include <cmdline.h>

#include "qwctl.h"
#include "commands.h"
#include "../include/conf.h"

int *quota;
unsigned int *low_watermark;

static void
setup_shared_variables(void)
{
    const struct rte_memzone *qw_memzone;

    qw_memzone = rte_memzone_lookup(QUOTA_WATERMARK_MEMZONE_NAME);
    if (qw_memzone == NULL)
        rte_exit(EXIT_FAILURE, "Couldn't find memzone\n");

    quota = qw_memzone->addr;
    low_watermark = (unsigned int *) qw_memzone->addr + sizeof(int);
}

int MAIN(int argc, char **argv)
{
    int ret;
    struct cmdline *cl;

    rte_set_log_level(RTE_LOG_INFO);

    ret = rte_eal_init(argc, argv);
    if (ret < 0)
        rte_exit(EXIT_FAILURE, "Cannot initialize EAL\n");

    setup_shared_variables();

    cl = cmdline_stdin_new(qwctl_ctx, "qwctl> ");
    if (cl == NULL)
        rte_exit(EXIT_FAILURE, "Cannot create cmdline instance\n");

    cmdline_interact(cl);
    cmdline_stdin_exit(cl);

    return 0;
}


text:
using namespace std;

int main(int argc, char* argv[])
{
	TextBuddy app;
	app.initWithFileNamed(argv[1]);

	return 0;
}


text:
package org.log4mongo.contrib;

import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.spi.LoggingEvent;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * PatternParser that adds pattern converters for logging useful host-related info, specifically:
 *

 *
hostname

 *
VM name (which often includes the pid) of the JVM on this host

 *
IP address

 *

 */
public class HostInfoPatternParser extends PatternParser {

    static final char HOST_NAME = 'H';

    static final char VM_NAME = 'V';

    static final char IP_ADDRESS = 'I';

    static final Map<String, PatternConverter> converters;

    static {
        Map<String, PatternConverter> tmp = new HashMap<String, PatternConverter>();
        tmp.put(String.valueOf(HOST_NAME), new HostPatternConverter());
        tmp.put(String.valueOf(VM_NAME), new VMNamePatternConverter());
        tmp.put(String.valueOf(IP_ADDRESS), new IPAddressPatternConverter());

        converters = Collections.unmodifiableMap(tmp);
    }

    public HostInfoPatternParser(String pattern) {
        super(pattern);
    }

    /**
     * This method is called on each pattern converter character while the PatternParser superclass
     * is parsing the pattern. If the character is for a custom converter handled by this
     * PatternParser subclass, this class adds the appropriate converter to a LinkedList of
     * converters. If not, it allows the superclass to handle the converter character.
     *
     * @see org.apache.log4j.helpers.PatternParser#finalizeConverter(char)
     */
    public void finalizeConverter(char formatChar) {
        PatternConverter pc = null;
        switch (formatChar) {
        case HOST_NAME:
            pc = HostInfoPatternParser.converters.get(String.valueOf(HOST_NAME));
            currentLiteral.setLength(0);
            addConverter(pc);
            break;
        case VM_NAME:
            pc = HostInfoPatternParser.converters.get(String.valueOf(VM_NAME));
            currentLiteral.setLength(0);
            addConverter(pc);
            break;
        case IP_ADDRESS:
            pc = HostInfoPatternParser.converters.get(String.valueOf(IP_ADDRESS));
            currentLiteral.setLength(0);
            addConverter(pc);
            break;

        default:
            super.finalizeConverter(formatChar);
        }
    }

    /**
     * Custom PatternConverter for replacing converter character 'H' with the host name.
     */
    private static class HostPatternConverter extends PatternConverter {

        private String hostname = "";

        HostPatternConverter() {
            super();

            try {
                hostname = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                LogLog.warn(e.getMessage());
            }
        }

        public String convert(LoggingEvent event) {
            return hostname;
        }
    }

    /**
     * Custom PatternConverter for replacing converter character 'V' with the VM name of the JVM,
     * usually formatted as pid@host.
     */
    private static class VMNamePatternConverter extends PatternConverter {

        private String process = "";

        VMNamePatternConverter() {
            super();

            process = ManagementFactory.getRuntimeMXBean().getName();
        }

        public String convert(LoggingEvent event) {
            return process;
        }
    }

    /**
     * Custom PatternConverter for replacing converter character 'I' with the IP Address.
     */
    private static class IPAddressPatternConverter extends PatternConverter {

        private String ipaddress = "";

        IPAddressPatternConverter() {
            super();

            try {
                ipaddress = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                LogLog.warn(e.getMessage());
            }
        }

        public String convert(LoggingEvent event) {
            return ipaddress;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <feature>
        <name>vendor-bb-uib-datepicker</name>
        <contextItemName>[BBHOST]</contextItemName>
        <properties>
            <property name="title" label="Title" viewHint="admin,designModeOnly">
                <value type="string">Bootstrap UI Datepicker</value>
            </property>
            <property name="version" label="Version" viewHint="admin,designModeOnly">
                <value type="string">1.3.3-bb.3</value>
            </property>
            <property name="path" label="Path" readonly="true" viewHint="designModeOnly">
                <value type="string">$(itemRoot)/scripts/vendor-bb-uib-datepicker.js</value>
            </property>
            <property name="feature.vendor-bb-angular" label="Feature Vendor Bb Angular" readonly="true" viewHint="">
                <value type="string">vendor-bb-angular</value>
            </property>
            <property name="feature.vendor-bb-uib-dateparser" label="Feature Vendor Bb Uib Dateparser" readonly="true" viewHint="">
                <value type="string">vendor-bb-uib-dateparser</value>
            </property>
            <property name="feature.vendor-bb-uib-is-class" label="Feature Vendor Bb Uib Is Class" readonly="true" viewHint="">
                <value type="string">vendor-bb-uib-is-class</value>
            </property>
        </properties>
    </feature>
</catalog>


text:
package com.intellij.openapi.roots.ui.configuration.projectRoot.daemon;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.module.UnloadedModuleDescription;
import com.intellij.openapi.roots.ui.configuration.GeneralProjectSettingsElement;
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import com.intellij.ui.navigation.Place;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.Collection;

/**
 * @author nik
 */
public class UsagesInUnloadedModules extends ProjectStructureElementUsage {
  private final StructureConfigurableContext myContext;
  private final GeneralProjectSettingsElement myContainingElement;
  private final ProjectStructureElement mySourceElement;
  private final String myPresentableName;

  public UsagesInUnloadedModules(@NotNull StructureConfigurableContext context, @NotNull GeneralProjectSettingsElement element,
                                 @NotNull ProjectStructureElement sourceElement, @NotNull Collection<UnloadedModuleDescription> unloadedModules) {
    myContext = context;
    myContainingElement = element;
    mySourceElement = sourceElement;
    myPresentableName =
      unloadedModules.size() > 1 ? unloadedModules.size() + " Unloaded Modules"
                                 : "Unloaded Module '" + ObjectUtils.notNull(ContainerUtil.getFirstItem(unloadedModules)).getName() + "'";
  }

  @Override
  public ProjectStructureElement getSourceElement() {
    return mySourceElement;
  }

  @Override
  public ProjectStructureElement getContainingElement() {
    return myContainingElement;
  }

  @Override
  public String getPresentableName() {
    return myPresentableName;
  }

  @Override
  public PlaceInProjectStructure getPlace() {
    Place configurablePlace = ProjectStructureConfigurable.getInstance(myContext.getProject()).createProjectConfigurablePlace();
    return new PlaceInProjectStructureBase(myContext.getProject(), configurablePlace, myContainingElement, false);
  }

  @Override
  public void removeSourceElement() {
  }

  @Override
  public void replaceElement(ProjectStructureElement newElement) {

  }

  @Override
  public Icon getIcon() {
    return AllIcons.Modules.UnloadedModule;
  }

  @Override
  public int hashCode() {
    return mySourceElement.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    return obj instanceof UsagesInUnloadedModules && mySourceElement.equals(((UsagesInUnloadedModules)obj).mySourceElement);
  }
}


text:
import Ember from 'ember';

// Get integer of temperature - decimally numbers doesn't matter
export function temperature(params) {
    var temperature = params[0];
    return Math.floor(temperature) + "°";
}

export default Ember.Helper.helper(temperature);


text:
'use strict';
/* global Stats */
angular.module('artpopApp')
.factory('stats', function () {
	var stats = new Stats();

	var statsContainer = document.getElementById('apwgl-stats');

	return {
		obj: stats,
		begin: stats.begin,
		end: stats.end,
		show: function(){
			// stats.domElement.style.display = 'block';
			if (statsContainer && typeof statsContainer.appendChild === 'function'){
				statsContainer.appendChild(stats.domElement);
			}
		},
		hide: function(){
			// stats.domElement.style.display = 'none';

			if (statsContainer && typeof statsContainer.removeChild === 'function'){
				statsContainer.removeChild(stats.domElement);
			}
		}
	};
});


text:
"""
    El usuario introduce una cadena y un carácter, produciendo el programa como salida la cadena de entrada invertida
    quitando los caracteres coincidentes con el introducido.
"""
string = input('Introduce the String to modify:\n')
charac = input('Introduce the Character to delete:\n')

res = ''  # Cadena resultado, la que trataremos al final, la inicializamos con un color
color = '\033[33m'  # Opcional, esta cositas es para dar color a la cadena de salida

for c in string:
    if c != charac:
        res = c + res
print('The new string is:\n' + color + res)


text:
from m5.objects import *
from arm_generic import *

root = LinuxArmFSSystem(machine_type='VExpress_EMM64',
                        mem_mode='timing',
                        mem_class=DDR3_1600_8x8,
                        cpu_class=MinorCPU,
                        num_cpus=2).create_root()


text:
import { root } from './root';
import { isArrayLike } from './isArrayLike';
import { isPromise } from './isPromise';
import { isObject } from './isObject';
import { Subscriber } from '../Subscriber';
import { Observable, ObservableInput } from '../Observable';
import { iterator as Symbol_iterator } from '../symbol/iterator';
import { Subscription } from '../Subscription';
import { InnerSubscriber } from '../InnerSubscriber';
import { OuterSubscriber } from '../OuterSubscriber';
import { observable as Symbol_observable } from '../symbol/observable';

export function subscribeToResult<T, R>(outerSubscriber: OuterSubscriber<T, R>,
                                        result: any,
                                        outerValue?: T,
                                        outerIndex?: number): Subscription;
export function subscribeToResult<T>(outerSubscriber: OuterSubscriber<any, any>,
                                     result: ObservableInput<T>,
                                     outerValue?: T,
                                     outerIndex?: number): Subscription {
  let destination: Subscriber<any> = new InnerSubscriber(outerSubscriber, outerValue, outerIndex);

  if (destination.closed) {
    return null;
  }

  if (result instanceof Observable) {
    if (result._isScalar) {
      destination.next((<any>result).value);
      destination.complete();
      return null;
    } else {
      destination.syncErrorThrowable = true;
      return result.subscribe(destination);
    }
  } else if (isArrayLike(result)) {
    for (let i = 0, len = result.length; i < len && !destination.closed; i++) {
      destination.next(result[i]);
    }
    if (!destination.closed) {
      destination.complete();
    }
  } else if (isPromise(result)) {
    result.then(
      (value) => {
        if (!destination.closed) {
          destination.next(<any>value);
          destination.complete();
        }
      },
      (err: any) => destination.error(err)
    )
    .then(null, (err: any) => {
      // Escaping the Promise trap: globally throw unhandled errors
      root.setTimeout(() => { throw err; });
    });
    return destination;
  } else if (result && typeof result[Symbol_iterator] === 'function') {
    const iterator = <any>result[Symbol_iterator]();
    do {
      let item = iterator.next();
      if (item.done) {
        destination.complete();
        break;
      }
      destination.next(item.value);
      if (destination.closed) {
        break;
      }
    } while (true);
  } else if (result && typeof result[Symbol_observable] === 'function') {
    const obs = result[Symbol_observable]();
    if (typeof obs.subscribe !== 'function') {
      destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
    } else {
      return obs.subscribe(new InnerSubscriber(outerSubscriber, outerValue, outerIndex));
    }
  } else {
    const value = isObject(result) ? 'an invalid object' : `'${result}'`;
    const msg = `You provided ${value} where a stream was expected.`
      + ' You can provide an Observable, Promise, Array, or Iterable.';
    destination.error(new TypeError(msg));
  }
  return null;
}


text:
<!--
  Copyright 2015 mifort.org

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<a href=""
   class="report-filter"
   uib-popover-template="dynamicPopover.templateUrl"
   popover-title="{{dynamicPopover.title}}"
   popover-placement="bottom"
   popover-trigger="outsideClick"
   data-toggle="popover"
   ng-class="{'active': hasFilter()}">
</a>
<!--popover-append-to-body="true"-->


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Threading;

namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar
{
    internal partial class NavigationBarController
    {
        /// <summary>
        /// Starts a new task to compute the model based on the current text.
        /// </summary>
        private async ValueTask<NavigationBarModel> ComputeModelAndSelectItemAsync(ImmutableArray<bool> unused, CancellationToken cancellationToken)
        {
            // Jump back to the UI thread to determine what snapshot the user is processing.
            await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
            var textSnapshot = _subjectBuffer.CurrentSnapshot;

            // Ensure we switch to the threadpool before calling GetDocumentWithFrozenPartialSemantics.  It ensures
            // that any IO that performs is not potentially on the UI thread.
            await TaskScheduler.Default;

            var model = await ComputeModelAsync(textSnapshot, cancellationToken).ConfigureAwait(false);

            // Now, enqueue work to select the right item in this new model.
            StartSelectedItemUpdateTask();

            return model;

            static async Task<NavigationBarModel> ComputeModelAsync(ITextSnapshot textSnapshot, CancellationToken cancellationToken)
            {
                // When computing items just get the partial semantics workspace.  This will ensure we can get data for this
                // file, and hopefully have enough loaded to get data for other files in the case of partial types.  In the
                // event the other files aren't available, then partial-type information won't be correct.  That's ok though
                // as this is just something that happens during solution load and will pass once that is over.  By using
                // partial semantics, we can ensure we don't spend an inordinate amount of time computing and using full
                // compilation data (like skeleton assemblies).
                var document = textSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken);
                if (document == null)
                    return null;

                var itemService = document.GetLanguageService<INavigationBarItemService>();
                if (itemService != null)
                {
                    using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken))
                    {
                        var items = await itemService.GetItemsAsync(document, textSnapshot.Version, cancellationToken).ConfigureAwait(false);
                        return new NavigationBarModel(itemService, items);
                    }
                }

                return new NavigationBarModel(itemService: null, ImmutableArray<NavigationBarItem>.Empty);
            }
        }

        /// <summary>
        /// Starts a new task to compute what item should be selected.
        /// </summary>
        private void StartSelectedItemUpdateTask()
        {
            // 'true' value is unused.  this just signals to the queue that we have work to do.
            _selectItemQueue.AddWork();
        }

        private async ValueTask SelectItemAsync(CancellationToken cancellationToken)
        {
            // Switch to the UI so we can determine where the user is and determine the state the last time we updated
            // the UI.
            await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var currentView = _presenter.TryGetCurrentView();
            var caretPosition = currentView?.GetCaretPoint(_subjectBuffer);
            if (!caretPosition.HasValue)
                return;

            var position = caretPosition.Value.Position;
            var lastPresentedInfo = _lastPresentedInfo;

            // Jump back to the BG to do any expensive work walking the entire model
            await TaskScheduler.Default;

            // Ensure the latest model is computed.
            var model = await _computeModelQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(true);

            var currentSelectedItem = ComputeSelectedTypeAndMember(model, position, cancellationToken);

            GetProjectItems(out var projectItems, out var selectedProjectItem);
            if (Equals(model, lastPresentedInfo.model) &&
                Equals(currentSelectedItem, lastPresentedInfo.selectedInfo) &&
                Equals(selectedProjectItem, lastPresentedInfo.selectedProjectItem) &&
                projectItems.SequenceEqual(lastPresentedInfo.projectItems))
            {
                // Nothing changed, so we can skip presenting these items.
                return;
            }

            // Finally, switch back to the UI to update our state and UI.
            await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            _presenter.PresentItems(
                projectItems,
                selectedProjectItem,
                model.Types,
                currentSelectedItem.TypeItem,
                currentSelectedItem.MemberItem);

            _lastPresentedInfo = (projectItems, selectedProjectItem, model, currentSelectedItem);
        }

        internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember(
            NavigationBarModel model, int caretPosition, CancellationToken cancellationToken)
        {
            var (item, gray) = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken);
            if (item == null)
            {
                // Nothing to show at all
                return new NavigationBarSelectedTypeAndMember(null, null);
            }

            var rightItem = GetMatchingItem(item.ChildItems, caretPosition, model.ItemService, cancellationToken);
            return new NavigationBarSelectedTypeAndMember(item, gray, rightItem.item, rightItem.gray);
        }

        /// <summary>
        /// Finds the item that point is in, or if it's not in any items, gets the first item that's
        /// positioned after the cursor.
        /// </summary>
        /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns>
        private static (NavigationBarItem item, bool gray) GetMatchingItem(
            ImmutableArray<NavigationBarItem> items, int point, INavigationBarItemService itemsService, CancellationToken cancellationToken)
        {
            NavigationBarItem exactItem = null;
            var exactItemStart = 0;
            NavigationBarItem nextItem = null;
            var nextItemStart = int.MaxValue;

            foreach (var item in items)
            {
                foreach (var span in item.Spans)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (span.Contains(point) || span.End == point)
                    {
                        // This is the item we should show normally. We'll continue looking at other
                        // items as there might be a nested type that we're actually in. If there
                        // are multiple items containing the point, choose whichever containing span
                        // starts later because that will be the most nested item.

                        if (exactItem == null || span.Start >= exactItemStart)
                        {
                            exactItem = item;
                            exactItemStart = span.Start;
                        }
                    }
                    else if (span.Start > point && span.Start <= nextItemStart)
                    {
                        nextItem = item;
                        nextItemStart = span.Start;
                    }
                }
            }

            if (exactItem != null)
            {
                return (exactItem, gray: false);
            }
            else
            {
                // The second parameter is if we should show it grayed. We'll be nice and say false
                // unless we actually have an item
                var itemToGray = nextItem ?? items.LastOrDefault();
                if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray))
                {
                    itemToGray = null;
                }

                return (itemToGray, gray: itemToGray != null);
            }
        }
    }
}


text:
/*
 ~   DataTables WSO2 Integration
 ~   ©2016 WSO2 Inc. - datatables.net/license
 ~
 ~   DataTables integration for WSO2 Visual Elements. This requires WSO2 Visual Elements 1.0.0 and
 ~   DataTables 1.10 or newer.
 */

(function(window, document, undefined){

    var factory = function($, DataTable) {
        "use strict";

        /* Set the defaults for DataTables initialisation */
        $.extend(true, DataTable.defaults, {
            bSortCellsTop: true,
            responsive: false,
            autoWidth: false,
            dom: '<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            language: {
                searchPlaceholder: 'Filter by ...',
                search: ''
            }
        });
        var wso2Extend = function(settings, opts) {
            // Sanity check that we are using DataTables 1.10 or newer
            if (!DataTable.versionCheck || !DataTable.versionCheck('1.10.12')) {
                throw 'DataTables Responsive requires DataTables 1.10.12 or newer';
            }

            this.s = {
                dt: new DataTable.Api(settings),
                columns: []
            };

            // Check if responsive has already been initialised on this table
            if (this.s.dt.settings()[0].wso2) {
                return;
            }

            // details is an object, but for simplicity the user can give it as a string
            if (opts && typeof opts.details === 'string') {
                opts.details = { type: opts.details };
            }
            this.c = $.extend( true, {}, wso2Extend.defaults, DataTable.defaults.wso2, opts );
            settings.wso2 = this;
            this._constructor();

        };

        wso2Extend.prototype = {
            _constructor: function() {
		        var dt = this.s.dt;
                var elem = $('table', dt.table().container());
                var ROW_SELECTED_CLASS = 'DTTT_selected';

                dt.table().columns().every(function() {

                    var column = this;
                    var filterColumn = $('.filter-row th', elem);

                    //Create & add select/text filters to each column
                    if (filterColumn.eq(column.index()).hasClass('select-filter')) {
                        var select = $('<select class="form-control"><option value="">All</option></select>')
                            .appendTo(filterColumn.eq(column.index()).empty())
                            .on('change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    .search(val ? '^' + val + '$' : '', true, false)
                                    .draw();
                            });

                        $(column).each(function () {
                            if ($(column.nodes()).attr('data-search')) {
                                var titles = [];
                                column.nodes().unique().sort().each(function (d, j) {
                                    var title = $(d).attr('data-display');
                                    if ($.inArray(title, titles) < 0) {
                                        titles.push(title);
                                        if (title !== undefined) {
                                            select.append('<option value="' + title + '">' + title + '</option>')
                                        }
                                    }
                                });
                            } else {
                                column.data().unique().sort().each(function (d, j) {
                                    select.append('<option value="' + d + '">' + d + '</option>')
                                });
                            }
                        });
                    } else if (filterColumn.eq(column.index()).hasClass('text-filter')) {
                        var title = filterColumn.eq(column.index()).attr('data-for');
                        $(filterColumn.eq(column.index()).empty()).html('<input type="text" class="form-control" placeholder="Search for ' + title + '" />');

                        filterColumn.eq(column.index()).find('input').on('keyup change', function () {
                            column
                                .search($(this).val())
                                .draw();
                        });
                    }

                });

                //Search input default styles override
                var search_input = elem.closest('.dataTables_wrapper').find('div[id$=_filter] input');
                search_input.before('').removeClass('input-sm');

                // Create sorting dropdown menu for list table advance operations
                var dropdownmenu = $('
' +
                    '
Sort by

');
                $('.sort-row th', elem).each(function () {
                    if (!$(this).hasClass('no-sort')) {
                        dropdownmenu.append('
' + $(this).html() + '
');
                    }
                });

                //Append advance operations to list table toolbar
                $('.dataTable.list-table').closest('.dataTables_wrapper').find('.dataTablesTop .dataTables_toolbar').html('' +
                    '
' +
                    '
<button data-click-event="toggle-select" class="btn btn-default btn-primary">Select
' +
                    '
<button data-click-event="toggle-select-all" ' +
                    'class="btn btn-default btn-primary">Select All
' +
                    '
<button data-click-event="toggle-list-view" data-view="grid" class="btn btn-default">' +
                    '</button>
' +
                    '
<button data-click-event="toggle-list-view" data-view="list" class="btn btn-default">' +
                    '</button>
' +
                    '
<button class="btn btn-default" data-toggle="dropdown"></button>' +
                    dropdownmenu[0].outerHTML + '
' + '
'
                );

                //Sorting dropdown menu select function
                $('.dataTables_wrapper .sort-list li a').click(function () {
                    $(this).closest('li').siblings('li').find('a').removeClass('sorting_asc').removeClass('sorting_desc');

                    var thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();

                    if (!($(this).hasClass('sorting_asc')) && !($(this).hasClass('sorting_desc'))) {
                        $(this).addClass('sorting_asc');
                        thisTable.fnSort([
                            [$(this).attr('data-column'), 'asc']
                        ]);
                    } else if ($(this).hasClass('sorting_asc')) {
                        $(this).switchClass('sorting_asc', 'sorting_desc');
                        thisTable.fnSort([
                            [$(this).attr('data-column'), 'desc']
                        ]);
                    } else if ($(this).hasClass('sorting_desc')) {
                        $(this).switchClass('sorting_desc', 'sorting_asc');
                        thisTable.fnSort([
                            [$(this).attr('data-column'), 'asc']
                        ]);
                    }
                });

                //Enable/Disable selection on rows
                $('.dataTables_wrapper').off('click', '[data-click-event=toggle-select]');
                $('.dataTables_wrapper').on('click', '[data-click-event=toggle-select]', function () {
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    if ($(button).html() == 'Select') {
                        thisTable.api().rows().every(function () {
                            $(this.node()).attr('data-type','selectable');
                        });
                        thisTable.addClass("table-selectable");
                        $(button).addClass("active").html('Cancel');
                        $(button).closest('li').siblings('.select-all-btn').show();
                    } else if ($(button).html() == 'Cancel'){
                        thisTable.api().rows().every(function () {
                            $(this.node()).removeAttr('data-type');
                            $(this.node()).removeClass(ROW_SELECTED_CLASS);
                        });
                        thisTable.removeClass("table-selectable");
                        $(button).removeClass("active").html('Select');
                        $(button).closest('li').siblings('.select-all-btn').hide();
                    }
                });

                //Select/Deselect all rows functions
                $('.dataTables_wrapper').off('click', '[data-click-event=toggle-select-all]');
                $('.dataTables_wrapper').on('click', '[data-click-event=toggle-select-all]', function () {
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    if ($(button).html() == 'Select All') {
                        thisTable.api().rows().every(function () {
                            $(this.node()).addClass(ROW_SELECTED_CLASS);
                            $(button).html('Deselect All');
                        });
                    } else if ($(button).html() == 'Deselect All') {
                        thisTable.api().rows().every(function () {
                            $(this.node()).removeClass(ROW_SELECTED_CLASS);
                            $(button).html('Select All');
                        });
                    }
                });

                //Event for row select/deselect
                $('body').on('click', '[data-type=selectable]', function() {
                    $(this).toggleClass(ROW_SELECTED_CLASS);
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();

                    thisTable.api().rows().every(function () {
                        if (!$(this.node()).hasClass(ROW_SELECTED_CLASS)) {
                            $(button).closest('.dataTables_wrapper').find('[data-click-event=toggle-selected]').html('Select All');
                        }
                    });
                });

                //list table list/grid view toggle function
                var toggleButton = $('[data-click-event=toggle-list-view]');
                toggleButton.click(function () {
                    if ($(this).attr('data-view') == 'grid') {
                        $(this).closest('.dataTables_wrapper').find('.dataTable').addClass('grid-view');
                    } else {
                        $(this).closest('.dataTables_wrapper').find('.dataTable').removeClass('grid-view');
                    }
                });

                //delete selected rows
                $('[data-click-event=delete-selected-rows]').click(function () {
                    var thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    thisTable.api().rows('.' + ROW_SELECTED_CLASS).remove().draw(false);
                });

            }
        }

        wso2Extend.defaults = {
            bSortCellsTop: true,
            responsive: false,
            autoWidth: false,
            dom: '<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            language: {
                searchPlaceholder: 'Filter by ...',
                search: ''
            }
        }

        /**
         * Version information
         *
         * @name wso2Extend.version
         * @static
         */
        wso2Extend.version = '1.0.0';

        $.fn.dataTable.wso2Extend = wso2Extend;
        $.fn.DataTable.wso2Extend = wso2Extend;

        // Attach a listener to the document which listens for DataTables initialisation
        // events so we can automatically initialise
        $(document).on('preInit.dt.dte', function(e, settings, json) {
            if (e.namespace !== 'dt') {
                return;
            }
            var init = settings.oInit.wso2;
            if (init !== false) {
                new wso2Extend (settings, $.isPlainObject(init) ? init : {});
            }
        });
        return wso2Extend;
    };

    // Define as an AMD module if possible
    if (typeof define === 'function' && define.amd){
        define(['jquery', 'datatables'], factory);
    }
    else if (typeof exports === 'object'){
        // Node/CommonJS
        factory(require('jquery'), require('datatables'));
    }
    else if (jQuery && !jQuery.fn.dataTable.wso2Extend) {
        // Otherwise simply initialise as normal, stopping multiple evaluation
        factory(jQuery, jQuery.fn.dataTable);
    }

})(window, document);


text:
layout: post
title: 搬瓦工vps安装LNMP
date: 2017-1-27
categories: blog
description: SA
---

# 搬瓦工vps安装LNMP

## 安装mysql
* Clean and remove MySQL and old/cached packages

		    sudo apt-get clean
			sudo apt-get purge mysql*
			sudo apt-get autoremove
			sudo apt-get autoclean

* Upgrade to latest distribution version

			sudo apt-get dist-upgrade

*  Install MySQL

			sudo apt-get install mysql-server

*  配置数据库安全

			mysql_secure_installation

*  解决编码问题

			service mysql stop
			vim /etc/mysql/my.cnf
			打开my.cnf后,在文件内的[mysqld]下增加如下两行设置:
			character_set_server=utf8
			init_connect='SET NAMES utf8'
			service mysql start
			show global variables like '%character%'

## nginx
*  安装

			apt-get install nginx

## php7.0
*  安装

			wget https://downloads.php.net/~ab/php-7.0.0alpha2.tar.bz2

			//用winscp把下载好的文件上传到网站中
			tar jxf php-7.0.0alpha2.tar.bz2

			安装:
			sudo apt-get update
			sudo apt-get install libxml2-dev

			安装gcc
			sudo apt-get  install  build-essential

			sudo apt-get install openssl
			sudo apt-get install libssl-dev
			apt-get install make
			apt-get install curl
			apt-get install libcurl4-gnutls-dev

			sudo apt-get install libjpeg-dev
			sudo apt-get install libpng-dev
			sudo apt-get install libmcrypt-dev
			sudo apt-get install libreadline6 libreadline6-dev
			cd php-7*

			3. 编译
			./configure

			./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --with-mysqli --with-pdo-mysql --with-iconv-dir --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --with-mcrypt --enable-ftp --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --without-pear --with-gettext --disable-fileinfo --enable-maintainer-zts

			./configure --prefix=/usr/local/php --enable-fpm --enable-inline-optimization --disable-debug --disable-rpath --enable-shared --enable-opcache  --with-mysql --with-mysqli --with-mysql-sock  --enable-pdo --with-pdo-mysql --with-gettext --enable-mbstring --with-iconv --with-mcrypt --with-mhash --with-openssl --enable-bcmath --enable-soap --with-libxml-dir --enable-pcntl --enable-shmop --enable-sysvmsg --enable-sysvsem --enable-sysvshm --enable-sockets --with-curl --with-zlib --enable-zip --enable-bz2 --with-readline --without-sqlite3 --without-pdo-sqlite --with-pear --with-libdir=/lib/x86_64-linux-gnu --with-gd --with-jpeg-dir=/usr/lib --enable-gd-native-ttf --enable-xml

			#安装 PHP
			 make && make test
			 make && sudo make install

			下面是对php-fpm运行用户进行设置
			 配置php-fpm
			cd /usr/local/php/etc
			cp php-fpm.conf.default php-fpm.conf
			vim php-fpm.conf

			修改
			user = www-data
			 group = www-data

			如果www-data用户不存在,那么先添加www-data用户
			groupadd www-data
			 useradd -g www-data www-data

			启动php-fpm

			sudo /usr/local/php/sbin/php-fpm

			加入系统变量

			sudo echo "PATH=$PATH:/usr/local/php/bin">> /etc/profile
			 sudo echo "export PATH">> /etc/profile
			 source /etc/profile

			php -v

## composer
*  安装

			apt-get install nginx


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

namespace CSC.CSClassroom.Model.Projects.ServiceResults
{
	/// <summary>
	/// The status of a project's build.
	/// </summary>
	public class ProjectStatus
	{
		/// <summary>
		/// The project name.
		/// </summary>
		public string ProjectName { get; }

		/// <summary>
		/// The repository name.
		/// </summary>
		public string RepoName { get; }

		/// <summary>
		/// The last commit date.
		/// </summary>
		public DateTime LastCommitDate { get; }

		/// <summary>
		/// Whether or not the last build succeeded.
		/// </summary>
		public bool LastBuildSucceeded { get; }

		/// <summary>
		/// Test counts for the build, in ascending order.
		/// </summary>
		public IList<BuildTestCount> BuildTestCounts { get; }

		/// <summary>
		/// Constructor.
		/// </summary>
		public ProjectStatus(
			string projectName,
			string repoName,
			DateTime lastCommitDate,
			bool lastBuildSucceeded,
			IList<BuildTestCount> buildTestCounts)
		{
			ProjectName = projectName;
			RepoName = repoName;
			LastCommitDate = lastCommitDate;
			LastBuildSucceeded = lastBuildSucceeded;
			BuildTestCounts = buildTestCounts;
		}
	}
}


text:
namespace SitecoreExtensions.Modules.SectionSwitches {
    import ICommand = SitecoreExtensions.Modules.Launcher.ICommand;

    export class SectionSwitchesCommandsProvider implements Launcher.Providers.ICommandsProvider {
        commands: ICommand[];
        constructor() {
            this.commands = new Array<ICommand>();
            this.initCommands();
        }

        initCommands(): void {
            var cmd1: ICommand = {
                id: 0,
                name: 'Open sections',
                description: 'Open all closed sections',
                execute: SectionSwitches.SectionSwitchesModule.prototype.openClosedSections,
                canExecute: () => { return Context.Location() == Enums.Location.ContentEditor; }
            };
            var cmd2: ICommand = {
                id: 0,
                name: 'Close sections',
                description: 'Close all opened sections',
                execute: SectionSwitches.SectionSwitchesModule.prototype.closeOpenedSections,
                canExecute: () => { return Context.Location() == Enums.Location.ContentEditor; }
            };
            this.commands.push(cmd1);
            this.commands.push(cmd2);
        }

        getCommands(): ICommand[] {
            return this.commands;
        }
    }
}


text:
package com.android.dx.cf.code;

import com.android.dx.rop.cst.Constant;
import com.android.dx.rop.cst.CstMemberRef;
import com.android.dx.rop.cst.CstString;
import com.android.dx.rop.cst.CstType;
import com.android.dx.rop.type.Type;
import com.android.dx.util.Bits;
import com.android.dx.util.IntList;
import java.util.ArrayList;

/**
 * Utility that identifies basic blocks in bytecode.
 */
public final class BasicBlocker implements BytecodeArray.Visitor {
    /** {@code non-null;} method being converted */
    private final ConcreteMethod method;

    /**
     * {@code non-null;} work set; bits indicate offsets in need of
     * examination
     */
    private final int[] workSet;

    /**
     * {@code non-null;} live set; bits indicate potentially-live
     * opcodes; contrawise, a bit that isn't on is either in the
     * middle of an instruction or is a definitely-dead opcode
     */
    private final int[] liveSet;

    /**
     * {@code non-null;} block start set; bits indicate the starts of
     * basic blocks, including the opcodes that start blocks of
     * definitely-dead code
     */
    private final int[] blockSet;

    /**
     * {@code non-null, sparse;} for each instruction offset to a branch of
     * some sort, the list of targets for that instruction
     */
    private final IntList[] targetLists;

    /**
     * {@code non-null, sparse;} for each instruction offset to a throwing
     * instruction, the list of exception handlers for that instruction
     */
    private final ByteCatchList[] catchLists;

    /** offset of the previously parsed bytecode */
    private int previousOffset;

    /**
     * Identifies and enumerates the basic blocks in the given method,
     * returning a list of them. The returned list notably omits any
     * definitely-dead code that is identified in the process.
     *
     * @param method {@code non-null;} method to convert
     * @return {@code non-null;} list of basic blocks
     */
    public static ByteBlockList identifyBlocks(ConcreteMethod method) {
        BasicBlocker bb = new BasicBlocker(method);

        bb.doit();
        return bb.getBlockList();
    }

    /**
     * Constructs an instance. This class is not publicly instantiable; use
     * {@link #identifyBlocks}.
     *
     * @param method {@code non-null;} method to convert
     */
    private BasicBlocker(ConcreteMethod method) {
        if (method == null) {
            throw new NullPointerException("method == null");
        }

        this.method = method;

        /*
         * The "+1" below is so the idx-past-end is also valid,
         * avoiding a special case, but without preventing
         * flow-of-control falling past the end of the method from
         * getting properly reported.
         */
        int sz = method.getCode().size() + 1;

        workSet = Bits.makeBitSet(sz);
        liveSet = Bits.makeBitSet(sz);
        blockSet = Bits.makeBitSet(sz);
        targetLists = new IntList[sz];
        catchLists = new ByteCatchList[sz];
        previousOffset = -1;
    }

    /*
     * Note: These methods are defined implementation of the interface
     * BytecodeArray.Visitor; since the class isn't publicly
     * instantiable, no external code ever gets a chance to actually
     * call these methods.
     */

    /** {@inheritDoc} */
    @Override
	public void visitInvalid(int opcode, int offset, int length) {
        visitCommon(offset, length, true);
    }

    /** {@inheritDoc} */
    @Override
	public void visitNoArgs(int opcode, int offset, int length, Type type) {
        switch (opcode) {
            case ByteOps.IRETURN:
            case ByteOps.RETURN: {
                visitCommon(offset, length, false);
                targetLists[offset] = IntList.EMPTY;
                break;
            }
            case ByteOps.ATHROW: {
                visitCommon(offset, length, false);
                visitThrowing(offset, length, false);
                break;
            }
            case ByteOps.IALOAD:
            case ByteOps.LALOAD:
            case ByteOps.FALOAD:
            case ByteOps.DALOAD:
            case ByteOps.AALOAD:
            case ByteOps.BALOAD:
            case ByteOps.CALOAD:
            case ByteOps.SALOAD:
            case ByteOps.IASTORE:
            case ByteOps.LASTORE:
            case ByteOps.FASTORE:
            case ByteOps.DASTORE:
            case ByteOps.AASTORE:
            case ByteOps.BASTORE:
            case ByteOps.CASTORE:
            case ByteOps.SASTORE:
            case ByteOps.ARRAYLENGTH:
            case ByteOps.MONITORENTER:
            case ByteOps.MONITOREXIT: {
                /*
                 * These instructions can all throw, so they have to end
                 * the block they appear in (since throws are branches).
                 */
                visitCommon(offset, length, true);
                visitThrowing(offset, length, true);
                break;
            }
            case ByteOps.IDIV:
            case ByteOps.IREM: {
                /*
                 * The int and long versions of division and remainder may
                 * throw, but not the other types.
                 */
                visitCommon(offset, length, true);
                if ((type == Type.INT) || (type == Type.LONG)) {
                    visitThrowing(offset, length, true);
                }
                break;
            }
            default: {
                visitCommon(offset, length, true);
                break;
            }
        }
    }

    /** {@inheritDoc} */
    @Override
	public void visitLocal(int opcode, int offset, int length,
						   int idx, Type type, int value) {
        if (opcode == ByteOps.RET) {
            visitCommon(offset, length, false);
            targetLists[offset] = IntList.EMPTY;
        } else {
            visitCommon(offset, length, true);
        }
    }

    /** {@inheritDoc} */
    @Override
	public void visitConstant(int opcode, int offset, int length,
							  Constant cst, int value) {
        visitCommon(offset, length, true);

        if ((cst instanceof CstMemberRef) || (cst instanceof CstType) ||
            (cst instanceof CstString)) {
            /*
             * Instructions with these sorts of constants have the
             * possibility of throwing, so this instruction needs to
             * end its block (since it can throw, and possible-throws
             * are branch points).
             */
            visitThrowing(offset, length, true);
        }
    }

    /** {@inheritDoc} */
    @Override
	public void visitBranch(int opcode, int offset, int length,
							int target) {
        switch (opcode) {
            case ByteOps.GOTO: {
                visitCommon(offset, length, false);
                targetLists[offset] = IntList.makeImmutable(target);
                break;
            }
            case ByteOps.JSR: {
                /*
                 * Each jsr is quarantined into a separate block (containing
                 * only the jsr instruction) but is otherwise treated
                 * as a conditional branch. (That is to say, both its
                 * target and next instruction begin new blocks.)
                 */
                addWorkIfNecessary(offset, true);
                // Fall through to next case...
            }
            default: {
                int next = offset + length;
                visitCommon(offset, length, true);
                addWorkIfNecessary(next, true);
                targetLists[offset] = IntList.makeImmutable(next, target);
                break;
            }
        }

        addWorkIfNecessary(target, true);
    }

    /** {@inheritDoc} */
    @Override
	public void visitSwitch(int opcode, int offset, int length,
							SwitchList cases, int padding) {
        visitCommon(offset, length, false);
        addWorkIfNecessary(cases.getDefaultTarget(), true);

        int sz = cases.size();
        for (int i = 0; i < sz; i++) {
            addWorkIfNecessary(cases.getTarget(i), true);
        }

        targetLists[offset] = cases.getTargets();
    }

    /** {@inheritDoc} */
    @Override
	public void visitNewarray(int offset, int length, CstType type,
							  ArrayList<Constant> intVals) {
        visitCommon(offset, length, true);
        visitThrowing(offset, length, true);
    }

    /**
     * Extracts the list of basic blocks from the bit sets.
     *
     * @return {@code non-null;} the list of basic blocks
     */
    private ByteBlockList getBlockList() {
        BytecodeArray bytes = method.getCode();
        ByteBlock[] bbs = new ByteBlock[bytes.size()];
        int count = 0;

        for (int at = 0, next; /*at*/; at = next) {
            next = Bits.findFirst(blockSet, at + 1);
            if (next < 0) {
                break;
            }

            if (Bits.get(liveSet, at)) {
                /*
                 * Search backward for the branch or throwing
                 * instruction at the end of this block, if any. If
                 * there isn't any, then "next" is the sole target.
                 */
                IntList targets = null;
                int targetsAt = -1;
                ByteCatchList blockCatches;

                for (int i = next - 1; i >= at; i--) {
                    targets = targetLists[i];
                    if (targets != null) {
                        targetsAt = i;
                        break;
                    }
                }

                if (targets == null) {
                    targets = IntList.makeImmutable(next);
                    blockCatches = ByteCatchList.EMPTY;
                } else {
                    blockCatches = catchLists[targetsAt];
                    if (blockCatches == null) {
                        blockCatches = ByteCatchList.EMPTY;
                    }
                }

                bbs[count] =
                    new ByteBlock(at, at, next, targets, blockCatches);
                count++;
            }
        }

        ByteBlockList result = new ByteBlockList(count);
        for (int i = 0; i < count; i++) {
            result.set(i, bbs[i]);
        }

        return result;
    }

    /**
     * Does basic block identification.
     */
    private void doit() {
        BytecodeArray bytes = method.getCode();
        ByteCatchList catches = method.getCatches();
        int catchSz = catches.size();

        /*
         * Start by setting offset 0 as the start of a block and in need
         * of work...
         */
        Bits.set(workSet, 0);
        Bits.set(blockSet, 0);

        /*
         * And then process the work set, add new work based on
         * exception ranges that are active, and iterate until there's
         * nothing left to work on.
         */
        while (!Bits.isEmpty(workSet)) {
            try {
                bytes.processWorkSet(workSet, this);
            } catch (IllegalArgumentException ex) {
                // Translate the exception.
                throw new SimException("flow of control falls off " +
                                       "end of method",
                                       ex);
            }

            for (int i = 0; i < catchSz; i++) {
                ByteCatchList.Item item = catches.get(i);
                int start = item.getStartPc();
                int end = item.getEndPc();
                if (Bits.anyInRange(liveSet, start, end)) {
                    Bits.set(blockSet, start);
                    Bits.set(blockSet, end);
                    addWorkIfNecessary(item.getHandlerPc(), true);
                }
            }
        }
    }

    /**
     * Sets a bit in the work set, but only if the instruction in question
     * isn't yet known to be possibly-live.
     *
     * @param offset offset to the instruction in question
     * @param blockStart {@code true} iff this instruction starts a
     * basic block
     */
    private void addWorkIfNecessary(int offset, boolean blockStart) {
        if (!Bits.get(liveSet, offset)) {
            Bits.set(workSet, offset);
        }

        if (blockStart) {
            Bits.set(blockSet, offset);
        }
    }

    /**
     * Helper method used by all the visitor methods.
     *
     * @param offset offset to the instruction
     * @param length length of the instruction, in bytes
     * @param nextIsLive {@code true} iff the instruction after
     * the indicated one is possibly-live (because this one isn't an
     * unconditional branch, a return, or a switch)
     */
    private void visitCommon(int offset, int length, boolean nextIsLive) {
        Bits.set(liveSet, offset);

        if (nextIsLive) {
            /*
             * If the next instruction is flowed to by this one, just
             * add it to the work set, and then a subsequent visit*()
             * will deal with it as appropriate.
             */
            addWorkIfNecessary(offset + length, false);
        } else {
            /*
             * If the next instruction isn't flowed to by this one,
             * then mark it as a start of a block but *don't* add it
             * to the work set, so that in the final phase we can know
             * dead code blocks as those marked as blocks but not also marked
             * live.
             */
            Bits.set(blockSet, offset + length);
        }
    }

    /**
     * Helper method used by all the visitor methods that deal with
     * opcodes that possibly throw. This method should be called after calling
     * {@link #visitCommon}.
     *
     * @param offset offset to the instruction
     * @param length length of the instruction, in bytes
     * @param nextIsLive {@code true} iff the instruction after
     * the indicated one is possibly-live (because this one isn't an
     * unconditional throw)
     */
    private void visitThrowing(int offset, int length, boolean nextIsLive) {
        int next = offset + length;

        if (nextIsLive) {
            addWorkIfNecessary(next, true);
        }

        ByteCatchList catches = method.getCatches().listFor(offset);
        catchLists[offset] = catches;
        targetLists[offset] = catches.toTargetList(nextIsLive ? next : -1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
	public void setPreviousOffset(int offset) {
        previousOffset = offset;
    }

    /**
     * {@inheritDoc}
     */
    @Override
	public int getPreviousOffset() {
        return previousOffset;
    }
}


text:
//
//  UIView+Placeholder.h
//  JXPlaygroundDemo
//
//  Created by 晓梦影 on 2017/9/26.
//  Copyright © 2017年 Mr.Gao. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (Placeholder)
/** 加载*/
@property (nonatomic, copy) void(^reloadBlock)();
/** 字体颜色*/
@property (nonatomic, strong) UIColor *jx_placeholderColor;
/** 背景颜色*/
@property (nonatomic, strong) UIColor *jx_placeholderBackgroundColor;

/** 加载按钮背景颜色*/
@property (nonatomic, strong) UIColor *jx_reloadBtnBackgroundColor;

- (void)jx_showPlaceholderView:(NSString *)imageName
                       desText:(NSString *)desText
               reloadBtnTitle:(NSString *)reloadBtnTitle
                  reloadBlock:(void(^)())reloadBlock;
@end


text:
var Barista = {};

// current version of the library
Barista.VERSION = '0.2.0';

// build objects to be extended for Models, Collections, and Views
Barista.Models = {};
Barista.Collections = {};
Barista.Views = {};

// build an array to contain backing datasets definitions
Barista.Datasets = {};

// build a set of configuration attributes that are referenced throughout the
// library
Barista.APIURL = '//api.lincscloud.org';

// build an object of utilities that we need to make sure are not overwritten
Barista.Utils = {cookie: $.cookie};


text:
var gulp    = require('gulp');
var connect = require('gulp-connect');

// run connect server
gulp.task('connect', function() {
	connect.server({
		root: 'dist',
		port: 3000,
		livereload: true
	});
});

// run livereload
gulp.task('reload', function () {
	connect.reload()
});


text:
LeetCode
=========

[LeetCode](https://leetcode.com/)部分Java Solution


text:
package org.rapidoid.collection;

import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.lambda.Mapper;
import org.rapidoid.u.U;

@Authors("Nikolche Mihajlovski")
@Since("5.1.0")
public class AutoExpandingMap<K, V> extends AbstractMapDecorator<K, V> {

    private final Mapper<K, V> valueFactory;

    public AutoExpandingMap(Mapper<K, V> valueFactory) {
        super(Coll.synchronizedMap());
        this.valueFactory = valueFactory;
    }

    @SuppressWarnings("unchecked")
    @Override
    public V get(Object key) {
        V val = decorated.get(key);

        if (val == null) {
            synchronized (decorated) {
                val = decorated.get(key);

                if (val == null) {
                    try {
                        val = valueFactory.map((K) key);
                    } catch (Exception e) {
                        throw U.rte(e);
                    }

                    decorated.put((K) key, val);
                }

                return val;
            }
        }

        return val;
    }

    public AutoExpandingMap<K, V> copy() {
        return new AutoExpandingMap<>(valueFactory);
    }

}


text:
<?php namespace ProcessWire\GraphQL\Test\Permissions\Superuser\Update\NotAllowed;

use ProcessWire\GraphQL\Test\GraphqlTestCase;
use ProcessWire\GraphQL\Utils;

class RenameTest extends GraphqlTestCase
{
  /**
   * + For superuser.
   * + The target template is legal.
   * - The new name is already taken.
   */
  public static function getSettings()
  {
    return [
      "login" => "admin",
      "legalTemplates" => ["architect"],
    ];
  }

  public function testPermission()
  {
    $architect = Utils::pages()->get("template=architect, sort=random");
    $newName = Utils::pages()->get(
      "template=architect, sort=random, id!={$architect->id}"
    )->name;
    $query = 'mutation renamePage($page: ArchitectUpdateInput!){
      updateArchitect(page: $page) {
        name
      }
    }';

    $variables = [
      "page" => [
        "id" => $architect->id,
        "name" => $newName,
      ],
    ];

    self::assertNotEquals($newName, $architect->name);
    $res = self::execute($query, $variables);
    self::assertEquals(
      1,
      count($res->errors),
      "Does not allow to updates the name if it conflicts."
    );
    assertStringContainsString($newName, $res->errors[0]->message);
    self::assertNotEquals(
      $newName,
      $architect->name,
      "Does not update the name of the target."
    );
  }
}


text:
package com.animbus.music.ui.activity.settings;

import android.content.Context;
import android.util.AttributeSet;

import com.afollestad.appthemeengine.prefs.ATEListPreference;

/**
 * Created by Adrian on 1/1/2016.
 */
public class DependencyListPreference extends ATEListPreference {
    public DependencyListPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public DependencyListPreference(Context context) {
        super(context);
    }

    public DependencyListPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DependencyListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void setValue(String value) {
        String mOldValue = getValue();
        super.setValue(value);
        if (!value.equals(mOldValue)) {
            notifyDependencyChange(shouldDisableDependents());
        }
    }

    @Override
    public boolean shouldDisableDependents() {
        boolean shouldDisableDependents = super.shouldDisableDependents();
        String value = getValue();
        return shouldDisableDependents || value == null || !value.equals("0");
    }
}