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
_student_t_likelihood_function.py
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An...
self._nu = value def __init__(self, nu, num_input=None, data=None, mean_function=None, cov=None, name='Student-t Likelihood Function'): """Initialize the object. Arguments: nu --- The degrees of freedom of the distribution. Keywor...
raise TypeError('nu must be a float.')
conditional_block
_student_t_likelihood_function.py
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An...
"""Evaluate the function at x.""" mu = self.mean_function(x) y = scipy.linalg.solve_triangular(self.L_cov, self.data - mu) return ( - 0.5 * (self.nu + self.num_data) * math.log(1. + np.dot(y, y) / self.nu))
identifier_body
_student_t_likelihood_function.py
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An...
(self, value): """Set the degrees of freedom.""" if not isinstance(value, float): raise TypeError('nu must be a float.') self._nu = value def __init__(self, nu, num_input=None, data=None, mean_function=None, cov=None, name='Student-t Likelihood Function'): ...
nu
identifier_name
bubble.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 ...
axis: { orient: radios( 'y.axis.orient', { left: 'left', right: 'right' }, 'left', ), }, }, size: { field: 'sum__SP_POP_TOTL', type: 'quantitative', scale: { type: 'linear', ...
type: 'quantitative', scale: { type: 'linear', },
random_line_split
pshb.py
# Copyright 2009 Google 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 writing, ...
(self): pass class PshbConnection(base.Connection): def __init__(self, endpoint): self.endpoint = endpoint def publish_async(self, urls): if settings.MANAGE_PY: logging.info('pshb.publish(%s, %s)', self.endpoint, self.urls) return _DevRpc() rpc = urlfetch.create_rpc() def _callbac...
get_result
identifier_name
pshb.py
# Copyright 2009 Google 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 writing, ...
rpc.callback = _callback data = urllib.urlencode( {'hub.url': urls, 'hub.mode': 'publish'}, doseq=True) urlfetch.make_fetch_call(rpc, self.endpoint, method='POST', payload=data) return rpc
result = rpc.get_result() if result.status_code == 204: return raise exception.ServiceError(result.content)
identifier_body
pshb.py
# Copyright 2009 Google 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 writing, ...
raise exception.ServiceError(result.content) rpc.callback = _callback data = urllib.urlencode( {'hub.url': urls, 'hub.mode': 'publish'}, doseq=True) urlfetch.make_fetch_call(rpc, self.endpoint, method='POST', payload=data) return rpc
return
conditional_block
pshb.py
# Copyright 2009 Google 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 writing, ...
rpc = urlfetch.create_rpc() def _callback(): result = rpc.get_result() if result.status_code == 204: return raise exception.ServiceError(result.content) rpc.callback = _callback data = urllib.urlencode( {'hub.url': urls, 'hub.mode': 'publish'}, doseq=True) urlfetch...
return _DevRpc()
random_line_split
color.js
22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa'...
{ const redRatio = red / 255; const greenRatio = green / 255; const blueRatio = blue / 255; const max = Math.max(redRatio, greenRatio, blueRatio); const min = Math.min(redRatio, greenRatio, blueRatio); const delta = max - min; const saturation = max === 0 ? 0 : (delta / max) * 100; const value = max *...
identifier_body
color.js
cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0',...
return returnColor; } if ('red' in options || 'blue' in options || 'green' in options) { const rgb = assign({}, oldColor.rgb, options); const errors = this.getRgbErrors(rgb); if (Object.values(errors).includes(true)) { return assign({}, oldColor, { rgb, errors: assign({}, oldColor.erro...
{ returnColor.name = options.name; }
conditional_block
color.js
cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0',...
(name) { return COLOR_NAMES[name.toLowerCase()] || null; }, getHsvFromRgb({ red, green, blue }) { const redRatio = red / 255;
getHexFromNamedColor
identifier_name
color.js
2cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0'...
slateblue: '#6a5acd', slategray: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellow...
sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb',
random_line_split
work.js
/* eslint no-unused-vars: ["error", {"args": "after-used"}] */ const DEFAULT_USER = process.env.HARBORMASTER_SSH_DEFAULT_USER || 'ubuntu'; const get_user = (manifest) => { return manifest.user || DEFAULT_USER; }; const maybe_get_private_key = (manifest) => { let private_key; if (manifest.use_key && manifest.k...
result = `<pre>${handle_ansi_color(manifest, result)}</pre>`; shipment.stdout[key] = shipment.stdout[key] ? shipment.stdout[key] + result : result ; manifest.result = manifest.result || ''; manifest.result += result.length ? result : ''; shipment.manifest = manifest; Shipments.update(shipment._id...
); const key = new Date();
random_line_split
issue-21361.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
random_line_split
issue-21361.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 ...
{ let v = vec![1, 2, 3]; let boxed: Box<Iterator<Item=i32>> = Box::new(v.into_iter()); assert_eq!(boxed.max(), Some(3)); let v = vec![1, 2, 3]; let boxed: &mut Iterator<Item=i32> = &mut v.into_iter(); assert_eq!(boxed.max(), Some(3)); }
identifier_body
issue-21361.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 ...
() { let v = vec![1, 2, 3]; let boxed: Box<Iterator<Item=i32>> = Box::new(v.into_iter()); assert_eq!(boxed.max(), Some(3)); let v = vec![1, 2, 3]; let boxed: &mut Iterator<Item=i32> = &mut v.into_iter(); assert_eq!(boxed.max(), Some(3)); }
main
identifier_name
GeoLocation.ts
///<reference path='refs.ts'/> module TDev { export module RT { export module GeoLocation { export function isSupported() : boolean { return !!(<any>window).navigator.geolocation; } function getCurrentPosition(accurate : boolean, r : ResumeCtx) { if (isSupported())
else { r.resumeVal(undefined); } } export function currentLocation(r: ResumeCtx) { getCurrentPosition(false, r); } export function currentLocationAccurate(r : ResumeCtx) { getCurrentPosition(true, r); } } } }
{ (<any>window).navigator.geolocation.getCurrentPosition( (position : any) => { var coords = position.coords; var loc = Location_.mk( coords.latitude, coords.longitude, coords.altitude, ...
conditional_block
GeoLocation.ts
///<reference path='refs.ts'/> module TDev { export module RT { export module GeoLocation { export function isSupported() : boolean { return !!(<any>window).navigator.geolocation; } function getCurrentPosition(accurate : boolean, r : ResumeCtx) { if (isSupported()) { ...
} } }
{ getCurrentPosition(true, r); }
identifier_body
GeoLocation.ts
///<reference path='refs.ts'/> module TDev { export module RT { export module GeoLocation { export function isSupported() : boolean { return !!(<any>window).navigator.geolocation; } function getCurrentPosition(accurate : boolean, r : ResumeCtx) { if (isSupported()) { ...
} } }
export function currentLocationAccurate(r : ResumeCtx) { getCurrentPosition(true, r); }
random_line_split
GeoLocation.ts
///<reference path='refs.ts'/> module TDev { export module RT { export module GeoLocation { export function
() : boolean { return !!(<any>window).navigator.geolocation; } function getCurrentPosition(accurate : boolean, r : ResumeCtx) { if (isSupported()) { (<any>window).navigator.geolocation.getCurrentPosition( (position : any) => { var c...
isSupported
identifier_name
forms.py
from django import forms from rango.models import Page, Category, UserProfile class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.Hi...
class Meta: # Provide an association between the ModelForm and a model model = Page # What fields do we want to include in our form? # This way we don't need every field in the model present. # Some fields may allow NULL values, so we may not want to include them... ...
url = 'http://' + url cleaned_data['url'] = url return cleaned_data
conditional_block
forms.py
from django import forms from rango.models import Page, Category, UserProfile class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.Hi...
class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) def clean(self): clea...
model = Category fields = ('name',)
identifier_body
forms.py
from django import forms
class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0) slug = forms.CharField(widget=forms.HiddenInput(),...
from rango.models import Page, Category, UserProfile
random_line_split
forms.py
from django import forms from rango.models import Page, Category, UserProfile class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.Hi...
: # Provide an association between the ModelForm and a model model = Category fields = ('name',) class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL...
Meta
identifier_name
issue-10806.rs
// Copyright 2013-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-MI...
{ let _x = baz::quux(); let _y = grault::garply(); let _z = waldo::plugh(); }
identifier_body
issue-10806.rs
// Copyright 2013-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-MI...
() -> int { 3 } pub fn bar() -> int { 4 } pub mod baz { use {foo, bar}; pub fn quux() -> int { foo() + bar() } } pub mod grault { use {foo}; pub fn garply() -> int { foo() } } pub mod waldo { use {}; pub fn plugh() -> int { 0 } } pub fn main() { ...
foo
identifier_name
issue-10806.rs
// Copyright 2013-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-MI...
let _z = waldo::plugh(); }
pub fn main() { let _x = baz::quux(); let _y = grault::garply();
random_line_split
packagetools.py
#!/usr/bin/env python # JDownloader/src/jd/controlling/LinkGrabberPackager.java import re from urlparse import urlparse def matchFirst(string, *args): """ matches against list of regexp and returns first match""" for patternlist in args: for pattern in patternlist: r = pattern.search(stri...
ffsjPats = [re.compile("(.*)\\._((_[a-z])|([a-z]{2}))(\\.|$)"), re.compile("(.*)(\\.|_|-)[\\d]+(" + endings + "$)", re.I)] iszPats = [re.compile("(.*)\\.isz$", re.I), re.compile("(.*)\\.i\\d{2}$", re.I)] pat1 = re.compile("(\\.?CD\\d+)", re.I) pat2 = re.compile("(\\.?par...
""" Generates packages names from name, data lists :param files: list of (name, data) :return: packagenames mapt to data lists (eg. urls) """ packs = {} endings = "\\.(3gp|7zip|7z|abr|ac3|aiff|aifc|aif|ai|au|avi|bin|bz2|cbr|cbz|ccf|cue|cvd|chm|dta|deb|divx|djvu|dlc|dmg|doc|docx|dot|eps|exe|ff|flv|...
identifier_body
packagetools.py
#!/usr/bin/env python # JDownloader/src/jd/controlling/LinkGrabberPackager.java import re from urlparse import urlparse def matchFirst(string, *args): """ matches against list of regexp and returns first match""" for patternlist in args: for pattern in patternlist: r = pattern.search(stri...
return string def parseNames(files): """ Generates packages names from name, data lists :param files: list of (name, data) :return: packagenames mapt to data lists (eg. urls) """ packs = {} endings = "\\.(3gp|7zip|7z|abr|ac3|aiff|aifc|aif|ai|au|avi|bin|bz2|cbr|cbz|ccf|cue|cvd|chm|dta|d...
name = r.group(1) return name
conditional_block
packagetools.py
#!/usr/bin/env python # JDownloader/src/jd/controlling/LinkGrabberPackager.java import re from urlparse import urlparse def matchFirst(string, *args): """ matches against list of regexp and returns first match""" for patternlist in args: for pattern in patternlist: r = pattern.search(stri...
:param files: list of (name, data) :return: packagenames mapt to data lists (eg. urls) """ packs = {} endings = "\\.(3gp|7zip|7z|abr|ac3|aiff|aifc|aif|ai|au|avi|bin|bz2|cbr|cbz|ccf|cue|cvd|chm|dta|deb|divx|djvu|dlc|dmg|doc|docx|dot|eps|exe|ff|flv|f4v|gsd|gif|gz|iwd|iso|ipsw|java|jar|jpg|jpeg|jdeatm...
def parseNames(files): """ Generates packages names from name, data lists
random_line_split
packagetools.py
#!/usr/bin/env python # JDownloader/src/jd/controlling/LinkGrabberPackager.java import re from urlparse import urlparse def
(string, *args): """ matches against list of regexp and returns first match""" for patternlist in args: for pattern in patternlist: r = pattern.search(string) if r is not None: name = r.group(1) return name return string def parseNames(files...
matchFirst
identifier_name
cef_request_context_handler.rs
// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of ...
#![allow(non_snake_case, unused_imports)] use eutil; use interfaces; use types; use wrappers::CefWrap; use libc; use std::collections::HashMap; use std::ptr; // // Implement this structure to provide handler implementations. // #[repr(C)] pub struct _cef_request_context_handler_t { // // Base structure. // p...
random_line_split
cef_request_context_handler.rs
// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of ...
unsafe fn to_rust(c_object: *mut cef_request_context_handler_t) -> CefRequestContextHandler { CefRequestContextHandler::from_c_object_addref(c_object) } } impl CefWrap<*mut cef_request_context_handler_t> for Option<CefRequestContextHandler> { fn to_c(rust_object: Option<CefRequestContextHandler>) -> *mut cef...
{ rust_object.c_object_addrefed() }
identifier_body
cef_request_context_handler.rs
// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of ...
(&self) -> *mut cef_request_context_handler_t { self.c_object } pub fn c_object_addrefed(&self) -> *mut cef_request_context_handler_t { unsafe { if !self.c_object.is_null() { eutil::add_ref(self.c_object as *mut types::cef_base_t); } self.c_object } } pub fn is_null_cef_o...
c_object
identifier_name
mehuge-rest.ts
/// <reference path="../vendor/jquery.d.ts" /> /// <reference path="../cu/cu.ts" /> declare var Promise: any; declare var $: JQueryStatic; module MehugeRest { var servers: any[] = [], server: string = "Hatchery"; function getServerInfo(server?: string): any { var domain: string = "camelotunchained....
return new Promise(function (fulfill: (data: any) => void, reject: (status: string, errorThrown: string, jqXHR: JQueryXHR) => void) { $.ajax({ url: serverURI + verb, type: params.type || "GET", data: params.query, async: true, cache: fa...
var serverURI = getServerURI(verb); // Raw call the CU RESI API, returns a promise params = params || {};
random_line_split
mehuge-rest.ts
/// <reference path="../vendor/jquery.d.ts" /> /// <reference path="../cu/cu.ts" /> declare var Promise: any; declare var $: JQueryStatic; module MehugeRest { var servers: any[] = [], server: string = "Hatchery"; function getServerInfo(server?: string): any { var domain: string = "camelotunchained....
} export function selectServer(name: string) { server = name; } export function getServers() { return new Promise(function (fulfill: (data: any) => void, reject: (status: string, errorThrown: string, jqXHR: JQueryXHR) => void) { call("servers").then(function (list: any[]) {...
var serverURI = getServerURI(verb); // Raw call the CU RESI API, returns a promise params = params || {}; return new Promise(function (fulfill: (data: any) => void, reject: (status: string, errorThrown: string, jqXHR: JQueryXHR) => void) { $.ajax({ url: serve...
identifier_body
mehuge-rest.ts
/// <reference path="../vendor/jquery.d.ts" /> /// <reference path="../cu/cu.ts" /> declare var Promise: any; declare var $: JQueryStatic; module MehugeRest { var servers: any[] = [], server: string = "Hatchery"; function getServerInfo(server?: string): any { var domain: string = "camelotunchained....
uery: any) { return call("kills", { query: query }); } }
tKills(q
identifier_name
mehuge-rest.ts
/// <reference path="../vendor/jquery.d.ts" /> /// <reference path="../cu/cu.ts" /> declare var Promise: any; declare var $: JQueryStatic; module MehugeRest { var servers: any[] = [], server: string = "Hatchery"; function getServerInfo(server?: string): any { var domain: string = "camelotunchained....
} return { host: (server === "Hatchery" ? "hatchery" : server.toLowerCase()) + "." + domain }; } return { host: "api.citystateentertainment.com" }; } function getServerURI(verb: string) { var host: string, port: numb...
return servers[i]; }
conditional_block
tabs.d.ts
// Type definitions for iview 3.0.0 // Project: https://github.com/iview/iview // Definitions by: yangdan // Definitions: https://github.com/yangdan8/iview.git import Vue, { VNode } from "vue"; export interface Tabs extends Vue { /** * 当前激活 tab 面板的 name,可以使用 v-model 双向绑定数据 * @default 默认为第一项的 name */ value...
/** * 选项卡图标 */ icon?: string; /** * 是否禁用该选项卡 * @default false */ disabled?: boolean; /** * 是否可以关闭页签,仅在 type="card" 时有效 * @default null */ closable?: boolean; }
label?: string | (() => void);
random_line_split
BrowserSync.ts
import webdriver = require('selenium-webdriver'); import Screenshot = require('../Selenium/Screenshot'); import IAction = require('../../common/Test/IAction'); import IDarwinObject = require('../../common/IDarwinObject'); class BrowserSync { private _actions: IAction[]; private _screenshotCounter = 1; private...
} private _handleBrowserResult(darwinObj: IDarwinObject) { if(darwinObj === null) { this._done(this._actions); return; } if(typeof darwinObj === 'undefined') { this._pollBrowser(); } this._actions = darwinObj.actions; if (darwinObj.pendingScreenshot === true) { va...
}, 200);
random_line_split
BrowserSync.ts
import webdriver = require('selenium-webdriver'); import Screenshot = require('../Selenium/Screenshot'); import IAction = require('../../common/Test/IAction'); import IDarwinObject = require('../../common/IDarwinObject'); class BrowserSync { private _actions: IAction[]; private _screenshotCounter = 1; privat...
() { setTimeout(() => { this._driver .executeScript('return window.__darwin.poll();') .then((darwinObj: IDarwinObject) => { this._handleBrowserResult(darwinObj); }, (error) => { // TODO check that error is expected error (browser closed) this._done(this....
_pollBrowser
identifier_name
BrowserSync.ts
import webdriver = require('selenium-webdriver'); import Screenshot = require('../Selenium/Screenshot'); import IAction = require('../../common/Test/IAction'); import IDarwinObject = require('../../common/IDarwinObject'); class BrowserSync { private _actions: IAction[]; private _screenshotCounter = 1; privat...
} } export = BrowserSync;
{ this._pollBrowser(); }
conditional_block
BrowserSync.ts
import webdriver = require('selenium-webdriver'); import Screenshot = require('../Selenium/Screenshot'); import IAction = require('../../common/Test/IAction'); import IDarwinObject = require('../../common/IDarwinObject'); class BrowserSync { private _actions: IAction[]; private _screenshotCounter = 1; privat...
private _handleBrowserResult(darwinObj: IDarwinObject) { if(darwinObj === null) { this._done(this._actions); return; } if(typeof darwinObj === 'undefined') { this._pollBrowser(); } this._actions = darwinObj.actions; if (darwinObj.pendingScreenshot === true) { var s...
{ setTimeout(() => { this._driver .executeScript('return window.__darwin.poll();') .then((darwinObj: IDarwinObject) => { this._handleBrowserResult(darwinObj); }, (error) => { // TODO check that error is expected error (browser closed) this._done(this._ac...
identifier_body
secret.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Inplace inverse secret key (1 / scalar) pub fn inv(&mut self) -> Result<(), Error> { let mut key_secret = self.to_secp256k1_secret()?; key_secret.inv_assign(&SECP256K1)?; *self = key_secret.into(); Ok(()) } /// Compute power of secret key inplace (secret ^ pow). /// This function is not intended to...
{ let mut key_secret = self.to_secp256k1_secret()?; key_secret.mul_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; *self = key_secret.into(); Ok(()) }
identifier_body
secret.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self) -> String { self.inner.to_hex() } } impl fmt::Debug for Secret { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31]) } } impl Secret { pub fn from_slice(key: &[u8]) -> Self { assert_eq!(32,...
to_hex
identifier_name
secret.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Inplace decrease secret key (scalar - 1) pub fn dec(&mut self) -> Result<(), Error> { let mut key_secret = self.to_secp256k1_secret()?; key_secret.add_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; *self = key_secret.into(); Ok(()) } /// Inplace multiply one secret key to another (scalar * scalar) pub fn ...
random_line_split
no-useless-intersection.ts
/* * SonarQube JavaScript Plugin * Copyright (C) 2011-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3...
import { Rule } from 'eslint'; import * as estree from 'estree'; import * as ts from 'typescript'; import { TSESTree } from '@typescript-eslint/experimental-utils'; import { isRequiredParserServices } from '../utils'; export const rule: Rule.RuleModule = { create(context: Rule.RuleContext) { const services = co...
* along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // https://jira.sonarsource.com/browse/RSPEC-4335
random_line_split
no-useless-intersection.ts
/* * SonarQube JavaScript Plugin * Copyright (C) 2011-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3...
function isInterfaceDeclaration( declaration: ts.Declaration, ): declaration is ts.InterfaceDeclaration { return declaration.kind === ts.SyntaxKind.InterfaceDeclaration; }
{ // there is no declarations for `{}` // otherwise check that none of declarations has a heritage clause (`extends X` or `implements X`) if (!typeSymbol) { return false; } const { declarations } = typeSymbol; return ( !declarations || declarations.every(declaration => { return ( i...
identifier_body
no-useless-intersection.ts
/* * SonarQube JavaScript Plugin * Copyright (C) 2011-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3...
}, }; } return {}; }, }; function isTypeWithoutMembers(tp: ts.Type): boolean { return isNullLike(tp) || (isEmptyInterface(tp) && isStandaloneInterface(tp.symbol)); } function isNullLike(tp: ts.Type): boolean { return ( Boolean(tp.flags & ts.TypeFlags.Null) || Boolean(tp.flags & ts...
{ intersection.types.forEach(typeNode => { const tp: ts.Type = services.program .getTypeChecker() .getTypeAtLocation(services.esTreeNodeToTSNodeMap.get(typeNode)); if (isTypeWithoutMembers(tp)) { context.report({ m...
conditional_block
no-useless-intersection.ts
/* * SonarQube JavaScript Plugin * Copyright (C) 2011-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3...
(tp: ts.Type): boolean { return isNullLike(tp) || (isEmptyInterface(tp) && isStandaloneInterface(tp.symbol)); } function isNullLike(tp: ts.Type): boolean { return ( Boolean(tp.flags & ts.TypeFlags.Null) || Boolean(tp.flags & ts.TypeFlags.Undefined) || Boolean(tp.flags & ts.TypeFlags.Void) ); } funct...
isTypeWithoutMembers
identifier_name
stack.py
# Copyright 2017-2019 Tom Eulenfeld, MIT license """Stack correlations""" import numpy as np import obspy from obspy import UTCDateTime as UTC from yam.util import _corr_id, _time2sec, IterTime def
(stream, length=None, move=None): """ Stack traces in stream by correlation id :param stream: |Stream| object with correlations :param length: time span of one trace in the stack in seconds (alternatively a string consisting of a number and a unit -- ``'d'`` for days and ``'h'`` for hou...
stack
identifier_name
stack.py
# Copyright 2017-2019 Tom Eulenfeld, MIT license """Stack correlations""" import numpy as np import obspy from obspy import UTCDateTime as UTC from yam.util import _corr_id, _time2sec, IterTime def stack(stream, length=None, move=None):
traces = [tr for tr in stream if _corr_id(tr) == id_] if length is None: data = np.mean([tr.data for tr in traces], dtype='float16', axis=0) tr_stack = obspy.Trace(data, header=traces[0].stats) tr_stack.stats.key = tr_stack.stats.key + '_s' ...
""" Stack traces in stream by correlation id :param stream: |Stream| object with correlations :param length: time span of one trace in the stack in seconds (alternatively a string consisting of a number and a unit -- ``'d'`` for days and ``'h'`` for hours -- can be specified, i.e. `...
identifier_body
stack.py
# Copyright 2017-2019 Tom Eulenfeld, MIT license """Stack correlations""" import numpy as np import obspy from obspy import UTCDateTime as UTC from yam.util import _corr_id, _time2sec, IterTime def stack(stream, length=None, move=None): """ Stack traces in stream by correlation id :param stream: |Stream...
else: t1 = traces[0].stats.starttime lensec = _time2sec(length) movesec = _time2sec(move) if move else lensec if (lensec % (24 * 3600) == 0 or isinstance(length, str) and 'd' in length): t1 = UTC(t1.year, t1.month, t1.day) ...
data = np.mean([tr.data for tr in traces], dtype='float16', axis=0) tr_stack = obspy.Trace(data, header=traces[0].stats) tr_stack.stats.key = tr_stack.stats.key + '_s' if 'num' in traces[0].stats: tr_stack.stats.num = sum(tr.stats.num for tr...
conditional_block
stack.py
# Copyright 2017-2019 Tom Eulenfeld, MIT license """Stack correlations""" import numpy as np import obspy from obspy import UTCDateTime as UTC from yam.util import _corr_id, _time2sec, IterTime def stack(stream, length=None, move=None): """ Stack traces in stream by correlation id :param stream: |Stream...
in the stacked traces :return: |Stream| object with stacked correlations """ stream.sort() stream_stack = obspy.Stream() ids = {_corr_id(tr) for tr in stream} ids.discard(None) for id_ in ids: traces = [tr for tr in stream if _corr_id(tr) == id_] if length is None: ...
default: None -- no moving stack, if specified move usually is smaller than length to get an overlap
random_line_split
actions.ts
import { TaggedDevice, TaggedWizardStepResult } from "farmbot"; import { DeviceAccountSettings, WizardStepResult, } from "farmbot/dist/resources/api_resources"; import moment from "moment"; import { destroy, edit, initSave, save } from "../api/crud"; import { t } from "../i18next_wrapper"; export const addOrUpdateWi...
}; export const destroyAllWizardStepResults = (wizardStepResults: TaggedWizardStepResult[]) => (dispatch: Function) => confirm(t("Are you sure you want to delete all setup progress?")) ? Promise.all(wizardStepResults.map(result => dispatch(destroy(result.uuid)))) : Promise.reject...
{ return dispatch(initSave("WizardStepResult", stepResult)); }
conditional_block
actions.ts
import { TaggedDevice, TaggedWizardStepResult } from "farmbot"; import { DeviceAccountSettings, WizardStepResult, } from "farmbot/dist/resources/api_resources"; import moment from "moment"; import { destroy, edit, initSave, save } from "../api/crud"; import { t } from "../i18next_wrapper"; export const addOrUpdateWi...
(dispatch: Function) => { dispatch(edit(device, update)); dispatch(save(device.uuid)); };
fb_order_number: value ? value : null as unknown as undefined }); const setDeviceProperty = (device: TaggedDevice, update: Partial<DeviceAccountSettings>) =>
random_line_split
sub-app.ts
import { RouterConfiguration, Router } from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; import { processContent, BehaviorInstruction } from 'aurelia-framework'; @processContent((_: any, __: any, ___: any, behaviorInstuction: BehaviorInstruction) => { behaviorInstuction.inheritBindingContext = false; ...
(e.currentTarget as HTMLElement).scrollLeft += e.deltaY; return false; } return true; } }
onWheel(e: WheelEvent) { if (!e.shiftKey && e.deltaY) {
random_line_split
sub-app.ts
import { RouterConfiguration, Router } from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; import { processContent, BehaviorInstruction } from 'aurelia-framework'; @processContent((_: any, __: any, ___: any, behaviorInstuction: BehaviorInstruction) => { behaviorInstuction.inheritBindingContext = false; ...
}, { route: 'scroller-table-multiple-repeats', moduleId: PLATFORM.moduleName('./scroller-table-multiple-repeats/sub-app'), nav: true, title: 'Scroller + Table + Position Relative + Multiple Repeats' }, { route: 'scroller-not-first-parent-div', modu...
{ config.map([ { name: 'non-issues.main', route: ['', 'get-more-promise'], moduleId: PLATFORM.moduleName('./get-more-promise/sub-app'), nav: true, title: 'Get More + Promise' }, { route: 'scroller-table-position-relative', moduleId: PLATFORM....
identifier_body
sub-app.ts
import { RouterConfiguration, Router } from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; import { processContent, BehaviorInstruction } from 'aurelia-framework'; @processContent((_: any, __: any, ___: any, behaviorInstuction: BehaviorInstruction) => { behaviorInstuction.inheritBindingContext = false; ...
return true; } }
{ (e.currentTarget as HTMLElement).scrollLeft += e.deltaY; return false; }
conditional_block
sub-app.ts
import { RouterConfiguration, Router } from 'aurelia-router'; import { PLATFORM } from 'aurelia-pal'; import { processContent, BehaviorInstruction } from 'aurelia-framework'; @processContent((_: any, __: any, ___: any, behaviorInstuction: BehaviorInstruction) => { behaviorInstuction.inheritBindingContext = false; ...
(e: WheelEvent) { if (!e.shiftKey && e.deltaY) { (e.currentTarget as HTMLElement).scrollLeft += e.deltaY; return false; } return true; } }
onWheel
identifier_name
storage.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {HEADER_OFFSET, LView, TView} from '../interfaces/view'; import {getContextLView} from '../state'; import {loa...
* @param index The index of the local ref in contextViewData. * * @codeGenApi */ export function ɵɵreference<T>(index: number) { const contextLView = getContextLView(); return load<T>(contextLView, index); }
* with a nextContext() call, which walks up the tree and updates the contextViewData instance. *
random_line_split
storage.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {HEADER_OFFSET, LView, TView} from '../interfaces/view'; import {getContextLView} from '../state'; import {loa...
/** * Retrieves a local reference from the current contextViewData. * * If the reference to retrieve is in a parent view, this instruction is used in conjunction * with a nextContext() call, which walks up the tree and updates the contextViewData instance. * * @param index The index of the local ref in contextV...
{ // We don't store any static data for local variables, so the first time // we see the template, we should store as null to avoid a sparse array const adjustedIndex = index + HEADER_OFFSET; if (adjustedIndex >= tView.data.length) { tView.data[adjustedIndex] = null; tView.blueprint[adjustedIndex] = nul...
identifier_body
storage.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {HEADER_OFFSET, LView, TView} from '../interfaces/view'; import {getContextLView} from '../state'; import {loa...
>(index: number) { const contextLView = getContextLView(); return load<T>(contextLView, index); }
ɵɵreference<T
identifier_name
storage.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {HEADER_OFFSET, LView, TView} from '../interfaces/view'; import {getContextLView} from '../state'; import {loa...
lView[adjustedIndex] = value; } /** * Retrieves a local reference from the current contextViewData. * * If the reference to retrieve is in a parent view, this instruction is used in conjunction * with a nextContext() call, which walks up the tree and updates the contextViewData instance. * * @param index The ...
{ tView.data[adjustedIndex] = null; tView.blueprint[adjustedIndex] = null; }
conditional_block
extra-arguments.js
// Copyright 2008 Google Inc. All Rights Reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions a...
; // Make sure we can pass any number of arguments to f and read them // from g. for (var i = 0; i < 25; i++) { var array = new Array(i); var expected = 0; for (var j = 0; j < i; j++) { expected += j; array[j] = j; } assertEquals(expected, f.apply(null, array), String(i)); }
{ var result = 0; var array = f.arguments; for (var i = 0; i < array.length; i++) { result += array[i]; } return result; }
identifier_body
extra-arguments.js
// Copyright 2008 Google Inc. All Rights Reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions a...
// Make sure we can pass any number of arguments to f and read them // from g. for (var i = 0; i < 25; i++) { var array = new Array(i); var expected = 0; for (var j = 0; j < i; j++) { expected += j; array[j] = j; } assertEquals(expected, f.apply(null, array), String(i)); }
};
random_line_split
extra-arguments.js
// Copyright 2008 Google Inc. All Rights Reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions a...
return result; }; // Make sure we can pass any number of arguments to f and read them // from g. for (var i = 0; i < 25; i++) { var array = new Array(i); var expected = 0; for (var j = 0; j < i; j++) { expected += j; array[j] = j; } assertEquals(expected, f.apply(null, array), String(i)); }
{ result += array[i]; }
conditional_block
extra-arguments.js
// Copyright 2008 Google Inc. All Rights Reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions a...
() { var result = 0; var array = f.arguments; for (var i = 0; i < array.length; i++) { result += array[i]; } return result; }; // Make sure we can pass any number of arguments to f and read them // from g. for (var i = 0; i < 25; i++) { var array = new Array(i); var expected = 0; for (var j = 0; j...
g
identifier_name
kill.rs
#![crate_name = "uu_kill"] /* * This file is part of the uutils coreutils package. * * (c) Maciej Dziardziel <fiedzia@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_us...
(signalname: &str, pids: std::vec::Vec<String>) -> i32 { let mut status = 0; let optional_signal_value = uucore::signals::signal_by_name_or_value(signalname); let signal_value = match optional_signal_value { Some(x) => x, None => crash!(EXIT_ERR, "unknown signal name {}", signalname) }; ...
kill
identifier_name
kill.rs
#![crate_name = "uu_kill"] /* * This file is part of the uutils coreutils package. * * (c) Maciej Dziardziel <fiedzia@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_us...
} fn table() { let mut name_width = 0; /* Compute the maximum width of a signal name. */ for s in &ALL_SIGNALS { if s.name.len() > name_width { name_width = s.name.len() } } for (idx, signal) in ALL_SIGNALS.iter().enumerate() { print!("{0: >#2} {1: <#8}", idx+1...
{ let mut i = 0; while i < args.len() { // this is safe because slice is valid when it is referenced let slice = &args[i].clone(); if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { let val = &slice[1..]; mat...
identifier_body
kill.rs
#![crate_name = "uu_kill"] /* * This file is part of the uutils coreutils package. * * (c) Maciej Dziardziel <fiedzia@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; extern crate libc; #[macro_us...
pos = 0; } else { pos += 1; print!(" "); } } } fn list(arg: Option<String>) { match arg { Some(ref x) => print_signal(x), None => print_signals(), }; } fn help(opts: &getopts::Options) { let msg = format!("{0} {1} Usage: {0} [options] <...
print!("{}", signal.name); if idx > 0 && pos > 73 { println!("");
random_line_split
bpfs_recovery.ts
import 'bluebird-global' import 'reflect-metadata' // eslint-disable-next-line import/order import './sdk/rewire' import chalk from 'chalk' import { container } from 'core/app/inversify/app.inversify' import { GhostService } from 'core/bpfs' import Database from 'core/database' import { TYPES } from 'core/types' impor...
const destFolder = path.dirname(dest || file) const destFile = path.basename(dest || file) await ghost.root().upsertFile(destFolder, destFile, fs.readFileSync(path.resolve(file), 'UTF-8')) console.info(chalk.green(`File "${file}" saved at ${path.join(destFolder, destFile)}`)) } process.exit() }
{ console.error(`File ${file} doesn't exist locally.`) process.exit() }
conditional_block
bpfs_recovery.ts
import 'bluebird-global' import 'reflect-metadata' // eslint-disable-next-line import/order import './sdk/rewire' import chalk from 'chalk' import { container } from 'core/app/inversify/app.inversify' import { GhostService } from 'core/bpfs' import Database from 'core/database' import { TYPES } from 'core/types' impor...
process.exit() } if (!file) { console.error(chalk.red('The --file parameter is required')) process.exit() } if (action === 'pullfile') { let rootFolder = path.dirname(file) const filename = path.basename(file) if (rootFolder.startsWith('data/')) { rootFolder = rootFolder.replace...
console.info(`Directory listing of ${path.join('data', argv.list)} =========================================`) const files = await ghost.root().directoryListing(argv.list) files.forEach(file => console.info(chalk.green(` - ${file}`)))
random_line_split
G_farthest_BST_sum.py
""" given a BST, find the two nodes that sums up to a value and are the farthest apart. """ class Tree: def __init__(self, val): self.val = val self.left = self.right = None def __repr__(self): return '[ %d ]' % self.val def get_tree(): def build_tree(vals): if not vals: ...
return root, path if __name__ == '__main__': # print_tree(get_tree()) print(Solution().find_farthest_nodes(get_tree(), 7))
root = root.right
random_line_split
G_farthest_BST_sum.py
""" given a BST, find the two nodes that sums up to a value and are the farthest apart. """ class Tree: def __init__(self, val): self.val = val self.left = self.right = None def __repr__(self):
def get_tree(): def build_tree(vals): if not vals: return mid = len(vals) / 2 root = Tree(vals[mid]) root.left = build_tree(vals[:mid]) root.right = build_tree(vals[mid+1:]) return root return build_tree(range(1, 8)) def print_tree(r): stack = [...
return '[ %d ]' % self.val
identifier_body
G_farthest_BST_sum.py
""" given a BST, find the two nodes that sums up to a value and are the farthest apart. """ class Tree: def __init__(self, val): self.val = val self.left = self.right = None def __repr__(self): return '[ %d ]' % self.val def get_tree(): def build_tree(vals): if not vals: ...
return root, path if __name__ == '__main__': # print_tree(get_tree()) print(Solution().find_farthest_nodes(get_tree(), 7))
root = root.right
conditional_block
G_farthest_BST_sum.py
""" given a BST, find the two nodes that sums up to a value and are the farthest apart. """ class Tree: def __init__(self, val): self.val = val self.left = self.right = None def __repr__(self): return '[ %d ]' % self.val def get_tree(): def build_tree(vals): if not vals: ...
(self, tree, sums): values = self.in_order(tree) distance = 0 nodes = [0, 0] for val in values: if val > sums or val > sums - val: break if self.bs(values, sums - val): d, n1, n2 = self.find_distance(tree, val, sums - val) ...
find_farthest_nodes
identifier_name
test_schedule_jobs.py
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
module_name = 'test_jobs.test_schedule_jobs' assert len(sched_jobs) == 2, sched_jobs assert module_name + '.a_function' in job_func_names, job_func_names assert module_name + '.another_function' in job_func_names, job_func_names def test_does_not_add_job_if_already_added(self): ...
job_func_names = [job.func_name for job in sched_jobs]
random_line_split
test_schedule_jobs.py
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
def test_adds_several_jobs_(self): schedule_job(a_job, self.scheduler) schedule_job(another_job, self.scheduler) sched_jobs = self.scheduler.get_jobs() job_func_names = [job.func_name for job in sched_jobs] module_name = 'test_jobs.test_schedule_jobs' assert len(sc...
a_job['interval'] = 7 schedule_job(a_job, self.scheduler) sched_jobs = self.scheduler.get_jobs() assert len(sched_jobs) == 1, sched_jobs assert sched_jobs[0].meta['interval'] == 7 , sched_jobs[0].meta a_job['interval'] = 1
identifier_body
test_schedule_jobs.py
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
(): return a_job = dict(name=a_function, args=[], kwargs={}, interval=1, timeout=180) another_job = dict(name=another_function, args=[], kwargs={}, interval=1, timeout=180) class TestSetupScheduledJobs(object): """Tests for setup function 'schedule_job'""" def setUp(self)...
another_function
identifier_name
Es_monthly.py
# -*- coding: utf-8 -*- """ Created on Wed Jan 03 09:36:48 2018 @author: tih """ import os import sys from DataAccess import DownloadData def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1):
if __name__ == '__main__': main(sys.argv)
""" This function downloads monthly ETmonitor data Keyword arguments: Dir -- 'C:/file/to/path/' Startdate -- 'yyyy-mm-dd' Enddate -- 'yyyy-mm-dd' latlim -- [ymin, ymax] (values must be between -60 and 70) lonlim -- [xmin, xmax] (values must be between -180 and 180) """ print '\nDown...
identifier_body
Es_monthly.py
# -*- coding: utf-8 -*- """ Created on Wed Jan 03 09:36:48 2018 @author: tih """ import os import sys from DataAccess import DownloadData def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1): """ This function downloads monthly ETmonitor data Keyword arguments: ...
main(sys.argv)
conditional_block
Es_monthly.py
# -*- coding: utf-8 -*- """ Created on Wed Jan 03 09:36:48 2018 @author: tih """ import os import sys from DataAccess import DownloadData def
(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1): """ This function downloads monthly ETmonitor data Keyword arguments: Dir -- 'C:/file/to/path/' Startdate -- 'yyyy-mm-dd' Enddate -- 'yyyy-mm-dd' latlim -- [ymin, ymax] (values must be between -60 and 70) ...
main
identifier_name
Es_monthly.py
# -*- coding: utf-8 -*- """ Created on Wed Jan 03 09:36:48 2018 @author: tih """ import os import sys from DataAccess import DownloadData def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1): """ This function downloads monthly ETmonitor data Keyword arguments: ...
if __name__ == '__main__': main(sys.argv)
# Download data DownloadData(Dir, Startdate, Enddate, latlim, lonlim, Type, Waitbar)
random_line_split
validation.ts
/* eslint-disable no-shadow */ import { ValidationFn } from './types' export const required: ValidationFn = (value) => { return value.length === 0 } export const email: ValidationFn = (value) => { const emailRegex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])...
export const min: ValidationFn = (value, min) => { if (!min) return true return Number(value) < min } export const max: ValidationFn = (value, max) => { if (!max) return true return Number(value) > max }
}
random_line_split
main.rs
#![warn(clippy::all)] mod channel; mod guild; use std::sync::Arc; use async_trait::async_trait; use parking_lot::RwLock; use rendezvous_common::{ anyhow, futures::prelude::*, proto::{ bouncer_service_client::BouncerServiceClient, event, ClientType, Event, Header, MessageCreated, UserRenam...
} async fn guild_member_update(&self, _ctx: Context, new: model::event::GuildMemberUpdateEvent) { let guild_id = new.guild_id; let new = UserData::from(new); let mut event = None; if let Some(m) = self .guilds .write() .get_mut(&guild_id) ...
{ g.members.remove(&user.id); }
conditional_block
main.rs
#![warn(clippy::all)] mod channel; mod guild; use std::sync::Arc; use async_trait::async_trait; use parking_lot::RwLock; use rendezvous_common::{ anyhow, futures::prelude::*, proto::{ bouncer_service_client::BouncerServiceClient, event, ClientType, Event, Header, MessageCreated, UserRenam...
fn register_guild_channel<'a>(&'a self, channel: &GuildChannel) -> bool { if channel.kind != ChannelType::Text { return false; } self.channels .write() .get_or_insert_with(channel.id, || Channel::Guild(channel.clone())); true } } #[async_tra...
{ let mut lock = self.guilds.write(); lock.insert(guild.id, guild.into()) }
identifier_body
main.rs
#![warn(clippy::all)] mod channel; mod guild; use std::sync::Arc; use async_trait::async_trait; use parking_lot::RwLock; use rendezvous_common::{ anyhow, futures::prelude::*, proto::{ bouncer_service_client::BouncerServiceClient, event, ClientType, Event, Header, MessageCreated, UserRenam...
current_user: RwLock<Option<model::user::CurrentUser>>, rpc_client: BouncerServiceClient<transport::Channel>, } impl Handler { fn new(rpc_client: BouncerServiceClient<transport::Channel>) -> Self { Handler { guilds: Default::default(), channels: Default::default(), ...
struct Handler { guilds: RwLock<GuildMap>, channels: Arc<RwLock<ChannelList>>,
random_line_split
main.rs
#![warn(clippy::all)] mod channel; mod guild; use std::sync::Arc; use async_trait::async_trait; use parking_lot::RwLock; use rendezvous_common::{ anyhow, futures::prelude::*, proto::{ bouncer_service_client::BouncerServiceClient, event, ClientType, Event, Header, MessageCreated, UserRenam...
(&self, guild: Guild) -> Option<GuildData> { let mut lock = self.guilds.write(); lock.insert(guild.id, guild.into()) } fn register_guild_channel<'a>(&'a self, channel: &GuildChannel) -> bool { if channel.kind != ChannelType::Text { return false; } self.channe...
insert_guild
identifier_name
_version.py
LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][...
"""Exception raised if a method is not valid for the current scenario."""
identifier_body
_version.py
stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the...
describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improve...
raise NotThisMethod("'git describe' failed")
conditional_block
_version.py
(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), ...
random_line_split
_version.py
*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: ...
render_pep440_post
identifier_name
server.js
'use strict' const assert = require('assert') const http = require('http') const https = require('https') const { kState, kOptions } = require('./symbols') const { codes: { FST_ERR_HTTP2_INVALID_VERSION } } = require('./errors') function createServer (options, httpHandler) { assert(options, 'Missing options') ...
} else { /* Deal with listen ([port[, host[, backlog]]]) */ options.port = argsLength >= 1 && firstArg ? firstArg : 0 // This will listen to what localhost is. // It can be 127.0.0.1 or ::1, depending on the operating system. // Fixes https://github.com/fastify/fastify/issu...
{ const normalizeListenArgs = (args) => { if (args.length === 0) { return { port: 0, host: 'localhost' } } const cb = typeof args[args.length - 1] === 'function' ? args.pop() : undefined const options = { cb: cb } const firstArg = args[0] const argsLength = args.length ...
identifier_body
server.js
'use strict' const assert = require('assert') const http = require('http') const https = require('https') const { kState, kOptions } = require('./symbols') const { codes: { FST_ERR_HTTP2_INVALID_VERSION } } = require('./errors') function createServer (options, httpHandler) { assert(options, 'Missing options') ...
() { this.close() } module.exports = { createServer }
close
identifier_name
server.js
'use strict' const assert = require('assert') const http = require('http') const https = require('https') const { kState, kOptions } = require('./symbols') const { codes: { FST_ERR_HTTP2_INVALID_VERSION } } = require('./errors') function createServer (options, httpHandler) { assert(options, 'Missing options') ...
} const logServerAddress = () => { var address = server.address() const isUnixSocket = typeof address === 'string' if (!isUnixSocket) { if (address.address.indexOf(':') === -1) { address = address.address + ':' + address.port } else { address = '[' + addres...
})
random_line_split
app.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import Location from '....
() { const container = document.getElementById('app'); Location.listen(location => { route(location.pathname, async (component) => ReactDOM.render(component, container, () => { // Track the page view event via Google Analytics window.ga('send', 'pageview'); })); }); } if (canUseDOM) { // Run ...
run
identifier_name
app.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import Location from '....
if (canUseDOM) { // Run the application when both DOM is ready // and page content is loaded if (window.addEventListener) { window.addEventListener('DOMContentLoaded', run); } else { window.attachEvent('onload', run); } } export default { route, routes };
{ const container = document.getElementById('app'); Location.listen(location => { route(location.pathname, async (component) => ReactDOM.render(component, container, () => { // Track the page view event via Google Analytics window.ga('send', 'pageview'); })); }); }
identifier_body
app.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import Location from '....
else { window.attachEvent('onload', run); } } export default { route, routes };
{ window.addEventListener('DOMContentLoaded', run); }
conditional_block
app.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import Location from '....
if (window.addEventListener) { window.addEventListener('DOMContentLoaded', run); } else { window.attachEvent('onload', run); } } export default { route, routes };
// Run the application when both DOM is ready // and page content is loaded
random_line_split