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 |
|---|---|---|---|---|
run.py | from flask import Flask, request, redirect, session
import twilio.twiml
import navigation
SECRET_KEY = 'donuts'
logging = True
app = Flask(__name__)
app.config.from_object(__name__)
def log(mesagge=""):
|
@app.route("/", methods=['GET', 'POST'])
def main_reply():
# Log values from request
from_number = request.values.get('From', None)
log(from_number)
recieved_message = request.values.get('Body')
log(recieved_message)
# pick reply to message
reply = navigation.choose_script(bodyText=reciev... | if logging:
print mesagge | identifier_body |
test.py | # noinspection PyMethodMayBeStatic
class TestDevice:
def __init__(self, cf):
self.type = cf.get('device_test_type', 'test')
self.host = ('test', 80)
self.mac = [1, 2, 3, 4, 5, 6]
def auth(self):
pass
# RM2/RM4
def check_temperature(self):
return 23.5
# RM4
... | (self):
return 56
def enter_learning(self):
pass
def check_data(self):
payload = bytearray(5)
payload[0] = 0xAA
payload[1] = 0xBB
payload[2] = 0xCC
payload[3] = 0xDD
payload[4] = 0xEE
return payload
def send_data(self, data):
... | check_humidity | identifier_name |
test.py | # noinspection PyMethodMayBeStatic
class TestDevice:
def __init__(self, cf):
|
def auth(self):
pass
# RM2/RM4
def check_temperature(self):
return 23.5
# RM4
def check_humidity(self):
return 56
def enter_learning(self):
pass
def check_data(self):
payload = bytearray(5)
payload[0] = 0xAA
payload[1] = 0xBB
... | self.type = cf.get('device_test_type', 'test')
self.host = ('test', 80)
self.mac = [1, 2, 3, 4, 5, 6] | identifier_body |
test.py | # noinspection PyMethodMayBeStatic
class TestDevice:
def __init__(self, cf):
self.type = cf.get('device_test_type', 'test')
self.host = ('test', 80)
self.mac = [1, 2, 3, 4, 5, 6]
def auth(self):
pass
# RM2/RM4
def check_temperature(self):
return 23.5
# RM4
... | def check_sensors_raw(self):
return {'temperature': 23.5, 'humidity': 36, 'light': 1, 'air_quality': 3, 'noise': 2}
def get_percentage(self):
return 33
def open(self):
pass
def get_state(self):
return {'pwr': 1, 'pwr1': 1, 'pwr2': 0, 'maxworktime': 60, 'maxworktime1': ... | def check_sensors(self):
return {'temperature': 23.5, 'humidity': 36, 'light': 'dim', 'air_quality': 'normal', 'noise': 'noisy'}
| random_line_split |
terminal.rs | //! Functions related to terminal devices.
use std::{mem, ptr};
use libc::{c_int, c_void};
use remacs_macros::lisp_fn;
use crate::{
dispnew::LispGlyphRef,
frames::Fselected_frame,
frames::LispFrameRef,
lisp::{ExternalPtr, LispObject},
remacs_sys::build_string,
remacs_sys::{pvec_type, Lisp_Te... | }
/// Insert LEN glyphs from START at the nominal cursor position.
///
/// If start is zero, insert blanks instead of a string at start
#[no_mangle]
pub unsafe extern "C" fn insert_glyphs(mut f: LispFrameRef, mut start: LispGlyphRef, len: c_int) {
if len <= 0 {
return;
}
if let Some(hook) = (*f.ter... | random_line_split | |
terminal.rs | //! Functions related to terminal devices.
use std::{mem, ptr};
use libc::{c_int, c_void};
use remacs_macros::lisp_fn;
use crate::{
dispnew::LispGlyphRef,
frames::Fselected_frame,
frames::LispFrameRef,
lisp::{ExternalPtr, LispObject},
remacs_sys::build_string,
remacs_sys::{pvec_type, Lisp_Te... |
/// Clear entire frame.
#[no_mangle]
pub unsafe extern "C" fn clear_frame(mut f: LispFrameRef) {
if let Some(hook) = (*f.terminal).clear_frame_hook {
hook(f.as_mut())
}
}
/// Clear from cursor to end of line.
/// Assume that the line is already clear starting at column first_unused_hpos.
///
/// Note... | {
if let Some(hook) = (*f.terminal).clear_to_end_hook {
hook(f.as_mut())
}
} | identifier_body |
terminal.rs | //! Functions related to terminal devices.
use std::{mem, ptr};
use libc::{c_int, c_void};
use remacs_macros::lisp_fn;
use crate::{
dispnew::LispGlyphRef,
frames::Fselected_frame,
frames::LispFrameRef,
lisp::{ExternalPtr, LispObject},
remacs_sys::build_string,
remacs_sys::{pvec_type, Lisp_Te... |
}
/// Delete N glyphs at the nominal cursor position.
#[no_mangle]
pub unsafe extern "C" fn delete_glyphs(mut f: LispFrameRef, n: c_int) {
if let Some(hook) = (*f.terminal).delete_glyphs_hook {
hook(f.as_mut(), n)
}
}
/// Insert N lines at vpos VPOS. If N is negative, delete -N lines.
#[no_mangle]
p... | {
hook(f.as_mut(), start.as_mut(), len)
} | conditional_block |
terminal.rs | //! Functions related to terminal devices.
use std::{mem, ptr};
use libc::{c_int, c_void};
use remacs_macros::lisp_fn;
use crate::{
dispnew::LispGlyphRef,
frames::Fselected_frame,
frames::LispFrameRef,
lisp::{ExternalPtr, LispObject},
remacs_sys::build_string,
remacs_sys::{pvec_type, Lisp_Te... | (mut f: LispFrameRef) {
if let Some(hook) = (*f.terminal).update_begin_hook {
hook(f.as_mut())
}
}
#[no_mangle]
pub unsafe extern "C" fn update_end(mut f: LispFrameRef) {
if let Some(hook) = (*f.terminal).update_end_hook {
hook(f.as_mut())
}
}
// Erase operations.
/// Clear from curso... | update_begin | identifier_name |
__init__.py | #
# Copyright (C) 2014 Mathias Weber <mathew.weber@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# thi... |
from user import *
from event import * | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
# | random_line_split |
rms.py | # -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Functions'... | ():
""" RESTful CRUD controller """
tablename = "%s_%s" % (prefix, resourcename)
table = db[tablename]
s3xrc.model.configure(table, insertable=False)
return s3_rest_controller(prefix, resourcename)
def store_for_req():
store_table = None
return dict(store_table = store_table)
| ritem | identifier_name |
rms.py | # -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Functions'... | store_table = None
return dict(store_table = store_table) | identifier_body | |
rms.py | # -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Functions'... | menu_shelter = [
[selection.name, False, URL(r=request, c="cr", f="shelter", args=[selection.id])]
]
menu.extend(menu_shelter)
response.menu_options = menu
def index():
""" Module's Home Page
Default to the rms_req list view.
"""
request.fun... | if "cr_shelter" in session.rcvars:
shelter = db.cr_shelter
query = (shelter.id == session.rcvars["cr_shelter"])
selection = db(query).select(shelter.id, shelter.name, limitby=(0, 1)).first()
if selection: | random_line_split |
rms.py | # -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
|
# Options Menu (available in all Functions' Views)
menu = [
[T("Home"), False, URL(r=request, f="index")],
[T("Requests"), False, URL(r=request, f="req"), [
[T("List"), False, URL(r=request, f="req")],
[T("Add"), False, URL(r=request, f="req", args="create")],
# @ToDo Search by priorit... | session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index")) | conditional_block |
prefab.rs | use crayon::errors::*;
use crayon::res::utils::prelude::ResourceState;
use crayon::sched::prelude::LatchProbe;
use crayon::uuid::Uuid;
use crayon::video::assets::mesh::MeshHandle;
use spatial::prelude::Transform;
impl_handle!(PrefabHandle);
/// A prefab asset acts as a template from which you can create new
/// enti... | fn is_set(&self) -> bool {
ResourceState::NotReady != crate::prefab_state(*self)
}
} | impl LatchProbe for PrefabHandle { | random_line_split |
prefab.rs | use crayon::errors::*;
use crayon::res::utils::prelude::ResourceState;
use crayon::sched::prelude::LatchProbe;
use crayon::uuid::Uuid;
use crayon::video::assets::mesh::MeshHandle;
use spatial::prelude::Transform;
impl_handle!(PrefabHandle);
/// A prefab asset acts as a template from which you can create new
/// enti... |
}
| {
ResourceState::NotReady != crate::prefab_state(*self)
} | identifier_body |
prefab.rs | use crayon::errors::*;
use crayon::res::utils::prelude::ResourceState;
use crayon::sched::prelude::LatchProbe;
use crayon::uuid::Uuid;
use crayon::video::assets::mesh::MeshHandle;
use spatial::prelude::Transform;
impl_handle!(PrefabHandle);
/// A prefab asset acts as a template from which you can create new
/// enti... | {
/// The mesh index.
pub mesh: usize,
/// Indicates whether this object cast shadows.
pub shadow_caster: bool,
/// Indicates whether this object receive shadows.
pub shadow_receiver: bool,
/// Is this renderer visible.
pub visible: bool,
}
impl Prefab {
pub fn validate(&self) -> R... | PrefabMeshRenderer | identifier_name |
x01sidenav.controller.js | /// <reference path="../references.d.ts" />
/// <reference path="./gameManager.service.ts" />
/// <reference path="../kdarts.ts" />
var kdarts;
(function (kdarts) {
var game;
(function (game) {
var X01SidenavController = (function () {
function | ($state, $mdSidenav, $mdDialog) {
this.$state = $state;
this.$mdSidenav = $mdSidenav;
this.$mdDialog = $mdDialog;
}
X01SidenavController.prototype.closeMenu = function () {
this.$mdSidenav('left').close()
.then(f... | X01SidenavController | identifier_name |
x01sidenav.controller.js | /// <reference path="../references.d.ts" />
/// <reference path="./gameManager.service.ts" />
/// <reference path="../kdarts.ts" />
var kdarts;
(function (kdarts) {
var game;
(function (game) {
var X01SidenavController = (function () {
function X01SidenavController($state, $mdSidenav, $mdDia... | .then(function () {
});
};
X01SidenavController.prototype.cancelGame = function () {
var _this = this;
var confirm = this.$mdDialog.confirm()
.title('Cancel Game')
.content('Are you sure y... | X01SidenavController.prototype.closeMenu = function () {
this.$mdSidenav('left').close() | random_line_split |
x01sidenav.controller.js | /// <reference path="../references.d.ts" />
/// <reference path="./gameManager.service.ts" />
/// <reference path="../kdarts.ts" />
var kdarts;
(function (kdarts) {
var game;
(function (game) {
var X01SidenavController = (function () {
function X01SidenavController($state, $mdSidenav, $mdDia... |
X01SidenavController.prototype.closeMenu = function () {
this.$mdSidenav('left').close()
.then(function () {
});
};
X01SidenavController.prototype.cancelGame = function () {
var _this = this;
var con... | {
this.$state = $state;
this.$mdSidenav = $mdSidenav;
this.$mdDialog = $mdDialog;
} | identifier_body |
jquery-ui-timepicker-l10n.js | /* global define */
define(['jquery', 'orotranslation/js/translator', 'orolocale/js/locale-settings', 'jquery-ui-timepicker'],
function($, __, localeSettings) {
'use strict';
var locale = localeSettings.locale;
$.timepicker.regional[locale] = { // Default regional settings
currentText: __('Now'),
... | hourText: __('Hour'),
minuteText: __('Minute'),
secondText: __('Second'),
millisecText: __('Millisecond'),
microsecText: __('Microsecond'),
timezoneText: __('Time Zone'),
timezone: localeSettings.getTimeZoneOffset().replace(':', ''),
separator: localeSetti... | timeFormat: localeSettings.getVendorDateTimeFormat('jquery_ui', 'time', 'HH:mm'),
timeSuffix: '',
timeOnlyTitle: __('Choose Time'),
timeText: __('Time'), | random_line_split |
esnext.set.symmetric-difference.js | import { createIterable } from '../helpers/helpers';
import from from 'core-js-pure/es/array/from';
import Set from 'core-js-pure/features/set';
QUnit.test('Set#symmetricDifference', assert => { | assert.name(symmetricDifference, 'symmetricDifference');
assert.nonEnumerable(Set.prototype, 'symmetricDifference');
const set = new Set([1]);
assert.notSame(set.symmetricDifference([2]), set);
assert.deepEqual(from(new Set([1, 2, 3]).symmetricDifference([4, 5])), [1, 2, 3, 4, 5]);
assert.deepEqual(from(n... | const { symmetricDifference } = Set.prototype;
assert.isFunction(symmetricDifference);
assert.arity(symmetricDifference, 1); | random_line_split |
configuration.ts | // tslint:disable
/**
* backend/api/filter.proto
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swag... |
}
| {
this.apiKey = param.apiKey;
this.username = param.username;
this.password = param.password;
this.accessToken = param.accessToken;
this.basePath = param.basePath;
} | identifier_body |
configuration.ts | // tslint:disable
/**
* backend/api/filter.proto
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swag... | /**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
username?: string;
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
password?: string;
/**
* parameter for oauth2 security
* @param name security name
* @... | apiKey?: string | ((name: string) => string); | random_line_split |
configuration.ts | // tslint:disable
/**
* backend/api/filter.proto
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swag... | (param: ConfigurationParameters = {}) {
this.apiKey = param.apiKey;
this.username = param.username;
this.password = param.password;
this.accessToken = param.accessToken;
this.basePath = param.basePath;
}
}
| constructor | identifier_name |
reach_api.py | import os
import json
import tempfile
import urllib, urllib2
import requests
from indra.java_vm import autoclass, JavaException
import indra.databases.pmc_client as pmc_client
from processor import ReachProcessor
def process_pmc(pmc_id):
xml_str = pmc_client.get_xml(pmc_id)
with tempfile.NamedTemporaryFile() ... | json_str = res.read()
json_dict = json.loads(json_str)
return process_json_str(json_str, events_only=False)
def process_json_file(file_name):
try:
with open(file_name, 'rt') as fh:
json_str = fh.read()
return process_json_str(json_str)
except IOError:
... | if offline:
base = os.path.basename(file_name)
file_id = os.path.splitext(base)[0]
if use_tempdir:
tmp_dir = tempfile.mkdtemp()
else:
tmp_dir = '.'
try:
paper_reader = autoclass('edu.arizona.sista.reach.ReadPaper')
paper_reader.main... | identifier_body |
reach_api.py | import os
import json
import tempfile
import urllib, urllib2
import requests
from indra.java_vm import autoclass, JavaException
import indra.databases.pmc_client as pmc_client
from processor import ReachProcessor
def process_pmc(pmc_id):
xml_str = pmc_client.get_xml(pmc_id)
with tempfile.NamedTemporaryFile() ... | rp.get_phosphorylation()
rp.get_complexes()
return rp
if __name__ == '__main__':
rp = process_json_file('PMC0000001.uaz.events.json') | events_json_str = events_json_str.replace('argument-label','argument_label')
events_json_str = events_json_str.replace('object-meta','object_meta')
events_json_str = events_json_str.replace('doc-id','doc_id')
json_dict = json.loads(events_json_str)
rp = ReachProcessor(json_dict) | random_line_split |
reach_api.py | import os
import json
import tempfile
import urllib, urllib2
import requests
from indra.java_vm import autoclass, JavaException
import indra.databases.pmc_client as pmc_client
from processor import ReachProcessor
def process_pmc(pmc_id):
xml_str = pmc_client.get_xml(pmc_id)
with tempfile.NamedTemporaryFile() ... |
def process_json_file(file_name):
try:
with open(file_name, 'rt') as fh:
json_str = fh.read()
return process_json_str(json_str)
except IOError:
print 'Could not read file %s.' % file_name
def process_json_str(json_str, events_only=True):
if not events_only:
... | url = 'http://agathon.sista.arizona.edu:8080/odinweb/api/nxml'
txt = open(file_name, 'rt').read()
req = urllib2.Request(url, data=urllib.urlencode({'nxml': txt}))
res = urllib2.urlopen(req)
json_str = res.read()
json_dict = json.loads(json_str)
return process_json_str(jso... | conditional_block |
reach_api.py | import os
import json
import tempfile
import urllib, urllib2
import requests
from indra.java_vm import autoclass, JavaException
import indra.databases.pmc_client as pmc_client
from processor import ReachProcessor
def process_pmc(pmc_id):
xml_str = pmc_client.get_xml(pmc_id)
with tempfile.NamedTemporaryFile() ... | (txt, use_tempdir=False, offline=False):
if offline:
nxml_txt = '<article><body><sec><p>%s</p></sec></body></article>' % txt
tmp_file = tempfile.NamedTemporaryFile()
tmp_file.file.write(nxml_txt)
tmp_file.file.flush()
return process_nxml(tmp_file.name)
else:
url =... | process_text | identifier_name |
sky.js | var fs = require('fs');
var mysql = require('mysql');
var qs = require('querystring');
var express = require('express');
var config = JSON.parse(fs.readFileSync(__dirname+'/config.json', 'UTF-8'));
// -----------------------------------------------------------------------------
// Keep a persistant connection to the ... | app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// -----------------------------------------------------------------------------
// API Endpoint to receive data
// ------------... | // ==================================================
// Below this point are URIs that are accesible from outside, in REST API calls
// ==================================================
| random_line_split |
sky.js |
var fs = require('fs');
var mysql = require('mysql');
var qs = require('querystring');
var express = require('express');
var config = JSON.parse(fs.readFileSync(__dirname+'/config.json', 'UTF-8'));
// -----------------------------------------------------------------------------
// Keep a persistant connection to the... | {
return typeof obj != 'undefined';
} | identifier_body | |
sky.js |
var fs = require('fs');
var mysql = require('mysql');
var qs = require('querystring');
var express = require('express');
var config = JSON.parse(fs.readFileSync(__dirname+'/config.json', 'UTF-8'));
// -----------------------------------------------------------------------------
// Keep a persistant connection to the... | (req, callback){
var body = '';
req.on('data', function (data){
body += data;
if (body.length > 1e8)
req.connection.destroy();
});
req.on('end', function (data){
var post = body;
try{
post = JSON.parse(post);
}
catch(e){
try{
post = qs.parse(post);
}
catch(e){}
}
callback(post);
... | handlePost | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
import re
from setuptools import setup
if sys.argv[-1] == "publish":
|
packages = [
"the_big_username_blacklist"
]
# Handle requirements
install_requires = []
tests_requires = [
"pytest==3.0.5",
]
# Convert markdown to rst
try:
from pypandoc import convert
long_description = convert("README.md", "rst")
except:
long_description = ""
version = ''
with io.open('th... | os.system("python setup.py sdist upload")
sys.exit() | conditional_block |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
import re
from setuptools import setup
if sys.argv[-1] == "publish":
os.system("python setup.py sdist upload")
sys.exit()
packages = [
"the_big_username_blacklist"
]
# Handle requirements
install_requires = []
tests_requires... |
version = ''
with io.open('the_big_username_blacklist/__init__.py', 'r', encoding='utf-8') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
setup(
name="the_big_username_blacklist",
version=version,
description="Validate us... | except:
long_description = ""
| random_line_split |
15.4.4.15-5-20.js | /// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the fol... | /// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
| random_line_split | |
effect.rs | // Copyright 2012-2013 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-MI... | ty::ty_bare_fn(ref f) => f.purity == ast::unsafe_fn,
ty::ty_closure(ref f) => f.purity == ast::unsafe_fn,
_ => false,
}
}
struct EffectCheckVisitor {
tcx: ty::ctxt,
/// The method map.
method_map: method_map,
/// Whether we're in an unsafe context.
unsafe_context: Unsaf... | UnsafeBlock(ast::NodeId),
}
fn type_is_unsafe_function(ty: ty::t) -> bool {
match ty::get(ty).sty { | random_line_split |
effect.rs | // Copyright 2012-2013 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-MI... | (tcx: ty::ctxt,
method_map: method_map,
crate: &ast::Crate) {
let mut visitor = EffectCheckVisitor {
tcx: tcx,
method_map: method_map,
unsafe_context: SafeContext,
};
visit::walk_crate(&mut visitor, crate, ());
}
| check_crate | identifier_name |
effect.rs | // Copyright 2012-2013 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-MI... |
ast::ExprAssign(base, _) | ast::ExprAssignOp(_, _, base, _) => {
self.check_str_index(base);
}
ast::ExprAddrOf(ast::MutMutable, base) => {
self.check_str_index(base);
}
ast::ExprInlineAsm(*) => {
self.require_un... | {
let base_type = ty::node_id_to_type(self.tcx, base.id);
debug2!("effect: unary case, base type is {}",
ppaux::ty_to_str(self.tcx, base_type));
match ty::get(base_type).sty {
ty::ty_ptr(_) => {
self.requ... | conditional_block |
service.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... |
service._context = context
service.obj_reset_changes()
return service
@classmethod
def _from_db_objects(cls, context, list_obj):
return [cls._from_db_object(context, cls(context), obj)
for obj in list_obj]
@classmethod
def get_by_id(cls, context, servic... | service[field] = db_service[field] | conditional_block |
service.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | return cls._from_db_objects(
context,
db_api.service_get_all_by_args(context,
host,
binary,
topic)) | identifier_body | |
service.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... |
@classmethod
def create(cls, context, values):
return cls._from_db_object(
context,
cls(),
db_api.service_create(context, values))
@classmethod
def update_by_id(cls, context, service_id, values):
return cls._from_db_object(
context,
... | return service | random_line_split |
service.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | (cls, context, values):
return cls._from_db_object(
context,
cls(),
db_api.service_create(context, values))
@classmethod
def update_by_id(cls, context, service_id, values):
return cls._from_db_object(
context,
cls(),
db_api... | create | identifier_name |
vs_metadata.py | __author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>'
import xml.etree.ElementTree as ET
import dateutil.parser
from .vidispine_api import always_string
class VSMetadata:
def __init__(self, initial_data={}):
self.contentDict=initial_data
self.primaryGroup = None
def | (self,key,value):
if key in self.contentDict:
self.contentDict[key].append(value)
else:
self.contentDict[key]=[]
self.contentDict[key].append(value)
def setPrimaryGroup(self,g):
self.primaryGroup = g
def toXML(self,mdGroup=None):
from datetim... | addValue | identifier_name |
vs_metadata.py | __author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>'
import xml.etree.ElementTree as ET
import dateutil.parser
from .vidispine_api import always_string
class VSMetadata:
def __init__(self, initial_data={}):
self.contentDict=initial_data
self.primaryGroup = None
def addValue(self,key... |
for key,value in list(self.contentDict.items()):
fieldEl=ET.Element('{0}field'.format(ns))
nameEl=ET.Element('{0}name'.format(ns))
nameEl.text = key
fieldEl.append(nameEl)
if not isinstance(value,list):
value = [value]
... | groupEl=ET.Element('{0}group'.format(ns))
groupEl.text=mdGroup
rootEl.append(groupEl) | conditional_block |
vs_metadata.py | __author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>'
import xml.etree.ElementTree as ET
import dateutil.parser
from .vidispine_api import always_string
class VSMetadata:
def __init__(self, initial_data={}):
self.contentDict=initial_data
self.primaryGroup = None
def addValue(self,key... |
class VSMetadataValue(VSMetadataMixin):
def __init__(self, valuenode=None, uuid=None):
self.user = None
self.uuid = None
self.timestamp = None
self.change = None
self.value = None
if valuenode is not None:
self.uuid = self._safe_get_attrib(valuenode,"u... | try:
node = xmlnode.find(subnode_name)
if node is not None:
return node.text
else:
return default
except AttributeError:
return default | identifier_body |
vs_metadata.py | __author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>'
import xml.etree.ElementTree as ET
import dateutil.parser
from .vidispine_api import always_string
class VSMetadata:
def __init__(self, initial_data={}):
self.contentDict=initial_data
self.primaryGroup = None
def addValue(self,key... | :param refnode: pointer to an elementtree node of <referenced> in a MetadataDocument
"""
if refnode is not None:
self.uuid = self._safe_get_attrib(refnode,"uuid",None)
self.id = self._safe_get_attrib(refnode,"id",None)
self.type = self._safe_get_attrib(refnode... | """
Initialises, either to an empty reference, to an existing uuid or to an xml fragment
:param uuid: string representing the uuid of something to reference | random_line_split |
ignore_test.py | # Created By: Virgil Dupras
# Created On: 2006/05/02
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... |
def test_clear():
il = IgnoreList()
il.Ignore('foo','bar')
il.Clear()
assert not il.AreIgnored('foo','bar')
assert not il.AreIgnored('bar','foo')
eq_(0,len(il))
def test_add_same_twice():
il = IgnoreList()
il.Ignore('foo','bar')
il.Ignore('bar','foo')
eq_(1,len(il))
def test_... | il = IgnoreList()
il.Ignore('foo','bar')
il.Ignore('foo','bleh')
il.Ignore('bleh','bar')
il.Ignore('aybabtu','bleh')
assert il.AreIgnored('foo','bar')
assert il.AreIgnored('bar','foo')
assert il.AreIgnored('foo','bleh')
assert il.AreIgnored('bleh','bar')
assert not il.AreIgnored('ayb... | identifier_body |
ignore_test.py | # Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
import io
from xml.etree import ElementT... | # Created By: Virgil Dupras
# Created On: 2006/05/02 | random_line_split | |
ignore_test.py | # Created By: Virgil Dupras
# Created On: 2006/05/02
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | ():
il = IgnoreList()
il.Ignore('foo','bar')
il.Clear()
assert not il.AreIgnored('foo','bar')
assert not il.AreIgnored('bar','foo')
eq_(0,len(il))
def test_add_same_twice():
il = IgnoreList()
il.Ignore('foo','bar')
il.Ignore('bar','foo')
eq_(1,len(il))
def test_save_to_xml():
... | test_clear | identifier_name |
ignore_test.py | # Created By: Virgil Dupras
# Created On: 2006/05/02
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... |
assert not expected #expected should be empty
def test_filter():
il = IgnoreList()
il.Ignore('foo','bar')
il.Ignore('bar','baz')
il.Ignore('foo','baz')
il.Filter(lambda f,s: f == 'bar')
eq_(1,len(il))
assert not il.AreIgnored('foo','bar')
assert il.AreIgnored('bar','baz')
def test... | expected.remove(i) #No exception should be raised | conditional_block |
mod.rs | pub mod elf_parser;
use cpuio::Port;
macro_rules! raw_ptr {
(u8 $ptr:expr ; $offset:expr) => (
*(($ptr as *const u8).offset($offset / 1))
);
(u16 $ptr:expr ; $offset:expr) => (
*(($ptr as *const u16).offset($offset / 2))
);
(u32 $ptr:expr ; $offset:expr) => (
*(($ptr as *co... | };
}
macro_rules! sizeof {
($t:ty) => {{ ::core::mem::size_of::<$t>() }};
} | } | random_line_split |
lightbox.js | module.exports = Lightbox;
/**
* Lightbox with default configuration to
* lightbox all webhook wysiwyg generated
*
* - Adds a lightbox container to the DOM.
* - Adds a new image tag in the lightbox container
* for each lightbox image.
* - Adds click events for preventing the default
* image wrapping anchor... |
};
/**
* Decorate targets with lightbox attributes, to attach lightbox
* functionality to thme.
* Returns $decorated based on the selector.
*
* @param {string|object} $query jQuery selector or string of
* selector query
* @return {object} $decorated
*/
Lightbox.prototype.decora... | {
var innerImage = $(element).find('img').get(0);
if (innerImage) {
if (innerImage.dataset.hasOwnProperty('resizeSrc')) {
return innerImage.dataset.resizeSrc + '=s1200';
}
else {
return element.href;
}
}
} | identifier_body |
lightbox.js | module.exports = Lightbox;
/**
* Lightbox with default configuration to
* lightbox all webhook wysiwyg generated | * for each lightbox image.
* - Adds click events for preventing the default
* image wrapping anchor tag, and enables the
* lightbox instead
*
* elements on a page.
* @param {object} opts
* @param {string} opts.decorate Query selector string for all a tags
* that contain imag... | *
* - Adds a lightbox container to the DOM.
* - Adds a new image tag in the lightbox container | random_line_split |
lightbox.js | module.exports = Lightbox;
/**
* Lightbox with default configuration to
* lightbox all webhook wysiwyg generated
*
* - Adds a lightbox container to the DOM.
* - Adds a new image tag in the lightbox container
* for each lightbox image.
* - Adds click events for preventing the default
* image wrapping anchor... | (base) {
function element (element) {
if (!element) return base;
function modifier (modifier) {
var baseElement = [base, element].join('__');
if (!modifier) return baseElement;
return function () {
return [baseElement, modifier].join('--');
}
}
return modifier;
}
... | bem | identifier_name |
device.py | modified scroll action", u"Pan"),
}
class Settings (object):
"""A device's settings"""
DEFAULT_USAGE = AllowedUsage.VALUES[0]
DEFAULT_SCROLL = ScrollAction.VALUES[0]
def __init__(self, prefs, usage=DEFAULT_USAGE, scroll=DEFAULT_SCROLL):
super(Settings, self).__init__()
self._usag... |
## Devices list
def get_device_settings(self, device):
"""Gets the settings for a device
:param Gdk.Device device: a physical ("slave") device
:returns: A settings object which can be manipulated, or None
:rtype: Settings
Changes to the returned object made via its A... | self._init_device_settings(physical_device) | conditional_block |
device.py | modified scroll action", u"Pan"),
}
class Settings (object):
"""A device's settings"""
DEFAULT_USAGE = AllowedUsage.VALUES[0]
DEFAULT_SCROLL = ScrollAction.VALUES[0]
def __init__(self, prefs, usage=DEFAULT_USAGE, scroll=DEFAULT_SCROLL):
super(Settings, self).__init__()
self._usag... | (self):
"""Yields devices and their settings, for UI stuff
:rtype: iterator
:returns: ultimately a sequence of (Gdk.Device, Settings) pairs
"""
for device, settings in self._device_settings.items():
yield (device, settings)
## Current device
@event
def... | get_devices | identifier_name |
device.py | user preferences immediately.
If the device is a keyboard, or is otherwise unsuitable as a
pointing device, None is returned instead. The caller needs to
check this case.
"""
return (self._device_settings.get(device)
or self._init_device_settings(device))
... | # Scroll action config value => string store (dropdowns)
store = Gtk.ListStore(str, str)
for conf_val in ScrollAction.VALUES:
string = ScrollAction.DISPLAY_STRING[conf_val]
store.append([conf_val, string]) | random_line_split | |
device.py | return False
if device == self._last_event_device:
return True
self.current_device_changed(self._last_event_device, device)
old_device = self._last_event_device
new_device = device
self._last_event_device = device
# small problem with this code: i... | ce = model.get_value(iter_, 0)
settings = self._monitor.get_device_settings(device)
if not settings:
return
text = ScrollAction.DISPLAY_STRING[settings.scroll]
cell.set_property("text", text)
| identifier_body | |
simplequerystring.py | __author__ = 'Joe Linn'
from pylastica.query.abstract import AbstractQuery
class SimpleQueryString(AbstractQuery):
"""
@see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
"""
OPERATOR_AND = "and"
OPERATOR_OR = "or"
def __init__(... | """
return self.set_param("fields", fields)
def set_default_operator(self, operator):
"""
Set the default operator to use if no explicit operator is defined in the query string
@param operator: see OPERATOR_* constants for options
@type operator: str
@return:... | @param fields: the fields on which to perform this query. Defaults to index.query.default_field.
@type fields: list of str
@return:
@rtype: self | random_line_split |
simplequerystring.py | __author__ = 'Joe Linn'
from pylastica.query.abstract import AbstractQuery
class SimpleQueryString(AbstractQuery):
"""
@see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
"""
OPERATOR_AND = "and"
OPERATOR_OR = "or"
def __init__(... |
def set_query(self, query):
"""
Set the querystring for this query
@param query: see linked documentation for querystring syntax
@type query: str
@return:
@rtype: self
"""
return self.set_param("query", query)
def set_fields(self, fields):
... | self.set_fields(fields) | conditional_block |
simplequerystring.py | __author__ = 'Joe Linn'
from pylastica.query.abstract import AbstractQuery
class SimpleQueryString(AbstractQuery):
"""
@see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
"""
OPERATOR_AND = "and"
OPERATOR_OR = "or"
def __init__(... | (self, operator):
"""
Set the default operator to use if no explicit operator is defined in the query string
@param operator: see OPERATOR_* constants for options
@type operator: str
@return:
@rtype: self
"""
return self.set_param("default_operator", opera... | set_default_operator | identifier_name |
simplequerystring.py | __author__ = 'Joe Linn'
from pylastica.query.abstract import AbstractQuery
class SimpleQueryString(AbstractQuery):
"""
@see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html
"""
OPERATOR_AND = "and"
OPERATOR_OR = "or"
def __init__(... |
def set_default_operator(self, operator):
"""
Set the default operator to use if no explicit operator is defined in the query string
@param operator: see OPERATOR_* constants for options
@type operator: str
@return:
@rtype: self
"""
return self.set_p... | """
@param fields: the fields on which to perform this query. Defaults to index.query.default_field.
@type fields: list of str
@return:
@rtype: self
"""
return self.set_param("fields", fields) | identifier_body |
tx-decoder.js | /**
* This `decodeTx` decodes a bitcoin transaction. Its an example of how to use the composable helpers
* to make a decoder.
*/
const bitcoin = require('bitcoinjs-lib')
const bcrypto = bitcoin.crypto
const sha3_256 = require('js-sha3').sha3_256 // eslint-disable-line
const { compose, addProp } = requi... | addresses: [ bitcoin.address.fromOutputScript(scriptBuffer) ]
}, bufferLeft ]
}
// decodeTx :: Buffer -> [Object, Buffer]
const decodeTx = buffer =>
(
compose([
addProp('version', readInt32), // 4 bytes
addProp('vin', readInputs(readInput)), // 1-9 bytes (VarInt), Input counter; Variable,... | return [ {
hex: scriptBuffer.toString('hex'),
type: scriptBuffer[0] === bitcoin.opcodes.OP_DUP && scriptBuffer[1] === bitcoin.opcodes.OP_HASH160 ? 'pubkeyhash' : 'nonstandard',
asm: bitcoin.script.toASM(scriptBuffer), | random_line_split |
tx-decoder.js | /**
* This `decodeTx` decodes a bitcoin transaction. Its an example of how to use the composable helpers
* to make a decoder.
*/
const bitcoin = require('bitcoinjs-lib')
const bcrypto = bitcoin.crypto
const sha3_256 = require('js-sha3').sha3_256 // eslint-disable-line
const { compose, addProp } = requi... |
return [vins, bufferLeft]
}
// readScript :: Buffer -> [ScriptPubKey, Buffer]
const readScript = buffer => {
const [ scriptBuffer, bufferLeft ] = readVarSlice(buffer)
return [ {
hex: scriptBuffer.toString('hex'),
type: scriptBuffer[0] === bitcoin.opcodes.OP_DUP && scriptBuffer[1] === bitcoin.opcodes.OP... | {
[vin, bufferLeft] = readFn(bufferLeft)
vins.push(vin)
} | conditional_block |
boxplus.transition.js | __ = jQuery;
}
(function ($) {
var CLASS_DISABLED = 'boxplus-disabled';
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
/**
* Maximum computed width of matched elements including margin, border and padding.
*/
$.fn.maxWidth = function () {
var width = 0;
this.each( function(index, el) {
... | () {
return scroll('prev');
}
function scrollNext() {
return scroll('next');
}
function scrollLast() {
return scroll('last');
}
/**
* Sets the image shown as the background image of elements.
* @param elem The element whose background-image property to set.
*/
function _setI... | scrollPrevious | identifier_name |
boxplus.transition.js | = jQuery;
}
(function ($) {
var CLASS_DISABLED = 'boxplus-disabled';
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
/**
* Maximum computed width of matched elements including margin, border and padding.
*/
$.fn.maxWidth = function () {
var width = 0;
this.each( function(index, el) {
... |
/**
* Execute image transition.
*/
function scroll(dir) {
var bars = $('.boxplus-transition-bars', container);
if (animation) { // clear ongoing transitions
_setImage(container, 0, 0);
bars.clearQueue().stop().css('visibility', 'hidden');
}
animation = true; // indicate an ong... | {
_preloadImage(items.eq(sliderIndexPosition));
_preloadImage(items.eq((sliderIndexPosition - 1) % itemCount));
_preloadImage(items.eq((sliderIndexPosition + 1) % itemCount));
} | identifier_body |
boxplus.transition.js | = jQuery;
}
(function ($) {
var CLASS_DISABLED = 'boxplus-disabled';
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
/**
* Maximum computed width of matched elements including margin, border and padding.
*/
$.fn.maxWidth = function () {
var width = 0;
this.each( function(index, el) {
... |
}
function _preloadImages() {
_preloadImage(items.eq(sliderIndexPosition));
_preloadImage(items.eq((sliderIndexPosition - 1) % itemCount));
_preloadImage(items.eq((sliderIndexPosition + 1) % itemCount));
}
/**
* Execute image transition.
*/
function scroll(dir) {
var bars = $('.b... | { // higher-resolution image is available
item.attr('src', longdesc).attr('longdesc', '');
} | conditional_block |
boxplus.transition.js | = max(width, $(el).safeWidth());
});
return width;
}
/**
* Maximum computed height of matched elements including margin, border and padding.
*/
$.fn.maxHeight = function () {
var height = 0;
this.each( function(index, el) {
height = max(height, $(el).safeHeight());
});
return height;
}
/**
* "... | });
var position = bar.position();
_setImage(bar, position.left, position.top); | random_line_split | |
btc.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Btc plugin for Varas
Author: Neon & A Sad Loner
Last modified: November 2016
"""
import urllib2
from plugin import Plugin
name = 'Bitcoin'
class Bitcoin(Plugin):
| def __init__(self):
Plugin.__init__(self,"bitcoin","<wallet> Return current balance from a Bitcoin wallet","A Sad Loners",1.0)
def run(self,address):
#1btc = 100000000satoshi
print "https://blockchain.info/it/q/addressbalance/"+address
try:
api = urllib2.urlopen("https://blockch... | identifier_body | |
btc.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Btc plugin for Varas
Author: Neon & A Sad Loner
Last modified: November 2016
"""
import urllib2 |
class Bitcoin(Plugin):
def __init__(self):
Plugin.__init__(self,"bitcoin","<wallet> Return current balance from a Bitcoin wallet","A Sad Loners",1.0)
def run(self,address):
#1btc = 100000000satoshi
print "https://blockchain.info/it/q/addressbalance/"+address
try:
api = ... | from plugin import Plugin
name = 'Bitcoin'
| random_line_split |
btc.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Btc plugin for Varas
Author: Neon & A Sad Loner
Last modified: November 2016
"""
import urllib2
from plugin import Plugin
name = 'Bitcoin'
class Bitcoin(Plugin):
def | (self):
Plugin.__init__(self,"bitcoin","<wallet> Return current balance from a Bitcoin wallet","A Sad Loners",1.0)
def run(self,address):
#1btc = 100000000satoshi
print "https://blockchain.info/it/q/addressbalance/"+address
try:
api = urllib2.urlopen("https://blockchain.info/it/... | __init__ | identifier_name |
SetupStore.ts | import alt, { AbstractStoreModel } from '../alt';
import * as _ from 'lodash';
import connections from '../data-sources/connections';
import { DataSourceConnector, IDataSourceDictionary } from '../data-sources';
import SetupActions from '../actions/SetupActions';
export interface ISetupStoreState extends ISetupConfig... |
this.loaded = true;
this.saveSuccess = true;
setTimeout(() => { this.saveSuccess = false; }, 500);
}
}
const setupStore = alt.createStore<ISetupStoreState>(SetupStore, 'SetupStore');
export default setupStore;
| {
this.admins = setupConfig.admins;
this.stage = setupConfig.stage;
this.enableAuthentication = setupConfig.enableAuthentication;
this.allowHttp = setupConfig.allowHttp;
this.redirectUrl = setupConfig.redirectUrl;
this.clientID = setupConfig.clientID;
this.clientSecret = setupC... | conditional_block |
SetupStore.ts | import alt, { AbstractStoreModel } from '../alt';
import * as _ from 'lodash';
import connections from '../data-sources/connections';
import { DataSourceConnector, IDataSourceDictionary } from '../data-sources';
import SetupActions from '../actions/SetupActions';
export interface ISetupStoreState extends ISetupConfig... | () {
super();
this.admins = [];
this.stage = '';
this.enableAuthentication = false;
this.allowHttp = false;
this.redirectUrl = '';
this.clientID = '';
this.clientSecret = '';
this.loaded = false;
this.saveSuccess = false;
this.issuer = '';
this.bindListeners({
loa... | constructor | identifier_name |
SetupStore.ts | import alt, { AbstractStoreModel } from '../alt';
import * as _ from 'lodash';
import connections from '../data-sources/connections';
import { DataSourceConnector, IDataSourceDictionary } from '../data-sources';
import SetupActions from '../actions/SetupActions';
export interface ISetupStoreState extends ISetupConfig... | loaded: boolean;
saveSuccess: boolean;
}
class SetupStore extends AbstractStoreModel<ISetupStoreState> implements ISetupStoreState {
admins: string[];
stage: string;
enableAuthentication: boolean;
allowHttp: boolean;
redirectUrl: string;
clientID: string;
clientSecret: string;
issuer: string;
lo... | random_line_split | |
fetch_command.rs | extern crate zip;
use std::fs::{create_dir, create_dir_all, File};
use std::io::{Cursor, Read, Write};
use std::path::{Path, PathBuf};
use curl::http;
use rustc_serialize::json::Json;
use zip::read::ZipArchive;
use version;
use commands::command::Command;
pub struct FetchCommand<'a> {
slice_root_directory: &'a Pat... | (uri: &str) -> Vec<u8> {
let mut handle = http::handle();
let request = handle.get(uri).header("user-agent", "Mozilla/4.0 (compatible)");
let response = request.exec().unwrap();
response.move_body()
}
fn determine_latest_version() -> String {
let body = FetchCommand::exe... | execute_request_to_uri | identifier_name |
fetch_command.rs | extern crate zip;
use std::fs::{create_dir, create_dir_all, File};
use std::io::{Cursor, Read, Write};
use std::path::{Path, PathBuf};
use curl::http;
use rustc_serialize::json::Json;
use zip::read::ZipArchive;
use version;
use commands::command::Command;
pub struct FetchCommand<'a> {
slice_root_directory: &'a Pat... |
fn write_bytes_to_temporary_file(bytes: &[u8], file_path: &PathBuf) {
let _ = create_dir(file_path.parent().unwrap());
let mut file = File::create(file_path).unwrap();
let _ = file.write(bytes);
}
}
impl<'a> Command for FetchCommand<'a> {
fn run(&mut self) {
let bytes = Fe... | {
for i in 0..zip_archive.len() {
let mut path = path.clone();
let mut file = zip_archive.by_index(i).unwrap();
{
let file_name = file.name();
path.push(file_name);
}
if file.size() != 0 {
let _ = create_... | identifier_body |
fetch_command.rs | extern crate zip;
use std::fs::{create_dir, create_dir_all, File};
use std::io::{Cursor, Read, Write};
use std::path::{Path, PathBuf};
use curl::http;
use rustc_serialize::json::Json;
use zip::read::ZipArchive;
use version;
use commands::command::Command;
pub struct FetchCommand<'a> {
slice_root_directory: &'a Pat... | let response = request.exec().unwrap();
response.move_body()
}
fn determine_latest_version() -> String {
let body = FetchCommand::execute_request_to_uri("https://api.github.\
com/repos/slicebuild/slices/branches");
let bod... |
fn execute_request_to_uri(uri: &str) -> Vec<u8> {
let mut handle = http::handle();
let request = handle.get(uri).header("user-agent", "Mozilla/4.0 (compatible)"); | random_line_split |
saddle.py | #!/usr/bin/python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
Print = PETSc.Sys.Print
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sps
import scipy.sparse.linalg as slinalg
import os
import scipy.io
i... | else:
l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1]))
Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1]))
print errL2b[xx-1]
print errCurlb[xx-1]
import pandas as pd
print "\n\n Magnetic convergence"
MagneticTitles = ["Total DoF","Sol... | a = 1 | random_line_split |
saddle.py | #!/usr/bin/python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
Print = PETSc.Sys.Print
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sps
import scipy.sparse.linalg as slinalg
import os
import scipy.io
i... |
if case == 1:
u0 = Expression(("x[1]*x[1]*(x[1]-1)","x[0]*x[0]*(x[0]-1)","0"))
elif case == 2:
u0 = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])","-sin(2*pi*x[0])*cos(2*pi*x[1])"))
elif case == 3:
u0 = Expression(("x[0]*x[0]*(x[0]-1)","x[1]*x[1]*(x[1]-1)","0"))
elif case == 4:
... | return on_boundary | identifier_body |
saddle.py | #!/usr/bin/python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
Print = PETSc.Sys.Print
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sps
import scipy.sparse.linalg as slinalg
import os
import scipy.io
i... | (x, on_boundary):
return on_boundary
if case == 1:
u0 = Expression(("x[1]*x[1]*(x[1]-1)","x[0]*x[0]*(x[0]-1)","0"))
elif case == 2:
u0 = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])","-sin(2*pi*x[0])*cos(2*pi*x[1])"))
elif case == 3:
u0 = Expression(("x[0]*x[0]*(x[0]-1)","x[1... | boundary | identifier_name |
saddle.py | #!/usr/bin/python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
Print = PETSc.Sys.Print
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sps
import scipy.sparse.linalg as slinalg
import os
import scipy.io
i... |
else:
if (xx != 1):
MU[xx-1] = MU[xx-2]
# Create mesh and define function space
nn = int(nn)
NN[xx-1] = nn
parameters["form_compiler"]["quadrature_degree"] = 3
parameters["form_compiler"]["optimize"] = True
parameters["form_compiler"]["representation"] = 'quadrature'
... | MU[xx-1] = MU[xx-2]/10 | conditional_block |
hotkeyUtils.js | ets';
// TODO: add this to namespace definitions
Meteor.startup(function() {
if (!OHIF.viewer) {
OHIF.viewer = {};
}
OHIF.viewer.loadIndicatorDelay = 200;
OHIF.viewer.defaultTool = 'wwwc';
OHIF.viewer.refLinesEnabled = true;
OHIF.viewer.isPlaying = {};
OHIF.viewer.cine = {
... | (hotkeysActions) {
// Merge hotkeys, overriding OHIF's settings
let mergedHotkeys = {
...OHIF.viewer.defaultHotkeys,
...hotkeysActions
};
const defaultHotkeys = OHIF.viewer.defaultHotkeys;
const hotkeysKeys = Object.keys(hotkeysActions);
// Check for conflicts with same keys bu... | mergeHotkeys | identifier_name |
hotkeyUtils.js | ets';
// TODO: add this to namespace definitions
Meteor.startup(function() {
if (!OHIF.viewer) {
OHIF.viewer = {};
}
OHIF.viewer.loadIndicatorDelay = 200;
OHIF.viewer.defaultTool = 'wwwc';
OHIF.viewer.refLinesEnabled = true;
OHIF.viewer.isPlaying = {};
OHIF.viewer.cine = {
... | ,
dragProbe() {
toolManager.setActiveTool('dragProbe');
},
ellipticalRoi() {
toolManager.setActiveTool('ellipticalRoi');
},
magnify() {
toolManager.setActiveTool('magnify');
},
annotate() {
toolManager.setActiveTool(... | {
toolManager.setActiveTool('angle');
} | identifier_body |
hotkeyUtils.js | ets';
// TODO: add this to namespace definitions
Meteor.startup(function() {
if (!OHIF.viewer) {
OHIF.viewer = {};
}
OHIF.viewer.loadIndicatorDelay = 200;
OHIF.viewer.defaultTool = 'wwwc';
OHIF.viewer.refLinesEnabled = true;
OHIF.viewer.isPlaying = {};
OHIF.viewer.cine = {
... |
});
});
return mergedHotkeys;
}
/**
* Add an active class to a button for 100ms only
* to give the impressiont the button was pressed.
* This is for tools that don't keep the button "pressed"
* all the time the tool is active.
*
* @param button DOM Element for the button to be "flashed"
*/
f... | {
delete mergedHotkeys[ohifAction];
} | conditional_block |
hotkeyUtils.js | resets';
// TODO: add this to namespace definitions
Meteor.startup(function() {
if (!OHIF.viewer) {
OHIF.viewer = {};
}
OHIF.viewer.loadIndicatorDelay = 200;
OHIF.viewer.defaultTool = 'wwwc';
OHIF.viewer.refLinesEnabled = true;
OHIF.viewer.isPlaying = {};
OHIF.viewer.cine = {
... | scrollFirstImage() {
const container = $('.viewportContainer.active');
if (!container.find('.imageViewerViewport').hasClass('empty')) {
switchToImageByIndex(0);
}
},
scrollLastImage() {
const container = $('.viewportContainer.active... | if (!container.find('.imageViewerViewport').hasClass('empty')) {
flashButton(button);
switchToImageRelative(1);
}
}, | random_line_split |
authController.js | angular
.module('app')
.controller('authController', ['$scope', '$location', '$log', 'userModel', 'userService', 'session', 'storageService', function($scope, $location, $log, userModel, userService, session, storageService) {
if(session){
storageService.populateStorageData(session);
... | if (userModel.collection) {
getUserCollection(userModel);
}else{
userService.Users.query(function(data) {
var users = TAFFY(data);
var user = users({id: userModel.id}).first();
// User has Collection?
... |
if(userModel.id) { | random_line_split |
authController.js | angular
.module('app')
.controller('authController', ['$scope', '$location', '$log', 'userModel', 'userService', 'session', 'storageService', function($scope, $location, $log, userModel, userService, session, storageService) {
if(session){
storageService.populateStorageData(session);
... |
function getUserCollection(user){
userService.userCollection.query({
userCollection: user.collection
}, function(data) {
userService.userModel.id = user.id;
userService.userModel.name = user.name;
userService.userModel.use... | {
if(session){
storageService.createSession(session);
}
} | identifier_body |
authController.js | angular
.module('app')
.controller('authController', ['$scope', '$location', '$log', 'userModel', 'userService', 'session', 'storageService', function($scope, $location, $log, userModel, userService, session, storageService) {
if(session){
storageService.populateStorageData(session);
... | createSession();
redirectToUserPage(userModel.username);
});
}
});
}
}else{
redirectToUserPage('')
}
function createSession(){
if(session){
... | {
// create a Default User Collection
userService.postUserCollection.save(userModel.cards, function(data) {
userModel.collection = data.uri.substr(data.uri.lastIndexOf('/') + 1);
// User has same name than another?
... | conditional_block |
authController.js | angular
.module('app')
.controller('authController', ['$scope', '$location', '$log', 'userModel', 'userService', 'session', 'storageService', function($scope, $location, $log, userModel, userService, session, storageService) {
if(session){
storageService.populateStorageData(session);
... | (username){
userService.destroyNeighbor();
userService.userModel.preview = false;
$location.path("/" + username);
}
}]);
| redirectToUserPage | identifier_name |
main.py | % (self.__class__.__name__, self.file, self.build)
def __contains__(self, id):
return id in self._addresses
def __getitem__(self, item):
if isinstance(item, slice):
keys = sorted(self._addresses.keys())[item]
return [self[k] for k in keys]
if item not in self._values:
self._parse_row(item)
retur... |
class DBRow(list):
"""
A database row.
Names of the variables of that class should not be used in field names of structures
"""
initialized = False
def __init__(self, parent, data=None, columns=None, reclen=0):
self._parent = parent
self._values = {} # Columns values storage
self.structure = parent.stru... | """
Write the file data on disk. If filename is not given, use currently opened file.
"""
_filename = filename or self.file.name
data = self.header.data() + self.data() + self.eof()
f = open(_filename, "wb") # Don't open before calling data() as uncached rows would be empty
f.write(data)
f.close()
log... | identifier_body |
main.py | % (self.__class__.__name__, self.file, self.build)
def __contains__(self, id):
return id in self._addresses
def __getitem__(self, item):
if isinstance(item, slice):
keys = sorted(self._addresses.keys())[item]
return [self[k] for k in keys]
if item not in self._values:
self._parse_row(item)
retur... | """
A database row.
Names of the variables of that class should not be used in field names of structures
"""
initialized = False
def __init__(self, parent, data=None, columns=None, reclen=0):
self._parent = parent
self._values = {} # Columns values storage
self.structure = parent.structure
self.initiali... | class DBRow(list): | random_line_split |
main.py | Master):
ret, = unpack("<I", data.read(4))
self._rowDynamicFields = ret
else:
ret, = unpack("<%s" % (field.char), data.read(field.size))
except StructError:
log.warning("Field %s could not be parsed properly" % (field))
ret = None
return ret
def supportsSeeking(self):
return hasattr(self.... | id | identifier_name | |
main.py | % (self.__class__.__name__, self.file, self.build)
def __contains__(self, id):
return id in self._addresses
def __getitem__(self, item):
if isinstance(item, slice):
keys = sorted(self._addresses.keys())[item]
return [self[k] for k in keys]
if item not in self._values:
self._parse_row(item)
retur... |
if reclen:
real_reclen = reclen + self._parent.row_header_size
if data.tell() != real_reclen:
log.warning("Reclen not respected for row %r. Expected %i, read %i. (%+i)" % (self.id, real_reclen, data.tell(), real_reclen-data.tell()))
def __dir__(self):
result = self.__dict__.keys()
result.extend(... | _data = parent._parse_field(data, field, self)
self.append(_data) | conditional_block |
basic-types.rs | // Copyright 2013 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 ... | () {()}
| _zzz | identifier_name |
basic-types.rs | // Copyright 2013 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 ... | {()} | identifier_body | |
basic-types.rs | // Copyright 2013 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 ... | // about UTF-32 character encoding and will print a rust char as only
// its numerical value.
// compile-flags:-Z extra-debug-info
// debugger:break _zzz
// debugger:run
// debugger:finish
// debugger:print b
// check:$1 = false
// debugger:print i
// check:$2 = -1
// debugger:print c
// check:$3 = 97
// debugger:prin... | // as its numerical value along with its associated ASCII char, there
// doesn't seem to be any way around this. Also, gdb doesn't know | random_line_split |
dst-index.rs | // Copyright 2014 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 ... | {
assert_eq!(&S[0], "hello");
&T[0];
// let x = &x as &Debug;
} | identifier_body | |
dst-index.rs | // Copyright 2014 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 ... | ;
impl Index<usize> for S {
type Output = str;
fn index<'a>(&'a self, _: usize) -> &'a str {
"hello"
}
}
struct T;
impl Index<usize> for T {
type Output = Debug + 'static;
fn index<'a>(&'a self, idx: usize) -> &'a (Debug + 'static) {
static X: usize = 42;
&X as &(Debug +... | S | identifier_name |
dst-index.rs | // Copyright 2014 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[0];
// let x = &x as &Debug;
} | }
fn main() {
assert_eq!(&S[0], "hello"); | random_line_split |
getLinks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
get url(): string {
return this._link.url;
}
resolve(): TPromise<URI> {
if (this._link.url) {
try {
return TPromise.as(URI.parse(this._link.url));
} catch (e) {
return TPromise.wrapError<URI>(new Error('invalid'));
}
}
if (typeof this._provider.resolveLink === 'function') {
return a... | random_line_split | |
getLinks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return TPromise.wrapError<URI>(new Error('missing'));
});
}
return TPromise.wrapError<URI>(new Error('missing'));
}
}
export function getLinks(model: ITextModel): TPromise<Link[]> {
let links: Link[] = [];
// ask all providers for links in parallel
const promises = LinkProviderRegistry.ordered(mode... | {
// recurse
return this.resolve();
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.