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
predictor_py_utils.py
## @package predictor_py_utils # Module caffe2.python.predictor.predictor_py_utils from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, scope def create_predict_net(predictor_export_meta): ...
net.Proto().external_input.extend(external_blobs) if predictor_export_meta.extra_init_net: net.AppendNet(predictor_export_meta.extra_init_net) # Add the model_id in the predict_net to the init_net AddModelIdArg(predictor_export_meta, net.Proto()) return net.Proto() def get_comp_name(st...
zero_fill(blob)
conditional_block
AddSliceContainer.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
}), ); return `/superset/explore/?form_data=${formData}`; } gotoSlice() { window.location.href = this.exploreUrl(); } changeDatasource(value: string) { this.setState({ datasourceValue: value, datasourceId: value.split('__')[0], }); } changeVisType(visType: string | n...
exploreUrl() { const formData = encodeURIComponent( JSON.stringify({ viz_type: this.state.visType, datasource: this.state.datasourceValue,
random_line_split
AddSliceContainer.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
(value: string) { this.setState({ datasourceValue: value, datasourceId: value.split('__')[0], }); } changeVisType(visType: string | null) { this.setState({ visType }); } isBtnDisabled() { return !(this.state.datasourceId && this.state.visType); } render() { return ( ...
changeDatasource
identifier_name
AddSliceContainer.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
exploreUrl() { const formData = encodeURIComponent( JSON.stringify({ viz_type: this.state.visType, datasource: this.state.datasourceValue, }), ); return `/superset/explore/?form_data=${formData}`; } gotoSlice() { window.location.href = this.exploreUrl(); } chang...
{ super(props); this.state = { visType: null, }; this.changeDatasource = this.changeDatasource.bind(this); this.changeVisType = this.changeVisType.bind(this); this.gotoSlice = this.gotoSlice.bind(this); }
identifier_body
decorators.ts
/** * Memorize the calculated result of a function by an ES6 Map; * the default is to memorize its the first argument; * @return the memorized version of a function. */ type memorize = <T, U extends any[]>(
resolver?: (...args: U) => unknown ) => (...args: U) => T; export const memorize: memorize = (fn, resolver) => { const memo = new Map(); return (...arg) => { const key = resolver ? resolver(...arg) : arg[0]; return memo.get(key) || memo.set(key, fn(...arg)).get(key); }; }; /** * Enforce a given funct...
fn: (...args: U) => T,
random_line_split
functions_11.js
var searchData= [ ['tan',['tan',['../a00151.html#gab3ae890c38b7d3aa4d5e00998fd296b2',1,'glm']]], ['tanh',['tanh',['../a00151.html#ga234e904a0075f88654a594b5f837711f',1,'glm']]], ['third',['third',['../a00162.html#ga3077c6311010a214b69ddc8214ec13b5',1,'glm']]], ['three_5fover_5ftwo_5fpi',['three_over_two_pi',['....
['tweakedinfiniteperspective',['tweakedInfinitePerspective',['../a00169.html#gaed64bd81f5ecdab52fecbdf7f6b58194',1,'glm::tweakedInfinitePerspective(T fovy, T aspect, T near)'],['../a00169.html#gaa50fce7f50b5d5da881ed30f5532a921',1,'glm::tweakedInfinitePerspective(T fovy, T aspect, T near, T ep)']]], ['two_5fover_5f...
random_line_split
GeoNetworkRecordSpec.js
/* * Copyright 2013 IMOS * * The AODN/IMOS Portal is distributed under the terms of the GNU General Public License * */ describe('Portal.data.GeoNetworkRecord', function() { var record; beforeEach(function() { record = new Portal.data.GeoNetworkRecord({ abstract: 'the abstract', ...
expect(link.protocol).toBe('OGC:WMS-1.1.1-http-get-map'); }); }); });
record.get('links')[0].protocol = 'OGC:WMS-1.1.1-http-get-map'; var link = record.getFirstWmsLink(); expect(link.server.uri).toBe('http://geoserver.imos.org.au/geoserver/wms');
random_line_split
screens.js
var _ = require("underscore"); var util = require("util"); exports.show = function (req, res) { var async = require('async'); if (!req.session.screen) { req.session.messages = { errors: ['screen not found'] }; res.redirect('/'); return; } var Handlebars = require('../hbs_helpers/hbs_helpers.js'); ...
req.session.messages = { errors: ["Error adding widgets to the screen: " + err] }; res.redirect("/screens/"+req.params.id + "/widgets/add"); }else{ console.log(" Widgets added successfully!!") req.session.messages = { success: [ "Widgets added successfully!!"] }; res.redir...
Screen.addWidgets(req.params.id, req.body.widgets, function(err, suc){ if(err){ console.log("Error adding widgets to the screen: ", err);
random_line_split
addTranslatorPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {TranslatorsDataService} from "../../providers/translatorsDataService"; import {SearchDataService} from "../../providers/searchDataService"; import {BluetoothOnboardingPage} from "../onboarding/bluetoothOnboarding...
}
{ var searchString = '<arg name="' + argName + '" value='; let searchStringEnd = manifestContent.search(searchString) + searchString.length; let foreStripped = manifestContent.substring(searchStringEnd + 1); searchStringEnd = foreStripped.search('"'); var endStripped = foreStripp...
identifier_body
addTranslatorPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {TranslatorsDataService} from "../../providers/translatorsDataService"; import {SearchDataService} from "../../providers/searchDataService"; import {BluetoothOnboardingPage} from "../onboarding/bluetoothOnboarding...
(manifestContent: string, argName: string): string { var searchString = '<arg name="' + argName + '" value='; let searchStringEnd = manifestContent.search(searchString) + searchString.length; let foreStripped = manifestContent.substring(searchStringEnd + 1); searchStringEnd = foreStrippe...
getOnboardingValue
identifier_name
addTranslatorPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {TranslatorsDataService} from "../../providers/translatorsDataService"; import {SearchDataService} from "../../providers/searchDataService"; import {BluetoothOnboardingPage} from "../onboarding/bluetoothOnboarding...
// ctor constructor(private nav: NavController, private navParams: NavParams, private translatorsDataService: TranslatorsDataService, private searchDataService: SearchDataService) { this.fullName = navParams.get("name"); this.name = this.fullName.split(".")[this.fullNam...
random_line_split
index.tsx
import * as React from 'react' import * as css from './styles.scss' import { Classes } from 'helpers' export interface P { name?: string; type?: 'button' | 'checkbox' | 'file' | 'hidden' | 'password' | 'radio' | 'text'; label?: string; value?: string | number; focus?: boolean; integer?: boolean; floatin...
} static getDerivedStateFromProps (props: P, state: S) { if (state.value !== props.value) { return { value: props.value, touch: false, } } return { touch: false, } } state = { value: '', } input: any = React.createRef() componentDidMount () { ...
value: '', focus: false, integer: false, floating: false, clearable: false,
random_line_split
index.tsx
import * as React from 'react' import * as css from './styles.scss' import { Classes } from 'helpers' export interface P { name?: string; type?: 'button' | 'checkbox' | 'file' | 'hidden' | 'password' | 'radio' | 'text'; label?: string; value?: string | number; focus?: boolean; integer?: boolean; floatin...
} handleBlur = (e: any) => { const value = this.prepared(e.target.value) if (this.props.handleBlur) { this.props.handleBlur(value) } } handleKeyPress = (e: any) => { const keyCode = e.keyCode || e.charCode || e.which if (this.props.handleKeyPress) { this.props.handleKeyPress...
{ this.props.handleFocus(e) }
conditional_block
index.tsx
import * as React from 'react' import * as css from './styles.scss' import { Classes } from 'helpers' export interface P { name?: string; type?: 'button' | 'checkbox' | 'file' | 'hidden' | 'password' | 'radio' | 'text'; label?: string; value?: string | number; focus?: boolean; integer?: boolean; floatin...
(props: P, state: S) { if (state.value !== props.value) { return { value: props.value, touch: false, } } return { touch: false, } } state = { value: '', } input: any = React.createRef() componentDidMount () { if (this.props.focus) { this.inp...
getDerivedStateFromProps
identifier_name
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages PROJECT = 'cax' VERSION = '5.2.1' with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'checksumdir', 'scp', '...
'cax-process = cax.tasks.process:main', 'cax-mv = cax.main:move', 'cax-rm = cax.main:remove', 'cax-stray = cax.main:stray', 'cax-status = cax.main:status', 'massive-tsm = cax.main:massive_tsmclient', 'cax-tsm-remove = cax.main:remove_fr...
'massive-cax = cax.main:massive', 'caxer = cax.main:main', # For uniformity with paxer
random_line_split
gl.js
//! moment.js locale configuration //! locale : Galician [gl] //! author : Juan G. Hurtado : https://github.com/juanghurtado ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define =...
}, ordinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return gl; }));
yy : '%d anos'
random_line_split
gl.js
//! moment.js locale configuration //! locale : Galician [gl] //! author : Juan G. Hurtado : https://github.com/juanghurtado ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define =...
return 'en ' + str; }, past : 'hai %s', s : 'uns segundos', m : 'un minuto', mm : '%d minutos', h : 'unha hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM...
return 'n' + str; }
conditional_block
geo_repo.py
__author__ = 'roscoe' import os from datetime import datetime import qgis.utils import qgis.utils from src.geogigpy import Repository from src.geogigpy import geogig from src.geogigpy.geogigexception import GeoGigException from qgis.core import QgsVectorLayer, QgsMapLayerRegistry class GeoRepo(object): def __in...
def add_commit_push(self, name, email, message): message += " " + str(datetime.now()) self.local_repo.config(geogig.USER_NAME, name) self.local_repo.config(geogig.USER_EMAIL, email) try: self.import_all_shapefiles() except GeoGigException, e: print ...
shp_path = os.path.join(self.path, f) self.local_repo.importshp(shp_path)
conditional_block
geo_repo.py
__author__ = 'roscoe' import os from datetime import datetime import qgis.utils import qgis.utils from src.geogigpy import Repository from src.geogigpy import geogig from src.geogigpy.geogigexception import GeoGigException from qgis.core import QgsVectorLayer, QgsMapLayerRegistry class GeoRepo(object):
print "New repo initialized at : %s" % self.path return local_repo def export_to_shapefiles(self): for t in self.local_repo.trees: if t.path not in ("layer_statistics", "views_layer_statistics", "virts_layer_statistics"): self.local_repo.exportshp('H...
def __init__(self, remote, path, repo_type): """constructor""" self.repo_type = repo_type self.remote = remote self.path = path self.sql_database = os.path.join(self.path, 'database.sqlite') self.local_repo = self.connect2repo() self.root_path = os.path.normpath(_...
identifier_body
geo_repo.py
__author__ = 'roscoe' import os from datetime import datetime import qgis.utils import qgis.utils from src.geogigpy import Repository from src.geogigpy import geogig from src.geogigpy.geogigexception import GeoGigException from qgis.core import QgsVectorLayer, QgsMapLayerRegistry class GeoRepo(object): def __in...
(self): try: self.local_repo.pull("origin") except GeoGigException, e: print e # Notes: # ------------------------------------------------------------------------ # changed self.connector.importpg to self.connector.importsl in repo.py # changed ...
pull_from_remote
identifier_name
geo_repo.py
__author__ = 'roscoe' import os from datetime import datetime import qgis.utils import qgis.utils from src.geogigpy import Repository from src.geogigpy import geogig from src.geogigpy.geogigexception import GeoGigException from qgis.core import QgsVectorLayer, QgsMapLayerRegistry class GeoRepo(object): def __in...
except GeoGigException, e: print 'Error with import_from_spatialite()' try: self.local_repo.addandcommit(message) print 'Repo added and committed.' except GeoGigException, e: print e def push_to_remote(self): try: self.loc...
message += " " + str(datetime.now()) self.local_repo.config(geogig.USER_NAME, name) self.local_repo.config(geogig.USER_EMAIL, email) try: self.import_all_shapefiles()
random_line_split
hs256.rs
extern crate crypto; extern crate jwt; use std::default::Default; use crypto::sha2::Sha256; use jwt::{ Header, Registered, Token, }; fn new_token(user_id: &str, password: &str) -> Option<String>
fn login(token: &str) -> Option<String> { let token = Token::<Header, Registered>::parse(token).unwrap(); if token.verify(b"secret_key", Sha256::new()) { token.claims.sub } else { None } } fn main() { let token = new_token("Michael Yang", "password").unwrap(); let logged_in_...
{ // Dummy auth if password != "password" { return None } let header: Header = Default::default(); let claims = Registered { iss: Some("mikkyang.com".into()), sub: Some(user_id.into()), ..Default::default() }; let token = Token::new(header, claims); toke...
identifier_body
hs256.rs
extern crate crypto; extern crate jwt; use std::default::Default; use crypto::sha2::Sha256; use jwt::{ Header, Registered, Token, }; fn new_token(user_id: &str, password: &str) -> Option<String> { // Dummy auth if password != "password" { return None } let header: Header = Default...
(token: &str) -> Option<String> { let token = Token::<Header, Registered>::parse(token).unwrap(); if token.verify(b"secret_key", Sha256::new()) { token.claims.sub } else { None } } fn main() { let token = new_token("Michael Yang", "password").unwrap(); let logged_in_user = log...
login
identifier_name
hs256.rs
extern crate crypto; extern crate jwt; use std::default::Default; use crypto::sha2::Sha256; use jwt::{ Header, Registered, Token, }; fn new_token(user_id: &str, password: &str) -> Option<String> { // Dummy auth if password != "password" { return None } let header: Header = Default...
fn login(token: &str) -> Option<String> { let token = Token::<Header, Registered>::parse(token).unwrap(); if token.verify(b"secret_key", Sha256::new()) { token.claims.sub } else { None } } fn main() { let token = new_token("Michael Yang", "password").unwrap(); let logged_in_u...
random_line_split
hs256.rs
extern crate crypto; extern crate jwt; use std::default::Default; use crypto::sha2::Sha256; use jwt::{ Header, Registered, Token, }; fn new_token(user_id: &str, password: &str) -> Option<String> { // Dummy auth if password != "password" { return None } let header: Header = Default...
else { None } } fn main() { let token = new_token("Michael Yang", "password").unwrap(); let logged_in_user = login(&*token).unwrap(); assert_eq!(logged_in_user, "Michael Yang"); }
{ token.claims.sub }
conditional_block
utils.py
.repr(k), reprlib.repr(v)) for k, v in self.iteritems()) + '}' __str__ = __unicode__ = __repr__ def pretty(self, leading_whitespace=''): return leading_whitespace + ('\n' + leading_whitespace).join( '%s: %s' % (k, (repr(v) if isinstance(v, bytes) else v)) for k, v in sorted(self.items(), ke...
import win32file, pywintypes try: win32file.MoveFileEx(src, dest, win32file.MOVEFILE_REPLACE_EXISTING|win32file.MOVEFILE_WRITE_THROUGH) except pywintypes.error as e: raise_winerror(e)
conditional_block
utils.py
): for v in dict.itervalues(self): if duplicates: for x in v: yield x else: yield v[-1] itervalues = values def set(self, key, val, replace_all=False): if replace_all: dict.__setitem__(self, key, [val]) ...
self.filename, self.history, self.max_size = filename, history, max_size if iswindows: self.filename = '\\\\?\\' + os.path.abspath(self.filename) self.set_output() def set_output(self): self.stream = share_open(self.filename, 'ab', -1 if iswindows else 1) # line buffere...
random_line_split
utils.py
quoted string could have quotes in the middle. Neither commas nor quotes count if they are escaped. Only double-quotes count, not single-quotes. """ if isinstance(header_val, bytes): slash, dquote, comma = b'\\",' empty = b'' else: slash, dquote, comma = '\\",' empty...
self.sz, self.mv = len(raw), (raw if isinstance(raw, memoryview) else memoryview(raw)) self.pos = 0
identifier_body
utils.py
): for v in dict.itervalues(self): if duplicates: for x in v: yield x else: yield v[-1] itervalues = values def set(self, key, val, replace_all=False): if replace_all: dict.__setitem__(self, key, [val]) ...
(self): return '{' + ', '.join('%s: %s' % (reprlib.repr(k), reprlib.repr(v)) for k, v in self.iteritems()) + '}' __str__ = __unicode__ = __repr__ def pretty(self, leading_whitespace=''): return leading_whitespace + ('\n' + leading_whitespace).join( '%s: %s' % (k, (repr(v) if isinsta...
__repr__
identifier_name
output.rs
use crate::error::LucetcErrorKind; use crate::function_manifest::{write_function_manifest, FUNCTION_MANIFEST_SYM}; use crate::name::Name; use crate::stack_probe; use crate::table::{link_tables, TABLE_SYM}; use crate::traps::write_trap_tables; use byteorder::{LittleEndian, WriteBytesExt}; use cranelift_codegen::{ir, isa...
/// This outputs a .clif file pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { use cranelift_codegen::write_function; let mut buffer = String::new(); for (n, func) in self.funcs.iter() { buffer.push_str(&format!("; {}\n", n.symbol())); write_fun...
impl CraneliftFuncs { pub fn new(funcs: HashMap<Name, ir::Function>, isa: Box<dyn isa::TargetIsa>) -> Self { Self { funcs, isa } }
random_line_split
output.rs
use crate::error::LucetcErrorKind; use crate::function_manifest::{write_function_manifest, FUNCTION_MANIFEST_SYM}; use crate::name::Name; use crate::stack_probe; use crate::table::{link_tables, TABLE_SYM}; use crate::traps::write_trap_tables; use byteorder::{LittleEndian, WriteBytesExt}; use cranelift_codegen::{ir, isa...
{ funcs: HashMap<Name, ir::Function>, isa: Box<dyn isa::TargetIsa>, } impl CraneliftFuncs { pub fn new(funcs: HashMap<Name, ir::Function>, isa: Box<dyn isa::TargetIsa>) -> Self { Self { funcs, isa } } /// This outputs a .clif file pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<...
CraneliftFuncs
identifier_name
output.rs
use crate::error::LucetcErrorKind; use crate::function_manifest::{write_function_manifest, FUNCTION_MANIFEST_SYM}; use crate::name::Name; use crate::stack_probe; use crate::table::{link_tables, TABLE_SYM}; use crate::traps::write_trap_tables; use byteorder::{LittleEndian, WriteBytesExt}; use cranelift_codegen::{ir, isa...
LUCET_MODULE_SYM, Some(TABLE_SYM), table_manifest_len as u64, )?; write_relocated_slice( obj, &mut native_data, LUCET_MODULE_SYM, Some(FUNCTION_MANIFEST_SYM), function_manifest_len as u64, )?; obj.define(LUCET_MODULE_SYM, native_data.into_...
{ let mut native_data = Cursor::new(Vec::with_capacity(std::mem::size_of::<SerializedModule>())); obj.declare(LUCET_MODULE_SYM, Decl::data().global()) .context(format!("declaring {}", LUCET_MODULE_SYM))?; let version = VersionInfo::current(include_str!(concat!(env!("OUT_DIR"), "/commit_hash...
identifier_body
persistence.js
Handle every persistence-related task * The interface Datastore expects to be implemented is * * Persistence.loadDatabase(callback) and callback has signature err * * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err */ var fs = require('fs'...
/** * Check if a directory exists and create it on the fly if it is not the case * cb is optional, signature: err */ Persistence.ensureDirectoryExists = function (dir, cb) { var callback = cb || function () {} ; mkdirp(dir, function (err) { return callback(err); }); }; /** * Return the path ...
};
random_line_split
persistence.js
Handle every persistence-related task * The interface Datastore expects to be implemented is * * Persistence.loadDatabase(callback) and callback has signature err * * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err */ var fs = require('fs'...
; /** * Check if a directory exists and create it on the fly if it is not the case * cb is optional, signature: err */ Persistence.ensureDirectoryExists = function (dir, cb) { var callback = cb || function () {} ; mkdirp(dir, function (err) { return callback(err); }); }; /** * Return th...
{ this.db = options.db; this.inMemoryOnly = this.db.inMemoryOnly; this.filename = this.db.filename; if (!this.inMemoryOnly && this.filename) { if (this.filename.charAt(this.filename.length - 1) === '~') { throw "The datafile name can't end with a ~, which is reserved for automatic backup fil...
identifier_body
persistence.js
Handle every persistence-related task * The interface Datastore expects to be implemented is * * Persistence.loadDatabase(callback) and callback has signature err * * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err */ var fs = require('fs'...
}); } , function (cb) { fs.writeFile(self.tempFilename, toPersist, function (err) { return cb(err); }); } , function (cb) { fs.rename(self.tempFilename, self.filename, function (err) { return cb(err); }); } , async.apply(customUtils.ensureFileDoesntExist, self.oldFilename) ...
{ return cb(); }
conditional_block
persistence.js
Handle every persistence-related task * The interface Datastore expects to be implemented is * * Persistence.loadDatabase(callback) and callback has signature err * * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err */ var fs = require('fs'...
(options) { this.db = options.db; this.inMemoryOnly = this.db.inMemoryOnly; this.filename = this.db.filename; if (!this.inMemoryOnly && this.filename) { if (this.filename.charAt(this.filename.length - 1) === '~') { throw "The datafile name can't end with a ~, which is reserved for automatic...
Persistence
identifier_name
playwire.py
# -*- coding: utf-8 -*- import re,urlparse,json from liveresolver.modules import client from BeautifulSoup import BeautifulSoup as bs import xbmcgui def resolve(url):
for link in linklist: url = base + link['url'] bitrate = link['bitrate'] choices.append(bitrate) links.append(url) if len(links)==1: return links[0] if len(links)>1: dialog = xbmcgui.Dialog() index = dia...
try: result = client.request(url) html = result result = json.loads(result) try: f4m=result['content']['media']['f4m'] except: reg=re.compile('"src":"http://(.+?).f4m"') f4m=re.findall(reg,html)[0] f4m='http://'+pom+'.f4m' ...
identifier_body
playwire.py
# -*- coding: utf-8 -*- import re,urlparse,json from liveresolver.modules import client from BeautifulSoup import BeautifulSoup as bs import xbmcgui def
(url): try: result = client.request(url) html = result result = json.loads(result) try: f4m=result['content']['media']['f4m'] except: reg=re.compile('"src":"http://(.+?).f4m"') f4m=re.findall(reg,html)[0] f4m='http://'...
resolve
identifier_name
playwire.py
# -*- coding: utf-8 -*- import re,urlparse,json from liveresolver.modules import client from BeautifulSoup import BeautifulSoup as bs
def resolve(url): try: result = client.request(url) html = result result = json.loads(result) try: f4m=result['content']['media']['f4m'] except: reg=re.compile('"src":"http://(.+?).f4m"') f4m=re.findall(reg,html)[0] f4...
import xbmcgui
random_line_split
playwire.py
# -*- coding: utf-8 -*- import re,urlparse,json from liveresolver.modules import client from BeautifulSoup import BeautifulSoup as bs import xbmcgui def resolve(url): try: result = client.request(url) html = result result = json.loads(result) try: f4m=res...
if len(links)>1: dialog = xbmcgui.Dialog() index = dialog.select('Select bitrate', choices) if index>-1: return links[index] return except: return
return links[0]
conditional_block
admin.py
from django.contrib import admin from .models import BookingState, Booking, BookingItem, TrackingEvent, TrackingValue, Agreement, Payment @admin.register(BookingState) class BookingStateAdmin(admin.ModelAdmin): list_display = ('title', 'color', 'income') @admin.register(Agreement) class AgreementAdmin(admin.Mod...
@admin.register(Booking) class BookingAdmin(admin.ModelAdmin): inlines = (AgreementInline, BookingItemInline, PaymentInline) list_display = ('title', 'year', 'state', 'contact', 'email', 'tel', 'agreement') list_filter = ('state', 'year') search_fields = ('title', 'contact', 'email') class Tracking...
model = Payment fields = ('mean', 'date', 'amount', 'scan') extra = 1
identifier_body
admin.py
from django.contrib import admin from .models import BookingState, Booking, BookingItem, TrackingEvent, TrackingValue, Agreement, Payment @admin.register(BookingState) class BookingStateAdmin(admin.ModelAdmin): list_display = ('title', 'color', 'income') @admin.register(Agreement) class AgreementAdmin(admin.Mod...
class BookingAdmin(admin.ModelAdmin): inlines = (AgreementInline, BookingItemInline, PaymentInline) list_display = ('title', 'year', 'state', 'contact', 'email', 'tel', 'agreement') list_filter = ('state', 'year') search_fields = ('title', 'contact', 'email') class TrackingValueInline(admin.TabularInl...
fields = ('mean', 'date', 'amount', 'scan') extra = 1 @admin.register(Booking)
random_line_split
admin.py
from django.contrib import admin from .models import BookingState, Booking, BookingItem, TrackingEvent, TrackingValue, Agreement, Payment @admin.register(BookingState) class
(admin.ModelAdmin): list_display = ('title', 'color', 'income') @admin.register(Agreement) class AgreementAdmin(admin.ModelAdmin): list_display = ('number', 'date', 'booking') list_filter = ('booking__year', ) ordering = ('-booking__year', '-order', ) date_hierarchy = 'date' class AgreementInlin...
BookingStateAdmin
identifier_name
findNearestGroupDatum.ts
import { PositionScale } from '@visx/shape/lib/types'; import { ScaleTypeToD3Scale } from '@visx/scale'; import { NearestDatumArgs } from '../types'; import findNearestDatumX from './findNearestDatumX'; import findNearestDatumY from './findNearestDatumY'; /** * This is a wrapper around findNearestDatumX/Y for BarGrou...
< XScale extends PositionScale, YScale extends PositionScale, Datum extends object >( nearestDatumArgs: NearestDatumArgs<XScale, YScale, Datum>, groupScale: ScaleTypeToD3Scale<string, string>['band'], horizontal?: boolean, ) { const { dataKey, xAccessor, yAccessor, xScale, yScale, point } = nearestDatumAr...
findNearestGroupDatum
identifier_name
findNearestGroupDatum.ts
import { PositionScale } from '@visx/shape/lib/types'; import { ScaleTypeToD3Scale } from '@visx/scale'; import { NearestDatumArgs } from '../types'; import findNearestDatumX from './findNearestDatumX'; import findNearestDatumY from './findNearestDatumY'; /** * This is a wrapper around findNearestDatumX/Y for BarGrou...
} const groupPosition = xScale(xAccessor(datum.datum)); const barStart = (groupPosition ?? Infinity) + (barGroupOffset ?? Infinity); const barEnd = barStart + barWidth; const barMiddle = (barStart + barEnd) / 2; const cursorIsOnBar = point.x >= barStart && point.x <= barEnd; return { ...datum, dis...
{ const { dataKey, xAccessor, yAccessor, xScale, yScale, point } = nearestDatumArgs; const datum = (horizontal ? findNearestDatumY : findNearestDatumX)(nearestDatumArgs); if (!datum || !point) return null; const barGroupOffset = groupScale(dataKey); const barWidth = groupScale.step(); if (horizontal) { ...
identifier_body
findNearestGroupDatum.ts
import { PositionScale } from '@visx/shape/lib/types'; import { ScaleTypeToD3Scale } from '@visx/scale'; import { NearestDatumArgs } from '../types'; import findNearestDatumX from './findNearestDatumX'; import findNearestDatumY from './findNearestDatumY'; /** * This is a wrapper around findNearestDatumX/Y for BarGrou...
const groupPosition = xScale(xAccessor(datum.datum)); const barStart = (groupPosition ?? Infinity) + (barGroupOffset ?? Infinity); const barEnd = barStart + barWidth; const barMiddle = (barStart + barEnd) / 2; const cursorIsOnBar = point.x >= barStart && point.x <= barEnd; return { ...datum, distan...
{ const groupPosition = yScale(yAccessor(datum.datum)); const barStart = (groupPosition ?? Infinity) + (barGroupOffset ?? Infinity); const barEnd = barStart + barWidth; const barMiddle = (barStart + barEnd) / 2; const cursorIsOnBar = point.y >= barStart && point.y <= barEnd; return { ...da...
conditional_block
findNearestGroupDatum.ts
import { PositionScale } from '@visx/shape/lib/types'; import { ScaleTypeToD3Scale } from '@visx/scale'; import { NearestDatumArgs } from '../types'; import findNearestDatumX from './findNearestDatumX'; import findNearestDatumY from './findNearestDatumY'; /** * This is a wrapper around findNearestDatumX/Y for BarGrou...
>( nearestDatumArgs: NearestDatumArgs<XScale, YScale, Datum>, groupScale: ScaleTypeToD3Scale<string, string>['band'], horizontal?: boolean, ) { const { dataKey, xAccessor, yAccessor, xScale, yScale, point } = nearestDatumArgs; const datum = (horizontal ? findNearestDatumY : findNearestDatumX)(nearestDatumArgs...
YScale extends PositionScale, Datum extends object
random_line_split
page-settings.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { PageService } from '../../../../shared/services/page.service'; import { SiteService } from '../../../../shared/services/site.service'; import { RouteService } from '../../../../shared/services/route.service'; declare var toast: any; @Com...
}
{ console.log('[respond.error] ' + this.errorMessage); toast.show('failure'); }
identifier_body
page-settings.component.ts
import { SiteService } from '../../../../shared/services/site.service'; import { RouteService } from '../../../../shared/services/route.service'; declare var toast: any; @Component({ selector: 'respond-page-settings', templateUrl: 'page-settings.component.html', providers: [PageService, SiteService, Route...
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { PageService } from '../../../../shared/services/page.service';
random_line_split
page-settings.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { PageService } from '../../../../shared/services/page.service'; import { SiteService } from '../../../../shared/services/site.service'; import { RouteService } from '../../../../shared/services/route.service'; declare var toast: any; @Com...
(private _pageService: PageService, private _siteService: SiteService, private _routeService: RouteService) {} /** * Init pages */ ngOnInit() { this._routeService.list() .subscribe( data => { this.routes = data; }, error => { this.onEr...
constructor
identifier_name
conf.py
# -*- coding: utf-8 -*- # Copyright (C) 2020 Red Hat, Inc. # # 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 ...
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinxcontrib.apidoc', 'openstackdocstheme', ] # openstackdocstheme options openstackdocs_repo_name = 'openstack/oslo.privsep' openstackdocs_bug_project = 'oslo.privsep' openstackdocs_bug_tag =...
# Add any Sphinx extension module names here, as strings. They can be
random_line_split
tingapp.py
import collections import json import os import sys import hashlib import logging from .utils import cached_property, get_resource from .graphics import Image def load_json(filename): try: with open(filename, 'r') as fp: result = json.load(fp) if not isinstance(result, dict): ...
(self): if 'name' in self.info and self.info['name'] != '': return self.info['name'] else: return os.path.basename(self.path) @cached_property def icon(self): icon_path = os.path.join(self.path, 'icon.png') if not os.path.isfile(icon_path): r...
name
identifier_name
tingapp.py
import collections import json import os import sys import hashlib import logging from .utils import cached_property, get_resource from .graphics import Image def load_json(filename): try: with open(filename, 'r') as fp: result = json.load(fp) if not isinstance(result, dict): ...
return icon app = TingApp()
resized_icon = Image(size=(96, 96)) resized_icon.image(icon, scale='shrinkToFit') return resized_icon
conditional_block
tingapp.py
import collections import json import os import sys import hashlib import logging from .utils import cached_property, get_resource from .graphics import Image def load_json(filename): try: with open(filename, 'r') as fp: result = json.load(fp) if not isinstance(result, dict): ...
class SettingsDict(collections.MutableMapping): ''' Represents the tingapp.settings dict-like object. The settings are loaded from three files in the app bundle - default_settings.json This file contains default settings as defined by the app creator - settings.json This...
data = json.dumps(obj) with open(filename, 'w') as fp: fp.write(data)
identifier_body
tingapp.py
import collections import json import os import sys import hashlib import logging from .utils import cached_property, get_resource from .graphics import Image def load_json(filename): try: with open(filename, 'r') as fp: result = json.load(fp) if not isinstance(result, dict): ...
self.dct.update(load_json(os.path.join(self.path, 'settings.json'))) self.local_settings = load_json(os.path.join(self.path, 'local_settings.json')) self.dct.update(self.local_settings) self.loaded = True def save(self): save_json(os.path.join(self.path, 'local_settings.json...
random_line_split
__init__.py
# Copyright 2016 Cisco Systems, Inc. # # 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 writin...
__author__ = 'Cisco Systems' __email__ = 'ucs-python@cisco.com' __version__ = '0.9.3.1'
enable_file_logging()
conditional_block
__init__.py
# Copyright 2016 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging import logging.handlers log = logging.getLogger('imc') console = logging.StreamHandler() formatter = logging.Forma...
# You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
__init__.py
# Copyright 2016 Cisco Systems, Inc. # # 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 writin...
set_log_level(logging.DEBUG) log.addHandler(console) if os.path.exists('/tmp/imcsdk_debug'): enable_file_logging() __author__ = 'Cisco Systems' __email__ = 'ucs-python@cisco.com' __version__ = '0.9.3.1'
""" Allows setting log level Args: level: logging level - import logging and pass enums from it(INFO/DEBUG/ERROR/etc..) Returns: None Example: from imcsdk import set_log_level import logging set_log_level(logging.INFO) """ log.setLevel(level) conso...
identifier_body
__init__.py
# Copyright 2016 Cisco Systems, Inc. # # 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 writin...
(level=logging.DEBUG): """ Allows setting log level Args: level: logging level - import logging and pass enums from it(INFO/DEBUG/ERROR/etc..) Returns: None Example: from imcsdk import set_log_level import logging set_log_level(logging.INFO) """ lo...
set_log_level
identifier_name
suggest-change-mut.rs
#![allow(warnings)] use std::io::{BufRead, BufReader, Read, Write}; fn issue_81421<T: Read + Write>(mut stream: T) { //~ HELP consider introducing a `where` bound let initial_message = format!("Hello world"); let mut buffer: Vec<u8> = Vec::new(); let bytes_written = stream.write_all(initial_message.as_byt...
{}
identifier_body
suggest-change-mut.rs
#![allow(warnings)] use std::io::{BufRead, BufReader, Read, Write}; fn issue_81421<T: Read + Write>(mut stream: T) { //~ HELP consider introducing a `where` bound let initial_message = format!("Hello world"); let mut buffer: Vec<u8> = Vec::new(); let bytes_written = stream.write_all(initial_message.as_byt...
() {}
main
identifier_name
suggest-change-mut.rs
#![allow(warnings)] use std::io::{BufRead, BufReader, Read, Write}; fn issue_81421<T: Read + Write>(mut stream: T) { //~ HELP consider introducing a `where` bound let initial_message = format!("Hello world"); let mut buffer: Vec<u8> = Vec::new(); let bytes_written = stream.write_all(initial_message.as_byt...
} fn main() {}
}
random_line_split
index.d.ts
// Type definitions for react-router-bootstrap // Project: https://github.com/react-bootstrap/react-router-bootstrap // Definitions by: Vincent Lesierse <https://github.com/vlesierse> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="react"/> /// <reference types="react-router"/>...
disabled?: boolean } interface LinkContainer extends React.ComponentClass<LinkContainerProps> {} interface LinkContainerElement extends React.ReactElement<LinkContainerProps> {} const LinkContainer: LinkContainer const IndexLinkContainer: LinkContainer } declare module "react-router-bootst...
interface LinkContainerProps extends ReactRouter.LinkProps {
random_line_split
test_ValueIterationGS.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 15:08:01 2013 @author: steve """ import numpy as np import mdptoolbox from .utils import SMALLNUM, P_forest, R_forest, P_small, R_small, P_sparse from .utils import P_forest_sparse, R_forest_sparse def test_ValueIterationGS_small(): sdp = mdptoolbox.mdp.ValueIt...
(): sdp = mdptoolbox.mdp.ValueIterationGS(P_forest_sparse, R_forest_sparse, 0.96) sdp.run() p = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) itr = 16 # from Octave MDPtoolbox assert sdp.policy == p assert sdp.iter == itr
test_ValueIterationGS_forest_sparse
identifier_name
test_ValueIterationGS.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 15:08:01 2013 @author: steve """ import numpy as np import mdptoolbox from .utils import SMALLNUM, P_forest, R_forest, P_small, R_small, P_sparse from .utils import P_forest_sparse, R_forest_sparse def test_ValueIterationGS_small(): sdp = mdptoolbox.mdp.ValueIt...
assert sdp.iter == itr assert (np.absolute(np.array(sdp.V) - v) < SMALLNUM).all() def test_ValueIterationGS_forest_sparse(): sdp = mdptoolbox.mdp.ValueIterationGS(P_forest_sparse, R_forest_sparse, 0.96) sdp.run() p = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) itr =...
v = np.matrix('69.98910821400665, 73.46560194552877, 77.46560194552877') itr = 63 # from Octave MDPtoolbox assert sdp.max_iter == 63 assert sdp.policy == p
random_line_split
test_ValueIterationGS.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 15:08:01 2013 @author: steve """ import numpy as np import mdptoolbox from .utils import SMALLNUM, P_forest, R_forest, P_small, R_small, P_sparse from .utils import P_forest_sparse, R_forest_sparse def test_ValueIterationGS_small():
def test_ValueIterationGS_small_sparse(): sdp = mdptoolbox.mdp.ValueIterationGS(P_sparse, R_small, 0.9) sdp.run() p = (1, 0) itr = 28 # from Octave MDPtoolbox v = np.matrix('42.27744026138212, 35.89524504047155') assert sdp.iter == itr assert sdp.policy == p assert (np.absolute(np.arra...
sdp = mdptoolbox.mdp.ValueIterationGS(P_small, R_small, 0.9) sdp.run() p = (1, 0) itr = 28 # from Octave MDPtoolbox v = np.matrix('42.27744026138212, 35.89524504047155') assert sdp.iter == itr assert sdp.policy == p assert (np.absolute(np.array(sdp.V) - v) < SMALLNUM).all()
identifier_body
VariableInput.tsx
import * as React from 'react'; import { WegasScriptEditor } from '../../ScriptEditors/WegasScriptEditor'; import Form from 'jsoninput'; import { schemaProps } from '../../../../Components/PageComponents/tools/schemaProps'; import { WidgetProps } from 'jsoninput/typings/types'; import { LabeledView } from '../labeled';...
value={props.value} onChange={props.onChange} noGutter minimap={false} returnType={props.view.scriptableClassFilter} /> ) : ( <Form value={props.value} schema={schema(props.view.scriptableClassFilter)} ...
{srcMode ? ( <WegasScriptEditor
random_line_split
drain.rs
use std::mem; use pin_project_lite::pin_project; use tokio::sync::watch; use super::{task, Future, Pin, Poll}; pub(crate) fn channel() -> (Signal, Watch) { let (tx, rx) = watch::channel(()); (Signal { tx }, Watch { rx }) } pub(crate) struct Signal { tx: watch::Sender<()>, } pub(crate) struct Draining(P...
} impl Future for TestMe { type Output = (); fn poll(mut self: Pin<&mut Self>, _: &mut task::Context<'_>) -> Poll<Self::Output> { self.poll_cnt += 1; if self.finished { Poll::Ready(()) } else { Poll::Pending } ...
random_line_split
drain.rs
use std::mem; use pin_project_lite::pin_project; use tokio::sync::watch; use super::{task, Future, Pin, Poll}; pub(crate) fn channel() -> (Signal, Watch) { let (tx, rx) = watch::channel(()); (Signal { tx }, Watch { rx }) } pub(crate) struct Signal { tx: watch::Sender<()>, } pub(crate) struct Draining(P...
else { Poll::Pending } } } #[test] fn watch() { let mut mock = tokio_test::task::spawn(()); mock.enter(|cx, _| { let (tx, rx) = channel(); let fut = TestMe { draining: false, finished: false, ...
{ Poll::Ready(()) }
conditional_block
drain.rs
use std::mem; use pin_project_lite::pin_project; use tokio::sync::watch; use super::{task, Future, Pin, Poll}; pub(crate) fn channel() -> (Signal, Watch) { let (tx, rx) = watch::channel(()); (Signal { tx }, Watch { rx }) } pub(crate) struct Signal { tx: watch::Sender<()>, } pub(crate) struct Draining(P...
<F> { Watch(F), Draining, } impl Signal { pub(crate) fn drain(self) -> Draining { let _ = self.tx.send(()); Draining(Box::pin(async move { self.tx.closed().await })) } } impl Future for Draining { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) ...
State
identifier_name
main.rs
fn main() { // associating types with the trait. // helps to avoid everything related with original trait // to be generic over associated types. trait Graph { type Node; type Edge; fn has_edge(&self, &Self::Node, &Self::Node) -> bool; fn edges(&self, &Self::Node) ->Vec<Self::Edge>;...
fn edges(&self, _n: &Node) -> Vec<Edge> { Vec::new() } } // providing actual assoc types for trait objects: let graph = MyGraph; let _obj = Box::new(graph) as Box<Graph<Node=Node, Edge=Edge>>; }
{ true }
identifier_body
main.rs
fn main() { // associating types with the trait. // helps to avoid everything related with original trait // to be generic over associated types. trait Graph { type Node; type Edge;
fn edges(&self, &Self::Node) ->Vec<Self::Edge>; } #[allow(dead_code)] fn distance<G: Graph>( _graph: &G, _start: &G::Node, _end: &G::Node ) -> u32 { unimplemented!(); } // implementing associated types: struct Node; struct Edge; #[allow(dead_code)] struct MyGraph; i...
fn has_edge(&self, &Self::Node, &Self::Node) -> bool;
random_line_split
main.rs
fn main() { // associating types with the trait. // helps to avoid everything related with original trait // to be generic over associated types. trait Graph { type Node; type Edge; fn has_edge(&self, &Self::Node, &Self::Node) -> bool; fn edges(&self, &Self::Node) ->Vec<Self::Edge>;...
<G: Graph>( _graph: &G, _start: &G::Node, _end: &G::Node ) -> u32 { unimplemented!(); } // implementing associated types: struct Node; struct Edge; #[allow(dead_code)] struct MyGraph; impl Graph for MyGraph { type Node = Node; type Edge = Edge; fn has_edge( &self, _n1...
distance
identifier_name
full-layout.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from "../services/_security/_services/authentication.service"; import { Router } from "@angular/router"; import * as firebase from 'firebase'; import {NotificationsService} from "angular2-notifications"; @Co...
}
{ this.newNotification = true; this.notificationCounter = this.notificationCounter + 1; this._notificationsService.info( payload.notification.title, payload.notification.body ) }
identifier_body
full-layout.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from "../services/_security/_services/authentication.service"; import { Router } from "@angular/router"; import * as firebase from 'firebase'; import {NotificationsService} from "angular2-notifications"; @Co...
this.messaging = firebase.messaging(); this.messaging.requestPermission() .then(() => { console.log('Have Permission!:)'); return this.messaging.getToken() }) .then((token) => { console.log('token: ' + token); ...
this.login = currUser && currUser.username; } public initializeFCM(): void {
random_line_split
full-layout.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from "../services/_security/_services/authentication.service"; import { Router } from "@angular/router"; import * as firebase from 'firebase'; import {NotificationsService} from "angular2-notifications"; @Co...
(payload) { this.newNotification = true; this.notificationCounter = this.notificationCounter + 1; this._notificationsService.info( payload.notification.title, payload.notification.body ) } }
handleNotification
identifier_name
rest.py
from mod_python import apache from mod_python import util import os.path import urllib import logging debug = True def handler(req): """ This is called by Apache and maps the request to the resource class. Process of maping: 1. Try import a python script which handles this resource. T...
resourceModule = apache.import_module(mtype.strip('/').replace('/','.'), path=os.path.dirname(__file__)) except Exception, err: if debug: raise return apache.HTTP_NOT_FOUND # 2. try: allowedMethodes = resourceModule.allowedMethodes except AttributeError, err: if...
random_line_split
rest.py
from mod_python import apache from mod_python import util import os.path import urllib import logging debug = True def handler(req): """ This is called by Apache and maps the request to the resource class. Process of maping: 1. Try import a python script which handles this resource. T...
(req, error, message): """Send a error page to client. Replaces http error page.""" req.status = apache.HTTP_FORBIDDEN req.content_type = 'text/plain' req.write(message) return apache.OK
writeError
identifier_name
rest.py
from mod_python import apache from mod_python import util import os.path import urllib import logging debug = True def handler(req): """ This is called by Apache and maps the request to the resource class. Process of maping: 1. Try import a python script which handles this resource. T...
"""Send a error page to client. Replaces http error page.""" req.status = apache.HTTP_FORBIDDEN req.content_type = 'text/plain' req.write(message) return apache.OK
identifier_body
rest.py
from mod_python import apache from mod_python import util import os.path import urllib import logging debug = True def handler(req): """ This is called by Apache and maps the request to the resource class. Process of maping: 1. Try import a python script which handles this resource. T...
return apache.HTTP_HTTP_NOT_FOUND if not req.method in allowedMethodes: req.allow_methods(resourceModule.allowedMethodes, 1) return apache.HTTP_METHOD_NOT_ALLOWED # 3. if not 'form' in dir(req): req.form = util.FieldStorage(req, True) # 4. try: return getattr...
raise
conditional_block
setup.py
''' Created on Jan 15, 2014 @author: Jose Borreguero ''' from setuptools import setup setup( name = 'dsfinterp', packages = ['dsfinterp','dsfinterp/test' ], version = '0.1', description = 'Cubic Spline Interpolation of Dynamics Structure Factors', long_description = open('README.md').read(), author = 'J...
keywords = ['AMBER', 'mdend', 'energy', 'molecular dynamics'], classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: ...
random_line_split
fr-VU.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
'fr-VU', [['AM', 'PM'], u, u], u, [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'] ], u, [ ['J', 'F', ...
return 5; } global.ng.common.locales['fr-vu'] = [
random_line_split
fr-VU.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
global.ng.common.locales['fr-vu'] = [ 'fr-VU', [['AM', 'PM'], u, u], u, [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], ['di', 'lu', 'ma', 'me', 'je', 've', 's...
{ var i = Math.floor(Math.abs(n)); if (i === 0 || i === 1) return 1; return 5; }
identifier_body
fr-VU.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
(n) { var i = Math.floor(Math.abs(n)); if (i === 0 || i === 1) return 1; return 5; } global.ng.common.locales['fr-vu'] = [ 'fr-VU', [['AM', 'PM'], u, u], u, [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], ['dimanche', 'lundi', ...
plural
identifier_name
vodo.js
(function (App) { 'use strict'; var apiUrl = 'http://vodo.net/popcorn', db = new Datastore(); function Vodo() { if (!(this instanceof Vodo)) { return new Vodo(); } App.Providers.Generic.call(this); } inherits(Vodo, App.Providers.Generic); function ...
params.sort = filters.sorter; } var sortOpts = {}; sortOpts[params.sort] = params.order; self.fetchPromise.then(function () { db.find(findOpts) .sort(sortOpts) .skip((filters.page - 1) * params.limit) .limit(Number...
if (filters.sorter && filters.sorter !== 'popularity') {
random_line_split
vodo.js
(function (App) { 'use strict'; var apiUrl = 'http://vodo.net/popcorn', db = new Datastore(); function
() { if (!(this instanceof Vodo)) { return new Vodo(); } App.Providers.Generic.call(this); } inherits(Vodo, App.Providers.Generic); function formatForButter(items) { var results = {}; var movieFetch = {}; movieFetch.results = []; movieFet...
Vodo
identifier_name
vodo.js
(function (App) { 'use strict'; var apiUrl = 'http://vodo.net/popcorn', db = new Datastore(); function Vodo() { if (!(this instanceof Vodo))
App.Providers.Generic.call(this); } inherits(Vodo, App.Providers.Generic); function formatForButter(items) { var results = {}; var movieFetch = {}; movieFetch.results = []; movieFetch.hasMore = (Number(items.length) > 1 ? true : false); _.each(items, functi...
{ return new Vodo(); }
conditional_block
vodo.js
(function (App) { 'use strict'; var apiUrl = 'http://vodo.net/popcorn', db = new Datastore(); function Vodo() { if (!(this instanceof Vodo)) { return new Vodo(); } App.Providers.Generic.call(this); } inherits(Vodo, App.Providers.Generic); function ...
seed: seeds, peer: peers }; var ptItem = results[imdb]; if (!ptItem) { ptItem = { imdb_id: imdb, title: movie.MovieTitleClean.replace(/\([^)]*\)|1080p|DIRECTORS CUT|EXTENDED|UNRATED|3D|[()]/g, ''...
{ var results = {}; var movieFetch = {}; movieFetch.results = []; movieFetch.hasMore = (Number(items.length) > 1 ? true : false); _.each(items, function (movie) { if (movie.Quality === '3D') { return; } var imdb = movie.ImdbCode...
identifier_body
test_file_size_validator.py
# -*- coding: utf-8 -*- import os import pytest import boto3 from pontus.exceptions import ValidationError from pontus.validators import FileSize class TestFileSizeValidator(object): @pytest.fixture def jpeg_key(self, bucket): with open(os.path.join( os.path.dirname(__file__), ...
( self, jpeg_key ): validator = FileSize(min=27670) with pytest.raises(ValidationError) as e: validator(jpeg_key) assert e.value.error == ( u'File is smaller than 27670 bytes.' ) def test_does_not_raise_validation_error_if_file_is_of_valid...
test_raises_validation_error_if_file_is_too_small
identifier_name
test_file_size_validator.py
# -*- coding: utf-8 -*- import os import pytest import boto3 from pontus.exceptions import ValidationError from pontus.validators import FileSize class TestFileSizeValidator(object): @pytest.fixture def jpeg_key(self, bucket): with open(os.path.join( os.path.dirname(__file__), ...
) def test_repr(self): assert repr(FileSize(min=27660, max=27662)) == ( u"<FileSize min=27660, max=27662>" )
with pytest.raises(ValueError) as e: FileSize(min=2, max=1) assert str(e.value) == ( 'Argument `min` cannot be more than `max`.'
random_line_split
test_file_size_validator.py
# -*- coding: utf-8 -*- import os import pytest import boto3 from pontus.exceptions import ValidationError from pontus.validators import FileSize class TestFileSizeValidator(object): @pytest.fixture def jpeg_key(self, bucket): with open(os.path.join( os.path.dirname(__file__), ...
def test_raises_value_error_if_min_is_more_than_max(self): with pytest.raises(ValueError) as e: FileSize(min=2, max=1) assert str(e.value) == ( 'Argument `min` cannot be more than `max`.' ) def test_repr(self): assert repr(FileSize(min=27660, max=27662)...
with pytest.raises(ValueError) as e: FileSize() assert str(e.value) == ( 'At least one of `min` or `max` must be defined.' )
identifier_body
TurConverseMainCtrl.js
turConverseApp .controller( 'TurConverseMainCtrl', [ "$scope", "$translate", "amMoment", "vigLocale", "$http", "turAPIServerService", "$timeout", "$location", "$anchorScroll", "$stateParams", "turConverseAgentResource", function ($scope, $translate, amMoment, vigLocale, $http, ...
$scope.agentResponse = response.data; var message = { "bot": true, "text": $scope.agentResponse.response }; $timeout(function () { $scope.waiting = false; $scope.messages.push(message); $location.hash('bottom'); $a...
$scope.start = false; if (response !== null) {
random_line_split
TurConverseMainCtrl.js
turConverseApp .controller( 'TurConverseMainCtrl', [ "$scope", "$translate", "amMoment", "vigLocale", "$http", "turAPIServerService", "$timeout", "$location", "$anchorScroll", "$stateParams", "turConverseAgentResource", function ($scope, $translate, amMoment, vigLocale, $http, ...
$scope .$evalAsync($http .get(turAPIServerService.get().concat("/converse/agent/" + $scope.agentId + "/chat?q=" + $scope.turConverseText + startStr)) .then( function (response) { $scope.start = false; if (response !== null) { $scope.agentResponse = response....
{ startStr = "&start=true" }
conditional_block
ConnectedAccountMutations.ts
import express from 'express'; import { GraphQLNonNull } from 'graphql'; import { pick } from 'lodash'; import { Service } from '../../../constants/connected_account'; import { crypto } from '../../../lib/encryption'; import * as paypal from '../../../lib/paypal'; import * as privacy from '../../../lib/privacy'; impor...
throw new ValidationFailed('The token is not a valid TransferWise token'); } } else if (args.connectedAccount.service === Service.PAYPAL) { try { await paypal.validateConnectedAccount(args.connectedAccount); } catch (e) { throw new ValidationFail...
await transferwise.getProfiles(args.connectedAccount.token); } catch (e) {
random_line_split
ConnectedAccountMutations.ts
import express from 'express'; import { GraphQLNonNull } from 'graphql'; import { pick } from 'lodash'; import { Service } from '../../../constants/connected_account'; import { crypto } from '../../../lib/encryption'; import * as paypal from '../../../lib/paypal'; import * as privacy from '../../../lib/privacy'; impor...
} catch (e) { throw new ValidationFailed('The Client ID and Token are not a valid combination'); } } else if (args.connectedAccount.service === Service.PRIVACY) { try { await privacy.listCards(args.connectedAccount.token); } catch (e) { ...
{ if (!args.connectedAccount.token) { throw new ValidationFailed('A token is required'); } const sameTokenCount = await models.ConnectedAccount.count({ where: { hash: crypto.hash(args.connectedAccount.service + args.connectedAccount.token) }, }); if (sameToken...
conditional_block
ConnectedAccountMutations.ts
import express from 'express'; import { GraphQLNonNull } from 'graphql'; import { pick } from 'lodash'; import { Service } from '../../../constants/connected_account'; import { crypto } from '../../../lib/encryption'; import * as paypal from '../../../lib/paypal'; import * as privacy from '../../../lib/privacy'; impor...
(_: void, args, req: express.Request): Promise<Record<string, unknown>> { if (!req.remoteUser) { throw new Unauthorized('You need to be logged in to delete a connected account'); } const connectedAccount = await fetchConnectedAccountWithReference(args.connectedAccount, { throwIfMissin...
resolve
identifier_name
ConnectedAccountMutations.ts
import express from 'express'; import { GraphQLNonNull } from 'graphql'; import { pick } from 'lodash'; import { Service } from '../../../constants/connected_account'; import { crypto } from '../../../lib/encryption'; import * as paypal from '../../../lib/paypal'; import * as privacy from '../../../lib/privacy'; impor...
if (args.connectedAccount.service === Service.TRANSFERWISE) { try { await transferwise.getProfiles(args.connectedAccount.token); } catch (e) { throw new ValidationFailed('The token is not a valid TransferWise token'); } } else if (args.connectedAcco...
{ if (!req.remoteUser) { throw new Unauthorized('You need to be logged in to create a connected account'); } const collective = await fetchAccountWithReference(args.account, { loaders: req.loaders, throwIfMissing: true }); if (!req.remoteUser.isAdminOfCollective(collective)) { t...
identifier_body
argv.js
'use strict'; var _createClass = function () { function
(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor...
defineProperties
identifier_name
argv.js
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.definePro...
}); _this.clear(); _this.list = expandedArgs; })(); } } }, { key: 'expandGetoptNotation', value: function expandGetoptNotation() { var combinedArg = option.combined; var hasGetopt = this.list.some(combinedArg.test.bind(combinedArg)); ...
{ expandedArgs.push(arg); }
conditional_block
argv.js
'use strict'; var _createClass = function () { function defineProperties(target, props)
return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new...
{ for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
identifier_body