file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
models.py | from __future__ import unicode_literals
from csacompendium.utils.abstractmodels import (
AuthUserDetail,
CreateUpdateTime,
)
from csacompendium.locations.models import Location
from csacompendium.utils.createslug import create_slug
from django.contrib.contenttypes.models import ContentType
from django.db impor... | (self):
"""
Get related location object/record
:return: Query result from the location model
:rtye: object/record
"""
instance = self
qs = Location.objects.filter_by_instance(instance)
return qs
@receiver(pre_save, sender=Country)
def pre_save_country_rec... | locations | identifier_name |
models.py | from __future__ import unicode_literals
from csacompendium.utils.abstractmodels import (
AuthUserDetail,
CreateUpdateTime,
)
from csacompendium.locations.models import Location
from csacompendium.utils.createslug import create_slug
from django.contrib.contenttypes.models import ContentType
from django.db impor... | :param args: Any other argument
:param kwargs: Keyword arguments
:return: None
:rtype: None
"""
if not instance.slug:
instance.slug = create_slug(instance, Country, instance.country_name) | random_line_split | |
models.py | from __future__ import unicode_literals
from csacompendium.utils.abstractmodels import (
AuthUserDetail,
CreateUpdateTime,
)
from csacompendium.locations.models import Location
from csacompendium.utils.createslug import create_slug
from django.contrib.contenttypes.models import ContentType
from django.db impor... |
@property
def locations(self):
"""
Get related location object/record
:return: Query result from the location model
:rtye: object/record
"""
instance = self
qs = Location.objects.filter_by_instance(instance)
return qs
@receiver(pre_save, sender=... | ordering = ['-time_created', '-last_update']
verbose_name_plural = 'Countries' | identifier_body |
models.py | from __future__ import unicode_literals
from csacompendium.utils.abstractmodels import (
AuthUserDetail,
CreateUpdateTime,
)
from csacompendium.locations.models import Location
from csacompendium.utils.createslug import create_slug
from django.contrib.contenttypes.models import ContentType
from django.db impor... | instance.slug = create_slug(instance, Country, instance.country_name) | conditional_block | |
PageNotReady.tsx | import { makeStyles } from "@material-ui/core/styles"
import Grid from "@material-ui/core/Grid"
import Button from "@material-ui/core/Button"
import FontAwesome from "react-fontawesome"
import Image from "next/image"
const useStyles = makeStyles({
container: {
backgroundColor: "#eff8fb",
textAlign: "center",... | textDecoration: "none",
},
})
/**
* Fallback component for non-existent routes -- "Page Not Ready"/"Under Construction"
*/
const PageNotReady = () => {
const classes = useStyles()
return (
<Grid container className={classes.mainGrid} justifyContent="center">
<Grid item xs={10} md={8}>
<... | paddingRight: "10px",
},
routerLink: {
color: "#428bca", | random_line_split |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... |
if perl.cfg("useshrplib") == "true" {
println!("cargo:rustc-cfg=perl_useshrplib");
// Make sure ld links to libperl that matches current perl interpreter, instead of whatever
// is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded
// installation... | {
println!("cargo:rustc-cfg=perl_multiplicity");
} | conditional_block |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... | (&self) -> PathBuf {
let archlib = self.cfg("archlibexp");
Path::new(&archlib).join("CORE")
}
}
fn build(perl: &Perl) {
let mut cc = cc::Build::new();
let ccflags = std::env::var("LIBPERL_CCFLAGS").unwrap_or_else(|_e| { perl.cfg("ccflags") });
for flag in ccflags.split_whitespace() {
... | path_core | identifier_name |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... | // is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded
// installation path for default perl so this ought to be enough in most cases.
println!("cargo:rustc-link-search=native={}", perl.path_core().to_str().unwrap());
}
} | random_line_split | |
build.rs | extern crate cc;
use std::path::{ PathBuf, Path };
use std::process::Command;
struct Perl {
bin: String,
}
impl Perl {
fn new() -> Perl {
Perl {
bin: std::env::var("PERL").unwrap_or("perl".to_owned()),
}
}
fn cfg(&self, key: &str) -> String {
let out = Command::ne... | {
let perl = Perl::new();
perl.run("build/regen.pl");
build(&perl);
if perl.cfg("usemultiplicity") == "define" {
println!("cargo:rustc-cfg=perl_multiplicity");
}
if perl.cfg("useshrplib") == "true" {
println!("cargo:rustc-cfg=perl_useshrplib");
// Make sure ld links ... | identifier_body | |
util.py | (n):
return 11000 + n + os.getpid()%999
def rpc_port(n):
return 12000 + n + os.getpid()%999
def check_json_precision():
"""Make sure json library being used does not lose precision converting EKW values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
i... | p2p_port | identifier_name | |
util.py | oshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def sync_blocks(rpc_connections):
"""
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc... |
def stop_node(node, i):
node.stop()
ekwicoind_processes[i].wait()
del ekwicoind_processes[i]
def stop_nodes(nodes):
for i in range(len(nodes)):
nodes[i].stop()
del nodes[:] # Emptying array closes connections as a side effect
def wait_ekwicoinds():
# Wait for all ekwicoinds to cleanl... | return os.path.join(dir, "node"+str(n_node), "regtest", "debug.log") | identifier_body |
util.py | satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def sync_blocks(rpc_connections):
"""
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in... | """
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
def gather_inputs(from_node, amount_needed):
"""
Return a random se... | """
Return index to output of txid with value amount
Raises exception if there is none. | random_line_split |
util.py | oshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def sync_blocks(rpc_connections):
"""
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc... |
def find_output(node, txid, amount):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise Runtime... | time.sleep(0.1) | conditional_block |
framework_lib.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# 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 a... | from tensorflow.python.framework.ops import get_collection
from tensorflow.python.framework.ops import get_collection_ref
from tensorflow.python.framework.ops import convert_to_tensor
from tensorflow.python.framework.ops import convert_to_tensor_or_indexed_slices
from tensorflow.python.framework.random_seed import get_... | from tensorflow.python.framework.ops import GraphKeys
from tensorflow.python.framework.ops import add_to_collection | random_line_split |
queue_manager.py | request in sorted(response_subjects.items()):
responses = []
for _, serialized, _ in response_data.get(response_urn, []):
responses.append(rdfvalue.GrrMessage(serialized))
yield (request, sorted(responses, key=lambda msg: msg.response_id))
# Indicate to the caller that there are more me... | """Same as GetNotificationsByPriority but for all shards.
Used by worker_test to cover all shards with a single worker.
Args:
queue: usually rdfvalue.RDFURN("aff4:/W")
Returns:
dict of notifications objects keyed by priority.
"""
output_dict = {}
for queue_shard in self.GetAllNotif... | identifier_body | |
queue_manager.py | already deleted task.
Args:
queue: A queue to clear.
tasks: A list of tasks to remove. Tasks may be Task() instances
or integers representing the task_id.
"""
if queue:
predicates = []
for task in tasks:
try:
task_id = task.task_id
except Attribute... | all_tasks.sort(key=lambda task: task.priority, reverse=True)
return all_tasks[:limit] | random_line_split | |
queue_manager.py | yield (rdfvalue.RequestState(serialized),
rdfvalue.GrrMessage(status[request_id]))
def FetchCompletedResponses(self, session_id, timestamp=None, limit=10000):
"""Fetch only completed requests and responses up to a limit."""
response_subjects = {}
if timestamp is None:
timest... | stats.STATS.SetGaugeValue("notification_queue_count",
len(output_dict[priority]),
fields=[queue.Basename(), str(priority)])
random.shuffle(output_dict[priority]) | conditional_block | |
queue_manager.py | % request_id)
def DeQueueClientRequest(self, client_id, task_id):
"""Remove the message from the client queue that this request forms."""
# Check this request was actually bound for a client.
if client_id:
client_id = rdfvalue.ClientURN(client_id)
self.client_messages_to_delete.setdefault(c... | (self, msg, timestamp=None):
if timestamp is None:
timestamp = self.frozen_timestamp
self.new_client_messages.append((msg, timestamp))
def QueueNotification(self, notification=None, timestamp=None, **kw):
"""Queues a notification for a flow."""
if notification is None:
notification = rd... | QueueClientMessage | identifier_name |
component.ts | import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency-decorators';
import fetch from 'fetch';
import { NotificationsService } from '@frontile/notifications';
interface Args {}
export default ... | () {
let response = await fetch('/register', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
inviteCode: this.inviteCode,
email: this.email,
password: this.password,
}),
}... | register | identifier_name |
component.ts | import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency-decorators';
import fetch from 'fetch';
import { NotificationsService } from '@frontile/notifications';
interface Args {}
export default ... |
return result;
} catch (e) {
throw new Error('Not ok');
}
}
}
| {
this.notifications.add(result.errors.join('\n'), {
appearance: 'error',
});
} | conditional_block |
component.ts | import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency-decorators';
import fetch from 'fetch'; |
interface Args {}
export default class RegisterForm extends Component<Args> {
@service notifications!: NotificationsService;
@tracked email?: string;
@tracked password?: string;
@tracked inviteCode?: string;
@task async register() {
let response = await fetch('/register', {
method: 'post',
... | import { NotificationsService } from '@frontile/notifications'; | random_line_split |
CaseInsensitiveTerminal.js | 'use strict';
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
const Failure = require('./Failure');
const TerminalNode = require('./nodes').TerminalNode;
const assert = require('./common').assert;
const {PExpr, ... |
}
getArity() {
return 1;
}
substituteParams(actuals) {
return new CaseInsensitiveTerminal(this.obj.substituteParams(actuals));
}
toDisplayString() {
return this.obj.toDisplayString() + ' (case-insensitive)';
}
toFailure(grammar) {
return new Failure(
this,
this.obj.t... | {
state.pushBinding(new TerminalNode(state.grammar, matchStr), origPos);
return true;
} | conditional_block |
CaseInsensitiveTerminal.js | 'use strict';
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
const Failure = require('./Failure');
const TerminalNode = require('./nodes').TerminalNode;
const assert = require('./common').assert;
const {PExpr, ... | (grammar, memo) {
return this.obj._isNullable(grammar, memo);
}
}
module.exports = CaseInsensitiveTerminal;
| _isNullable | identifier_name |
CaseInsensitiveTerminal.js | 'use strict';
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
const Failure = require('./Failure');
const TerminalNode = require('./nodes').TerminalNode;
const assert = require('./common').assert;
const {PExpr, ... |
_isNullable(grammar, memo) {
return this.obj._isNullable(grammar, memo);
}
}
module.exports = CaseInsensitiveTerminal;
| {
return new Failure(
this,
this.obj.toFailure(grammar) + ' (case-insensitive)',
'description'
);
} | identifier_body |
CaseInsensitiveTerminal.js | 'use strict';
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
const Failure = require('./Failure');
const TerminalNode = require('./nodes').TerminalNode;
const assert = require('./common').assert;
const {PExpr, ... | state.pushBinding(new TerminalNode(state.grammar, matchStr), origPos);
return true;
}
}
getArity() {
return 1;
}
substituteParams(actuals) {
return new CaseInsensitiveTerminal(this.obj.substituteParams(actuals));
}
toDisplayString() {
return this.obj.toDisplayString() + ' (cas... | state.processFailure(origPos, this);
return false;
} else { | random_line_split |
request_redraw_threaded.rs | use std::{thread, time};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn | () {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("A fantastic window!")
.build(&event_loop)
.unwrap();
thread::spawn(move || loop {
thread::sleep(time::Duration::from_secs(1));
window.requ... | main | identifier_name |
request_redraw_threaded.rs | use std::{thread, time};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn main() {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.wi... | }
});
} | _ => (), | random_line_split |
request_redraw_threaded.rs | use std::{thread, time};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn main() | Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
_ => (),
},
Event::RedrawRequested(_) => {
println!("\nredrawing!\n");
}
_ => (),
}
... | {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("A fantastic window!")
.build(&event_loop)
.unwrap();
thread::spawn(move || loop {
thread::sleep(time::Duration::from_secs(1));
window.request... | identifier_body |
tea-ass.ts | import { Component, Input } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { Http, Headers } from '@angular/http';
/*
Generated class for the TeaAss page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigat... | {
SData: any;
items:any;
hostname:string;
userdata: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http, public alertCtrl: AlertController) {
this.SData = navParams.data;
this.userdata = JSON.parse(localStorage.getItem("userdata"));
this.http = http;
... | TeaAssPage | identifier_name |
tea-ass.ts | import { Component, Input } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { Http, Headers } from '@angular/http';
/*
Generated class for the TeaAss page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigat... | let _6 = this._6;
let _7 = this._7;
let _8 = this._8;
let _9 = this._9;
let _10 = this._10;
let _11 = this._11;
let _12 = this._12;
let _13 = this._13;
let _14 = this._14;
let _15 = this._15;
let _16 = this._16;
let _17 = this._17;
let _18 = this._18;
let _19 = th... | let _4 = this._4;
let _5 = this._5; | random_line_split |
simulationcraft.spec.ts | import { test, expect } from "@jest/globals";
import { IoC } from "../ioc";
import { assertDefined, assertIs } from "../tests/helpers";
test("parse decimal number", () => {
// Arrange
const code = `deathknight="test"
spec=blood
level=120
actions=/potion,if=buff.test.stack>=0.1`;
const ioc = new IoC();
... | // const result = OvaleSimulationCraft.Emit(profile);
// // Assert
// t.regex(result, /if not target\.DebuffPresent\(havoc_debuff\) and Talent\(grimoire_of_supremacy_talent\) Spell\(chaos_bolt\)/);
// t.regex(result, /if not { not target\.DebuffPresent\(havoc_debuff\) and Talent\(grimoire_of_supremacy_... | // t.not(profile, undefined); | random_line_split |
main.rs | extern crate hyper;
extern crate iron;
extern crate router;
extern crate handlebars_iron as hbsi;
extern crate rustc_serialize;
extern crate persistent;
extern crate urlencoded;
extern crate traitobject;
#[macro_use]
extern crate mime;
extern crate mysql;
extern crate crypto;
extern crate rand;
extern crate iron_login;... | mount.mount("/", chain);
mount.mount("/static/", Static::new(Path::new("static")));
let listen = config.get("listen").as_str().unwrap();
iron::Iron::new(mount).http(listen).unwrap();
}
| {
// init logging
log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
let mut chain = Chain::new(route::gen_router());
let config = Config::new();
chain.link_before(Read::<Config>::one(config.clone()));
let my_pool = MyPool::new(&config);
chain.link_before(Read::<MyPool>::one(my... | identifier_body |
main.rs | extern crate hyper;
extern crate iron;
extern crate router;
extern crate handlebars_iron as hbsi;
extern crate rustc_serialize;
extern crate persistent;
extern crate urlencoded;
extern crate traitobject;
#[macro_use]
extern crate mime;
extern crate mysql;
extern crate crypto;
extern crate rand;
extern crate iron_login;... | () {
// init logging
log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
let mut chain = Chain::new(route::gen_router());
let config = Config::new();
chain.link_before(Read::<Config>::one(config.clone()));
let my_pool = MyPool::new(&config);
chain.link_before(Read::<MyPool>::one... | main | identifier_name |
main.rs | extern crate hyper;
extern crate iron;
extern crate router;
extern crate handlebars_iron as hbsi;
extern crate rustc_serialize;
extern crate persistent;
extern crate urlencoded;
extern crate traitobject;
#[macro_use]
extern crate mime;
extern crate mysql;
extern crate crypto;
extern crate rand;
extern crate iron_login;... | extern crate pulldown_cmark;
extern crate regex;
extern crate ammonia;
extern crate rss;
extern crate cookie;
extern crate oven;
extern crate url;
extern crate mount;
extern crate staticfile;
extern crate form_checker;
mod base;
mod handlers;
mod route;
use iron::Chain;
use hbsi::{HandlebarsEngine, DirectorySource};
... | extern crate log4rs;
extern crate time;
extern crate chrono;
#[macro_use]
extern crate lazy_static; | random_line_split |
app.ts | // Implement override method that can retrieve day, month(as number as text format) and year and return Date object
// Override this method for retrieve array of such parameters and retrieve array with dates.
function overrideFunction(day: number, month: number | string, year: number): Date;
function overrideFunction(... | // Implements valueOf method. Retrieve different type of objects returns true/false.
function customValueOf(obj: any): boolean {
return !!obj;
} | return obj.toString();
}
| random_line_split |
app.ts | // Implement override method that can retrieve day, month(as number as text format) and year and return Date object
// Override this method for retrieve array of such parameters and retrieve array with dates.
function overrideFunction(day: number, month: number | string, year: number): Date;
function overrideFunction(... |
return createDate(args[0], args[1], args[2]);
}
overrideFunction(25, 7, 1994);
overrideFunction(25, 'August', 1994);
overrideFunction([[25, 7, 1994], [25, 'August', 1994]]);
// Implements to string method. Retrieve different type of object returns string
function customToString(obj: any): string {
return obj.t... | {
return args.map(dateArgs => createDate(dateArgs[0], dateArgs[1], dateArgs[2]));
} | conditional_block |
app.ts | // Implement override method that can retrieve day, month(as number as text format) and year and return Date object
// Override this method for retrieve array of such parameters and retrieve array with dates.
function overrideFunction(day: number, month: number | string, year: number): Date;
function overrideFunction(... | (obj: any): string {
return obj.toString();
}
// Implements valueOf method. Retrieve different type of objects returns true/false.
function customValueOf(obj: any): boolean {
return !!obj;
} | customToString | identifier_name |
app.ts | // Implement override method that can retrieve day, month(as number as text format) and year and return Date object
// Override this method for retrieve array of such parameters and retrieve array with dates.
function overrideFunction(day: number, month: number | string, year: number): Date;
function overrideFunction(... | {
return !!obj;
} | identifier_body | |
config.js | var _ = require('lodash');
var localConfig = {};
try {
localConfig = require('./config.local');
} catch (e) {
console.log(e.code === 'MODULE_NOT_FOUND');
if (e.code !== 'MODULE_NOT_FOUND' || e.message.indexOf('config.local') < 0) |
}
var path = require('path');
var defaultConfig = {
dataSources: [
{
type: 'local',
base: 'tmp/',
endpoints: ['nodes.json', 'graph.json'],
interval: 3000
}
// {
// type: 'remote',
// base: 'http://example.com/ffmap/',
// e... | {
//config.local module is broken, rethrow the exception
throw e;
} | conditional_block |
config.js | var _ = require('lodash');
var localConfig = {};
try {
localConfig = require('./config.local');
} catch (e) {
console.log(e.code === 'MODULE_NOT_FOUND');
if (e.code !== 'MODULE_NOT_FOUND' || e.message.indexOf('config.local') < 0) {
//config.local module is broken, rethrow the exception
throw... | db: 'ffmap'
},
port: 8000
};
module.exports = _.defaults({
defaults: defaultConfig
}, localConfig, defaultConfig); | host: 'rethinkdb',
port: '28015', | random_line_split |
client_builder.py | import os
import importlib
import logging
from dataclasses import dataclass
import sys
from typing import Any, Dict, Optional, Tuple
from ray.ray_constants import RAY_ADDRESS_ENVIRONMENT_VARIABLE
from ray.job_config import JobConfig
import ray.util.client_connect
logger = logging.getLogger(__name__)
@dataclass
cla... | (self) -> "ClientContext":
return self
def __exit__(self, *exc) -> None:
self.disconnect()
def disconnect(self) -> None:
"""
Disconnect Ray. This either disconnects from the remote Client Server
or shuts the current driver down.
"""
if ray.util.client.ra... | __enter__ | identifier_name |
client_builder.py | import os
import importlib
import logging
from dataclasses import dataclass
import sys
from typing import Any, Dict, Optional, Tuple
from ray.ray_constants import RAY_ADDRESS_ENVIRONMENT_VARIABLE
from ray.job_config import JobConfig
import ray.util.client_connect
logger = logging.getLogger(__name__)
@dataclass
cla... | * ``"IP:Port"``: Connects to a Ray Client Server at the given address.
* ``"module://inner_address"``: load module.ClientBuilder & pass
inner_address
"""
env_address = os.environ.get(RAY_ADDRESS_ENVIRONMENT_VARIABLE)
if env_address and address is None:
logger.debug(
... |
* None: Connects to or creates a local cluster and connects to it.
* ``"local"``: Creates a new cluster locally and connects to it. | random_line_split |
client_builder.py | import os
import importlib
import logging
from dataclasses import dataclass
import sys
from typing import Any, Dict, Optional, Tuple
from ray.ray_constants import RAY_ADDRESS_ENVIRONMENT_VARIABLE
from ray.job_config import JobConfig
import ray.util.client_connect
logger = logging.getLogger(__name__)
@dataclass
cla... |
def disconnect(self) -> None:
"""
Disconnect Ray. This either disconnects from the remote Client Server
or shuts the current driver down.
"""
if ray.util.client.ray.is_connected():
# This is only a client connected to a server.
ray.util.client_connec... | self.disconnect() | identifier_body |
client_builder.py | import os
import importlib
import logging
from dataclasses import dataclass
import sys
from typing import Any, Dict, Optional, Tuple
from ray.ray_constants import RAY_ADDRESS_ENVIRONMENT_VARIABLE
from ray.job_config import JobConfig
import ray.util.client_connect
logger = logging.getLogger(__name__)
@dataclass
cla... |
else:
# This is only a driver connected to an existing cluster.
ray.shutdown()
class ClientBuilder:
"""
Builder for a Ray Client connection. This class can be subclassed by
custom builder classes to modify connection behavior to include additional
features or altered s... | logger.debug(
"The current Ray Cluster is scoped to this process. "
"Disconnecting is not possible as it will shutdown the "
"cluster.") | conditional_block |
sortable-scroll.js |
/**
* Plugin for sortable to handle scrolling lists.
* @module sortable
* @submodule sortable-scroll
*/
/**
* Plugin for sortable to handle scrolling lists.
* @class SortScroll
* @extends Base
* @constructor
* @namespace Plugin
*/
var SortScroll = function... |
});
}
}, {
ATTRS: {
host: {
value: ''
}
},
/**
* @property NAME
* @default SortScroll
* @readonly
* @protected
* @static
* @description The name of the class.
* @type {String}... | {
e.drag.nodescroll.set('parentScroll', Y.one(this.get('container')));
} | conditional_block |
sortable-scroll.js | /**
* Plugin for sortable to handle scrolling lists.
* @module sortable
* @submodule sortable-scroll
*/
/**
* Plugin for sortable to handle scrolling lists.
* @class SortScroll
* @extends Base
* @constructor
* @namespace Plugin
*/
var SortScroll = function() {
... | ATTRS: {
host: {
value: ''
}
},
/**
* @property NAME
* @default SortScroll
* @readonly
* @protected
* @static
* @description The name of the class.
* @type {String}
*/
NAME: 'SortScrol... | random_line_split | |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... |
}
*self.parameters.borrow_mut() = parameters.clone();
}
}
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> Non... | {
array.update(¶meters.sitting_to_standing_transform);
} | conditional_block |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... | (&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array {
array.update(¶meters.sitting_to_standing_transform);
}
... | update | identifier_name |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... | pub struct VRStageParameters {
reflector_: Reflector,
#[ignore_malloc_size_of = "Defined in rust-webvr"]
parameters: DomRefCell<WebVRStageParameters>,
transform: Heap<*mut JSObject>,
}
unsafe_no_jsmanaged_fields!(WebVRStageParameters);
impl VRStageParameters {
fn new_inherited(parameters: WebVRSta... | #[dom_struct] | random_line_split |
vrstageparameters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding... | }
#[allow(unsafe_code)]
pub fn update(&self, parameters: &WebVRStageParameters) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let array: Float32Array = self.transform.get());
if let Ok(mut array) = array {
array.update(¶meter... | {
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>());
unsafe {
let _ = Float32Array::create(
cx,
CreateWith::Slice(¶meters.sitting_to_standing_transform),
array.handle_mut(),
);
... | identifier_body |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... | let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return true;
}
SkipResult::End => {
return false;
}
SkipResult::OverStep ... | } | random_line_split |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... | (&mut self) -> bool {
let (left, right) = (&mut self.left, &mut self.right);
if !left.advance() {
return false;
}
let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return ... | advance | identifier_name |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... |
SkipResult::End => {
return false;
}
SkipResult::OverStep => {
candidate = left.doc();
}
}
}
}
fn doc(&self) -> DocId {
self.left.doc()
}
fn size_hint(&self) -> u32 {
... | {
return true;
} | conditional_block |
intersection_two.rs | use docset::DocSet;
use query::Scorer;
use DocId;
use Score;
use SkipResult;
/// Creates a `DocSet` that iterator through the intersection of two `DocSet`s.
pub struct IntersectionTwoTerms<TDocSet> {
left: TDocSet,
right: TDocSet
}
impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> {
pub fn new(left: TD... | return true;
}
SkipResult::End => {
return false;
}
SkipResult::OverStep => {
candidate = left.doc();
}
}
}
}
fn doc(&self) -> DocId {
self.le... | {
let (left, right) = (&mut self.left, &mut self.right);
if !left.advance() {
return false;
}
let mut candidate = left.doc();
loop {
match right.skip_next(candidate) {
SkipResult::Reached => {
return true;
... | identifier_body |
beanstalkc.py | KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__version__ = '0.4.0'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 11300
DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120
DEFAULT_TUBE_NAME = 'default'
class BeanstalkcException(Excepti... |
try:
return self._interact_job(command,
['RESERVED'],
['DEADLINE_SOON', 'TIMED_OUT'])
except CommandFailed:
exc = sys.exc_info()[1]
_, status, results = exc.args
if status == 'TIM... | command = 'reserve\r\n' | conditional_block |
beanstalkc.py | ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__version__ = '0.4.0'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 11300
DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120
DEFAULT_TUBE_NAME = 'default'
class BeanstalkcException(Exc... | def use(self, name):
"""Use a given tube."""
return self._interact_value('use %s\r\n' % name, ['USING'])
def watching(self):
"""Return a list of all tubes being watched."""
return self._interact_yaml('list-tubes-watched\r\n', ['OK'])
def watch(self, name):
"""Watch ... | random_line_split | |
beanstalkc.py | ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__version__ = '0.4.0'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 11300
DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120
DEFAULT_TUBE_NAME = 'default'
class BeanstalkcException(Exc... |
def stats(self):
"""Return a dict of beanstalkd statistics."""
return self._interact_yaml('stats\r\n', ['OK'])
def stats_tube(self, name):
"""Return a dict of stats about a given tube."""
return self._interact_yaml('stats-tube %s\r\n' % name,
... | """Stop watching a given tube."""
try:
return int(self._interact_value('ignore %s\r\n' % name,
['WATCHING'],
['NOT_IGNORED']))
except CommandFailed:
# Tried to ignore the only tube in the watc... | identifier_body |
beanstalkc.py | KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__version__ = '0.4.0'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 11300
DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120
DEFAULT_TUBE_NAME = 'default'
class BeanstalkcException(Excepti... | (BeanstalkcException): pass
class CommandFailed(BeanstalkcException): pass
class DeadlineSoon(BeanstalkcException): pass
class SocketError(BeanstalkcException):
@staticmethod
def wrap(wrapped_function, *args, **kwargs):
try:
return wrapped_function(*args, **kwargs)
except socket.err... | UnexpectedResponse | identifier_name |
direct.py | # Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
class SSHClientFactory(protocol.ClientFactory):
def __init__(self, d, o... |
d, self.factory.d = self.factory.d, None
d.errback(error.ConchError(desc, code))
def sendDisconnect(self, code, reason):
if self.factory.d is None:
return
d, self.factory.d = self.factory.d, None
transport.SSHClientTransport.sendDisconnect(self, code, reason)
... | return | conditional_block |
direct.py | # Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
class SSHClientFactory(protocol.ClientFactory):
def __init__(self, d, o... |
def clientConnectionFailed(self, connector, reason):
if self.d is None:
return
d, self.d = self.d, None
d.errback(reason)
def buildProtocol(self, addr):
trans = SSHClientTransport(self)
if self.options['ciphers']:
trans.supportedCiphers = self... | if self.options['reconnect']:
connector.connect() | identifier_body |
direct.py | # Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
class SSHClientFactory(protocol.ClientFactory):
def __init__(self, d, o... |
def connect(host, port, options, verifyHostKey, userAuthObject):
d = defer.Deferred()
factory = SSHClientFactory(d, options, verifyHostKey, userAuthObject)
reactor.connectTCP(host, port, factory)
return d | random_line_split | |
direct.py | # Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
class SSHClientFactory(protocol.ClientFactory):
def __init__(self, d, o... | (self):
self.requestService(self.factory.userAuthObject)
def connect(host, port, options, verifyHostKey, userAuthObject):
d = defer.Deferred()
factory = SSHClientFactory(d, options, verifyHostKey, userAuthObject)
reactor.connectTCP(host, port, factory)
return d
| connectionSecure | identifier_name |
app.component.spec.ts | import { LayoutModule } from '@angular/cdk/layout';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
i... | MatSidenavModule,
MatToolbarModule,
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
... | MatListModule, | random_line_split |
ua_optical_verifier_device.ts | // ----- this file has been automatically generated - do not edit
import { UAMethod } from "node-opcua-address-space-base"
import { DataType } from "node-opcua-variant"
import { DTArgument } from "node-opcua-nodeset-ua/source/dt_argument"
import { UAOpticalReaderDevice, UAOpticalReaderDevice_Base } from "./ua_optical_r... | */
export interface UAOpticalVerifierDevice_Base extends UAOpticalReaderDevice_Base {
scan?: UAMethod;
}
export interface UAOpticalVerifierDevice extends Omit<UAOpticalReaderDevice, "scan">, UAOpticalVerifierDevice_Base {
} | * |isAbstract |false | | random_line_split |
avi_role.py | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... | # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: avi_role
a... | # Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# | random_line_split |
avi_role.py | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... | set([]))
if __name__ == '__main__':
main()
| argument_specs = dict(
state=dict(default='present',
choices=['absent', 'present']),
avi_api_update_method=dict(default='put',
choices=['put', 'patch']),
avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
name=dict(type='str... | identifier_body |
avi_role.py | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... | ():
argument_specs = dict(
state=dict(default='present',
choices=['absent', 'present']),
avi_api_update_method=dict(default='put',
choices=['put', 'patch']),
avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
name=dict(t... | main | identifier_name |
avi_role.py | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... |
return avi_ansible_api(module, 'role',
set([]))
if __name__ == '__main__':
main()
| return module.fail_json(msg=(
'Avi python API SDK (avisdk>=17.1) is not installed. '
'For more details visit https://github.com/avinetworks/sdk.')) | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// Make |cargo bench| work.
#![cfg_attr(feature = "bench", feature(test))]
#[macro_use]
extern crate bitflags;
#... | extern crate smallvec;
extern crate to_shmem;
#[macro_use]
extern crate to_shmem_derive;
pub mod attr;
pub mod bloom;
mod builder;
pub mod context;
pub mod matching;
mod nth_index_cache;
pub mod parser;
pub mod sink;
mod tree;
pub mod visitor;
pub use crate::nth_index_cache::NthIndexCache;
pub use crate::parser::{Par... | extern crate phf;
extern crate precomputed_hash;
extern crate servo_arc; | random_line_split |
actor.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... |
/// Find an actor by registered name
pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T {
let actor = self.actors.get_mut(name).unwrap();
actor.actor_as_any_mut().downcast_mut::<T>().unwrap()
}
/// Attempt to process a message as directed by its `to` property. If the ac... | /// Find an actor by registered name
pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T {
let actor = self.actors.get(name).unwrap();
actor.actor_as_any().downcast_ref::<T>().unwrap()
} | random_line_split |
actor.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... | {
actors: HashMap<String, Box<Actor + Send>>,
new_actors: RefCell<Vec<Box<Actor + Send>>>,
old_actors: RefCell<Vec<String>>,
script_actors: RefCell<HashMap<String, String>>,
shareable: Option<Arc<Mutex<ActorRegistry>>>,
next: Cell<u32>,
start_stamp: PreciseTime,
}
impl ActorRegistry {
... | ActorRegistry | identifier_name |
actor.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// General actor system infrastructure.
use devtools_traits::PreciseTime;
use rustc_serialize::json;
use std::an... |
pub fn drop_actor_later(&self, name: String) {
let mut actors = self.old_actors.borrow_mut();
actors.push(name);
}
}
| {
self.actors.remove(&name);
} | identifier_body |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... | <T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> {
if exp == 0 {
return Some(T::one());
}
macro_rules! optry {
( $ expr : expr ) => {
if let Some(val) = $expr { val } else { return None }
}
}
while exp & 1 == 0 {
base = optry!(base... | checked_pow | identifier_name |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... |
let mut acc = base.clone();
while exp > 1 {
exp >>= 1;
base = optry!(base.checked_mul(&base));
if exp & 1 == 1 {
acc = optry!(acc.checked_mul(&base));
}
}
Some(acc)
}
| {
return Some(base);
} | conditional_block |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... | } | Some(acc) | random_line_split |
pow.rs | use libtww::std::ops::Mul;
use {One, CheckedMul};
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num_traits::pow;
///
/// assert_eq!(pow(2i8, 4), 16);
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>... | while exp > 1 {
exp >>= 1;
base = optry!(base.checked_mul(&base));
if exp & 1 == 1 {
acc = optry!(acc.checked_mul(&base));
}
}
Some(acc)
}
| {
if exp == 0 {
return Some(T::one());
}
macro_rules! optry {
( $ expr : expr ) => {
if let Some(val) = $expr { val } else { return None }
}
}
while exp & 1 == 0 {
base = optry!(base.checked_mul(&base));
exp >>= 1;
}
if exp == 1 {
... | identifier_body |
setup.py | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def | (fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "S20Control",
version = "0.1",
author = "Glen Pitt-Pladdy / Guy Sheffer",
author_email = "glenpp@users.noreply.github.com",
description = ("Python management utility for Orvibo S20 WiFi Plug"),
license... | read | identifier_name |
setup.py | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
|
setup(
name = "S20Control",
version = "0.1",
author = "Glen Pitt-Pladdy / Guy Sheffer",
author_email = "glenpp@users.noreply.github.com",
description = ("Python management utility for Orvibo S20 WiFi Plug"),
license = "GNU",
keywords = "s20 orvibo orvibos20",
url = "https://github.com/... | return open(os.path.join(os.path.dirname(__file__), fname)).read() | identifier_body |
setup.py | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.di... | long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Beta",
"Topic :: Utilities",
"License :: GNU License",
],
entry_points = {
'console_scripts': [
'S20control = S20control.S20control:main',
], ... | description = ("Python management utility for Orvibo S20 WiFi Plug"),
license = "GNU",
keywords = "s20 orvibo orvibos20",
url = "https://github.com/glenpp/OrviboS20",
packages=['S20control'], | random_line_split |
websocket.py | from typing import Union
from asphalt.core.context import Context
from wsproto.connection import WSConnection, ConnectionType
from wsproto.events import ConnectionRequested, ConnectionClosed, DataReceived
from asphalt.web.api import AbstractEndpoint
from asphalt.web.request import HTTPRequest
from asphalt.web.servers... |
def on_data(self, data: bytes) -> None:
"""Called when there is new data from the peer.""" | random_line_split | |
websocket.py | from typing import Union
from asphalt.core.context import Context
from wsproto.connection import WSConnection, ConnectionType
from wsproto.events import ConnectionRequested, ConnectionClosed, DataReceived
from asphalt.web.api import AbstractEndpoint
from asphalt.web.request import HTTPRequest
from asphalt.web.servers... |
bytes_to_send = self._ws.bytes_to_send()
if bytes_to_send:
self._client.write(bytes_to_send)
def begin_request(self, request: HTTPRequest):
trailing_data = self._client.upgrade()
self._ws.receive_bytes(trailing_data)
self._process_ws_events()
def receive_b... | self.on_close() | conditional_block |
websocket.py | from typing import Union
from asphalt.core.context import Context
from wsproto.connection import WSConnection, ConnectionType
from wsproto.events import ConnectionRequested, ConnectionClosed, DataReceived
from asphalt.web.api import AbstractEndpoint
from asphalt.web.request import HTTPRequest
from asphalt.web.servers... | elif isinstance(event, ConnectionClosed):
self.on_close()
bytes_to_send = self._ws.bytes_to_send()
if bytes_to_send:
self._client.write(bytes_to_send)
def begin_request(self, request: HTTPRequest):
trailing_data = self._client.upgrade()
self.... | """
Implements websocket endpoints.
Subprotocol negotiation is currently not supported.
"""
__slots__ = ('ctx', '_client', '_ws')
def __init__(self, ctx: Context, client: BaseHTTPClientConnection):
self.ctx = ctx
self._client = client
self._ws = WSConnection(ConnectionType... | identifier_body |
websocket.py | from typing import Union
from asphalt.core.context import Context
from wsproto.connection import WSConnection, ConnectionType
from wsproto.events import ConnectionRequested, ConnectionClosed, DataReceived
from asphalt.web.api import AbstractEndpoint
from asphalt.web.request import HTTPRequest
from asphalt.web.servers... | (self, payload: Union[str, bytes]) -> None:
"""
Send a message to the client.
:param payload: either a unicode string or a bytestring
"""
self._ws.send_data(payload)
bytes_to_send = self._ws.bytes_to_send()
self._client.write(bytes_to_send)
def close(self) ... | send_message | identifier_name |
verify.rs | extern crate regex;
#[phase(link, plugin)]
extern crate log;
#[phase(plugin)] extern crate regex_macros;
use std::collections::HashMap;
use std::io::File;
use syntax::parse;
use syntax::parse::lexer;
use rustc::driver::{session, config};
use syntax::ast;
use syntax::ast::Name;
use syntax::parse::token::*;
use synt... |
fn main() {
fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
use syntax::parse::lexer::Reader;
r.next_token()
}
let args = std::os::args();
let mut token_file = File::open(&Path::new(args.get(2).as_slice()));
let token_map = parse_token_list(token_file.read_to_string().unwr... | {
match a {
&IDENT(id, _) => match b {
&IDENT(id2, _) => id == id2,
_ => false
},
_ => a == b
}
} | identifier_body |
verify.rs | extern crate regex;
#[phase(link, plugin)]
extern crate log;
#[phase(plugin)] extern crate regex_macros;
use std::collections::HashMap;
use std::io::File;
use syntax::parse;
use syntax::parse::lexer;
use rustc::driver::{session, config};
use syntax::ast;
use syntax::ast::Name;
use syntax::parse::token::*;
use synt... |
debug!("What we got: content (`{}`), proto: {}", content, proto_tok);
let real_tok = match *proto_tok {
BINOP(..) => BINOP(str_to_binop(content)),
BINOPEQ(..) => BINOPEQ(str_to_binop(content.slice_to(content.len() - 1))),
LIT_STR(..) => LIT_STR(fix(content)),
LIT_STR_RAW(..) =>... |
let proto_tok = tokens.find_equiv(&toknum).expect(format!("didn't find token {} in the map",
toknum).as_slice());
let nm = parse::token::intern(content); | random_line_split |
verify.rs | extern crate regex;
#[phase(link, plugin)]
extern crate log;
#[phase(plugin)] extern crate regex_macros;
use std::collections::HashMap;
use std::io::File;
use syntax::parse;
use syntax::parse::lexer;
use rustc::driver::{session, config};
use syntax::ast;
use syntax::ast::Name;
use syntax::parse::token::*;
use synt... | (a: &Token, b: &Token) -> bool {
match a {
&IDENT(id, _) => match b {
&IDENT(id2, _) => id == id2,
_ => false
},
_ => a == b
}
}
fn main() {
fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
use syntax::parse::lexer::Reader;
r.nex... | tok_cmp | identifier_name |
Sphere.js | /**
* @module og/bv/Sphere
*/
'use strict';
import { Vec3 } from '../math/Vec3.js';
/**
* Bounding sphere class.
* @class
* @param {Number} [radius] - Bounding sphere radius.
* @param {og.Vec3} [center] - Bounding sphere coordiantes.
*/
class Sphere {
constructor(radius, center) {
... |
/**
* Sets bounding sphere coordiantes by ellipsoid geodetic extend.
* @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {og.Extent} extent - Geodetic extent.
*/
setFromExtent(ellipsoid, extent) {
this.setFromBounds(extent.getCartesianBounds(ellipsoid));
}
};
e... | {
let m = new Vec3(bounds[0], bounds[1], bounds[2]);
this.center.set(m.x + (bounds[3] - m.x) * 0.5, m.y + (bounds[3] - m.y) * 0.5, m.z + (bounds[5] - m.z) * 0.5);
this.radius = this.center.distance(m);
} | identifier_body |
Sphere.js | /**
* @module og/bv/Sphere
*/
'use strict';
import { Vec3 } from '../math/Vec3.js';
/**
* Bounding sphere class.
* @class
* @param {Number} [radius] - Bounding sphere radius.
* @param {og.Vec3} [center] - Bounding sphere coordiantes.
*/
class Sphere {
constructor(radius, center) {
... | * @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {og.Extent} extent - Geodetic extent.
*/
setFromExtent(ellipsoid, extent) {
this.setFromBounds(extent.getCartesianBounds(ellipsoid));
}
};
export { Sphere }; |
/**
* Sets bounding sphere coordiantes by ellipsoid geodetic extend.
| random_line_split |
Sphere.js | /**
* @module og/bv/Sphere
*/
'use strict';
import { Vec3 } from '../math/Vec3.js';
/**
* Bounding sphere class.
* @class
* @param {Number} [radius] - Bounding sphere radius.
* @param {og.Vec3} [center] - Bounding sphere coordiantes.
*/
class Sphere {
constructor(radius, center) {
... | (ellipsoid, extent) {
this.setFromBounds(extent.getCartesianBounds(ellipsoid));
}
};
export { Sphere };
| setFromExtent | identifier_name |
import_rewrite_visitor.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AotCompilerHost} from '@angular/compiler';
import {dirname, resolve} from 'path';
import * as ts from 'types... | <T extends ts.Node>(ctx: ts.TransformationContext, newSourceFile: ts.SourceFile):
ts.Transformer<T> {
const visitNode: ts.Visitor = (node: ts.Node) => {
if (ts.isIdentifier(node)) {
// Record the identifier reference and return the new identifier. The identifier
// name can change if the... | create | identifier_name |
import_rewrite_visitor.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AotCompilerHost} from '@angular/compiler';
import {dirname, resolve} from 'path';
import * as ts from 'types... |
const sourceFileExports = getExportSymbolsOfFile(sourceFile, this.typeChecker);
this.sourceFileExports.set(sourceFile, sourceFileExports);
return sourceFileExports;
}
/** Rewrites a module import to be relative to the target file location. */
private _rewriteModuleImport(resolvedImport: Import, new... | {
return this.sourceFileExports.get(sourceFile) !;
} | conditional_block |
import_rewrite_visitor.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
|
import {Import, getImportOfIdentifier} from '../../../utils/typescript/imports';
import {getValueSymbolOfDeclaration} from '../../../utils/typescript/symbol';
import {ImportManager} from '../import_manager';
import {getPosixPath} from './path_format';
import {ResolvedExport, getExportSymbolsOfFile} from './source_fil... | import {AotCompilerHost} from '@angular/compiler';
import {dirname, resolve} from 'path';
import * as ts from 'typescript'; | random_line_split |
index.ts | import { useHistory } from 'react-router-dom';
import {useMobile} from '../../mobile';
export * from '../../mobile';
export const useConnectToMobile=()=>{
const history = useHistory();
const mobile = useMobile(initData);
mobile.setOnchange(({ field }) => {
switch (field.id) { | return false;
}
});
return mobile;
};
const FIELDS = {
companyName: {
id: "company_name",
type: "text",
label: "Company Name",
value: "Iterative Solution"
},
address: {
id: "address",
label: "Address",
type: "text",
... | case FIELDS.back.id:
history.push('/');
break;
default: | random_line_split |
htm2dbk.py | m()("<[hH]2>") >> "<sect1 id=\"--filename--\"><title>",
m()("<[Pp]([> ])","m") >> "<para\\1",
m()("</[Pp]>") >> "</para>",
m()("<(pre|PRE)>") >> "<screen>",
m()("</(pre|PRE)>") >> "</screen>",
m()("<[hH]3>") >> "<sect2><title>",
m()("</[hH]3>((?:.(?!<sect2>))*.?)", "s") ... | htm2dbk_files | identifier_name | |
htm2dbk.py | subtitle>\\1</subtitle>",
m()("<[hH]2>") >> "<sect1 id=\"--filename--\"><title>",
m()("<[Pp]([> ])","m") >> "<para\\1",
m()("</[Pp]>") >> "</para>",
m()("<(pre|PRE)>") >> "<screen>",
m()("</(pre|PRE)>") >> "</screen>",
m()("<[hH]3>") >> "<sect2><title>",
m()("</[h... | return self.text + self.book_end_chapters + self.book_end | random_line_split | |
htm2dbk.py | ]3>((?:.(?!<sect2>))*.?)", "s") >> "</title>\\1</sect2>",
m()("<!doctype [^<>]*>","s") >> "",
m()("<!DOCTYPE [^<>]*>","s") >> "",
m()("(<\w+\b[^<>]*\swidth=)(\d+\%)","s") >> "\\1\"\\2\"",
m()("(<\w+\b[^<>]*\s\w+=)(\d+)","s") >> "\\1\"\\2\"",
m()("&&") >> "\&\;\&\;",
... | """ the C comment may contain html markup - simulate with docbook tags """
return htm2dbk_conversion().convert2(text) | identifier_body | |
htm2dbk.py | m = match.Match
class htm2dbk_conversion_base:
regexlist = [
m()("</[hH]2>(.*)", "m") >> "</title>\n<subtitle>\\1</subtitle>",
m()("<[hH]2>") >> "<sect1 id=\"--filename--\"><title>",
m()("<[Pp]([> ])","m") >> "<para\\1",
m()("</[Pp]>") >> "</para>",
m()("<(pre|PRE)>") >> "<s... |
return txt
class htm2dbk_document(htm2dbk_conversion):
""" create document, add(text) and get the value() """
doctype = (
'<!DOCTYPE book PUBLIC "-//OASIS//DTD'+
' DocBook XML V4.1.2//EN"'+"\n"+
' "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">'+
"\n")... | txt &= conv | conditional_block |
sparse.rs | use std::fmt;
use std::ops::Deref;
use std::slice;
/// A sparse set used for representing ordered NFA states.
///
/// This supports constant time addition and membership testing. Clearing an
/// entire set can also be done in constant time. Iteration yields elements
/// in the order in which they were inserted.
///
//... |
}
impl fmt::Debug for SparseSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SparseSet({:?})", self.dense)
}
}
impl Deref for SparseSet {
type Target = [usize];
fn deref(&self) -> &Self::Target {
&self.dense
}
}
impl<'a> IntoIterator for &'a SparseSet {
... | {
self.dense.clear();
} | identifier_body |
sparse.rs | use std::fmt;
use std::ops::Deref;
use std::slice;
/// A sparse set used for representing ordered NFA states.
///
/// This supports constant time addition and membership testing. Clearing an
/// entire set can also be done in constant time. Iteration yields elements
/// in the order in which they were inserted.
///
//... | sparse: vec![0; size].into_boxed_slice(),
}
}
pub fn len(&self) -> usize {
self.dense.len()
}
pub fn is_empty(&self) -> bool {
self.dense.is_empty()
}
pub fn capacity(&self) -> usize {
self.dense.capacity()
}
pub fn insert(&mut self, value:... | SparseSet {
dense: Vec::with_capacity(size), | random_line_split |
sparse.rs | use std::fmt;
use std::ops::Deref;
use std::slice;
/// A sparse set used for representing ordered NFA states.
///
/// This supports constant time addition and membership testing. Clearing an
/// entire set can also be done in constant time. Iteration yields elements
/// in the order in which they were inserted.
///
//... | (&mut self, value: usize) {
let i = self.len();
assert!(i < self.capacity());
self.dense.push(value);
self.sparse[value] = i;
}
pub fn contains(&self, value: usize) -> bool {
let i = self.sparse[value];
self.dense.get(i) == Some(&value)
}
pub fn clear(&m... | insert | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.