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
palindrama.js
var flag = "did_you_use_python's_[::-1]_notation?"; exports.get_data = function(req, callback) { var result = []; var s = [ "[Go, droop aloof] sides reversed, is [fool a poor dog]. I did roar again, Niagara! ... or did I?", "Help Max, Enid -- in example, H. See, slave, I demonstrate yet arts no medieval sees.", ...
req.session.data = result; callback(result); }; exports.check_data = function(req, callback) { var answer = req.param("answer"); var data = req.session.data; var s = data[0]; var longest = ""; var longestOrig = ""; for(var i = s.length - 1; i >= 0; i--) { for (var j = i + 1; j < s.length; j++) { var...
//console.log(s,a); result.push(a);
random_line_split
palindrama.js
var flag = "did_you_use_python's_[::-1]_notation?"; exports.get_data = function(req, callback) { var result = []; var s = [ "[Go, droop aloof] sides reversed, is [fool a poor dog]. I did roar again, Niagara! ... or did I?", "Help Max, Enid -- in example, H. See, slave, I demonstrate yet arts no medieval sees.", ...
} } var correct = longestOrig; /*console.log("!"+longestOrig+"!"); console.log("!"+output+"!"); console.log(longestOrig == output);*/ // return longestOrig === answer; if (answer) { answer = answer.replace(/^\s+|\s+$/g,''); correct = correct.replace(/^\s+|\s+$/g,''); if (answer.toLowerCase() === correct...
{ longest = t; longestOrig = q.trim(); }
conditional_block
index.js
/** * Copyright JS Foundation and other contributors, http://js.foundation * * 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 r...
var auth = require("./auth"); var apiUtil = require("./util"); var adminApp; var server; var runtime; var editor; function init(_server,_runtime) { server = _server; runtime = _runtime; var settings = runtime.settings; if (settings.httpAdminRoot !== false) { apiUtil.init(runtime); admi...
random_line_split
index.js
/** * Copyright JS Foundation and other contributors, http://js.foundation * * 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 r...
() { return server; } };
server
identifier_name
index.js
/** * Copyright JS Foundation and other contributors, http://js.foundation * * 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 r...
var adminApiApp = require("./admin").init(runtime); adminApp.use(adminApiApp); } else { adminApp = null; } } function start() { if (editor) { return editor.start(); } else { return when.resolve(); } } function stop() { if (editor) { editor.stop()...
{ var corsHandler = cors(settings.httpAdminCors); adminApp.use(corsHandler); }
conditional_block
index.js
/** * Copyright JS Foundation and other contributors, http://js.foundation * * 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 r...
auth.ensureClientSecret, auth.authenticateClient, auth.getToken, auth.errorHandler ); } adminApp.post("/auth/revoke",auth.needsPermission(""),auth.revoke,apiUtil.errorHandler); } // E...
{ server = _server; runtime = _runtime; var settings = runtime.settings; if (settings.httpAdminRoot !== false) { apiUtil.init(runtime); adminApp = express(); auth.init(runtime); var maxApiRequestSize = settings.apiMaxLength || '5mb'; adminApp.use(bodyParser.json(...
identifier_body
realness_tests.py
# coding: utf-8 from __future__ import print_function from __future__ import unicode_literals import re import poetryutils2 # this is all for use within ipython def sample_words(): lines = poetryutils2.utils.debug_lines() words = list() for l in lines: words.extend(w.lower() for w in l.split()) ...
def main(): # print(len(sample_words())) sample = sample_words() print(len(sample)) fails = realness(sample) # for f in fails: # print(f) from collections import Counter counter = Counter(fails) for word, count in counter.most_common(): if count > 1: prin...
fails = [w for w in sample if not poetryutils2.utils.is_real_word(w)] return fails
identifier_body
realness_tests.py
# coding: utf-8 from __future__ import print_function from __future__ import unicode_literals import re import poetryutils2 # this is all for use within ipython def sample_words(): lines = poetryutils2.utils.debug_lines() words = list() for l in lines: words.extend(w.lower() for w in l.split()) ...
for word, count in counter.most_common(): if count > 1: print(word, count) # import argparse # parser = argparse.ArgumentParser() # parser.add_argument('arg1', type=str, help="required argument") # parser.add_argument('arg2', '--argument-2', help='optional boolean argument', acti...
random_line_split
realness_tests.py
# coding: utf-8 from __future__ import print_function from __future__ import unicode_literals import re import poetryutils2 # this is all for use within ipython def sample_words(): lines = poetryutils2.utils.debug_lines() words = list() for l in lines: words.extend(w.lower() for w in l.split()) ...
main()
conditional_block
realness_tests.py
# coding: utf-8 from __future__ import print_function from __future__ import unicode_literals import re import poetryutils2 # this is all for use within ipython def
(): lines = poetryutils2.utils.debug_lines() words = list() for l in lines: words.extend(w.lower() for w in l.split()) # maybe we want to clean words up more? let's just do that I think # words = [w[:-1] for w in words if w[-1] in {'.',',','!','?'}] # tofix = [w for w in words if w[-1] in...
sample_words
identifier_name
scale_button.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_double; use cast::GTK_SCALEBUTTON; use ffi; pub trait ScaleButtonTrait: ::Widge...
(&self, value: f64) -> () { unsafe { ffi::gtk_scale_button_set_value(GTK_SCALEBUTTON(self.unwrap_widget()), value as c_double); } } fn get_value(&self) -> f64 { unsafe { ffi::gtk_scale_button_get_value(GTK_SCALEBUTTON(self.unwrap_widget())) as f64 } }...
set_value
identifier_name
scale_button.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_double; use cast::GTK_SCALEBUTTON; use ffi; pub trait ScaleButtonTrait: ::Widge...
}
{ unsafe { ::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) } }
identifier_body
scale_button.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_double; use cast::GTK_SCALEBUTTON; use ffi; pub trait ScaleButtonTrait: ::Widge...
ffi::gtk_scale_button_get_value(GTK_SCALEBUTTON(self.unwrap_widget())) as f64 } } fn get_adjustment(&self) -> ::Adjustment { unsafe { ::Adjustment::wrap_pointer(ffi::gtk_scale_button_get_adjustment(GTK_SCALEBUTTON(self.unwrap_widget()))) } } }
} } fn get_value(&self) -> f64 { unsafe {
random_line_split
init-api-with-user-auth.ts
/*! * Copyright 2019 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
const meta = document.createElement('meta'); meta.setAttribute('name', 'google-signin-client_id'); meta.setAttribute('content', process.env.GOOGLE_SIGNIN_CLIENT_ID || ''); head.appendChild(meta); return new Promise(resolve => { const signin = () => { gapi.client.setApiKey(''); gapi.signin2....
{ script = document.createElement('script'); script.id = 'auth_script'; script.type = 'text/javascript'; script.src = 'https://apis.google.com/js/platform.js'; }
conditional_block
init-api-with-user-auth.ts
/*! * Copyright 2019 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 * * https://www.apache.org/licenses/LICENSE-2.0
* limitations under the License. */ /** * Load & Initialize Google Auth */ export default function(): Promise<void> { const scriptExists = document.querySelector( 'script[src="https://apis.google.com/js/platform.js"]' ); const head = document.getElementsByTagName('head')[0]; let script: HTMLScriptEleme...
* * Unless required by applicable law or agreed to in writing, software * 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
random_line_split
run.test.ts
import htmlKeyboardResponse from "@jspsych/plugin-html-keyboard-response"; import { flushPromises, startTimeline } from "../utils"; describe("jsPsych.run()", () => { beforeEach(() => { document.body.innerHTML = ""; }); function setReadyState(targetState: "loading" | "complete") { jest.spyOn(document, "...
() { await startTimeline([ { type: htmlKeyboardResponse, stimulus: "foo", }, ]); } // Currently not implemented – we need a way to await promises it("should delay execution until the document is ready", async () => { expect(getBodyHTML()).toBe(""); setReadyState("load...
init
identifier_name
run.test.ts
import htmlKeyboardResponse from "@jspsych/plugin-html-keyboard-response"; import { flushPromises, startTimeline } from "../utils"; describe("jsPsych.run()", () => { beforeEach(() => { document.body.innerHTML = ""; }); function setReadyState(targetState: "loading" | "complete") { jest.spyOn(document, "...
}); it("should execute immediately when the document is ready", async () => { // The document is ready by default in jsdom await init(); expect(getBodyHTML()).not.toBe(""); }); });
random_line_split
run.test.ts
import htmlKeyboardResponse from "@jspsych/plugin-html-keyboard-response"; import { flushPromises, startTimeline } from "../utils"; describe("jsPsych.run()", () => { beforeEach(() => { document.body.innerHTML = ""; }); function setReadyState(targetState: "loading" | "complete")
function getBodyHTML() { return document.body.innerHTML; } async function init() { await startTimeline([ { type: htmlKeyboardResponse, stimulus: "foo", }, ]); } // Currently not implemented – we need a way to await promises it("should delay execution until the doc...
{ jest.spyOn(document, "readyState", "get").mockImplementation(() => targetState); }
identifier_body
jsonp.js
const chunks = {} // chunkId => exports const chunksInstalling = {} // chunkId => Promise const failedChunks = {} function importChunk(chunkId, src) { // Already installed if (chunks[chunkId]) { return Promise.resolve(chunks[chunkId]) } // Failed loading if (failedChunks[chunkId]) { return Promise.r...
// Set a promise in chunk cache let resolve, reject const promise = chunksInstalling[chunkId] = new Promise((_resolve, _reject) => { resolve = _resolve reject = _reject }) // Clear chunk data from cache delete chunks[chunkId] // Start chunk loading const script = document.createElement('script...
}
random_line_split
jsonp.js
const chunks = {} // chunkId => exports const chunksInstalling = {} // chunkId => Promise const failedChunks = {} function
(chunkId, src) { // Already installed if (chunks[chunkId]) { return Promise.resolve(chunks[chunkId]) } // Failed loading if (failedChunks[chunkId]) { return Promise.reject(failedChunks[chunkId]) } // Installing if (chunksInstalling[chunkId]) { return chunksInstalling[chunkId] } // Set...
importChunk
identifier_name
jsonp.js
const chunks = {} // chunkId => exports const chunksInstalling = {} // chunkId => Promise const failedChunks = {} function importChunk(chunkId, src) { // Already installed if (chunks[chunkId]) { return Promise.resolve(chunks[chunkId]) } // Failed loading if (failedChunks[chunkId])
// Installing if (chunksInstalling[chunkId]) { return chunksInstalling[chunkId] } // Set a promise in chunk cache let resolve, reject const promise = chunksInstalling[chunkId] = new Promise((_resolve, _reject) => { resolve = _resolve reject = _reject }) // Clear chunk data from cache d...
{ return Promise.reject(failedChunks[chunkId]) }
conditional_block
jsonp.js
const chunks = {} // chunkId => exports const chunksInstalling = {} // chunkId => Promise const failedChunks = {} function importChunk(chunkId, src)
reject = _reject }) // Clear chunk data from cache delete chunks[chunkId] // Start chunk loading const script = document.createElement('script') script.charset = 'utf-8' script.timeout = 120 script.src = src let timeout // Create error before stack unwound to get useful stacktrace later con...
{ // Already installed if (chunks[chunkId]) { return Promise.resolve(chunks[chunkId]) } // Failed loading if (failedChunks[chunkId]) { return Promise.reject(failedChunks[chunkId]) } // Installing if (chunksInstalling[chunkId]) { return chunksInstalling[chunkId] } // Set a promise in c...
identifier_body
type-alias-impl-trait.rs
// run-pass
#![allow(unused_assignments)] #![allow(unused_variables)] #![feature(type_alias_impl_trait)] fn main() { assert_eq!(foo().to_string(), "foo"); assert_eq!(bar1().to_string(), "bar1"); assert_eq!(bar2().to_string(), "bar2"); let mut x = bar1(); x = bar2(); assert_eq!(my_iter(42u8).collect::<Vec<u...
#![allow(dead_code)]
random_line_split
type-alias-impl-trait.rs
// run-pass #![allow(dead_code)] #![allow(unused_assignments)] #![allow(unused_variables)] #![feature(type_alias_impl_trait)] fn main() { assert_eq!(foo().to_string(), "foo"); assert_eq!(bar1().to_string(), "bar1"); assert_eq!(bar2().to_string(), "bar2"); let mut x = bar1(); x = bar2(); assert...
// two definitions type Bar = impl std::fmt::Display; fn bar1() -> Bar { "bar1" } fn bar2() -> Bar { "bar2" } type MyIter<T> = impl Iterator<Item = T>; fn my_iter<T>(t: T) -> MyIter<T> { std::iter::once(t) } fn my_iter2<T>(t: T) -> MyIter<T> { std::iter::once(t) } // param names should not have ...
{ "foo" }
identifier_body
type-alias-impl-trait.rs
// run-pass #![allow(dead_code)] #![allow(unused_assignments)] #![allow(unused_variables)] #![feature(type_alias_impl_trait)] fn main() { assert_eq!(foo().to_string(), "foo"); assert_eq!(bar1().to_string(), "bar1"); assert_eq!(bar2().to_string(), "bar2"); let mut x = bar1(); x = bar2(); assert...
<U>(u: U) -> MyIter<U> { std::iter::once(u) } // param position should not have an effect! fn my_iter4<U, V>(_: U, v: V) -> MyIter<V> { std::iter::once(v) } // param names should not have an effect! type MyOtherIter<T> = impl Iterator<Item = T>; fn my_other_iter<U>(u: U) -> MyOtherIter<U> { std::iter::on...
my_iter3
identifier_name
box.js
Template.box.onCreated(function () { var token = BX.Session.get('token'), boxId = BX.Session.get('boxId'); this.subscribe('boxNotCancelled', token, boxId); this.subscribe('boxItemsForBox', token, boxId); this.subscribe('productVariations'); // If called from an iframe, pass the content height back to the if...
return BX.Model.BoxStatus[this.statusId].label; }, boxItemsExist: function () { var box = BX.Collection.Boxes.findOne(), boxItemsCount = 0; if (box) { boxItemsCount = BX.Collection.BoxItems.find().count(); } return boxItemsCount; }, boxItems: function () { return BX.Collection.Bo...
var box = BX.Collection.Boxes.findOne(); return BX.Utility.Date.formatDate(box.renewalDate); }, boxStatusLabel: function () {
random_line_split
box.js
Template.box.onCreated(function () { var token = BX.Session.get('token'), boxId = BX.Session.get('boxId'); this.subscribe('boxNotCancelled', token, boxId); this.subscribe('boxItemsForBox', token, boxId); this.subscribe('productVariations'); // If called from an iframe, pass the content height back to the if...
} }); } }); }) Template.box.helpers({ box: function () { return BX.Collection.Boxes.findOne(); }, boxRenewalDate: function () { var box = BX.Collection.Boxes.findOne(); return BX.Utility.Date.formatDate(box.renewalDate); }, boxStatusLabel: function () { return BX.Mod...
{ var box = BX.Collection.Boxes.findOne(); if (box && (box.statusId === BX.Model.BoxStatus.paused.id)) { Meteor.defer(function () { $('.box-pause').hide(); $('.box-resume').show(); }); } Meteor.defer(function () { $('.box-renewal-date').datepicker({ ...
conditional_block
run.rs
use agent::Crowd; use observer::{Observer, ProgressMeter, DiskWriter}; mod agent; mod geometry; mod observer; fn main() { let mut cells=Crowd::new(1); let tmax=10f64; let dt=0.0001; let mut t=0.0; for _ in range(0,(tmax/dt) as uint){ let new_cells=cells.evolve(dt); let obs_cell...
} } ); cells=new_cells; t+=dt; } }
obs2.see(st, &obs_cells);
random_line_split
run.rs
use agent::Crowd; use observer::{Observer, ProgressMeter, DiskWriter}; mod agent; mod geometry; mod observer; fn
() { let mut cells=Crowd::new(1); let tmax=10f64; let dt=0.0001; let mut t=0.0; for _ in range(0,(tmax/dt) as uint){ let new_cells=cells.evolve(dt); let obs_cells=cells; let st=t; spawn(proc() { let obs = ProgressMeter::new(tmax, 100); if obs.reque...
main
identifier_name
run.rs
use agent::Crowd; use observer::{Observer, ProgressMeter, DiskWriter}; mod agent; mod geometry; mod observer; fn main() { let mut cells=Crowd::new(1); let tmax=10f64; let dt=0.0001; let mut t=0.0; for _ in range(0,(tmax/dt) as uint){ let new_cells=cells.evolve(dt); let obs_cell...
} ); cells=new_cells; t+=dt; } }
{ obs2.see(st, &obs_cells); }
conditional_block
run.rs
use agent::Crowd; use observer::{Observer, ProgressMeter, DiskWriter}; mod agent; mod geometry; mod observer; fn main()
if obs2.request_at(st,dt) { obs2.see(st, &obs_cells); } } ); cells=new_cells; t+=dt; } }
{ let mut cells=Crowd::new(1); let tmax=10f64; let dt=0.0001; let mut t=0.0; for _ in range(0,(tmax/dt) as uint){ let new_cells=cells.evolve(dt); let obs_cells=cells; let st=t; spawn(proc() { let obs = ProgressMeter::new(tmax, 100); if obs.request_...
identifier_body
app.controller.js
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribut...
}); // Set The lookAndFeel to default on every page $rootScope.$on('$routeChangeStart', function(event, next, current) { $rootScope.$broadcast('setLookAndFeel', 'default'); }); BootstrapDialog.defaultOptions.onshown = function() { angular.element('#' + this.id).find('.btn:last').focus(); }; //...
{ $scope.looknfeel = data; event.preventDefault(); }
conditional_block
app.controller.js
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the 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 govern...
*
random_line_split
rtlsdr.rs
/* Copyright Ian Daniher, 2013, 2014. Distributed under the terms of the GPLv3. */ #![feature(libc)] #![feature(collections)] #![feature(core)] extern crate num; extern crate libc; use num::complex; use libc::{c_int, c_uint}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::vec; use std::str; use std::ff...
(i: u8) -> f32 {i as f32/127.0 - 1.0} pub fn data_to_samples(data: Vec<u8>) -> Vec<complex::Complex<f32>> { data[0..].chunks(2).map(|i| complex::Complex{re:i2f(i[0]), im:i2f(i[1])}).collect() }
i2f
identifier_name
rtlsdr.rs
/* Copyright Ian Daniher, 2013, 2014. Distributed under the terms of the GPLv3. */ #![feature(libc)] #![feature(collections)] #![feature(core)] extern crate num; extern crate libc; use num::complex; use libc::{c_int, c_uint}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::vec; use std::str; use std::ff...
i += 1; } return RtlSdrDev {bx: Arc::new(internal)}; } } pub fn clear_buffer(&self) { unsafe { let success = rtlsdr_reset_buffer(&(*self.bx)); assert_eq!(success, 0); } } pub fn set_frequency(&self, freq: u32) { unsafe { let success = rtlsdr_set_center_freq(&(*self.bx), freq); a...
{ panic!("no available devices"); }
conditional_block
rtlsdr.rs
/* Copyright Ian Daniher, 2013, 2014. Distributed under the terms of the GPLv3. */ #![feature(libc)] #![feature(collections)] #![feature(core)] extern crate num; extern crate libc; use num::complex; use libc::{c_int, c_uint}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::vec; use std::str; use std::ff...
pub fn set_frequency(&self, freq: u32) { unsafe { let success = rtlsdr_set_center_freq(&(*self.bx), freq); assert_eq!(success, 0); } } pub fn set_gain(&self, v: u32) { unsafe { let success = rtlsdr_set_tuner_gain_mode(&(*self.bx), 1); assert_eq!(success, 0); let success = rtlsdr_set_tuner_gain(...
{ unsafe { let success = rtlsdr_reset_buffer(&(*self.bx)); assert_eq!(success, 0); } }
identifier_body
rtlsdr.rs
/* Copyright Ian Daniher, 2013, 2014. Distributed under the terms of the GPLv3. */ #![feature(libc)] #![feature(collections)] #![feature(core)] extern crate num; extern crate libc; use num::complex; use libc::{c_int, c_uint}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::vec; use std::str; use std::ff...
unsafe { let mut i: u32 = 0; let internal: RtlSdrInternal = intrinsics::init(); 'tryDevices: loop { let success = rtlsdr_open(&internal, i); if success == 0 { break 'tryDevices } if i > get_device_count() { panic!("no available devices"); } i += 1; } retur...
pub fn open() -> RtlSdrDev {
random_line_split
node_tree.ts
'use strict'; import destCopy from '../broccoli-dest-copy'; import compileWithTypescript, {INTERNAL_TYPINGS_PATH} from '../broccoli-typescript'; var Funnel = require('broccoli-funnel'); import mergeTrees from '../broccoli-merge-trees'; var path = require('path'); import renderLodashTemplate from '../broccoli-lodash'; ...
function extractPkgJsons(tree, BASE_PACKAGE_JSON) { // Generate shared package.json info var COMMON_PACKAGE_JSON = { version: BASE_PACKAGE_JSON.version, homepage: BASE_PACKAGE_JSON.homepage, bugs: BASE_PACKAGE_JSON.bugs, license: BASE_PACKAGE_JSON.license, repository: BASE_PACKAGE_JSON.reposit...
{ var docs = new Funnel(tree, {include: ['**/*.md', '**/*.png'], exclude: ['**/*.dart.md']}); return stew.rename(docs, 'README.js.md', 'README.md'); }
identifier_body
node_tree.ts
'use strict'; import destCopy from '../broccoli-dest-copy'; import compileWithTypescript, {INTERNAL_TYPINGS_PATH} from '../broccoli-typescript'; var Funnel = require('broccoli-funnel'); import mergeTrees from '../broccoli-merge-trees'; var path = require('path'); import renderLodashTemplate from '../broccoli-lodash'; ...
'angular2/test/common/forms/**', 'angular2/manual_typings/**', 'angular2/typings/**', // we call browser's bootstrap 'angular2/test/router/route_config/route_config_spec.ts', 'angular2/test/router/integration/bootstrap_spec.ts', // we check the public api by importing angular2/angular2 ...
'angular2/test/testing/fake_async_spec.ts', 'angular2/test/testing/testing_public_spec.ts', 'angular2/test/platform/xhr_impl_spec.ts', 'angular2/test/platform/browser/**/*.ts',
random_line_split
node_tree.ts
'use strict'; import destCopy from '../broccoli-dest-copy'; import compileWithTypescript, {INTERNAL_TYPINGS_PATH} from '../broccoli-typescript'; var Funnel = require('broccoli-funnel'); import mergeTrees from '../broccoli-merge-trees'; var path = require('path'); import renderLodashTemplate from '../broccoli-lodash'; ...
(tree) { var docs = new Funnel(tree, {include: ['**/*.md', '**/*.png'], exclude: ['**/*.dart.md']}); return stew.rename(docs, 'README.js.md', 'README.md'); } function extractPkgJsons(tree, BASE_PACKAGE_JSON) { // Generate shared package.json info var COMMON_PACKAGE_JSON = { version: BASE_PACKAGE_JSON.versi...
extractDocs
identifier_name
backports.py
from operator import itemgetter from heapq import nlargest from itertools import repeat, ifilter class Counter(dict): '''Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Coun...
(self, iterable=None, **kwds): '''Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Coun...
__init__
identifier_name
backports.py
from operator import itemgetter from heapq import nlargest from itertools import repeat, ifilter class Counter(dict): '''Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Coun...
>>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem in set(self) | set(other): newcount = self[elem] - other[elem] if newcount > 0: ...
def __sub__(self, other): ''' Subtract count, but keep only results with positive counts.
random_line_split
backports.py
from operator import itemgetter from heapq import nlargest from itertools import repeat, ifilter class Counter(dict):
self.update(iterable, **kwds) def __missing__(self, key): return 0 def most_common(self, n=None): '''List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abracadabra').most_common(...
'''Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Counter('zyzygy') Counter({'y': 3, 'z': 2, 'g': 1}) ''' def __init__(self, iterable=None, **kwds): '''Crea...
identifier_body
backports.py
from operator import itemgetter from heapq import nlargest from itertools import repeat, ifilter class Counter(dict): '''Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Coun...
for elem in ifilter(self.__contains__, other): newcount = _min(self[elem], other[elem]) if newcount > 0: result[elem] = newcount return result
self, other = other, self
conditional_block
server.rs
use chatterbox::*; use output::WavChatterboxOutput; use iron::prelude::*; use iron::status; use staticfile::Static; use mount::Mount; use router::Router; use url::percent_encoding::percent_decode; use iron::headers::{ContentLength, ContentType}; use iron::mime::{Mime, TopLevel, SubLevel}; use iron::modifiers::Header; u...
(backend: Arc<Box<Backend + Send + Sync>>) { let mut router = Router::new(); router .get("/synth/:query", move |req: &mut Request| synth(req, backend.clone())); let mut mount = Mount::new(); mount .mount("/api/", router) .mount("/", Static::new(Path::new("www"))); prin...
run
identifier_name
server.rs
use chatterbox::*; use output::WavChatterboxOutput; use iron::prelude::*; use iron::status; use staticfile::Static; use mount::Mount; use router::Router; use url::percent_encoding::percent_decode; use iron::headers::{ContentLength, ContentType}; use iron::mime::{Mime, TopLevel, SubLevel}; use iron::modifiers::Header; u...
fn synth(req: &mut Request, backend: Arc<Box<Backend + Send + Sync>>) -> IronResult<Response> { let ref query = req.extensions.get::<Router>().unwrap().find("query").unwrap_or(""); let decoded_query = percent_decode(query.as_bytes()).decode_utf8().unwrap(); let mut buf = Cursor::new(Vec::new()); { let mut outp...
random_line_split
server.rs
use chatterbox::*; use output::WavChatterboxOutput; use iron::prelude::*; use iron::status; use staticfile::Static; use mount::Mount; use router::Router; use url::percent_encoding::percent_decode; use iron::headers::{ContentLength, ContentType}; use iron::mime::{Mime, TopLevel, SubLevel}; use iron::modifiers::Header; u...
pub fn run(backend: Arc<Box<Backend + Send + Sync>>) { let mut router = Router::new(); router .get("/synth/:query", move |req: &mut Request| synth(req, backend.clone())); let mut mount = Mount::new(); mount .mount("/api/", router) .mount("/", Static::new(Path::new("www"))...
{ let ref query = req.extensions.get::<Router>().unwrap().find("query").unwrap_or(""); let decoded_query = percent_decode(query.as_bytes()).decode_utf8().unwrap(); let mut buf = Cursor::new(Vec::new()); { let mut output = WavChatterboxOutput::new_for_mem(&mut buf); backend.synth(&decoded_query, &mut output);...
identifier_body
proxyIdentifier.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
<T>(identifier: string): ProxyIdentifier<T> { const result = new ProxyIdentifier<T>(true, identifier); identifiers[result.nid] = result; return result; } export function createExtHostContextProxyIdentifier<T>(identifier: string): ProxyIdentifier<T> { const result = new ProxyIdentifier<T>(false, identifier); ident...
createMainContextProxyIdentifier
identifier_name
proxyIdentifier.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export function createExtHostContextProxyIdentifier<T>(identifier: string): ProxyIdentifier<T> { const result = new ProxyIdentifier<T>(false, identifier); identifiers[result.nid] = result; return result; } export function getStringIdentifierForProxy(nid: number): string { return identifiers[nid].sid; } /** * Ma...
export function createMainContextProxyIdentifier<T>(identifier: string): ProxyIdentifier<T> { const result = new ProxyIdentifier<T>(true, identifier); identifiers[result.nid] = result; return result; }
random_line_split
load_orgs.py
# Copyright 2015, Province of British Columbia # License: https://github.com/bcgov/ckanext-bcgov/blob/master/license import os import sys import json import urllib2 import urllib from base import (create_org, site_url, api_key) def
(id, members): for member in members : data_dict = { 'id' : id, 'username' : member[0], 'role': member[2]} data_string = json.dumps(data_dict) try : request = urllib2.Request(site_url + '/api/3/action/or...
create_org_members
identifier_name
load_orgs.py
# Copyright 2015, Province of British Columbia # License: https://github.com/bcgov/ckanext-bcgov/blob/master/license import os import sys import json import urllib2 import urllib from base import (create_org, site_url, api_key) def create_org_members(id, members): for member in members : data_di...
assert response.code == 200 response_dict = json.loads(response.read()) assert response_dict['success'] is True except Exception: pass
(suborg_raw_name, suborg_title) = suborg_obj.items()[0] suborg_name = suborg_raw_name.replace('_', '-') suborg_data = loaded_orgs[suborg_name] suborg_dict = { 'name' : suborg_name, 'title' : suborg_title, ...
conditional_block
load_orgs.py
# Copyright 2015, Province of British Columbia # License: https://github.com/bcgov/ckanext-bcgov/blob/master/license import os import sys import json import urllib2 import urllib from base import (create_org, site_url, api_key) def create_org_members(id, members): for member in members : data_di...
'name' : suborg_name, 'title' : suborg_title, 'id' : suborg_data['id'] } suborg = create_org(suborg_dict) create_org_members(suborg_data['id'], suborg_data['members']) #Add t...
suborg_data = loaded_orgs[suborg_name] suborg_dict = {
random_line_split
load_orgs.py
# Copyright 2015, Province of British Columbia # License: https://github.com/bcgov/ckanext-bcgov/blob/master/license import os import sys import json import urllib2 import urllib from base import (create_org, site_url, api_key) def create_org_members(id, members):
#Get the json file for organization and sun-organizations (Ministry and branches) orgs_dict = json.load(urllib2.urlopen('http://apps.gov.bc.ca/pub/odc/v2/orgs.json')) suborgs_dict = json.load(urllib2.urlopen('http://apps.gov.bc.ca/pub/odc/v2/orgs/suborgs.json')) org_filename = './data/orgs_list....
for member in members : data_dict = { 'id' : id, 'username' : member[0], 'role': member[2]} data_string = json.dumps(data_dict) try : request = urllib2.Request(site_url + '/api/3/action/organization_member_create...
identifier_body
copies.rs
prevent the overlap let min_block_size = blocks.iter().map(|x| x.stmts.len()).min().unwrap(); if (start_eq + end_eq) > min_block_size { end_eq = min_block_size - start_eq; } Some(BlockEqual { start_eq, end_eq, expr_eq, }) } fn check_for_warn_of_moved_symbol( cx...
Expr<'_>) -> u64 = &|expr| -> u64 { let mut h = SpanlessHash::new(cx); h.hash_expr(expr); h.finish() }; let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool { eq_expr_value(cx, lhs, rhs) }; for (i, j) in search_same(conds, hash, eq) { span_lint_and_note( ...
identifier_body
copies.rs
if both are /// `None` expr_eq: bool, } /// This function can also trigger the `IF_SAME_THEN_ELSE` in which case it'll return `None` to /// abort any further processing and avoid duplicate lint triggers. fn scan_block_for_eq(cx: &LateContext<'tcx>, blocks: &[&Block<'tcx>]) -> Option<BlockEqual> { let mut ...
'tcx> { cx: &'a L
identifier_name
copies.rs
) { let block = blocks[0]; let start_stmts = block.stmts.split_at(start_eq).0; let mut start_walker = UsedValueFinderVisitor::new(cx); for stmt in start_stmts { intravisit::walk_stmt(&mut start_walker, stmt); } emit_branches_sharing_code_lint( cx...
block.stmts.len() - end_stmts].span } .source_callsite(
conditional_block
copies.rs
See [rust-clippy#7452](https://github.com/rust-lang/rust-clippy/issues/7452) /// /// ### Example /// ```ignore /// let foo = if … { /// println!("Hello World"); /// 13 /// } else { /// println!("Hello World"); /// 42 /// }; /// ``` /// /// Could be wr...
(block_eq.start_eq, block_eq.end_eq, block_eq.expr_eq) } else { return; }; // BRANCHES_SHARING_CODE prerequisites if has_conditional_else || (start_eq == 0 && end_eq == 0 && (has_expr && !expr_eq)) { return; } // Only the start is the same if start_eq != 0 && end_eq...
let (start_eq, mut end_eq, expr_eq) = if let Some(block_eq) = scan_block_for_eq(cx, blocks) {
random_line_split
index_en.js
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Wrapper from '../components/wrapper' import Articles from '../components/articles' import Nav from '../components/nav' import Hero from '../components/hero' import Footer from '../components/footer' import D...
() { const meta = { title: 'Wanderlust - A blog about digital nomad lifestyle', description: 'Digital nomads travel the world and work location independent.', canonical: 'https://wanderlust.tech/en/', locale: 'en' } this.props.route.path = '/en/' this.props.route.page.data = { ...
render
identifier_name
index_en.js
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Wrapper from '../components/wrapper' import Articles from '../components/articles' import Nav from '../components/nav' import Hero from '../components/hero' import Footer from '../components/footer' import D...
<Hero route={this.props.route} /> <Wrapper> <Articles route={this.props.route} /> </Wrapper> <Footer /> </div> ) } }
<DocumentMeta {...meta} /> <Nav route={this.props.route} />
random_line_split
index_en.js
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Wrapper from '../components/wrapper' import Articles from '../components/articles' import Nav from '../components/nav' import Hero from '../components/hero' import Footer from '../components/footer' import D...
</Wrapper> <Footer /> </div> ) } }
{ const meta = { title: 'Wanderlust - A blog about digital nomad lifestyle', description: 'Digital nomads travel the world and work location independent.', canonical: 'https://wanderlust.tech/en/', locale: 'en' } this.props.route.path = '/en/' this.props.route.page.data = { ...
identifier_body
jquery.slimscroll.js
/gpl-license.php) licenses. * * Version: 1.0.0 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { wheelStep : 20, width : 'auto', height : '250px', size : '7px', color: '#000', position : 'right', distance : ...
() { // calculate scrollbar height and make sure it is not too small barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight); bar.css({ height: barHeight + 'px' }); } // set up initial height getBarHeight(); f...
getBarHeight
identifier_name
jquery.slimscroll.js
/gpl-license.php) licenses. * * Version: 1.0.0 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { wheelStep : 20, width : 'auto', height : '250px', size : '7px', color: '#000', position : 'right', distance : ...
var e = e || window.event; var delta = 0; if (e.wheelDelta) { delta = -e.wheelDelta/120; } if (e.detail) { delta = e.detail / 3; } // scroll content scrollContent(delta, true); // stop window scroll if (e.preventDefault && !releaseScro...
{ return; }
conditional_block
jquery.slimscroll.js
/gpl-license.php) licenses. * * Version: 1.0.0 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { wheelStep : 20, width : 'auto', height : '250px', size : '7px', color: '#000', position : 'right', distance : ...
// set up initial height getBarHeight(); function showBar() { // recalculate bar height getBarHeight(); clearTimeout(queueHide); // when bar reached top or bottom if (percentScroll == ~~ percentScroll) { //releas...
{ // calculate scrollbar height and make sure it is not too small barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight); bar.css({ height: barHeight + 'px' }); }
identifier_body
jquery.slimscroll.js
/licenses/gpl-license.php) licenses. * * Version: 1.0.0 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { wheelStep : 20, width : 'auto', height : '250px', size : '7px', color: '#000', position : 'right', di...
percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight()); delta = percentScroll * (me[0].scrollHeight - me.outerHeight()); if (isJump) { delta = y; var offsetTop = delta / me[0].scrollHeight * me.outerHeight(); bar.css...
} // calculate actual scroll amount
random_line_split
doctree.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ pub name: Ident, pub id: ast::NodeId, pub attrs: Vec<ast::Attribute>, pub where: Span, } pub fn struct_type_from_def(sd: &ast::StructDef) -> StructType { if sd.ctor_id.is_some() { // We are in a tuple-struct match sd.fields.len() { 0 => Unit, 1 => Newtype,...
Macro
identifier_name
doctree.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub variants: Vec<Variant>, pub generics: ast::Generics, pub attrs: Vec<ast::Attribute>, pub id: NodeId, pub where: Span, pub name: Ident, } pub struct Variant { pub name: Ident, pub attrs: Vec<ast::Attribute>, pub kind: ast::VariantKind, pub id: ast::NodeId, pub vis: ast::V...
pub struct Enum { pub vis: ast::Visibility,
random_line_split
cargo_run.rs
use std::path::Path; use ops::{self, Packages}; use util::{self, CargoResult, CargoError, ProcessError}; use util::errors::CargoErrorKind; use core::Workspace; pub fn run(ws: &Workspace, options: &ops::CompileOptions, args: &[String]) -> CargoResult<Option<ProcessError>> { let config = ws.co...
bail!("a bin target must be available for `cargo run`") } else { // this will be verified in cargo_compile } } if bins.next().is_some() { if !options.filter.is_specific() { bail!("`cargo run` requires that a project only have one \ e...
}); if bins.next().is_none() { if !options.filter.is_specific() {
random_line_split
cargo_run.rs
use std::path::Path; use ops::{self, Packages}; use util::{self, CargoResult, CargoError, ProcessError}; use util::errors::CargoErrorKind; use core::Workspace; pub fn
(ws: &Workspace, options: &ops::CompileOptions, args: &[String]) -> CargoResult<Option<ProcessError>> { let config = ws.config(); let pkg = match options.spec { Packages::All => unreachable!("cargo run supports single package only"), Packages::OptOut(_) => unreachable!("ca...
run
identifier_name
cargo_run.rs
use std::path::Path; use ops::{self, Packages}; use util::{self, CargoResult, CargoError, ProcessError}; use util::errors::CargoErrorKind; use core::Workspace; pub fn run(ws: &Workspace, options: &ops::CompileOptions, args: &[String]) -> CargoResult<Option<ProcessError>>
a.is_bin() } else { options.filter.matches(a) } }); if bins.next().is_none() { if !options.filter.is_specific() { bail!("a bin target must be available for `cargo run`") } else { // this will be verified in cargo_compile } ...
{ let config = ws.config(); let pkg = match options.spec { Packages::All => unreachable!("cargo run supports single package only"), Packages::OptOut(_) => unreachable!("cargo run supports single package only"), Packages::Packages(xs) => match xs.len() { 0 => ws.current()?, ...
identifier_body
table_edit.js
�得標題相關 function getQCTableTitleList(){ $("#titleID").empty(); selectOptionPut("titleID","null","請選擇自檢表"); var typeId = $("#tableType").val(); $.getJSON(QCAPI + "GetEmptyList",{typeId:typeId},function(rs){ console.log(rs); if(rs.Status){ // var optionStr = ''; $.each(rs.Data,function(...
} // 取得標題內容 // GET /api/CheckList/GetTemplate function getQCTableTitleContent(){ var selectTableObj = getUserInput("selectTableItem"); if(selectTableObj.titleID != "null"){ $(".qc-table-content").show(); // 放入標題 var tableTitle = $("#titleID :selected").text(); $("#qc_table_title").html(tableTitl...
callback(data); });
random_line_split
table_edit.js
�得標題相關 function getQCTableTitleList(){ $("#titleID").empty(); selectOptionPut("titleID","null","請選擇自檢表"); var typeId = $("#tableType").val(); $.getJSON(QCAPI + "GetEmptyList",{typeId:typeId},function(rs){ console.log(rs); if(rs.Status){ // var optionStr = ''; $.each(rs.Data,function(...
id = $("#titleID").val(); $("#table-totalContent").find(".qcTableItem").each(function(){ var aplyQCItemChecked = $(this).find(".aplyQCItemSelect").prop("checked"); if(!aplyQCItemChecked){ var itemTitle = $(this).find(".item-title").val(); }else{ var itemTitle = $(this).find(".qcItemSelect ...
; // console.log(object); } function removeItem(object){ object.parent().parent().remove(); } //新增與修改 function saveQCTable(){ var selectTableObj = getUserInput("selectTableItem"); var tableTitle, TitleUid, MyContent=[]; TitleU
identifier_body
table_edit.js
取得標題相關 function getQCTableTitleList(){ $("#titleID").empty(); selectOptionPut("titleID","null","請選擇自檢表"); var typeId = $("#tableType").val(); $.getJSON(QCAPI + "GetEmptyList",{typeId:typeId},function(rs){ console.log(rs); if(rs.Status){ // var optionStr = ''; $.each(rs.Data,function...
束 } function addListContent(object){ var object = object.parent().parent().find(".item-list"); // 取得內匡的樣式 getListStyle(function(pageList){ var pageListObj = $.parseHTML(pageList); $(pageListObj).appendTo(object); }); // console.log(object); } function removeItem(object){ object.parent().pa...
// 外匡樣式結
identifier_name
table_edit.js
取得標題相關 function getQCTableTitleList(){ $("#titleID").empty(); selectOptionPut("titleID","null","請選擇自檢表"); var typeId = $("#tableType").val(); $.getJSON(QCAPI + "GetEmptyList",{typeId:typeId},function(rs){ console.log(rs); if(rs.Status){ // var optionStr = ''; $.each(rs.Data,function...
childContent){ var pageListObj = $.parseHTML(pageList); $(pageListObj).find(".item-list-title").prop("id",childContent.Uid).val(childContent.Name).prop("readonly",true); // $(pageListObj).find(".standard-value").prop("id",childContent.SV_uid).val(childContent.SV_Name); $(pageList...
st){ $.each(DIItem.Data,function(childIndex,
conditional_block
dev.command.ts
import * as yargs from "yargs";
export const devCommand: yargs.CommandModule = { command: "dev", describe: "Start a development server.", builder: { open: { alias: "o", type: "boolean", description: "Automatically open the web browser." }, "update-dlls": { alias: "u"...
import { getEnvironment, getSlimConfig } from "../cli-helpers";
random_line_split
ArchiveDatabaseEx.ts
module nid { /** * സെവൻ സിപ്പ് (Dedicated to my mother tongue :D , http://en.wikipedia.org/wiki/Malayalam) * 7zip Archive Decoder * Version 0.1 * @author Nidin Vinayakan | nidinthb@gmail.com */ import ByteArray = nid.utils.ByteArray; import UInt64 = ctypes.UInt64;
export class ArchiveDatabaseEx extends ArchiveDatabase { public archiveInfo:InArchiveInfo; public packStreamStartPositions:Array<number>;//UInt64 public folderStartPackStreamIndex:Array<number>; public folderStartFileIndex:Array<number>; public fileIndexToFolderIndexMap:Arra...
random_line_split
ArchiveDatabaseEx.ts
module nid { /** * സെവൻ സിപ്പ് (Dedicated to my mother tongue :D , http://en.wikipedia.org/wiki/Malayalam) * 7zip Archive Decoder * Version 0.1 * @author Nidin Vinayakan | nidinthb@gmail.com */ import ByteArray = nid.utils.ByteArray; import UInt64 = ctypes.UInt64; export cla...
FolderPackStreamSize(folderIndex:number, streamIndex:number)//UInt64 { return this.packSizes[this.folderStartPackStreamIndex[folderIndex] + streamIndex]; } public getFilePackSize(fileIndex:number)//UInt64 { var folderIndex:number = this.fileIndexToFolderIndexMap[...
ckStreamIndex:number = this.folderStartPackStreamIndex[folderIndex]; var folder:Folder = this.folders[folderIndex]; var size:number = 0; for (var i = 0; i < folder.packStreams.length; i++){ size += this.packSizes[packStreamIndex + i]; } return ...
identifier_body
ArchiveDatabaseEx.ts
module nid { /** * സെവൻ സിപ്പ് (Dedicated to my mother tongue :D , http://en.wikipedia.org/wiki/Malayalam) * 7zip Archive Decoder * Version 0.1 * @author Nidin Vinayakan | nidinthb@gmail.com */ import ByteArray = nid.utils.ByteArray; import UInt64 = ctypes.UInt64; export cla...
ublic fillStartPos(){ } public fillFolderStartFileIndex(){ } public fill() { this.fillFolderStartPackStream(); this.fillStartPos(); this.fillFolderStartFileIndex(); } public getFolderStreamPos(folderIndex:number, indexInFold...
is.folderStartPackStreamIndex.push(startPos); startPos += this.folders[i].packStreams.length; } } p
conditional_block
ArchiveDatabaseEx.ts
module nid { /** * സെവൻ സിപ്പ് (Dedicated to my mother tongue :D , http://en.wikipedia.org/wiki/Malayalam) * 7zip Archive Decoder * Version 0.1 * @author Nidin Vinayakan | nidinthb@gmail.com */ import ByteArray = nid.utils.ByteArray; import UInt64 = ctypes.UInt64; export cla...
public fill() { this.fillFolderStartPackStream(); this.fillStartPos(); this.fillFolderStartFileIndex(); } public getFolderStreamPos(folderIndex:number, indexInFolder:number):number { return this.archiveInfo.dataStartPosition + ...
ndex(){ }
identifier_name
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { HttpModule } from '@angular/http'; import { SharedModule } from './modules/shared.modu...
{};
AppModule
identifier_name
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { HttpModule } from '@angular/http'; import { SharedModule } from './modules/shared.modu...
import { InviteModule } from './modules/invite/invite.module'; import { LoginModule } from './modules/login/login.module'; import { VersionModule } from './modules/versions/version.module'; import { AppComponent } from './app.component'; import { AuthGuard } from './modules/auth/auth.guard'; import { AuthService } fro...
import { ApplicationModule } from './modules/applications/application.module'; import { AuthModule } from './modules/auth/auth.module'; import { DashboardModule } from './modules/dashboard/dashboard.module'; import { EnvironmentModule } from './modules/environments/environment.module'; import { HelpModule } from './mod...
random_line_split
type.rs
// rustfmt-normalize_comments: true fn types() { let x: [Vec<_>] = []; let y: *mut [SomeType; konst_funk()] = expr(); let z: (// #digits usize, // exp i16) = funk(); let z: (usize /* #digits */, i16 /* exp */) = funk(); } struct F { f: extern "C" fn(x: u8, ... /*...
fn impl_trait_fn_2<E>() -> impl Future<Item = &'a i64, Error = E> {} fn issue_1234() { do_parse!(name: take_while1!(is_token) >> (Header)) }
{}
identifier_body
type.rs
// rustfmt-normalize_comments: true fn types() { let x: [Vec<_>] = []; let y: *mut [SomeType; konst_funk()] = expr(); let z: (// #digits usize, // exp i16) = funk(); let z: (usize /* #digits */, i16 /* exp */) = funk(); } struct F { f: extern "C" fn(x: u8, ... /*...
fn issue_1006(def_id_to_string: for<'a, 'b> unsafe fn(TyCtxt<'b, 'tcx, 'tcx>, DefId) -> String) {} fn impl_trait_fn_1() -> impl Fn(i32) -> Option<u8> {} fn impl_trait_fn_2<E>() -> impl Future<Item = &'a i64, Error = E> {} fn issue_1234() { do_parse!(name: take_while1!(is_token) >> (Header)) }
// comment ... /* comment 2 */), }
random_line_split
type.rs
// rustfmt-normalize_comments: true fn types() { let x: [Vec<_>] = []; let y: *mut [SomeType; konst_funk()] = expr(); let z: (// #digits usize, // exp i16) = funk(); let z: (usize /* #digits */, i16 /* exp */) = funk(); } struct F { f: extern "C" fn(x: u8, ... /*...
<E>() -> impl Future<Item = &'a i64, Error = E> {} fn issue_1234() { do_parse!(name: take_while1!(is_token) >> (Header)) }
impl_trait_fn_2
identifier_name
friendship.py
from riotwatcher import * from time import sleep import logging log = logging.getLogger('log') def getTeamOfSummoner( summonerId, game ): for p in game['participants']: if p['summonerId'] == summonerId: return p['teamId'] def getSummonerIdsOfOpponentTeam( summonerId, game ): teamId = getTeamOfS...
return friendships def computePremades( friendshipRelations ): premades = [] for id in friendshipRelations: group = set(friendshipRelations[id].keys()) group.add(id) if group not in premades: premades.append(group) finPremades = [] for group1 in premades: finGroup = group1 for grou...
for id2 in IdSets: if not id2 in searchedSets: if gameId in IdSets[id2]: if not id2 in friendships[id]: friendships[id][id2] = 1 if not id in friendships[id2]: friendships[id2][id] = 1 friendships[id][id2] += 1 friendships[id2][id] += 1
conditional_block
friendship.py
from riotwatcher import * from time import sleep import logging log = logging.getLogger('log') def getTeamOfSummoner( summonerId, game ): for p in game['participants']: if p['summonerId'] == summonerId: return p['teamId'] def getSummonerIdsOfOpponentTeam( summonerId, game ): teamId = getTeamOfS...
premadesNames.append(groupNames) return premadesNames
random_line_split
friendship.py
from riotwatcher import * from time import sleep import logging log = logging.getLogger('log') def getTeamOfSummoner( summonerId, game ): for p in game['participants']: if p['summonerId'] == summonerId: return p['teamId'] def getSummonerIdsOfOpponentTeam( summonerId, game ): teamId = getTeamOfS...
( summonerName, lolAPIKey, past10 ): w = riotwatcher.RiotWatcher(lolAPIKey, default_region=riotwatcher.EUROPE_WEST) id = w.get_summoner(name=summonerName)['id'] game = w.get_current_game(id) participants = game['participants'] idToParticipantsMap = {} for p in participants: log.info(p['summonerName'].enc...
getPremades
identifier_name
friendship.py
from riotwatcher import * from time import sleep import logging log = logging.getLogger('log') def getTeamOfSummoner( summonerId, game ): for p in game['participants']: if p['summonerId'] == summonerId: return p['teamId'] def getSummonerIdsOfOpponentTeam( summonerId, game ): teamId = getTeamOfS...
sets[id] = s return sets def computeFriendship( IdSets ): searchedSets = set() friendships = {} for id in IdSets: friendships[id] = {} for id in IdSets: searchedSets.add(id) for gameId in IdSets[id]: for id2 in IdSets: if not id2 in searchedSets: if gameId in IdSets[id2]: ...
sets = {} rqs = 0 for id in summonerIds: response = w.get_match_list(id); matchlist = [] if 'matches' in response: matchlist = response['matches'] gamelist = [] if past10: gamelist = w.get_recent_games(id)['games'] rqs += 2 if rqs >= 8: sleep(10) rqs = 0 log.debug('matche...
identifier_body
interfacewebservice.py
# -*- coding: utf-8 -*- from tg.configuration import AppConfig, config from tg import request from pollandsurvey import model from tgext.pyutilservice import Utility import logging log = logging.getLogger(__name__) from tgext.pylogservice import LogDBHandler class InterfaceWebService(object): def __init__(self...
Keyword arguments: voter -- Object Voter """ self.memberUser = model.MemberUser(); try: if voter: user = model.User.by_email_address(voter.email) if user : self.memberUser = model.MemberUser.getByUserIdandVoter(user...
random_line_split
interfacewebservice.py
# -*- coding: utf-8 -*- from tg.configuration import AppConfig, config from tg import request from pollandsurvey import model from tgext.pyutilservice import Utility import logging log = logging.getLogger(__name__) from tgext.pylogservice import LogDBHandler class InterfaceWebService(object): def __init__(self...
del user except Exception as e: log.error("mapVoterUser : %s" %e, extra=extraLog(modules=self.modules)); return self.memberUser;
self.memberUser = model.MemberUser.getByUserIdandVoter(user.user_id, voter.id_voter) if self.memberUser is None: self.memberUser = model.MemberUser(); self.memberUser.user_id = user.user_id self.memberUser.id_voter = voter.id_vo...
conditional_block
interfacewebservice.py
# -*- coding: utf-8 -*- from tg.configuration import AppConfig, config from tg import request from pollandsurvey import model from tgext.pyutilservice import Utility import logging log = logging.getLogger(__name__) from tgext.pylogservice import LogDBHandler class
(object): def __init__(self): self.modules ='INTERFACESERVICE.WEBSERVICE' dh = LogDBHandler( config=config,request=request) log.addHandler(dh) self.utility = Utility() def mapVoterUser(self, voter): """ Check Voter and User in table sur_member_u...
InterfaceWebService
identifier_name
interfacewebservice.py
# -*- coding: utf-8 -*- from tg.configuration import AppConfig, config from tg import request from pollandsurvey import model from tgext.pyutilservice import Utility import logging log = logging.getLogger(__name__) from tgext.pylogservice import LogDBHandler class InterfaceWebService(object): def __init__(self...
log.error("mapVoterUser : %s" %e, extra=extraLog(modules=self.modules)); return self.memberUser;
""" Check Voter and User in table sur_member_user is Empty will create again. if not will pass. Keyword arguments: voter -- Object Voter """ self.memberUser = model.MemberUser(); try: if voter: user = model.User.by_email_address(vote...
identifier_body
safe-base64.ts
/** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ /** * Encode the given string to base64url, with support for all UTF-16 code * points, and '=' padding omitted. * * Built-in btoa throws on non-latin code points (>0xFF), so this function first * converts the input to a bina...
// [3] Extract UTF-8 code points, and re-interpret as UTF-16 code points, // creating a string where all code points are <= 0xFF and hence safe // to base64 encode: {F0 9F 98 83} const percentEscaped = encodeURIComponent(str); const utf8 = percentEscaped.replace(/%([0-9A-F]{2})/g, (_, hex) => ...
// Example: // // [1] Given UTF-16 input: "😃" {D83D DE03} // [2] Convert to UTF-8 escape sequences: "%F0%9F%98%83"
random_line_split
svc-big-query-logging.tests.js
"use strict"; describe("Services: bigQueryLogging", function() { beforeEach(module("risevision.common.components.logging")); var bigQueryLogging, httpResp, forceHttpError, externalLogEventSpy; beforeEach(module(function($provide) { $provide.service("$q", function() {return Q;}); $provide.factory("extern...
else { deferred.resolve(httpResp); } deferred.resolve(httpResp); return deferred.promise; } }; }]); $provide.factory("userState", [function () { return { getUsername: function() {return "user1";}, getSelectedCompanyId: function() {...
{ deferred.reject("Http Error"); }
conditional_block
svc-big-query-logging.tests.js
"use strict";
beforeEach(module(function($provide) { $provide.service("$q", function() {return Q;}); $provide.factory("externalLogging", [function () { return { logEvent: function(eventName, eventDetails, eventValue, userId, companyId) { console.log(eventName, eventDetails, eventValue,user...
describe("Services: bigQueryLogging", function() { beforeEach(module("risevision.common.components.logging")); var bigQueryLogging, httpResp, forceHttpError, externalLogEventSpy;
random_line_split
15.4.4.19-8-b-10.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
} } runTestCase(testcase);
{ function callbackfn(val, idx, obj) { return idx === 1 && typeof val === "undefined"; } var obj = { 2: 2, length: 20 }; Object.defineProperty(obj, "0", { get: function () { delete Object.prototype[1]; return 0; }, ...
identifier_body
15.4.4.19-8-b-10.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
(val, idx, obj) { return idx === 1 && typeof val === "undefined"; } var obj = { 2: 2, length: 20 }; Object.defineProperty(obj, "0", { get: function () { delete Object.prototype[1]; return 0; }, configurable: true ...
callbackfn
identifier_name
15.4.4.19-8-b-10.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
delete Object.prototype[1]; } } runTestCase(testcase);
try { Object.prototype[1] = 1; var testResult = Array.prototype.map.call(obj, callbackfn); return testResult.length === 20 && typeof testResult[1] === "undefined"; } finally {
random_line_split
node_item.py
__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(s...
if crop == 'vegetables': self.vegetables += 2 @property def has_resources(self): num_resources = self.cattle + self.boars + self.sheep + self.grain + self.vegetables return num_resources > 0 def update(self): """ Called every turn """ raise NotImplement...
self.grain += 3
conditional_block
node_item.py
__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(s...
(self): if self.material == 'wood': return 0 elif self.material == 'clay': return 1 elif self.material == 'stone': return 2 def describe(self): return u"\u25A1" # white square (unicode) class StableItem(FieldNodeItem): """ A stable on t...
score
identifier_name
node_item.py
__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(s...
raise ValueError('Invalid material %s not in %s' % (material, self.MATERIAL_CHOICES)) self.material = material def set_material(self, material): if material not in self.MATERIAL_CHOICES: raise ValueError('Invalid material %s not in %s' % (material, self.MATERIAL_CHOICES)) ...
def __init__(self, material='wood'): super(RoomItem, self).__init__() if material not in self.MATERIAL_CHOICES:
random_line_split