file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
context.js
var url = require('url') , path = require('path') , fs = require('fs') , utils = require('./utils') , EventEmitter = require('events').EventEmitter exports = module.exports = Context function Context(app, req, res) { var self = this this.app = app this.req = req this.res = res this.done = ...
done: function(err) { if (this._notifiedDone === true) return if (err) { if (this.writable) { this.resHeaders = {} this.type = 'text/plain' this.status = err.code === 'ENOENT' ? 404 : (err.status || 500) this.length = Buffer.byteLength(err.message) this.res.end(er...
Context.prototype = {
random_line_split
vmware_local_user_manager.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, IBM Corp # Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE...
self.state = self.module.params['state'] if self.is_vcenter(): self.module.fail_json(msg="Failed to get local account manager settings " "from ESXi server: %s" % self.module.params['hostname'], details="It seems that %s...
def __init__(self, module): super(VMwareLocalUserManager, self).__init__(module) self.local_user_name = self.module.params['local_user_name'] self.local_user_password = self.module.params['local_user_password'] self.local_user_description = self.module.params['local_user_description'...
random_line_split
vmware_local_user_manager.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, IBM Corp # Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE...
def create_account_spec(self): account_spec = vim.host.LocalAccountManager.AccountSpecification() account_spec.id = self.local_user_name account_spec.password = self.local_user_password account_spec.description = self.local_user_description return account_spec def stat...
searchStr = self.local_user_name exactMatch = True findUsers = True findGroups = False user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups) return user_account
identifier_body
vmware_local_user_manager.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, IBM Corp # Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE...
(self): searchStr = self.local_user_name exactMatch = True findUsers = True findGroups = False user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups) return user_account def create_account_spec(sel...
find_user_account
identifier_name
vmware_local_user_manager.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, IBM Corp # Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE...
def find_user_account(self): searchStr = self.local_user_name exactMatch = True findUsers = True findGroups = False user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups) return user_account ...
return 'present'
conditional_block
ng-admin.js
/*global require,define,angular*/ define('angular', [], function () { 'use strict'; return angular; }); require.config({ paths: { 'angular-bootstrap': 'bower_components/angular-bootstrap/ui-bootstrap.min', 'angular-bootstrap-tpls': 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min...
'papaparse': 'bower_components/papaparse/papaparse.min', 'MainModule': 'ng-admin/Main/MainModule', 'AdminDescription': '../../build/ng-admin-configuration' }, shim: { 'papaparse': { exports: 'Papa' }, 'restangular': { deps: ['angular', 'lod...
random_line_split
AlgoliaSearchProvider.tsx
import React, { createContext, useMemo, useCallback, useContext, FC } from 'react'; import algoliasearch from 'algoliasearch'; import { searchRelatedArticles, AlgoliaArticle, SearchRelatedArticlesResult } from './algoliaRelatedArticles'; const createAlgoliaIndex = (algoliaSearchKeys: AlgoliaSearchKey...
type AlgoliaSearchContextType = { getRelatedArticles?: () => Promise<SearchRelatedArticlesResult | null>; }; const AlgoliaSearchContext = createContext<AlgoliaSearchContextType>({}); export const AlgoliaSearchProvider: FC<AlgoliaSearchProps> = ({ algoliaSearchKeys, article, analyticsStream, children }) => { ...
random_line_split
AlgoliaSearchProvider.tsx
import React, { createContext, useMemo, useCallback, useContext, FC } from 'react'; import algoliasearch from 'algoliasearch'; import { searchRelatedArticles, AlgoliaArticle, SearchRelatedArticlesResult } from './algoliaRelatedArticles'; const createAlgoliaIndex = (algoliaSearchKeys: AlgoliaSearchKey...
return null; }; type AlgoliaSearchContextType = { getRelatedArticles?: () => Promise<SearchRelatedArticlesResult | null>; }; const AlgoliaSearchContext = createContext<AlgoliaSearchContextType>({}); export const AlgoliaSearchProvider: FC<AlgoliaSearchProps> = ({ algoliaSearchKeys, article, analyticsStream,...
{ const { applicationId, apiKey, indexName } = algoliaSearchKeys; return algoliasearch(applicationId, apiKey).initIndex(indexName); }
conditional_block
number.js
'use strict'; // MODULES // var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' ); // QUANTILE // /** * FUNCTION: quantile( p, d1, d2 ) * Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`. * * @pa...
bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p ); x1 = bVal[ 0 ]; x2 = bVal[ 1 ]; return d2 * x1 / ( d1 * x2 ); } // end FUNCTION quantile() // EXPORTS // module.exports = quantile;
{ return NaN; }
conditional_block
number.js
'use strict'; // MODULES // var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' ); // QUANTILE // /** * FUNCTION: quantile( p, d1, d2 ) * Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`. * * @pa...
( p, d1, d2 ) { var bVal, x1, x2; if ( p !== p || p < 0 || p > 1 ) { return NaN; } bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p ); x1 = bVal[ 0 ]; x2 = bVal[ 1 ]; return d2 * x1 / ( d1 * x2 ); } // end FUNCTION quantile() // EXPORTS // module.exports = quantile;
quantile
identifier_name
number.js
'use strict'; // MODULES // var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' ); // QUANTILE // /** * FUNCTION: quantile( p, d1, d2 ) * Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`. * * @pa...
// EXPORTS // module.exports = quantile;
{ var bVal, x1, x2; if ( p !== p || p < 0 || p > 1 ) { return NaN; } bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p ); x1 = bVal[ 0 ]; x2 = bVal[ 1 ]; return d2 * x1 / ( d1 * x2 ); } // end FUNCTION quantile()
identifier_body
number.js
'use strict'; // MODULES // var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' ); // QUANTILE // /** * FUNCTION: quantile( p, d1, d2 ) * Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`. *
* @param {Number} p - input value * @param {Number} d1 - numerator degrees of freedom * @param {Number} d2 - denominator degrees of freedom * @returns {Number} evaluated quantile function */ function quantile( p, d1, d2 ) { var bVal, x1, x2; if ( p !== p || p < 0 || p > 1 ) { return NaN; } bVal = betaincinv( d1 /...
random_line_split
core_sphere.rs
extern crate rustcmb; use rustcmb::core::sphere; const SIZE: usize = 4; fn main() { let default_field = sphere::Field::default(); let field = sphere::Field::new(SIZE); let mut mut_field = sphere::Field::new(SIZE); println!("default_field: {:?}", default_field); println!("field: {:?}", field); ...
let mut foo_coef = sphere::Coef::new(SIZE); for l in foo_coef.a_l_begin()..foo_coef.a_l_end() { for m in foo_coef.a_m_begin()..foo_coef.a_m_end(l) { *foo_coef.a_at_mut(l, m) = (l + m + 5) as f64; } } for i in foo_coef.b_l_begin()..foo_coef.b_l_end() { for j in foo_...
random_line_split
core_sphere.rs
extern crate rustcmb; use rustcmb::core::sphere; const SIZE: usize = 4; fn
() { let default_field = sphere::Field::default(); let field = sphere::Field::new(SIZE); let mut mut_field = sphere::Field::new(SIZE); println!("default_field: {:?}", default_field); println!("field: {:?}", field); println!("mut_field: {:?}", mut_field); println!("field size: {:?}", field....
main
identifier_name
core_sphere.rs
extern crate rustcmb; use rustcmb::core::sphere; const SIZE: usize = 4; fn main()
{ let default_field = sphere::Field::default(); let field = sphere::Field::new(SIZE); let mut mut_field = sphere::Field::new(SIZE); println!("default_field: {:?}", default_field); println!("field: {:?}", field); println!("mut_field: {:?}", mut_field); println!("field size: {:?}", field.siz...
identifier_body
test_cp2_x_cincoffset_sealed.py
#- # Copyright (c) 2014 Michael Roe # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BER...
(self): '''Test that CIncOffset on a sealed capability does not change the offsrt''' self.assertRegisterEqual(self.MIPS.a0, 0, "CIncOffset changed the offset of a sealed capability") @attr('capabilities') def test_cp2_x_cincoffset_sealed_2(self): '''Test that CIncOffset on a sealed capability ...
test_cp2_x_cincoffset_sealed_1
identifier_name
test_cp2_x_cincoffset_sealed.py
#- # Copyright (c) 2014 Michael Roe # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BER...
@attr('capabilities') def test_cp2_x_cincoffset_sealed_1(self): '''Test that CIncOffset on a sealed capability does not change the offsrt''' self.assertRegisterEqual(self.MIPS.a0, 0, "CIncOffset changed the offset of a sealed capability") @attr('capabilities') def test_cp2_x_cincoffset_sealed_2(se...
identifier_body
test_cp2_x_cincoffset_sealed.py
#- # Copyright (c) 2014 Michael Roe # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BER...
# # Unless required by applicable law or agreed to in writing, Work distributed # under the License is distributed on an "AS IS" BASIS, 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. # # @BE...
# # http://www.beri-open-systems.org/legal/license-1-0.txt
random_line_split
test_diff.py
#!/usr/bin/env python # encoding: utf-8 import unittest import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), "..")) from _diff import diff, guess_edit from geometry import Position def transform(a, cmds): buf = a.split("\n") for cmd in cmds: ctype, line, col, char = cmd if...
class TestCommonCharacters(_Base, unittest.TestCase): a,b = "hasomelongertextbl", "hol" wanted = ( ("D", 0, 1, "asomelongertextb"), ("I", 0, 1, "o"), ) class TestUltiSnipsProblem(_Base, unittest.TestCase): a = "this is it this is it this is it" b = "this is it a this is it" wa...
a,b = "abc", "def" wanted = ( ("D", 0, 0, "abc"), ("I", 0, 0, "def"), )
identifier_body
test_diff.py
#!/usr/bin/env python # encoding: utf-8 import unittest import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), "..")) from _diff import diff, guess_edit from geometry import Position def transform(a, cmds): buf = a.split("\n") for cmd in cmds: ctype, line, col, char = cmd if...
else: buf[line] = buf[line] + buf[line+1] del buf[line+1] elif ctype == "I": buf[line] = buf[line][:col] + char + buf[line][col:] buf = '\n'.join(buf).split('\n') return '\n'.join(buf) import unittest # Test Guessing {{{ class _BaseGuessin...
buf[line] = buf[line][:col] + buf[line][col+len(char):]
conditional_block
test_diff.py
#!/usr/bin/env python # encoding: utf-8 import unittest import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), "..")) from _diff import diff, guess_edit from geometry import Position def transform(a, cmds): buf = a.split("\n") for cmd in cmds: ctype, line, col, char = cmd if...
wanted = ( ("D", 0, 0, "abc"), ("I", 0, 0, "def"), ) class TestCommonCharacters(_Base, unittest.TestCase): a,b = "hasomelongertextbl", "hol" wanted = ( ("D", 0, 1, "asomelongertextb"), ("I", 0, 1, "o"), ) class TestUltiSnipsProblem(_Base, unittest.TestCase): a =...
class TestNoSubstring(_Base, unittest.TestCase): a,b = "abc", "def"
random_line_split
test_diff.py
#!/usr/bin/env python # encoding: utf-8 import unittest import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), "..")) from _diff import diff, guess_edit from geometry import Position def transform(a, cmds): buf = a.split("\n") for cmd in cmds: ctype, line, col, char = cmd if...
(_Base, unittest.TestCase): a, b = "abcdef", "abcdef" wanted = () class TestLotsaNewlines(_Base, unittest.TestCase): a, b = "Hello", "Hello\nWorld\nWorld\nWorld" wanted = ( ("I", 0, 5, "\n"), ("I", 1, 0, "World"), ("I", 1, 5, "\n"), ("I", 2, 0, "World"), ("I", 2,...
TestAllMatch
identifier_name
views.py
from django.shortcuts import render from django.conf import settings from common.views import AbsSegmentSelection #from common.views import AbsTargetSelection from common.views import AbsTargetSelectionTable # from common.alignment_SITE_NAME import Alignment from protwis.context_processors import site_title Alignment...
(AbsTargetSelectionTable): step = 1 number_of_steps = 2 title = "SELECT RECEPTORS" description = "Select receptors in the table (below) or browse the classification tree (right). You can select entire" \ + " families or individual receptors.\n\nOnce you have selected all your receptors, click th...
TargetSelection
identifier_name
views.py
from django.shortcuts import render from django.conf import settings from common.views import AbsSegmentSelection #from common.views import AbsTargetSelection from common.views import AbsTargetSelectionTable # from common.alignment_SITE_NAME import Alignment from protwis.context_processors import site_title Alignment...
def render_csv_matrix(request): # get the user selection from session simple_selection = request.session.get('selection', False) # create an alignment object a = Alignment() a.show_padding = False # load data from selection into the alignment a.load_proteins_from_selection(simple_selecti...
simple_selection = request.session.get('selection', False) # create an alignment object a = Alignment() # load data from selection into the alignment a.load_proteins_from_selection(simple_selection) a.load_segments_from_selection(simple_selection) # build the alignment data matrix a.build...
identifier_body
views.py
from django.shortcuts import render from django.conf import settings from common.views import AbsSegmentSelection #from common.views import AbsTargetSelection from common.views import AbsTargetSelectionTable # from common.alignment_SITE_NAME import Alignment from protwis.context_processors import site_title Alignment...
# }, # } class SegmentSelection(AbsSegmentSelection): step = 2 number_of_steps = 2 docs = 'sequences.html#similarity-matrix' selection_boxes = OrderedDict([ ('reference', False), ('targets', False), ('segments', True), ]) buttons = { 'continue': { ...
# 'continue': { # 'label': 'Continue to next step', # 'url': '/similaritymatrix/segmentselection', # 'color': 'success',
random_line_split
forEach.js
"use strict"; var Activity = require("./activity"); var util = require("util"); var _ = require("lodash"); var is = require("../common/is"); var Block = require("./block"); var WithBody = require("./withBody"); var errors = require("../common/errors"); function ForEach()
util.inherits(ForEach, WithBody); ForEach.prototype.initializeStructure = function () { if (this.parallel) { var numCPUs = require("os").cpus().length; this._bodies = []; if (this.args && this.args.length) { for (var i = 0; i < Math.min(process.env.UV_THREADPOOL_SIZE || 100000...
{ WithBody.call(this); this.items = null; this.varName = "item"; this.parallel = false; this._bodies = null; }
identifier_body
forEach.js
"use strict"; var Activity = require("./activity"); var util = require("util"); var _ = require("lodash"); var is = require("../common/is"); var Block = require("./block"); var WithBody = require("./withBody"); var errors = require("../common/errors"); function ForEach() { WithBody.call(this); this.items = n...
while (remainingItems.length && idx < bodies.length) { var item = remainingItems[0]; remainingItems.splice(0, 1); var variables = {}; variables[varName] = item; pack.push({ variables: variables, ...
if (remainingItems && remainingItems.length) { if (this.parallel) { var bodies = this._bodies; var pack = []; var idx = 0;
random_line_split
forEach.js
"use strict"; var Activity = require("./activity"); var util = require("util"); var _ = require("lodash"); var is = require("../common/is"); var Block = require("./block"); var WithBody = require("./withBody"); var errors = require("../common/errors"); function ForEach() { WithBody.call(this); this.items = n...
else { var item = remainingItems[0]; remainingItems.splice(0, 1); var variables = {}; variables[varName] = item; callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished"); } return; } if (iterator) { ...
{ var bodies = this._bodies; var pack = []; var idx = 0; while (remainingItems.length && idx < bodies.length) { var item = remainingItems[0]; remainingItems.splice(0, 1); var variables = {}; variables[varName...
conditional_block
forEach.js
"use strict"; var Activity = require("./activity"); var util = require("util"); var _ = require("lodash"); var is = require("../common/is"); var Block = require("./block"); var WithBody = require("./withBody"); var errors = require("../common/errors"); function
() { WithBody.call(this); this.items = null; this.varName = "item"; this.parallel = false; this._bodies = null; } util.inherits(ForEach, WithBody); ForEach.prototype.initializeStructure = function () { if (this.parallel) { var numCPUs = require("os").cpus().length; this._bodie...
ForEach
identifier_name
firstValueFrom.ts
import { Observable } from './Observable'; import { EmptyError } from './util/EmptyError'; import { SafeSubscriber } from './Subscriber'; export interface FirstValueFromConfig<T> { defaultValue: T; } export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>; export...
}, }); source.subscribe(subscriber); }); }
{ reject(new EmptyError()); }
conditional_block
firstValueFrom.ts
import { Observable } from './Observable'; import { EmptyError } from './util/EmptyError'; import { SafeSubscriber } from './Subscriber'; export interface FirstValueFromConfig<T> { defaultValue: T; } export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>; export...
{ const hasConfig = typeof config === 'object'; return new Promise<T | D>((resolve, reject) => { const subscriber = new SafeSubscriber<T>({ next: (value) => { resolve(value); subscriber.unsubscribe(); }, error: reject, complete: () => { if (hasConfig) { ...
identifier_body
firstValueFrom.ts
import { Observable } from './Observable'; import { EmptyError } from './util/EmptyError'; import { SafeSubscriber } from './Subscriber'; export interface FirstValueFromConfig<T> { defaultValue: T; } export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>; export...
<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> { const hasConfig = typeof config === 'object'; return new Promise<T | D>((resolve, reject) => { const subscriber = new SafeSubscriber<T>({ next: (value) => { resolve(value); subscriber.unsubscribe(); }, ...
firstValueFrom
identifier_name
firstValueFrom.ts
import { Observable } from './Observable'; import { EmptyError } from './util/EmptyError'; import { SafeSubscriber } from './Subscriber'; export interface FirstValueFromConfig<T> { defaultValue: T; } export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>; export...
* Wait for the first value from a stream and emit it from a promise in * an async function. * * ```ts * import { interval, firstValueFrom } from 'rxjs'; * * async function execute() { * const source$ = interval(2000); * const firstNumber = await firstValueFrom(source$); * console.log(`The first number i...
* something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil} * amongst others. * * ### Example *
random_line_split
categorical_color_mapper.ts
import {ColorMapper} from "./color_mapper" import {Factor} from "../ranges/factor_range" import * as p from "core/properties" import {Arrayable} from "core/types" import {findIndex} from "core/util/array" import {isString} from "core/util/types" function _equals(a: Arrayable<any>, b: Arrayable<any>): boolean { if (...
protected _v_compute<T>(data: Arrayable<Factor>, values: Arrayable<T>, palette: Arrayable<T>, {nan_color}: {nan_color: T}): void { for (let i = 0, end = data.length; i < end; i++) { let d = data[i] let key: number if (isString(d)) key = this.factors.indexOf(d) else { ...
}
random_line_split
categorical_color_mapper.ts
import {ColorMapper} from "./color_mapper" import {Factor} from "../ranges/factor_range" import * as p from "core/properties" import {Arrayable} from "core/types" import {findIndex} from "core/util/array" import {isString} from "core/util/types" function
(a: Arrayable<any>, b: Arrayable<any>): boolean { if (a.length != b.length) return false for (let i = 0, end = a.length; i < end; i++) { if (a[i] !== b[i]) return false } return true } export namespace CategoricalColorMapper { export interface Attrs extends ColorMapper.Attrs { factors: st...
_equals
identifier_name
categorical_color_mapper.ts
import {ColorMapper} from "./color_mapper" import {Factor} from "../ranges/factor_range" import * as p from "core/properties" import {Arrayable} from "core/types" import {findIndex} from "core/util/array" import {isString} from "core/util/types" function _equals(a: Arrayable<any>, b: Arrayable<any>): boolean { if (...
static initClass(): void { this.prototype.type = "CategoricalColorMapper" this.define({ factors: [ p.Array ], start: [ p.Number, 0 ], end: [ p.Number ], }) } protected _v_compute<T>(data: Arrayable<Factor>, values: Arrayable<T>, palette: Arrayable<T>, {nan_colo...
{ super(attrs) }
identifier_body
rbf.py
import numpy as np import tensorflow as tf from .module import Module class RBFExpansion(Module): def __init__(self, low, high, gap, dim=1, name=None): self.low = low self.high = high self.gap = gap self.dim = dim xrange = high - low self.centers = np.linspace(low...
(self, d): cshape = tf.shape(d) CS = d.get_shape() centers = self.centers.reshape((1, -1)).astype(np.float32) d -= tf.constant(centers) rbf = tf.exp(-(d ** 2) / self.gap) # rbf = tf.reshape(rbf, ( # cshape[0], cshape[1], cshape[2], # self.dim * cen...
_forward
identifier_name
rbf.py
import numpy as np import tensorflow as tf from .module import Module class RBFExpansion(Module): def __init__(self, low, high, gap, dim=1, name=None): self.low = low self.high = high self.gap = gap self.dim = dim xrange = high - low self.centers = np.linspace(low...
cshape = tf.shape(d) CS = d.get_shape() centers = self.centers.reshape((1, -1)).astype(np.float32) d -= tf.constant(centers) rbf = tf.exp(-(d ** 2) / self.gap) # rbf = tf.reshape(rbf, ( # cshape[0], cshape[1], cshape[2], # self.dim * centers.shape[-1])) ...
identifier_body
rbf.py
import numpy as np import tensorflow as tf from .module import Module
class RBFExpansion(Module): def __init__(self, low, high, gap, dim=1, name=None): self.low = low self.high = high self.gap = gap self.dim = dim xrange = high - low self.centers = np.linspace(low, high, int(np.ceil(xrange / gap))) self.centers = self.centers[:...
random_line_split
data_exportor.py
# -*- coding: utf-8 -*- # @date 161103 - Export excel with get_work_order_report function """ Data exportor (Excel, CSV...) """ import io import math from datetime import datetime from xlsxwriter.workbook import Workbook import tablib from utils.tools import get_product_size def get_customers(customer_list=None...
by worker and machine performance.""" row_number = 11 data = tablib.Dataset() data.append(['個人效率期間表 ({})'.format( datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1)) data.append(['工號', '姓名', '日期', '標準量', '效率標準量', '實質生產量', '總稼動時間', '總停機時間', '稼動 %', '數量效率 %', ...
te excel file for download
identifier_name
data_exportor.py
# -*- coding: utf-8 -*- # @date 161103 - Export excel with get_work_order_report function """ Data exportor (Excel, CSV...) """ import io import math from datetime import datetime from xlsxwriter.workbook import Workbook import tablib from utils.tools import get_product_size def get_customers(customer_list=None...
data.headers = ('機台', '維修項目', '開始時間', '員工', '結束時間', '員工', '總計時間') for log in log_list: m_code = log['m_code'].replace('<br>', '\n') data.append((log['machine_id'], m_code, log['start_time'], log['who_start'], log['end_time'], log['who...
"""Generate maintenance log to csv file for download.""" if log_list is None: log_list = [] data = tablib.Dataset()
random_line_split
data_exportor.py
# -*- coding: utf-8 -*- # @date 161103 - Export excel with get_work_order_report function """ Data exportor (Excel, CSV...) """ import io import math from datetime import datetime from xlsxwriter.workbook import Workbook import tablib from utils.tools import get_product_size def get_customers(customer_list=None...
a def get_maintenance_log(log_list=None, file_format='csv'): """Generate maintenance log to csv file for download.""" if log_list is None: log_list = [] data = tablib.Dataset() data.headers = ('機台', '維修項目', '開始時間', '員工', '結束時間', '員工', '總計時間') for l...
return dat
conditional_block
data_exportor.py
# -*- coding: utf-8 -*- # @date 161103 - Export excel with get_work_order_report function """ Data exportor (Excel, CSV...) """ import io import math from datetime import datetime from xlsxwriter.workbook import Workbook import tablib from utils.tools import get_product_size def get_customers(customer_list=None...
"Generate excel file for download by worker and machine performance.""" row_number = 11 data = tablib.Dataset() data.append(['個人效率期間表 ({})'.format( datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1)) data.append(['工號', '姓名', '日期', '標準量', '效率標準量', '實質生產量', '總稼動時間', '...
tenance log to csv file for download.""" if log_list is None: log_list = [] data = tablib.Dataset() data.headers = ('機台', '維修項目', '開始時間', '員工', '結束時間', '員工', '總計時間') for log in log_list: m_code = log['m_code'].replace('<br>', '\n') data.a...
identifier_body
phantom-tests.ts
import phantom = require("phantom"); phantom.create().then((ph: phantom.PhantomJS): void => { ph.createPage().then((page): void => { page.open("http://www.google.com", { operation: "GET" }).then((status: string) => { console.log("opened google? ", status); return p...
aaa: this.arguments, obj: my_obj }; }; var finishedFunc = (result: any) => { ph.exit(); }; return page.evaluate<string, { wahtt: number; }, void>(someFunc, 'div', { wahtt: 111 }).then(finishedFunc); ...
return { h2: h2Arr,
random_line_split
phantom-tests.ts
import phantom = require("phantom"); phantom.create().then((ph: phantom.PhantomJS): void => { ph.createPage().then((page): void => { page.open("http://www.google.com", { operation: "GET" }).then((status: string) => { console.log("opened google? ", status); return p...
}); }); }); });
{ page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js').then(() => { page.injectJs('do.js').then((res) => { page.evaluate(() => { return document.title; }).then...
conditional_block
dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# python3 -m pip install google-cloud-dialogflow # [START dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync] from google.cloud import dialogflow_v2 def sample_delete_conversation_dataset(): # Create a client client = dialogflow_v2.ConversationDatasetsClient() # Initialize re...
# NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following:
random_line_split
dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# [END dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync]
client = dialogflow_v2.ConversationDatasetsClient() # Initialize request argument(s) request = dialogflow_v2.DeleteConversationDatasetRequest( name="name_value", ) # Make the request operation = client.delete_conversation_dataset(request=request) print("Waiting for operation to comple...
identifier_body
dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
(): # Create a client client = dialogflow_v2.ConversationDatasetsClient() # Initialize request argument(s) request = dialogflow_v2.DeleteConversationDatasetRequest( name="name_value", ) # Make the request operation = client.delete_conversation_dataset(request=request) print("W...
sample_delete_conversation_dataset
identifier_name
pickle_helpers.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from ...extern import ...
(object, fileorname, usecPickle=True, protocol=None, append=False): """Pickle an object to a specified file. Parameters ---------- object The python object to pickle. fileorname : str or file-like The filename or file into which the `object` should be pickled. If a file obje...
fnpickle
identifier_name
pickle_helpers.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from ...extern import ...
Parameters ---------- object The python object to pickle. fileorname : str or file-like The filename or file into which the `object` should be pickled. If a file object, it should have been opened in binary mode. usecPickle : bool If True (default), the :mod:`cPickle...
return res def fnpickle(object, fileorname, usecPickle=True, protocol=None, append=False): """Pickle an object to a specified file.
random_line_split
pickle_helpers.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from ...extern import ...
def fnpickle(object, fileorname, usecPickle=True, protocol=None, append=False): """Pickle an object to a specified file. Parameters ---------- object The python object to pickle. fileorname : str or file-like The filename or file into which the `object` should be pickled. If a ...
""" Unpickle pickled objects from a specified file and return the contents. Parameters ---------- fileorname : str or file-like The file name or file from which to unpickle objects. If a file object, it should have been opened in binary mode. number : int If 0, a single object w...
identifier_body
pickle_helpers.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from ...extern import ...
else: # number==0 res = pickle.load(f) finally: if close: f.close() return res def fnpickle(object, fileorname, usecPickle=True, protocol=None, append=False): """Pickle an object to a specified file. Parameters ---------- object The python ob...
res = [] eof = False while not eof: try: res.append(pickle.load(f)) except EOFError: eof = True
conditional_block
admin-date-preview.js
/** * Provides live preview facilities for the event date format fields, akin * to (and using the same ajax mechanism as) the date format preview in WP's * general settings screen. */ jQuery( document ).ready( function( $ ) { // Whenever the input field for a date format changes, update the matching // live previ...
// Before making the request, show the spinner (this should naturally be "wiped" // when the response is rendered) $preview_field.append( "<span class='spinner'></span>" ); $preview_field.find( ".spinner" ).css( "visibility", "visible" ); var request = { action: "date_format", date: new_format } ...
$preview_field.html( preview_text ); }
random_line_split
compiled.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Create a dummy TermInfo struct for msys terminals pub fn msys_terminfo() -> TermInfo { let mut strings = HashMap::new(); strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec()); strings.insert("bold".to_string(), b"\x1B[1m".to_vec()); strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec()); ...
{ macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ); let (bnames, snames, nnames) = if longnames { (boolfnames, stringfnames, numfnames) } else { (boolnames, stringnames, numnames) }; // ...
identifier_body
compiled.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(file: &mut io::Read, longnames: bool) -> Result<TermInfo, String> { macro_rules! try( ($e:expr) => ( match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) } ) ); let (bnames, snames, nnames) = if longnames { (boolfnames, stringfnames, numfnames) ...
parse
identifier_name
compiled.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let numbers_map: HashMap<String, u16> = try!( (0..numbers_count).filter_map(|i| match read_le_u16(file) { Ok(0xFFFF) => None, Ok(n) => Some(Ok((nnames[i].to_string(), n))), Err(e) => Some(Err(e)) }).collect()); let string_map: HashMap<String, Vec<u8>> = if s...
random_line_split
compiled.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { snames[i] }; if offset == 0xFFFE { // undocumented: FFFE indicates cap@, which means the capability is not present // unsure if the handling for this is correct return Ok((name.to_string(), Vec::new())); } ...
{ stringfnames[i] }
conditional_block
gstr.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library 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 Softwa...
(&mut self) { unsafe { ffi::g_free(self.ptr as gpointer) } } } impl Clone for OwnedGStr { fn clone(&self) -> OwnedGStr { unsafe { OwnedGStr::from_ptr(ffi::g_strdup(self.ptr)) } } } impl PartialEq for OwnedGStr { fn eq(&self, other: &OwnedGStr) -> bool { unsa...
drop
identifier_name
gstr.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library 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 Softwa...
inner: CString } impl Deref for Utf8String { type Target = Utf8; fn deref(&self) -> &Utf8 { unsafe { Utf8::from_ptr(self.inner.as_ptr()) } } } impl Utf8String { pub fn new<T>(t: T) -> Result<Utf8String, NulError> where T: Into<String> { let c_str = try!(CString::new(t...
#[inline] fn as_ref(&self) -> &CStr { &self.inner } } pub struct Utf8String {
random_line_split
gstr.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library 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 Softwa...
pub unsafe fn from_ptr<'a>(ptr: *const gchar) -> &'a Utf8 { mem::transmute(CStr::from_ptr(ptr)) } } impl AsRef<CStr> for Utf8 { #[inline] fn as_ref(&self) -> &CStr { &self.inner } } pub struct Utf8String { inner: CString } impl Deref for Utf8String { type Target = Utf8; fn der...
{ assert!(s.ends_with("\0"), "static string is not null-terminated: \"{}\"", s); unsafe { Utf8::from_ptr(s.as_ptr() as *const gchar) } }
identifier_body
AlwaysBeCasting.tsx
import React from 'react'; class AlwaysBeCasting extends CoreAlwaysBeCasting { get suggestionThresholds() { return { actual: this.activeTimePercentage, isLessThan: { minor: 0.95, average: 0.85, major: 0.75, }, style: ThresholdStyle.PERCENTAGE, }; } suggest...
import CoreAlwaysBeCasting from 'parser/shared/modules/AlwaysBeCasting'; import { ThresholdStyle, When } from 'parser/core/ParseResults'; import { SpellLink } from 'interface'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format';
random_line_split
AlwaysBeCasting.tsx
import CoreAlwaysBeCasting from 'parser/shared/modules/AlwaysBeCasting'; import { ThresholdStyle, When } from 'parser/core/ParseResults'; import { SpellLink } from 'interface'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import React from 'react'; class AlwaysBeCasting extends...
(when: When) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => suggest(<>Your downtime can be improved. If you need to move use <SpellLink id={SPELLS.FLAME_SHOCK.id} />, <SpellLink id={SPELLS.EARTH_SHOCK.id} /> or <SpellLink id={SPELLS.FROST_SHOCK.id} /></>) .icon('spell_mage_a...
suggestions
identifier_name
page_test_runner.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core import browser_finder from telemetry.core import browser_options from telemetry.page import page_...
(test_dir, page_set_filenames): """Turns a PageTest into a command-line program. Args: test_dir: Path to directory containing PageTests. """ tests = discover.DiscoverClasses(test_dir, os.path.join(test_dir, '..'), page_test.PageTest) ...
Main
identifier_name
page_test_runner.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core import browser_finder from telemetry.core import browser_options from telemetry.page import page_...
return RunTestOnPageSet(options, ps, test, results) def RunTestOnPageSet(options, ps, test, results): test.CustomizeBrowserOptions(options) possible_browser = browser_finder.FindBrowser(options) if not possible_browser: print >> sys.stderr, """No browser found.\n Use --browser=list to figure out which are...
for f in page_set_filenames])) sys.exit(1) ps = page_set.PageSet.FromFile(args[1]) results = page_test.PageTestResults()
random_line_split
page_test_runner.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core import browser_finder from telemetry.core import browser_options from telemetry.page import page_...
test.CustomizeBrowserOptions(options) possible_browser = browser_finder.FindBrowser(options) if not possible_browser: print >> sys.stderr, """No browser found.\n Use --browser=list to figure out which are available.\n""" sys.exit(1) with page_runner.PageRunner(ps) as runner: runner.Run(options, possi...
identifier_body
page_test_runner.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core import browser_finder from telemetry.core import browser_options from telemetry.page import page_...
ps = page_set.PageSet.FromFile(args[1]) results = page_test.PageTestResults() return RunTestOnPageSet(options, ps, test, results) def RunTestOnPageSet(options, ps, test, results): test.CustomizeBrowserOptions(options) possible_browser = browser_finder.FindBrowser(options) if not possible_browser: pr...
parser.print_usage() print >> sys.stderr, 'Available tests:\n%s\n' % ',\n'.join( sorted(tests.keys())) print >> sys.stderr, 'Available page_sets:\n%s\n' % ',\n'.join( sorted([os.path.relpath(f) for f in page_set_filenames])) sys.exit(1)
conditional_block
test_cookiestorage.py
from django.test import TestCase from django.core import signing from django.core.exceptions import SuspiciousOperation from django.http import HttpResponse from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.formtools.wizard.storage.cookie import CookieStorage from django.contrib.formtool...
storage.update_response(response) cookie_signer = signing.get_cookie_signer(storage.prefix) signed_cookie_data = cookie_signer.sign(storage.encoder.encode(storage.data)) self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data) storage.init_data() sto...
storage = self.get_storage()('wizard1', request, None) storage.data = {'key1': 'value1'} response = HttpResponse()
random_line_split
test_cookiestorage.py
from django.test import TestCase from django.core import signing from django.core.exceptions import SuspiciousOperation from django.http import HttpResponse from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.formtools.wizard.storage.cookie import CookieStorage from django.contrib.formtool...
(TestStorage, TestCase): def get_storage(self): return CookieStorage def test_manipulated_cookie(self): request = get_request() storage = self.get_storage()('wizard1', request, None) cookie_signer = signing.get_cookie_signer(storage.prefix) storage.request.COOKIES[stor...
TestCookieStorage
identifier_name
test_cookiestorage.py
from django.test import TestCase from django.core import signing from django.core.exceptions import SuspiciousOperation from django.http import HttpResponse from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.formtools.wizard.storage.cookie import CookieStorage from django.contrib.formtool...
request = get_request() storage = self.get_storage()('wizard1', request, None) storage.data = {'key1': 'value1'} response = HttpResponse() storage.update_response(response) cookie_signer = signing.get_cookie_signer(storage.prefix) signed_cookie_data = cookie_signer.sig...
identifier_body
parameter_tests_edges.py
# coding: utf-8 # In[1]: import os from shutil import copyfile import subprocess from save_embedded_graph27 import main_binary as embed_main from spearmint_ghsom import main as ghsom_main import numpy as np import pickle from time import time def save_obj(obj, name): with open(name + '.pkl', 'wb'...
#cmd strings change_dir_cmd = "cd {}".format(dir_string_p) generate_network_cmd = "benchmark -f {}".format(filename) #output of cmd output_file = open("cmd_output.out", 'w') network_rename = "{}_{}".format(r,network) fir...
print 'number of edges: {}'.format(num_edges) print 'number of communities: {}'.format(num_communities) print '-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}'.format(N, k, maxk, minc, maxc, mu) with open(filename,"w") as f: f.write("-N {} -k {} -max...
conditional_block
parameter_tests_edges.py
# coding: utf-8 # In[1]: import os from shutil import copyfile import subprocess from save_embedded_graph27 import main_binary as embed_main from spearmint_ghsom import main as ghsom_main import numpy as np import pickle from time import time def save_obj(obj, name): with open(name + '.pkl', 'wb'...
(name): with open(name + '.pkl', 'rb') as f: return pickle.load(f) #root dir os.chdir("C:\Miniconda3\Jupyter\GHSOM_simplex_dsd") #save directory dir = os.path.abspath("parameter_tests_edges") #number of times to repeat num_repeats = 30 #number of nodes in the graph N = 64 #make save d...
load_obj
identifier_name
parameter_tests_edges.py
# coding: utf-8 # In[1]: import os from shutil import copyfile import subprocess from save_embedded_graph27 import main_binary as embed_main from spearmint_ghsom import main as ghsom_main import numpy as np import pickle from time import time def save_obj(obj, name): with open(name + '.pkl', 'wb') ...
print 'OVERALL NMI SCORES' print overall_nmi_scores # In[3]: for scores in overall_nmi_scores: print scores idx = np.argsort(scores)[::-1] print parameter_settings[idx[0]]
random_line_split
parameter_tests_edges.py
# coding: utf-8 # In[1]: import os from shutil import copyfile import subprocess from save_embedded_graph27 import main_binary as embed_main from spearmint_ghsom import main as ghsom_main import numpy as np import pickle from time import time def save_obj(obj, name): with open(name + '.pkl', 'wb'...
#root dir os.chdir("C:\Miniconda3\Jupyter\GHSOM_simplex_dsd") #save directory dir = os.path.abspath("parameter_tests_edges") #number of times to repeat num_repeats = 30 #number of nodes in the graph N = 64 #make save directory if not os.path.isdir(dir): os.mkdir(dir) #change to dir os.ch...
with open(name + '.pkl', 'rb') as f: return pickle.load(f)
identifier_body
bip.py
#! /usr/bin/env python ################################################################################################# # # Script Name: bip.py # Script Usage: This script is the menu system and runs everything else. Do not use other # files unless you are comfortable with the code. # # ...
varMySQLPassword = bip_config.mysqlconfig['password'] varMySQLDB = bip_config.mysqlconfig['db'] # setup to find GAM varCommandGam = bip_config.gamconfig['fullpath'] ################################################################################################# # #####################################################...
import bip_config # declare installation specific variables # setup for MySQLdb connection varMySQLHost = bip_config.mysqlconfig['host'] varMySQLUser = bip_config.mysqlconfig['user']
random_line_split
setup.py
""" Setup Module This module is used to make a distribution of the game using distutils. """ from distutils.core import setup setup( name = 'Breakout', version = '1.0', description = 'A remake of the classic video game', author = 'Derek Morey', author_email = 'dman...
'Intended Audience :: Education', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Topic :: Games/Entertainment', ...
'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers',
random_line_split
testSegment.py
# -*- coding: utf8 -*- ########################################################################### # This is part of the module phystricks # # phystricks 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...
(): echo_single_test("Usual constructor") seg=Segment( Point(0,0),Point(2,10) ) assert_equal(seg.I,Point(0,0)) assert_equal(seg.F,Point(2,10)) echo_single_test("Construct with a vector") seg=Segment( Point(-3,4),vector=Vector(1,2) ) assert_equal(seg.I,Point(-3,4)) assert_equal(seg.F,...
test_constructors
identifier_name
testSegment.py
# -*- coding: utf8 -*- ########################################################################### # This is part of the module phystricks # # phystricks 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...
test_constructors() test_almost_equal()
identifier_body
testSegment.py
# -*- coding: utf8 -*- ########################################################################### # This is part of the module phystricks # # phystricks 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...
def test_constructors(): echo_single_test("Usual constructor") seg=Segment( Point(0,0),Point(2,10) ) assert_equal(seg.I,Point(0,0)) assert_equal(seg.F,Point(2,10)) echo_single_test("Construct with a vector") seg=Segment( Point(-3,4),vector=Vector(1,2) ) assert_equal(seg.I,Point(-3,4)) ...
assert_almost_equal(v.F,Point(1/2*sqrt(2) + 1.5,-1/2*sqrt(2) + 1.5),epsilon=0.001)
random_line_split
graph.js
// @flow // connection types export type Edge<T> = { node: T, cursor: string } export type PageInfo = { hasNextPage: boolean } export type Connection<T> = { edges: Array<Edge<T>>, pageInfo: PageInfo } export type SearchConnection<T> = { count: number } & Connection<T> // data types export type Chamber ...
| 'FAILED' | 'SIGNED' | 'VETOED' | 'VETOED_LINE' | 'NONE' export type Step = { actor: StepActor, action: StepAction, resolution: StepResolution, date: string } export type Document = { id: string, number: string, fullTextUrl: string, slipUrl: string, slipResultsUrl: string } export type B...
export type StepResolution = 'PASSED'
random_line_split
npm-installation-manager.ts
import * as path from "path"; import * as semver from "semver"; import * as npm from "npm"; import * as constants from "./constants"; import {sleep} from "../lib/common/helpers"; export class NpmInstallationManager implements INpmInstallationManager { private static NPM_LOAD_FAILED = "Failed to retrieve data from npm...
(packageName: string, version: string): IFuture<any> { return (() => { let cachedPackageData = this.$npm.cache(packageName, version).wait(); let packagePath = path.join(this.getCacheRootPath(), packageName, cachedPackageData.version, "package"); if(!this.isPackageUnpacked(packagePath, packageName).wait()) { ...
addToCacheCore
identifier_name
npm-installation-manager.ts
import * as path from "path"; import * as semver from "semver"; import * as npm from "npm"; import * as constants from "./constants"; import {sleep} from "../lib/common/helpers"; export class NpmInstallationManager implements INpmInstallationManager { private static NPM_LOAD_FAILED = "Failed to retrieve data from npm...
private hasFilesInDirectory(directory: string): IFuture<boolean> { return ((): boolean => { return this.$fs.exists(directory).wait() && this.$fs.enumerateFilesInDirectorySync(directory).length > 0; }).future<boolean>()(); } } $injector.register("npmInstallationManager", NpmInstallationManager);
random_line_split
npm-installation-manager.ts
import * as path from "path"; import * as semver from "semver"; import * as npm from "npm"; import * as constants from "./constants"; import {sleep} from "../lib/common/helpers"; export class NpmInstallationManager implements INpmInstallationManager { private static NPM_LOAD_FAILED = "Failed to retrieve data from npm...
public install(packageName: string, opts?: INpmInstallOptions): IFuture<string> { return (() => { while(this.$lockfile.check().wait()) { sleep(10); } this.$lockfile.lock().wait(); try { let packageToInstall = packageName; let pathToSave = (opts && opts.pathToSave) || npm.cache; let v...
{ return (() => { let cliVersionRange = `~${this.$staticConfig.version}`; let latestVersion = this.getLatestVersion(packageName).wait(); if(semver.satisfies(latestVersion, cliVersionRange)) { return latestVersion; } let data: any = this.$npm.view(packageName, "versions").wait(); /* data is some...
identifier_body
npm-installation-manager.ts
import * as path from "path"; import * as semver from "semver"; import * as npm from "npm"; import * as constants from "./constants"; import {sleep} from "../lib/common/helpers"; export class NpmInstallationManager implements INpmInstallationManager { private static NPM_LOAD_FAILED = "Failed to retrieve data from npm...
let data: any = this.$npm.view(packageName, "versions").wait(); /* data is something like: { "1.1.0":{ "versions":[ "1.0.0", "1.0.1-2016-02-25-181", "1.0.1", "1.0.2-2016-02-25-182", "1.0.2", "1.1.0-2016-02-25-183", "1.1.0", "1.2.0-2016-02-25...
{ return latestVersion; }
conditional_block
app.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 30 09:53:39 2018 @author: mayank """ from forms import SignupForm from flask import Flask, request, render_template from flask_login import LoginManager, login_user, login_required, logout_user app = Flask(__name__) app.secret_key = 'gMALVWEuxBSx...
init_db() app.run(port=5000, host='localhost')
if __name__ == '__main__': from models import db, User
random_line_split
app.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 30 09:53:39 2018 @author: mayank """ from forms import SignupForm from flask import Flask, request, render_template from flask_login import LoginManager, login_user, login_required, logout_user app = Flask(__name__) app.secret_key = 'gMALVWEuxBSx...
@app.route('/protected') @login_required def protected(): return "protected area" def init_db(): db.init_app(app) db.app = app db.create_all() if __name__ == '__main__': from models import db, User init_db() app.run(port=5000, host='localhost')
logout_user() return "Logged out"
identifier_body
app.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 30 09:53:39 2018 @author: mayank """ from forms import SignupForm from flask import Flask, request, render_template from flask_login import LoginManager, login_user, login_required, logout_user app = Flask(__name__) app.secret_key = 'gMALVWEuxBSx...
(): return "Welcome to Home Page" @app.route('/signup', methods=['GET', 'POST']) def signup(): form = SignupForm() if request.method == 'GET': return render_template('signup.html', form=form) elif request.method == 'POST': if form.validate_on_submit(): if User.query.filter_...
index
identifier_name
app.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 30 09:53:39 2018 @author: mayank """ from forms import SignupForm from flask import Flask, request, render_template from flask_login import LoginManager, login_user, login_required, logout_user app = Flask(__name__) app.secret_key = 'gMALVWEuxBSx...
@login_manager.user_loader def load_user(email): return User.query.filter_by(email=email).first() @app.route('/login', methods=['GET', 'POST']) def login(): form = SignupForm() if request.method == 'GET': return render_template('login.html', form=form) elif request.method == 'POST' and form...
return "Form didn't validate"
conditional_block
css-hint-server.js
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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...
/** * @param {files: [{name, type, text}], query: {type: string, end:{line,ch}, file: string}} body * @returns {from: {line, ch}, to: {line, ch}, list: [string]} **/ csshint.request = function (serverId, body, c) { _.each(body.files, function (file) { if (file.type === 'full...
{ var result = {}; var token = body.query.token; if (token) { if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) { token.type = 'class'; token.start = token.start + 1; token.string = token.string.sub...
identifier_body
css-hint-server.js
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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...
(body) { var result = {}; var token = body.query.token; if (token) { if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) { token.type = 'class'; token.start = token.start + 1; token.string = token.str...
findCompletions
identifier_name
css-hint-server.js
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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...
fileServer.setText(file.name, file.text); file.type = null; } }); body.files = _.filter(body.files, function (file) { return file.type !== null; }); var result = {}; if (body.query.type === 'completions') { res...
**/ csshint.request = function (serverId, body, c) { _.each(body.files, function (file) { if (file.type === 'full') {
random_line_split
css-hint-server.js
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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...
_.each(htmls, function (htmlpath) { var html = fileServer.getLocalFile(htmlpath); if (html) { if (token.type === 'id') { result.list = _.union(result, html.getHtmlIds()); } else if (token...
{ htmls = _.union(htmls, [body.query.file]); }
conditional_block
TakeoutDiningOutlined.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true });
exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m7.79 18-.51-7h9.46l-.51 7H7.79zM9.83 5h4.33l2.8 2.73L16.87 9H7.12l-.0...
random_line_split
p2p_fingerprint.py
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If a stale block more than a month old or its header are requ...
if __name__ == '__main__': P2PFingerprintTest().main()
node0 = self.nodes[0].add_p2p_connection(P2PInterface()) # Set node time to 60 days ago self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60) # Generating a chain of 10 blocks block_hashes = self.nodes[0].generate(nblocks=10) # Create longer chain starting 2 blocks b...
identifier_body
p2p_fingerprint.py
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If a stale block more than a month old or its header are requ...
P2PFingerprintTest().main()
conditional_block
p2p_fingerprint.py
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If a stale block more than a month old or its header are requ...
node0.send_message(msg_headers(new_blocks)) node0.wait_for_getdata() for block in new_blocks: node0.send_and_ping(msg_block(block)) # Check that reorg succeeded assert_equal(self.nodes[0].getblockcount(), 13) stale_hash = int(block_hashes[-1], 16) #...
random_line_split
p2p_fingerprint.py
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If a stale block more than a month old or its header are requ...
(self): node0 = self.nodes[0].add_p2p_connection(P2PInterface()) # Set node time to 60 days ago self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60) # Generating a chain of 10 blocks block_hashes = self.nodes[0].generate(nblocks=10) # Create longer chain sta...
run_test
identifier_name
FlattenIntoArray.js
'use strict'; var GetIntrinsic = require('../GetIntrinsic'); var $TypeError = GetIntrinsic('%TypeError%'); var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); var Call = require('./Call'); var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow'); var Get = require('./Get'); var HasProperty = ...
sourceIndex += 1; } return targetIndex; };
{ var element = Get(source, P); if (typeof mapperFunction !== 'undefined') { if (arguments.length <= 6) { throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided'); } element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]); } var shou...
conditional_block
FlattenIntoArray.js
'use strict'; var GetIntrinsic = require('../GetIntrinsic'); var $TypeError = GetIntrinsic('%TypeError%'); var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); var Call = require('./Call'); var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow'); var Get = require('./Get'); var HasProperty = ...
if (arguments.length > 5) { mapperFunction = arguments[5]; } var targetIndex = start; var sourceIndex = 0; while (sourceIndex < sourceLen) { var P = ToString(sourceIndex); var exists = HasProperty(source, P); if (exists === true) { var element = Get(source, P); if (typeof mapperFunction !== 'undefin...
var mapperFunction;
random_line_split
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle};...
#[test] fn fast_forward() { let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(10)), tm.at(1001)); assert_eq!(next_interval(tm.at(7777), tm.at(8888), dur(100)), tm.at(8977)); assert_eq!...
{ let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(2), dur(10)), tm.at(11)); assert_eq!(next_interval(tm.at(7777), tm.at(7788), dur(100)), tm.at(7877)); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(2100)), ...
identifier_body
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle};...
(at: Instant, dur: Duration, handle: &Handle) -> io::Result<Interval> { Ok(Interval { token: try!(TimeoutToken::new(at, &handle)), next: at, interval: dur, handle: handle.remote().clone(), }) } } impl Stream for Interval { type Item = ...
new_at
identifier_name