file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
gru_cell.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 Timothy Dozat # # 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 ...
(self, inputs, state, scope=None): """""" with tf.variable_scope(scope or type(self).__name__): cell_tm1, hidden_tm1 = tf.split(axis=1, num_or_size_splits=2, value=state) with tf.variable_scope('Gates'): linear = linalg.linear([inputs, hidden_tm1], self.ou...
__call__
identifier_name
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// Most of this is modelled after the expansion of the `quote_expr!` // macro ... let parse_sess = cx.parse_sess(); let cfg = cx.cfg(); // ... except this is where we inject a forged identifier, // and deliberately do not call `cx.parse_tts_with_hygiene` // (because we are testing that th...
{ cx.span_fatal(sp, "forged_ident takes no arguments"); }
conditional_block
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} // See Issue #15750 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(...
if !tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacExpr::new(quote_expr!(cx, 1i))
random_line_split
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: P<Item>) -> P<Item> { P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() }) } fn expand_forged_ident(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResu...
{ // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(); MacExpr::new(quote_expr!(&mut *cx, $expr)) }
identifier_body
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_macro("forged_ident", expand_forged_ident); reg.register_macro("identity", expand_identity); reg.register_syntax_extension( token::intern("into_foo"), Modifier(box expand_into_foo)); } fn expand_make_a_...
plugin_registrar
identifier_name
index.d.ts
// Type definitions for tiny-async-pool 1.0 // Project: https://github.com/rxaviers/async-pool#readme // Definitions by: Karl-Philipp Wulfert <https://github.com/krlwlfrt> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** * This declaration specifies that the function is the exported object from ...
*/ declare function asyncPool<IN, OUT>( poolLimit: number, array: ReadonlyArray<IN>, iteratorFn: (generator: IN) => Promise<OUT> ): Promise<OUT[]>;
* @template OUT Type of the resolves of the promises
random_line_split
shadows.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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 app...
} void shadowsKernel(const uchar4 *in, uchar4 *out) { ushort3 hsv = rgb2hsv(*in); double v = (fastevalPoly(poly,5,hsv.x/4080.)*4080); if (v>4080) v = 4080; hsv.x = (unsigned short) ((v>0)?v:0); *out = hsv2rgb(hsv); }
}
random_line_split
shadows.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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 app...
uchar4 rgb; rgb.r = rr; rgb.g = rg; rgb.b = rb; return rgb; } void prepareShadows(float scale) { double s = (scale>=0)?scale:scale/5; for (int i = 0; i < 5; i++) { poly[i] = fastevalPoly(shadowFilterMap+i*2,2 , s); } } void shadowsKernel(const uchar4 *in, uchar4 *out) { ...
{ ih=(int)ch; is=(int)cs; iv=(int)cv; H = (6*ih)/k2; X = ((iv*is)/k2)*(k2- abs(6*ih- 2*(H>>1)*k2 - k2)) ; // removing additional bits --> unit8 X=( (X+iv*(k1 - is ))/k1 + k3 ) >> ABITS; m=m >> ABITS; // ( chroma + m ) --> cv ; cv=(short)...
conditional_block
main.rs
#![feature(iter_arith)] use std::io::Read; use std::fs::File; fn main()
{ let mut f = File::open("../input.txt").unwrap(); let mut s = String::new(); f.read_to_string(&mut s).ok(); let s = s; let answer: i32 = s.lines().map(|x| { let char_num = x.len() as i32; let mut chars_in_memory = 0; let mut index = 1; let chars = x.chars().collect...
identifier_body
main.rs
#![feature(iter_arith)] use std::io::Read; use std::fs::File; fn
() { let mut f = File::open("../input.txt").unwrap(); let mut s = String::new(); f.read_to_string(&mut s).ok(); let s = s; let answer: i32 = s.lines().map(|x| { let char_num = x.len() as i32; let mut chars_in_memory = 0; let mut index = 1; let chars = x.chars().coll...
main
identifier_name
main.rs
#![feature(iter_arith)] use std::io::Read; use std::fs::File; fn main() { let mut f = File::open("../input.txt").unwrap(); let mut s = String::new(); f.read_to_string(&mut s).ok(); let s = s; let answer: i32 = s.lines().map(|x| { let char_num = x.len() as i32; let mut chars_in_me...
index += 3; chars_in_memory += 1; }, _ => { index += 1; chars_in_memory += 1; } } }, ...
index += 1; match chars[index] { 'x' => {
random_line_split
KarmaCukesListener.js
/** * Karma Listener listening for CucumberJS events * * @author Benjamin Nowack <mail@bnowack.de> * * @param {module:karma} karma - Karma * @returns {KarmaCukesListener} */ var KarmaCukesListener = function(karma) { /** * Initialises the listener */ this.init = function() { this.karma...
else if (failureException && typeof failureException === 'string') { stack = failureException; } karmaResult.step.result.error_message += stack .replace(/^(.*\/(base)\/)/gm, '') // remove leading path noise .replace(/^(.*\/(absolute)\/)/gm, '/') /...
{ stack = failureException.message; }
conditional_block
KarmaCukesListener.js
/** * Karma Listener listening for CucumberJS events * * @author Benjamin Nowack <mail@bnowack.de> * * @param {module:karma} karma - Karma * @returns {KarmaCukesListener} */ var KarmaCukesListener = function(karma) { /** * Initialises the listener */ this.init = function() { this.karma...
* * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event */ this.onBeforeFeature = function(event) { var feature = event.getPayload(); this.feature = { id: feature.getName().toLowerCase().replace(/\s+/g, '-'), uri: feature.getUri().r...
/** * Sets the current feature reference
random_line_split
to_csv_pretty.py
#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from math import ceil, floor, log10, pi from sys import argv, stdout from xml.dom import minidom import bz2 import csv # local imports from my_helper_functions_bare import * def pretty_mean_std(data): return uncertain_number_...
if data["msds_diffusion"][i][0] is None: continue """ stdout_writer.writerow([ "{:.9f}".format(data["packings"][i]), "{:.9f}".format(data["packings"][i]*6.0/pi), data["collisions"][i], data["n_atoms"][i], pretty_mean_std(data["pressures_virial"][i]), prett...
conditional_block
to_csv_pretty.py
#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from math import ceil, floor, log10, pi from sys import argv, stdout from xml.dom import minidom import bz2 import csv # local imports from my_helper_functions_bare import * def
(data): return uncertain_number_string(my_mean(data), my_means_std(data)) varying_parameters = ["pressures_virial", "pressures_collision", "msds_val", "msds_diffusion", "times"] data = { i:[] for i in varying_parameters } data = dict(data.items() + {"packings": [], "collisions": [], "n_atoms": []}.items())...
pretty_mean_std
identifier_name
to_csv_pretty.py
#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from math import ceil, floor, log10, pi from sys import argv, stdout from xml.dom import minidom import bz2 import csv # local imports from my_helper_functions_bare import * def pretty_mean_std(data):
varying_parameters = ["pressures_virial", "pressures_collision", "msds_val", "msds_diffusion", "times"] data = { i:[] for i in varying_parameters } data = dict(data.items() + {"packings": [], "collisions": [], "n_atoms": []}.items()) for input_file in argv[1:]: xmldoc = minidom.parse(bz2.BZ2File(input_fi...
return uncertain_number_string(my_mean(data), my_means_std(data))
identifier_body
to_csv_pretty.py
#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from math import ceil, floor, log10, pi from sys import argv, stdout from xml.dom import minidom import bz2 import csv # local imports from my_helper_functions_bare import * def pretty_mean_std(data): return uncertain_number_...
stdout.write("\multicolumn{1}{c}{$\zeta$}\t\multicolumn{1}{c}{$Z_{MD}$}\t" "\multicolumn{1}{c}{$\Delta Z_{MD}$}\n") for i in xrange(len(data["packings"])): if data["msds_diffusion"][i][0] is None: continue """ stdout_writer.writerow([ "{:.9f}".format(data["packings"][i]), "{...
random_line_split
15.4.4.4-2.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
"var A = new Array(); A.reverse(); A.length", 0, eval("var A = new Array(); A.reverse(); A.length") ); test(); function CheckItems( R, A ) { for ( var i = 0; i < R.length; i++ ) { new TestCase( SECTION, "A["+i+ "]", R[i], A[i] ); } } test(); function Object_1( value ) { th...
new TestCase( SECTION, "delete Array.prototype.reverse.length; Array.prototype.reverse.length", 0, eval("delete Array.prototype.reverse.length; Array.prototype.reverse.length") ); // length of array is 0 new TestCase( SECTION,
random_line_split
15.4.4.4-2.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
function Object_1( value ) { this.array = value.split(","); this.length = this.array.length; for ( var i = 0; i < this.length; i++ ) { this[i] = this.array[i]; } this.reverse = Array.prototype.reverse; this.getClass = Object.prototype.toString; }
{ for ( var i = 0; i < array.length; i++ ) { // print( i+": "+ array[String(i)] ); } }
identifier_body
15.4.4.4-2.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
} function Object_1( value ) { this.array = value.split(","); this.length = this.array.length; for ( var i = 0; i < this.length; i++ ) { this[i] = this.array[i]; } this.reverse = Array.prototype.reverse; this.getClass = Object.prototype.toString; }
{ // print( i+": "+ array[String(i)] ); }
conditional_block
15.4.4.4-2.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
( value ) { this.array = value.split(","); this.length = this.array.length; for ( var i = 0; i < this.length; i++ ) { this[i] = eval(this.array[i]); } this.join = Array.prototype.reverse; this.getClass = Object.prototype.toString; } function Reverse( array ) { var r2 = array.length; var k = 0; var...
Object_1
identifier_name
CreateNetworkDialog.tsx
import { useDispatch } from 'react-redux'; import { translate } from '@waldur/i18n'; import { closeModalDialog } from '@waldur/modal/actions'; import { createLatinNameField, createDescriptionField, } from '@waldur/resource/actions/base'; import { ResourceActionDialog } from '@waldur/resource/actions/ResourceAction...
(formData) => { try { await createNetwork(resource.uuid, formData); dispatch( showSuccess(translate('OpenStack networks has been created.')), ); dispatch(closeModalDialog()); } catch (e) { dispatch( showErrorResponse( ...
async
identifier_name
CreateNetworkDialog.tsx
import { useDispatch } from 'react-redux'; import { translate } from '@waldur/i18n'; import { closeModalDialog } from '@waldur/modal/actions'; import { createLatinNameField, createDescriptionField, } from '@waldur/resource/actions/base'; import { ResourceActionDialog } from '@waldur/resource/actions/ResourceAction...
} /> ); };
{ try { await createNetwork(resource.uuid, formData); dispatch( showSuccess(translate('OpenStack networks has been created.')), ); dispatch(closeModalDialog()); } catch (e) { dispatch( showErrorResponse( e, ...
identifier_body
CreateNetworkDialog.tsx
import { useDispatch } from 'react-redux';
createLatinNameField, createDescriptionField, } from '@waldur/resource/actions/base'; import { ResourceActionDialog } from '@waldur/resource/actions/ResourceActionDialog'; import { showSuccess, showErrorResponse } from '@waldur/store/notify'; import { createNetwork } from '../../api'; export const CreateNetworkDi...
import { translate } from '@waldur/i18n'; import { closeModalDialog } from '@waldur/modal/actions'; import {
random_line_split
loadjs.js
loadjs = (function () { /** * Global dependencies. * @global {Object} document - DOM */ var devnull = function() {}, bundleIdCache = {}, bundleResultCache = {}, bundleCallbackQueue = {}; /** * Subscribe to bundle load event. * @param {string[]} bundleIds - Bundle ids * @param {Function} callbackFn ...
/** * Publish bundle load event. * @param {string} bundleId - Bundle id * @param {string[]} pathsNotFound - List of files not found */ function publish(bundleId, pathsNotFound) { // exit if id isn't defined if (!bundleId) return; var q = bundleCallbackQueue[bundleId]; // cache result bundleResultCach...
{ // listify bundleIds = bundleIds.push ? bundleIds : [bundleIds]; var depsNotFound = [], i = bundleIds.length, numWaiting = i, fn, bundleId, r, q; // define callback function fn = function (bundleId, pathsNotFound) { if (pathsNotFound.length) depsNotFound.push(bundle...
identifier_body
loadjs.js
loadjs = (function () { /** * Global dependencies. * @global {Object} document - DOM */ var devnull = function() {}, bundleIdCache = {}, bundleResultCache = {}, bundleCallbackQueue = {}; /** * Subscribe to bundle load event. * @param {string[]} bundleIds - Bundle ids * @param {Function} callbackFn ...
(paths, callbackFn, args) { // listify paths paths = paths.push ? paths : [paths]; var numWaiting = paths.length, x = numWaiting, pathsNotFound = [], fn, i; // define callback function fn = function(path, result, defaultPrevented) { // handle error if (result == 'e') pathsNot...
loadFiles
identifier_name
loadjs.js
loadjs = (function () { /** * Global dependencies. * @global {Object} document - DOM */ var devnull = function() {}, bundleIdCache = {}, bundleResultCache = {}, bundleCallbackQueue = {}; /** * Subscribe to bundle load event. * @param {string[]} bundleIds - Bundle ids * @param {Function} callbackFn ...
else { // javascript e = doc.createElement('script'); e.src = path; e.async = async === undefined ? true : async; } e.onload = e.onerror = e.onbeforeload = function (ev) { var result = ev.type[0]; // Note: The following code isolates IE using `hideFocus` and treats empty // stylesheet...
{ isCss = true; // css e = doc.createElement('link'); e.rel = 'stylesheet'; e.href = path; }
conditional_block
loadjs.js
loadjs = (function () { /** * Global dependencies. * @global {Object} document - DOM */ var devnull = function() {}, bundleIdCache = {}, bundleResultCache = {}, bundleCallbackQueue = {}; /** * Subscribe to bundle load event. * @param {string[]} bundleIds - Bundle ids * @param {Function} callbackFn ...
*/ loadjs.done = function done(bundleId) { publish(bundleId, []); }; /** * Reset loadjs dependencies statuses */ loadjs.reset = function reset() { bundleIdCache = {}; bundleResultCache = {}; bundleCallbackQueue = {}; }; /** * Determine if bundle has already been defined * @param String} bundleId - The ...
/** * Manually satisfy bundle dependencies. * @param {string} bundleId - The bundle id
random_line_split
torlock.py
#VERSION: 2.1 # AUTHORS: Douman (custparasite@gmx.se) # CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es) from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from re import compile as re_compile from HTMLParser import HTMLParser class torlock(object): url = "https://www.torl...
(HTMLParser): """ Sub-class for parsing results """ def __init__(self, url): HTMLParser.__init__(self) self.url = url self.article_found = False # true when <article> with results is found self.item_found = False self.item_bad = False # set t...
MyHtmlParser
identifier_name
torlock.py
#VERSION: 2.1 # AUTHORS: Douman (custparasite@gmx.se) # CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es) from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from re import compile as re_compile from HTMLParser import HTMLParser class torlock(object): url = "https://www.torl...
elif self.article_found and tag == "a": if "href" in params: link = params["href"] if link.startswith("/torrent"): self.current_item["desc_link"] = "".join((self.url, link)) self.current_item["link"] = ...
self.item_name = self.parser_class.get(params["class"], None) if self.item_name: self.current_item[self.item_name] = ""
conditional_block
torlock.py
#VERSION: 2.1 # AUTHORS: Douman (custparasite@gmx.se) # CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es) from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from re import compile as re_compile from HTMLParser import HTMLParser class torlock(object): url = "https://www.torl...
def handle_data(self, data): if self.item_name: self.current_item[self.item_name] += data def handle_endtag(self, tag): if tag == "article": self.article_found = False elif self.item_name and (tag == "a" or tag == "td"): ...
params = dict(attrs) if self.item_found: if tag == "td": if "class" in params: self.item_name = self.parser_class.get(params["class"], None) if self.item_name: self.current_item[self.item_name] = ...
identifier_body
torlock.py
#VERSION: 2.1 # AUTHORS: Douman (custparasite@gmx.se) # CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es) from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from re import compile as re_compile from HTMLParser import HTMLParser class torlock(object): url = "https://www.torl...
supported_categories = {'all': 'all', 'anime': 'anime', 'software': 'software', 'games': 'game', 'movies': 'movie', 'music': 'music', 'tv': 'televis...
name = "TorLock"
random_line_split
metalib_links.js
$(document).ready(function() { checkMetaLibLinks(); }); function
() { var id = $.map($('.recordId'), function(i) { var id = $(i).attr('id').substr('record'.length); if (id.substr(0, 8) == 'metalib_') { return id; } return null; }); if (id.length) { // set the spinner going $('.metalib_link').addClass('ajax_fulltext...
checkMetaLibLinks
identifier_name
metalib_links.js
$(document).ready(function() { checkMetaLibLinks();
var id = $.map($('.recordId'), function(i) { var id = $(i).attr('id').substr('record'.length); if (id.substr(0, 8) == 'metalib_') { return id; } return null; }); if (id.length) { // set the spinner going $('.metalib_link').addClass('ajax_fulltext_avai...
}); function checkMetaLibLinks() {
random_line_split
metalib_links.js
$(document).ready(function() { checkMetaLibLinks(); }); function checkMetaLibLinks()
{ var id = $.map($('.recordId'), function(i) { var id = $(i).attr('id').substr('record'.length); if (id.substr(0, 8) == 'metalib_') { return id; } return null; }); if (id.length) { // set the spinner going $('.metalib_link').addClass('ajax_fulltext_av...
identifier_body
metalib_links.js
$(document).ready(function() { checkMetaLibLinks(); }); function checkMetaLibLinks() { var id = $.map($('.recordId'), function(i) { var id = $(i).attr('id').substr('record'.length); if (id.substr(0, 8) == 'metalib_') { return id; } return null; }); if (id.len...
else { $('#metalib_link_na_' + safeId).show(); } }); }).error(function() { $('.metalib_link').removeClass('ajax_fulltext_availability'); $('.metalib_link').text("MetaLib link check failed."); }); } }
{ $('#metalib_link_' + safeId).show(); }
conditional_block
ziv_service.py
from requests import post import io import base64 class ZivService(object):
def __init__(self, cnc_url, user=None, password=None, sync=True): self.cnc_url = cnc_url self.sync = sync self.auth = None if user and password: self.auth = (user,password) def send_cycle(self, filename, cycle_filedata): """Send a cycle file to the concentrator s...
identifier_body
ziv_service.py
from requests import post import io import base64 class ZivService(object): def __init__(self, cnc_url, user=None, password=None, sync=True): self.cnc_url = cnc_url self.sync = sync self.auth = None if user and password: self.auth = (user,password) def
(self, filename, cycle_filedata): """Send a cycle file to the concentrator service Keyword arguments: filename -- the name of our file (doesn't matter) cycle_filedata -- the file to send, encoded as a base64 string """ filecontent = base64.b64decode(cycle_filedata) ...
send_cycle
identifier_name
ziv_service.py
from requests import post
import base64 class ZivService(object): def __init__(self, cnc_url, user=None, password=None, sync=True): self.cnc_url = cnc_url self.sync = sync self.auth = None if user and password: self.auth = (user,password) def send_cycle(self, filename, cycle_filedata): ...
import io
random_line_split
ziv_service.py
from requests import post import io import base64 class ZivService(object): def __init__(self, cnc_url, user=None, password=None, sync=True): self.cnc_url = cnc_url self.sync = sync self.auth = None if user and password: self.auth = (user,password) def send_cycle(se...
else: result = post(url, files={'file': (filename, filecontent)}) return result
result = post(url, files={'file': (filename, filecontent)}, auth=self.auth)
conditional_block
admin.component.ts
import { Observable } from 'rxjs/Rx'; import { Component } from '@angular/core'; import { AuthService } from '../authentication'; import { Router } from '@angular/router'; import { MettAppointmentModel, MettOrder, AppointmentService } from './../mett-appointment'; @Component({ selector: 'app-admin', templateUrl: '...
{ public appointments: Observable<any[]>; public selectedItem: MettOrder[]; constructor(private appointmentService: AppointmentService, private authService: AuthService, private router: Router){ this.appointments = this.appointmentService.appointments.map((item: MettAppointmentModel[]) => { let mapped...
AdminComponent
identifier_name
admin.component.ts
import { Observable } from 'rxjs/Rx'; import { Component } from '@angular/core'; import { AuthService } from '../authentication'; import { Router } from '@angular/router'; import { MettAppointmentModel, MettOrder, AppointmentService } from './../mett-appointment'; @Component({ selector: 'app-admin', templateUrl: '...
constructor(private appointmentService: AppointmentService, private authService: AuthService, private router: Router){ this.appointments = this.appointmentService.appointments.map((item: MettAppointmentModel[]) => { let mapped = item.map(x => { return { Date: x.Date, CreatedBy: x...
export class AdminComponent{ public appointments: Observable<any[]>; public selectedItem: MettOrder[];
random_line_split
opendata.footer.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; export class
extends Component { render() { return ( <footer className="opendata-footer footer"> <nav className="navbar bottom navbar-expand-lg navbar-dark bg-primary"> <div> <span style={{ color: "#fff" }}>{this.props.text}:</span> ...
Footer
identifier_name
opendata.footer.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; export class Footer extends Component { render() { return ( <footer className="opendata-footer footer"> <nav className="navbar bottom navbar-expand-lg navbar-dark bg-primary"> <d...
} export default connect( state => ({ text: state.locale.translation.footer }) )(Footer)
</footer> ); }
random_line_split
header.component.ts
import { Component, AfterViewInit, ElementRef } from '@angular/core'; declare const fabric: any; /** * This class represents the header component. */ @Component({ moduleId: module.id, selector: 'header', templateUrl: 'header.component.html', styleUrls: ['header.component.css'] }) export class HeaderComponen...
}
let contextualMenu = new fabric['ContextualMenu'](ContextualMenuElement, ButtonElement); }
random_line_split
header.component.ts
import { Component, AfterViewInit, ElementRef } from '@angular/core'; declare const fabric: any; /** * This class represents the header component. */ @Component({ moduleId: module.id, selector: 'header', templateUrl: 'header.component.html', styleUrls: ['header.component.css'] }) export class HeaderComponen...
ngAfterViewInit() { // let CommandBarElements = this.element.nativeElement.querySelectorAll(".ms-CommandBar"); // for (var i = 0; i < CommandBarElements.length; i++) { // new fabric['CommandBar'](CommandBarElements[i]); // } let ContextualMenuElement = this.element.nativeElement.querySelector...
{ }
identifier_body
header.component.ts
import { Component, AfterViewInit, ElementRef } from '@angular/core'; declare const fabric: any; /** * This class represents the header component. */ @Component({ moduleId: module.id, selector: 'header', templateUrl: 'header.component.html', styleUrls: ['header.component.css'] }) export class
implements AfterViewInit { constructor(private element: ElementRef) { } ngAfterViewInit() { // let CommandBarElements = this.element.nativeElement.querySelectorAll(".ms-CommandBar"); // for (var i = 0; i < CommandBarElements.length; i++) { // new fabric['CommandBar'](CommandBarElements[i]); /...
HeaderComponent
identifier_name
main_waveform_20170517.py
# coding = utf-8 # import modules import os import matplotlib.pyplot as plt import numpy as np import scipy as sp import my_config path = my_config.ROOT_DIR # Please create your config file file = my_config.FILE # Please create your config file # get time series for ch0 and plot import wave def t...
fs, t, y = time_series(os.path.join(path, file), i_ch = 0) plt.figure(1) plt.plot(t, y) plt.title('Time series (Fs = {})'.format(fs)) plt.xlabel('Time [s]') plt.ylabel('Signal') plt.grid() # detrend and plot from scipy.signal import detrend y_detrend = detrend(y) plt.figure(2) plt.plot(t, y_detrend) plt.title('T...
with wave.open(file,'r') as wav_file: # Extract Raw Audio from Wav File signal = wav_file.readframes(-1) signal = np.fromstring(signal, 'Int16') # Split the data into channels channels = [[] for channel in range(wav_file.getnchannels())] for index, datum in enumerate(si...
identifier_body
main_waveform_20170517.py
# coding = utf-8 # import modules import os import matplotlib.pyplot as plt import numpy as np import scipy as sp import my_config path = my_config.ROOT_DIR # Please create your config file file = my_config.FILE # Please create your config file # get time series for ch0 and plot import wave def
(file, i_ch = 0): with wave.open(file,'r') as wav_file: # Extract Raw Audio from Wav File signal = wav_file.readframes(-1) signal = np.fromstring(signal, 'Int16') # Split the data into channels channels = [[] for channel in range(wav_file.getnchannels())] for index,...
time_series
identifier_name
main_waveform_20170517.py
# coding = utf-8 # import modules import os import matplotlib.pyplot as plt import numpy as np import scipy as sp import my_config path = my_config.ROOT_DIR # Please create your config file file = my_config.FILE # Please create your config file # get time series for ch0 and plot import wave def t...
#Get time from indices fs = wav_file.getframerate() Time = np.linspace(0, len(signal)/len(channels)/fs, num=len(signal)/len(channels)) # return return fs, Time, channels[i_ch] fs, t, y = time_series(os.path.join(path, file), i_ch = 0) plt.figure(1) plt.plot(t, y) plt.title(...
channels[index%len(channels)].append(datum)
conditional_block
main_waveform_20170517.py
# coding = utf-8 # import modules import os import matplotlib.pyplot as plt import numpy as np import scipy as sp import my_config path = my_config.ROOT_DIR # Please create your config file file = my_config.FILE # Please create your config file # get time series for ch0 and plot import wave def t...
# get fft and plot T = 1.0 / fs # time interval n_sample = len(y_filtered) freq = np.linspace(0.0, 1.0/(2.0*T), n_sample//2) yf = sp.fft(y_filtered) plt.figure(5) plt.plot(freq, 2.0/n_sample * np.abs(yf[0:n_sample//2])) plt.title('FFT') plt.xlabel('Freq. [Hz]') plt.ylabel('Fourier Coef.') plt.grid() # get psd and p...
random_line_split
PlatformDropbox.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_IN...
}; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'PlatformDropbox'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']), resp...
{ const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-platform-dropbox`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}...
identifier_body
PlatformDropbox.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_IN...
() { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-platform-dropbox`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_R...
render
identifier_name
PlatformDropbox.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_IN...
a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
random_line_split
spark_webservice_demo.py
# Copyright 2015 David Wang. All rights reserved. # Use of this source code is governed by MIT license. # Please see LICENSE file # WebSpark # Spark web service demo # version 0.2 # use REPL or define sc SparkContext import urllib2, urllib import math import time import traceback # Spark Web Application demo wi...
(url): rawdata = range(1000, 20000, 1100) data = sc.parallelize(rawdata) above=data.map(lambda x: (x, firstprimeabove(x))).collect() primelist=[element%x for x in above] response = template % ' '.join(primelist) return response def parserequest(rawrequest): lines = rawrequest.split('\n') if len(lines)<4: pr...
demo
identifier_name
spark_webservice_demo.py
# Copyright 2015 David Wang. All rights reserved. # Use of this source code is governed by MIT license. # Please see LICENSE file # WebSpark # Spark web service demo # version 0.2 # use REPL or define sc SparkContext import urllib2, urllib import math import time import traceback # Spark Web Application demo wi...
else: name = lines[0] url = lines[1] remoteaddr = lines[2] header = lines[3:] return name, url, remoteaddr, header st ='' # publish web service with WebSpark while True: try: url = RegisterURL + urllib.urlencode({'name': servicename}) conn = urllib2.urlopen(url) data = conn.read() conn.close() ...
print 'incorrect WebSpark request'
conditional_block
spark_webservice_demo.py
# Copyright 2015 David Wang. All rights reserved. # Use of this source code is governed by MIT license. # Please see LICENSE file # WebSpark # Spark web service demo # version 0.2 # use REPL or define sc SparkContext import urllib2, urllib import math import time import traceback # Spark Web Application demo wi...
def firstprimeabove(num): i=num+1 while True: if slow_isprime(i): return i i+=1 servicename = 'demo' # Spark Web Application demo def demo(url): rawdata = range(1000, 20000, 1100) data = sc.parallelize(rawdata) above=data.map(lambda x: (x, firstprimeabove(x))).collect() primelist=[element%x for x i...
if num<2: return False for i in range(2, int(math.sqrt(num))+1): if num%i==0: return False return True
identifier_body
spark_webservice_demo.py
# Copyright 2015 David Wang. All rights reserved. # Use of this source code is governed by MIT license. # Please see LICENSE file # WebSpark # Spark web service demo # version 0.2 # use REPL or define sc SparkContext import urllib2, urllib import math import time import traceback
ServerAddr="http://<enter WebSpark IP address here>:8001" RegisterURL=ServerAddr + "/addapi?" RespondURL=ServerAddr + "/respond?" errwaitseconds = 3 element = '<li class="list-group-item">first prime above %d is %d</li>' with open('template.html') as f: template = f.read() def slow_isprime(num): if num<2: retu...
# Spark Web Application demo with parallel processing # see demoservice function
random_line_split
habhub.view.ts
namespace $.$$ {
export class $mol_app_habhub extends $.$mol_app_habhub { uriSource(){ return 'https://api.github.com/search/issues?q=label:HabHub+is:open&sort=reactions' } gists() { return $mol_github_search_issues.item( this.uriSource() ).items() } gists_dict() { const dict = {} as { [ key : string ] : ...
random_line_split
habhub.view.ts
namespace $.$$ { export class $mol_app_habhub extends $.$mol_app_habhub { uriSource(){ return 'https://api.github.com/search/issues?q=label:HabHub+is:open&sort=reactions' } gists() { return $mol_github_search_issues.item( this.uriSource() ).items() }
() { const dict = {} as { [ key : string ] : $mol_github_issue } for( let gist of this.gists() ) { dict[ gist.uri() ] = gist } return dict } gist( id : number ) { return this.gists_dict()[ id ] } gist_current() { return $mol_maybe( $mol_state_arg.value( 'gist' ) ).map( uri => this.gi...
gists_dict
identifier_name
data.py
# ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
def h5_cost_data(filename, epoch_axis=True): """ Read cost data from hdf5 file. Generate x axis data for each cost line. Arguments: filename (str): Filename with hdf5 cost data epoch_axis (bool): whether to render epoch or minibatch as the integer step in the x axis Returns: ...
""" Helper function to build x axis for points captured per epoch. Arguments: points (int): how many data points need a corresponding x axis points epoch_freq (int): are points once an epoch or once every n epochs? minibatch_markers (int array): cumulative number of minibatches complete...
identifier_body
data.py
# ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
last_e = e else: x = minibatch_markers[(epoch_freq - 1)::epoch_freq] - 1 return x def h5_cost_data(filename, epoch_axis=True): """ Read cost data from hdf5 file. Generate x axis data for each cost line. Arguments: filename (str): Filename with hdf5 cost data ...
x[e_idx // epoch_freq] = e_idx + ((e_minibatches - 1) // e_minibatches)
conditional_block
data.py
# ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
(filename, epoch_axis=True): """ Read histogram data from hdf5 file. Generate x axis data for each hist line. Arguments: filename (str): Filename with hdf5 cost data epoch_axis (bool): whether to render epoch or minibatch as the integer step in the x axis Returns: list of tuple...
h5_hist_data
identifier_name
data.py
# ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
x = create_minibatch_x(total_minibatches, minibatch_markers, epoch_axis) else: raise TypeError('Unsupported data format for h5_cost_data') ret.append((name, x, y)) return ret def h5_hist_data(filename, epoch_axis=True): """ Read histogram data fro...
assert len(y) == total_minibatches
random_line_split
mastakilla_spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from lyricwiki.items import LyricWikiItem class LyricWikiSpider(CrawlSpider):
name = "mastakilla" #CHANGE NAME allowed_domains = ["lyrics.wikia.com"] start_urls = [ "http://lyrics.wikia.com/Masta_Killa", #CHANGE URL ] rules = ( #CHANGE REGEX Rule(SgmlLinkExtractor(allow...
identifier_body
mastakilla_spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from lyricwiki.items import LyricWikiItem class LyricWikiSpider(CrawlSpider): name = "mastakilla" #CHANGE NAME ...
(self, response): sel = Selector(response) info = sel.xpath('//div[@class="mw-content-ltr"]') item = LyricWikiItem() item['title'] = sel.xpath('//header[@id="WikiaPageHeader"]/h1/text()').extract() item['artist'] = info.xpath('b/a/text()').extract() item['album'] = ...
parse_item
identifier_name
mastakilla_spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from lyricwiki.items import LyricWikiItem class LyricWikiSpider(CrawlSpider): name = "mastakilla" #CHANGE NAME allowed_domains = ["lyrics.wikia.com"] start_urls = [ "http://lyrics.wikia.com/Masta_Killa", #CHANGE URL ] rules = ( ...
from scrapy.selector import Selector
random_line_split
mount.ts
import { DEBUG } from '@glimmer/env'; import { ComponentCapabilities } from '@glimmer/interfaces'; import { CONSTANT_TAG, Tag, VersionedPathReference } from '@glimmer/reference'; import { ComponentDefinition, Invocation, WithDynamicLayout } from '@glimmer/runtime'; import { Destroyable, Opaque, Option } from '@glimmer/...
return bucket; } getSelf({ self }: EngineState): VersionedPathReference<Opaque> { return self; } getTag(state: EngineState | EngineWithModelState): Tag { return state.tag; } getDestructor({ engine }: EngineState): Option<Destroyable> { return engine; } didRenderLayout(): void { ...
{ controller = controllerFactory.create(); self = new RootReference(controller); tag = CONSTANT_TAG; bucket = { engine, controller, self, tag }; }
conditional_block
mount.ts
import { DEBUG } from '@glimmer/env'; import { ComponentCapabilities } from '@glimmer/interfaces'; import { CONSTANT_TAG, Tag, VersionedPathReference } from '@glimmer/reference'; import { ComponentDefinition, Invocation, WithDynamicLayout } from '@glimmer/runtime'; import { Destroyable, Opaque, Option } from '@glimmer/...
didRenderLayout(): void { if (DEBUG) { this.debugStack.pop(); } } update(bucket: EngineWithModelState): void { if (EMBER_ENGINES_MOUNT_PARAMS) { let { controller, modelRef, modelRev } = bucket; if (!modelRef.tag.validate(modelRev!)) { let model = modelRef.value(); ...
{ return engine; }
identifier_body
mount.ts
import { DEBUG } from '@glimmer/env'; import { ComponentCapabilities } from '@glimmer/interfaces'; import { CONSTANT_TAG, Tag, VersionedPathReference } from '@glimmer/reference'; import { ComponentDefinition, Invocation, WithDynamicLayout } from '@glimmer/runtime'; import { Destroyable, Opaque, Option } from '@glimmer/...
(state: EngineState, _: RuntimeResolver): Invocation { let template = state.engine.lookup('template:application') as OwnedTemplate; let layout = template.asLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable, }; } getCapabilities(): ComponentCapabilities { r...
getDynamicLayout
identifier_name
mount.ts
import { DEBUG } from '@glimmer/env'; import { ComponentCapabilities } from '@glimmer/interfaces'; import { CONSTANT_TAG, Tag, VersionedPathReference } from '@glimmer/reference'; import { ComponentDefinition, Invocation, WithDynamicLayout } from '@glimmer/runtime'; import { Destroyable, Opaque, Option } from '@glimmer/...
let template = state.engine.lookup('template:application') as OwnedTemplate; let layout = template.asLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable, }; } getCapabilities(): ComponentCapabilities { return CAPABILITIES; } create(environment: Environm...
extends AbstractManager<EngineState | EngineWithModelState, EngineDefinitionState> implements WithDynamicLayout<EngineState | EngineWithModelState, OwnedTemplateMeta, RuntimeResolver> { getDynamicLayout(state: EngineState, _: RuntimeResolver): Invocation {
random_line_split
de.js
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * German language. */ /**#@+ @type String @example */ /** * Contains the dic...
editorHelp: 'Drücken Sie ALT 0 für Hilfe', browseServer: 'Server durchsuchen', url: 'URL', protocol: 'Protokoll', upload: 'Hochladen', uploadSubmit: 'Zum Server senden', image: 'Bild', flash: 'Flash', form: 'Formular', checkbox: 'Checkbox', radio: 'Radiobutton', textField: 'Textfeld einzeilig',...
common: { // Screenreader titles. Please note that screenreaders are not always capable // of reading non-English words. So be careful while translating it.
random_line_split
info.service.ts
import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import {Observable} from "rxjs/Observable"; import {Info} from "../model/info"; import {BaseService} from "./base.service";
isLoginSuccess: boolean = false; redirectUrl: string; constructor(private http:Http) { super() } getInfo(): Observable<Info>{ return this.http.get(Constants.BASE_URL+"/info") .map(res => { console.log('getInfo: ', res.text()); return res....
import {Constants} from "../constants"; @Injectable() export class InfoService extends BaseService{
random_line_split
info.service.ts
import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import {Observable} from "rxjs/Observable"; import {Info} from "../model/info"; import {BaseService} from "./base.service"; import {Constants} from "../constants"; @Injectable() export class InfoService extends BaseService{ isLoginSucce...
}
{ return this.http.get(Constants.BASE_URL+"/logout") .map(res => { console.log('logout: ', res.status); this.isLoginSuccess = false; }) .catch(this.handleError); }
identifier_body
info.service.ts
import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import {Observable} from "rxjs/Observable"; import {Info} from "../model/info"; import {BaseService} from "./base.service"; import {Constants} from "../constants"; @Injectable() export class InfoService extends BaseService{ isLoginSucce...
(info: Info): Observable<boolean>{ return this.http.post(Constants.BASE_URL+'/login.action', JSON.stringify(info), {headers: Constants.HEADERS_JSON}) .map( res => { console.log('doLogin: ', res.text()); if (res.text()=='true') this.isLoginSuccess = tru...
doLogin
identifier_name
MagicWordManagerAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from otp.ai.MagicWordGlobal import * from direct.distributed.PyDatagram import PyDatagram from direct.distributed.MsgTypes import * class MagicWordManagerAI(DistributedObjectAI): notify = Direc...
return response = spellbook.process(invoker, target, word) if response: self.sendUpdateToAvatarId(invokerId, 'sendMagicWordResponse', [response]) self.air.writeServerEvent('magic-word', invokerId, invoker.getAdminAccess(), ...
target = self.air.doId2do.get(targetId) if not target: self.sendUpdateToAvatarId(invokerId, 'sendMagicWordResponse', ['missing target'])
random_line_split
MagicWordManagerAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from otp.ai.MagicWordGlobal import * from direct.distributed.PyDatagram import PyDatagram from direct.distributed.MsgTypes import * class
(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory("MagicWordManagerAI") def sendMagicWord(self, word, targetId): invokerId = self.air.getAvatarIdFromSender() invoker = self.air.doId2do.get(invokerId) if not 'DistributedToonAI' in str(self.air.doId2do.get(targe...
MagicWordManagerAI
identifier_name
MagicWordManagerAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from otp.ai.MagicWordGlobal import * from direct.distributed.PyDatagram import PyDatagram from direct.distributed.MsgTypes import * class MagicWordManagerAI(DistributedObjectAI): notify = Direc...
if invoker.getAdminAccess() < MINIMUM_MAGICWORD_ACCESS: self.air.writeServerEvent('suspicious', invokerId, 'Attempted to issue magic word: %s' % word) dg = PyDatagram() dg.addServerHeader(self.GetPuppetConnectionChannel(invokerId), self.air.ourChannel, CLIENTAGENT_EJECT) ...
self.sendUpdateToAvatarId(invokerId, 'sendMagicWordResponse', ['missing invoker']) return
conditional_block
MagicWordManagerAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from otp.ai.MagicWordGlobal import * from direct.distributed.PyDatagram import PyDatagram from direct.distributed.MsgTypes import * class MagicWordManagerAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory("MagicWordManagerAI") def sendMagicWord(self, word, targetId): invokerId = self.air.getAvatarIdFromSender() invoker = self.air.doId2do.get(invokerId) if not 'DistributedToonAI' in str(self.air.doId2do.get(targetId)): self.sen...
identifier_body
test_combiner.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
# # Contributor(s): # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable inste...
# The Initial Developer of the Original Code is # Mozilla. # Portions created by the Initial Developer are Copyright (C) 2009 # the Initial Developer. All Rights Reserved.
random_line_split
test_combiner.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
p = path(__file__).dirname() / "noindexapp" output = StringIO() plugin = Plugin("noindexapp", p, dict(name="testing")) combine_files(output, StringIO(), plugin, p) combined = output.getvalue() print combined assert 'tiki.module("noindexapp:index"' in combined assert 'tiki.main' not in combin...
identifier_body
test_combiner.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
(): p = path(__file__).dirname() / "noindexapp" output = StringIO() plugin = Plugin("noindexapp", p, dict(name="testing")) combine_files(output, StringIO(), plugin, p) combined = output.getvalue() print combined assert 'tiki.module("noindexapp:index"' in combined assert 'tiki.main' not i...
test_package_index_generation
identifier_name
item.ts
import { Map } from 'immutable'; import { ItemException } from '../exceptions/index'; // This can be removed when Symbol is known to TypeScript declare const Symbol; /** * Interfaces */ export interface ItemData { [x: string]: any; } export interface ItemInterface { create(data: ItemData): this; fill...
return values.length === 1 ? values[0] : values; } /** * Gets all values mapping back to array of keys. * * @param keys * @returns {Array<any>} */ protected getFromArray(keys : string[]) : any[] { return this.data.filter((val, key) => keys.includes(key)).toArray()...
{ return; }
conditional_block
item.ts
import { Map } from 'immutable'; import { ItemException } from '../exceptions/index'; // This can be removed when Symbol is known to TypeScript declare const Symbol; /** * Interfaces */ export interface ItemData { [x: string]: any; } export interface ItemInterface { create(data: ItemData): this; fill...
(data : ItemData) : this { this.data = this.data.merge(data); return this; } /** * Sets the given key / value pair in this.data. Will overwrite any existing value for key. * * @param key * @param value * @returns {Item} */ set(key : string, value : any) { ...
fill
identifier_name
item.ts
import { Map } from 'immutable'; import { ItemException } from '../exceptions/index'; // This can be removed when Symbol is known to TypeScript declare const Symbol; /** * Interfaces */ export interface ItemData { [x: string]: any; } export interface ItemInterface { create(data: ItemData): this; fill...
* * @param key * @param value * @returns {Item} */ set(key : string, value : any) { this.data = this.data.set(key, value); return this; } /** * Return single or array of values corresponding to string / array of keys provided. * * @param keys * ...
} /** * Sets the given key / value pair in this.data. Will overwrite any existing value for key.
random_line_split
item.ts
import { Map } from 'immutable'; import { ItemException } from '../exceptions/index'; // This can be removed when Symbol is known to TypeScript declare const Symbol; /** * Interfaces */ export interface ItemData { [x: string]: any; } export interface ItemInterface { create(data: ItemData): this; fill...
/** * Returns unique symbol for Item. * * @returns {symbol} */ uid() : symbol { return this.symbol; } /** * Returns true if provided symbol equals known symbol for Item. * * @param symbol * @returns {boolean} */ isUid(symbol : symbol) : boolean...
{ return this.data.get(key) === value; }
identifier_body
convert_seconds_to_compound_duration.rs
// http://rosettacode.org/wiki/Convert_seconds_to_compound_duration fn seconds_to_compound(secs: u32) -> String { let part = |comps: &mut String, c: &str, one: u32, secs: &mut u32| { if *secs >= one
}; let mut secs = secs; let mut comps = String::new(); part(&mut comps, " wk", 60 * 60 * 24 * 7, &mut secs); part(&mut comps, " d", 60 * 60 * 24, &mut secs); part(&mut comps, " hr", 60 * 60, &mut secs); part(&mut comps, " min", 60, &mut secs); part(&mut comps, " sec", 1, &mut secs); ...
{ let div = *secs / one; comps.push_str(&(div.to_string() + c)); *secs -= one * div; if *secs > 0 { comps.push_str(", "); } }
conditional_block
convert_seconds_to_compound_duration.rs
// http://rosettacode.org/wiki/Convert_seconds_to_compound_duration fn seconds_to_compound(secs: u32) -> String { let part = |comps: &mut String, c: &str, one: u32, secs: &mut u32| { if *secs >= one { let div = *secs / one; comps.push_str(&(div.to_string() + c)); *secs -...
{ println!("7,259 seconds = {}", seconds_to_compound(7259)); println!("86,400 seconds = {}", seconds_to_compound(86400)); println!("6,000,000 seconds = {}", seconds_to_compound(6000000)); }
identifier_body
convert_seconds_to_compound_duration.rs
// http://rosettacode.org/wiki/Convert_seconds_to_compound_duration fn seconds_to_compound(secs: u32) -> String { let part = |comps: &mut String, c: &str, one: u32, secs: &mut u32| { if *secs >= one { let div = *secs / one; comps.push_str(&(div.to_string() + c)); *secs -...
() { assert_eq!(seconds_to_compound(7259), "2 hr, 59 sec"); } #[test] fn one_day() { assert_eq!(seconds_to_compound(86400), "1 d"); } #[test] fn six_million_seconds() { assert_eq!(seconds_to_compound(6000000), "9 wk, 6 d, 10 hr, 40 min"); } fn main() { println!("7,259 seconds = {}", seconds_to_compou...
hours_and_seconds
identifier_name
convert_seconds_to_compound_duration.rs
// http://rosettacode.org/wiki/Convert_seconds_to_compound_duration fn seconds_to_compound(secs: u32) -> String { let part = |comps: &mut String, c: &str, one: u32, secs: &mut u32| {
let div = *secs / one; comps.push_str(&(div.to_string() + c)); *secs -= one * div; if *secs > 0 { comps.push_str(", "); } } }; let mut secs = secs; let mut comps = String::new(); part(&mut comps, " wk", 60 * 60 * 24 * 7...
if *secs >= one {
random_line_split
pm.rs
use core::marker::PhantomData; use volatile::*; #[repr(C, packed)] pub struct PowerManager { pub control: ReadWrite<u8>, // Offset: 0x00 (R/W 8) Control pub sleep: ReadWrite<u8>, // Offset: 0x01 (R/W 8) Sleep Mode pub external_control: ReadWrite<u8>, // Offset: 0x02 (R/W 8) External ...
} }
random_line_split
pm.rs
use core::marker::PhantomData; use volatile::*; #[repr(C, packed)] pub struct
{ pub control: ReadWrite<u8>, // Offset: 0x00 (R/W 8) Control pub sleep: ReadWrite<u8>, // Offset: 0x01 (R/W 8) Sleep Mode pub external_control: ReadWrite<u8>, // Offset: 0x02 (R/W 8) External Reset Controller reserved_1: [u8; 5], pub cpu_select: ReadWrite<u8>, // Offse...
PowerManager
identifier_name
pm.rs
use core::marker::PhantomData; use volatile::*; #[repr(C, packed)] pub struct PowerManager { pub control: ReadWrite<u8>, // Offset: 0x00 (R/W 8) Control pub sleep: ReadWrite<u8>, // Offset: 0x01 (R/W 8) Sleep Mode pub external_control: ReadWrite<u8>, // Offset: 0x02 (R/W 8) External ...
}
{ // Now that all system clocks are configured, we can set CPU and APBx BUS clocks. // There[sic] values are normally the one present after Reset. let PM_CPUSEL_CPUDIV_POS = 0; // (PM_CPUSEL) CPU Prescaler Selection let PM_CPUSEL_CPUDIV_DIV1_VAL = 0x0; // (PM_CPUSEL) Divide by 1 ...
identifier_body
payments.js
"use strict"; const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const PaymentSchema = require("./../schemas/payment"); const PaymentModel = mongoose.model('Payment', PaymentSchema); const parser = require("./../parser/parser"); const _ = require("lodash"); cons...
}); res.json(mappedCollection); }); router.put('/:id', (req, res) => { PaymentModel .updateOnePayment(req) .then(() => res.json({})) .catch(error => res.json({error})); }); router.delete('/:id', (req, res) => { PaymentModel .deleteOnePayment(req) .then(() =...
}; parser.prePopulateCategoryForPayment(payment, item.description); return payment;
random_line_split
payments.js
"use strict"; const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const PaymentSchema = require("./../schemas/payment"); const PaymentModel = mongoose.model('Payment', PaymentSchema); const parser = require("./../parser/parser"); const _ = require("lodash"); cons...
PaymentModel .addMany(req) .then(payments => res.json(payments)) .catch(error => res.json({error})); }); /*router.post('/importcollection', (req, res) => { const collection = require("./../parser/payments.json"); const request = _.chain(collection) .map(item => { ...
{ for (const item of req.body.data) { delete item._id; } }
conditional_block
log_parser.py
#============================================================================== # Copyright 2019-2020 Intel Corporation # # 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...
match = lambda current, expected: all( [expected[k] == current[k] for k in expected]) for graph_id_1 in expected_vals: # The ordering is not important and could be different, hence search through all elements of parsed_vals matching_id = None for graph_id_2 in parsed_vals: ...
identifier_body
log_parser.py
#============================================================================== # Copyright 2019-2020 Intel Corporation # # 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...
return all_results def compare_parsed_values(parsed_vals, expected_vals): # Both inputs are expected to be 2 dictionaries (representing jsons) # The constraints in expected is <= parsed_vals. Parsed_vals should have all possible values that the parser can spit out. However expected_vals can be relaxed (e...
# add the last section to the results all_results[str(ctr)] = curr_result
random_line_split
log_parser.py
#============================================================================== # Copyright 2019-2020 Intel Corporation # # 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...
elif 'Number of nodes marked for clustering' in line: curr_result['num_nodes_marked_for_clustering'] = int( line.split(':')[-1].strip().split(' ')[0].strip()) if verbose: # get percentage of total nodes match = re.s...
curr_result['num_nodes_in_graph'] = int( line.split(':')[-1].strip())
conditional_block
log_parser.py
#============================================================================== # Copyright 2019-2020 Intel Corporation # # 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...
(parsed_vals, expected_vals): # Both inputs are expected to be 2 dictionaries (representing jsons) # The constraints in expected is <= parsed_vals. Parsed_vals should have all possible values that the parser can spit out. However expected_vals can be relaxed (even empty) and choose to only verify/match certain ...
compare_parsed_values
identifier_name
pyrarcr-0.2.py
#!/usr/bin/env python3 ##### ##### ##### ##### #### #### # # # # # # # # # # #### #### # # # ##### #### ##### ##### ##### # # # # #### # # # # # # # # # # # # # # # # # # # # # #### # #### # #### #finds the password of a desired ...
else: print("ERROR: File doesn't exist.\nExiting...") else: print("Usage:",os.path.basename(__file__),"[rar file]") print("Example:",os.path.basename(__file__),"foobar.rar")
rc(sys.argv[1])
conditional_block