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 |
|---|---|---|---|---|
robotremoteserver.py | """Server port as an integer.
If the initial given port is 0, also this property returns 0 until
the server is activated.
"""
return self._server.server_address[1]
def activate(self):
"""Bind port and activate the server but do not yet start serving.
:retur... | (self, handler):
self._handler = lambda signum, frame: handler()
self._original = {}
def __enter__(self):
for name in 'SIGINT', 'SIGTERM', 'SIGHUP':
if hasattr(signal, name):
try:
orig = signal.signal(getattr(signal, name), self._handler)
... | __init__ | identifier_name |
robotremoteserver.py | , name):
keyword = self._get_keyword(name)
return getattr(keyword, 'robot_tags', [])
class HybridRemoteLibrary(StaticRemoteLibrary):
def __init__(self, library, get_keyword_names):
StaticRemoteLibrary.__init__(self, library)
self.get_keyword_names = get_keyword_names
class Dynam... | action, uri = parse_args(*sys.argv)
success = action(uri)
sys.exit(0 if success else 1) | random_line_split | |
robotremoteserver.py | , name):
keyword = self._get_keyword(name)
return getattr(keyword, 'robot_tags', [])
class HybridRemoteLibrary(StaticRemoteLibrary):
def __init__(self, library, get_keyword_names):
StaticRemoteLibrary.__init__(self, library)
self.get_keyword_names = get_keyword_names
class Dynam... | def parse_args(script, *args):
actions = {'stop': stop_remote_server, 'test': test_remote_server}
if not (0 < len(args) < 3) or args[0] not in actions:
sys.exit('Usage: %s {test|stop} [uri]' % os.path.basename(script))
uri = args[1] if len(args) == 2 else 'http://127.0.0.1:8270'
... | conditional_block | |
default.py | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... | brar el evento """
if request.vars.id_event and request.vars.new_name:
if db.events[request.vars.id_event].owner_event == auth.user_id:
db.events[request.vars.id_event] = dict(name=request.vars.new_name)
else:
raise (500, 'false')
else:
raise (400, 'false')
def user():
"""
exposes:
http://..... | :
""" Renom | identifier_name |
default.py | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... | db.events[request.vars.id_event] = dict(json_shared_data=json_shared_data)
return 'true'
else:
return db.events[request.vars.id_event].json_shared_data
else:
raise (400, 'false')
@auth.requires_login()
def rename_event():
""" Renombrar el evento """
if request.vars.id_event and request.vars.new_name:
... | import json
python_shared_data = json.loads(json_shared_data)
python_shared_data[request.vars.variable][request.vars.id_object] = request.vars.value
json_shared_data = json.dumps(python_shared_data)
# Actualizar el json en la base de datos | random_line_split |
default.py | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... | downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request, db)
| identifier_body | |
default.py | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... | e (400, 'false')
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_pas... | equest.vars.id_event].owner_event == auth.user_id:
db.events[request.vars.id_event] = dict(name=request.vars.new_name)
else:
raise (500, 'false')
else:
rais | conditional_block |
ng2now.ts | }
/**
SetModule(module:String, dependencies: String[])
SetModule() is a function that must be used instead of angular.module()
before any ng2now decorators are used. It is functionally equivalent to
angular.module().
Please see the documentation for angular.module() for more details.
If used without any arguments,... | if (options.uiRouterTemplate)
common.uiRouterTemplate = options.uiRouterTemplate; | random_line_split | |
ng2now.ts | .x. So, do look at ui-router 1.x documentation for
// more details on this new feature.
// Another way to look at what the resolve is doing is like so:
// <home-page state="vm.app.homepage"></home-page>
// The above assumes the host component's controller contains
// a reference to app, of course... | {
config = {
strictDi: false
};
} | conditional_block | |
ng2now.ts | (s) {
return s.replace(/-(.)/g, (a, b) => b.toUpperCase());
}
function options(options) {
if (!options)
return Object.assign({}, common);
if (options.hasOwnProperty('controllerAs'))
common.controllerAs = options.controllerAs;
if (options.uiRouterTemplate)
common.uiRouterTemplat... | camelCase | identifier_name | |
ng2now.ts | deps;
if (args[0] instanceof Array) {
deps = args[0];
} else {
deps = args;
}
if (deps.length === 0) {
throw new Error('@Inject: No dependencies passed in');
}
return function InjectTarget(target, name, descriptor) {
if (descriptor) {
throw new Typ... | {
if (options.name === undefined
&& options.hasOwnProperty('html5Mode') === false
&& options.hasOwnProperty('html5mode') === false) {
throw new Error('@State: valid options are: name, url, defaultRoute, otherwise, template, templateUrl, templateProvider, resolve, abstract, parent, data.');
... | identifier_body | |
app.component.ts | import { Component, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import * as go from "gojs";
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><div #myDiagramDiv style="border: solid blue 1px; width:350px; height:350px"></div>`,
})
export class AppComponent implements AfterViewIni... | { from: "Alpha", to: "Gamma" },
{ from: "Beta", to: "Beta" },
{ from: "Gamma", to: "Delta" },
{ from: "Delta", to: "Alpha" }
]);
}
} | ],
[
{ from: "Alpha", to: "Beta" }, | random_line_split |
app.component.ts | import { Component, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import * as go from "gojs";
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><div #myDiagramDiv style="border: solid blue 1px; width:350px; height:350px"></div>`,
})
export class | implements AfterViewInit {
name = 'GoJS';
@ViewChild('myDiagramDiv')
element: ElementRef;
ngAfterViewInit() {
//(go as any).licenseKey = "...";
const $ = go.GraphObject.make; // for conciseness in defining templates
const myDiagram: go.Diagram = $(go.Diagram, this.element.nativeElement,
... | AppComponent | identifier_name |
TagList.tsx | import React, { forwardRef, memo } from 'react';
import { css, cx } from '@emotion/css';
import { OnTagClick, Tag } from './Tag';
import { useTheme2 } from '../../themes';
import { GrafanaTheme2 } from '@grafana/data';
import { IconName } from '../../types/icon';
export interface Props {
displayMax?: number;
tags:... | </ul>
);
})
);
TagList.displayName = 'TagList';
const getStyles = (theme: GrafanaTheme2, isTruncated: boolean) => {
return {
wrapper: css`
position: relative;
align-items: ${isTruncated ? 'center' : 'unset'};
display: flex;
flex: 1 1 auto;
flex-wrap: wrap;
flex-sh... | ))}
{displayMax && displayMax > 0 && numTags - 1 > 0 && (
<span className={styles.moreTagsLabel}>+ {numTags - 1}</span>
)} | random_line_split |
play_card.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use runes::play_minion::PlayMinion;
use runes::set_mana::SetMana;
use hlua;
// the play_minion rune is called when you play a minion
// out of your hand. It will call battle_cry if it has one
// and it will remove the card f... |
fn to_json(&self) -> String {
json::encode(self).unwrap().replace("{", "{\"runeType\":\"PlayCard\",")
}
fn into_box(&self) -> Box<Rune> {
Box::new(self.clone())
}
}
| {
return true;
} | identifier_body |
play_card.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use runes::play_minion::PlayMinion;
use runes::set_mana::SetMana;
use hlua;
// the play_minion rune is called when you play a minion
// out of your hand. It will call battle_cry if it has one
// and it will remove the card f... | (card_uid: UID,
controller_uid: UID,
field_index: usize,
target_uid: UID)
-> PlayCard {
PlayCard {
card_uid: card_uid,
controller_uid: controller_uid,
field_index: field_index,
target_uid: target_uid,
... | new | identifier_name |
play_card.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use runes::play_minion::PlayMinion;
use runes::set_mana::SetMana;
use hlua;
// the play_minion rune is called when you play a minion
// out of your hand. It will call battle_cry if it has one
// and it will remove the card f... | fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool {
return true;
}
fn to_json(&self) -> String {
json::encode(self).unwrap().replace("{", "{\"runeType\":\"PlayCard\",")
}
fn into_box(&self) -> Box<Rune> {
Box::new(self.clone())
}
} |
game_state.stage_rune(Box::new(pm));
}
| random_line_split |
main.rs |
use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
c... |
}
Spinlock { buffer }
}
fn get_value_after(&self, value: usize) -> Option<usize> {
if let Some((idx, _)) = self.buffer.iter().enumerate().find(
|&(_idx, val)| *val == value,
)
{
let pos = (idx + 1) % self.buffer.len();
self.buffer.i... | {
println!("*** {}", i);
} | conditional_block |
main.rs |
use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
c... | () {
let lock = Spinlock::new(3, 3);
assert_eq!(vec![0, 2, 3, 1], lock.buffer);
let lock = Spinlock::new(3, 2017);
println!("{:?}", lock.buffer);
assert_eq!(Some(638), lock.get_value_after(2017));
}
#[test]
fn spinlock_special_case_test() {
assert_eq!(Som... | spinlock_test | identifier_name |
main.rs | use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
cu... | lock_len += 1;
}
val
}
fn main() {
let mut args = env::args();
args.next();
let step_size = args.next().expect("missing argument").parse().expect(
"parse error",
);
let lock = Spinlock::new(step_size, 2017);
println!(
"Short lock: The value right after 2017... |
if curr_pos == 1 {
val = Some(i);
}
| random_line_split |
main.rs |
use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
c... |
fn main() {
let mut args = env::args();
args.next();
let step_size = args.next().expect("missing argument").parse().expect(
"parse error",
);
let lock = Spinlock::new(step_size, 2017);
println!(
"Short lock: The value right after 2017 is {}.",
lock.get_value_after(... | {
let mut val = None;
let mut curr_pos = 0;
let mut lock_len = 1;
for i in 1..(num_insertions + 1) {
curr_pos = (curr_pos + step_size) % lock_len + 1;
if curr_pos == 1 {
val = Some(i);
}
lock_len += 1;
}
val
} | identifier_body |
file_reading.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/. */
use dom::domexception::DOMErrorName;
use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaDa... | (&self) -> FileReadingTaskSource {
FileReadingTaskSource(self.0.clone(), self.1.clone())
}
}
impl TaskSource for FileReadingTaskSource {
const NAME: TaskSourceName = TaskSourceName::FileReading;
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
) ->... | clone | identifier_name |
file_reading.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaData};
use msg::constellation_msg::PipelineId;
use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory, ScriptChan};
use std::sync::Arc;
use task::{TaskCanceller, TaskOnce};
use task_source::{TaskSource, TaskSourceName};
#[derive(JSTrac... | * 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/. */
use dom::domexception::DOMErrorName; | random_line_split |
file_reading.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/. */
use dom::domexception::DOMErrorName;
use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaDa... |
}
impl TaskOnce for FileReadingTask {
fn run_once(self) {
self.handle_task();
}
}
#[allow(dead_code)]
pub enum FileReadingTask {
ProcessRead(TrustedFileReader, GenerationId),
ProcessReadData(TrustedFileReader, GenerationId),
ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName),... | {
self.0.send(CommonScriptMsg::Task(
ScriptThreadEventCategory::FileRead,
Box::new(canceller.wrap_task(task)),
Some(self.1),
))
} | identifier_body |
day_three_part2.py | class PresentDeliverer:
present_locations = {}
def | (self, name):
self.name = name
self.x = 0
self.y = 0
self.present_locations[self.get_key()]=1
def get_key(self):
return str(self.x)+"-"+str(self.y)
def status(self):
print(self.name + " x: "+str(self.x)+" y: "+str(self.y))
def move(self,instruction):
if instruction == ">":
self.x += 1
elif... | __init__ | identifier_name |
day_three_part2.py | class PresentDeliverer:
present_locations = {}
def __init__(self, name):
self.name = name
self.x = 0
self.y = 0
self.present_locations[self.get_key()]=1
def get_key(self):
return str(self.x)+"-"+str(self.y)
def status(self):
print(self.name + " x: "+str(self.x)+" y: "+str(self.y))
def move(self... |
def unique_houses(self):
print("Unique houses: "+str(len(self.present_locations.keys())))
filename = "..\inputs\day_three_input.txt"
f = open(filename)
input_line = f.readline()
santa = PresentDeliverer("Santa")
robo = PresentDeliverer("RoboSanta")
instruction_count = 0
for c in input_line:
instruction_count... | else:
self.y -= 1
self.present_locations[self.get_key()]=1 | random_line_split |
day_three_part2.py | class PresentDeliverer:
present_locations = {}
def __init__(self, name):
self.name = name
self.x = 0
self.y = 0
self.present_locations[self.get_key()]=1
def get_key(self):
return str(self.x)+"-"+str(self.y)
def status(self):
print(self.name + " x: "+str(self.x)+" y: "+str(self.y))
def move(self... |
def unique_houses(self):
print("Unique houses: "+str(len(self.present_locations.keys())))
filename = "..\inputs\day_three_input.txt"
f = open(filename)
input_line = f.readline()
santa = PresentDeliverer("Santa")
robo = PresentDeliverer("RoboSanta")
instruction_count = 0
for c in input_line:
instruction_coun... | if instruction == ">":
self.x += 1
elif instruction == "<":
self.x -= 1
elif instruction == "^":
self.y += 1
else:
self.y -= 1
self.present_locations[self.get_key()]=1 | identifier_body |
day_three_part2.py | class PresentDeliverer:
present_locations = {}
def __init__(self, name):
self.name = name
self.x = 0
self.y = 0
self.present_locations[self.get_key()]=1
def get_key(self):
return str(self.x)+"-"+str(self.y)
def status(self):
print(self.name + " x: "+str(self.x)+" y: "+str(self.y))
def move(self... |
elif instruction == "^":
self.y += 1
else:
self.y -= 1
self.present_locations[self.get_key()]=1
def unique_houses(self):
print("Unique houses: "+str(len(self.present_locations.keys())))
filename = "..\inputs\day_three_input.txt"
f = open(filename)
input_line = f.readline()
santa = PresentDeliverer... | self.x -= 1 | conditional_block |
event-type.ts | import {WebSocketConnectionState} from 'interface';
export enum EventTypeKey {
APP_STATE_UPDATED = 'APP_STATE_UPDATED',
LOGIN = 'LOGIN',
UNKNOWN_ERROR = 'UNKNOWN_ERROR',
WEB_SOCKET_CONNECTION_STATE_CHANGED = 'WEB_SOCKET_CONNECTION_STATE_CHANGED',
SOMEONE_SAID_HELLO = 'SOMEONE_SAID_HELLO'
};
export interface... | const event: IWebSocketConnectionStateChangedEvent = {
type: EventTypeKey.WEB_SOCKET_CONNECTION_STATE_CHANGED,
webSocketConnectionState: state
};
return event;
};
export interface ISomeoneSaidHelloEvent {
type: EventTypeKey.SOMEONE_SAID_HELLO;
username: string;
}
export const makeSomeoneSaidHelloEv... | }
export const makeWebSocketConnectionStateChangedEvent = (state: WebSocketConnectionState) => { | random_line_split |
Todo.tsx | import * as React from 'react';
import state$ from '../state';
import bindAction from '../state/bindAction';
import connect from '../state/connect';
import TodoActions from '../actions/TodoActions';
import { ITodo } from '../model/todo';
import TodoListComponent from './TodoList';
import TodoInput from './TodoInput';
... | interface IState {
title: string;
}
export class TodoComponent extends React.Component<IProps, IState> {
add(description: string) {
this.props.add(description);
}
handleTitleChange(event: any) {
this.setState({
title: event.target.value,
});
}
render() {
return (
<div>
... | random_line_split | |
Todo.tsx | import * as React from 'react';
import state$ from '../state';
import bindAction from '../state/bindAction';
import connect from '../state/connect';
import TodoActions from '../actions/TodoActions';
import { ITodo } from '../model/todo';
import TodoListComponent from './TodoList';
import TodoInput from './TodoInput';
... | (description: string) {
this.props.add(description);
}
handleTitleChange(event: any) {
this.setState({
title: event.target.value,
});
}
render() {
return (
<div>
<TodoListComponent todos={ this.props.todos } updateStatus={ this.props.updateStatus.bind(this) } />
<To... | add | identifier_name |
Todo.tsx | import * as React from 'react';
import state$ from '../state';
import bindAction from '../state/bindAction';
import connect from '../state/connect';
import TodoActions from '../actions/TodoActions';
import { ITodo } from '../model/todo';
import TodoListComponent from './TodoList';
import TodoInput from './TodoInput';
... |
handleTitleChange(event: any) {
this.setState({
title: event.target.value,
});
}
render() {
return (
<div>
<TodoListComponent todos={ this.props.todos } updateStatus={ this.props.updateStatus.bind(this) } />
<TodoInput add={this.add.bind(this)}/>
</div>
);
}
... | {
this.props.add(description);
} | identifier_body |
meteor.d.ts | /* eslint-disable @typescript-eslint/camelcase */
import { EJSON } from 'meteor/ejson';
declare module 'meteor/meteor' {
namespace Meteor {
interface IDDPMessage {
msg: 'method';
method: string;
params: EJSON[];
id: string;
}
interface IDDPUpdatedMessage {
msg: 'updated';
methods: string[];
... | }): Collection<T>;
}
}
} | connection?: object | null;
idGeneration?: string;
transform?: Function | null; | random_line_split |
errors.rs | inner: Error,
}
impl VerboseError {
pub fn new(inner: Error) -> VerboseError {
VerboseError { inner }
}
}
impl std::error::Error for VerboseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.source()
}
}
impl fmt::Debug for VerboseError {
fn fmt(&... |
pub fn code(code: i32) -> CliError {
CliError {
error: None,
exit_code: code,
}
}
}
impl From<anyhow::Error> for CliError {
fn from(err: anyhow::Error) -> CliError {
CliError::new(err, 101)
}
}
impl From<clap::Error> for CliError {
fn from(err: cla... | {
CliError {
error: Some(error),
exit_code: code,
}
} | identifier_body |
errors.rs | inner: Error,
}
impl VerboseError {
pub fn new(inner: Error) -> VerboseError {
VerboseError { inner }
}
}
impl std::error::Error for VerboseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.source()
}
}
impl fmt::Debug for VerboseError {
fn fm... | pub type CliResult = Result<(), CliError>;
#[derive(Debug)]
/// The CLI error is the error type used at Cargo's CLI-layer.
///
/// All errors from the lib side of Cargo will get wrapped with this error.
/// Other errors (such as command-line argument validation) will create this
/// directly.
pub struct CliError {
... | // =============================================================================
// CLI errors
| random_line_split |
errors.rs | inner: Error,
}
impl VerboseError {
pub fn new(inner: Error) -> VerboseError {
VerboseError { inner }
}
}
impl std::error::Error for VerboseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.source()
}
}
impl fmt::Debug for VerboseError {
fn fmt(&... | (&self) -> ManifestCauses<'_> {
ManifestCauses { current: self }
}
}
impl std::error::Error for ManifestError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.cause.source()
}
}
impl fmt::Debug for ManifestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt:... | manifest_causes | identifier_name |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
def strip_comments(l):
return l.split('#', 1)[0].strip()
def reqs(*f):
|
def get_version(version_tuple):
if not isinstance(version_tuple[-1], int):
return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1]
return '.'.join(map(str, version_tuple))
init = os.path.join(os.path.dirname(__file__), 'src', 'gmaps', '__init__.py')
version_line = list(filter(lambda l: l.... | return list(filter(None, [strip_comments(l) for l in open(
os.path.join(os.getcwd(), *f)).readlines()])) | identifier_body |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
def strip_comments(l):
return l.split('#', 1)[0].strip()
def reqs(*f):
return list(filter(None, [strip_comments(l) for l in open(
os.path.join(os.getcwd(), *f)).readlines()]))
def get_version(version_tuple):
if not i... | version_line = list(filter(lambda l: l.startswith('VERSION'), open(init)))[0]
VERSION = get_version(eval(version_line.split('=')[-1]))
INSTALL_REQUIRES = reqs('requirements.txt')
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
PACKAGES = find_packages('src')
PACKAGE_DIR = {'': 'src'}
setup... | return '.'.join(map(str, version_tuple))
init = os.path.join(os.path.dirname(__file__), 'src', 'gmaps', '__init__.py') | random_line_split |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
def | (l):
return l.split('#', 1)[0].strip()
def reqs(*f):
return list(filter(None, [strip_comments(l) for l in open(
os.path.join(os.getcwd(), *f)).readlines()]))
def get_version(version_tuple):
if not isinstance(version_tuple[-1], int):
return '.'.join(map(str, version_tuple[:-1])) + version... | strip_comments | identifier_name |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
def strip_comments(l):
return l.split('#', 1)[0].strip()
def reqs(*f):
return list(filter(None, [strip_comments(l) for l in open(
os.path.join(os.getcwd(), *f)).readlines()]))
def get_version(version_tuple):
if not i... |
return '.'.join(map(str, version_tuple))
init = os.path.join(os.path.dirname(__file__), 'src', 'gmaps', '__init__.py')
version_line = list(filter(lambda l: l.startswith('VERSION'), open(init)))[0]
VERSION = get_version(eval(version_line.split('=')[-1]))
INSTALL_REQUIRES = reqs('requirements.txt')
README = open... | return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] | conditional_block |
0001_initial.py | # Generated by Django 2.1.1 on 2018-09-08 20:47
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('tags', '0001_initial'),
('accounts', '0001_initial'), | fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('label', models.CharField(max_length=255, verbose_name='Label')),
('date', models.DateField(default=datetime.date.today, verbose_name='Date')),
... | ]
operations = [
migrations.CreateModel(
name='Scheduler', | random_line_split |
0001_initial.py | # Generated by Django 2.1.1 on 2018-09-08 20:47
import datetime
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
initial = True
dependencies = [
('tags', '0001_initial'),
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Scheduler',
fields=[
('id', models.AutoField(auto_created=True, primary_key=Tr... | Migration | identifier_name |
0001_initial.py | # Generated by Django 2.1.1 on 2018-09-08 20:47
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| ('type', models.CharField(choices=[('monthly', 'Monthly'), ('weekly', 'Weekly')], default='monthly', help_text='The type of recurrence to be applied.', max_length=32, verbose_name='Type')),
('recurrence', models.PositiveSmallIntegerField(blank=True, help_text='How many time the bank tran... | initial = True
dependencies = [
('tags', '0001_initial'),
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Scheduler',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_... | identifier_body |
test_loaders.py | from unittest import TestCase
from pydigmips import instructions, loaders
class HexaLoaderTestCase(TestCase):
def testAdd(self):
i = ['1510', # 000 101 010 001 0000
'1C60',
'2C60'] # 001 011 000 110 0000
o = [instructions.Add(5, 2, 1), instructions.Add(7, 0, 6),
... |
def testLdi(self):
i = ['B0AA'] # 101 100 00 10101010
o = [instructions.Ldi(4, 170)]
prog = loaders.load_hexa(i)
self.assertEqual(prog, o)
def testJa(self):
i = ['CE80'] # 110 011 101 0000000
o = [instructions.Ja(3, 5)]
prog = loaders.load_hexa(i)
... | i = ['8EAA'] # 100 011 101 0101010
o = [instructions.Ble(3, 5, 42)]
prog = loaders.load_hexa(i)
self.assertEqual(prog, o) | identifier_body |
test_loaders.py | from unittest import TestCase
from pydigmips import instructions, loaders
class HexaLoaderTestCase(TestCase):
def testAdd(self):
i = ['1510', # 000 101 010 001 0000
'1C60',
'2C60'] # 001 011 000 110 0000
o = [instructions.Add(5, 2, 1), instructions.Add(7, 0, 6),
... | i = ['B0AA'] # 101 100 00 10101010
o = [instructions.Ldi(4, 170)]
prog = loaders.load_hexa(i)
self.assertEqual(prog, o)
def testJa(self):
i = ['CE80'] # 110 011 101 0000000
o = [instructions.Ja(3, 5)]
prog = loaders.load_hexa(i)
self.assertEqual(prog,... | o = [instructions.Ble(3, 5, 42)]
prog = loaders.load_hexa(i)
self.assertEqual(prog, o)
def testLdi(self): | random_line_split |
test_loaders.py | from unittest import TestCase
from pydigmips import instructions, loaders
class HexaLoaderTestCase(TestCase):
def testAdd(self):
i = ['1510', # 000 101 010 001 0000
'1C60',
'2C60'] # 001 011 000 110 0000
o = [instructions.Add(5, 2, 1), instructions.Add(7, 0, 6),
... | (self):
i = ['4EAA', # 010 011 101 0101010
'6EAA'] # 011 011 101 0101010
o = [instructions.Ld(3, (5, 42)),
instructions.St(3, (5, 42))]
prog = loaders.load_hexa(i)
self.assertEqual(prog, o)
def testBle(self):
i = ['8EAA'] # 100 011 101 0101010
... | testLd | identifier_name |
expr.rs | // Expressions
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later ... | (&self) -> Prec {
match *self {
Expr::Id (ref i) => i.prec(),
Expr::Int (ref i) => i.prec(),
Expr::Reg (ref r) => r.prec(),
Expr::Unary (ref u) => u.prec(),
Expr::Binary (ref b) => b.prec(),
Expr::Deref (ref d) => d.prec(),
... | prec | identifier_name |
expr.rs | // Expressions
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later ... |
#[test]
fn fmt_reg() {
let e = Expr::Reg(Reg::new("a"));
let s = format!("{}", e);
assert_eq!(s, "a");
}
}
| {
let e = Expr::Int(Int::from(42));
let s = format!("{}", e);
assert_eq!(s, "0x2A");
} | identifier_body |
expr.rs | // Expressions
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later ... |
#[test]
fn prec() {
let e = Binary::new(
BinaryOp::Add,
Expr::Id(Id::new("a")),
Expr::Id(Id::new("b"))
);
assert_eq!(e.prec(), Prec::Additive);
}
#[test]
fn fmt_id() {
let e = Expr::Id(Id::new("a"));
let s = format!("{}", ... | use super::*; | random_line_split |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% f... | };
dest.write_str(s)
}
}
impl ToComputedValue for SystemColor {
type ComputedValue = u32; // nscolor
#[inline]
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
unsafe {
Gecko_GetLookAndFeelSystemColor(
... | % for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(), | random_line_split |
stack_overflow.rs | 0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use libc;
use core::prelude::*;
use self::imp::{make_handler, drop_... | pub struct Handler {
_data: *mut libc::c_void
}
impl Handler {
pub unsafe fn new() -> Handler {
make_handler()
}
}
impl Drop for Handler {
fn drop(&mut self) {
unsafe {
drop_handler(self);
}
}
}
#[cfg(any(target_os = "linux",
target_os = "macos",
... | pub use self::imp::{init, cleanup};
| random_line_split |
stack_overflow.rs | 0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use libc;
use core::prelude::*;
use self::imp::{make_handler, drop_... | (signum: libc::c_int,
info: *mut siginfo,
_data: *mut libc::c_void) {
// We can not return from a SIGSEGV or SIGBUS signal.
// See: https://www.gnu.org/software/libc/manual/html_node/Handler-Returns.html
unsafe fn term(s... | signal_handler | identifier_name |
stack_overflow.rs | 0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use libc;
use core::prelude::*;
use self::imp::{make_handler, drop_... |
PAGE_SIZE = psize as uint;
let mut action: sigaction = mem::zeroed();
action.sa_flags = SA_SIGINFO | SA_ONSTACK;
action.sa_sigaction = signal_handler as sighandler_t;
sigaction(SIGSEGV, &action, ptr::null_mut());
sigaction(SIGBUS, &action, ptr::null_mut());
le... | {
panic!("failed to get page size");
} | conditional_block |
xmlToJSON.js | /* Copyright 2013 William Summers, metaTribal LLC
* adapted from https://developer.mozilla.org/en-US/docs/JXON
*
* 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... |
// parse attributes
// using attributes property instead of hasAttributes method to support older browsers
if (oXMLParent.attributes && oXMLParent.attributes.length > 0) {
var vAttribs = {};
for (nLength; nLength < oXMLParent.attributes.length; nLength++) {
... | {
vResult[options.namespaceKey] = oXMLParent.namespaceURI;
} | conditional_block |
xmlToJSON.js | /* Copyright 2013 William Summers, metaTribal LLC
* adapted from https://developer.mozilla.org/en-US/docs/JXON
*
* 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... | for (var key in opt) {
options[key] = opt[key];
}
var vResult = {},
nLength = 0,
sCollectedTxt = "";
// parse namespace information
if (options.xmlns && oXMLParent.namespaceURI) {
vResult[options.namespaceKey] = oXMLParent.namespa... |
this.parseXML = function (oXMLParent, opt) {
// initialize options | random_line_split |
MD10-pie-plot.py | import time
t0 = time.time()
import os
import numpy as n
import sys
import glob
import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
from scipy.interpolate import interp1d
L_box = 1000./0.6777
tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B... | (points, name='slice_1_Lbox.png', lims=(0,L_box)) :
p.figure(0, ((6,6)))
p.axes([0.17,0.17,0.78,0.78])
for tracer in tracer_names:
x_pos, y_pos = points[tracer].T
p.plot(x_pos, y_pos,marker=marker_dict[tracer],color=color_dict[tracer],rasterized=True,ls='None',label=tracer)
p.legend(loc=0, frameon=False, fonts... | plot_slice | identifier_name |
MD10-pie-plot.py | import time
t0 = time.time()
import os
import numpy as n
import sys
import glob
import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
from scipy.interpolate import interp1d
L_box = 1000./0.6777
tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B... | tracer_name = spl_bn[-2]+'_'+spl_bn[-1]
ids = fits.open(path_2_tracer_file)[1].data['line_number']
x_i = positions['x'][ids]/0.6777 - x_observer + x_shift
y_i = positions['y'][ids]/0.6777 - y_observer + y_shift
z_i = positions['z'][ids]/0.6777 - z_observer + z_shift
shell = (x_i*x_i + y_i*y_i ... | z_min, z_max = z_boundaries[ii], z_boundaries[ii+1]
r_min, r_max = cosmoMD.comoving_distance(z_min).value, cosmoMD.comoving_distance(z_max).value
position_files = n.array(glob.glob(os.path.join(work_dir, 'out_'+el['snap_name']+'_SAM_Nb_?.fits')))
position_files.sort()
# position file loop
print r_min, r_max... | conditional_block |
MD10-pie-plot.py | import time
t0 = time.time()
import os
import numpy as n
import sys
import glob
import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
from scipy.interpolate import interp1d
L_box = 1000./0.6777
tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B... |
plot_slice(points_1, name='slice_1_Lbox.png', lims=(0*L_box,1*L_box))
plot_slice(points_2, name='slice_2_Lbox.png', lims=(1*L_box,2*L_box))
plot_slice(points_3, name='slice_3_Lbox.png', lims=(2*L_box,3*L_box))
plot_slice(points_4, name='slice_4_Lbox.png', lims=(3*L_box,4*L_box))
sys.exit()
p.figure(0, ((6,6)))
p.ax... | p.figure(0, ((6,6)))
p.axes([0.17,0.17,0.78,0.78])
for tracer in tracer_names:
x_pos, y_pos = points[tracer].T
p.plot(x_pos, y_pos,marker=marker_dict[tracer],color=color_dict[tracer],rasterized=True,ls='None',label=tracer)
p.legend(loc=0, frameon=False, fontsize=9)
p.xlabel('Mpc')
p.ylabel('Mpc')
p.xlim(lims... | identifier_body |
MD10-pie-plot.py | import time
t0 = time.time()
import os
import numpy as n
import sys
import glob
import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
from scipy.interpolate import interp1d
L_box = 1000./0.6777
tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B... | p.plot(x_pos, y_pos,marker=marker_dict[tracer],color=color_dict[tracer],rasterized=True,ls='None',label=tracer)
p.legend(loc=0, frameon=False, fontsize=9)
p.xlabel('Mpc')
p.ylabel('Mpc')
p.xlim(lims)
p.ylim((0,L_box))
p.title(str(n.round(dc_2_z(lims[0]),2))+'<z<'+str(n.round(dc_2_z(lims[1]),2)) )
p.savefig(os... | random_line_split | |
generic-tup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn get_third<T>(... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
generic-tup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; }
pub fn main() {
info!(get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
}
| get_third | identifier_name |
generic-tup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
info!(get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
}
| { let (_, _, x) = t; return x; } | identifier_body |
desktopreport.js | 'use strict';
function desktopreport($q, $routeParams, $location, common, datacontext, threatmodellocator, electron) {
var fsp = require('promise-fs');
/*jshint validthis: true */
var vm = this;
var controllerId = 'desktopreport';
var getLogFn = common.logger.getLogFn;
var log = getLogFn(contro... | () {
vm.loaded = true;
return 'called onLoaded';
}
function onError(err) {
vm.error = err;
logError(err.data.message);
}
function threatModelLocation() {
return threatmodellocator.getModelLocation($routeParams);
}
function savePDF(done) {
electr... | onLoaded | identifier_name |
desktopreport.js | 'use strict';
function desktopreport($q, $routeParams, $location, common, datacontext, threatmodellocator, electron) |
function activate() {
common.activateController([getThreatModel()], controllerId)
.then(function () { log('Activated Desktop Report Controller'); });
}
function getThreatModel(forceReload) {
var location = threatModelLocation();
return datacontext.load(location, force... | {
var fsp = require('promise-fs');
/*jshint validthis: true */
var vm = this;
var controllerId = 'desktopreport';
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var logError = getLogFn(controllerId, 'error');
// Bindable properties and functions are placed on v... | identifier_body |
desktopreport.js | 'use strict';
function desktopreport($q, $routeParams, $location, common, datacontext, threatmodellocator, electron) {
var fsp = require('promise-fs');
/*jshint validthis: true */
var vm = this;
var controllerId = 'desktopreport';
var getLogFn = common.logger.getLogFn;
var log = getLogFn(contro... |
electron.dialog.savePDF(defaultPath, function (fileName) {
fsp.writeFile(fileName, data).then(function() {
done();
});
},
function() {
log('Cancelled save threat model');
... |
var defaultPath = null;
if (datacontext.threatModelLocation) {
defaultPath = datacontext.threatModelLocation.replace('.json', '.pdf');
} | random_line_split |
desktopreport.js | 'use strict';
function desktopreport($q, $routeParams, $location, common, datacontext, threatmodellocator, electron) {
var fsp = require('promise-fs');
/*jshint validthis: true */
var vm = this;
var controllerId = 'desktopreport';
var getLogFn = common.logger.getLogFn;
var log = getLogFn(contro... |
}
}
}
module.exports = desktopreport; | {
// see Electron issue https://github.com/electron/electron/issues/19008
// application will "hang" if the print dialog is cancelled
// calling reload instead of done is a temporary workaround
// it looks bad but the app keeps working
logE... | conditional_block |
wsgi.py | """
WSGI config for auth_example project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "auth_example.settings"
os... | Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another | random_line_split |
auth_routes_test.js | /* test/auth_route_spec.js -- test Authentication helper
* Copyright 2014 Sergei Ianovich
*
* Licensed under AGPL-3.0 or later, see LICENSE
* Process Control Service Web Interface
*/
var expect = require('expect.js');
var Routes = require('../routes/_auth');
var User = require('../models/user');
describe('Authen... | });
it("should assign operator", function(done) {
var user = null;
var userAttrs = {
name: "Example User",
email: "user@example.com",
password: 'password',
confirmation: 'password',
};
(new User(userAttrs)).save(function(err, user) {
var req = { s... | done();
}};
Routes.authenticate(req, res, null);
}); | random_line_split |
treemap.src.js | extend(node, {
ignore: true,
isLeaf: false,
visible: false
});
if (node.children.length) {
next = (next || []).concat(node.children);
}
});
return next;
});
}
});
// Sort the children
stableSort(children, function (a, b) {
ret... | var childrenArea = [],
series = this,
pTot, | random_line_split | |
treemap.src.js | to better location
};
series.nodeMap[node.id] = node;
if (point) {
point.node = node;
}
return node;
},
setTreeValues: function (tree) {
var series = this,
options = series.options,
childrenTotal = 0,
children = [],
val,
point = series.points[tree.i];
// First give the... | {
plot.x = plot.x + pW;
} | conditional_block | |
chromium_code_search.py | # Copyright 2017 Josh Karlin. All rights reserved.
# Use of this source code is governed by the Apache license found in the LICENSE
# file.
import argparse
import datetime
import getopt
import json
import sys
import tempfile
import threading
import time
import urllib.request
import urllib.parse
gFileCache = None;
# ... | :
def __init__(self):
self.store = {}
threading.Timer(15 * 60, self.gc).start();
def put(self, url, data):
f = tempfile.TemporaryFile();
f.write(data);
self.store[url] = (f, datetime.datetime.now());
def get(self, url):
if not url in self.store:
return ''
(f, timestamp) = self.... | FileCache | identifier_name |
chromium_code_search.py | # Copyright 2017 Josh Karlin. All rights reserved.
# Use of this source code is governed by the Apache license found in the LICENSE
# file.
import argparse
import datetime
import getopt
import json
import sys
import tempfile
import threading
import time
import urllib.request
import urllib.parse
gFileCache = None;
# ... | if timestamp < expired:
remove.append(url)
for url in remove:
self.store.pop(url);
def cacheResponses(should_cache):
global gFileCache
if not should_cache:
gFileCache = None;
return
if gFileCache:
return
gFileCache = FileCache();
# Retrieve the url by first trying to cache ... | expired = datetime.datetime.now() - datetime.timedelta(minutes=30);
remove = []
for url, (f, timestamp) in self.store.items(): | random_line_split |
chromium_code_search.py | # Copyright 2017 Josh Karlin. All rights reserved.
# Use of this source code is governed by the Apache license found in the LICENSE
# file.
import argparse
import datetime
import getopt
import json
import sys
import tempfile
import threading
import time
import urllib.request
import urllib.parse
gFileCache = None;
# ... |
# Retrieve the url by first trying to cache and falling back to the network.
def retrieve(url):
global gFileCache
if gFileCache:
cached_response = gFileCache.get(url);
if (cached_response):
return cached_response.decode('utf8');
response = None
try:
if len(url) > 1500:
short_url = u... | global gFileCache
if not should_cache:
gFileCache = None;
return
if gFileCache:
return
gFileCache = FileCache(); | identifier_body |
chromium_code_search.py | # Copyright 2017 Josh Karlin. All rights reserved.
# Use of this source code is governed by the Apache license found in the LICENSE
# file.
import argparse
import datetime
import getopt
import json
import sys
import tempfile
import threading
import time
import urllib.request
import urllib.parse
gFileCache = None;
# ... |
results['xrefs'] = getXrefsFor(signature);
results['callers'] = getCallGraphFor(signature);
print(json.dumps(results))
| logAndExit("Could not find signature for %s" % (args.word)) | conditional_block |
tests.rs | use rocket::local::Client;
use rocket::http::{Status, ContentType};
use std::io::Read;
use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let mut res = client.get("/").dispatch();
... | {
// Delete the upload file before we begin.
let _ = fs::remove_file("/tmp/upload.txt");
// Do the upload. Make sure we get the expected results.
let client = Client::new(super::rocket()).unwrap();
let mut res = client.post("/upload")
.header(ContentType::Plain)
.body(UPLOAD_CONTENT... | identifier_body | |
tests.rs | use rocket::local::Client;
use rocket::http::{Status, ContentType}; | use std::io::Read;
use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let mut res = client.get("/").dispatch();
assert_eq!(res.body_string(), Some(super::index().to_string()));
}
... | random_line_split | |
tests.rs | use rocket::local::Client;
use rocket::http::{Status, ContentType};
use std::io::Read;
use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let mut res = client.get("/").dispatch();
... | () {
// Delete the upload file before we begin.
let _ = fs::remove_file("/tmp/upload.txt");
// Do the upload. Make sure we get the expected results.
let client = Client::new(super::rocket()).unwrap();
let mut res = client.post("/upload")
.header(ContentType::Plain)
.body(UPLOAD_CONT... | test_raw_upload | identifier_name |
encoding.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | ];
const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = {
'ibm866': 'cp866',
'big5': 'cp950'
};
export function detectEncoding(buffer: Buffer): string | null {
let result = detectEncodingByBOM(buffer);
if (result) {
return result;
}
const detected = jschardet.detect(buffer);
if (!detected || !... | 'ascii',
'utf-8',
'utf-16',
'utf-32' | random_line_split |
encoding.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (buffer: Buffer): string | null {
let result = detectEncodingByBOM(buffer);
if (result) {
return result;
}
const detected = jschardet.detect(buffer);
if (!detected || !detected.encoding) {
return null;
}
const encoding = detected.encoding;
// Ignore encodings that cannot guess correctly
// (http://cha... | detectEncoding | identifier_name |
encoding.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
const b0 = buffer.readUInt8(0);
const b1 = buffer.readUInt8(1);
// UTF-16 BE
if (b0 === 0xFE && b1 === 0xFF) {
return 'utf16be';
}
// UTF-16 LE
if (b0 === 0xFF && b1 === 0xFE) {
return 'utf16le';
}
if (buffer.length < 3) {
return null;
}
const b2 = buffer.readUInt8(2);
// UTF-8
if (b0 === 0xEF... | {
return null;
} | conditional_block |
encoding.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
const b2 = buffer.readUInt8(2);
// UTF-8
if (b0 === 0xEF && b1 === 0xBB && b2 === 0xBF) {
return 'utf8';
}
return null;
}
const IGNORE_ENCODINGS = [
'ascii',
'utf-8',
'utf-16',
'utf-32'
];
const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = {
'ibm866': 'cp866',
'big5': 'cp950'
};
exp... | {
if (!buffer || buffer.length < 2) {
return null;
}
const b0 = buffer.readUInt8(0);
const b1 = buffer.readUInt8(1);
// UTF-16 BE
if (b0 === 0xFE && b1 === 0xFF) {
return 'utf16be';
}
// UTF-16 LE
if (b0 === 0xFF && b1 === 0xFE) {
return 'utf16le';
}
if (buffer.length < 3) {
return null; | identifier_body |
angular-locale_jmc-tz.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
angular-locale_jmc-tz.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... |
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"utuko",
"kyiukonyi"
],
"DAY": [
"Jumapilyi",
"Jumatatuu",
"Jumanne",
"Jumatanu",
"Alhamisi",
"Ijumaa",
"Jumamosi"
],
"ERANAMES": [
"Kabla ya Kristu",
"Baada ya Kristu"
... | {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
} | identifier_body |
angular-locale_jmc-tz.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... | "Februari",
"Machi",
"Aprilyi",
"Mei",
"Junyi",
"Julyai",
"Agusti",
"Septemba",
"Oktoba",
"Novemba",
"Desemba"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:... | ],
"STANDALONEMONTH": [
"Januari", | random_line_split |
angular-locale_jmc-tz.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function | (n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.... | getDecimals | identifier_name |
rotation.ts | <!DOCTYPE TS><TS>
<defaultcodec>iso8859-1</defaultcodec> | <source>Rotation Settings</source>
<translation>Rotationseinstellungen</translation>
</message>
<message>
<source><p>Select orientation from options at left.</source>
<translation><p>Wählen Sie die Ausrichtung aus den Optionen auf der linken Seite.</translation>
<... | <context>
<name>RotationSettings</name>
<message> | random_line_split |
breakpoints.js | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
let {session, contextGroup, Protocol} = InspectorTest.start('Checks breakpoints.');
session.setupScriptMap();
InspectorTest.runAsyncTestSuite([
async... | (expression, expectedBreakpoint) {
InspectorTest.log('evaluating ' + expression + ':');
let paused = Protocol.Debugger.oncePaused();
let evaluate = Protocol.Runtime.evaluate({expression});
let result = await Promise.race([paused, evaluate]);
if (result.method === 'Debugger.paused') {
if (result.params.hit... | evaluate | identifier_name |
breakpoints.js | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
let {session, contextGroup, Protocol} = InspectorTest.start('Checks breakpoints.');
session.setupScriptMap();
InspectorTest.runAsyncTestSuite([
async... |
}
await Protocol.Debugger.resume();
} else {
InspectorTest.log(' not paused');
}
}
| {
InspectorTest.log(' hit unexpected breakpoint');
} | conditional_block |
breakpoints.js | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
let {session, contextGroup, Protocol} = InspectorTest.start('Checks breakpoints.');
session.setupScriptMap();
InspectorTest.runAsyncTestSuite([
async... | InspectorTest.logMessage(await Protocol.Debugger.removeBreakpoint({
breakpointId: ':::'
}));
await Protocol.Debugger.disable();
},
async function testSetBreakpointByUrl() {
await Protocol.Debugger.enable();
Protocol.Runtime.evaluate({expression: `
function foo1(arg) {
return arg;
}
//# ... | breakpointId: ''
})); | random_line_split |
breakpoints.js | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
let {session, contextGroup, Protocol} = InspectorTest.start('Checks breakpoints.');
session.setupScriptMap();
InspectorTest.runAsyncTestSuite([
async... | {
InspectorTest.log('evaluating ' + expression + ':');
let paused = Protocol.Debugger.oncePaused();
let evaluate = Protocol.Runtime.evaluate({expression});
let result = await Promise.race([paused, evaluate]);
if (result.method === 'Debugger.paused') {
if (result.params.hitBreakpoints) {
if (result.p... | identifier_body | |
doRPC.py | capacity_change = self.insertIntoC(i + 1) or capacity_change
self.nextN += 1
else:
break
if capacity_change:
self.F = edmonds_karp(self.a, self.C, 0, self.a - 1, self.sumC_active)
self.full_flow = sum([self.F[0][i] for i in xrange(self.a)])
self.ignore_flow = sum([self.F[i][self.a - 1] * self... |
else:
# Sort out detections that would have matched
matchingIndexes = []
for m,frect in enumerate(idlDet[filterIndex].rects):
if(style == 0):
if (j.isMatchingStd(frect, minCover,minOverlap, maxDistance)):
overlap = j.overlap_pascal(frect)
matchingIndex... | validGTRects.append(j) | conditional_block |
doRPC.py | capacity_change = self.insertIntoC(i + 1) or capacity_change
self.nextN += 1
else:
break
if capacity_change:
self.F = edmonds_karp(self.a, self.C, 0, self.a - 1, self.sumC_active)
self.full_flow = sum([self.F[0][i] for i in xrange(self.a)])
self.ignore_flow = sum([self.F[i][self.a - 1] * self... |
parser.add_option("-p", "--Pascal-Style", action="store_true", dest="pascalStyle")
parser.add_option("-l", "--Leibe-Seemann-Matching-Style", action="store_true", dest="leibeStyle")
parser.add_option("--minCover", action="store", type="float", dest="minCover", default=0.5)
parser.add_option("--maxDistance",... | parser = OptionParser(usage="usage: %prog [options] <groundTruthIdl> <detectionIdl>")
parser.add_option("-o", "--outFile",
action="store", type="string", dest="outFile")
parser.add_option("-a", "--analysisFiles",
action="store", type="string", dest="analysisFile")
... | identifier_body |
doRPC.py | capacity_change = self.insertIntoC(i + 1) or capacity_change
self.nextN += 1
else:
break
if capacity_change:
self.F = edmonds_karp(self.a, self.C, 0, self.a - 1, self.sumC_active)
self.full_flow = sum([self.F[0][i] for i in xrange(self.a)])
self.ignore_flow = sum([self.F[i][self.a - 1] * self... | (self):
ret = copy.copy(self.anno)
ret.rects = []
#iterate over GT
for i in xrange(self.n + 1, self.a - 1):
#Flow to sink > 0
if(self.F[i][self.a - 1] > 0 and self.ignore[i - self.n - 1] == 0):
#Find associated det
for j in xrange(1, self.n + 1):
if(self.F[j][i] > 0):
ret.rects.append(s... | getTruePositives | identifier_name |
doRPC.py | Det):
imageFound = False
filterIndex = -1
for i,filterAnno in enumerate(idlGT):
if (suffixMatch(anno.imageName, filterAnno.imageName) and anno.frameNr == filterAnno.frameNr):
filterIndex = i
imageFound = True
break
if(not imageFound):
continue
validDetRects = []
for... | for j, detAnno in enumerate(detIDL):
if (suffixMatch(annoIDL[i].imageName, detIDL[j].imageName) and annoIDL[i].frameNr == detIDL[j].frameNr):
filterIndex = j | random_line_split | |
cci_no_inline_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) {
let mut i = 0u;
let n = v.len();
while i < n {
f(v[i]);
i += 1u;
}
}
| iter | identifier_name |
cci_no_inline_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #![crate_name="cci_no_inline_lib"]
// same as cci_iter_lib, more-or-less, but not marked inline
pub fn iter<F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) {
let mut i = 0u;
let n = v.len();
while i < n {
f(v[i]);
i += 1u;
}
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
cci_no_inline_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut i = 0u;
let n = v.len();
while i < n {
f(v[i]);
i += 1u;
}
} | identifier_body | |
create.rs | // https://rustbyexample.com/std_misc/file/create.html
// http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html
// $ mkdir out
// $ rustc create.rs && ./create
// $ cat out/lorem_ipsum.txt
// create.rs
static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiu... | use std::path::Path;
fn main() {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// Open a file in write-only mode, returns `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
... | random_line_split | |
create.rs | // https://rustbyexample.com/std_misc/file/create.html
// http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html
// $ mkdir out
// $ rustc create.rs && ./create
// $ cat out/lorem_ipsum.txt
// create.rs
static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiu... | }
| {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// Open a file in write-only mode, returns `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
why.d... | identifier_body |
create.rs | // https://rustbyexample.com/std_misc/file/create.html
// http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html
// $ mkdir out
// $ rustc create.rs && ./create
// $ cat out/lorem_ipsum.txt
// create.rs
static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiu... | () {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// Open a file in write-only mode, returns `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
wh... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.