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
simple-record-test.ts
import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import TablesSimpleRecord from '@datahub/shared/components/tables/simple-record'; module('Integration | Component | tables/simple-record', function(hooks): void { setupRenderi...
import { module, test } from 'qunit';
random_line_split
rome_fields_dict.py
field_dict={'ROME-FIELD-01':[ 267.835895375 , -30.0608178195 , '17:51:20.6149','-30:03:38.9442' ], 'ROME-FIELD-02':[ 269.636745458 , -27.9782661111 , '17:58:32.8189','-27:58:41.758' ], 'ROME-FIELD-03':[ 268.000049542 , -28.8195573333 , '17:52:00.0119','-28:49:10.4064' ], 'ROME-FIE...
'ROME-FIELD-07':[ 268.529571333 , -28.6937071111 , '17:54:07.0971','-28:41:37.3456' ], 'ROME-FIELD-08':[ 268.709737083 , -29.1867251944 , '17:54:50.3369','-29:11:12.2107' ], 'ROME-FIELD-09':[ 268.881108542 , -29.7704673333 , '17:55:31.4661','-29:46:13.6824' ], 'ROME-FI...
random_line_split
bench.rs
#![feature(test)] extern crate fdlimit; extern crate test; extern crate tiny_http; use std::io::Write; use std::process::Command; use tiny_http::Method; #[test] #[ignore] // TODO: obtain time fn curl_bench() { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port();...
(bencher: &mut test::Bencher) { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port(); let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); bencher.iter(|| { (write!(stream, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")).unwra...
sequential_requests
identifier_name
bench.rs
#![feature(test)] extern crate fdlimit; extern crate test; extern crate tiny_http; use std::io::Write; use std::process::Command; use tiny_http::Method; #[test] #[ignore] // TODO: obtain time fn curl_bench() { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port();...
let request = match server.try_recv().unwrap() { None => break, Some(rq) => rq, }; assert_eq!(request.method(), &Method::Get); request.respond(tiny_http::Response::new_empty(tiny_http::StatusCode(204))); } }); }
{ fdlimit::raise_fd_limit(); let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port(); bencher.iter(|| { let mut streams = Vec::new(); for _ in 0..1000usize { let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwra...
identifier_body
bench.rs
#![feature(test)] extern crate fdlimit; extern crate test; extern crate tiny_http; use std::io::Write; use std::process::Command; use tiny_http::Method; #[test] #[ignore] // TODO: obtain time fn curl_bench() { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port();...
#[bench] fn sequential_requests(bencher: &mut test::Bencher) { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port(); let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); bencher.iter(|| { (write!(stream, "GET / HTTP/1.1\r\n...
Err(_) => return, // ignoring test }; drop(server); }
random_line_split
analyzeMissingDates.js
#!/usr/bin/env node var http = require('http'); var moment = require('moment'); var server = undefined; var threshold = undefined; var units = undefined; if (!isValid(process.argv)) { console.error('invalid arguments, expected hostname threshold and units'); process.exit(-1); } var request = http.request('http://...
(data) { var length = data.length; var i, sensorData, sensorId, sensorLog, dates; var analysis; for (i = 0; i < length; i++) { sensorData = data[i]; sensorId = sensorData['_id']; sensorLog = sensorData['value']; dates = sensorLog.map(function(log) { return moment(log.date); }); ...
analyze
identifier_name
analyzeMissingDates.js
#!/usr/bin/env node var http = require('http'); var moment = require('moment'); var server = undefined; var threshold = undefined; var units = undefined; if (!isValid(process.argv))
var request = http.request('http://' + server + '/api/temperatures', function(response) { var statusCode = response.statusCode; var result = []; var json = undefined; if (statusCode === 200) { response.on('data', function(chunk) { result.push(chunk.toString()); }); response.on('end', functi...
{ console.error('invalid arguments, expected hostname threshold and units'); process.exit(-1); }
conditional_block
analyzeMissingDates.js
#!/usr/bin/env node var http = require('http'); var moment = require('moment'); var server = undefined; var threshold = undefined; var units = undefined; if (!isValid(process.argv)) { console.error('invalid arguments, expected hostname threshold and units'); process.exit(-1); } var request = http.request('http://...
{ if (args.length === 5) { server = args[2]; threshold = parseInt(args[3], 10); units = args[4]; return true; } else { return false; } }
identifier_body
analyzeMissingDates.js
#!/usr/bin/env node var http = require('http'); var moment = require('moment'); var server = undefined; var threshold = undefined; var units = undefined; if (!isValid(process.argv)) { console.error('invalid arguments, expected hostname threshold and units'); process.exit(-1); } var request = http.request('http://...
var from = analysis.previous; var diff; if (analysis.previous) { diff = to.diff(from, units); if (diff > threshold) { analysis.result.push({ diff: diff + ' ' + units, from: from.format('YYMMDDHHmm'), to: to.format('YYMMDDHHmm') }...
analysis = dates.reduce(function(analysis, to) {
random_line_split
regress-349602.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var summary = 'decompilation of let with e4x literal'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUG...
var gTestfile = 'regress-349602.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 349602;
random_line_split
regress-349602.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gTestfile = 'regress-349602.js...
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'function () {\n (let (a = 3) <x/>);\n}'; try { var f = eval('(function () { let (a = 3) <x/>; })'); actual = f + ''; } catch(ex) { actual = ex + ''; } compareSource(expect, actual, summary); exitFu...
identifier_body
regress-349602.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gTestfile = 'regress-349602.js...
() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'function () {\n (let (a = 3) <x/>);\n}'; try { var f = eval('(function () { let (a = 3) <x/>; })'); actual = f + ''; } catch(ex) { actual = ex + ''; } compareSource(expect, actual, summary); exi...
test
identifier_name
api.rs
use std::io::Cursor; use rustc_serialize::json; use rustc_serialize::json::Json; use tiny_http::{Response, StatusCode}; use http::{ok, okJson, http_response}; use table::Tables; use table::TableError; pub fn post_table(tables: &mut Tables, table: &str) -> Response<Cursor<Vec<u8>>> { println!("Creating Table: {...
} pub fn post_key_to_table(tables: &mut Tables, table: &str, key: &str, data: Json) -> Response<Cursor<Vec<u8>>> { match tables.put(table, key, data) { Err(e) => handle_table_error(e), Ok(_) => ok(format!("Successfully added key: {} to table {}", key, table)) } } pub fn get_key(tables: &mut Ta...
}
random_line_split
api.rs
use std::io::Cursor; use rustc_serialize::json; use rustc_serialize::json::Json; use tiny_http::{Response, StatusCode}; use http::{ok, okJson, http_response}; use table::Tables; use table::TableError; pub fn post_table(tables: &mut Tables, table: &str) -> Response<Cursor<Vec<u8>>> { println!("Creating Table: ...
fn handle_table_error(error: TableError) -> Response<Cursor<Vec<u8>>> { match error { TableError::TableDoesNotExist => http_response(StatusCode(400), "Table does not exist"), TableError::TableAlreadyExists => http_response(StatusCode(400), "Table already exists"), TableError::KeyAlreadyPr...
{ match tables.delete_table(table) { Err(e) => handle_table_error(e), Ok(_) => ok(format!("Successfully deleted table: {}", table)), } }
identifier_body
api.rs
use std::io::Cursor; use rustc_serialize::json; use rustc_serialize::json::Json; use tiny_http::{Response, StatusCode}; use http::{ok, okJson, http_response}; use table::Tables; use table::TableError; pub fn post_table(tables: &mut Tables, table: &str) -> Response<Cursor<Vec<u8>>> { println!("Creating Table: ...
(tables: &mut Tables, table: &str, key: &str) -> Response<Cursor<Vec<u8>>> { match tables.get(table, key) { Err(e) => handle_table_error(e), Ok(json) => okJson(json), } } pub fn delete_key_from_table(tables: &mut Tables, table: &str, key: &str) -> Response<Cursor<Vec<u8>>> { match tables.de...
get_key
identifier_name
data-table.spec.ts
import { assert } from 'chai'; import { DataTable } from '../../src/group'; import { Text } from '../../src/question/text'; import { Required } from '../../src/validation'; describe('AngularForms :: Group :: DataTable', () => { it('should be instantiable', () => {
it('should getQuestionByName method', () => { const dataTable: DataTable = new DataTable('G-01', 'A simple group', [[new Text('Q-01', 'A simple question')]]); assert.isTrue(dataTable.getQuestionByName('Q-01') instanceof Text); }); it('should isRequired method', () => { const dataTable1: DataTable = ...
assert.ok(new DataTable('G-01', 'A simple group', [[], []], [])); });
random_line_split
candlestick.py
from math import pi import pandas as pd from bokeh.sampledata.stocks import MSFT from bokeh.plotting import * df = pd.DataFrame(MSFT)[:50] df['date'] = pd.to_datetime(df['date']) mids = (df.open + df.close)/2 spans = abs(df.close-df.open) inc = df.close > df.open dec = df.open > df.close w = 12*60*60*1000 # half da...
show()
random_line_split
templateeditordialog.py
# -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> import gtk from zim.fs import TrashNotSupportedError from zim.config import XDG_DATA_HOME, data_file from zim.templates import list_template_categories, list_templates from zim.gui.widgets import Dialog, BrowserTreeView, Button, ...
b.set_alignment(0.0, 0.5) vbbox.add(b) browse_button = Button(_('Browse')) # T: button label browse_button.connect('clicked', self.on_browse) self.add_extra_button(browse_button) self._buttonbox = vbbox self._delete_button = delete_button self.on_selection_changed() ## Same button appears in expo...
delete_button = gtk.Button(stock='gtk-remove') delete_button.connect('clicked', self.on_delete) for b in (view_button, copy_button, edit_button, delete_button):
random_line_split
templateeditordialog.py
# -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> import gtk from zim.fs import TrashNotSupportedError from zim.config import XDG_DATA_HOME, data_file from zim.templates import list_template_categories, list_templates from zim.gui.widgets import Dialog, BrowserTreeView, Button, ...
self.view.connect('row-activated', self.on_selection_changed) hbox.add(ScrolledWindow(self.view)) vbbox = gtk.VButtonBox() vbbox.set_layout(gtk.BUTTONBOX_START) hbox.pack_start(vbbox, False) view_button = Button(stock='gtk-file', label=_('_View')) # T: button label view_button.connect('clicked', self.on...
'''Dialog with a tree of available templates for export and new pages. Allows edit, delete, and create new templates. Uses external editor. ''' def __init__(self, ui): Dialog.__init__(self, ui, _('Templates'), help='Help:Templates', buttons=gtk.BUTTONS_CLOSE, defaultwindowsize=(400, 450)) # T: Dialog tit...
identifier_body
templateeditordialog.py
# -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> import gtk from zim.fs import TrashNotSupportedError from zim.config import XDG_DATA_HOME, data_file from zim.templates import list_template_categories, list_templates from zim.gui.widgets import Dialog, BrowserTreeView, Button, ...
def on_view(self, *a): # Open the file, witout waiting for editor to return custom, default = self.view.get_selected() if custom is None: return # Should not have been sensitive if custom.exists(): self.ui.open_file(custom) else: assert default and default.exists() self.ui.open_file(default) ...
self._delete_button.set_sensitive(False)
conditional_block
templateeditordialog.py
# -*- coding: utf-8 -*- # Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com> import gtk from zim.fs import TrashNotSupportedError from zim.config import XDG_DATA_HOME, data_file from zim.templates import list_template_categories, list_templates from zim.gui.widgets import Dialog, BrowserTreeView, Button, ...
(self, *a): # Only delete custom, may result in reset to default custom, default = self.view.get_selected() if custom is None or not custom.exists(): return # Should not have been sensitive try: custom.trash() except TrashNotSupportedError: # TODO warnings custom.remove() self.view.refresh() ...
on_delete
identifier_name
distillery.py
from .distillers import Distill, Distiller class NewsDistiller(Distiller): site = Distill("og:site_name") title = Distill("s:headline", "og:title") image_url = Distill("s:associatedMedia.ImageObject/url", "og:image") pub_date = Distill("s:datePublished") author = Distill("s:creator.Person/name", "...
(Distiller): site = Distill("og:site_name") title = Distill("pp:title", "s:headline", "og:title") image_url = Distill( "pp:image_url", "s:associatedMedia.ImageObject/url", "og:image") pub_date = Distill("pp:pub_date", "s:datePublished") author = Distill("pp:author", "s:creator.Person/name", ...
ParselyDistiller
identifier_name
distillery.py
from .distillers import Distill, Distiller class NewsDistiller(Distiller):
class ParselyDistiller(Distiller): site = Distill("og:site_name") title = Distill("pp:title", "s:headline", "og:title") image_url = Distill( "pp:image_url", "s:associatedMedia.ImageObject/url", "og:image") pub_date = Distill("pp:pub_date", "s:datePublished") author = Distill("pp:author", ...
site = Distill("og:site_name") title = Distill("s:headline", "og:title") image_url = Distill("s:associatedMedia.ImageObject/url", "og:image") pub_date = Distill("s:datePublished") author = Distill("s:creator.Person/name", "s:author") section = Distill("s:articleSection") description = Distill("s...
identifier_body
distillery.py
from .distillers import Distill, Distiller class NewsDistiller(Distiller): site = Distill("og:site_name") title = Distill("s:headline", "og:title") image_url = Distill("s:associatedMedia.ImageObject/url", "og:image") pub_date = Distill("s:datePublished") author = Distill("s:creator.Person/name", "...
class ParselyDistiller(Distiller): site = Distill("og:site_name") title = Distill("pp:title", "s:headline", "og:title") image_url = Distill( "pp:image_url", "s:associatedMedia.ImageObject/url", "og:image") pub_date = Distill("pp:pub_date", "s:datePublished") author = Distill("pp:author", "s:...
description = Distill("s:description", "og:description") link = Distill("s:url", "og:url") id = Distill("s:identifier")
random_line_split
db.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Stores subscription information for WebPush. //! //! # The WebPush database //! //! The "subscriptions" table ...
/// Removes an existing push subscription identified by `push_uri`. pub fn unsubscribe(&self, _: i32, push_uri: &str) -> rusqlite::Result<c_int> { self.db.execute("DELETE FROM subscriptions WHERE push_uri=$1", &[&escape(push_uri)] ) } /// Sets the resources to ...
{ self.db.execute("INSERT INTO subscriptions VALUES ($1, $2, $3)", &[&user_id, &escape(&sub.push_uri), &escape(&sub.public_key)] ) }
identifier_body
db.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Stores subscription information for WebPush. //! //! # The WebPush database //! //! The "subscriptions" table ...
public_key: "u1_sub0_pkey".to_owned() }).unwrap(); db.subscribe(1, &Subscription { push_uri: "u1_sub1_puri".to_owned(), public_key: "u1_sub1_pkey".to_owned() }).unwrap(); db.subscribe(2, &Subscription { push_uri: "u2_sub0_puri".to_owned(), ...
db.subscribe(1, &Subscription { push_uri: "u1_sub0_puri".to_owned(),
random_line_split
db.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Stores subscription information for WebPush. //! //! # The WebPush database //! //! The "subscriptions" table ...
(&self, _: i32, push_uri: &str) -> rusqlite::Result<c_int> { self.db.execute("DELETE FROM subscriptions WHERE push_uri=$1", &[&escape(push_uri)] ) } /// Sets the resources to subscribe to notifications for the user `user_id`. pub fn set_resources(&self, user_id: i32,...
unsubscribe
identifier_name
partition.service.ts
import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import "rxjs/add/operator/toPromise"; import {ConfigService, RuntimeService, Identity} from "../../../rest.servcie"; import {TextboxFormItem, FormItemBase, ArrayFormItem} from "../../../dynamic/form/form-item"; export interface Partition ext...
(public http: Http) { super(http); } }
constructor
identifier_name
partition.service.ts
import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import "rxjs/add/operator/toPromise"; import {ConfigService, RuntimeService, Identity} from "../../../rest.servcie"; import {TextboxFormItem, FormItemBase, ArrayFormItem} from "../../../dynamic/form/form-item"; export interface Partition ext...
new TextboxFormItem({ key: 'id', label: 'id', type: 'number', readonly: true, required: true }), new TextboxFormItem({ key: 'key', label: 'key', required: true }), new ArrayFormItem({ key: 'keys', label: 'keys'...
getFormItems(): FormItemBase<any>[] { return [
random_line_split
partition.service.ts
import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import "rxjs/add/operator/toPromise"; import {ConfigService, RuntimeService, Identity} from "../../../rest.servcie"; import {TextboxFormItem, FormItemBase, ArrayFormItem} from "../../../dynamic/form/form-item"; export interface Partition ext...
} @Injectable() export class RuntimePartitionService extends RuntimeService<RuntimePartition> { constructor(public http: Http) { super(http); } }
{ return [ new TextboxFormItem({ key: 'id', label: 'id', type: 'number', readonly: true, required: true }), new TextboxFormItem({ key: 'key', label: 'key', required: true }), new ArrayFormItem({ key: 'keys', ...
identifier_body
ktucloud.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
params["diskofferingid"] = size.id result = self._async_request( command="deployVirtualMachine", params=params, method="GET" ) node = result["virtualmachine"] return Node( id=node["id"], name=node["displayname"], state=self.N...
if size.id != self.EMPTY_DISKOFFERINGID:
random_line_split
ktucloud.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
(self, location=None): args = {"templatefilter": "executable"} if location is not None: args["zoneid"] = location.id imgs = self._sync_request(command="listAvailableProductTypes", method="GET") images = [] for img in imgs["producttypes"]: images.append( ...
list_images
identifier_name
ktucloud.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
return Node( id=node["id"], name=node["displayname"], state=self.NODE_STATE_MAP[node["state"]], public_ips=[], private_ips=[], driver=self, extra={ "zoneid": image.extra["zoneid"], "ip_addresses"...
params = { "displayname": name, "serviceofferingid": image.id, "templateid": str(image.extra["templateid"]), "zoneid": str(image.extra["zoneid"]), } if ex_usageplantype is None: params["usageplantype"] = "hourly" else: para...
identifier_body
ktucloud.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
imgs = self._sync_request(command="listAvailableProductTypes", method="GET") images = [] for img in imgs["producttypes"]: images.append( NodeImage( img["serviceofferingid"], img["serviceofferingdesc"], sel...
args["zoneid"] = location.id
conditional_block
api.ts
Renderer2Interceptor = new InjectionToken<Renderer2[]>('Renderer2Interceptor'); /** * Used by `RendererFactory2` to associate custom rendering data and styles * with a rendering implementation. * @publicApi */ export interface RendererType2 { /** * A unique identifying string for the new renderer, used when...
/** * Implement this callback to remove a class from an element in the DOM. * @param el The element. * @param name The class name. */ abstract removeClass(el: any, name: string): void; /** * Implement this callback to set a CSS style for an element in the DOM. * @param el The element. * @pa...
* @param name The class name. */ abstract addClass(el: any, name: string): void;
random_line_split
symEnum.py
# Copyright 2006-2014 Mark Diekhans # required enum34: https://pypi.python.org/pypi/enum34 from enum import Enum,EnumMeta SymEnum = None # class defined after use class SymEnumValue(object): "Class used to define SymEnum member that have additional attributes." def __init__(self, value, externalName=None): ...
(cls, value, names=None, module=None, typ=None): "look up a value object, either by name of value," if (names is None) and isinstance(value, str): # map string name to instance, check for external name value = cls.__extNameMap__.toIntName(value) member = cls._member_m...
__call__
identifier_name
symEnum.py
# Copyright 2006-2014 Mark Diekhans # required enum34: https://pypi.python.org/pypi/enum34 from enum import Enum,EnumMeta SymEnum = None # class defined after use class SymEnumValue(object): "Class used to define SymEnum member that have additional attributes." def __init__(self, value, externalName=None): ...
def __lt__(self, other): if isinstance(other, SymEnum): return self.value < other.value else: return self.value < other def __ge__(self, other): if isinstance(other, SymEnum): return self.value >= other.value else: return self.va...
if isinstance(other, SymEnum): return self.value <= other.value else: return self.value <= other
identifier_body
symEnum.py
# Copyright 2006-2014 Mark Diekhans # required enum34: https://pypi.python.org/pypi/enum34 from enum import Enum,EnumMeta SymEnum = None # class defined after use class SymEnumValue(object): "Class used to define SymEnum member that have additional attributes." def __init__(self, value, externalName=None): ...
if isinstance(other, SymEnum): return self.value != other.value else: return True
def __ne__(self, other):
random_line_split
symEnum.py
# Copyright 2006-2014 Mark Diekhans # required enum34: https://pypi.python.org/pypi/enum34 from enum import Enum,EnumMeta SymEnum = None # class defined after use class SymEnumValue(object): "Class used to define SymEnum member that have additional attributes." def __init__(self, value, externalName=None): ...
else: return True
return self.value != other.value
conditional_block
canvas_render_task.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::{DrawTarget, Color, B8G8R8A8, SkiaBackend, StrokeOptions, DrawOptions}; use azure::azure_hl::...
} pub struct CanvasRenderTask { drawtarget: DrawTarget, fill_color: ColorPattern, stroke_color: ColorPattern, stroke_opts: StrokeOptions, } impl CanvasRenderTask { fn new(size: Size2D<i32>) -> CanvasRenderTask { CanvasRenderTask { drawtarget: CanvasRenderTask::create(size), ...
Close,
random_line_split
canvas_render_task.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::{DrawTarget, Color, B8G8R8A8, SkiaBackend, StrokeOptions, DrawOptions}; use azure::azure_hl::...
{ drawtarget: DrawTarget, fill_color: ColorPattern, stroke_color: ColorPattern, stroke_opts: StrokeOptions, } impl CanvasRenderTask { fn new(size: Size2D<i32>) -> CanvasRenderTask { CanvasRenderTask { drawtarget: CanvasRenderTask::create(size), fill_color: ColorPatt...
CanvasRenderTask
identifier_name
canvas_render_task.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::{DrawTarget, Color, B8G8R8A8, SkiaBackend, StrokeOptions, DrawOptions}; use azure::azure_hl::...
fn create(size: Size2D<i32>) -> DrawTarget { DrawTarget::new(SkiaBackend, size, B8G8R8A8) } fn recreate(&mut self, size: Size2D<i32>) { self.drawtarget = CanvasRenderTask::create(size); } }
{ let drawopts = DrawOptions::new(1.0, 0); self.drawtarget.stroke_rect(rect, &self.stroke_color, &self.stroke_opts, &drawopts); }
identifier_body
webglbuffer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
} } impl WebGLBuffer { pub fn id(&self) -> u32 { self.id } // NB: Only valid buffer targets come here pub fn bind(&self, target: u32) -> WebGLResult<()> { if let Some(previous_target) = self.target.get() { if target != previous_target { return Err(WebGL...
pub fn new(global: GlobalRef, renderer: IpcSender<CanvasMsg>, id: u32) -> Root<WebGLBuffer> { reflect_dom_object(box WebGLBuffer::new_inherited(renderer, id), global, WebGLBufferBinding::Wrap)
random_line_split
webglbuffer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
(global: GlobalRef, renderer: IpcSender<CanvasMsg>, id: u32) -> Root<WebGLBuffer> { reflect_dom_object(box WebGLBuffer::new_inherited(renderer, id), global, WebGLBufferBinding::Wrap) } } impl WebGLBuffer { pub fn id(&self) -> u32 { self.id } // NB: Only valid buffer targets come here ...
new
identifier_name
webglbuffer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
} else { self.target.set(Some(target)); } self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::BindBuffer(target, self.id))).unwrap(); Ok(()) } pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); let _ = self...
{ return Err(WebGLError::InvalidOperation); }
conditional_block
service.rs
oHandler<Message> + Send>, }, AddTimer { handler_id: HandlerId, token: TimerToken, delay: u64, }, RemoveTimer { handler_id: HandlerId, token: TimerToken, }, RegisterStream { handler_id: HandlerId, token: StreamToken, }, DeregisterStream { handler_id: HandlerId, token: StreamToken, }, UpdateS...
} IoMessage::RegisterStream { handler_id, token } => { let handler = self.handlers.get(handler_id).expect("Unknown handler id").clone(); handler.register_stream(token, Token(token + handler_id * TOKENS_PER_HANDLER), event_loop); } IoMessage::DeregisterStream { handler_id, token } => { let handl...
{ event_loop.clear_timeout(timer.timeout); }
conditional_block
service.rs
} /// Broadcast a message to other IO clients pub fn message(&self, message: Message) { self.channel.send(message).expect("Error seding message"); } /// Get message channel pub fn channel(&self) -> IoChannel<Message> { self.channel.clone() } } #[derive(Clone)] struct UserTimer { delay: u64, timeout: Time...
host_channel: channel, }) }
random_line_split
service.rs
oHandler<Message> + Send>, }, AddTimer { handler_id: HandlerId, token: TimerToken, delay: u64, }, RemoveTimer { handler_id: HandlerId, token: TimerToken, }, RegisterStream { handler_id: HandlerId, token: StreamToken, }, DeregisterStream { handler_id: HandlerId, token: StreamToken, }, UpdateS...
(channel: IoChannel<Message>, handler: HandlerId) -> IoContext<Message> { IoContext { handler: handler, channel: channel, } } /// Register a new IO timer. 'IoHandler::timeout' will be called with the token. pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), UtilError> { try!(self.cha...
new
identifier_name
admin.py
#/usr/bin/env python3 import webtools as wt import os, crypt, cgitb cgitb.enable() modes = {"0": "no mode", "1": "lock", "2": "sticky", "3": "stickylock", "4": "permasage" } settings = "./settings.txt" b_conf = [] cd = {} with open(settings, "r") as settings: setting...
elif wt.get_form('pw') and \ tripcode(wt.get_form('pw')) == b_conf[3]: print(wt.put_cookie('pw', wt.get_form('pw'))) return 1 else: if wt.get_form('pw'): print("Password incorrect.<br>") print("<h1>Login</h1>") print("<p>", wt.new_form('admin.py', 'p...
return 1
conditional_block
admin.py
#/usr/bin/env python3 import webtools as wt import os, crypt, cgitb cgitb.enable() modes = {"0": "no mode", "1": "lock", "2": "sticky", "3": "stickylock", "4": "permasage" } settings = "./settings.txt" b_conf = [] cd = {} with open(settings, "r") as settings: setting...
def mod_threads(): print("<pre>") with open(b_conf[6]) as t_list: print(t_list.read()) print("</pre>") ti = thread_index() for t in ti["ti"]: # t = filename # t[0] last reply time, t[1] thread title # t[2] reply count, t[3] thread mode mic = mode_icons(ti[t...
print("""<pre> - change settings - moderate threads - modify wordfilter </pre>""") if not wt.get_form('mode') or not wt.get_form('thread'): print("<h2>Settings</h2>") print("\n".join(["<br> - "+str(i) for i in b_conf])) for s in cd.keys(): print("<p>",s + ":<br>&emsp;", cd[s]) ...
identifier_body
admin.py
#/usr/bin/env python3 import webtools as wt import os, crypt, cgitb cgitb.enable() modes = {"0": "no mode", "1": "lock", "2": "sticky", "3": "stickylock", "4": "permasage" } settings = "./settings.txt" b_conf = [] cd = {} with open(settings, "r") as settings: setting...
elif wt.get_form('pw') and \ tripcode(wt.get_form('pw')) == b_conf[3]: print(wt.put_cookie('pw', wt.get_form('pw'))) return 1 else: if wt.get_form('pw'): print("Password incorrect.<br>") print("<h1>Login</h1>") print("<p>", wt.new_form('admin.py', 'po...
if 'pw' in cookies.keys(): if tripcode(cookies['pw']) == b_conf[3]: return 1
random_line_split
admin.py
#/usr/bin/env python3 import webtools as wt import os, crypt, cgitb cgitb.enable() modes = {"0": "no mode", "1": "lock", "2": "sticky", "3": "stickylock", "4": "permasage" } settings = "./settings.txt" b_conf = [] cd = {} with open(settings, "r") as settings: setting...
(): print(wt.head(b_conf[0])) print("<h2>", b_conf[0], "admin</h2>") # print(wt.get_cookie()) if login_admin() == 1: admin_splash() main()
main
identifier_name
pascals-triangle.rs
extern crate pascals_triangle; use pascals_triangle::*; #[test] fn no_rows() { let pt = PascalsTriangle::new(0); let expected: Vec<Vec<u32>> = Vec::new(); assert_eq!(expected, pt.rows()); } #[test] fn one_row() { let pt = PascalsTriangle::new(1); let expected: Vec<Vec<u32>> = vec![vec![1]]; a...
() { let pt = PascalsTriangle::new(2); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]]; assert_eq!(expected, pt.rows()); } #[test] fn three_rows() { let pt = PascalsTriangle::new(3); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1], vec![1, 2, 1]]; assert_eq!(expected, pt.rows());...
two_rows
identifier_name
pascals-triangle.rs
extern crate pascals_triangle; use pascals_triangle::*; #[test] fn no_rows() { let pt = PascalsTriangle::new(0); let expected: Vec<Vec<u32>> = Vec::new(); assert_eq!(expected, pt.rows()); } #[test] fn one_row() { let pt = PascalsTriangle::new(1); let expected: Vec<Vec<u32>> = vec![vec![1]]; a...
#[test] fn three_rows() { let pt = PascalsTriangle::new(3); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1], vec![1, 2, 1]]; assert_eq!(expected, pt.rows()); } #[test] fn last_of_four_rows() { let pt = PascalsTriangle::new(4); let expected: Vec<u32> = vec![1, 3, 3, 1]; assert_eq!(expec...
{ let pt = PascalsTriangle::new(2); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]]; assert_eq!(expected, pt.rows()); }
identifier_body
pascals-triangle.rs
extern crate pascals_triangle; use pascals_triangle::*;
assert_eq!(expected, pt.rows()); } #[test] fn one_row() { let pt = PascalsTriangle::new(1); let expected: Vec<Vec<u32>> = vec![vec![1]]; assert_eq!(expected, pt.rows()); } #[test] fn two_rows() { let pt = PascalsTriangle::new(2); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]]; ass...
#[test] fn no_rows() { let pt = PascalsTriangle::new(0); let expected: Vec<Vec<u32>> = Vec::new();
random_line_split
issue-42467.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) -> Option<()> { None } } impl<T> IntoIterator for Foo<T> { type Item = (); type IntoIter = IntoIter<T>; fn into_iter(self) -> IntoIter<T> { IntoIter(self.0) } } fn main() {}
next
identifier_name
issue-42467.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] struct Foo<T>(T); struct IntoIter<T>(T); impl<'a,...
random_line_split
issue-42467.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{}
identifier_body
index.test.js
// @flow import type { ConfigSparseWithSource } from '../../'; import configResolve from '../'; type Fixture = { name: string, in: ConfigSparseWithSource, }; const fixtures: Fixture[] = [ { name: '01 empty input config', in: {},
configFile: '/foo/bar/package.json', }, }, { name: '03 empty input config with rootDir', in: { rootDir: '/foo/bar', }, }, { name: '04 empty input config with both configFile and rootDir', in: { configFile: '/a/b/c/pack...
}, { name: '02 empty input config with configFile', in: {
random_line_split
sql_to_sheets.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
item_list.append(item) yield item_list def _get_data(self): hook = self.get_db_hook() with closing(hook.get_conn()) as conn, closing(conn.cursor()) as cur: self.log.info("Executing query") cur.execute(self.sql, self.parameters or ()) ...
item = float(item)
conditional_block
sql_to_sheets.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
self.log.info("Getting data") values = list(self._get_data()) self.log.info("Connecting to Google") sheet_hook = GSheetsHook( gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, impersonation_chain=self.impersonation_chain, ) self.log...
identifier_body
sql_to_sheets.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(BaseSQLOperator): """ Copy data from SQL results to provided Google Spreadsheet. :param sql: The SQL to execute. :param spreadsheet_id: The Google Sheet ID to interact with. :param conn_id: the connection ID used to connect to the database. :param parameters: The parameters to render the SQL q...
SQLToGoogleSheetsOperator
identifier_name
sql_to_sheets.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
template_fields_renderers = {"sql": "sql"} template_ext: Sequence[str] = (".sql",) ui_color = "#a0e08c" def __init__( self, *, sql: str, spreadsheet_id: str, sql_conn_id: str, parameters: Optional[Union[Mapping, Iterable]] = None, database: Opti...
"sql", "spreadsheet_id", "spreadsheet_range", "impersonation_chain", )
random_line_split
no_0079_word_search.rs
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool { let m = board.len(); if m == 0 { return false; } let n = board[0].len(); let mut marked = vec![vec![false; n]; m]; let directions = vec![ (-1, 0), // 上 (0, 1), // 右 (1, 0), // 下 (0, -1), // 左 ...
word_idx == word.len() - 1 { // 匹配完了 return true; } marked[board_x][board_y] = true; // 当前匹配上了,再匹配下一个,可选的是相邻的四个位置 for (dx, dy) in directions { let (x, y) = (board_x as isize + *dx, board_y as isize + *dy); if 0 <= x && x < m as isize && 0 <= y && y < n as isize { ...
return false; } if
conditional_block
no_0079_word_search.rs
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool { let m = board.len(); if m == 0 { return false; } let n = board[0].len(); let mut marked = vec![vec![false; n]; m]; let directions = vec![ (-1, 0), // 上 (0, 1), // 右 (1, 0), // 下 (0, -1), // 左 ...
&board, m, n, word.as_bytes(), 0, i, j, &mut marked, &directions, ) { return true; } } } false } fn match_word( bo...
if match_word(
random_line_split
no_0079_word_search.rs
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool { let m = board.len(); if m == 0 { return false; } let n = board[0].len(); let mut marked = vec![vec![false; n]; m]; let directions = vec![ (-1, 0), // 上 (0, 1), // 右 (1, 0), // 下 (0, -1), // 左 ...
S'], vec!['A', 'D', 'E', 'E'], ]; assert_eq!(exist(board.clone(), "ABCCED".to_owned()), true); assert_eq!(exist(board.clone(), "SEE".to_owned()), true); assert_eq!(exist(board.clone(), "ABCB".to_owned()), false); } }
F', 'C', '
identifier_name
no_0079_word_search.rs
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool
m, n, word.as_bytes(), 0, i, j, &mut marked, &directions, ) { return true; } } } false } fn mat ch_word( board: &Vec<Vec<char>>, ...
{ let m = board.len(); if m == 0 { return false; } let n = board[0].len(); let mut marked = vec![vec![false; n]; m]; let directions = vec![ (-1, 0), // 上 (0, 1), // 右 (1, 0), // 下 (0, -1), // 左 ]; for i in 0..m { for j in 0..n { ...
identifier_body
task-comm-11.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let (tx, rx) = channel(); let _child = Thread::spawn(move|| { start(&tx) }); let _tx = rx.recv().unwrap(); }
identifier_body
task-comm-11.rs
// Copyright 2012-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
// except according to those terms. use std::sync::mpsc::{channel, Sender}; use std::thread::Thread; fn start(tx: &Sender<Sender<int>>) { let (tx2, _rx) = channel(); tx.send(tx2).unwrap(); } pub fn main() { let (tx, rx) = channel(); let _child = Thread::spawn(move|| { start(&tx) }); l...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
task-comm-11.rs
// Copyright 2012-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...
(tx: &Sender<Sender<int>>) { let (tx2, _rx) = channel(); tx.send(tx2).unwrap(); } pub fn main() { let (tx, rx) = channel(); let _child = Thread::spawn(move|| { start(&tx) }); let _tx = rx.recv().unwrap(); }
start
identifier_name
ili9341.rs
timer: timer, dc: dc, cs: cs, reset:reset, // dc: gpio::OutGPIO::new(0, 24), // cs: gpio::OutGPIO::new(0, 16), // reset: gpio::OutGPIO::new(0, 23), // backlight: gpio::OutGPIO::new(0, 999), }; // FIXME(farcaller): SPI uses MSB, SCL rising lcd.configure(); ...
{ self.set_col(0, 239); self.set_page(0, 319); self.send_cmd(0x2c); self.dc.set_high(); self.cs.set_low(); for _ in range(0usize, 38400) { self.spi.transfer(0); self.spi.transfer(0); self.spi.transfer(0); self.spi.transfer(0); } self.cs.set_high(); }
identifier_body
ili9341.rs
Timer; use hal::pin::Gpio; use hal::spi::Spi; /// ILI9341 driver. pub struct ILI9341<'a, S:'a, T:'a, P:'a> { spi: &'a S, timer: &'a T, dc: &'a P, cs: &'a P, reset: &'a P, // backlight: gpio::OutGPIO, } impl<'a, S: Spi, T: Timer, P: Gpio> ILI9341<'a, S, T, P> { /// Creates a new ILI9341 driver instance. ...
} true } fn set_power_control_a(&self) { self.send_cmd(0xcb); self.write_data(0x39); self.write_data(0x2c); self.write_data(0x00); self.write_data(0x34); // REG_VD = 0b100 = Vcore 1.6V self.write_data(0x02); // VBC = 0b010 = DDVDH 5.6V } fn set_power_control_b(&self) { ...
{ return false; }
conditional_block
ili9341.rs
} fn configure(&self) { self.cs.set_high(); self.dc.set_high(); self.reset.set_low(); self.timer.wait_ms(10); self.reset.set_high(); self.verify_id(); // this fails :) self.verify_id(); // TODO(farcaller): verify that this didn't fail or bail out self.verify_id(); // and this as we...
clear
identifier_name
ili9341.rs
::Timer; use hal::pin::Gpio; use hal::spi::Spi; /// ILI9341 driver. pub struct ILI9341<'a, S:'a, T:'a, P:'a> { spi: &'a S, timer: &'a T, dc: &'a P, cs: &'a P, reset: &'a P, // backlight: gpio::OutGPIO, } impl<'a, S: Spi, T: Timer, P: Gpio> ILI9341<'a, S, T, P> { /// Creates a new ILI9341 driver instance...
self.write_data(0x28); // VCOML = -1.5V } fn everything_else(&self) { self.send_cmd(0xC7); self.write_data(0x86); self.send_cmd(0x36); self.write_data(0x48); self.send_cmd(0x3A); self.write_data(0x55); self.send_cmd(0xB1); self.write_data(0x00); self.write_data(0x18); ...
random_line_split
store.js
var ReduxDebug, ReduxFreeze, applyMiddleware, compose, createStore, cuid, instrument, makeAStore, makeDevToolsStore, ref, testComponentMixin; ref = require('redux'), createStore = ref.createStore, applyMiddleware = ref.applyMiddleware, compose = ref.compose; ReduxDebug = require('redux-debug'); ReduxFreeze = require...
enhancer = compose(applyMiddleware(ReduxDebug(console.log), ReduxFreeze), instrument(monitorReducer)); return createStore((function(x) { return x; }), initialState, enhancer); }; testComponentMixin = { verbs: ['SET'], componentWillMount: function() { this.iid = cuid(); return console.log(`${this....
}; makeDevToolsStore = function(initialState, monitorReducer) { var enhancer;
random_line_split
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use itertools::Itertools; use ordered_float::OrderedFloat; use stats::LogProb; ...
let peps = [ LogProb(0.1f64.ln()), LogProb::ln_zero(), LogProb(0.25f64.ln()), ]; let fdrs = expected_fdr(&peps); println!("{:?}", fdrs); assert_relative_eq!(*fdrs[1], *LogProb::ln_zero()); assert_relative_eq!(*fdrs[0], *LogProb(0.05f64...
identifier_body
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use itertools::Itertools; use ordered_float::OrderedFloat; use stats::LogProb; ...
eps: &[LogProb]) -> Vec<LogProb> { // sort indices let sorted_idx = (0..peps.len()).sorted_by(|&i, &j| OrderedFloat(*peps[i]).cmp(&OrderedFloat(*peps[j]))); // estimate FDR let mut expected_fdr = vec![LogProb::ln_zero(); peps.len()]; for (i, expected_fp) in LogProb::ln_cumsum_exp(sorted_idx....
pected_fdr(p
identifier_name
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use itertools::Itertools; use ordered_float::OrderedFloat; use stats::LogProb; ...
assert_relative_eq!(*fdrs[1], *LogProb::ln_zero()); assert_relative_eq!(*fdrs[0], *LogProb(0.05f64.ln())); assert_relative_eq!(*fdrs[2], *LogProb((0.35 / 3.0f64).ln())); } }
LogProb::ln_zero(), LogProb(0.25f64.ln()), ]; let fdrs = expected_fdr(&peps); println!("{:?}", fdrs);
random_line_split
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use itertools::Itertools; use ordered_float::OrderedFloat; use stats::LogProb; ...
lse { LogProb::ln_one() }; } expected_fdr } #[cfg(test)] mod tests { use super::*; use stats::LogProb; #[test] fn test_expected_fdr() { let peps = [ LogProb(0.1f64.ln()), LogProb::ln_zero(), LogProb(0.25f64.ln()), ]; ...
fdr } e
conditional_block
upc-a.js
export const CODE_LENGTH = 12 export const ALL_DIGITS = /^\d+$/ export const normalizedValue = (value) => { const { length } = value const systemDigitMissing = !value.startsWith('0') return length == CODE_LENGTH - 1 && systemDigitMissing ? '0' + value : value }
const sum = targetDigits.reduce(function(total, digit, index) { const isOneBasedOddPositionedNumber = index % 2 === 0 const parsedDigit = parseInt(digit, 10) return total + (isOneBasedOddPositionedNumber ? parsedDigit * 3 : parsedDigit) }, 0) const sumModTen = sum % 10 const checkDigit = sumModTe...
export const passesCheckDigitVerification = (value) => { const digits = value.split('') const targetCheckDigit = parseInt(digits[CODE_LENGTH - 1], 10) const targetDigits = digits.slice(0, CODE_LENGTH - 1)
random_line_split
serial_ports.py
#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports():
s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports())
""" Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.sta...
identifier_body
serial_ports.py
#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :ra...
print(serial_ports())
pass return result if __name__ == '__main__':
random_line_split
serial_ports.py
#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def
(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.plat...
serial_ports
identifier_name
serial_ports.py
#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :ra...
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported...
ports = ['COM%s' % (i + 1) for i in range(256)]
conditional_block
trees.py
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #cha...
def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] if classList.count(classList[0]) == len(classList): return classList[0]#stop splitting when all of the classes are equal if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet ...
classCount={} for vote in classList: if vote not in classCount.keys(): classCount[vote] = 0 classCount[vote] += 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0]
identifier_body
trees.py
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet():
[1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #change to discrete values return dataSet, labels def calcShannonEnt(dataSet): numEntries = len(dataSet) labelCounts = {} for feat...
dataSet = [[1, 1, 'yes'],
random_line_split
trees.py
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #cha...
(inputTree,featLabels,testVec): firstStr = inputTree.keys()[0] secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) key = testVec[featIndex] valueOfFeat = secondDict[key] if isinstance(valueOfFeat, dict): classLabel = classify(valueOfFeat, featLabels, testVec) ...
classify
identifier_name
trees.py
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #cha...
classCount[vote] += 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] if classList.count(classList[0]) == len(classList): ...
classCount[vote] = 0
conditional_block
UsersSubview.tsx
// UsersSubview -------------------------------------------------------------- // Render a list of Users for the current Facility, with a callback to // handleSelect(user) when a particular User is selected, or // handleSelect(null) if a previously selected User is unselected. // External Modules --------------------...
context: "UsersSubview.fetchUsers", msg: "FORBIDDEN", }); } else { ReportError("UsersSubview.fetchUsers", error); } } } else { setIn...
if (error.response && (error.response.status === 403)) { logger.debug({
random_line_split
UsersSubview.tsx
// UsersSubview -------------------------------------------------------------- // Render a list of Users for the current Facility, with a callback to // handleSelect(user) when a particular User is selected, or // handleSelect(null) if a previously selected User is unselected. // External Modules --------------------...
else { currentFacility = new Facility({ id: -1, name: "(Select Facility)"}); } setFacility(currentFacility); logger.debug({ context: "UsersSubview.setFacility", facility: Abridgers.FACILITY(currentFacility), }); ...
{ currentFacility = facilityContext.facility; }
conditional_block
iconTeamwork.tsx
import React from 'react'; import SvgIcon from './svgIcon'; type Props = React.ComponentProps<typeof SvgIcon>;
const IconTeamwork = React.forwardRef(function IconTeamwork( props: Props, ref: React.Ref<SVGSVGElement> ) { return ( <SvgIcon {...props} ref={ref}> <path d="M5.86,6A1.28,1.28,0,0,0,7.31,4.66,1.32,1.32,0,0,0,5.89,3.3H3.8V1.77A1.59,1.59,0,0,0,2.2.09,1.58,1.58,0,0,0,.6,1.77V12.33c0,2.53,1,3.66,3.32,3.66a4...
random_line_split
iterative-generator.js
"use strict"; function Point(r, g, b, a)
// Singleton generator var IterativeGenerator = { defaultValue:null, previousValue:undefined, colourArray:[], _isRunning:false, width:null, height:null, imageData:null, heatmapData:[], init: function(canvas, defaultValue) { if (typeof(defaultValue) != 'undefi...
{ this.r = r; this.g = g; this.b = b; this.a = a; this.hash = function() { return btoa('r' + this.r + 'g' + this.g + 'b' + this.b); }; this.toSimpleObject = function() { return { 'r':this.r, 'g':this.g, 'b':this.b, ...
identifier_body
iterative-generator.js
"use strict"; function Point(r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; this.hash = function() { return btoa('r' + this.r + 'g' + this.g + 'b' + this.b); }; this.toSimpleObject = function() { return { 'r':this.r, 'g':th...
this.colourArray.push(row); } this.imageData = canvas.imageData; this.width = canvas.width; this.height = canvas.height; }, createImage: function() { this._isRunning = true; for (var i = 0; i < this.width; i++) { for (var j = 0...
{ var column = [] for (var b = 0; b < 256; b++) { column.push(true); } row.push(column); }
conditional_block
iterative-generator.js
"use strict"; function
(r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; this.hash = function() { return btoa('r' + this.r + 'g' + this.g + 'b' + this.b); }; this.toSimpleObject = function() { return { 'r':this.r, 'g':this.g, 'b':this.b...
Point
identifier_name
iterative-generator.js
"use strict"; function Point(r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; this.hash = function() { return btoa('r' + this.r + 'g' + this.g + 'b' + this.b); }; this.toSimpleObject = function() { return { 'r':this.r, 'g':th...
break; case 'getData': self.postMessage({ 'running':IterativeGenerator.isRunning(), 'imageData':IterativeGenerator.getData() }); break; case 'abilities': self.postMessage({ 'abilities':{ ...
IterativeGenerator.createImage();
random_line_split
utils.py
#!/usr/bin/env python # coding: utf-8 import logging import config def
(name='common', logfile=None): ''' args: name (str): logger name logfile (str): log file, use stream handler (stdout) as default. return: logger obj ''' my_logger = logging.getLogger(name) my_logger.setLevel(config.LOG_LEVEL) if logfile: handler = logging.FileHandler(...
get_common_logger
identifier_name
utils.py
#!/usr/bin/env python # coding: utf-8 import logging import config def get_common_logger(name='common', logfile=None): ''' args: name (str): logger name logfile (str): log file, use stream handler (stdout) as default. return: logger obj ''' my_logger = logging.getLogger(name) ...
else: handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') handler.setFormatter(formatter) my_logger.addHandler(handler) # Stop logger propagate, forbiden duplicate log. ...
handler = logging.FileHandler(logfile)
conditional_block
utils.py
#!/usr/bin/env python # coding: utf-8 import logging import config def get_common_logger(name='common', logfile=None):
COMMON_LOGGER = get_common_logger('common logger') if __name__ == '__main__': COMMON_LOGGER.debug('test')
''' args: name (str): logger name logfile (str): log file, use stream handler (stdout) as default. return: logger obj ''' my_logger = logging.getLogger(name) my_logger.setLevel(config.LOG_LEVEL) if logfile: handler = logging.FileHandler(logfile) else: handler ...
identifier_body
utils.py
#!/usr/bin/env python # coding: utf-8 import logging import config def get_common_logger(name='common', logfile=None): ''' args: name (str): logger name logfile (str): log file, use stream handler (stdout) as default. return: logger obj ''' my_logger = logging.getLogger(name) ...
if __name__ == '__main__': COMMON_LOGGER.debug('test')
return my_logger COMMON_LOGGER = get_common_logger('common logger')
random_line_split
globalize.culture.no.js
/* * Globalize Culture no * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to b...
AM: null, PM: null, patterns: { d: "dd.MM.yyyy", D: "d. MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "d. MMMM yyyy HH:mm", F: "d. MMMM yyyy HH:mm:ss", M: "d. MMMM", Y: "MMMM yyyy" } } } }); }( this ));
random_line_split