text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="generator" content="AsciiDoc 8.6.9" />
<title>Webservices</title>

Webservices

Sebastien RAILLARD and Brice DUBOST

Table of Contents

JavaScript must be enabled in your browser to display the table of contents.

To activate the webservices, just enable the unicast mode with something like that:

unicast=1         : Activate the internal webserver
ip_http=127.0.0.1 : IP address for accepting the HTTP requests
port_http=8005    : Listening port

Note

When you use several card on one server you can use the template %card for the listening port. Ex: port_http=4000+%card. Ports higher than 1024 can be used by unprivileged users.

The webservices responses are not SOAP compliant, but formatted in simple XML documents (UTF-8) or in JSON.
The output can be easily parsed in PHP for example.

1. Status monitoring :

There is no input parameters.
URL : http://ip_http:port_http/monitor/state.xml

Example of response with comments:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mumudvb card="5" frontend="0">                                          => adapter and frontend devices
        <card_path>/dev/dvb/adapter5</card_path>                             => card device path
        <global_version><![CDATA[1.6.1b_20101101]]></global_version>         => MuMuDVB version
        <global_pid>19574</global_pid>                                       => process PID
        <global_uptime>45</global_uptime>                                    => process uptime in seconds
        <frontend_name><![CDATA[ST STV0299 DVB-S]]></frontend_name>          => frontend name
        <frontend_tuned>1</frontend_tuned>                                   => 0 if adapter not tuned, 1 if adapter is tuned
        <frontend_frequency>11856000</frontend_frequency>                    => tuning frequency (always in kHz)
        <frontend_polarization><![CDATA[V]]></frontend_polarization>         => "-" if polarization isn't applicable, or "V" (Vertical), "H" (Horizontal", "L" (Left), "R" (Right)
        <frontend_symbolrate>27500000</frontend_symbolrate>                  => Satellite symbole rate in symbols per second (or 0 if not applicable)
        <frontend_system><![CDATA[DVB-S]]></frontend_system>                 => System used : "DVB-C", "DVB-T", "DVB-S", "DVB-S2", "ATSC"
        <frontend_status><![CDATA[SCVYL]]></frontend_status>                 => Tuner lock status: "S"/"-" (Signal), "C"/"-" (Carrier), "V"/"-" (Viterbi), "Y"/"-" (Synchro), "L"/"-" (Locked)
        <frontend_ber>0</frontend_ber>                                       => RAW BER value from driver (unsigned 16-bits integer)
        <frontend_signal>56955</frontend_signal>                             => RAW Signal level value from driver (unsigned 16-bits integer)
        <frontend_snr>54759</frontend_snr>                                   => RAW Signal to noise ratio from driver (unsigned 16-bits integer)
        <autoconfiguration>2</autoconfiguration>                             => Autoconfiguration status 0: none, 2: full
        <autoconfiguration_detected_parameters>                              => Part displayed only when autoconfiguration is enabled
                <transport_stream_id>2</transport_stream_id>                     => Transport stream id
                <network_id>8442</network_id>                                    => network id (see ts_10261102v010201p.pdf p14 and ts_101162v010701p.pdf p18 p19)
                <original_network_id>8442</original_network_id>                  => original network id (see ts_10261102v010201p.pdf p14 and ts_101162v010701p.pdf p18 p19)
                <pat_version>19</pat_version>                                    => Version of the PAT PID
                <sdt_version>2</sdt_version>                                     => Version of the SDT PID
                <nit_version>28</nit_version>                                    => Version of the NIT PID
                <psip_version>0</psip_version>                                   => Version of the PSIP PID (ATSC only)
        </autoconfiguration_detected_parameters>                             =>
        <autoconfiguration_finished>1</autoconfiguration_finished>                       => 0 if not autoconfiguration or autoconfiguration in progress, 1 if autoconfiguration is finished
        <cam_support>1</cam_support>                                         => 0 if no CAM support asked, 1 if CAM support was asked
        <cam_number>0</cam_number>                                           => CAM slot number
        <cam_menustring><![CDATA[Not retrieved]]></cam_menustring>           => When CAM is initialized, CAM model
        <cam_initialized>0</cam_initialized>                                 => 0 if CAM isn't initialized, 1 if CAM is initialized

        <channel number="1">                                                 => Loop over channels, one node per channel, with MuMuDVB internal id (starting at 1)
                <lcn>0</lcn>                                                     => If present, Channel Logical Number (Channel number)
                <name><![CDATA[CANAL+]]></name>                                  => Channel name
                <service_type type="1"><![CDATA[Television]]></service_type>     => See function "service_type_to_str" in "log.c" file for complete description
                <ip_multicast><![CDATA[0.0.0.0]]></ip_multicast>                 => Multicast IP address (0.0.0.0 if multicast is disabled)
                <port_multicast>0</port_multicast>                               => Multicast UDP port (0 if multicast is disabled)
                <is_up>0</is_up>                                                 => 0 if channel is not streamed, 1 if channel is streamed
                <traffic>7</traffic>                                             => Channel streamed IP bandwidth in kB (kilo-Bytes) per second
                <ratio_scrambled>99</ratio_scrambled>                            => Percentage of scrambled packets received
                <service_id>8201</service_id>                                    => Service ID of channel
                <pmt_pid>1280</pmt_pid>                                          => PMT PID of channel
                <pmt_version>1</pmt_version>                                     => The version of the PMT PID in the TS stream
                <pcr_pid>160</pcr_pid>                                           => PCR PID of channel
                <unicast_port>0</unicast_port>                                   => Unicast port associated with the channle if unicast is setup by port
                <ca_sys>                                                         => Loop over all the CA systems listed in the PMT for the channel
                        <ca num="256"><![CDATA[Canal Plus]]></ca>                    => CA identifier and description if avaliable
                </ca_sys>                                                        => End of CA systems loop
                <pids>                                                           => Loop over all PID related to the channel and declared in the PMT
                        <pid number="1280" language="---"><![CDATA[PMT]]></pid>      => PID number, Language associated (or "---" if no language associated), PID description if avaliable
                        <pid number="160" language="---"><![CDATA[Video (MPEG2)]]></pid>
                        <pid number="80" language="fra"><![CDATA[Audio (MPEG2)]]></pid>
                        <pid number="81" language="eng"><![CDATA[Audio (MPEG2)]]></pid>
                        <pid number="32" language="---"><![CDATA[Teletext]]></pid>
                        <pid number="82" language="fra"><![CDATA[Audio (AC3)]]></pid>
                        <pid number="83" language="eng"><![CDATA[Audio (AC3)]]></pid>
                </pids>                                                          => End of PID loop
                <clients count="1">                                              => Loop over unicast clients
                    <client number="0">                                          => Client Information
                          <socket>80</socket>                                        => Local socket FD
                          <remote_address><![CDATA[192.168.0.54]]></remote_address>  => Remote IP address of the client
                          <remote_port>438754</remote_port>                          => Remote port
                          <buffersize>0</buffersize>                                 => Client Buffer
                          <consecutive_errors>0</consecutive_errors>                 => Count of consecutive errors when writing to this client
                          <first_error_time>1411392479</first_error_time>            =>
                          <last_error_time>0</last_error_time>                       =>
                        </client>                                                    => End of Client.
                </clients>                                                       => End of clients loop
        </channel>                                                           => End of channels loop
</mumudvb>                                                               => End of response

1.1. JSON files:

You can get similar information in the JSON files

http://ip_http:port_http/channels_list.json

http://ip_http:port_http/monitor/signal_power.json

http://ip_http:port_http/channels_traffic.json

http://ip_http:port_http/monitor/state.json

2. Access to the CAM menu:

These two webservices allow for accessing the CAM menu during streaming.
This is usefull for checking rights or download status for example.

The file cam_menu.php is a simple demonstration on how to use these webservices in order to make a web interface with AJAX compatible with the most important browsers (Firefox, Chrome, Internet Explorer).

For using it, you just need a webserver (lighttpd, apache, etc.) with PHP activated.
The web page accept one GET parameter: port_server. This is the unicast port setup for accessing MuMuDVB webservices.

The CAM menu is refresded every 2 seconds and buttons can be used to navigate in the menus.
MENU, LIST and ENQUIRY MMI objects are supported.

First webservice return the latest menu returned by the CAM.
There is no input parameters.
URL : http://ip_http:port_http/cam/menu.xml
Below, some examples of response with comments.

Case when the CAM isn’t initialized:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
        <datetime><![CDATA[Mon Nov  1 22:08:17 2010]]></datetime>  => Last update time/date
        <object><![CDATA[NONE]]></object>                          => No object to show
        <title><![CDATA[CAM not initialized!]]></title>            => Message about CAM not initialized
</menu>

Case when the CAM is initialized but there is no menu to display:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
        <datetime><![CDATA[Tue Nov  2 22:38:37 2010]]></datetime>       => Last update time/date
        <cammenustring><![CDATA[Aston Module 2.1800]]></cammenustring>  => CAM model
        <object><![CDATA[NONE]]></object>                               => No object to show
        <title><![CDATA[No menu to display]]></title>                   => Message about no menu to display
</menu>

Case when a object is send by the CAM to be displayed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
        <datetime><![CDATA[Tue Nov  2 22:39:58 2010]]></datetime>       => When the object was received
        <cammenustring><![CDATA[Aston Module 2.1800]]></cammenustring>  => CAM model
        <object><![CDATA[MENU]]></object>                               => Object: "MENU", "LIST" or "ENQUIRY"
        <title><![CDATA[Module Aston]]></title>                         => Object title
        <subtitle><![CDATA[Carte num ro 544.193.724]]></subtitle>       => Object subtitle (when an "ENQUIRY" object is display, show the number of characters expected in the answer)
        <item num="0"><![CDATA[Return]]></item>                         => For "MENU" and "LIST" objects, contain the lines of information or the items to be choosen. The "num" attribute correspond to the key to press to choose the item.
        <item num="1"><![CDATA[Consultation des droits]]></item>
        <item num="2"><![CDATA[R glages]]></item>
        <item num="3"><![CDATA[Information]]></item>
        <bottom><![CDATA[Votre choix, svp]]></bottom>                   => Object bottom line
</menu>

Second webservice allows for sending response to the CAM.
There is one integer GET paramter: key.
Possible keys: 0 to 9 (numbers), M for asking the CAM menu, C for cancelling an ENQUIRY object.
URL : http://ip_http:port_http/cam/action.xml?key=X
There are 4 king of responses.

OK:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<action>
        <datetime><![CDATA[Mon Nov  1 22:13:30 2010]]></datetime>
        <key><![CDATA[X]]></key>
        <result><![CDATA[OK]]></result>
</action>

Unknown key:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<action>
        <datetime><![CDATA[Mon Nov  1 22:13:30 2010]]></datetime>
        <key><![CDATA[X]]></key>
        <result><![CDATA[ERROR: Unknown key!]]></result>
</action>

CAM not initialized:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<action>
        <datetime><![CDATA[Mon Nov  1 22:13:30 2010]]></datetime>
        <key><![CDATA[X]]></key>
        <result><![CDATA[ERROR: CAM not initialized!]]></result>
</action>

MuMuDVB compiled without CAM support:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<action>
        <datetime><![CDATA[Mon Nov  1 22:13:30 2010]]></datetime>
        <key><![CDATA[X]]></key>
        <result><![CDATA[Compiled without CAM support]]></result>
</action>

3. Electronic program guide

The content of the EIT table (electronic programs guide) is now available via the Webservices.

To enable it, put store_eit=1 in your configuration file and get the file:

http://ip_http:port_http/monitor/EIT.json

The structure follow the structure of the data descriptors of the DVB
stream, so please consult the norm EN 300 468 if you want to get more
info see documentation.

An example result is available here.

Last updated
 2015-08-23 13:09:31 EDT


text:
package io.github.jklingsporn.vertx.jooq.generate.classic;

import io.github.jklingsporn.vertx.jooq.generate.builder.DelegatingVertxGenerator;
import io.github.jklingsporn.vertx.jooq.generate.builder.PredefinedNamedInjectionStrategy;
import io.github.jklingsporn.vertx.jooq.generate.builder.VertxGeneratorBuilder;

/**
 * Created by jensklingsporn on 06.02.18.
 */
public class ClassicJDBCGuiceVertxGenerator extends DelegatingVertxGenerator {

    public ClassicJDBCGuiceVertxGenerator() {
        super(VertxGeneratorBuilder.init().withClassicAPI().withJDBCDriver().withGuice(true, PredefinedNamedInjectionStrategy.DISABLED).build());
    }
}

redpajama_set_name: RedPajamaGithub


text:
const fs = require('fs');
const path = require('path');

const prettierOptions = JSON.parse(
  fs.readFileSync(path.resolve(__dirname, '.prettierrc'), 'utf8'),
);

module.exports = {
  extends: ['airbnb-base', 'prettier'],
  plugins: ['prettier', 'import'],
  parser: '@babel/eslint-parser',
  parserOptions: {
    requireConfigFile: false,
  },
  rules: {
    'prettier/prettier': ['error', prettierOptions],
    'no-use-before-define': 0,
    'import/no-extraneous-dependencies': 0,
  },
  globals: {
    document: true,
    window: true,
    location: true,
    fetch: true,
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: 'webpack/webpack.config.base.js',
      },
    },
  },
};


text: /koolshare/scripts/mia_config.sh &


text:
"""

    This python script reads a full tree and plots some tree statistics, like merger rates, merger trees

"""

import sys,os,string,time,re,struct
import math,operator
import random as rn
import matplotlib
matplotlib.use('Agg')
import numpy as np

#load python routines
#one of these paths should work
sys.path.append('/path/to/VELOCIraptor-STF/stf/tools/')
import velociraptor_python_tools as vpt

def dtda(a,Omegam,OmegaL):
    return 1.0/np.sqrt(Omegam*np.power(a,-3.0)+OmegaL)/a
def getCosmicTime(a1,a2,Omegam,OmegaL,hval):
    intval=scipyint.romberg(dtda,a1,a2,args=(Omegam,OmegaL,))
    return 9.77813/hval*intval

#load the data
#note that if you want you do not need to load everything into memory and can select a subset of fields/halo properites
#just set requestedfields=['ID','Mass_200crit'] for example to load only those properties
#otherwise, can leave requestedfields empty
requestedfields=[]
#not by default tis read routines places z=0 at index=0 but of course, you can reverse the order
atime,tree,numhalos,halodata,cosmodata,unitdata=vpt.ReadUnifiedTreeandHaloCatalog(treefilename,requestedfields)
numsnaps=len(atime)

"""
    -----------------------------------------------
    Now for some sample analysis
    -----------------------------------------------
"""
#this is the special value that allows the tree to be walked
TEMPORALHALOIDVAL=1000000000000

#here's an example of looking at the evolution, motion of a halo
#lets select a sample of halos at z=0.
selectedhalos=halodata[0]['ID'][np.where(halodata[0]['Mass_tot']*unitdata['Mass_to_solarmass']>1e12)]
len(numobjs)
for j in range(numobjs):
    #start off with some halo
    haloid=selectedhalos[j]
    #get the halo's index by looking at its id
    haloindex=int(haloid%TEMPORALHALOIDVAL-1)
    halosnap=0

    #store the values
    mainindex=haloindex
    mainsnap=halosnap
    mainid=haloid

    #move along main halo store properties
    progid=halodata[i][halosnap]["Tail"][haloindex]
    progindex=int(progid%TEMPORALHALOIDVAL-1)
    progsnap=int(np.floor(progid/TEMPORALHALOIDVAL))
    #now for a reverse ordered data set where you have the halos at z=0 located at [0]
    progsnap=numsnaps-1-progsnap
    #otherwise, leave at is

    #find out how long the object has lived for
    proglength=1
    #we do this by checking if the progenitor id is not a halo's own id
    while (progid!=haloid):
        proglength+=1
        #move to the next halo in time
        haloid=progid
        halosnap=progsnap
        haloindex=progindex
        #get the next progenitor
        progid=halodata[i][halosnap]["Tail"][haloindex]
        progindex=int(progid%HALOIDVAL-1)
        progsnap=int(np.floor(progid/TEMPORALHALOIDVAL))
        progsnap=numsnaps-1-progsnap

    #now that we know how long an object has lived for,
    #lets do some stuff

    #reset
    haloid=mainid
    haloindex=mainindex
    halosnap=mainsnap

    #allocate mem
    pos=np.zeros(proglength,3)
    vel=np.zeros(proglength,3)
    mass=np.zeros(proglength)

    #init the prog id
    progid=halodata[i][halosnap]["Tail"][haloindex]
    progindex=int(progid%HALOIDVAL-1)
    progsnap=int(np.floor(progid/TEMPORALHALOIDVAL))
    progsnap=numsnaps-1-progsnap

    isnapcount=0
    start=time.clock()
    while (haloid!=progid):
        pos[isnapcount]=np.array([halodata[i][halosnap]["Xc"][haloindex],halodata[i][halosnap]["Yc"][haloindex],halodata[i][halosnap]["Zc"][haloindex]])
        vel[isnapcount]=np.array([halodata[i][halosnap]["VXc"][haloindex],halodata[i][halosnap]["VYc"][haloindex],halodata[i][halosnap]["VZc"][haloindex]])
        mass[isnapcount]=[halodata[i][halosnap]["Mass_tot"][haloindex]
        isnapcount+=1
        haloid=progid
        halosnap=progsnap
        haloindex=progindex
        progid=halodata[i][halosnap]["Tail"][haloindex]
        progindex=int(progid%HALOIDVAL-1)
        progsnap=int(np.floor(progid/TEMPORALHALOIDVAL))
        progsnap=numsnaps-1-progsnap
    print "done",j,"with ",proglength,time.clock()-start


text:
"""
Shikin review page and associated API
"""

from sqlalchemy import func
import datetime
import random
from flask import render_template, abort, request, jsonify, session

from . import app, ocrfix
from .model import DocSegment, DocSegmentReview, User
from .util import dologin

def get_user_or_abort():
    # if request.remote_addr == '127.0.0.1':
    #     user = 'admin'
    # else:
    user = session.get('username')
    if not user:
        abort(403)

    u = User.query.filter(User.name == user).first()
    if not u:
        abort(403)

    return u

@app.route('/api/reviewcount/<user>')
def review_count(user):
    u = User.query.filter(User.name == user).first()
    if not u:
        return abort(404)
    return jsonify({'user': user, 'count': len(u.reviews)})

@app.route('/api/unreview/<int:segmentid>')
def unreview(segmentid):
    user = get_user_or_abort()

    revid = request.args.get('revid')

    ds = DocSegment.query.filter(DocSegment.id == segmentid).first()
    if not ds:
        abort(404)
    ds.viewcount = max(0, ds.viewcount-1)
    app.dbobj.session.add(ds)
    if not revid or not revid.isdigit():
        app.dbobj.session.commit()
        return
    revid = int(revid)
    old = DocSegmentReview.query.filter(DocSegmentReview.id == revid, DocSegmentReview.user_id == user.id).first()
    if not old:
        abort(404)
    app.dbobj.session.delete(old)
    app.dbobj.session.commit()

    return jsonify({'status': 'ok', 'id': revid})

@app.route('/api/review/<int:segmentid>')
def review_submit(segmentid):
    user = get_user_or_abort()

    ds = DocSegment.query.filter(DocSegment.id == segmentid).first()
    if not ds:
        abort(404)

    text = request.args.get('text')
    skip = request.args.get('skip')

    if text is None and not skip:
        abort(404)

    timestamp = datetime.datetime.now()
    ds.viewcount += 1
    app.dbobj.session.add(ds)

    if skip:
        app.dbobj.session.commit()
        return jsonify({'status': 'ok'})

    old = DocSegmentReview.query\
                          .filter(DocSegmentReview.segment_id == ds.id)\
                          .order_by(DocSegmentReview.rev.desc())\
                          .first()
    if old is not None:
        rev = old.rev + 1
    else:
        rev = 1

    newrev = DocSegmentReview(segment=ds, rev=rev, timestamp=timestamp, user=user, text=text)
    app.dbobj.session.add(newrev)
    app.dbobj.session.commit()

    return jsonify({'status': 'ok', 'id': newrev.id})

@app.route('/api/reviewdata', methods=['GET'])
def reviewdata():
    # Find a random early page with lots of unreviewed items.  This way even
    # with multiple simulteanous users they should get different pages.
    minviewcount = app.dbobj.session.query(func.min(DocSegment.viewcount)).one()[0]

    q = app.dbobj.session.query(DocSegment.doc_id, DocSegment.page)\
                 .filter(DocSegment.ocrtext != None)\
                 .filter(DocSegment.viewcount <= minviewcount)\
                 .distinct()

    pages = list(q.all())

    app.logger.debug("%d pages with segments of only %d views" % (len(pages), minviewcount))

    # FIXME: this kinda works, but as all the pages get reviewed it will tend
    # toward giving all users the same page.  not really a problem until I have
    # more than 1 user.
    docid, page = random.choice(pages)
    q = DocSegment.query.filter(DocSegment.doc_id == docid)\
                        .filter(DocSegment.page == page)\
                        .filter(DocSegment.viewcount <= minviewcount)

    segments = q.all()
    if not segments:
        abort(404)

    segdata = []
    for d in segments:
        if d.usertext is None:
            txt = ocrfix.guess_fix(d.ocrtext)
            suggests = ocrfix.suggestions(d)
        else:
            txt = d.usertext.text
            suggests = []

        lines = max(len(d.ocrtext.splitlines()), len(txt.splitlines()))

        segdata.append(dict(ocrtext=d.ocrtext, text=txt, segment_id=d.id,
                            x1=d.x1, x2=d.x2, y1=d.y1, y2=d.y2,
                            textlines=lines, docid=docid, page=page+1, suggests=suggests))

    return jsonify(dict(segments=segdata, docid=docid, page=page+1))

@app.route('/review', methods=['GET', 'POST'])
def review():
    """ Review page """
    error = None
    user = None
    if request.method == 'POST':
        user, error = dologin()

    if 'username' in session:
        u = get_user_or_abort()
        uname = u.name
    else:
        uname = None

    return render_template('review.html', user=uname, error=error)


text:
#ifndef TENSORFLOW_PYTHON_EAGER_PYWRAP_TENSOR_CONVERSION_H_
#define TENSORFLOW_PYTHON_EAGER_PYWRAP_TENSOR_CONVERSION_H_

// Place `<locale>` before <Python.h> to avoid build failure in macOS.
#include <locale>

// The empty line above is on purpose as otherwise clang-format will
// automatically move <Python.h> before <locale>.
#include <Python.h>

#include "absl/container/flat_hash_map.h"
#include "absl/hash/hash.h"
#include "absl/strings/string_view.h"
#include "tensorflow/c/eager/c_api.h"
#include "tensorflow/core/common_runtime/eager/tensor_handle.h"
#include "tensorflow/core/framework/types.pb.h"

namespace tensorflow {

// Wrapper-class allowing to use Python hashing/comparison functions
// for PyObject*.
//
// Note that unlike Safe_PyObjectPtr this class does not steal a
// reference to a Python object. The caller is responsible for doing
// Py_INCREF/Py_DECREF.
struct PyObjectPtr {
  template <typename H>
  friend H AbslHashValue(H h, const PyObjectPtr& obj) {
    return H::combine(std::move(h), PyObject_Hash(obj.ptr));
  }

  explicit PyObjectPtr(PyObject* ptr) : ptr(ptr) {}

  explicit inline operator PyObject*() const { return ptr; }

  inline bool operator==(const PyObjectPtr& other) const {
    // We require exact type equality to account for 0 == 0.0 == False.
    if (Py_TYPE(ptr) != Py_TYPE(other.ptr)) {
      return false;
    }

    bool result = PyObject_RichCompareBool(ptr, other.ptr, Py_EQ) > 0;
    CHECK(!PyErr_Occurred());
    return result;
  }

 private:
  PyObject* ptr;
};

// Cache mapping PyObject* to the corresponding on-device TFE_TensorHandles.
// Used to speed up ConvertToEagerTensor for scalars.
// TODO(slebedev): move ConvertToEagerTensor here.
struct TFE_TensorHandleCache {
  static TFE_TensorHandleCache* Get();

  TFE_TensorHandleCache() { cache.reserve(64); }
  ~TFE_TensorHandleCache() { DecrefUnrefAll(); }

  TFE_TensorHandle* Lookup(PyObject* value, tensorflow::DataType dtype,
                           TFE_Context* ctx,
                           absl::string_view device_name) const;

  void Insert(PyObject* value, tensorflow::DataType dtype, TFE_Context* ctx,
              absl::string_view device_name, TFE_TensorHandle* h);

  void Clear();

 private:
  // TODO(kkb): Instead of `TFE_Context*` key, ideally Python's context object
  // should have TFE_TensorHandleCache instance. Migrate once we Python context
  // object is backed by C++ data structure. b/169790439
  using Key = std::tuple<PyObjectPtr, tensorflow::DataType, TFE_Context*,
                         absl::string_view>;

  void DecrefUnrefAll() {
    for (const auto& p : cache) {
      Py_DECREF(static_cast<PyObject*>(std::get<0>(p.first)));
      TFE_DeleteTensorHandle(p.second);
    }
  }

  // Not guarded by a mutex because the code is only used while the
  // GIL is held.
  absl::flat_hash_map<Key, TFE_TensorHandle*> cache;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_PYTHON_EAGER_PYWRAP_TENSOR_CONVERSION_H_


text:
<?php

use app\core\helpers\Html;
use app\core\helpers\Url;
use app\core\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\memorial\models\MemorialSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::searchBegin(); ?>

    <?= $form->field($model, 'title') ?>

        <?= Html::submitButton('  查找', ['class' => 'btn btn-primary btn-sm']) ?>
        <?= Html::a('  重置',Url::toRoute(['index']),['class'=>'btn btn-danger btn-sm']);?>

    <?php ActiveForm::end(); ?>


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
/// @author Matthew Von-Maszewski
////////////////////////////////////////////////////////////////////////////////

#pragma once

#include "Basics/Result.h"
#include "Cluster/MaintenanceStrings.h"

#include <map>
#include <memory>
#include <string>

#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>

namespace arangodb {
namespace maintenance {

//
// state accessor and set functions
//  (some require time checks and/or combination tests)
//
enum ActionState {
  READY = 1,        // waiting for a worker on the deque
  EXECUTING = 2,    // user or worker thread currently executing
  WAITING = 3,      // initiated a pre-task, waiting for its completion
  WAITINGPRE = 4,   // parent task created, about to execute on parent's thread - not used
  WAITINGPOST = 5,  // parent task created, will execute after parent's success - not used
  PAUSED = 6,       // (not implemented) user paused task - not used
  COMPLETE = 7,     // task completed successfully
  FAILED = 8,       // task failed, no longer executing
};

/**
 * @brief Action description for maintenance actions
 *
 * This structure holds once initialized constant parameters of a maintenance
 * action. Members are declared const, thus thread safety guards are omitted.
 */
struct ActionDescription final {
  /**
   * @brief Construct with properties
   * @param  desc  Descriminatory properties, which are considered for hash
   * @param  properties  Non discriminatory properties
   */
  ActionDescription(
      std::map<std::string, std::string> description,
      int priority,
      bool runEvenIfDuplicate,
      std::shared_ptr<VPackBuilder> properties = std::make_shared<VPackBuilder>());

  /**
   * @brief Clean up
   */
  ~ActionDescription();

  /**
   * @brief Check equality (only _description considered)
   * @param  other  Other descriptor
   */
  bool operator==(ActionDescription const& other) const;

  /**
   * @brief Calculate hash of _description as concatenation
   * @param  other  Other descriptor
   */
  std::size_t hash() const noexcept;
  static std::size_t hash(std::map<std::string, std::string> const& desc) noexcept;

  /// @brief Name of action
  std::string const& name() const noexcept;

  /**
   * @brief Check if key exists in discriminatory container
   * @param  key   Key to lookup
   * @return       true if key is found
   */
  bool has(std::string const& key) const noexcept;

  /**
   * @brief Check if key exists in discriminatory container and if it has the specified value
   * @param  key   Key to lookup
   * @param  value Value to compare against
   * @return       true if key is found and has the exact same value
   */
  bool has(std::string const& key, std::string const& value) const noexcept;

  /**
   * @brief Get a string value from description
   * @param  key   Key to get
   * @exception    std::out_of_range if the we do not have this key in discriminatory container
   * @return       Value to specified key
   */
  std::string get(std::string const& key) const;

  /**
   * @brief Get a string value from description
   * @param  key   Key to get
   * @exception    std::out_of_range if the we do not have this key in discriminatory container
   * @return       Value to specified key
   */
  std::string operator()(std::string const& key) const;

  /**
   * @brief Get a string value from description
   *
   * @param  key   Key to get
   * @param  value If key is found the value is assigned to this variable
   * @return       Success (key found?)
   */
  Result get(std::string const& key, std::string& value) const;

  /**
   * @brief Dump to JSON(vpack)
   * @return       JSON Velocypack of all paramters
   */
  VPackBuilder toVelocyPack() const;

  /**
   * @brief Dump to JSON(vpack)
   * @return       JSON Velocypack of all paramters
   */
  void toVelocyPack(VPackBuilder&) const;

  /**
   * @brief Dump to JSON(string)
   * @return       JSON string of all paramters
   */
  std::string toJson() const;

  /**
   * @brief Dump to JSON(output stream)
   * @param  os    Output stream reference
   * @return       Output stream reference
   */
  std::ostream& print(std::ostream& os) const;

  /**
   * @brief Get non discriminatory properties
   *            Get non discriminatory properties.
   *            This function does not throw as builder is always when here.
   * @return    Non discriminatory properties
   */
  std::shared_ptr<VPackBuilder> const properties() const;

  /**
   * @brief Get priority, the higher the more priority, 1 is default
   * @return int
   */
  int priority() const {
    return _priority;
  }

  /**
   * @brief Get the fact if it is forced or not. If forced, the MaintenanceFeature
   * will not sort out duplicates by hashing the description. Rather, the action
   * will always be submitted.
   */
  bool isRunEvenIfDuplicate() const {
    return _runEvenIfDuplicate;
  }

 private:
  /** @brief discriminatory properties */
  std::map<std::string, std::string> const _description;

  /** @brief non-discriminatory properties */
  std::shared_ptr<VPackBuilder> const _properties;

  /** @brief priority */
  int _priority;

  /// @brief flag to not sort out duplicates by hashing
  bool _runEvenIfDuplicate;
};

}  // namespace maintenance
}  // namespace arangodb

namespace std {
ostream& operator<<(ostream& o, arangodb::maintenance::ActionDescription const& d);
/// @brief Hash function used by std::unordered_map<ActionDescription,...>
template <>
struct hash<arangodb::maintenance::ActionDescription> {
  typedef arangodb::maintenance::ActionDescription argument_t;
  typedef std::size_t result_t;
  result_t operator()(argument_t const& a) const noexcept;
};

}  // namespace std


text:
namespace leveldb {

class FlexCacheTest { };

TEST(FlexCacheTest, UserSizing) {
    Options options;
    DB * db[10];
    Status st;
    std::string dbname, value;
    int loop;
    char buffer[12];

    options.create_if_missing=true;
    options.filter_policy=NewBloomFilterPolicy2(16);
    options.total_leveldb_mem=1000*1024*1024L;
    options.write_buffer_size=45*1024*1024L;

    // verify accounting with one database
    dbname = test::TmpDir() + "/flexcache0";
    st=DB::Open(options, dbname, &db[0]);
    ASSERT_OK(st);
    ASSERT_EQ(1, DBList()->GetDBCount(false));

    db[0]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(922742784L, atoi(value.c_str()));

    db[0]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(920645632L, atoi(value.c_str()));

    // verify accounting with three databases
    dbname = test::TmpDir() + "/flexcache1";
    st=DB::Open(options, dbname, &db[1]);
    ASSERT_OK(st);
    dbname = test::TmpDir() + "/flexcache2";
    st=DB::Open(options, dbname, &db[2]);
    ASSERT_OK(st);
    ASSERT_EQ(3, DBList()->GetDBCount(false));

    db[0]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(223692117L, atoi(value.c_str()));

    db[0]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(221594965L, atoi(value.c_str()));

    db[1]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(223692117L, atoi(value.c_str()));

    db[1]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(221594965L, atoi(value.c_str()));

    db[2]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(223692117L, atoi(value.c_str()));

    db[2]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(221594965L, atoi(value.c_str()));

    // verify accounting after two databases go away
    delete db[0];
    delete db[2];

    db[1]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(922742784L, atoi(value.c_str()));

    db[1]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(920645632L, atoi(value.c_str()));

    // rebuild from zero to ten databases, verify accounting
    delete db[1];

    options.total_leveldb_mem=3000*1024*1024L;
    for(loop=0; loop<10; ++loop)
    {
        snprintf(buffer, sizeof(buffer), "/flexcache%u", loop);
        dbname=test::TmpDir() + buffer;
        st=DB::Open(options, dbname, &db[loop]);
        ASSERT_OK(st);
        ASSERT_EQ(loop+1, DBList()->GetDBCount(false));
    }   // for

    for(loop=0; loop<10; ++loop)
    {
        db[loop]->GetProperty("leveldb.block-cache", &value);
        ASSERT_EQ(188739584l, atoi(value.c_str()));

        db[loop]->GetProperty("leveldb.file-cache", &value);
        ASSERT_EQ(186642432L, atoi(value.c_str()));
    }   // for

    for (loop=0; loop<10; ++loop)
    {
        delete db[loop];
        snprintf(buffer, sizeof(buffer), "/flexcache%u", loop);
        dbname=test::TmpDir() + buffer;
        st=DestroyDB(dbname, options);
        ASSERT_OK(st);
    }   // for

    delete options.filter_policy;
    options.filter_policy=NULL;
}

TEST(FlexCacheTest, MixedSizing) {
    Options options;
    DB * db[10];
    Status st;
    std::string dbname, value;
    int loop;
    char buffer[12];

    options.create_if_missing=true;
    options.filter_policy=NewBloomFilterPolicy2(16);
    options.total_leveldb_mem=1000*1024*1024L;
    options.write_buffer_size=45*1024*1024L;

    // verify accounting with one user & one internal
    dbname = test::TmpDir() + "/flexcache0";
    st=DB::Open(options, dbname, &db[0]);
    ASSERT_OK(st);
    ASSERT_EQ(1, DBList()->GetDBCount(false));
    ASSERT_EQ(0, DBList()->GetDBCount(true));

    db[0]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(922742784l, atoi(value.c_str()));

    db[0]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(920645632L, atoi(value.c_str()));

    // add internal
    dbname = test::TmpDir() + "/flexcache1";
    options.is_internal_db=true;
    options.total_leveldb_mem=1600*1024*1024L;
    st=DB::Open(options, dbname, &db[1]);
    ASSERT_OK(st);
    ASSERT_EQ(1, DBList()->GetDBCount(false));
    ASSERT_EQ(1, DBList()->GetDBCount(true));

    db[0]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(1216344064l, atoi(value.c_str()));

    db[0]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(1214246912L, atoi(value.c_str()));

    db[1]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(209711104l, atoi(value.c_str()));

    db[1]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(207613952L, atoi(value.c_str()));

    delete db[0];
    ASSERT_EQ(0, DBList()->GetDBCount(false));
    ASSERT_EQ(1, DBList()->GetDBCount(true));
    db[1]->GetProperty("leveldb.block-cache", &value);
    ASSERT_EQ(209711104L, atoi(value.c_str()));

    db[1]->GetProperty("leveldb.file-cache", &value);
    ASSERT_EQ(207613952L, atoi(value.c_str()));

    delete db[1];

    // rebuild from zero to ten databases, verify accounting
    options.total_leveldb_mem=4000*1024*1024L;

    for(loop=0; loop<10; ++loop)
    {
        options.is_internal_db=(1==(loop %2));
        snprintf(buffer, sizeof(buffer), "/flexcache%u", loop);
        dbname=test::TmpDir() + buffer;
        st=DB::Open(options, dbname, &db[loop]);
        ASSERT_OK(st);
    }   // for

    ASSERT_EQ(5, DBList()->GetDBCount(false));
    ASSERT_EQ(5, DBList()->GetDBCount(true));

    for(loop=0; loop<10; ++loop)
    {
        if (0==(loop %2))
        {
            db[loop]->GetProperty("leveldb.block-cache", &value);
            ASSERT_EQ(545255424l, atoi(value.c_str()));

            db[loop]->GetProperty("leveldb.file-cache", &value);
            ASSERT_EQ(543158272L, atoi(value.c_str()));
        }   // if
        else
        {
            db[loop]->GetProperty("leveldb.block-cache", &value);
            ASSERT_EQ(41938944l, atoi(value.c_str()));

            db[loop]->GetProperty("leveldb.file-cache", &value);
            ASSERT_EQ(39841792L, atoi(value.c_str()));
        }   // else
    }   // for

    for (loop=0; loop<10; ++loop)
    {
        delete db[loop];
        snprintf(buffer, sizeof(buffer), "/flexcache%u", loop);
        dbname=test::TmpDir() + buffer;
        st=DestroyDB(dbname, options);
        ASSERT_OK(st);
    }   // for

    delete options.filter_policy;
    options.filter_policy=NULL;
}

}  // namespace leveldb

int main(int argc, char** argv) {
  return leveldb::test::RunAllTests();
}


text:
"""
test_python-boilerplate
----------------------------------

Tests for `python-boilerplate` module.
"""

import unittest

from python-boilerplate import python-boilerplate

class TestPython-boilerplate(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass

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


text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;

namespace OpenADK.Library.us.Common{

/// <summary>This element contains information about a map location. The GridLocation element is utilized within another object or element, such as Address or BusStopInfo</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 1.1</para>
/// </remarks>
[Serializable]
public class GridLocation : SifElement
{
	/// <summary>
	/// Creates an instance of a GridLocation
	/// </summary>
	public GridLocation() : base ( CommonDTD.GRIDLOCATION ){}

	/// <summary>
	/// Constructor that accepts values for all mandatory fields
	/// </summary>
	///<param name="latitude">The latitude coordinate of this location expressed in decimal format (e.g. "41.7699657")</param>
	///<param name="longitude">The longitude coordinate of this location expressed in decimal format (e.g. "79.548445")</param>
	///
	public GridLocation( decimal? latitude, decimal? longitude ) : base( CommonDTD.GRIDLOCATION )
	{
		this.Latitude = latitude;
		this.Longitude = longitude;
	}

	/// <summary>
	/// Constructor used by the .Net Serialization formatter
	/// </summary>
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected GridLocation( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	/// <summary>
	/// Gets the metadata fields that make up the key of this object
	/// </summary>
	/// <value>
	/// an array of metadata fields that make up the object's key
	/// </value>
	public  IElementDef[] KeyFields {
		get { return new IElementDef[] { CommonDTD.GRIDLOCATION_LATITUDE, CommonDTD.GRIDLOCATION_LONGITUDE }; }
	}

	/// <summary>
	/// Gets or sets the value of the <c><Latitude></c> element.
	/// </summary>
	/// <value> The <c>Latitude</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "The latitude coordinate of this location expressed in decimal format (e.g. "41.7699657")"</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.1</para>
	/// </remarks>
	public decimal? Latitude
	{
		get
		{
			return (decimal?) GetSifSimpleFieldValue( CommonDTD.GRIDLOCATION_LATITUDE ) ;
		}
		set
		{
			SetFieldValue( CommonDTD.GRIDLOCATION_LATITUDE, new SifDecimal( value ), value );
		}
	}

	/// <summary>
	/// Gets or sets the value of the <c><Longitude></c> element.
	/// </summary>
	/// <value> The <c>Longitude</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "The longitude coordinate of this location expressed in decimal format (e.g. "79.548445")"</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.1</para>
	/// </remarks>
	public decimal? Longitude
	{
		get
		{
			return (decimal?) GetSifSimpleFieldValue( CommonDTD.GRIDLOCATION_LONGITUDE ) ;
		}
		set
		{
			SetFieldValue( CommonDTD.GRIDLOCATION_LONGITUDE, new SifDecimal( value ), value );
		}
	}

}}


text:
from Products.ZenRRD.CommandParser import CommandParser

class sqlite(CommandParser):

    def processResults(self, cmd, result):
        """
        Example output:

                         bytes.dropped = 0
             bytes.fromcache.toclients = 0
               bytes.fromcache.topeers = 0
            bytes.fromorigin.toclients = 3741796533
              bytes.fromorigin.topeers = 0
             bytes.frompeers.toclients = 0
                 bytes.imported.byhttp = 0
                  bytes.imported.byxpc = 0
                    bytes.purged.total = 0
          bytes.purged.youngerthan1day = 0
        bytes.purged.youngerthan30days = 0
         bytes.purged.youngerthan7days = 0
                        imports.byhttp = 0
                         imports.byxpc = 0
           replies.fromcache.toclients = 0
             replies.fromcache.topeers = 0
          replies.fromorigin.toclients = 13
            replies.fromorigin.topeers = 0
           replies.frompeers.toclients = 0
                  requests.fromclients = 15
                    requests.frompeers = 0
        """

        values = dict()
        for line in cmd.result.output.splitlines():
            key, value = line.split(' = ')
            values[key.strip()] = int(value) if value.isdigit() else 0

        for point in cmd.points:
            if point.id in values:
                result.values.append((point, values[point.id]))


text:
"""movefast.py sets up the infrastructure for a fictional company MoveFast.

The infrastructure makes heavy use of Google Cloud Platform.

You need to get the json credentials file before using this script. See
https://developers.google.com/identity/protocols/application-default-credentials#howtheywork.

After getting the credentials, you can simply run this script by:

    movefast.py --google-json-credentials <your-gcp-json-credentials-file>

    Copyright 2016 Heung Ming Tai

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

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

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

import argparse
import json
import logging
import os
import pprint
import sys

from apiclient import discovery
from oauth2client import client as oauth2client
import googleapiclient
import requests
import six
import time

from sorno import loggingutil

_log = logging.getLogger()
_plain_error_logger = None  # will be created in main()

class MoveFast(object):
    """A console application to do work"""
    def __init__(self, args):
        """
        Args:
            args (argparse.Namespace): The flags for the script.
        """
        self.args = args
        self.credentials = None
        self.compute = None
        self.project_id = None
        self.existing_instances = {}
        self.zone_name = args.zone

    def run(self):
        """The entry point of setting up MoveFast."""
        retcode = self._process_args()
        if retcode != 0:
            return retcode

        self._create_credentials()
        self._create_compute_service_client()

        # create all GCP resources
        self._setup_gce()

        return 0

    def _process_args(self):
        if self.args.google_json_credentials:
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = (
                self.args.google_json_credentials
            )

        project_id = self._get_project_id()

        if not project_id:
            _plain_error_logger.info(
                "Please provide project id with --project-id"
            )
            return 1

        self.project_id = project_id
        return 0

    def _create_credentials(self):
        """Creates credentials to use GCP API

        https://cloud.google.com/compute/docs/tutorials/python-guide
        """
        self.credentials = oauth2client.GoogleCredentials.get_application_default()

    def _create_compute_service_client(self):
        """Creates the client to use the Google Compute API.

        https://cloud.google.com/compute/docs/tutorials/python-guide
        """
        self.compute = discovery.build(
            "compute",
            "v1",
            credentials=self.credentials,
        )

    def _get_project_id(self):
        project_id = self.args.project_id
        if not project_id:
            # try to get it from credentials
            credentials_filename = oauth2client._get_environment_variable_file()
            if not credentials_filename:
                credentials_filename = oauth2client._get_well_known_file()

            if credentials_filename:
                with open(credentials_filename) as file_obj:
                    client_credentials = json.load(file_obj)
                    project_id = client_credentials['project_id']
        return project_id

    def _setup_gce(self):
        indent = " " * 2
        print("Existing Google Compute Engine instances:")
        resp = self.compute.instances().aggregatedList(
            project=self.project_id).execute()
        logging.debug("Resp: %s", resp)
        is_first = True
        for key, obj in resp['items'].iteritems():
            instances = obj.get('instances')
            if not instances:
                continue

            if is_first:
                is_first = False
            else:
                _print_horizontal_line()

            print("%s:" % key)
            for instance in instances:
                self.existing_instances[instance['name']] = instance
                print(indent + instance['name'])
                external_ip = self._get_instance_external_ip(instance)
                if external_ip:
                    print(
                        indent * 2 + "External IP - %s" % (
                            external_ip,
                        )
                    )

        _print_section_separator()
        print("Existing zones:")

        resp = self.compute.zones().list(project=self.project_id).execute()
        logging.debug("Resp: %s", resp)
        for zone in resp['items']:
            zone_desc = zone['description']
            print(zone_desc)
            if not self.zone_name and zone_desc.startswith("us-central1"):
                self.zone_name = zone_desc

        if self.args.do_sample_gce_vm_setup:
            _print_section_separator()
            _log.info("Set up Google Compute Engine resources")

            self._setup_echo_service()

    def _setup_echo_service(self):
        _log.info(
            "Create a Google Compute Engine vm with a simple echo serice"
            " that you can find in:"
            " https://github.com/hermantai/samples/blob/master/python/cherrypy_web_server.py"
        )

        instance_name = self.args.resource_name_prefix + "echo-service"
        if instance_name in self.existing_instances:
            print(
                "Instance %s already exists,"
                " skip creating an echo service" % instance_name
            )
            echo_service_instance = self.existing_instances[instance_name]
        else:
            echo_service_instance = self._create_echo_service_on_gce(
                instance_name,
            )

        _log.info("Test the echo service...")
        external_ip = self._get_instance_external_ip(echo_service_instance)
        if not external_ip:
            _log.error("No external ip")
            return

        url = "http://%s/echo?se=hello" % external_ip
        _log.info("Connect to %s", url)
        # check for at most two minutes
        deadline = time.time() + 120
        while True:
            try:
                resp = requests.get(url)
                break
            except requests.exceptions.ConnectionError as e:
                diff = deadline - time.time()
                if diff > 0:
                    _log.error("Cannot connect to the echo service: %s", e)
                    _log.info(
                        "%d seconds before deadline, sleep 5 seconds then retry...",
                        diff,
                    )
                    time.sleep(5)
                    continue
                else:
                    _log.exception("Failed to connect to the echo service")
                    return

        _log.debug("Resp: %s", resp.__dict__)
        if resp.status_code == 200:
            _log.info("Succeeded!")
        else:
            _log.error("Failed: %s", resp.__dict__)

    def _create_echo_service_on_gce(self, instance_name):
        instance_config = self._get_echo_service_instance_config(
            self.zone_name,
            instance_name,
        )
        _log.debug("Instance config: %s", instance_config)

        operation = self.compute.instances().insert(
            project=self.project_id,
            zone=self.zone_name,
            body=instance_config).execute()
        _log.debug("Resp: %s", operation)

        self._wait_for_operation(self.zone_name, operation)
        _log.info(
            "You should be able to see the startup script"
            " in /var/run/google.startup.script"
        )
        _log.info(
            "The output of the startup script run at startup is in"
            " /var/log/daemon.log"
        )

        instance = self.compute.instances().get(
            project=self.project_id,
            zone=self.zone_name,
            instance=instance_name,
        ).execute()
        if instance:
            self.existing_instances[instance_name] = instance

        return instance

    def _get_echo_service_instance_config(self, zone, name):
        """https://cloud.google.com/compute/docs/tutorials/python-guide"""

        source_disk_image = \
            "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-8-jessie-v20160329"
        machine_type = "zones/%s/machineTypes/f1-micro" % zone
        startup_script = """
            echo Hello && date +%Y-%m-%dT%H:%M:%S
            fruit=$(curl http://metadata/computeMetadata/v1/instance/attributes/fruit -H "Metadata-Flavor: Google")
            echo My favorite food is "$fruit".
            sudo apt-get install -y python-pip
            sudo apt-get install -y git
            sudo pip install cherrypy

            mkdir /tmp/apps
            cd /tmp/apps
            git clone https://github.com/hermantai/samples.git
            sudo python samples/python/cherrypy_web_server.py --port 80 --host 0.0.0.0
        """

        config = {
            'name': name,
            'machineType': machine_type,

            # Specify the boot disk and the image to use as a source.
            'disks': [
                {
                    "type": "PERSISTENT",
                    'boot': True,
                    'model': "READ_WRITE",
                    'autoDelete': True,
                    'initializeParams': {
                        'sourceImage': source_disk_image,
                        'diskType': "projects/%s/zones/%s/diskTypes/pd-ssd" % (
                            self.project_id, zone),
                        'diskSizeGb': "10"
                    }
                }
            ],

            # Specify a network interface with NAT to access the public
            # internet.
            'networkInterfaces': [{
                'network': 'global/networks/default',
                'accessConfigs': [
                    {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}
                ]
            }],

            # Allow the instance to access cloud storage and logging.
            'serviceAccounts': [{
                'email': 'default',
                'scopes': [
                    # every cloud API
                    "https://www.googleapis.com/auth/cloud-platform",
                ]
            }],
            'scheduling': {
                "preemptible": False,
                "onHostMaintenance": "MIGRATE",
                "automaticRestart": True
            },

            "tags": {
                "items": [
                    "http-server",
                    "https-server",
                ]
            },

            # Metadata is readable from the instance and allows you to
            # pass configuration from deployment scripts to instances.
            'metadata': {
                'items': [
                    {
                        # Startup script is automatically executed by the
                        # instance upon startup.
                        'key': 'startup-script',
                        'value': startup_script
                    }, {
                        'key': 'fruit',
                        'value': "blueberries",
                    },
                ]
            }
        }
        return config

    def _wait_for_operation(self, zone_name, operation):
        while True:
            _log.info(
                "Waiting for operation %s to finish (status: %s)...",
                operation['name'],
                operation['status'],
            )
            result = self.compute.zoneOperations().get(
                project=self.project_id,
                zone=zone_name,
                operation=operation['name']).execute()

            _log.debug("Resp: %s", result)

            if result['status'] == 'DONE':
                _log.info("Done")
                if 'error' in result:
                    raise Exception(result['error'])
                return result

            time.sleep(3)

    def _get_instance_external_ip(self, instance):
        network_access_configs = _get_null_safe(
            instance,
            'networkInterfaces',
            'accessConfigs',
        )
        if network_access_configs:
            for network_access_config in network_access_configs:
                if network_access_config['name'] == "External NAT":
                    return network_access_config.get('natIP')

        return None

def _print_horizontal_line():
    print("-" * 70)

def _print_section_separator():
    print("=" * 70)

def _get_null_safe(mixed, *keys):
    val = mixed
    for key in keys:
        if val is None:
            return val

        if type(val) is dict:
            val = val.get(key)
        elif type(val) is list:
            if type(key) in six.integer_types:
                if key < len(val):
                    val = val[key]
                else:
                    val = None
            else:
                # iterate the list to find the first item
                # that has the specified key, and use that as the value
                new_val = None
                for item in val:
                    new_val = _get_null_safe(item, key)
                    if new_val is not None:
                        break
                val = new_val

    return val

def parse_args(cmd_args):
    description = __doc__.split("Copyright 2016")[0].strip()

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        "--debug",
        action="store_true",
    )
    parser.add_argument(
        "--google-json-credentials",
        help="Path to the google json credentials file. See https://developers.google.com/identity/protocols/application-default-credentials#howtheywork",
    )
    parser.add_argument(
        "--project-id",
    )
    parser.add_argument(
        "--resource-name-prefix",
        default="movefast-",
    )
    parser.add_argument(
        "--zone",
    )
    parser.add_argument(
        "--skip-sample-gce-vm-setup",
        action="store_false",
        default=True,
        dest="do_sample_gce_vm_setup",
    )

    args = parser.parse_args(cmd_args)
    return args

def main():
    global _plain_error_logger
    args = parse_args(sys.argv[1:])

    loggingutil.setup_logger(_log, debug=args.debug)
    if not args.debug:
        # tone down the verbosity of some modules
        verbose_modules = [
            "googleapiclient.discovery",
            "oauth2client.client",
            "requests",
        ]
        for mod in verbose_modules:
            logging.getLogger(mod).setLevel(
                logging.WARNING
            )

    _plain_error_logger = loggingutil.create_plain_logger(
        "PLAIN_ERROR",
        debug=args.debug,
        stdout=False,
    )

    app = MoveFast(args)
    sys.exit(app.run())

if __name__ == '__main__':
    main()


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Specifies the C# or VB source code kind.
    /// </summary>
    public enum SourceCodeKind
    {
        /// <summary>
        /// No scripting. Used for .cs/.vb file parsing.
        /// </summary>
        Regular = 0,

        /// <summary>
        /// Allows top-level statements and declarations. Used for .csx/.vbx file parsing.
        /// </summary>
        Script = 1,

        /// <summary>
        /// Allows top-level expressions and optional semicolon.
        /// </summary>
        Interactive = 2,
    }

    internal static partial class SourceCodeKindExtensions
    {
        internal static bool IsValid(this SourceCodeKind value)
        {
            return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Interactive;
        }
    }
}


text:
package com.jpavlich.astvisualizer;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

public class ASTVNode {
	private Object node;
	private ASTVNode parent;
	private List<ASTVNode> children = new ArrayList<ASTVNode>();
	private Color bgColor;
	private Color fgColor;
	String name;
	private int yOffset;

	public ASTVNode(Object node, ASTVNode parent, String name, Color bgColor, Color fgColor, int yOffset) {
		super();
		this.node = node;
		if (parent != null) {
			this.parent = parent;
			parent.addChild(this);
		}
		this.name = name;
		this.bgColor = bgColor;
		this.fgColor = fgColor;
		this.yOffset = yOffset;
	}

	public Object getNode() {
		return node;
	}

	public ASTVNode getParent() {
		return parent;
	}

	public boolean addChild(ASTVNode e) {
		return children.add(e);
	}

	public List<ASTVNode> getChildren() {
		return children;
	}

	public String getText() {
		return name;
	}

	public String getName() {
		return name;
	}

	public Color getBgColor() {
		return bgColor;
	}

	public Color getFgColor() {
		return fgColor;
	}

	public int getyOffset() {
		return yOffset;
	}

}


text:
/**
 * @requires OpenLayers/Geometry/Collection.js
 * @requires OpenLayers/Geometry/LinearRing.js
 */

/**
 * Class: OpenLayers.Geometry.Polygon
 * Polygon is a collection of Geometry.LinearRings.
 *
 * Inherits from:
 *  - <OpenLayers.Geometry.Collection>
 *  - <OpenLayers.Geometry>
 */
OpenLayers.Geometry.Polygon = OpenLayers.Class(
  OpenLayers.Geometry.Collection, {

    /**
     * Property: componentTypes
     * {Array(String)} An array of class names representing the types of
     * components that the collection can include.  A null value means the
     * component types are not restricted.
     */
    componentTypes: ["OpenLayers.Geometry.LinearRing"],

    /**
     * Constructor: OpenLayers.Geometry.Polygon
     * Constructor for a Polygon geometry.
     * The first ring (this.component[0])is the outer bounds of the polygon and
     * all subsequent rings (this.component[1-n]) are internal holes.
     *
     *
     * Parameters:
     * components - {Array(<OpenLayers.Geometry.LinearRing>)}
     */

    /**
     * APIMethod: getArea
     * Calculated by subtracting the areas of the internal holes from the
     *   area of the outer hole.
     *
     * Returns:
     * {float} The area of the geometry
     */
    getArea: function() {
        var area = 0.0;
        if ( this.components && (this.components.length > 0)) {
            area += Math.abs(this.components[0].getArea());
            for (var i=1, len=this.components.length; i<len; i++) {
                area -= Math.abs(this.components[i].getArea());
            }
        }
        return area;
    },

    /**
     * APIMethod: getGeodesicArea
     * Calculate the approximate area of the polygon were it projected onto
     *     the earth.
     *
     * Parameters:
     * projection - {<OpenLayers.Projection>} The spatial reference system
     *     for the geometry coordinates.  If not provided, Geographic/WGS84 is
     *     assumed.
     *
     * Reference:
     * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
     *     Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
     *     Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
     *
     * Returns:
     * {float} The approximate geodesic area of the polygon in square meters.
     */
    getGeodesicArea: function(projection) {
        var area = 0.0;
        if(this.components && (this.components.length > 0)) {
            area += Math.abs(this.components[0].getGeodesicArea(projection));
            for(var i=1, len=this.components.length; i<len; i++) {
                area -= Math.abs(this.components[i].getGeodesicArea(projection));
            }
        }
        return area;
    },

    /**
     * Method: containsPoint
     * Test if a point is inside a polygon.  Points on a polygon edge are
     *     considered inside.
     *
     * Parameters:
     * point - {<OpenLayers.Geometry.Point>}
     *
     * Returns:
     * {Boolean | Number} The point is inside the polygon.  Returns 1 if the
     *     point is on an edge.  Returns boolean otherwise.
     */
    containsPoint: function(point) {
        var numRings = this.components.length;
        var contained = false;
        if(numRings > 0) {
            // check exterior ring - 1 means on edge, boolean otherwise
            contained = this.components[0].containsPoint(point);
            if(contained !== 1) {
                if(contained && numRings > 1) {
                    // check interior rings
                    var hole;
                    for(var i=1; i<numRings; ++i) {
                        hole = this.components[i].containsPoint(point);
                        if(hole) {
                            if(hole === 1) {
                                // on edge
                                contained = 1;
                            } else {
                                // in hole
                                contained = false;
                            }
                            break;
                        }
                    }
                }
            }
        }
        return contained;
    },

    /**
     * APIMethod: intersects
     * Determine if the input geometry intersects this one.
     *
     * Parameters:
     * geometry - {<OpenLayers.Geometry>} Any type of geometry.
     *
     * Returns:
     * {Boolean} The input geometry intersects this one.
     */
    intersects: function(geometry) {
        var intersect = false;
        var i, len;
        if(geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
            intersect = this.containsPoint(geometry);
        } else if(geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" ||
                  geometry.CLASS_NAME == "OpenLayers.Geometry.LinearRing") {
            // check if rings/linestrings intersect
            for(i=0, len=this.components.length; i<len; ++i) {
                intersect = geometry.intersects(this.components[i]);
                if(intersect) {
                    break;
                }
            }
            if(!intersect) {
                // check if this poly contains points of the ring/linestring
                for(i=0, len=geometry.components.length; i<len; ++i) {
                    intersect = this.containsPoint(geometry.components[i]);
                    if(intersect) {
                        break;
                    }
                }
            }
        } else {
            for(i=0, len=geometry.components.length; i<len; ++ i) {
                intersect = this.intersects(geometry.components[i]);
                if(intersect) {
                    break;
                }
            }
        }
        // check case where this poly is wholly contained by another
        if(!intersect && geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon") {
            // exterior ring points will be contained in the other geometry
            var ring = this.components[0];
            for(i=0, len=ring.components.length; i<len; ++i) {
                intersect = geometry.containsPoint(ring.components[i]);
                if(intersect) {
                    break;
                }
            }
        }
        return intersect;
    },

    /**
     * APIMethod: distanceTo
     * Calculate the closest distance between two geometries (on the x-y plane).
     *
     * Parameters:
     * geometry - {<OpenLayers.Geometry>} The target geometry.
     * options - {Object} Optional properties for configuring the distance
     *     calculation.
     *
     * Valid options:
     * details - {Boolean} Return details from the distance calculation.
     *     Default is false.
     * edge - {Boolean} Calculate the distance from this geometry to the
     *     nearest edge of the target geometry.  Default is true.  If true,
     *     calling distanceTo from a geometry that is wholly contained within
     *     the target will result in a non-zero distance.  If false, whenever
     *     geometries intersect, calling distanceTo will return 0.  If false,
     *     details cannot be returned.
     *
     * Returns:
     * {Number | Object} The distance between this geometry and the target.
     *     If details is true, the return will be an object with distance,
     *     x0, y0, x1, and y1 properties.  The x0 and y0 properties represent
     *     the coordinates of the closest point on this geometry. The x1 and y1
     *     properties represent the coordinates of the closest point on the
     *     target geometry.
     */
    distanceTo: function(geometry, options) {
        var edge = !(options && options.edge === false);
        var result;
        // this is the case where we might not be looking for distance to edge
        if(!edge && this.intersects(geometry)) {
            result = 0;
        } else {
            result = OpenLayers.Geometry.Collection.prototype.distanceTo.apply(
                this, [geometry, options]
            );
        }
        return result;
    },

    CLASS_NAME: "OpenLayers.Geometry.Polygon"
});

/**
 * APIMethod: createRegularPolygon
 * Create a regular polygon around a radius. Useful for creating circles
 * and the like.
 *
 * Parameters:
 * origin - {<OpenLayers.Geometry.Point>} center of polygon.
 * radius - {Float} distance to vertex, in map units.
 * sides - {Integer} Number of sides. 20 approximates a circle.
 * rotation - {Float} original angle of rotation, in degrees.
 */
OpenLayers.Geometry.Polygon.createRegularPolygon = function(origin, radius, sides, rotation) {
    var angle = Math.PI * ((1/sides) - (1/2));
    if(rotation) {
        angle += (rotation / 180) * Math.PI;
    }
    var rotatedAngle, x, y;
    var points = [];
    for(var i=0; i<sides; ++i) {
        rotatedAngle = angle + (i * 2 * Math.PI / sides);
        x = origin.x + (radius * Math.cos(rotatedAngle));
        y = origin.y + (radius * Math.sin(rotatedAngle));
        points.push(new OpenLayers.Geometry.Point(x, y));
    }
    var ring = new OpenLayers.Geometry.LinearRing(points);
    return new OpenLayers.Geometry.Polygon([ring]);
};


text:
using System;
using NetFusion.Bootstrap.Plugins;
using System.Collections.Generic;

namespace NetFusion.Bootstrap.Container
{
    /// <summary>
    /// Interface for an implementation responsible for resolving types allowing
    /// the composite-application to be independent of runtime information such
    /// as assemblies.  This greatly simplifies unit-testing.
    /// </summary>
    public interface ITypeResolver
    {
        /// <summary>
        /// The implementation should invoke the SetPluginMeta method on the passed plugin.
        /// </summary>
        /// <param name="plugin">The plugin to have its metadata set.</param>
        void SetPluginMeta(IPlugin plugin);

        /// <summary>
        /// The implementation should check each plugin module for IEnumerable properties where the
        /// generic parameter derives from IKnownPluginType.  Each of these properties should be set
        /// to an array containing all derived concrete instances.
        /// </summary>
        /// <param name="plugin">The plugin to be composed.</param>
        /// <param name="fromPluginTypes">The list of types from which the IKnownPluginType derived
        /// instances are created.</param>
        void ComposePlugin(IPlugin plugin, IEnumerable<Type> fromPluginTypes);
    }
}


text:
#import <IDESubversion/SVNOperation.h>

@interface SVNImportOperation : SVNOperation
{
}

- (id)initWithRequest:(id)arg1;

@end


text:
const { exec: nodeExec } = require('child_process')
const clipboardy = require('clipboardy')
const { isNil, split, head, tail, dissoc, trim, identity } = require('ramda')
const execa = require('execa')
const nodeWhich = require('which')
const crossSpawn = require('cross-spawn')

/**
 * Extensions to launch processes, open files, and talk to the clipboard.
 *
 * @return {Function} A function to attach to the context.
 */
module.exports = function (plugin, command, context) {
  /**
   * Executes a commandline program asynchronously.
   *
   * @param {string} commandLine The command line to execute.
   * @param {options} options Additional child_process options for node.
   * @returns {Promise}
   */
  async function run (commandLine, options = {}) {
    const trimmer = options && options.trim ? trim : identity
    const nodeOptions = dissoc('trim', options)

    return new Promise((resolve, reject) => {
      nodeExec(commandLine, nodeOptions, (error, stdout, stderr) => {
        if (error) {
          error.stderr = stderr
          reject(error)
        }
        resolve(trimmer(stdout || ''))
      })
    })
  }

  /**
   * Executes a commandline via execa.
   *
   * @param {string} commandLine The command line to execute.
   * @param {options} options Additional child_process options for node.
   * @returns {Promise}
   */
  async function exec (commandLine, options) {
    return new Promise((resolve, reject) => {
      const args = split(' ', commandLine)
      execa(head(args), tail(args), options)
        .then(result => resolve(result.stdout))
        .catch(error => reject(error))
    })
  }

  /**
   * Uses cross-spawn to run a process.
   *
   * @param {any} commandLine The command line to execute.
   * @param {options} options Additional child_process options for node.
   * @returns {Promise} The response code.
   */
  async function spawn (commandLine, options) {
    return new Promise((resolve, reject) => {
      const args = split(' ', commandLine)
      const spawned = crossSpawn(head(args), tail(args), options)
      let result = {
        stdout: null,
        status: null,
        error: null
      }
      if (spawned.stdout) {
        spawned.stdout.on('data', data => {
          if (isNil(result.stdout)) {
            result.stdout = data
          } else {
            result.stdout += data
          }
        })
      }
      spawned.on('close', code => {
        result.status = code
        resolve(result)
      })
      spawned.on('error', err => {
        result.error = err
        resolve(result)
      })
    })
  }

  /**
   * Returns text that is on the clipboard.
   *
   * @return {string}
   */
  function readFromClipboard () {
    return clipboardy.readSync()
  }

  /**
   * Writes text to the clipboard.
   *
   * @param {string} text The text to send
   */
  function writeToClipboard (text) {
    clipboardy.writeSync(text)
  }

  /**
   * Finds the location of the path.
   *
   * @param {string} command The name of program you're looking for.
   * @return {string} The full path or null.
   */
  function which (command) {
    return nodeWhich.sync(command)
  }

  return { exec, run, spawn, readFromClipboard, writeToClipboard, which }
}


text:
import unittest

import command
import config
import thread_cert

# Test description:
#
#   This test verifies the behavior of DNS client feature where the SRP
#   server address (from SRP client auto-start feature) is used as the
#   default IPv6 address for DNS resolver config when user does not
#   explicitly set a default address
#
# Topology: two nodes
#
#   leader (SRP server & client & DNS client) --- router (SRP client & DNS client)
#

LEADER = 1
ROUTER = 2

DEFAULT_ADDRESS = 'fd00:1:2:3:4:5:6:7'

class DnsClientConfigAutoStart(thread_cert.TestCase):
    USE_MESSAGE_FACTORY = False
    SUPPORT_NCP = False

    TOPOLOGY = {
        LEADER: {
            'name': 'LEADER',
            'mode': 'rdn',
        },
        ROUTER: {
            'name': 'ROUTER',
            'mode': 'rdn',
        },
    }

    def test(self):
        leader = self.nodes[LEADER]
        router = self.nodes[ROUTER]

        # Form network.

        leader.start()
        self.simulator.go(config.LEADER_STARTUP_DELAY)
        self.assertEqual(leader.get_state(), 'leader')

        router.start()
        self.simulator.go(config.ROUTER_STARTUP_DELAY)
        self.assertEqual(router.get_state(), 'router')

        # On leader set DNS config explicitly.

        leader.dns_set_config(DEFAULT_ADDRESS)
        dns_config = leader.dns_get_config()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(DEFAULT_ADDRESS))

        # Start leader to act as SRP server.

        leader.srp_server_set_enabled(True)

        # Enable SRP client auto start on both nodes.

        leader.srp_client_enable_auto_start_mode()
        router.srp_client_enable_auto_start_mode()
        self.simulator.go(5)

        # Verify that on router the default DNS config is changed
        # to the same address being used by SRP client.

        srp_server_address = router.srp_client_get_server_address()
        self.assertEqual(leader.srp_client_get_server_address(), srp_server_address)

        dns_config = router.dns_get_config()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(srp_server_address))

        # Verify that on leader the default DNS config remains
        # as before (the address explicitly set earlier).

        dns_config = leader.dns_get_config()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(DEFAULT_ADDRESS))

        # On leader clear DNS config (the explicitly set address)
        # and verify that it adopts the SRP server address.

        leader.dns_set_config("::")
        dns_config = leader.dns_get_config()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(srp_server_address))

        # On leader set DNS config explicitly again.

        leader.dns_set_config(DEFAULT_ADDRESS)
        dns_config = leader.dns_get_config()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(DEFAULT_ADDRESS))

        # Stop SRP server on leader and start it on router.

        leader.srp_server_set_enabled(False)
        router.srp_server_set_enabled(True)
        self.simulator.go(5)

        # Verify that SRP client on router switched to new SRP server.

        self.assertNotEqual(srp_server_address, router.srp_client_get_server_address())
        self.assertEqual(router.srp_client_get_server_address(), leader.srp_client_get_server_address())

        # Verify that config on router gets changed while on leader
        # it remains unchanged.

        dns_config = router.dns_get_config()
        srp_server_address = router.srp_client_get_server_address()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(srp_server_address))

        dns_config = leader.dns_get_config()
        self.assertEqual(dns_config['Server'], '[{}]:53'.format(DEFAULT_ADDRESS))

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


text:
module Iot
  module DeviceName

    def toggle_local_name
      yaml = load_yaml_body
      if yaml.empty?
        puts "No Yaml file"
        return
      end

      deviceinfo = yaml["deviceinfo"]
      deviceinfo["adpacket"]["localname"] = 1 - deviceinfo["adpacket"]["localname"].to_i

      if deviceinfo["adpacket"]["localname"] > 0
        puts "Short name is selected for advertising packet"
      else
        puts "Complete name is selected for advertising packet"
      end

      refresh_yaml_body yaml
    end

    def change_complete_name device_name
      change_name("name", device_name)
    end

    def change_short_name device_name
      change_name("shortname", device_name)
    end

    def change_name(key, device_name)
      yaml = load_yaml_body
      if yaml.empty?
        puts "No Yaml file"
        return
      end

      deviceinfo = yaml["deviceinfo"]
      deviceinfo[key] = device_name

      refresh_yaml_body yaml
    end

  end
end


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;

namespace Bit.BlazorUI;

public partial class BitLink
{
    [Inject] public IJSRuntime JSRuntime { get; set; } = default!;

    /// <summary>
    /// URL the link points to
    /// </summary>
    [Parameter] public string? Href { get; set; } = string.Empty;

    /// <summary>
    /// If Href provided, specifies how to open the link
    /// </summary>
    [Parameter] public string? Target { get; set; }

    /// <summary>
    /// The content of link, can be any custom tag or a text
    /// </summary>
    [Parameter] public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Whether the link is styled with an underline or not. Should be used when the link is placed alongside other text content
    /// </summary>
    [Parameter] public bool HasUnderline { get; set; } = false;

    /// <summary>
    /// Callback for when the link clicked
    /// </summary>
    [Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; }

    protected override string RootElementClass => "bit-lnk";

    protected virtual async Task HandleClick(MouseEventArgs e)
    {
        if (IsEnabled)
        {
            await OnClick.InvokeAsync(e);
        }
    }

    private async Task ScrollIntoView()
    {
        await JSRuntime.ScrollElementIntoView(Href![1..]);
    }
}


text:
class PhotoBare < ActiveRecord::Base
  acts_as_fleximage do
    image_directory 'public/uploads'
    validates_image_size '2x2'
    require_image true
  end
end


text:
import React from 'react'

/*
*  column of each Row
* */

class Column extends React.Component {

    constructor(props) {
        super(props)
    }

    componentDidMount() {}

    render() {

        const self = this
        const props = this.props
        let field  = props.field
        let row  = props.row

        return (
            <td>
                {row[field]}
            </td>
        )
    }

}

Column.propTypes = {
    field: React.PropTypes.string.isRequired,
    row: React.PropTypes.object.isRequired,
    dbname: React.PropTypes.string.isRequired,
    tablename: React.PropTypes.string.isRequired,
};

export default Column


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:focusableInTouchMode="true"
    android:minHeight="@dimen/large_height">

    <ImageView
      android:id="@+id/bookmarkButtonImage"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="@dimen/standard_gap"
      android:tint="?attr/rowButtonColor"
      app:srcCompat="@drawable/ic_round_star_border_24px" />

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/icon"
        android:layout_width="@dimen/dimen_40"
        android:layout_height="@dimen/dimen_40"
        android:layout_marginStart="@dimen/standard_gap"
        android:layout_marginTop="@dimen/standard_gap"
        android:layout_alignStart="@id/bookmarkButtonImage"
        android:scaleType="centerCrop"
        tools:src="@drawable/empty_photo"
        />

    <TextView
        android:id="@+id/distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="@dimen/standard_gap"
        android:layout_marginRight="@dimen/standard_gap"
        android:layout_marginTop="@dimen/standard_gap"
        tools:text="900m"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        />

    <ImageView
        android:id="@+id/toggleArrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="@dimen/standard_gap"
        android:layout_marginTop="@dimen/large_gap"

        />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/distance"
        android:layout_marginLeft="@dimen/standard_gap"
        android:layout_marginStart="@dimen/standard_gap"
        android:layout_toEndOf="@id/icon"
        android:layout_toLeftOf="@id/distance"
        android:layout_toRightOf="@id/icon"
        android:layout_toStartOf="@id/distance"
        android:ellipsize="end"
        android:maxLines="2"
        tools:text="St. Paul's School"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        />

    <TextView
        android:id="@+id/tvDesc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@id/distance"
        android:layout_alignLeft="@id/tvName"
        android:layout_alignRight="@id/distance"
        android:layout_alignStart="@id/tvName"
        android:layout_below="@id/tvName"
        android:layout_marginBottom="@dimen/standard_gap"
        android:ellipsize="end"
        android:maxLines="4"
        tools:text="school"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        />

    <include android:id="@+id/nearby_button_layout" layout="@layout/nearby_row_button" />
</RelativeLayout>