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

<TITLE>
Uses of Class org.apache.poi.xssf.binary.XSSFBRelation (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.poi.xssf.binary.XSSFBRelation

Packages that use XSSFBRelation

org.apache.poi.xssf.binary
The org.apache.poi.xssf.binary package includes necessary underlying components
for streaming/read-only processing of xlsb files.

Uses of XSSFBRelation in org.apache.poi.xssf.binary

Fields in org.apache.poi.xssf.binary declared as XSSFBRelation

static XSSFBRelation
XSSFBRelation.STYLES_BINARY

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

                Copyright 2017 The Apache Software Foundation or
        its licensors, as applicable.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nucleus.Model
{
    /// <summary>
    /// A data storage mechanism for materials
    /// Stores data components keyed by type.
    /// </summary>
    [Serializable]
    public class MaterialDataStore : DataStore<IMaterialDataComponent, Material>
    {
        #region Constructor

        public MaterialDataStore(Material owner) : base(owner) { }

        public MaterialDataStore() { }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="robots" content="index, follow, all" />
        <title>Thelia\Form\Api\ProductSaleElements | </title>
                    <link rel="stylesheet" type="text/css" href="../../../stylesheet.css">

Classes

Namespaces

Interfaces

Traits

Index

Namespace

Thelia\Form\Api\ProductSaleElements

                    ProductSaleElementsForm
                    Class ProductSaleElementsForm

        Generated by Sami, the API Documentation Generator.


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p5;

import org.gradle.test.performance.mediummonolithicjavaproject.p4.Production97;
import org.gradle.test.performance.mediummonolithicjavaproject.p4.Production98;
import org.gradle.test.performance.mediummonolithicjavaproject.p4.Production99;

public class Production100 {

    private Production97 property0;

    public Production97 getProperty0() {
        return property0;
    }

    public void setProperty0(Production97 value) {
        property0 = value;
    }

    private Production98 property1;

    public Production98 getProperty1() {
        return property1;
    }

    public void setProperty1(Production98 value) {
        property1 = value;
    }

    private Production99 property2;

    public Production99 getProperty2() {
        return property2;
    }

    public void setProperty2(Production99 value) {
        property2 = value;
    }

    private String property3;

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String value) {
        property3 = value;
    }

    private String property4;

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String value) {
        property4 = value;
    }

    private String property5;

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String value) {
        property5 = value;
    }

    private String property6;

    public String getProperty6() {
        return property6;
    }

    public void setProperty6(String value) {
        property6 = value;
    }

    private String property7;

    public String getProperty7() {
        return property7;
    }

    public void setProperty7(String value) {
        property7 = value;
    }

    private String property8;

    public String getProperty8() {
        return property8;
    }

    public void setProperty8(String value) {
        property8 = value;
    }

    private String property9;

    public String getProperty9() {
        return property9;
    }

    public void setProperty9(String value) {
        property9 = value;
    }

}


text:
module.exports = function(app) {
    const mongooseClient = app.get('mongooseClient');
    const products = new mongooseClient.Schema({
        name: { type: String, required: true },
        price: { type: Number, required: true },
        createdAt: { type: Date, default: Date.now },
        updatedAt: { type: Date, default: Date.now }
    });

    return mongooseClient.model('products', products);
};


text:
using namespace llvm;

static cl::
opt<bool> DisableMIPeephole("disable-bpf-peephole", cl::Hidden,
                            cl::desc("Disable machine peepholes for BPF"));

extern "C" void LLVMInitializeBPFTarget() {
  // Register the target.
  RegisterTargetMachine<BPFTargetMachine> X(getTheBPFleTarget());
  RegisterTargetMachine<BPFTargetMachine> Y(getTheBPFbeTarget());
  RegisterTargetMachine<BPFTargetMachine> Z(getTheBPFTarget());

  PassRegistry &PR = *PassRegistry::getPassRegistry();
  initializeBPFMIPeepholePass(PR);
}

// DataLayout: little or big endian
static std::string computeDataLayout(const Triple &TT) {
  if (TT.getArch() == Triple::bpfeb)
    return "E-m:e-p:64:64-i64:64-n32:64-S128";
  else
    return "e-m:e-p:64:64-i64:64-n32:64-S128";
}

static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
  if (!RM.hasValue())
    return Reloc::PIC_;
  return *RM;
}

static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) {
  if (CM)
    return *CM;
  return CodeModel::Small;
}

BPFTargetMachine::BPFTargetMachine(const Target &T, const Triple &TT,
                                   StringRef CPU, StringRef FS,
                                   const TargetOptions &Options,
                                   Optional<Reloc::Model> RM,
                                   Optional<CodeModel::Model> CM,
                                   CodeGenOpt::Level OL, bool JIT)
    : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
                        getEffectiveRelocModel(RM), getEffectiveCodeModel(CM),
                        OL),
      TLOF(make_unique<TargetLoweringObjectFileELF>()),
      Subtarget(TT, CPU, FS, *this) {
  initAsmInfo();

  BPFMCAsmInfo *MAI = static_cast<BPFMCAsmInfo *>(const_cast<MCAsmInfo *>(AsmInfo));
  MAI->setDwarfUsesRelocationsAcrossSections(!Subtarget.getUseDwarfRIS());
}
namespace {
// BPF Code Generator Pass Configuration Options.
class BPFPassConfig : public TargetPassConfig {
public:
  BPFPassConfig(BPFTargetMachine &TM, PassManagerBase &PM)
      : TargetPassConfig(TM, PM) {}

  BPFTargetMachine &getBPFTargetMachine() const {
    return getTM<BPFTargetMachine>();
  }

  bool addInstSelector() override;
  void addMachineSSAOptimization() override;
  void addPreEmitPass() override;
};
}

TargetPassConfig *BPFTargetMachine::createPassConfig(PassManagerBase &PM) {
  return new BPFPassConfig(*this, PM);
}

// Install an instruction selector pass using
// the ISelDag to gen BPF code.
bool BPFPassConfig::addInstSelector() {
  addPass(createBPFISelDag(getBPFTargetMachine()));

  return false;
}

void BPFPassConfig::addMachineSSAOptimization() {
  // The default implementation must be called first as we want eBPF
  // Peephole ran at last.
  TargetPassConfig::addMachineSSAOptimization();

  const BPFSubtarget *Subtarget = getBPFTargetMachine().getSubtargetImpl();
  if (Subtarget->getHasAlu32() && !DisableMIPeephole)
    addPass(createBPFMIPeepholePass());
}

void BPFPassConfig::addPreEmitPass() {
  const BPFSubtarget *Subtarget = getBPFTargetMachine().getSubtargetImpl();

  if (getOptLevel() != CodeGenOpt::None)
    if (Subtarget->getHasAlu32() && !DisableMIPeephole)
      addPass(createBPFMIPreEmitPeepholePass());
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ContosoUniversity.Models
{
    public class Instructor : Person
    {
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Hire Date")]
        public DateTime HireDate { get; set; }

        public virtual ICollection<Course> Courses { get; set; }
        public virtual OfficeAssignment OfficeAssignment { get; set; }
    }
}


text:
let socket = io();

// Set up Feathers client side
let app = feathers()
  .configure(feathers.socketio(socket))
  .configure(feathers.hooks())
  .configure(feathers.authentication({
    storage: localStorage
  }));

$('.logout').on('click', function () {
  app.logout().then(() => window.location.href = '/login.html');
});

$(document).ready(function () {

  socket.on('connect', function () {

    app.authenticate()
      .catch(function (error) {
        window.location.href = '/login.html';
      });

    socket.emit('joinRoom', {
      text: this.id,
      roomId: getQueryVariable('id')
    });

  });

  socket.on('hello', function (data) {

    console.log(data);

  });

  socket.on('salam', function (data) {

    console.log(data);

  });

  socket.on('iniroom', function (data) {

    console.log(data);

  });

  socket.on('getMessages', function (data, id) {

    leftMessage(data, id);

  });

  app.authenticate()
    .then(response => {
      console.log('Authenticated!', response);
      // By this point your accessToken has been stored in
      // localstorage

      tokens = response.accessToken;

      return app.passport.verifyJWT(response.accessToken);
    })
    .then(payload => {
      console.log('JWT Payload', payload);
      return app.service('users').get(payload.userId);
    })
    .then(user => {
      app.set('user', user);

      $('.username').append(user.firstName);

      app.service('projects').find({

        query: {
          id: getQueryVariable('id'),
          include: 1
        }

      })
        .then(respone => {

          const team = respone.data[0].users;

          team.forEach(function (data) {

            $('#team-result').append(
              `

${data.firstName} ${data.lastName}

programer asdasd asd as da

tokopediaasdasdasdasdasdasd

`)

          })

          const respones = respone.data[0];

          $(".projectname").append(respones.ProjectTitle);
          $(".projectroom").append(respones.id);

          $("#pname").append(respones.ProjectTitle);
          $("#pmname").append(respones.PmName);
          $("#strtdate").append(moment(respones.StartDate).format('DD-MM-YYYY'));
          $("#enddate").append(moment(respones.EndDate).format('DD-MM-YYYY'));

          $('#chlink').attr('href', '/projectcharter.html?id=' + getQueryVariable('id'));
          $('#mmlink').attr('href', '/mindmaps.html?id=' + getQueryVariable('id'));
          $('#gclink').attr('href', '/ganttchart.html?id=' + getQueryVariable('id'));

          $('#teamlink').attr('href', '/team.html?id=' + getQueryVariable('id'));

        });

      app.service('messages').find({
        query: {
          roomID: getQueryVariable('id'),
          $sort: {id: 1}
        }
      })
        .then(page => {

          const messages = page.data;

          for (let i = 0; i < messages.length; i++) {

            (function (i) {

              setTimeout(function () {

                if (messages[i].senderID != user.id) {
                  leftMessages(messages[i]);
                }
                else {
                  rightMessages(messages[i], user.firstName);
                }

              }, i * 50);

            })(i);

          }

        })
        .catch(function (error) {
          console.log(error);
        });

    })
    .then(() => {
      findInvitation();
      findFriends(getQueryVariable('id'));
    })
    .then(() => {
      stopIntro();
    })
    .catch(function (error) {
      //window.location.href = '/login.html';

      console.log(error)

    });

  function rightMessages(data, name) {

    $('.messages').append(
      `

     ${moment(data.createdAt).format('h:mm a')}, Today
     ${name}

${data.messagesBody}

`
    );

    toBottom();

  }

  function leftMessages(data) {

    app.service('users').get(data.senderID)
      .then(respone => {

        $('.messages').append(
          `

      ${respone.firstName}
      ${moment(data.createdAt).format('h:mm a')}, Today

${data.messagesBody}

`
        );

      });

    toBottom();

  }

  function leftMessage(data, id) {

    app.service('users').get(id)
      .then(respone => {

        $('.messages').append(
          `

      ${respone.firstName}
      ${moment().format('h:mm a')}, Today

${data}

`
        );

      });

    toBottom();

  }

});

function toBottom() {

  $('.messages').scrollTop(100000);

};

function getQueryVariable(variable) {

  let query = window.location.search.substring(1);
  let vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  console.log('Query Variable ' + variable + ' not found');

};

function send(data) {
  socket.emit('sendMessages', data);
};

function stopIntro() {

  $(".se-pre-con").fadeOut("slow");

}


text:
  <link rel="stylesheet" href="maven-theme.css">
  <title>AppSecInc. MSI Extensions</title>

Main Page

Related Pages

Namespaces

Classes

Files

File List

File Members

src

CustomActions

DataSource

Functions

SqlDMO.h File Reference

Go to the source code of this file.

Functions

CA_API UINT __stdcall 	SQLDMO_ListAvailableSQLServers (MSIHANDLE hInstall)

 	Enumerate available SQL servers using Data Management Objects (DMO).  More...

Function Documentation

          CA_API UINT __stdcall SQLDMO_ListAvailableSQLServers
          (
          MSIHANDLE
          hInstall	)

Enumerate available SQL servers using Data Management Objects (DMO).

Parameters

SQLDMO_LIST_TYPE	List type to populate with data.

SQLDMO_LIST_PROPERTY	The property associated with the list.

SQLDMO_LIST_INDEX	Optional index to start adding items at, default is 2 (assumes one item in the list already).

SQLDMO_LIST_LOCAL	Optional name to skip, eg. useful for local servers with "(local)".

This function populates an MSI list attached to a property SQLDMO_LIST_PROPERTY and of type SQLDMO_LIST_TYPE, beginning with index SQLDMO_LIST_INDEX (default is 2, assuming there's one item). It executes SELECT * FROM [SQLDMO_LIST_TYPE] WHERE Property=[SQLDMO_LIST_PROPERTY] to locate the target.

See http://support.microsoft.com/kb/287737 for details about retreiving SQL servers with DMO.

This custom action can be used in combination with a combo box. Call the CA in the InstallUISequence.

<CustomAction Id="SetSqlDmoListLocal" Property="SQLDMO_LIST_LOCAL" Value="(local)" Execute="immediate" />

<CustomAction Id="SetSqlDmoListIndex" Property="SQLDMO_LIST_INDEX" Value="2" Execute="immediate" />

<CustomAction Id="SetSqlDmoListProperty" Property="SQLDMO_LIST_PROPERTY" Value="DATABASE_SERVER" Execute="immediate" />

<CustomAction Id="SetSqlDmoListType" Property="SQLDMO_LIST_TYPE" Value="ComboBox" Execute="immediate" />

<InstallUISequence>

  <Custom Action="SetSqlDmoListProperty" After="CostInitialize" />

  <Custom Action="SetSqlDmoListType" After="SetSqlDmoListProperty" />

  <Custom Action="SetSqlDmoListIndex" After="SetSqlDmoListType" />

  <Custom Action="SetSqlDmoListLocal" After="SetSqlDmoListIndex" />

  <Custom Action="SQLDMO_ListAvailableSQLServers" After="SetSqlDmoListType">NOT Installed</Custom>

</InstallUISequence>

Use a ComboBox control in the UI.

<Control Id="Server" Type="ComboBox" X="30" Y="65" Width="200" Height="18" Property="DATABASE_SERVER">

  <ComboBox Property="DATABASE_SERVER">

    <ListItem Text="(local)" Value="(local)" />

  </ComboBox>

</Control>

     © Application Security Inc. - All Rights Reserved

     http://msiext.codeplex.com

  <link href="tabs.css" rel="stylesheet" type="text/css">


text:
package com.profitbricks.rest.domain;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author jasmin@stackpointcloud.com
 */
public class DataCenters extends ProfitbricksBase {

   private List<DataCenter> items =  new ArrayList<DataCenter>();

   /**
    * @return the items
    */
   public List<DataCenter> getItems() {
      return items;
   }

   /**
    * @param items the items to set
    */
   public void setItems(List<DataCenter> items) {
      this.items = items;
   }
}


text:
@interface menuPage : CCLayer <UIWebViewDelegate>
{

	CCMenuItemImage * _plusItem, *	_minusItem;
	CCMenuItemImage * _plusItem1, *	_minusItem1;
	UIWebView *vw_img1;
	CCSprite *scroll;
	//UIButton *btnimgvAlShow;
}

-(void) startOfGame;
-(void)soundCase;
- (void)plusMinusButtonTapped:(id)sender;

-(void)musicCase;
- (void)plusMinusButtonTapped1:(id)sender;
-(void)otherGamesCase;
-(void)buttonPressed;
-(void)tutorialPage;
-(void)aboutPage;
-(void)levelSelectionPage;
-(void)needToStart2;

@end


text:
import { EventEmitter } from 'events';
import * as os from 'os';
import Web3 from 'web3';
import { ChainStateProvider } from '../../';
import { timestamp } from '../../../../logger';
import logger from '../../../../logger';
import { StateStorage } from '../../../../models/state';
import { BaseP2PWorker } from '../../../../services/p2p';
import { IEVMNetworkConfig } from '../../../../types/Config';
import { valueOrDefault } from '../../../../utils/check';
import { wait } from '../../../../utils/wait';
import { BaseEVMStateProvider } from '../api/csp';
import { EVMBlockModel, EVMBlockStorage } from '../models/block';
import { EVMTransactionModel, EVMTransactionStorage } from '../models/transaction';
import { AnyBlock, ErigonTransaction, GethTransaction, IEVMBlock, IEVMTransaction } from '../types';
import { IRpc, Rpcs } from './rpcs';
import { MultiThreadSync } from './sync';

export class EVMP2pWorker extends BaseP2PWorker<IEVMBlock> {
  protected chainConfig: IEVMNetworkConfig;
  protected syncing: boolean;
  protected initialSyncComplete: boolean;
  protected blockModel: EVMBlockModel;
  protected txModel: EVMTransactionModel;
  protected txSubscription: any;
  protected blockSubscription: any;
  protected rpc?: IRpc;
  protected provider: BaseEVMStateProvider;
  protected web3?: Web3;
  protected client?: 'geth' | 'erigon';
  protected invCache: any;
  protected invCacheLimits: any;
  protected multiThreadSync: MultiThreadSync;
  public events: EventEmitter;
  public disconnecting: boolean;

  constructor({ chain, network, chainConfig, blockModel = EVMBlockStorage, txModel = EVMTransactionStorage }) {
    super({ chain, network, chainConfig, blockModel });
    this.chain = chain || 'ETH';
    this.network = network;
    this.chainConfig = chainConfig;
    this.syncing = false;
    this.initialSyncComplete = false;
    this.blockModel = blockModel;
    this.txModel = txModel;
    this.provider = new BaseEVMStateProvider(this.chain);
    this.events = new EventEmitter();
    this.invCache = {};
    this.invCacheLimits = {
      TX: 100000
    };
    this.disconnecting = false;
    this.multiThreadSync = new MultiThreadSync({ chain, network });
  }

  cacheInv(type: 'TX', hash: string): void {
    if (!this.invCache[type]) {
      this.invCache[type] = [];
    }
    if (this.invCache[type].length > this.invCacheLimits[type]) {
      this.invCache[type].shift();
    }
    this.invCache[type].push(hash);
  }

  isCachedInv(type: 'TX', hash: string): boolean {
    if (!this.invCache[type]) {
      this.invCache[type] = [];
    }
    return this.invCache[type].includes(hash);
  }

  async setupListeners() {
    const { host, port } = this.chainConfig.provider || this.chainConfig.providers![0];
    this.events.on('disconnected', async () => {
      logger.warn(
        `${timestamp()} | Not connected to peer: ${host}:${port} | Chain: ${this.chain} | Network: ${this.network}`
      );
    });
    this.events.on('connected', async () => {
      this.txSubscription = await this.web3!.eth.subscribe('pendingTransactions');
      this.txSubscription.subscribe(async (_err, txid) => {
        if (!this.isCachedInv('TX', txid)) {
          this.cacheInv('TX', txid);
          const tx = (await this.web3!.eth.getTransaction(txid)) as ErigonTransaction;
          if (tx) {
            await this.processTransaction(tx);
            this.events.emit('transaction', tx);
          }
        }
      });
      this.blockSubscription = await this.web3!.eth.subscribe('newBlockHeaders');
      this.blockSubscription.subscribe((_err, block) => {
        this.events.emit('block', block);
        if (!this.syncing) {
          this.sync();
        }
      });
    });

    this.multiThreadSync.once('INITIALSYNCDONE', () => {
      this.initialSyncComplete = true;
      this.events.emit('SYNCDONE');
    });
  }

  async disconnect() {
    this.disconnecting = true;
    try {
      if (this.txSubscription) {
        this.txSubscription.unsubscribe();
      }
      if (this.blockSubscription) {
        this.blockSubscription.unsubscribe();
      }
    } catch (e) {
      console.error(e);
    }
  }

  async getWeb3() {
    return this.provider.getWeb3(this.network);
  }

  async getClient() {
    try {
      const nodeVersion = await this.web3!.eth.getNodeInfo();
      const client = nodeVersion.split('/')[0].toLowerCase() as 'erigon' | 'geth';
      if (client !== 'erigon' && client !== 'geth') {
        // assume it's a geth fork, or at least more like geth.
        // this is helpful when using a dev solution like ganache.
        return 'geth';
      }
      return client;
    } catch (e) {
      console.error(e);
      return 'geth';
    }
  }

  async handleReconnects() {
    this.disconnecting = false;
    let firstConnect = true;
    let connected = false;
    let disconnected = false;
    const { host, port } = this.chainConfig.provider || this.chainConfig.providers![0];
    while (!this.disconnecting && !this.stopping) {
      try {
        if (!this.web3) {
          const { web3 } = await this.getWeb3();
          this.web3 = web3;
        }
        try {
          if (!this.client || !this.rpc) {
            this.client = await this.getClient();
            this.rpc = new Rpcs[this.client](this.web3);
          }
          connected = await this.web3.eth.net.isListening();
        } catch (e) {
          connected = false;
        }
        if (!connected) {
          this.web3 = undefined;
          this.client = undefined;
          this.events.emit('disconnected');
        } else if (disconnected || firstConnect) {
          this.events.emit('connected');
        }
        if (disconnected && connected && !firstConnect) {
          logger.warn(
            `${timestamp()} | Reconnected to peer: ${host}:${port} | Chain: ${this.chain} | Network: ${this.network}`
          );
        }
        if (connected && firstConnect) {
          firstConnect = false;
          logger.info(
            `${timestamp()} | Connected to peer: ${host}:${port} | Chain: ${this.chain} | Network: ${this.network}`
          );
        }
        disconnected = !connected;
      } catch (e) {}
      await wait(2000);
    }
  }

  async connect() {
    this.handleReconnects();
    return new Promise<void>(resolve => this.events.once('connected', resolve));
  }

  public async getBlock(height: number) {
    return this.rpc!.getBlock(height);
  }

  async processBlock(block: IEVMBlock, transactions: IEVMTransaction[]): Promise<any> {
    await this.blockModel.addBlock({
      chain: this.chain,
      network: this.network,
      forkHeight: this.chainConfig.forkHeight,
      parentChain: this.chainConfig.parentChain,
      initialSyncComplete: this.initialSyncComplete,
      block,
      transactions
    });
    if (!this.syncing) {
      logger.info(`Added block ${block.hash}`, {
        chain: this.chain,
        network: this.network
      });
    }
  }

  async processTransaction(tx: ErigonTransaction | GethTransaction) {
    const now = new Date();
    const convertedTx = this.convertTx(tx);
    this.txModel.batchImport({
      chain: this.chain,
      network: this.network,
      txs: [convertedTx],
      height: -1,
      mempoolTime: now,
      blockTime: now,
      blockTimeNormalized: now,
      initialSyncComplete: true
    });
  }

  useMultiThread() {
    if (this.chainConfig.threads == null) {
      // use multithread by default if there are >2 threads in the CPU
      return os.cpus().length > 2;
    }
    return this.chainConfig.threads > 0;
  }

  async sync() {
    if (this.syncing) {
      return false;
    }

    if (!this.initialSyncComplete && this.useMultiThread()) {
      return this.multiThreadSync.sync();
    }

    const { chain, chainConfig, network } = this;
    const { parentChain, forkHeight = 0 } = chainConfig;
    this.syncing = true;
    const state = await StateStorage.collection.findOne({});
    this.initialSyncComplete =
      state && state.initialSyncComplete && state.initialSyncComplete.includes(`${chain}:${network}`);
    let tip = await ChainStateProvider.getLocalTip({ chain, network });
    if (parentChain && (!tip || tip.height < forkHeight)) {
      let parentTip = await ChainStateProvider.getLocalTip({ chain: parentChain, network });
      while (!parentTip || parentTip.height < forkHeight) {
        logger.info(`Waiting until ${parentChain} syncs before ${chain} ${network}`);
        await new Promise(resolve => {
          setTimeout(resolve, 5000);
        });
        parentTip = await ChainStateProvider.getLocalTip({ chain: parentChain, network });
      }
    }

    const startHeight = tip ? tip.height : chainConfig.syncStartHeight || 0;
    const startTime = Date.now();
    try {
      let bestBlock = await this.web3!.eth.getBlockNumber();
      let lastLog = 0;
      let currentHeight = tip ? tip.height : chainConfig.syncStartHeight || 0;
      logger.info(`Syncing ${bestBlock - currentHeight} blocks for ${chain} ${network}`);
      while (currentHeight <= bestBlock) {
        const block = await this.getBlock(currentHeight);
        if (!block) {
          await wait(1000);
          continue;
        }
        const { convertedBlock, convertedTxs } = await this.convertBlock(block);
        await this.processBlock(convertedBlock, convertedTxs);
        if (currentHeight === bestBlock) {
          bestBlock = await this.web3!.eth.getBlockNumber();
        }
        tip = await ChainStateProvider.getLocalTip({ chain, network });
        currentHeight = tip ? tip.height + 1 : 0;

        const oneSecond = 1000;
        const now = Date.now();
        if (now - lastLog > oneSecond) {
          const blocksProcessed = currentHeight - startHeight;
          const elapsedMinutes = (now - startTime) / (60 * oneSecond);
          logger.info(
            `${timestamp()} | Syncing... | Chain: ${chain} | Network: ${network} |${(blocksProcessed / elapsedMinutes)
              .toFixed(2)
              .padStart(8)} blocks/min | Height: ${currentHeight.toString().padStart(7)}`
          );
          lastLog = Date.now();
        }
      }
    } catch (err) {
      logger.error(`Error syncing ${chain} ${network} -- ${err.message || err}`);
      await wait(2000);
      this.syncing = false;
      return this.sync();
    }
    logger.info(`${chain}:${network} up to date.`);
    this.syncing = false;
    StateStorage.collection.findOneAndUpdate(
      {},
      { $addToSet: { initialSyncComplete: `${chain}:${network}` } },
      { upsert: true }
    );
    this.events.emit('SYNCDONE');
    return true;
  }

  async syncDone() {
    return new Promise(resolve => this.events.once('SYNCDONE', resolve));
  }

  getBlockReward(block: AnyBlock): number {
    // TODO: implement block reward
    block;
    return 0;
  }

  async convertBlock(block: AnyBlock) {
    const blockTime = Number(block.timestamp) * 1000;
    const hash = block.hash;
    const height = block.number;
    const reward = this.getBlockReward(block);

    const convertedBlock: IEVMBlock = {
      chain: this.chain,
      network: this.network,
      height,
      hash,
      coinbase: Buffer.from(block.miner),
      merkleRoot: Buffer.from(block.transactionsRoot),
      time: new Date(blockTime),
      timeNormalized: new Date(blockTime),
      nonce: Buffer.from(block.extraData),
      previousBlockHash: block.parentHash,
      difficulty: block.difficulty,
      totalDifficulty: block.totalDifficulty,
      nextBlockHash: '',
      transactionCount: block.transactions.length,
      size: block.size,
      reward,
      logsBloom: Buffer.from(block.logsBloom),
      sha3Uncles: Buffer.from(block.sha3Uncles),
      receiptsRoot: Buffer.from(block.receiptsRoot),
      processed: false,
      gasLimit: block.gasLimit,
      gasUsed: block.gasUsed,
      stateRoot: Buffer.from(block.stateRoot)
    };
    const transactions = block.transactions as Array<ErigonTransaction | GethTransaction>;
    const convertedTxs = transactions.map(t => this.convertTx(t, convertedBlock));
    const traceTxs = await this.rpc!.getTransactionsFromBlock(convertedBlock.height);

    this.rpc!.reconcileTraces(convertedBlock, convertedTxs, traceTxs);

    return { convertedBlock, convertedTxs };
  }

  convertTx(tx: Partial<ErigonTransaction | GethTransaction>, block?: IEVMBlock): IEVMTransaction {
    if (!block) {
      const txid = tx.hash || '';
      const to = tx.to || '';
      const from = tx.from || '';
      const value = Number(tx.value);
      const fee = Number(tx.gas) * Number(tx.gasPrice);
      const abiType = this.txModel.abiDecode(tx.input!);
      const nonce = tx.nonce || 0;
      const convertedTx: IEVMTransaction = {
        chain: this.chain,
        network: this.network,
        blockHeight: valueOrDefault(tx.blockNumber, -1),
        blockHash: valueOrDefault(tx.blockHash, undefined),
        data: Buffer.from(tx.input || '0x'),
        txid,
        blockTime: new Date(),
        blockTimeNormalized: new Date(),
        fee,
        transactionIndex: tx.transactionIndex || 0,
        value,
        wallets: [],
        to,
        from,
        gasLimit: Number(tx.gas),
        gasPrice: Number(tx.gasPrice),
        // gasUsed: Number(tx.gasUsed),
        nonce,
        internal: [],
        calls: []
      };
      if (abiType) {
        convertedTx.abiType = abiType;
      }
      return convertedTx;
    } else {
      const { hash: blockHash, time: blockTime, timeNormalized: blockTimeNormalized, height } = block;
      const noBlockTx = this.convertTx(tx);
      return {
        ...noBlockTx,
        blockHeight: height,
        blockHash,
        blockTime,
        blockTimeNormalized
      };
    }
  }

  async stop() {
    this.stopping = true;
    this.multiThreadSync.stop();
    logger.debug(`Stopping worker for chain ${this.chain} ${this.network}`);
    await this.disconnect();
  }

  async start() {
    logger.debug(`Started worker for chain ${this.chain} ${this.network}`);
    this.setupListeners();
    await this.connect();
    this.sync();
  }
}


text:
//
//  @author raver119@gmail.com
//

#include <system/op_boilerplate.h>

#if NOT_EXCLUDED(OP_knn_mindistance)

#include <ops/declarable/helpers/knn.h>

namespace sd {
namespace ops {
namespace helpers {
template <typename T>
void mindistance_(const void *vinput, const void *vlow, const void *vhigh, int32_t length, void *vout) {
  auto input = reinterpret_cast<const T *>(vinput);
  auto low = reinterpret_cast<const T *>(vlow);
  auto high = reinterpret_cast<const T *>(vhigh);
  auto output = reinterpret_cast<T *>(vout);

  T res = 0.0f;
  T po = 2.f;
  T o = 1.f;
  PRAGMA_OMP_SIMD_SUM(res)
  for (auto e = 0; e < length; e++) {
    T p = input[e];
    T l = low[e];
    T h = high[e];
    if (!(l <= p || h <= p)) {
      if (p < l)
        res += sd::math::sd_pow<T, T, T>((p - o), po);
      else
        res += sd::math::sd_pow<T, T, T>((p - h), po);
    }
  }

  output[0] = sd::math::sd_pow<T, T, T>(res, (T)0.5f);
}

void knn_mindistance(const NDArray &input, const NDArray &lowest, const NDArray &highest, NDArray &output) {
  NDArray::preparePrimaryUse({&output}, {&input, &lowest, &highest});

  BUILD_SINGLE_SELECTOR(input.dataType(), mindistance_,
                        (input.buffer(), lowest.buffer(), highest.buffer(), input.lengthOf(), output.buffer()),
                        SD_FLOAT_TYPES);

  NDArray::registerPrimaryUse({&output}, {&input, &lowest, &highest});
}
}  // namespace helpers
}  // namespace ops
}  // namespace sd
#endif


text:
(function( $ ){
    "use strict";

	/**
	 * Enables you to select data using the DOM
	 * @class DomSelector
	 */
    var DomSelector = {
		/** Default options */
        _opts : {
            mode : 'once',	//
			selectedClass : 'selected'
        },

		/**
		 * Initialize the selection
		 *
		 * @memberOf DomSelector
		 * @param {Object} options
		 * @param {String} [options.mode="once"] the selection mode in: once, normal, exclusive
		 * @param {String} [options.selectedClass="selected"] css class applied on selected element
		 */
		_init : function(options){
			$.extend(DomSelector._opts, options);
			var opts = DomSelector._opts,
				selectMode = function selection($elt, selectedClass){
					if(opts.mode === 'once') {
						$elt.addClass(selectedClass);
					} else {
						$elt.toggleClass(selectedClass);
					}
				},
				$elts = this;
			return this.each(function() {
                var $elt = $(this);
				$elt.on('click', function(event){
					event.preventDefault;
					if(opts.mode === 'exclusive'){
						$elts.removeClass(opts.selectedClass);
					}
					selectMode($(this), opts.selectedClass);

					//trigger the 'selection.domselector' Event
					$elt.trigger('selection.domselector', $elt.domSelector('getSelected'));
					return false;
				});
			});
		},
		/**
		 * Get the currently selected elements
		 * @return {Array|String} the selected data
		 */
		getSelected : function(){
			var opts = DomSelector._opts,
				selected = [];
            this.each(function() {
                var $elt = $(this);
                if($elt.hasClass(opts.selectedClass)){
					switch($elt.prop("tagName").toLowerCase()){
						case 'img':
							selected.push($elt.attr('src')); break;
						case 'a':
							selected.push($elt.attr('href')); break;
						default :
							selected.push($elt.text()); break;
					}
                }
            });

            return (selected.length === 1) ? selected[0] : selected;
		}
	};

	/**
	 * jQuery plugin wrapper for the DomSelector object
	 */
    $.fn.domSelector = function( method ) {
        if ( DomSelector[method] ) {
            if(/^_/.test(method)){
                $.error( 'Trying to call a private method ' +  method + ' on jQuery.domSelector' );
			} else {
                return DomSelector[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
			}
        } else if ( typeof method === 'object' || ! method ) {
            return DomSelector._init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.domSelector' );
        }
    };
})( jQuery );


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Denmark Australia Diophantine Approximation Day">
    <meta name="author" content="Fabien Pazuki">

    <title>Denmark Australia Diophantine Approximation Day</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/portfolio-item.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                \(\mathbb{N}^3\)

                        Events

                        Members

                        Contact

                        Sponsors

                        History

                        Files

Denmark Australia Diophantine Approximation Day

				The aim of the meeting is to gather experts studying diophantine approximation and number theory.

 Location:
 Aarhus University: Auditorium D1, Department of Mathematics, Aarhus University, Ny Munkegade 118, 8000 Aarhus C.

 Dates:
 8 December 2017.

 Speakers:

Michael Coons (Univ. Newcastle)

Alex Ghitza (Univ. Melbourne)

Simon Kristensen (Aarhus Univ.)

Fabien Pazuki (Univ. Copenhagen)

Evgeniy Zorin (Univ. York)

 Program:
 The conference will start at 9:30 and will end at 17:30 on Friday 8.
				Click here for the detailed program.

 Organizers:
 Simon Kristensen (Aarhus Univ.), Fabien Pazuki (Univ. Copenhagen).

 Registration:
 There is no registration fee but if you want to participate we kindly ask you to send an email to fpazuki AT math.ku.dk.

 Directions:
 The conference will take place in Auditorium D1, Department of Mathematics, Aarhus University, Ny Munkegade 118, 8000 Aarhus C. Busses from the train station are 2A, 13 and 16. You should get off at Langelandsgade/Kasserneboulevarden. There's a short walk from the bus stop to the Department.

 Sponsors:

				Niels Bohr Professorship of Lars Hesselholt (Denmark).

Copyright © \(\mathbb{N}^3\)


text:
package gov.nasa.worldwind.formats.vpf;

import gov.nasa.worldwind.util.Logging;

import java.util.Comparator;

/**
 * From MIL-HDBK-857A, section 6.5: Display Hierarchy.  In order to ensure that features that overlap other are drawn in
 * the correct sequence, the GeoSym application software must allow for the definition of a display order for the
 * features being displayed.  GeoSym uses four "nested" methods to define the order in which symbols should be
 * displayed.
 *

 * 1. Display priority 2. Feature delineation 3. Order of rows in *sym.txt 4. Symbol type
 *

 * 6.5.1  Display Priority.  The first criterion to use to determine the order to display features is the display
 * priority.  Each row in the *sym.txt file defines a display priority number to that specific feature/attribute. The
 * display priority is a value between 0 and 9, where 9 identifies the highest priority.  A feature/attribute with a
 * higher priority should be displayed after (on top of) one with a lower priority.  For DNC, the values contained in
 * the display priority field are defined based on the S52 lookup tables.  Each DNC feature/attribute was mapped to a
 * corresponding S57 object class/attribute.  The S52 lookup tables were then utilized to obtain the display priority
 * values assigned to each object class.  For all other products, the display priority values were based on cartographic
 * experience with the corresponding hardcopy map/chart.
 *

 * 6.5.2  Feature Delineation.  Once the features to be displayed have been sorted based on display priority, they must
 * then be sorted by their delineation (area, line, point).  If the display priority is equal among features, then the
 * "painter's algorithm" should be used to display the area features first, followed by the linear features and then the
 * point features.
 *

 * 6.5.3  Order of Rows in *sym.txt.  The third criterion that affects the display order is the order of the rows in the
 * fullsym.txt file.  The order will be represented in the id column of each row.  Row ids will always be serial but may
 * not necessarily be consecutive.  Stated another way, the row ID for row N will always be less than the row ID for row
 * N+1.  Symbology being displayed based on this criterion should be displayed based on the least row id to the greatest
 * row id.
 *

 * 6.5.3.1  Point Features with Components.  For point features (e.g., buoys, beacons, lights) that are composed of
 * several symbol components, displaying the components according to the row ids in the *sym.txt file will result in the
 * properly constructed composite symbol.  Each symbol component is based on the value of a specific attribute and the
 * components will vary in display priority so should already have been sorted according to that value before examining
 * the row ids in the *sym.txt file.
 *

 * 6.5.3.2  Area Features with Multiple Fills.  There are some area features (e.g., Maritime Areas) that require both a
 * solid fill and one or more pattern fills.  Since the areasym column can only contain a single CGM reference, there is
 * a separate row in the *sym.txt file for each of the area symbols, as well as for the line symbol and/or point symbol
 * that apply to the specific area feature.  These multiple rows will have sequential row ids in the *sym.txt file
 * according to the order in which the symbols are to be displayed on the screen:  solid fill, pattern fill (may be more
 * than one), linear boundary, centered point symbol (may be more than one).
 *

 * 6.5.3.3  Features with Text Labels  As a general rule, the display priority specified for a feature's text label(s)
 * is the highest value possible, regardless of the display priority assigned to the base feature.  In DNC, all text
 * labels will have a display priority of 8 (per IHO S52).  In all other products, text labels have a display priority
 * of 9.  Therefore, the text labels will by default be displayed on top of all other symbols since the display priority
 * value is the first criterion controlling the order of symbology display on the screen. However, it is possible that a
 * critical feature in a product (e.g., area bridges in DNC) may be assigned the same high priority as the text label
 * for that feature.  Since the row(s) defining the text label(s) will always follow the row(s) defining the CGM symbols
 * for a feature, displaying the symbols and text labels according to their row ids (lowest to highest) in *sym.txt will
 * still result in the correct final symbology for a feature being displayed.
 *

 * 6.5.4  Symbol Type.  The final criterion for determining the order for symbol display applies only to area features.
 * Area features can be symbolized by any combination of centered point symbol, linear boundary, solid fill and/or
 * pattern fill.  Except for the special case where an area feature's symbology requires both a solid and pattern
 * fill(s) (see section 6.5.3.2), all symbols for an area feature will be specified in the same row of the *sym.txt
 * file.  In other words, any or all of the symbol columns may be populated.  In these cases, the symbols are to be
 * displayed according to the same "painter's algorithm" that applies at the feature level:  the area symbol (from
 * areasym) should be drawn first, followed by the linear symbol (from linesym) followed by the point symbol (from
 * pointsym).
 *
 * @author dcollins
 * @version $Id: VPFSymbolComparator.java 1171 2013-02-11 21:45:02Z dcollins $
 */
public class VPFSymbolComparator implements Comparator<VPFSymbol>
{
    public VPFSymbolComparator()
    {
    }

    /**
     * @param a
     * @param b
     *
     * @return
     */
    public int compare(VPFSymbol a, VPFSymbol b)
    {
        if (a == null || b == null)
        {
            String message = Logging.getMessage("nullValue.SymbolIsNull");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }

        VPFSymbolAttributes aAttr = a.getAttributes();
        VPFSymbolAttributes bAttr = b.getAttributes();

        if (aAttr == null && bAttr == null)
            return 0;

        if (aAttr == null || bAttr == null)
            return (aAttr != null) ? -1 : 1;

        double aPriority = a.getAttributes().getDisplayPriority();
        double bPriority = b.getAttributes().getDisplayPriority();
        int i = (aPriority < bPriority) ? -1 : (aPriority > bPriority ? 1 : 0);
        if (i != 0)
            return i;

        aPriority = this.getFeatureTypePriority(a.getAttributes().getFeatureType());
        bPriority = this.getFeatureTypePriority(b.getAttributes().getFeatureType());
        i = (aPriority < bPriority) ? -1 : (aPriority > bPriority ? 1 : 0);
        if (i != 0)
            return i;

        VPFSymbolKey aKey = a.getAttributes().getSymbolKey();
        VPFSymbolKey bKey = b.getAttributes().getSymbolKey();
        i = aKey.compareTo(bKey);
        if (i != 0)
            return i;

        return 0;
    }

    protected int getFeatureTypePriority(VPFFeatureType type)
    {
        switch (type)
        {
            case POINT:
                return 3;
            case LINE:
                return 2;
            case AREA:
                return 1;
            default:
                return 0;
        }
    }
}


text:
Come posso segnalare un campetto non presente sulla mappa?

Puoi segnalare un campetto scrivendo una mail a staff@playground-milano.it, comunicandoci l'indirizzo.


text:
<?php

namespace TobiasTest\Expressive\Form;

use Interop\Container\ContainerInterface;
use Tobias\Expressive\Form\FormElementManagerDelegatorFactory;
use Zend\Form\FormElementManager\FormElementManagerV2Polyfill;
use Zend\Form\FormElementManager\FormElementManagerV3Polyfill;
use Zend\Form\FormElementManagerFactory;
use Zend\ServiceManager\DelegatorFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Class FormElementManagerDelegatorFactoryTest
 * @package TobiasTest\Expressive\Form\Delegator
 */
class FormElementManagerDelegatorFactoryTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @return array
     */
    public function dataProvider()
    {
        return [
            [ContainerInterface::class, '__invoke'],
            [ServiceLocatorInterface::class, 'createDelegatorWithName'],
        ];
    }

    /**
     * @dataProvider dataProvider
     */
    public function testInvokeDelegator($interface, $method)
    {
        $config = [
            'form_elements' => [],
        ];

        /** @var ContainerInterface|\PHPUnit_Framework_MockObject_MockObject $container */
        $container = $this->getMockBuilder($interface)->getMockForAbstractClass();
        $container->expects($this->once())->method('has')->with('config')->will($this->returnValue(true));
        $container->expects($this->once())->method('get')->with('config')->will($this->returnValue($config));

        $callback = function () use ($container) {
            $factory = new FormElementManagerFactory();

            return $factory($container, 'FormElementManager');
        };
        $subject = new FormElementManagerDelegatorFactory();
        $this->assertInstanceOf(DelegatorFactoryInterface::class, $subject);

        if ($container instanceof ServiceLocatorInterface) {
            $instance = $subject->$method($container, 'FormElementManager', 'FormElementManager', $callback);
        } else {
            $instance = $subject->$method($container, 'FormElementManager', $callback);
        }
        if (method_exists($instance, 'configure')) {
            $this->assertInstanceOf(FormElementManagerV3Polyfill::class, $instance);
        } else {
            $this->assertInstanceOf(FormElementManagerV2Polyfill::class, $instance);
        }
    }
}


text:
package mysql

type Result struct {
	Status       uint16
	InsertId     uint64
	AffectedRows uint64
	*Resultset
}


text:
#ifndef GCC_GCC_H
#define GCC_GCC_H

#include "version.h"

/* The mapping of a spec function name to the C function that
   implements it.  */
struct spec_function
{
  const char *name;
  const char *(*func) (int, const char **);
};

/* This defines which switch letters take arguments.  */

#define DEFAULT_SWITCH_TAKES_ARG(CHAR) \
  ((CHAR) == 'D' || (CHAR) == 'U' || (CHAR) == 'o' \
   || (CHAR) == 'e' || (CHAR) == 'T' || (CHAR) == 'u' \
   || (CHAR) == 'I' || (CHAR) == 'm' || (CHAR) == 'x' \
   || (CHAR) == 'L' || (CHAR) == 'A' || (CHAR) == 'V' \
   || (CHAR) == 'B' || (CHAR) == 'b')

/* This defines which multi-letter switches take arguments.  */

#define DEFAULT_WORD_SWITCH_TAKES_ARG(STR)		\
 (!strcmp (STR, "Tdata") || !strcmp (STR, "Ttext")	\
  || !strcmp (STR, "Tbss") || !strcmp (STR, "include")	\
  || !strcmp (STR, "imacros") || !strcmp (STR, "aux-info") \
  || !strcmp (STR, "idirafter") || !strcmp (STR, "iprefix") \
  || !strcmp (STR, "iwithprefix") || !strcmp (STR, "iwithprefixbefore") \
  || !strcmp (STR, "iquote") || !strcmp (STR, "isystem") \
  || !strcmp (STR, "isysroot") \
  || !strcmp (STR, "-param") || !strcmp (STR, "specs") \
  || !strcmp (STR, "MF") || !strcmp (STR, "MT") || !strcmp (STR, "MQ"))

/* These are exported by gcc.c.  */
extern int do_spec (const char *);
extern void record_temp_file (const char *, int, int);
extern void fatal (const char *, ...) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
extern void error (const char *, ...) ATTRIBUTE_PRINTF_1;
extern void pfatal_with_name (const char *) ATTRIBUTE_NORETURN;
extern void set_input (const char *);

/* Spec files linked with gcc.c must provide definitions for these.  */

/* Called before processing to change/add/remove arguments.  */
extern void lang_specific_driver (int *, const char *const **, int *);

/* Called before linking.  Returns 0 on success and -1 on failure.  */
extern int lang_specific_pre_link (void);

extern int n_infiles;

/* Number of extra output files that lang_specific_pre_link may generate.  */
extern int lang_specific_extra_outfiles;

/* A vector of corresponding output files is made up later.  */

extern const char **outfiles;

#endif /* ! GCC_GCC_H */


text:
<?php
namespace Chat\ChatBundle\Interfaces;

use Ratchet\ConnectionInterface;

interface ConnectedClientInterface
{

    /**
     * @return mixed
     */
    public function getResourceId();

    /**
     * @param mixed $resourceId
     */
    public function setResourceId($resourceId);

    /**
     * @return ConnectionInterface
     */
    public function getConnection();

    /**
     * @param ConnectionInterface $connection
     */
    public function setConnection($connection);

    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return array
     */
    public function asArray();

}


text:
from typing import Union
from urllib.parse import urlencode

import qiniu
from aiohttp.client import ClientSession

from aioqiniu.services import StorageServiceMixin

__version__ = "1.3.1"

class QiniuClient(StorageServiceMixin):
    """七牛云存储异步客户端"""

    def __init__(self, access_key: str, secret_key: str, httpclient: ClientSession = None):
        """初始化七牛云异步客户端

        :param access_key: 七牛云 AccessKey
        :param secret_key: 七牛云 SecretKey
        :param httpclient: 自定义 `aiohttp.client.ClientSession` 对象,默认为空,自动创建
        """
        self.__access_key = access_key
        self.__secret_key = secret_key
        self._auth = qiniu.Auth(access_key, secret_key)
        if httpclient is None:
            httpclient = ClientSession()
        self.httpclient = httpclient

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()

    async def close(self) -> None:
        await self.httpclient.close()

    @property
    def closed(self) -> bool:
        return self.httpclient.closed

    def get_token(self, data: str) -> str:
        """从原始数据中生成的token

        该方法等同于`qiniu.Auth.token`

        :param data: 待签名数据

        :return: 数据签名
        """
        return self._auth.token(data)

    def get_token_with_data(self, data: str) -> str:
        """生成带原始数据的token

        该方法等同于`qiniu.Auth.token_with_data`

        :param data: 待签名数据

        :return: 数据签名,含已编码的原数据
        """
        return self._auth.token_with_data(data)

    def get_access_token(self, path: str, query: Union[str, dict] = "", body: str = "") -> str:
        """生成七牛云的管理凭证(access token)

        :param path: URL 路径
        :param query: URL 查询字符串,可以是 str 或 dict 类型
        :param body: 请求 body

        :return: 七牛云的管理凭证(access token)

        详见:https://developer.qiniu.com/kodo/manual/1201/access-token
        """
        if not query:
            return self._auth.token("{}\n{}".format(path, body))
        if isinstance(query, dict):
            query = urlencode(query)
        return self._auth.token("{}?{}\n{}".format(path, query, body))

    def get_upload_token(self, bucket: str, key: str = None, expires: int = 3600,
                         policy=None, strict_policy: bool = True) -> str:
        """生成七牛云的上传凭证(upload token)

        :param bucket: 空间名
        :param key: 上传的文件命名,默认为空
        :param expires: 上传凭证过期时间,单位为秒,默认为3600
        :param policy: 上传策略,默认为空

        :return: 七牛云的上传凭证(upload token)

        详见:https://developer.qiniu.com/kodo/manual/1208/upload-token
        """
        return self._auth.upload_token(
            bucket, key, expires, policy, strict_policy
        )

    def get_private_download_url(self, url: str, expires: int = 3600) -> str:
        """生成私有资源的下载 URL

        :param url: 私有资源的 URL
        :param expires: 下载 URL 的过期时间,单位为秒,默认为 3600

        :return: 私有资源的下载 URL

        详见:https://developer.qiniu.com/kodo/manual/1202/download-token
        """
        return self._auth.private_download_url(url, expires)


text:
package com.dood.java.dates.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

//@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        boolean enableFeature = true; //set a breakpoint and change the value if you want
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, enableFeature);
//        objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, enableFeature);
        return objectMapper;
    }

}


text:
var CindyJS = (function() {
            "use strict";

            var debugStartup = false;

            var waitCount = -1;

            var toStart = [];

            // waitFor returns a callback which will decrement the waitCount
            function waitFor(name) {
                if (waitCount === 0) {
                    console.error("Waiting for " + name + " after we finished waiting.");
                    return function() {};
                }
                if (waitCount < 0)
                    waitCount = 0;
                if (debugStartup)
                    console.log("Start waiting for " + name);
                ++waitCount;
                return function() {
                    if (debugStartup)
                        console.log("Done waiting for " + name);
                    --waitCount;
                    if (waitCount < 0) {
                        console.error("Wait count mismatch: " + name);
                    }
                    if (waitCount === 0) {
                        var i = 0,
                            n = toStart.length;
                        if (debugStartup)
                            console.log("Done waiting, starting " + n + " instances:");
                        while (i < n)
                            toStart[i++].startup();
                    }
                };
            }

            if (!Math.sign) {
                //polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign#Polyfill
                //needed for IE
                Math.sign = function(x) {
                    // If x is NaN, the result is NaN.
                    // If x is -0, the result is -0.
                    // If x is +0, the result is +0.
                    // If x is negative and not -0, the result is -1.
                    // If x is positive and not +0, the result is +1.
                    return ((x > 0) - (x < 0)) || +x;
                    // A more aesthetical persuado-representation is shown below
                    //
                    // ( (x > 0) ? 0 : 1 )  // if x is negative then negative one
                    //          +           // else (because you cant be both - and +)
                    // ( (x < 0) ? 0 : -1 ) // if x is positive then positive one
                    //         ||           // if x is 0, -0, or NaN, or not a number,
                    //         +x           // Then the result will be x, (or) if x is
                    //                      // not a number, then x converts to number
                };
            }

            if (typeof document !== "undefined" && typeof window !== "undefined" &&
                typeof document.addEventListener !== "undefined" &&
                (typeof window.cindyDontWait === "undefined" ||
                    window.cindyDontWait !== true)) {
                document.addEventListener("DOMContentLoaded", waitFor("DOMContentLoaded"));
            }

            function CindyJS(data) {
                var instance = CindyJS.newInstance(data);
                if (waitCount <= 0) instance.startup();
                else if (data.autostart !== false) toStart.push(instance);
                return instance;
            }

            var baseDir = null;
            var cindyJsScriptElement = null;
            var waitingForLoad = {};

            CindyJS.getBaseDir = function() {
                if (baseDir !== null)
                    return baseDir;
                var scripts = document.getElementsByTagName("script");
                for (var i = 0; i < scripts.length; ++i) {
                    var script = scripts[i];
                    var src = script.src;
                    if (!src) continue;
                    var match = /Cindy\.js$/.exec(src);
                    if (match) {
                        baseDir = src.substr(0, match.index);
                        console.log("Will load extensions from " + baseDir);
                        cindyJsScriptElement = script;
                        return baseDir;
                    }
                }
                console.error("Could not find <script> tag for Cindy.js");
                baseDir = cindyJsScriptElement = false;
                return baseDir;
            };

            CindyJS.addNewScript = function(path, onerror) {
                if (!onerror) onerror = console.error.bind(console);
                var baseDir = CindyJS.getBaseDir();
                if (baseDir === false) {
                    return false;
                }
                var elt = document.createElement("script");
                elt.src = baseDir + path;
                var next = cindyJsScriptElement.nextSibling;
                var parent = cindyJsScriptElement.parentElement;
                if (next)
                    parent.insertBefore(elt, next);
                else
                    parent.appendChild(elt);
                return elt;
            };

            CindyJS.loadScript = function(name, path, onload, onerror) {
                var names = String(name).split(".");
                var obj = window;
                while (names.length && typeof obj === "object" && obj !== null)
                    obj = obj[names.shift()];
                if (obj && !names.length) {
                    onload();
                    return true;
                }
                if (!onerror) onerror = console.error.bind(console);
                var elt = waitingForLoad[name];
                if (!elt) {
                    elt = CindyJS.addNewScript(path, onerror);
                    if (elt === false) {
                        onerror("Can't load additional components.");
                        return false;
                    }
                    waitingForLoad[name] = elt;
                }
                elt.addEventListener("load", onload);
                elt.addEventListener("error", onerror);
                return null;
            };

            CindyJS._autoLoadingPlugin = {};

            CindyJS.autoLoadPlugin = function(name, path, onload) {
                if (CindyJS._pluginRegistry[name]) {
                    onload();
                    return true;
                }
                var listeners = CindyJS._autoLoadingPlugin[name];
                if (!listeners) {
                    if (!path) path = name + "-plugin.js";
                    listeners = CindyJS._autoLoadingPlugin[name] = [];
                    var elt = CindyJS.addNewScript(path);
                    if (elt === false) {
                        return false;
                    }
                    elt.addEventListener("error", console.error.bind(console));
                }
                listeners.push(onload);
                return null;
            };

            var nada = {
                ctype: 'undefined'
            };

            CindyJS.waitFor = waitFor;
            CindyJS._pluginRegistry = {};
            CindyJS.instances = [];
            CindyJS.registerPlugin = function(apiVersion, pluginName, initCallback) {
                if (apiVersion !== 1) {
                    console.error("Plugin API version " + apiVersion + " not supported");
                    return false;
                }
                CindyJS._pluginRegistry[pluginName] = initCallback;
                var listeners = CindyJS._autoLoadingPlugin[pluginName] || [];
                listeners.forEach(function(callback) {
                    callback();
                });
            };

            var idCounter = 0;

            function generateId(prefix) {
                if (prefix === undefined)
                    prefix = "CindyJSid";
                return prefix + (++idCounter);
            }

            CindyJS.dumpState = function(index) {
                // Call this if you find a rendering bug you'd like to reproduce.
                // Then save the printed JSON to a file and include it in your report.
                var state = CindyJS.instances[index || 0].saveState();
                console.log(JSON.stringify(state));
            };

            CindyJS.debugState = function(index) {
                // Call this to test how a widget handles a save & reload.
                // You can paste javascript:CindyJS.debugState() into the
                // address bar of your browser to achieve this.
                CindyJS.instances.map(function(instance) {
                    var cfg = instance.config;
                    cfg = JSON.parse(JSON.stringify(cfg));
                    var state = instance.saveState();
                    console.log(JSON.stringify(state));
                    for (var key in state)
                        cfg[key] = state[key];
                    instance.shutdown();
                    return cfg;
                }).forEach(function(cfg) {
                    CindyJS(cfg);
                });
            };

            CindyJS.newInstance = function(instanceInvocationArguments) {


text:
<?php

abstract class CM_Provision_Script_OptionBased extends CM_Provision_Script_Abstract implements CM_Typed {

    use CM_Provision_Script_IsLoadedTrait;

    /**
     * @param bool $loaded
     */
    protected function _setLoaded($loaded) {
        $this->getServiceManager()->getOptions()->set($this->_getOptionName(), (bool) $loaded);
    }

    /**
     * @return bool
     */
    protected function _isLoaded() {
        try {
            return $this->getServiceManager()->getOptions()->get($this->_getOptionName());
        } catch (CM_Db_Exception $e) {
            return false;
        }
    }

    /**
     * @return string
     */
    private function _getOptionName() {
        return 'SetupScript.' . $this->getType();
    }
}


text:
package org.artifactory.storage.fs.lock.map;

import java.util.concurrent.TimeUnit;

/**
 * A data structure which allows only one concurrent writer and many readers.
 *
 * @author Shay Yaakov
 */
public interface LockingMap {

    /**
     * Adds a path to the map while locking other threads from writing the same path concurrently.
     *
     * @param path     The path to add
     * @param timeout  the maximum time to wait for the lock
     * @param timeUnit the time unit of the {@code time} argument
     * @return {@code true} if the lock was acquired and {@code false}
     * if the waiting time elapsed before the lock was acquired
     * @throws InterruptedException if the current thread is interrupted
     *                              while acquiring the lock (and interruption of lock
     *                              acquisition is supported)
     */
    boolean tryAddAndLock(String path, long timeout, TimeUnit timeUnit) throws InterruptedException;

    /**
     * Removes the path from the map and releases it's lock.
     *
     * @param path The path to remove
     */
    void removeAndUnlock(String path);

    /**
     * Removes the path from the map and releases it's lock regardless the thread owner.
     *
     * @param path The path to remove
     */
    void removeAndForceUnlock(String path);

    /**
     * checks if the path is locked.
     *
     * @param path The path to remove
     */
    boolean isLocked(String path);
}


text:
<?php namespace Modules\Logistic\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class LogisticTableSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
            Model::unguard();

            // $this->call("OthersTableSeeder");
    }

}


text:
import jwtDecode = require('jwt-decode');

const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJleHAiOjEzOTMyODY4OTMsImlhdCI6MTM5MzI2ODg5M30.4-iaDojEVl0pJQMjrbM1EzUIfAZgsbK_kgnVyVxFSVo";

interface TokenDto {
  foo: string;
  exp: number;
  iat: number;
}

const decodedTokenOld = jwtDecode(token);
const decodedToken = jwtDecode<TokenDto>(token);


text:
const initialState = {};

export default function(state = initialState, action){
    console.log(action)
    switch(action.type){
        case 'RECEVIE_ARTICLE':
            return {
                ...state,
                ...action.data
            }
            break;
        default:
            return state;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeepdreamGui.Model;

namespace DeepdreamGui.ViewModel
{
    /// <summary>
    /// Base class for the view models
    /// Load Parameters for the view models
    /// Derivative by ViewModelBase
    /// </summary>
    public class ParameterViewModel  : ViewModelBase
    {
        private ParameterCollection modelParameter;
        private ParameterCollection inputParameter;
        private DeepDreamParameter selectedModelParameter;
        /// <summary>
        /// Constructor for the parameter view model. Load the parameter
        /// </summary>
        public ParameterViewModel()
        {
            LoadParameter();
        }
        /// <summary>
        /// Async function to load the parameter model
        /// </summary>
        private async void LoadParameter()
        {
            var param = await ParameterModel.LoadParameter();
            InputParameter = param.InputParameter;
            ModelParameter = param.ModelParameter;
        }
        /// <summary>
        /// Property displaying a collection of input parameters
        /// </summary>
        public ParameterCollection InputParameter
        {
            get { return inputParameter; }
            set { inputParameter = value; OnPropertyChanged(); }
        }
        /// <summary>
        /// Property displaying a collection of model propertys
        /// </summary>
        public ParameterCollection ModelParameter
        {
            get { return modelParameter; }
            set
            {
                modelParameter = value; OnPropertyChanged();
                if (modelParameter.Collection.Count > 0 && SelectedModelParameter == null) SelectedModelParameter = modelParameter.Collection[0];
            }
        }
        /// <summary>
        /// Property displaying the selected model parameter
        /// </summary>
        public DeepDreamParameter SelectedModelParameter
        {
            get { return selectedModelParameter; }
            set { selectedModelParameter = value; OnPropertyChanged(); }
        }
    }
}


text:
/**
 * @file   type_traits.h
 * @author Sebastian Maisch <sebastian.maisch@uni-ulm.de>
 * @date   2016.05.08
 *
 * @brief  Definition of some type traits used.
 */

#ifndef CGU_TYPE_TRAITS_H
#define CGU_TYPE_TRAITS_H

#include <type_traits>
#include <vector>
#include <array>

namespace cgu {

    template<typename T>
    struct has_contiguous_memory : std::false_type {};

    template<typename T, typename U>
    struct has_contiguous_memory<std::vector<T, U>> : std::true_type{};

    template<typename T>
    struct has_contiguous_memory<std::vector<bool, T>> : std::false_type{};

    template<typename T, typename U, typename V>
    struct has_contiguous_memory<std::basic_string<T, U, V>> : std::true_type{};

    template<typename T, std::size_t N>
    struct has_contiguous_memory<std::array<T, N>> : std::true_type{};

    template<typename T>
    struct has_contiguous_memory<T[]> : std::true_type{};

    template<typename T, std::size_t N>
    struct has_contiguous_memory<T[N]> : std::true_type{};
}

#endif // CGU_TYPE_TRAITS_H


text:
public class Web {

}


text:
using BringMeSoup.Models;
using Microsoft.AspNet.Identity;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace BringMeSoup.Controllers.api
{

    public class RequestsController : ApiController
    {

        public IHttpActionResult Get()
        {

            using (var db = new ApplicationDbContext())
            {

                var userId = User.Identity.GetUserId();
                if (userId == null) return Unauthorized();
                var user = db.Users.FirstOrDefault(x => x.Id == userId);

                var userIdToSearchFor = userId;
                if (user.UserType == UserType.Caretaker) userIdToSearchFor = user.AssociatedSickUserId;

                var requests = db.Requests.Where(x => x.RequestedByUserId == userIdToSearchFor && x.FullfilledByUserId == null).ToList();

                return Ok(requests);

            }

        }

        public async Task<IHttpActionResult> Post()
        {

            using (var db = new ApplicationDbContext())
            {

                var userId = User.Identity.GetUserId();
                if (userId == null) return Unauthorized();

                var request = new Request()
                {
                    Id = Guid.NewGuid(),
                    RequestedByUserId = userId,
                    RequestedOn = DateTime.UtcNow
                };
                db.Requests.Add(request);

                await db.SaveChangesAsync();

                return Ok(request);

            }

        }

    }

}


text:
package com.produce.ciro.bchart4;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

/*
 * Transaction class used to bind JSON data from Transaction API https://www.bitstamp.net/api/transactions/ example JSON data: {"date":
 * "1395551812", "tid": 4151239, "price": "564.23", "amount": "0.05000000"}
 */
public class Transaction implements Parcelable {
	private static final String TAG = "transaction implements parcelable";

	private String date;
	private long tid;
	private String price;
	private String amount;

	public Transaction() {}

	public Transaction(String date, long tid, String price, String amount) {
		this.date = date;
		this.tid = tid;
		this.price = price;
		this.amount = amount;
	}

	public String getDate() {
		return date;
	}

	public long getTid() {
		return tid;
	}

	public String getPrice() {
		return price;
	}

	public String getAmount() {
		return amount;
	}

	@Override
	public String toString() {
		return String.format("(date=%s, tid=%d, price=%s, amount=%s)", date, tid, price, amount);
	}

	// implementing parcelable
	public Transaction(Parcel in) {
		// super();
		// readFromParcel(in);
		date = in.readString();
		tid = in.readLong();
		price = in.readString();
		amount = in.readString();
		Log.i(TAG, "1");
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		Log.i(TAG, "2");
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flag) {
		// TODO Auto-generated method stub
		dest.writeString(date);
		dest.writeLong(tid);
		dest.writeString(price);
		dest.writeString(amount);
		Log.i(TAG, "3");
	}

	public static final Parcelable.Creator<Transaction> CREATOR = new Parcelable.Creator<Transaction>() {
		public Transaction createFromParcel(Parcel in) {
			Log.i(TAG, "4");
			return new Transaction(in);
		}

		public Transaction[] newArray(int size) {
			Log.i(TAG, "5");
			return new Transaction[size];
		}
	};

}


text:
**Note:** To port mbed Client, you need to [install yotta and its dependencies](https://github.com/ARMmbed/yotta/blob/master/docs/index.md).

# mbed Client structure and build process

**Tip:** Before embarking on your own port, you should build the core mbed Client for an existing compilation target to get an understanding of how the mbed Client builds.

mbed Client is structured as a set of modules. Each module declares which other modules it depends on. When you build a module, our build system `yotta` looks at these dependencies and installs the necessary modules before completing the build.

This is also the process to build applications for the mbed Client (including the example application in the release). The application declares dependencies on the mbed Client and when it is built, `yotta` ensures that the modules (and anything that they depend on, recursively) are present before building.

In general, `yotta` downloads and installs the necessary modules over the internet from the public yotta Registry (which saves published versions of modules) or from a specified source control URL.

# Components of mbed Client

## Component software modules

mbed Client consists of one main component. More major components will be added in future development phases:

 * `mbed-client` is the core mbed Client, providing C++ APIs for the mbed Client.

This module depends on further internal modules:

```
mbed-client x.x.x
|
|_mbed-client-c x.x.x
|   |_mbed-client-libservice x.x.x
|
|_mbed-client-linux x.x.x
```

To list the dependency trees, use the [`yotta list --all` command](http://docs.yottabuild.org/reference/commands.html).

**Note**: In this case, we have listed the dependencies for the `x86-linux-native` compilation target. Different modules are needed for different compilation targets.

We are using the [mbed Client Linux example](https://github.com/ARMmbed/mbed-client-linux-example) in this document. You can see that it depends directly only on the `mbed-client` and `mbed-client-linux` modules. These modules depend internally on various other modules.

```
mbed-client-linux-example x.x.x
|
|_mbed-client x.x.x
   |
   |_mbed-client-c x.x.x
   |   |_mbed-client-libservice x.x.x
   |
   |_mbed-client-linux x.x.x
```

## Compilation targets

To compile for a target board, you need a [target description](http://docs.yottabuild.org/tutorial/targets.html) that describes how to compile for the target.

The `mbed-client` module uses the platform name that each target defines to choose which `mbed-client-<platform-name>` module to depend on to provide the platform-specific implementation.

# Porting mbed Client to a different platform

To port mbed Client to a new platform:

 1. [Request for a development repository](#requesting-for-a-development-repository).
 2. [Create a yotta compilation target for your board](#creating-a-yotta-compilation-target).
 3. [Implement the `mbed-client-xxx` module for your target platform](#implementing-mbed-client-xxx).
 4. [Modify the `module.json` of the `mbed-client` module](#modifying-the-json-file-in-the-mbed-client-module).
 5. [Verify that your implementation is correct](#testing-and-verification).

The `yotta` build system is designed for easy reuse of generic modules. If you intend to support multiple platforms that share common features, we recommend moving the common functionality into a separate module and use it for each platform.

## Requesting for a development repository

We provide private git repositories to our partners porting mbed Client. Only the members of the mbed Client team and relevant partner contacts and engineers have access to these repositories.

When you contact `support@mbed.org`, a repository will be created for your module. You also need to provide the target description of your board as follows:

- **`mbed-client-<platform-name>`** is the module that provides the `mbed-client-xxx` implementation for your platform. You may choose to split it into further modules in the future, to enable sharing of code, but we recommend that you implement the port for your first board in this module itself.

- **`target-<targetname>`** contains the yotta target description of the target you are porting to. This is usually your platform name.

## Creating a yotta compilation target

An example on compiling for linux target can be found in the `yotta_targets` directory of [the example application] (https://github.com/ARMmbed/mbed-client-linux-example).

Please, refer to the [yotta documentation](http://yottadocs.mbed.com/tutorial/targets.html) for setting up your compilation target.

1.To make your target available locally (without publishing it), you use the `yotta link-target` command to link it into the global install targets directory:

```
# in the directory of your target:
yotta link-target
```

2.Use `yotta link-target <targetname>` command to make the globally linked target available when compiling another module.

3.Use the `yotta target <targetname>` command to select your target for the compilation.

## Implementing mbed-client-xxx

Clone your `mbed-client-<your-platform-name>` module and `mbed-client` modules from GitHub.

The `mbed-client-<your-platform-name>` module needs to provide a socket and timer implementation for your target platform. The `mbed-client-xxx` module should include files `m2mconnectionhandler.h`and `m2mtimer.h` from `mbed-client` and implement a corresponding `.cpp` file that points to the platform-specific private implementations of the timer and the socket.

**Note**: Private implementation classes **must** be named as `M2MConnectionHandlerPimpl` and `M2MTimerPimpl`, because of forward declarations.

An example of mbed-client-platform:

```
|_module.json
|
|_mbed-client-platform
|    |_m2mconnectionhandlerpimpl.h
|    |_m2mtimerpimpl.h
|
|_source
    |_m2mconnectionhandler.cpp
    |_m2mconnectionhandlerpimpl.cpp
    |_m2mtimer.cpp
    |_m2mtimerpimpl.cpp
```

To make your module available to other modules that you want to build, you need to use the [`yotta link`](http://docs.yottabuild.org/reference/commands.html#yotta-link) command to link it to the module where you want to test it out.

For example, to use your local your in-development mbed-client implementation, use the command `yotta link mbed-client-xxx` in the main `mbed-client` module.

```
# in mbed-client, link your module:
yotta link mbed-client-xxx
```

You can also just commit and push your untested code to GitHub, but it is always a good idea to test before committing.

Your `mbed-client-xxx` module must provide a platform-specific implementation for the mbed-client. The APIs that need porting are defined in the `mbed-client-linux` module. The header files contain documentation alongside the declaration of each function, where the function is described along with its parameters and return value.

There are two header files that require porting for your platform:

- `m2mconnectionhandler.h`
- `m2mtimer.h`

To see how this is done in Linux, check the `mbed-client-linux` module from the mbed [Client Linux Example](https://github.com/ARMmbed/mbed-client-linux-example).

### Implementing the M2MConnectionHandler class for your platform

```

#ifndef M2M_CONNECTION_HANDLER_H__
#define M2M_CONNECTION_HANDLER_H__

#include "mbed-client/m2mconfig.h"
#include "mbed-client/m2minterface.h"
#include "mbed-client/m2mconnectionobserver.h"
#include "nsdl-c/sn_nsdl.h"

/**
 * \brief M2MConnectionHandler.
 * This class handles the socket connection for the LWM2M Client.
 */

class M2MConnectionHandler {
public:

    /**
     * @enum ConnectionError
     * This enum defines an error that can come from
     * socket read and write operation.
     */
    typedef enum {
        CONNECTION_ERROR_WANTS_READ = -1000,
        CONNECTION_ERROR_WANTS_WRITE = -1001,
        ERROR_NONE = 0,
        SSL_CONNECTION_ERROR,
        SOCKET_READ_ERROR,
        SOCKET_SEND_ERROR,
        SOCKET_ABORT,
        DNS_RESOLVING_ERROR,
        SSL_HANDSHAKE_ERROR
    }ConnectionError;

public:

    /**
    * \brief Constructor
    */
    M2MConnectionHandler(M2MConnectionObserver &observer,
                         M2MConnectionSecurity* sec,
                         M2MInterface::BindingMode mode,
                         M2MInterface::NetworkStack stack);

    /**
    * \brief Destructor
    */
    ~M2MConnectionHandler();

    /**
    * \brief This binds the socket connection.
    * \param listen_port Port to be listened to for an incoming connection.
    * \return True if successful, else false.
    */
    bool bind_connection(const uint16_t listen_port);

    /**
    * \brief This resolves the server address. Output is
    * returned through a callback.
    * \param String The server address.
    * \param uint16_t The server port.
    * \param ServerType The server type to be resolved.
    * \param security The M2MSecurity object that determines which
    * type of secure connection will be used by the socket.
    * \return True if address is valid, else false.
    */
    bool resolve_server_address(const String& server_address,
                                const uint16_t server_port,
                                M2MConnectionObserver::ServerType server_type,
                                const M2MSecurity* security);

    /**
    * \brief Sends data to the connected server.
    * \param data_ptr The data to be sent.
    * \param data_len The length of data to be sent.
    * \param address_ptr The address structure to which the data needs to be sent.
    * \return True if data is sent successfully, else false.
    */
    bool send_data(uint8_t *data_ptr,
                           uint16_t data_len,
                           sn_nsdl_addr_s *address_ptr);

    /**
    * \brief Listens to the incoming data from a remote server.
    * \return True if successful, else false.
    */
    bool start_listening_for_data();

    /**
    * \brief Stops listening to the incoming data.
    */
    void stop_listening();

    /**
     * \brief Sends directly to the socket. This is used by
     * security classes to send the data after it has been encrypted.
     * \param buf Buffer to send.
     * \param len The length of the buffer.
     * \return Number of bytes sent or -1 if failed.
     */
    int send_to_socket(const unsigned char *buf, size_t len);

    /**
     * \brief Receives directly from the socket. This
     * is used by the security classes to receive raw data to be decrypted.
     * \param buf Buffer to send.
     * \param len The length of the buffer.
     * \return Number of bytes read or -1 if failed.
     */
    int receive_from_socket(unsigned char *buf, size_t len);

    /**
    * \brief Closes the open connection.
    */
    void close_connection();

    /**
    * \brief Error handling for DTLS connectivity.
    * \param error Error code from the TLS library.
    */
    void handle_connection_error(int error);

    /**
     * \brief Sets the network interface handler that is used by client to connect
     * to a network over IP..
     * \param handler A network interface handler that is used by client to connect.
     *  This API is optional but provides a mechanism for different platforms to
     * manage usage of underlying network interface by client.
     */
    void set_platform_network_handler(void *handler = NULL);

    /**
    * \brief Claims mutex to prevent thread clashes
    * in multithreaded environment.
    */
    void claim_mutex();

    /**
    * \brief Releases mutex to prevent thread clashes
    * in multithreaded environment.
    */
    void release_mutex();

private:

    M2MConnectionObserver                       &_observer;
    M2MConnectionHandlerPimpl                   *_private_impl;

friend class Test_M2MConnectionHandler;
friend class Test_M2MConnectionHandler_mbed;
friend class Test_M2MConnectionHandler_linux;
friend class M2MConnection_TestObserver;
};

#endif //M2M_CONNECTION_HANDLER_H__

```

Please note that some of these functions are asynchronous in nature and some are expecting a callback from the network. For example, receiving data from a socket needs to be communicated back to `mbed-client` so that the library can act on the data received. The callback comes through the Observer class defined in `M2MConnectionObserver`.

The file `m2mconnectionobserver.h` is present in `mbed-client`. To see how the callback needs to be called, check the implementation in `m2mconnectionhandlerpimpl.cpp` in  `mbed-client-linux`.

```
/*
 * Copyright (c) 2015 ARM. All rights reserved.
 */
#ifndef M2M_CONNECTION_OBSERVER_H__
#define M2M_CONNECTION_OBSERVER_H__

#include "mbed-client/m2minterface.h"

/**
 * @brief Observer class for informing socket activity to the state machine
 */

class M2MConnectionObserver
{

public :

    /**
      * \enum ServerType, Defines the type of the
      * server that the client wants to use.
      */
    typedef enum {
        Bootstrap,
        LWM2MServer
    }ServerType;

    /**
     * \brief The M2MSocketAddress struct.
     * Unified container for holding socket address data
     * across different platforms.
     */
    struct SocketAddress{
        M2MInterface::NetworkStack  _stack;
        void                        *_address;
        uint8_t                     _length;
        uint16_t                    _port;
    };

    /**
    * \brief Indicates that data is available from socket.
    * \param data The data read from the socket.
    * \param data_size The length of the data read from the socket.
    * \param address The address of the server where the data is coming from.
    */
    virtual void data_available(uint8_t* data,
                                uint16_t data_size,
                                const M2MConnectionObserver::SocketAddress &address) = 0;

    /**
    * \brief Indicates an error occured in socket.
    * \param error_code The error code from socket, it cannot be used any further.
    * \param retry Indicates whether to re-establish connection.
    */
    virtual void socket_error(uint8_t error_code, bool retry = true) = 0;

    /**
    * \brief Indicates that the server address resolving is ready.
    * \param address The resolved socket address.
    * \param server_type The type of the server.
    * \param server_port The port of the resolved server address.
    */
    virtual void address_ready(const M2MConnectionObserver::SocketAddress &address,
                               M2MConnectionObserver::ServerType server_type,
                               const uint16_t server_port) = 0;

    /**
    * \brief Indicates that data has been sent successfully.
    */
    virtual void data_sent() = 0;
};

#endif // M2M_CONNECTION_OBSERVER_H__

```

### Implementing M2MTimer class for your platform

This class provides the periodic timer functionality for your platform.

```
/*
 * Copyright (c) 2015 ARM. All rights reserved.
 */
#ifndef M2M_TIMER_H
#define M2M_TIMER_H

#include <stdint.h>

class M2MTimerObserver;
/**
 * @brief M2MTimerImpl
 * Private implementation class for timer, this can be
 * modified based on the board on which mbed Client needs
 * to be used.
 */
class M2MTimerImpl
{
private:

    // Prevents the use of assignment operator
    M2MTimer& operator=(const M2MTimer& other);

    // Prevents the use of copy constructor
    M2MTimer(const M2MTimer& other);

public:

    /**
    * Constructor.
    */
    M2MTimer(M2MTimerObserver& _observer);

    /**
    * Destructor.
    */
    virtual ~M2MTimer();

    /**
     * Starts timer
     * @param interval Timer's interval in milliseconds
    * @param single_shot defines if timer is ticked
    * once or is it restarted everytime timer expires.
    */
    void start_timer(uint64_t interval, bool single_shot = true);

    /**
     * @brief Starts timer in DTLS manner.
     * @param intermediate_interval Intermediate interval to use, must be smaller than tiotal (usually 1/4 of total).
     * @param total_interval Total interval to use, this is the timeout value of a DTLS packet.
     * @param type Type of the timer
     */
    void start_dtls_timer(uint64_t intermediate_interval, uint64_t total_interval,
                          M2MTimerObserver::Type type = M2MTimerObserver::Dtls);

    /**
    * Stops timer.
    * This cancels the ongoing timer.
    */
    void stop_timer();

    /**
     * @brief Checks if the intermediate interval has passed.
     * @return true if interval has passed, false otherwise.
     */
    bool is_intermediate_interval_passed();

    /**
     * @brief Checks if the total interval has passed.
     * @return true if interval has passed, false otherwise.
     */
    bool is_total_interval_passed();

};

#endif // M2M_TIMER_H
```

The timer API functions are asynchronous in nature and whenever a timer event is available, `mbed-client` is notified, so that the library can act on the _timer expired_ signal. The callback is received through an Observer class defined in `M2MTimerObserver` .

The file `m2mtimerobserver.h` is present in `mbed-client`. To see how the callback needs to be called, check the implementation in `m2mtimerimpl.cpp` in `mbed-client-linux`.

```
/*
 * Copyright (c) 2015 ARM. All rights reserved.
 */
#ifndef M2M_TIMER_OBSERVER_H
#define M2M_TIMER_OBSERVER_H

/**
 *  Observer class for informing the parent class of the timer expiry.
 */
class M2MTimerObserver
{
public:
    /**
      * \enum Defines the types of timer
      * that can be created for mbed Client.
      */
    typedef enum {
        Notdefined,
        Registration,
        NsdlExecution,
        PMinTimer,
        PMaxTimer,
        Dtls,
        QueueSleep,
        RetryTimer
    }Type;

    /**
    * \brief Indicates that the timer has expired.
    * \param type The type of the timer that has expired.
    */
    virtual void timer_expired(M2MTimerObserver::Type type =
                               M2MTimerObserver::Notdefined) = 0;
};

#endif // M2M_TIMER_OBSERVER_H
```

## Modifying the `json` file in the `mbed-client` module

You need to add your target name to `module.json` so that when you set `yt target <platform>`, yotta can resolve the dependency correctly and link the main library with your module.

Two platforms, mbed OS and Linux, are already supported. You just need to add your module support after that.

```
{
  "name": "mbed-client",
  "version": "1.12.0",
  "description": "Mbed Client API",
  "private": true,
  "keywords": [],
  "author": "XXX XXX <xxx.xxx@xxx.com>",
  "homepage": "https://github.com/ARMmbed/mbed-client",
  "licenses": [
    {
      "url": "https://spdx.org/licenses/Apache-2.0",
      "type": "Apache-2.0"
    }
  ],
  "dependencies": {
    "mbed-client-c": "^2.0.0"
  },
  "targetDependencies": {
    "arm": {
      "mbed-client-mbed": "^3.0.0"
    },
    "linux": {
      "mbed-client-linux": "^3.0.0"
    },
    "<your platform as defined in target.json>" : {
      "mbed-client-platform": "<published version , can be done later, first link locally as explained in the steps above>"
    },
  }
}
```

## Testing and verification

You can build your mbed-client port immediately:

```
# use the target we previously made locally available (not necessary if your target has been published):
yotta link-target <yourtargetname>
# build!
yotta build
```

A `helloworld-mbedclient` program will be produced inside the `build/<yourtargetname>/test/` directory. This test application may require some changes to compile and run for your platform. Check for compilation errors. If you find any, fix the test application for your testing.

Follow the `readme` [instructions](https://github.com/ARMmbed/mbed-client-linux-example) of the `mbed-client-linux` example to see what the test application can do.


text:
import reduxFactory from 'redux-factory'
import fetch from 'isomorphic-fetch'

const defaultState = {
  results: [],
  loading: false
}

const actions = {
  loading : (state)          => ({...state, loading: true }),
  set     : (state, results) => ({...state, results, loading: false })
}

const factory = reduxFactory(defaultState, actions, 'standings')

function load() {
  return (dispatch) => {
    dispatch(factory.loading())
    return fetch('/standings').then((response) => {
      return response.json()
    }).then((response) => {
      setTimeout(() => {
        dispatch(factory.set(response.standing))
      }, 2000)

    })
  }
}

export default { ...factory, defaultState, load }


text:
<?php

namespace Thruway\Transport;

use React\EventLoop\LoopInterface;
use React\Socket\Connection;
use React\Socket\Server;
use Thruway\Logging\Logger;
use Thruway\Manager\ManagerDummy;
use Thruway\Peer\AbstractPeer;
use Thruway\Serializer\JsonSerializer;

/**
 * Class RawSocketTransportProvider
 *
 * Implements a transport provider on raw socket (for router)
 *
 * @package Thruway\Transport
 */
class RawSocketTransportProvider extends AbstractTransportProvider
{

    /**
     * @var string
     */
    private $address;

    /**
     * @var int
     */
    private $port;

    /**
     * @var \SplObjectStorage
     */
    private $transports;

    /**
     * Constructor
     *
     * @param string $address
     * @param int $port
     */
    function __construct($address = "127.0.0.1", $port = 8181)
    {
        $this->address = $address;
        $this->port    = $port;

        $this->setManager(new ManagerDummy());

        $this->transports = new \SplObjectStorage();
    }

    /**
     * Start transport provider
     *
     * @param \Thruway\Peer\AbstractPeer $peer
     * @param \React\EventLoop\LoopInterface $loop
     */
    public function startTransportProvider(AbstractPeer $peer, LoopInterface $loop)
    {
        $this->peer = $peer;
        $this->loop = $loop;

        $socket = new Server($loop);
        $socket->on('connection', [$this, "handleConnection"]);
        $socket->listen($this->port, $this->address);
    }

    /**
     * Handle process on open new connection
     *
     * @param \React\Socket\Connection $conn
     */
    public function handleConnection(Connection $conn)
    {
        Logger::debug($this, "Raw socket opened " . $conn->getRemoteAddress());

        $transport = new RawSocketTransport($conn, $this->loop, $this->peer);

        $this->transports->attach($conn, $transport);

        $transport->setSerializer(new JsonSerializer());

        $transport->setTrusted($this->trusted);

        $this->peer->onOpen($transport);

        $conn->on('data', [$this, "handleData"]);
        $conn->on('close', [$this, "handleClose"]);
    }

    /**
     * Handle process reveiced data
     *
     * @param mixed $data
     * @param \React\Socket\Connection $conn
     */
    public function handleData($data, Connection $conn)
    {
        $transport = $this->transports[$conn];

        $transport->handleData($data);
    }

    /**
     * Handle process on close transport
     *
     * @param \React\Socket\Connection $conn
     */
    public function handleClose(Connection $conn)
    {
        Logger::debug($this, "Raw socket closed " . $conn->getRemoteAddress());
        $transport = $this->transports[$conn];
        $this->transports->detach($conn);

        $this->peer->onClose($transport);
    }

}


text:
#ifndef _VarargsI_h_
#define _VarargsI_h_

#include <stdarg.h>

/* private routines */

_XFUNCPROTOBEGIN

extern void _XtCountVaList(
    va_list /*var*/, int* /*total_count*/, int* /*typed_count*/
);

extern void _XtVaToArgList(
   Widget /*widget*/, va_list /*var*/, int /*max_count*/, ArgList* /*args_return*/, Cardinal* /*num_args_return*/
);

extern void _XtVaToTypedArgList(
    va_list /*var*/, int /*count*/, XtTypedArgList* /*args_return*/, Cardinal* /*num_args_return*/
);

extern XtTypedArgList _XtVaCreateTypedArgList(
    va_list /*var*/, int /*count*/
);

extern void _XtFreeArgList(
    ArgList /*args*/, int /*total_count*/, int /*typed_count*/
);

extern void _XtGetApplicationResources(
    Widget /*w*/, XtPointer /*base*/, XtResourceList /*resources*/, Cardinal /*num_resources*/, ArgList /*args*/, Cardinal /*num_args*/, XtTypedArgList /*typed_args*/, Cardinal /*num_typed_args*/
);

extern void _XtGetSubresources(
    Widget /*w*/, XtPointer /*base*/, const char* /*name*/, const char* /*class*/, XtResourceList /*resources*/, Cardinal /*num_resources*/, ArgList /*args*/, Cardinal /*num_args*/, XtTypedArgList /*typed_args*/, Cardinal /*num_typed_args*/
);

_XFUNCPROTOEND

#endif /* _VarargsI_h_ */


text:
	×

	{{ validation.generalErrors | joinBy }}


text:
using namespace cv;

void sharpen(Mat &input, Mat &output) {
  Mat mask = (Mat_<char>(3,3) <<
	      0, -1,  0,
	      -1,  5, -1,
	      0, -1,  0);
  filter2D(input, output, input.depth(), mask);
}

RoopList Sharpen::execute(RoopMachine &machine, RoopList arguments) {
  Mat output_image;
  Mat input_image = arguments[0].resultMat;
  sharpen(input_image, output_image);
  return fromMatrix(output_image);
}