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
Test_Watchdog.py
""" unit test for Watchdog.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # imports import os from mock import MagicMock # sut from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog mock_exeThread = MagicMock() mock_spObject = Mag...
assert res['OK'] is True def test__performChecks(): pid = os.getpid() wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000) res = wd.calibrate() assert res['OK'] is True res = wd._performChecks() assert res['OK'] is True def test__performChecksFull(): pid = os.getpid() wd = Watchdog(pid, mock_e...
pid = os.getpid() wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000) res = wd.calibrate()
random_line_split
voucher.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2013 Camptocamp SA (http://www.camptocamp.com) # @author Nicolas Bessi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
if context is None: context = {} statement_id = context.get('statement_id', False) if not statement_id: return {'type': 'ir.actions.act_window_close'} data = self.read(cr, uid, ids, context=context)[0] line_ids = data['line_ids'] if not line_ids: ...
def populate_statement(self, cr, uid, ids, context=None): """Taken from account voucher as no hook is available. No function no refactoring, just trimming the part that generates voucher"""
random_line_split
voucher.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2013 Camptocamp SA (http://www.camptocamp.com) # @author Nicolas Bessi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
data = self.read(cr, uid, ids, [], context=context)[0] line_ids = data['lines'] if not line_ids: return {'type': 'ir.actions.act_window_close'} statement = statement_obj.browse( cr, uid, context['active_id'], context=context) for line in line_obj.browse(c...
context = {}
conditional_block
voucher.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2013 Camptocamp SA (http://www.camptocamp.com) # @author Nicolas Bessi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
ctx = context.copy() # take the date for computation of currency => use payment date ctx['date'] = line_date amount = 0.0 if line.debit > 0: amount = line.debit elif line.credit > 0: amount = -line.credit ...
"""Taken from account voucher as no hook is available. No function no refactoring, just trimming the part that generates voucher""" if context is None: context = {} statement_id = context.get('statement_id', False) if not statement_id: return {'type': 'ir.actions....
identifier_body
voucher.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2013 Camptocamp SA (http://www.camptocamp.com) # @author Nicolas Bessi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
(self, cr, uid, move_line, s_type, statement_id, amount, context=None): return {'name': move_line.name or '?', 'amount': amount, 'type': s_type, 'partner_id': move_line.partner_id.id, 'account_id': move_line.acc...
_prepare_statement_line_vals
identifier_name
animate-app.ts
import { Component, trigger, state, transition, keyframes, group, animate, style, sequence } from '@angular/core'; @Component({ selector: 'animate-app', styleUrls: ['css/animate-app.css'], template: ` <div @backgroundAnimation="bgStatus"> <button (click)="state='start'">Start State</b...
} }
{ this.items = [ 1,2,3,4,5, 6,7,8,9,10, 11,12,13,14,15, 16,17,18,19,20 ]; }
conditional_block
animate-app.ts
import { Component, trigger, state, transition, keyframes, group, animate, style, sequence } from '@angular/core'; @Component({ selector: 'animate-app', styleUrls: ['css/animate-app.css'], template: ` <div @backgroundAnimation="bgStatus"> <button (click)="state='start'">Start State</b...
animate(1000, style({ "background-color": "blue" })), animate(1000, keyframes([ style({ "background-color": "blue", "color": "black", "offset": 0.2 }), style({ "background-color": "brown", "color": "black", "offset": 0.5 }), style({ "background-color": "black", "color": "wh...
animate(500) ]), transition("* => *", [ animate(1000, style({ "opacity": 1, "height": 300 })),
random_line_split
animate-app.ts
import { Component, trigger, state, transition, keyframes, group, animate, style, sequence } from '@angular/core'; @Component({ selector: 'animate-app', styleUrls: ['css/animate-app.css'], template: ` <div @backgroundAnimation="bgStatus"> <button (click)="state='start'">Start State</b...
(s) { this._state = s; if (s == 'void') { this.items = []; } else { this.items = [ 1,2,3,4,5, 6,7,8,9,10, 11,12,13,14,15, 16,17,18,19,20 ]; } } }
state
identifier_name
clusters_calculator.py
from models import Marker from static.pymapcluster import calculate_clusters import time import logging import concurrent.futures import multiprocessing def retrieve_clusters(**kwargs): marker_boxes = divide_to_boxes(kwargs['ne_lat'], kwargs['ne_lng'], kwargs['sw_lat'], kwargs['sw_lng']) result_futures = [] ...
return boxes
random_line_split
clusters_calculator.py
from models import Marker from static.pymapcluster import calculate_clusters import time import logging import concurrent.futures import multiprocessing def
(**kwargs): marker_boxes = divide_to_boxes(kwargs['ne_lat'], kwargs['ne_lng'], kwargs['sw_lat'], kwargs['sw_lng']) result_futures = [] logging.info('number of cores: ' + str(multiprocessing.cpu_count())) with concurrent.futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor: ...
retrieve_clusters
identifier_name
clusters_calculator.py
from models import Marker from static.pymapcluster import calculate_clusters import time import logging import concurrent.futures import multiprocessing def retrieve_clusters(**kwargs): marker_boxes = divide_to_boxes(kwargs['ne_lat'], kwargs['ne_lng'], kwargs['sw_lat'], kwargs['sw_lng']) result_futures = [] ...
cpu_count = multiprocessing.cpu_count() lat_box_size = (ne_lat - sw_lat) / cpu_count # lng_box_size = (sw_lng - ne_lng) / cpu_count boxes = [] for i in xrange(cpu_count): # TODO: the below calculation is using sw_lat as first param instead of ne_lat. Plz verify my fix for that: # boxes.a...
identifier_body
clusters_calculator.py
from models import Marker from static.pymapcluster import calculate_clusters import time import logging import concurrent.futures import multiprocessing def retrieve_clusters(**kwargs): marker_boxes = divide_to_boxes(kwargs['ne_lat'], kwargs['ne_lng'], kwargs['sw_lat'], kwargs['sw_lng']) result_futures = [] ...
return result def divide_to_boxes(ne_lat, ne_lng, sw_lat, sw_lng): cpu_count = multiprocessing.cpu_count() lat_box_size = (ne_lat - sw_lat) / cpu_count # lng_box_size = (sw_lng - ne_lng) / cpu_count boxes = [] for i in xrange(cpu_count): # TODO: the below calculation is using sw_lat ...
result.extend(future.result())
conditional_block
esup_activ_bo.ts
'use strict'; import * as _ from 'lodash'; import * as fs from 'fs'; import * as xml2js from 'xml2js'; import * as Mustache from 'mustache'; import * as helpers from './helpers'; import * as utils from './utils'; import * as conf from './conf'; const parseString: (xml: string, options: xml2js.Options) => Promise<any>...
// returns "attrPersoInfo" + code, mail, supannAliasLogin // throws: "Authentification invalide pour l'utilisateur xxx" // throws: "Login invalide" export const authentificateUser = (supannAliasLogin: string, password: string, attrPersoInfo: string[]) => ( soap("authentificateUser.xml", { id: supannAliasLogin, pa...
{ let entries = deepGetKey(response, 'entry'); if (!_.isArray(entries)) return undefined; let r = _.zipObject(_.map(entries, 'key'), _.map(entries, 'value')); r = _.mapValues(r, val => val.split(conf.esup_activ_bo.multiValue_separator)); return r; }
identifier_body
esup_activ_bo.ts
'use strict'; import * as _ from 'lodash'; import * as fs from 'fs'; import * as xml2js from 'xml2js'; import * as Mustache from 'mustache'; import * as helpers from './helpers'; import * as utils from './utils'; import * as conf from './conf'; const parseString: (xml: string, options: xml2js.Options) => Promise<any>...
(url, body) { let headers = { SOAPAction: "", "content-type": "text/xml", }; return utils.post(url, body, { headers }).then(result => ( parseString(result, { explicitArray: false, ignoreAttrs: true }) )); } function soap(templateName, params, opts : { responseTag: string, fault_...
raw_soap
identifier_name
esup_activ_bo.ts
'use strict'; import * as _ from 'lodash'; import * as fs from 'fs'; import * as xml2js from 'xml2js'; import * as Mustache from 'mustache'; import * as helpers from './helpers'; import * as utils from './utils'; import * as conf from './conf'; const parseString: (xml: string, options: xml2js.Options) => Promise<any>...
function _get_entries(response) { let entries = deepGetKey(response, 'entry'); if (!_.isArray(entries)) return undefined; let r = _.zipObject(_.map(entries, 'key'), _.map(entries, 'value')); r = _.mapValues(r, val => val.split(conf.esup_activ_bo.multiValue_separator)); return r; } // returns "attrP...
}
random_line_split
esup_activ_bo.ts
'use strict'; import * as _ from 'lodash'; import * as fs from 'fs'; import * as xml2js from 'xml2js'; import * as Mustache from 'mustache'; import * as helpers from './helpers'; import * as utils from './utils'; import * as conf from './conf'; const parseString: (xml: string, options: xml2js.Options) => Promise<any>...
else { let ks = _.keys(o); return ks.length === 1 ? deepGetKey(o[ks[0]], k) : undefined; } } function raw_soap(url, body) { let headers = { SOAPAction: "", "content-type": "text/xml", }; return utils.post(url, body, { headers }).then(result => ( parseString(resu...
{ return o.length === 1 ? deepGetKey(o[0], k) : undefined; }
conditional_block
utils.py
import os import yaml import time from datetime import datetime def
(path): csv_paths = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith(".csv"): csv_paths.append(os.path.join(root, file)) return csv_paths def date_str_to_unixtime(date_str): if str(date_str).isnumeric(): return int(date_str) ...
get_all_csv_paths
identifier_name
utils.py
import os import yaml import time from datetime import datetime def get_all_csv_paths(path): csv_paths = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith(".csv"): csv_paths.append(os.path.join(root, file)) return csv_paths def date_str_to...
try: d = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %z') except: pass try: d = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') except: pass return int(time.mktime(d.timetuple())) if d else None def tag_dict_to_dict(tag_di...
d = datetime.strptime(date_str.split( '+')[0].replace("T", " "), '%Y-%m-%d %H:%M:%S') except: pass
random_line_split
utils.py
import os import yaml import time from datetime import datetime def get_all_csv_paths(path):
def date_str_to_unixtime(date_str): if str(date_str).isnumeric(): return int(date_str) else: d = None try: d = datetime.strptime(date_str) except: pass try: d = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %Z') except: ...
csv_paths = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith(".csv"): csv_paths.append(os.path.join(root, file)) return csv_paths
identifier_body
utils.py
import os import yaml import time from datetime import datetime def get_all_csv_paths(path): csv_paths = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith(".csv"): csv_paths.append(os.path.join(root, file)) return csv_paths def date_str_to...
except: pass try: d = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') except: pass return int(time.mktime(d.timetuple())) if d else None def tag_dict_to_dict(tag_dict): if not tag_dict: return None tags = [] tag_list = yaml.loa...
d = None try: d = datetime.strptime(date_str) except: pass try: d = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %Z') except: pass try: d = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %z') except: ...
conditional_block
lib.rs
GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FO...
/// ``` /// let h = ssdeep::hash(b"Hello there!").unwrap(); /// assert_eq!(h, "3:aNRn:aNRn"); /// ``` /// /// # Panics /// /// If the size of the buffer is strictly greater than `2^32 - 1` bytes. The /// reason for this is that the corresponding function from the underlying C /// library accepts the length of the buffe...
/// returns `None`. /// /// # Examples ///
random_line_split
lib.rs
General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A ...
fn result_buffer_to_string(mut result: Vec<u8>, rc: i32) -> Option<String> { if rc != 0 { // The function from libfuzzy failed, so there is no result. return None; } // Since the resulting vector that holds the fuzzy hash was populated in // the underlying C
{ // From fuzzy.h: "The buffer into which the fuzzy hash is stored has to be // allocated to hold at least FUZZY_MAX_RESULT bytes." Vec::with_capacity(raw::FUZZY_MAX_RESULT) }
identifier_body
lib.rs
General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A ...
// Since the resulting vector that holds the fuzzy hash was populated in // the underlying C
{ // The function from libfuzzy failed, so there is no result. return None; }
conditional_block
lib.rs
General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A ...
(buf: &[u8]) -> Option<String> { assert!(buf.len() <= uint32_t::max_value() as usize); let mut result = create_buffer_for_result(); let rc = unsafe { raw::fuzzy_hash_buf(buf.as_ptr(), buf.len() as uint32_t, result.as_mut_ptr() as *mut c_char) ...
hash
identifier_name
mod.rs
// Copyright 2015, 2016 Ethcore (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 later version....
pub fn new_expanse() -> Spec { load(include_bytes!("../../res/ethereum/expanse.json")) } /// Create a new Frontier chain spec as though it never changes to Homestead. pub fn new_frontier_test() -> Spec { load(include_bytes!("../../res/ethereum/frontier_test.json")) } /// Create a new Homestead chain spec as though it...
pub fn new_classic() -> Spec { load(include_bytes!("../../res/ethereum/classic.json")) } /// Create a new Frontier mainnet chain spec without the DAO hardfork.
random_line_split
mod.rs
// Copyright 2015, 2016 Ethcore (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 later version....
() -> Spec { load(include_bytes!("../../res/ethereum/frontier_test.json")) } /// Create a new Homestead chain spec as though it never changed from Frontier. pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/homestead_test.json")) } /// Create a new Homestead-EIP150 chain spec as though it ...
new_frontier_test
identifier_name
mod.rs
// Copyright 2015, 2016 Ethcore (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 later version....
/// Create a new Homestead chain spec as though it never changed from Frontier. pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/homestead_test.json")) } /// Create a new Homestead-EIP150 chain spec as though it never changed from Homestead/Frontier. pub fn new_eip150_test() -> Spec { lo...
{ load(include_bytes!("../../res/ethereum/frontier_test.json")) }
identifier_body
js-processor.ts
Processor { private static _unnamedCount = 0; private _context: MergeContext; private _file: File; private _originalSourceMap: convert.SourceMapConverter | null; private _originalSourceMapStyle: "url" | "inline" | "none"; private _sourceMapFile: File | null; /** Gets the source map file g...
keepOriginalData: boolean, ) { if (this._originalSourceMapStyle === "none") { return; } const newMap = convert.fromObject(data.map); const originalMap: any = this._originalSourceMap; const parsedMap: RawSourceMap = newMap.toObject(); parsedMap.f...
private _fixSourceMap( file: string, data: { code: string, map: any }, newName: string,
random_line_split
js-processor.ts
Processor { private static _unnamedCount = 0; private _context: MergeContext; private _file: File; private _originalSourceMap: convert.SourceMapConverter | null; private _originalSourceMapStyle: "url" | "inline" | "none"; private _sourceMapFile: File | null; /** Gets the source map file g...
() { return this._sourceMapFile; } /** * Initializes a new instance of the {@link JsProcessor} class, using the input file as content * source for the merging. * * @param file * A string with the file contents or a {@link File} object. * @param context * Context object used t...
sourceMapFile
identifier_name
js-processor.ts
); const mergeCount = this._optimizeScript(ast.body as any); this._log(`Total block merges for '${filePath}': ${mergeCount}`); return this._createFile(ast as any, mergeCount); } // Creates a file from the abstract tree program private _createFile(ast: Program, merges: number): File...
{ if (!sourceMapCommentRegex.test(this._file.contents)) { return; } // Checking if the original source-map comment is available const sourceMapComment = sourceMapCommentRegex.exec(this._file.contents); if (sourceMapComment === null) { return; }...
identifier_body
js-processor.ts
._file = file; this._originalSourceMap = null; this._originalSourceMapStyle = "none"; } /** * Merges the input JavaScript file of this object, returning the merged file as result. * * @return * A file object, containing the results of the merging and all attributes pertain...
{ mergeCount = this._mergeBodies(bodies, nodes, nesting, mergeCount); index -= bodies.length * 2 - 2; }
conditional_block
display.rs
use mon_gen::monster::{Monster, MonsterAttack}; use mon_gen::battle::{Party, Battle, BattleError, PartyMember}; pub fn display(text: String, left: bool) { if left { println!("{:>80}", text); } else { println!("{}", text); } } pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool) {...
else { "" }; let active_index = if let Some(num) = index { format!("{}", num) } else { String::new() }; let form_name = if monster.species().species().forms.len() > 1 { format!(" ({})", monster.species().species().form(monster.form() as usize)) } else { String::new() }; display(format!("{}{...
{ "-> " }
conditional_block
display.rs
use mon_gen::monster::{Monster, MonsterAttack}; use mon_gen::battle::{Party, Battle, BattleError, PartyMember}; pub fn display(text: String, left: bool) { if left { println!("{:>80}", text); } else { println!("{}", text); } } pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool) {...
}; println!("Invalid selection: {}", error_str); }
} BattleError::SwitchQueued => { "Selected party member is already queued to switch in." }
random_line_split
display.rs
use mon_gen::monster::{Monster, MonsterAttack}; use mon_gen::battle::{Party, Battle, BattleError, PartyMember}; pub fn display(text: String, left: bool) { if left { println!("{:>80}", text); } else { println!("{}", text); } } pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool) {...
(battle: &Battle, active: usize) { println!(""); for index in 0..battle.state().parties()[1].active_count() { display_member(battle.state().parties()[1].active_member_alive(index), true, false) } for index in 0..battle.state().parties()[0].active_count() { let active = active == index; display_member(battle...
display_active
identifier_name
display.rs
use mon_gen::monster::{Monster, MonsterAttack}; use mon_gen::battle::{Party, Battle, BattleError, PartyMember}; pub fn display(text: String, left: bool) { if left { println!("{:>80}", text); } else { println!("{}", text); } } pub fn display_member(member: Option<PartyMember>, opponent: bool, active: bool) {...
pub fn display_party(party: &Party, back: bool) { println!("Party members:"); println!(""); let mut alternate = true; for (index, monster) in party.iter().enumerate() { alternate = !alternate; display(format!("{}) {} Lv. {}", index + 1, monster.nick(), monster.level()), alternate); display(format!(" ...
{ let mut alternate = true; for (index, attack) in attacks.iter().enumerate() { alternate = !alternate; display(format!("{}) {}", index + 1, attack.attack().name()), alternate); display(format!(" {}", attack.attack().element.name()), alternate); display(format!(" Limit: {}/{}", attack.limit_left(), attac...
identifier_body
inherit_stock_location.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2010-2012 Associazione OpenERP Italia # (<http://www.openerp-italia.org>). # Copyright (C) 2014 Didotech srl # (<http://www.didotech.com>). # # This program is free software: you can r...
product_ids = product_obj.search(cr, uid, [('type', '!=', 'service')], context=context) product_context = context.copy() product_vals = {} for product_id in product_ids: product_vals[product_id] = {} for location_keys in location_vals.keys()...
location_vals[location.id] = location.product_related_columns
conditional_block
inherit_stock_location.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2010-2012 Associazione OpenERP Italia # (<http://www.openerp-italia.org>). # Copyright (C) 2014 Didotech srl # (<http://www.didotech.com>). # # This program is free software: you can r...
from openerp import SUPERUSER_ID from openerp.osv import orm, fields from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT _logger = logging.getLogger(__name__) _logger.setLevel(logging.DEBUG) class stock_location(orm.Model): _inherit = "stock.location" _columns = { 'update_product_bylocation': ...
# ############################################################################## import logging from datetime import datetime
random_line_split
inherit_stock_location.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2010-2012 Associazione OpenERP Italia # (<http://www.openerp-italia.org>). # Copyright (C) 2014 Didotech srl # (<http://www.didotech.com>). # # This program is free software: you can r...
if location_vals[location_keys] and (product[location_vals[location_keys]] != product.qty_available): product_vals[product.id][location_vals[location_keys]] = product.qty_available if product_vals: for product_id in product_vals.keys(): ...
context = context or self.pool['res.users'].context_get(cr, uid) location_ids = self.search(cr, uid, [('update_product_bylocation', '=', True)], context=context) location_vals = {} start_time = datetime.now() date_product_by_location_update = start_time.strftime(DEFAULT_SERVER_DATETIME_F...
identifier_body
inherit_stock_location.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2010-2012 Associazione OpenERP Italia # (<http://www.openerp-italia.org>). # Copyright (C) 2014 Didotech srl # (<http://www.didotech.com>). # # This program is free software: you can r...
(self, cr, location_name, context): model_id = self.pool['ir.model.data'].get_object_reference(cr, SUPERUSER_ID, 'product', 'model_product_product')[1] fields_value = { 'field_description': location_name, 'groups': [[6, False, []]], 'model_id': model_id, '...
create_product_by_location
identifier_name
associated-types-sugar-path.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 z: uint = bar(2, 4); }
main
identifier_name
associated-types-sugar-path.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Foo for int { type A = uint; fn boo(&self) -> uint { 5 } } // Using a type via a function. pub fn bar<T: Foo>(a: T, x: T::A) -> T::A { let _: T::A = a.boo(); x } // Using a type via an impl. trait C { fn f(); fn g(&self) { } } struct B<X>(X); impl<T: Foo> C for B<T> { f...
pub trait Foo { type A; fn boo(&self) -> Self::A;
random_line_split
audio.py
import pyaudio import struct from threading import Thread, Condition import time from logging import thread import socket CHUNK = 2**12 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 class AudioReader(Thread): def __init__(self, raw = False, remote = False, host = 'localhost', port = 9999): Thread._...
self.quit = False self.raw = raw self.remote = remote self.host = host self.port = port def pause(self): self.active = False def play(self): self.active = True self.condition.acquire() self.condition.notify() ...
self.listeners = [] self.condition = Condition()
random_line_split
audio.py
import pyaudio import struct from threading import Thread, Condition import time from logging import thread import socket CHUNK = 2**12 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 class AudioReader(Thread): def __init__(self, raw = False, remote = False, host = 'localhost', port = 9999): Thread._...
self.socket.close() def run(self): while not self.quit: if not self.remote: self.readData() else: self.readRemoteData()
l(data)
conditional_block
audio.py
import pyaudio import struct from threading import Thread, Condition import time from logging import thread import socket CHUNK = 2**12 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 class AudioReader(Thread): def __init__(self, raw = False, remote = False, host = 'localhost', port = 9999): Thread._...
def readData(self): self.condition.acquire() self.condition.wait() self.condition.release() self.stream = pyaudio.PyAudio().open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) ...
if not self.active: self.play() self.active = False self.quit = True
identifier_body
audio.py
import pyaudio import struct from threading import Thread, Condition import time from logging import thread import socket CHUNK = 2**12 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 class AudioReader(Thread): def __init__(self, raw = False, remote = False, host = 'localhost', port = 9999): Thread._...
(self): while not self.quit: if not self.remote: self.readData() else: self.readRemoteData()
run
identifier_name
SingularValuesDiagram.tsx
import { HoverCanvasView, HoverCanvasViewState, HoverCanvasViewProps } from "./HoverCanvasView"; import { RGB } from "./rgb"; export interface SingularValuesDiagramProps extends HoverCanvasViewProps { singularValues: RGB<Float64Array>; numSvs: number; } export class SingularValuesDiagram extends HoverCanvasView< ...
} ctx.putImageData(imageData, 0, 0); } }
{ const k = ((h - j) * w + i) * 4; data[k] = (j < redV ? 225 : 100) + b; data[k + 1] = (j < greenV ? 225 : 100) + b; data[k + 2] = (j < blueV ? 225 : 100) + b; data[k + 3] = hover ? 255 : (data[k] + data[k + 1] + data[k + 2]) / 3; }
conditional_block
SingularValuesDiagram.tsx
import { HoverCanvasView, HoverCanvasViewState, HoverCanvasViewProps } from "./HoverCanvasView"; import { RGB } from "./rgb"; export interface SingularValuesDiagramProps extends HoverCanvasViewProps { singularValues: RGB<Float64Array>; numSvs: number; } export class
extends HoverCanvasView< SingularValuesDiagramProps, HoverCanvasViewState > { constructor(props: SingularValuesDiagramProps) { super(props); this.state = { hover: false }; } paint(ctx: CanvasRenderingContext2D): void { const w = this.props.width, h = this.props.height; if (!ctx) { ...
SingularValuesDiagram
identifier_name
SingularValuesDiagram.tsx
import { HoverCanvasView, HoverCanvasViewState, HoverCanvasViewProps } from "./HoverCanvasView"; import { RGB } from "./rgb";
export class SingularValuesDiagram extends HoverCanvasView< SingularValuesDiagramProps, HoverCanvasViewState > { constructor(props: SingularValuesDiagramProps) { super(props); this.state = { hover: false }; } paint(ctx: CanvasRenderingContext2D): void { const w = this.props.width, h = this....
export interface SingularValuesDiagramProps extends HoverCanvasViewProps { singularValues: RGB<Float64Array>; numSvs: number; }
random_line_split
forms.py
from django import forms from django.utils.safestring import mark_safe from markupfield.widgets import MarkupTextarea from .models import Nomination class NominationForm(forms.ModelForm): class
: model = Nomination fields = ( "name", "email", "previous_board_service", "employer", "other_affiliations", "nomination_statement", ) widgets = { "nomination_statement": MarkupTextarea() } # , "...
Meta
identifier_name
forms.py
from django import forms from django.utils.safestring import mark_safe from markupfield.widgets import MarkupTextarea from .models import Nomination class NominationForm(forms.ModelForm): class Meta: model = Nomination fields = ( "name", "email", "previous_boa...
return data
if not self.request.user.first_name or not self.request.user.last_name: raise forms.ValidationError( mark_safe( 'You must set your First and Last name in your <a href="/users/edit/">User Profile</a> to self nominate.' ) )
conditional_block
forms.py
from django import forms from django.utils.safestring import mark_safe
from markupfield.widgets import MarkupTextarea from .models import Nomination class NominationForm(forms.ModelForm): class Meta: model = Nomination fields = ( "name", "email", "previous_board_service", "employer", "other_affiliations", ...
random_line_split
forms.py
from django import forms from django.utils.safestring import mark_safe from markupfield.widgets import MarkupTextarea from .models import Nomination class NominationForm(forms.ModelForm): class Meta: model = Nomination fields = ( "name", "email", "previous_boa...
data = self.cleaned_data["self_nomination"] if data: if not self.request.user.first_name or not self.request.user.last_name: raise forms.ValidationError( mark_safe( 'You must set your First and Last name in your <a href="/users/edit/">User ...
identifier_body
FileUpdateFunctions.ts
import fs = require("fs"); import path = require("path"); import xpath = require("xpath"); import xmldom = require("xmldom"); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&"); } function stringToBoolean (value: string) { switch (value.toLowerCase().trim()) { case ...
} return document; }
{ // Previously call this, but Typescript won't compile, so need to use any type // xmlNode.singleNodeValue.attributes.getNamedItem(attribute).textContent = value; let node: any = xmlNode.singleNodeValue; node.attributes.getNamedItem(attribute).textContent = value; logF...
conditional_block
FileUpdateFunctions.ts
import fs = require("fs"); import path = require("path"); import xpath = require("xpath"); import xmldom = require("xmldom"); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&"); } function stringToBoolean (value: string) { switch (value.toLowerCase().trim()) { case ...
}
{ const dom = xmldom.DOMParser; let document = new dom().parseFromString(rawContent); // XPathResult.FIRST_ORDERED_NODE_TYPE using int equiv 9 else build transpile issue let xmlNode = xpath.evaluate( xpathQuery , document, null, 9, null ); if (xmlNode != null) { if ((attribute == null) || (attribute.l...
identifier_body
FileUpdateFunctions.ts
import fs = require("fs"); import path = require("path"); import xpath = require("xpath"); import xmldom = require("xmldom"); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&"); } function stringToBoolean (value: string) { switch (value.toLowerCase().trim()) {
case "true": case "yes": case "1": return true; case "false": case "no": case "0": case null: return false; default: return Boolean(value); } } export function processFiles (filename: string, recurse: string, xpathQuery: string , value, attribute, logInfo, logDebug ) { let files; logDebug (`Loo...
random_line_split
FileUpdateFunctions.ts
import fs = require("fs"); import path = require("path"); import xpath = require("xpath"); import xmldom = require("xmldom"); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&"); } function stringToBoolean (value: string) { switch (value.toLowerCase().trim()) { case ...
(dir, filenamePattern, recurse, filelist): any { const regex = "^" + escapeRegExp(filenamePattern).replace(/\*/, ".*") + "$"; const r = new RegExp(regex, "i"); // make it case insensitive // let path = path || require('path'); // let fs = fs || require('fs'), const folderItems = fs.readdirSync(dir); file...
findFiles
identifier_name
elevation_image.py
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. """ TODO Docstring. """ import argparse import logging import sys import h5py import numpy as np from PIL import Image from matplotlib import colors from matplotlib import cm from openradar import calc from openradar import config lo...
(): """ Call command with args from parser. """ logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) return command(**vars(get_parser().parse_args())) if __name__ == '__main__': exit(main())
main
identifier_name
elevation_image.py
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. """ TODO Docstring. """ import argparse import logging import sys import h5py import numpy as np from PIL import Image from matplotlib import colors from matplotlib import cm from openradar import calc from openradar import config lo...
def command(paths): """ Show a lowest elevation image. """ # order index = dict( NL60=0, NL61=1, nhb=2, ess=3, emd=4, JAB=5, ) # load d_rang, d_elev, d_anth = {}, {}, {} for p in paths: with h5py.File(p, 'r') as h5: for ...
""" Return argument parser. """ parser = argparse.ArgumentParser( description=__doc__ ) parser.add_argument( 'paths', nargs='+', metavar='FILES', ) return parser
identifier_body
elevation_image.py
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. """ TODO Docstring. """ import argparse import logging import sys import h5py import numpy as np from PIL import Image from matplotlib import colors from matplotlib import cm from openradar import calc from openradar import config lo...
-1, ).max(0) what = alt.min(0) # colors hue = cm.hsv(colors.Normalize(vmax=len(radars))(which), bytes=True) sat = 1 - colors.Normalize(vmax=5, clip=True)(what)[..., np.newaxis] hue[..., :3] *= sat hue[sat.mask[..., 0]] = 255 Image.fromarray(hue).save('elevation_image.png') ...
np.indices(alt.shape)[0],
random_line_split
elevation_image.py
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. """ TODO Docstring. """ import argparse import logging import sys import h5py import numpy as np from PIL import Image from matplotlib import colors from matplotlib import cm from openradar import calc from openradar import config lo...
exit(main())
conditional_block
pathSegCurvetoCubicSmooth.js
/** * @author Ondrej Benda * @date 2011-2016 * @copyright GNU GPLv3 * @brief Implements SVGPathSegCubicSmoothAbs */ function pathSegCurvetoCubicSmooth(x2, y2, x, y) { this.pathSegType = 16; this.pathSegTypeAsLetter = 'S'; this.x = isNaN(x) ? 0 : x; this.y = isNaN(y) ? 0 : y; this.x2 = isNaN(x2) ? 0 : ...
if(handle2) { if(point) { this.x2 += dX; this.y2 += dY; } else { this.x2 = toX; this.y2 = toY; } } } pathSegCurvetoCubicSmooth.prototype.moveBy = function(byX, byY, point, handle1, handle2) { if(point) { this.x += byX; this.y += byY; } if(handle2) { this.x2 += byX; this.y2 += byY; } }...
{ this.x = toX; this.y = toY; }
conditional_block
pathSegCurvetoCubicSmooth.js
/** * @author Ondrej Benda * @date 2011-2016 * @copyright GNU GPLv3 * @brief Implements SVGPathSegCubicSmoothAbs */ function
(x2, y2, x, y) { this.pathSegType = 16; this.pathSegTypeAsLetter = 'S'; this.x = isNaN(x) ? 0 : x; this.y = isNaN(y) ? 0 : y; this.x2 = isNaN(x2) ? 0 : x2; this.y2 = isNaN(y2) ? 0 : y2; } pathSegCurvetoCubicSmooth.prototype = Object.create(pathSeg.prototype); pathSegCurvetoCubicSmooth.prototype.toString = fu...
pathSegCurvetoCubicSmooth
identifier_name
pathSegCurvetoCubicSmooth.js
/** * @author Ondrej Benda * @date 2011-2016 * @copyright GNU GPLv3 * @brief Implements SVGPathSegCubicSmoothAbs */ function pathSegCurvetoCubicSmooth(x2, y2, x, y)
pathSegCurvetoCubicSmooth.prototype = Object.create(pathSeg.prototype); pathSegCurvetoCubicSmooth.prototype.toString = function() { return 'S ' + this.x2 + ' ' + this.y2 + ' ' + this.x + ' ' + this.y; } pathSegCurvetoCubicSmooth.prototype.moveTo = function(toX, toY, point, handle1, handle2) { var dX = toX - thi...
{ this.pathSegType = 16; this.pathSegTypeAsLetter = 'S'; this.x = isNaN(x) ? 0 : x; this.y = isNaN(y) ? 0 : y; this.x2 = isNaN(x2) ? 0 : x2; this.y2 = isNaN(y2) ? 0 : y2; }
identifier_body
pathSegCurvetoCubicSmooth.js
/** * @author Ondrej Benda * @date 2011-2016 * @copyright GNU GPLv3 * @brief Implements SVGPathSegCubicSmoothAbs */ function pathSegCurvetoCubicSmooth(x2, y2, x, y) { this.pathSegType = 16; this.pathSegTypeAsLetter = 'S'; this.x = isNaN(x) ? 0 : x; this.y = isNaN(y) ? 0 : y; this.x2 = isNaN(x2) ? 0 : ...
this.y2 = toY; } } } pathSegCurvetoCubicSmooth.prototype.moveBy = function(byX, byY, point, handle1, handle2) { if(point) { this.x += byX; this.y += byY; } if(handle2) { this.x2 += byX; this.y2 += byY; } } pathSegCurvetoCubicSmooth.prototype.getAdjusted = function(matrix) { if(!(matrix instanceof...
this.y2 += dY; } else { this.x2 = toX;
random_line_split
navigatorinfo.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::str::DOMString; use std::borrow::Cow; pub fn Product() -> DOMString { DOMString::f...
pub fn AppCodeName() -> DOMString { DOMString::from("Mozilla") } #[cfg(target_os = "windows")] pub fn Platform() -> DOMString { DOMString::from("Win32") } #[cfg(any(target_os = "android", target_os = "linux"))] pub fn Platform() -> DOMString { DOMString::from("Linux") } #[cfg(target_os = "macos")] pub fn...
random_line_split
navigatorinfo.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::str::DOMString; use std::borrow::Cow; pub fn Product() -> DOMString { DOMString::f...
pub fn AppCodeName() -> DOMString { DOMString::from("Mozilla") } #[cfg(target_os = "windows")] pub fn Platform() -> DOMString { DOMString::from("Win32") } #[cfg(any(target_os = "android", target_os = "linux"))] pub fn Platform() -> DOMString { DOMString::from("Linux") } #[cfg(target_os = "macos")] pub ...
{ DOMString::from("Netscape") // Like Gecko/Webkit }
identifier_body
navigatorinfo.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::str::DOMString; use std::borrow::Cow; pub fn Product() -> DOMString { DOMString::f...
() -> DOMString { DOMString::from("Mac") } #[cfg(target_os = "ios")] pub fn Platform() -> DOMString { DOMString::from("iOS") } pub fn UserAgent(user_agent: Cow<'static, str>) -> DOMString { DOMString::from(&*user_agent) } pub fn AppVersion() -> DOMString { DOMString::from("4.0") } pub fn Language() ...
Platform
identifier_name
data.js
const util = require('util'); module.exports = function (req, res, utils) { var deferred = Promise.defer(); utils.request({ url: 'open/get_posts_by_category', method: 'POST', qs: { siteId: req.site.id, categoryId: 'susdanwmf4pckzxn7w24jw', pageSize:...
; result.body = JSON.parse(result.body); data.category = { href: util.format('category?id=%s', result.body.category.id) }; result.body.data.forEach(function (e) { //设置第一个显示的新闻 if (!data.first) { e.text ? e.text : (e.text = e.title);...
{ deferred.resolve(data); return; }
conditional_block
data.js
const util = require('util'); module.exports = function (req, res, utils) { var deferred = Promise.defer(); utils.request({ url: 'open/get_posts_by_category', method: 'POST', qs: { siteId: req.site.id, categoryId: 'susdanwmf4pckzxn7w24jw', pageSize:...
return deferred.promise; }
random_line_split
issue-14959.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. //
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(unboxed_closures)] use std::ops::Fn; trait Response {} trait Request {} trait Ingot<R, S> { fn enter(&mut self, _: &mut R, _: &mut S, a: ...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
issue-14959.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 ...
} fn main() {}
{ let send_file = alloy.find::<SendFile>().unwrap(); send_file(res); Status::Continue }
identifier_body
issue-14959.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 ...
; enum Status { Continue } impl Alloy { fn find<T>(&self) -> Option<T> { None } } impl<'a, 'b> Fn<(&'b mut (Response+'b),)> for SendFile<'a> { type Output = (); extern "rust-call" fn call(&self, (_res,): (&'b mut (Response+'b),)) {} } impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for Hel...
Alloy
identifier_name
angular-ui-select.js
return { lhs: lhs, rhs: rhs, trackByExp: trackByExp }; }; self.getNgRepeatExpression = function(lhs, rhs, trackByExp) { var expression = lhs + ' in ' + rhs; if (trackByExp) { expression += ' track by ' + trackByExp; } return expression; }; }]) /** * Contains ui-sele...
return { restrict: 'EA', templateUrl: function(tElement, tAttrs) { var theme = tAttrs.theme || uiSelectConfig.theme; return theme + '/select.tpl.html'; }, replace: true, transclude: true, require: ['uiSelect', 'ngModel'], scope: true, controller: 'uiSelectCtrl', contr...
}]) .directive('uiSelect', ['$document', 'uiSelectConfig', 'uiSelectMinErr', function($document, uiSelectConfig, uiSelectMinErr) {
random_line_split
angular-ui-select.js
/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177 if (_refreshDelayPromise) { $timeout.cancel(_refreshDelayPromise); } _refreshDelayPromise = $timeout(function() { $scope.$eval(refreshAttr); }, ctrl.refreshDelay); } }; // When the user clicks on an i...
{ return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); }
identifier_body
angular-ui-select.js
return { lhs: lhs, rhs: rhs, trackByExp: trackByExp }; }; self.getNgRepeatExpression = function(lhs, rhs, trackByExp) { var expression = lhs + ' in ' + rhs; if (trackByExp) { expression += ' track by ' + trackByExp; } return expression; }; }]) /** * Contains ui-sele...
(key) { var processed = true; switch (key) { case Key.Down: if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; } break; case Key.Up: if (ctrl.activeIndex > 0) { ctrl.activeIndex--; } break; case Key.Tab: case Key.Enter: ctrl.select...
_onKeydown
identifier_name
angular-ui-select.js
{ lhs: lhs, rhs: rhs, trackByExp: trackByExp }; }; self.getNgRepeatExpression = function(lhs, rhs, trackByExp) { var expression = lhs + ' in ' + rhs; if (trackByExp) { expression += ' track by ' + trackByExp; } return expression; }; }]) /** * Contains ui-select "int...
} // See Click everywhere but here event http://stackoverflow.com/questions/12931369 $document.on('click', onDocumentClick); scope.$on('$destroy', function() { $document.off('click', onDocumentClick); }); // Move transcluded elements to their correct position in main temp...
{ $select.close(); scope.$digest(); }
conditional_block
i18n_plural_pipe.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 {Pipe, PipeTransform} from '@angular/core'; import {NgLocalization, getPluralCategory} from '../localization'...
* - `expression` is a number. * - `mapping` is an object that mimics the ICU format, see * http://userguide.icu-project.org/formatparse/messages * * ## Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @experimental */ @Pipe({name: 'i18nPlural', pure: true}) export...
* Where:
random_line_split
i18n_plural_pipe.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 {Pipe, PipeTransform} from '@angular/core'; import {NgLocalization, getPluralCategory} from '../localization'...
implements PipeTransform { constructor(private _localization: NgLocalization) {} transform(value: number, pluralMap: {[count: string]: string}): string { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null) { throw invalidPipeArgumentError(I18nPluralPipe, pluralMap...
I18nPluralPipe
identifier_name
SortFactoryHelpers.spec.ts
import {TestUtils} from "../TestUtils"; import {Row} from "../../src/models/Row";
const detailRow:Row = TestUtils.getDetailRow(); const columnDefs:ColumnDef[] = TestUtils.getSimpleColumns(); const subtotalRow:Row = TestUtils.getSimpleSubtotalRow(); it("should extract a number detail row", ()=> { const val = extractCellValue(detailRow, columnDefs[0]); expect(...
import {ColumnDef} from "../../src/models/ColumnLike"; import {extractCellValue} from "../../src/static/SortFactoryHelpers"; describe("SortFactoryHelper.extractCellValue()", ()=> {
random_line_split
grammarReader.ts
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ 'use strict'; import { IRawGrammar } from './types'; import * as plist from './plist'; import { CAPTURE_METADATA } from './debug';...
return parsePLISTGrammar(content, filePath); } function parseJSONGrammar(contents: string, filename: string): IRawGrammar { if (CAPTURE_METADATA) { return <IRawGrammar>manualParseJSON(contents, filename, true); } return <IRawGrammar>JSON.parse(contents); } function parsePLISTGrammar(contents: string...
{ return parseJSONGrammar(content, filePath); }
conditional_block
grammarReader.ts
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ 'use strict'; import { IRawGrammar } from './types'; import * as plist from './plist'; import { CAPTURE_METADATA } from './debug';...
function parseJSONGrammar(contents: string, filename: string): IRawGrammar { if (CAPTURE_METADATA) { return <IRawGrammar>manualParseJSON(contents, filename, true); } return <IRawGrammar>JSON.parse(contents); } function parsePLISTGrammar(contents: string, filename: string): IRawGrammar { if (CAPTURE_M...
{ if (/\.json$/.test(filePath)) { return parseJSONGrammar(content, filePath); } return parsePLISTGrammar(content, filePath); }
identifier_body
grammarReader.ts
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ 'use strict'; import { IRawGrammar } from './types'; import * as plist from './plist'; import { CAPTURE_METADATA } from './debug';...
(contents: string, filename: string): IRawGrammar { if (CAPTURE_METADATA) { return <IRawGrammar>manualParseJSON(contents, filename, true); } return <IRawGrammar>JSON.parse(contents); } function parsePLISTGrammar(contents: string, filename: string): IRawGrammar { if (CAPTURE_METADATA) { return <IRawGra...
parseJSONGrammar
identifier_name
grammarReader.ts
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ 'use strict'; import { IRawGrammar } from './types'; import * as plist from './plist'; import { CAPTURE_METADATA } from './debug';...
export function parseRawGrammar(content: string, filePath: string): IRawGrammar { if (/\.json$/.test(filePath)) { return parseJSONGrammar(content, filePath); } return parsePLISTGrammar(content, filePath); } function parseJSONGrammar(contents: string, filename: string): IRawGrammar { if (CAPTURE_METADAT...
random_line_split
imageContainer.test.js
import imageContainer from '../server/api/helpers/imageContainer'; const entries = [ { html: '<img src="/img/60x30.png" alt="60x30" class="zoom" data-zoom-src="/img/60x30-original.png">', }, { html: `<div>
{ html: '<div>Hello, World!</div>', }, ]; describe('ImageContainer', () => { const modifiedEntries = imageContainer(entries, __dirname); it('Parses one image', () => { expect(modifiedEntries[0].html).toContain('<div class="imageContainer" style="width: 60px;">'); expect(modifiedEntries[0].html).to...
<img src="/img/20x50.jpg"> </div> <img src="/img/40x10.svg" alt="40x10">`, },
random_line_split
server.js
var util = require('util'); var async = require('async'); var path = require('path'); var Router = require('../utils/router.js'); var sandboxHelper = require('../utils/sandbox.js'); // Private fields var modules, library, self, private = {}, shared = {}; private.loaded = false // Constructor function Server(cb, scop...
if (private.loaded) { res.render('wallet.html', {layout: false}); } else { res.render('index.html'); } }); router.get('/dapps/:id', function (req, res) { res.render('dapps/' + req.params.id + '/index.html'); }); router.use(function (req, res, next) { if (req.url.indexOf('/api/'...
}); router.get('/', function (req, res) {
random_line_split
server.js
var util = require('util'); var async = require('async'); var path = require('path'); var Router = require('../utils/router.js'); var sandboxHelper = require('../utils/sandbox.js'); // Private fields var modules, library, self, private = {}, shared = {}; private.loaded = false // Constructor function Server(cb, scop...
// Private methods private.attachApi = function() { var router = new Router(); router.use(function (req, res, next) { if (modules) return next(); res.status(500).send({success: false, error: "Blockchain is loading"}); }); router.get('/', function (req, res) { if (private.loaded) { res.rend...
{ library = scope; self = this; self.__private = private; private.attachApi(); setImmediate(cb, null, self); }
identifier_body
server.js
var util = require('util'); var async = require('async'); var path = require('path'); var Router = require('../utils/router.js'); var sandboxHelper = require('../utils/sandbox.js'); // Private fields var modules, library, self, private = {}, shared = {}; private.loaded = false // Constructor function
(cb, scope) { library = scope; self = this; self.__private = private; private.attachApi(); setImmediate(cb, null, self); } // Private methods private.attachApi = function() { var router = new Router(); router.use(function (req, res, next) { if (modules) return next(); res.status(500).send({succ...
Server
identifier_name
object_list.js
= false; //var IsHidingAllFilled = true; var ListOffSet = 0; //This function creates and populates the list function RenderObjectList() { // If object list has been rendered, then remove it: var scrollPos = $("#anno_list").scrollTop(); if($('#anno_list').length) { $('#anno_list').remove(); } var html_str = '...
// Render the annotations: main_canvas.UnhideAllAnnotations(); main_canvas.RenderAnnotations(); //Fill all for (var i= 0; i < LMnumberOfObjects(LM_xml); i++){ main_canvas.annotations[i].FillPolygon(); } console.log("check progress"); // Create "hide all" button: $('#show_all_filled_button').replaceWith...
{ // Attach to main_canvas: main_canvas.AttachAnnotation(new annotation(pp)); if (!video_mode && LMgetObjectField(LM_xml, pp, 'x') == null){ main_canvas.annotations[main_canvas.annotations.length -1].SetType(1); main_canvas.annotations[main_canvas.annotations.length -1].scribble =...
conditional_block
object_list.js
= false; //var IsHidingAllFilled = true; var ListOffSet = 0; //This function creates and populates the list function RenderObjectList() { // If object list has been rendered, then remove it: var scrollPos = $("#anno_list").scrollTop(); if($('#anno_list').length) { $('#anno_list').remove(); } var html_str = '...
function HideAllPolygons() { if(!edit_popup_open) { IsHidingAllPolygons = true; ProgressChecking = false; // Delete all polygons from the canvas: for(var i = 0; i < main_canvas.annotations.length; i++) { main_canvas.annotations[i].DeletePolygon(); main_canvas.annotations[i].hidden = true; } // Cr...
{ document.getElementById('Link'+idx).style.color = '#FF0000'; var anid = main_canvas.GetAnnoIndex(idx); // If we're hiding all polygons, then render polygon on canvas: if(IsHidingAllPolygons && main_canvas.annotations[anid].hidden) { main_canvas.annotations[anid].DrawPolygon(main_media.GetImRatio(), main_canvas....
identifier_body
object_list.js
Checking = false; //var IsHidingAllFilled = true; var ListOffSet = 0; //This function creates and populates the list function RenderObjectList() { // If object list has been rendered, then remove it: var scrollPos = $("#anno_list").scrollTop(); if($('#anno_list').length) { $('#anno_list').remove(); } var html...
main_canvas.annotations[anid].DeletePolygon(); } } } function ChangeLinkColorFG(idx) { document.getElementById('Link'+idx).style.color = '#FF0000'; var anid = main_canvas.GetAnnoIndex(idx); // If we're hiding all polygons, then render polygon on canvas: if(IsHidingAllPolygons && main_canvas.annotations[anid...
// If we're hiding all polygons, then remove rendered polygon from canvas: if(IsHidingAllPolygons && main_canvas.annotations[anid].hidden) {
random_line_split
object_list.js
anno_list').length) { $('#anno_list').remove(); } var html_str = '<div class="object_list" id="anno_list" style="border:0px solid black;z-index:0;" ondrop="drop(event, -1)" ondragenter="return dragEnter(event)" ondragover="return dragOver(event)">'; var Npolygons = LMnumberOfObjects(LM_xml); // name of image h...
dragOver
identifier_name
errors.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
} impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.err { _ => write!(f, "{:?}", self.err), }?; if let Some(ref e) = self.pre_expressions { write!(f, "\nNear:\n{:?}", e)?; } Ok(()) } } impl er...
{ self.diagnostic.spans = exprs.iter().map(|e| e.span.clone()).collect(); self.pre_expressions.replace(exprs.clone().to_vec()); }
identifier_body
errors.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
ParseErrors::ProgramTooLarge => format!("Program too large to parse"), ParseErrors::IllegalContractName(contract_name) => { format!("Illegal contract name: '{}'", contract_name) } ParseErrors::IllegalVariableName(var_name) => { format!("Il...
{ format!("Whitespace expected after colon (:), Found: '{}'", found) }
conditional_block
errors.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
(err: ParseErrors) -> ParseError { let diagnostic = Diagnostic::err(&err); ParseError { err, pre_expressions: None, diagnostic, } } pub fn has_pre_expression(&self) -> bool { self.pre_expressions.is_some() } pub fn set_pre_expression(...
new
identifier_name
errors.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
ParseErrors::ClosingTupleLiteralExpected => { format!("Tuple literal {{..}} left opened.") } ParseErrors::ColonSeparatorUnexpected => format!("Misplaced colon."), ParseErrors::CommaSeparatorUnexpected => format!("Misplaced comma."), ParseErrors...
format!("Tried to close tuple literal which isn't open.") }
random_line_split
utils.ts
import { DataTypeFields, FieldType } from '@terascope/types'; import { isNumber, isBigInt, getTypeOf, isArrayLike, TSError } from '@terascope/utils'; import { ListVector } from './ListVector'; import { AnyVector, BigIntVector, BooleanVector, DateVector, FloatVector, GeoJSONVector, GeoPointVector, In...
return { type: changesToBigInt ? 'bigint' : curr.type, values: curr.values } as NumericValuesResult; } export function isNumberLike(type: FieldType): boolean { if (type === FieldType.Long) return true; return isFloatLike(type) || isIntLike(type); } export function isFloatLike(type: Fie...
// add the typescript hacks so will stop complaining (curr.values as number[]).push(v as number);
random_line_split
utils.ts
import { DataTypeFields, FieldType } from '@terascope/types'; import { isNumber, isBigInt, getTypeOf, isArrayLike, TSError } from '@terascope/utils'; import { ListVector } from './ListVector'; import { AnyVector, BigIntVector, BooleanVector, DateVector, FloatVector, GeoJSONVector, GeoPointVector, In...
/** * An interval function for doing recursion recursion, made for getNumericValues */ function _getNumericValues(curr: NumericValuesResult, v: unknown): NumericValuesResult { if (v == null) return curr; if (isArrayLike(v)) { let res: NumericValuesResult = curr; for (const nested of v) { ...
{ return _getNumericValues({ type: 'number', values: [] }, value); }
identifier_body
utils.ts
import { DataTypeFields, FieldType } from '@terascope/types'; import { isNumber, isBigInt, getTypeOf, isArrayLike, TSError } from '@terascope/utils'; import { ListVector } from './ListVector'; import { AnyVector, BigIntVector, BooleanVector, DateVector, FloatVector, GeoJSONVector, GeoPointVector, In...
(type: FieldType): boolean { if (type === FieldType.Byte) return true; if (type === FieldType.Short) return true; if (type === FieldType.Integer) return true; return false; } export function isStringLike(type: FieldType): boolean { if (type === FieldType.String) return true; if (type === FieldT...
isIntLike
identifier_name
mod.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 ...
(&mut self) -> u32 { self.rng.borrow_mut().next_u32() } fn next_u64(&mut self) -> u64 { self.rng.borrow_mut().next_u64() } #[inline] fn fill_bytes(&mut self, bytes: &mut [u8]) { self.rng.borrow_mut().fill_bytes(bytes) } }
next_u32
identifier_name
mod.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 ...
}
{ self.rng.borrow_mut().fill_bytes(bytes) }
identifier_body