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
update_default_servers.py
#!/usr/bin/env python3 # This script prints a new "servers.json" to stdout. # It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions), # and adds new servers from provided file(s) of candidate servers. # A file of new candidate servers can be created via e.g.: # $ ./electrum_ltc/...
(fname1, fname2=None): with open(fname1) as f: res_hostmap = json.loads(f.read()) if fname2 is not None: with open(fname2) as f: dict2 = json.loads(f.read()) common_set = set.intersection(set(res_hostmap), set(dict2)) res_hostmap = {k: v for k, v in res_hostmap.items(...
get_newly_added_servers
identifier_name
update_default_servers.py
#!/usr/bin/env python3 # This script prints a new "servers.json" to stdout. # It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions), # and adds new servers from provided file(s) of candidate servers. # A file of new candidate servers can be created via e.g.: # $ ./electrum_ltc/...
# testnet? #constants.set_testnet() config = SimpleConfig({'testnet': False}) loop, stopping_fut, loop_thread = create_and_start_event_loop() network = Network(config) network.start() @log_exceptions async def f(): try: # prune existing servers old_servers_all = constants.net.DEFAULT_SERVERS ...
with open(fname1) as f: res_hostmap = json.loads(f.read()) if fname2 is not None: with open(fname2) as f: dict2 = json.loads(f.read()) common_set = set.intersection(set(res_hostmap), set(dict2)) res_hostmap = {k: v for k, v in res_hostmap.items() if k in common_set} r...
identifier_body
index.js
const { describe, it, beforeEach } = require('kocha') const { createStore, documentObject } = require('./helper') const genel = require('genel') const { expect } = require('chai') const { Action } = require('~') const { make } = capsid let store describe('Store', () => { beforeEach(async () => { store = await ...
it('saves the currentJournal if exists', async () => { await store.dispatch({ type: Action.CREATE_JOURNAL_DOCUMENT, detail: documentObject }) await store.dispatch({ type: Action.LOAD_CHART }) const journalSaved = new Promise(resolve => { store.journalRepository = { ...
random_line_split
index.js
const { describe, it, beforeEach } = require('kocha') const { createStore, documentObject } = require('./helper') const genel = require('genel') const { expect } = require('chai') const { Action } = require('~') const { make } = capsid let store describe('Store', () => { beforeEach(async () => { store = await ...
(journal) { expect(journal).to.equal(store.currentJournal) resolve() } } }) await store.save() return journalSaved }) }) describe('notifyUpdate', () => { it('notifies the model update', async () => { const store = make( 'js-store'...
save
identifier_name
index.js
const { describe, it, beforeEach } = require('kocha') const { createStore, documentObject } = require('./helper') const genel = require('genel') const { expect } = require('chai') const { Action } = require('~') const { make } = capsid let store describe('Store', () => { beforeEach(async () => { store = await ...
} }) await store.save() return journalSaved }) }) describe('notifyUpdate', () => { it('notifies the model update', async () => { const store = make( 'js-store', genel.div`<p class="is-model-observer">hello</p>` ) store.languageReady = Promise.r...
{ expect(journal).to.equal(store.currentJournal) resolve() }
identifier_body
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct
{ pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializing)] pub password: Vec<u8>, } impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id, email: user.email, password: user.password, } } ...
User
identifier_name
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct User { pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializi...
} pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } pub fn create_user<'a>(user: &'a NewUser, conn: &'a PgConnection) -> Result<User, Error> { let new_user = ModelUser { email: &user.email.to_lowercase(), password: crypto::hash(user.password.as_ref(), crypto::generate_...
{ crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); }
identifier_body
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct User { pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializi...
email: user.email, password: user.password, } } } impl User { pub fn verify_password(&self, plaintext: &str) -> bool { crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); } } pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } p...
impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id,
random_line_split
_date_nl.py
of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Written by Benny Malengier # Last change 2005/12/05: # Correspond naming of dates with actual action, so for abbreviation # of month give...
(self): DateParser.init_strings(self) self._span = re.compile("(van)\s+(?P<start>.+)\s+(tot)\s+(?P<stop>.+)", re.IGNORECASE) self._range = re.compile("tussen\s+(?P<start>.+)\s+en\s+(?P<stop>.+)", re.IGNORECASE) self._...
init_strings
identifier_name
_date_nl.py
#------------------------------------------------------------------------- # # Python modules # #------------------------------------------------------------------------- import re #------------------------------------------------------------------------- # # GRAMPS modules # #---------------------------------------...
return ""
random_line_split
_date_nl.py
of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Written by Benny Malengier # Last change 2005/12/05: # Correspond naming of dates with actual action, so for abbreviation # of month give...
else: value = "%s %s" % (self.short_months[date_val[1]], year) else: value = "%d %s %s" % (date_val[0], self.short_months[date_val[1
value = year
conditional_block
_date_nl.py
of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Written by Benny Malengier # Last change 2005/12/05: # Correspond naming of dates with actual action, so for abbreviation # of month give...
month_to_int["8ber"] = 10 month_to_int["8bris"] = 10 month_to_int["9ber"] = 11 month_to_int["9bris"] = 11 month_to_int["10ber"] = 12 month_to_int["10bris"] = 12 month_to_int["xber"] = 12 month_to_int["xbris"] = 12 modifier_to_int = { 'voor' : Date.MOD_BEFORE, ...
month_to_int = DateParser.month_to_int # Always add dutch and flemish name variants # no matter what the current locale is month_to_int["januari"] = 1 month_to_int["jan"] = 1 # Add other common latin, local and historical variants month_to_int["januaris"] = 1 month_to_int["feber"] = 2 ...
identifier_body
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn
() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function() { println!("called `my::cool::function()`"); } } pub fn indirect_call() { // Let's access al...
function
identifier_name
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn function() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function()
} pub fn indirect_call() { // Let's access all the functions named `function` from this scope! print!("called `my::indirect_call()`, that\n> "); // The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling ...
{ println!("called `my::cool::function()`"); }
identifier_body
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn function() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function() { println!("called `my::cool::funct...
// the same result, because they refer to the same function. self::function(); function(); // We can also use `self` to access another module inside `my`: self::cool::function(); // The `super` keyword refers to the parent scope (outside the `my` module)...
// The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling `function()` directly both give
random_line_split
default.js
/* * Lupus in Tabula * ...un progetto di Edoardo Morassutto * Contributors: * - 2014 Edoardo Morassutto <edoardo.morassutto@gmail.com> */ var path = ""; var APIdir = path + "/api"; var errorCount = 0; var lastError = 0; var lastNotificationUpdate = null; function logout() { $.ajax({ url: APIdir+"/logout", ...
function removeError() { $("#error-"+(lastError++)).fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); } function removeNotification() { var $this = $(this); var id_notification = $this.attr('data-id-notification'); $.ajax({ url: APIdir + "/notification/dismiss", data: { id_notification: id_not...
{ try { return JSON.parse(jqError.responseText); } catch (e) { return JSON.stringify(jqError); } }
identifier_body
default.js
/* * Lupus in Tabula * ...un progetto di Edoardo Morassutto * Contributors: * - 2014 Edoardo Morassutto <edoardo.morassutto@gmail.com> */ var path = ""; var APIdir = path + "/api"; var errorCount = 0; var lastError = 0; var lastNotificationUpdate = null; function logout() { $.ajax({ url: APIdir+"/logout", ...
() { var $this = $(this); var id_notification = $this.attr('data-id-notification'); $.ajax({ url: APIdir + "/notification/dismiss", data: { id_notification: id_notification }, dataType: 'json', type: 'POST', success: function(data) { $this.closest('.notification-element').remove(); if ($('.notificati...
removeNotification
identifier_name
default.js
/* * Lupus in Tabula * ...un progetto di Edoardo Morassutto * Contributors: * - 2014 Edoardo Morassutto <edoardo.morassutto@gmail.com> */ var path = ""; var APIdir = path + "/api"; var errorCount = 0; var lastError = 0; var lastNotificationUpdate = null; function logout() { $.ajax({ url: APIdir+"/logout", ...
$(function() { if (location.pathname != path + "/login") { $(".btn-dismiss-notification").click(removeNotification); $("#notifications-refresh").click(refreshNotifications); $("#notifications-toggle").dropdown(); $("#notifications").on("show.bs.dropdown", function () { refreshNotifications(); }); refre...
} }
random_line_split
DBcon.py
# coding:utf-8 ''' Created on 19/1/2015 @author: PC30 ''' from flaskext.mysql import MySQL#importar mysql from flask import Flask#importar flask class
(): ''' classdocs ''' pass def __init__(self): ''' Constructor ''' pass def conexion(self): mysql = MySQL()#llamando a mysql app = Flask(__name__)#instanciando a flask app.config['MYSQL_DATABASE_USER'] = 'python'#nombre de usuario ...
DBcon
identifier_name
DBcon.py
# coding:utf-8 ''' Created on 19/1/2015 @author: PC30 ''' from flaskext.mysql import MySQL#importar mysql from flask import Flask#importar flask class DBcon():
''' classdocs ''' pass def __init__(self): ''' Constructor ''' pass def conexion(self): mysql = MySQL()#llamando a mysql app = Flask(__name__)#instanciando a flask app.config['MYSQL_DATABASE_USER'] = 'python'#nombre de usuario app...
identifier_body
VectorTile.js
//Single vector tile, received from GeoMixer server // dataProvider: has single method "load": function(x, y, z, v, s, d, callback), which calls "callback" with the following parameters: // - {Object[]} data - information about vector objects in tile // - {Number[4]} [bbox] - optional bbox of objects in tile...
ndsArr.push(arr); hiddenLines.push(hiddenLines1); } if (!hiddenFlag) { hiddenLines = null; } if (isPolygon) { boundsArr = boundsArr[0]; } } else if (type === 'POINT' || type === 'Point') { bounds = gmxAPIutils.bounds([coords]); } else if (t...
if (needFlatten && typeof coords[i][j][0] !== 'number') { coords[i][j] = gmxAPIutils.flattenRing(coords[i][j]); } var b = gmxAPIutils.bounds(coords[i][j]); arr.push(b); if (j === 0) { bounds.extendBounds(b); } ...
conditional_block
VectorTile.js
//Single vector tile, received from GeoMixer server // dataProvider: has single method "load": function(x, y, z, v, s, d, callback), which calls "callback" with the following parameters: // - {Object[]} data - information about vector objects in tile // - {Number[4]} [bbox] - optional bbox of objects in tile...
if (!hiddenFlag) { hiddenLines = null; } if (isPolygon) { boundsArr = boundsArr[0]; } } else if (type === 'POINT' || type === 'Point') { bounds = gmxAPIutils.bounds([coords]); } else if (type === 'MULTIPOINT' || type === 'MultiPoint') { bounds = gmxAPIutil...
boundsArr.push(arr); hiddenLines.push(hiddenLines1); }
random_line_split
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of ...
h } /// Pushes the next multiple of `n` (x2, x3, x5) to the queues pub fn enqueue(&mut self, n: &T) { let (two, three, five) = HammingNumber::multipliers(); self.q2.push(*n * two); self.q3.push(*n * three); self.q5.push(*n * five); } } // Implements the `Iterat...
h.q2.push(one()); h.q3.push(one()); h.q5.push(one());
random_line_split
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of ...
() { let mut hamming = Hamming::<BigUint>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<BigUint>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!...
hamming_iter
identifier_name
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of ...
; let h5 = if five { self.q5.pop_front() } else { None }; match h2.or(h3).or(h5) { Some(n) => { self.enqueue(&n); Some(n) } None => unreachable!() } } } #[test] fn create() { let mut h = Hamming::<BigUint>::new(5); ...
{ None }
conditional_block
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn getCounterValue(ptr: *mut Counter) -> u32 { l...
#[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) } #[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, by...
_counter.get() }
random_line_split
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn getCounterValue(ptr: *mut Counter) -> u32 { l...
#[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.decr(bys) } #[no_mangle] pub extern fn destroyCounter(ptr: *mut Counter) { ...
{ let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) }
identifier_body
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn
(ptr: *mut Counter) -> u32 { let mut _counter = unsafe { &mut *ptr }; _counter.get() } #[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) ...
getCounterValue
identifier_name
associated-types-in-impl-generics.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> &isize { &self.x } } trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.gra...
get
identifier_name
associated-types-in-impl-generics.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.grab(), 100); }
{ &self.x }
identifier_body
associated-types-in-impl-generics.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} struct Struct { x: isize, } impl Get for Struct { type Value = isize; fn get(&self) -> &isize { &self.x } } trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self....
trait Get { type Value; fn get(&self) -> &<Self as Get>::Value;
random_line_split
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] ...
} }
random_line_split
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] ...
merged .last_mut() .map(|last| last[1] = last[1].max(interval[1])); } } merged } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let r = merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]); let expect = vec!...
} else { // 和最后一个相交,两个取并集
conditional_block
merge_intervals.rs
pub fn
(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] < interval[0...
merge
identifier_name
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] ...
c![15, 18]]); let expect = vec![vec![1, 6], vec![8, 10], vec![15, 18]]; assert_eq!(r, expect); let r = merge(vec![vec![1, 4], vec![4, 5]]); let expect = vec![vec![1, 5]]; assert_eq!(r, expect); } }
identifier_body
email.js
require('dotenv').config(); const api_key = process.env.MAILGUN_API_KEY; const domain = process.env.MAILGUN_DOMAIN; const mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); const list = mailgun.lists('subscriberlist@example.com'); const data = { from: 'Dylan <me@...
console.log(`Sending the email to ${email}. Email content: ${body}`); }) }; module.exports = sendMail;
{ console.log(error) }
conditional_block
email.js
require('dotenv').config(); const api_key = process.env.MAILGUN_API_KEY; const domain = process.env.MAILGUN_DOMAIN; const mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); const list = mailgun.lists('subscriberlist@example.com'); const data = { from: 'Dylan <me@...
}); const sendMail = (id, email) => { mailgun.messages().send(data(id, email), (error, body) => { if(error) { console.log(error) } console.log(`Sending the email to ${email}. Email content: ${body}`); }) }; module.exports = sendMail;
console.log(body); }); mailgun.lists('dylan@gmail.com').members().add({ members: members, subscribed: true }, (err, body) => { console.log(body);
random_line_split
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api...
(id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self { Self { id_server_unbind_result } } } }
new
identifier_name
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api...
pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given medium and third-party address. pub fn new(medium: Medium, address: &'a str) -> Self { Self { id_server: Non...
response: { /// Result of unbind operation.
random_line_split
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api...
} }
{ Self { id_server_unbind_result } }
identifier_body
__init__.py
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # This program is free software: you can redistribute it and/or modify
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http...
# it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful,
random_line_split
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
(id: u32, msg: String) -> SQError { let full_msg_str = format!("error id={} msg={}", id, &msg); SQError { id, msg, full_msg: full_msg_str, } } /// Creates an OK error. pub fn ok() -> SQError { SQError::new(0, "ok".to_string()) } /...
new
identifier_name
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
} } pub fn is_sq(&self) -> bool { match *self { Error::SQ(_) => true, _ => false, } } pub fn is_other(&self) -> bool { match *self { Error::Other(_) => true, _ => false, } } } impl error::Error for Error { ...
random_line_split
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
} impl From<SQError> for Error { fn from(err: SQError) -> Error { Error::SQ(err) } } impl From<AddrParseError> for Error { fn from(err: AddrParseError) -> Error { Error::Other(err.description().to_string()) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>)...
{ Error::Io(err) }
identifier_body
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
Ok(val) => val, }; if parts[3] != "msg" { return None; } let msg = parts[4].to_string().clone(); Some(SQError::new(id, unescape(&msg))) } pub fn id(&self) -> u32 { self.id } pub fn msg(&self) -> String { self.msg.clone() ...
{ return None; }
conditional_block
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn
() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the 'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type ...
foo
identifier_name
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo()
// Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравств...
{ // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the 'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type is ...
identifier_body
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the 'str' type represents a string slice, and is usually seen in its b...
// Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравству...
random_line_split
__init__.py
import unittest, tempfile, uuid, os, shutil, sys class Test_CreateRemoveTempLocation(unittest.TestCase): def __init__(self, *args, **kwargs): super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs) self._tmpTestFolder = None def setUp(self):
def tearDown(self): if not self._tmpTestFolder: return if os.path.isdir(self._tmpTestFolder): print "removing test folder: '%s'" %self._tmpTestFolder shutil.rmtree(self._tmpTestFolder) self._tmpTestFolder = None if self._tmpTestFold...
self._tmpTestFolder = os.path.join(tempfile.gettempdir(), "unittest_%s_%s" % (self.__class__.__name__, str( uuid.uuid4() )[:8])) os.mkdir(self._tmpTestFolder) sys.path.append(self._tmpTestFolder)
identifier_body
__init__.py
import unittest, tempfile, uuid, os, shutil, sys class Test_CreateRemoveTempLocation(unittest.TestCase): def __init__(self, *args, **kwargs): super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs) self._tmpTestFolder = None def setUp(self): self._tmpTestFolder = os.pa...
if os.path.isdir(self._tmpTestFolder): print "removing test folder: '%s'" %self._tmpTestFolder shutil.rmtree(self._tmpTestFolder) self._tmpTestFolder = None if self._tmpTestFolder in sys.path: sys.path.remove(self._tmpTestFolder)
return
conditional_block
__init__.py
import unittest, tempfile, uuid, os, shutil, sys class Test_CreateRemoveTempLocation(unittest.TestCase): def __init__(self, *args, **kwargs): super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs) self._tmpTestFolder = None def
(self): self._tmpTestFolder = os.path.join(tempfile.gettempdir(), "unittest_%s_%s" % (self.__class__.__name__, str( uuid.uuid4() )[:8])) os.mkdir(self._tmpTestFolder) sys.path.append(self._tmpTestFolder) def tearDown(self): ...
setUp
identifier_name
__init__.py
import unittest, tempfile, uuid, os, shutil, sys class Test_CreateRemoveTempLocation(unittest.TestCase):
def setUp(self): self._tmpTestFolder = os.path.join(tempfile.gettempdir(), "unittest_%s_%s" % (self.__class__.__name__, str( uuid.uuid4() )[:8])) os.mkdir(self._tmpTestFolder) sys.path.append(self._tmpTestFolder) def tearDown(s...
def __init__(self, *args, **kwargs): super(Test_CreateRemoveTempLocation, self).__init__(*args, **kwargs) self._tmpTestFolder = None
random_line_split
QuickSort.py
""" Author: Maneesh Divana <mdaneeshd77@gmail.com> Interpreter: Python 3.6.8 Quick Sort Worst Case: O(n^2) Average Case: O(nlog n) Best Case: O(nlog n) """ from random import shuffle def partition(arr: list, left: int, right: int) -> int: """Partitions the given array based on a pivot element, then sorts the...
(arr: list, left: int, right: int) -> None: """Recursively partitions the given array and sorts based on QuickSort algorithm.""" if left < right: # Partition the array and get the partition index p_idx = partition(arr, left, right) # Recursively partition and sort the sub-arrays ...
qsort
identifier_name
QuickSort.py
""" Author: Maneesh Divana <mdaneeshd77@gmail.com> Interpreter: Python 3.6.8 Quick Sort Worst Case: O(n^2) Average Case: O(nlog n) Best Case: O(nlog n) """ from random import shuffle def partition(arr: list, left: int, right: int) -> int:
def qsort(arr: list, left: int, right: int) -> None: """Recursively partitions the given array and sorts based on QuickSort algorithm.""" if left < right: # Partition the array and get the partition index p_idx = partition(arr, left, right) # Recursively partition and sort the su...
"""Partitions the given array based on a pivot element, then sorts the sub-arrays and returns the partition index""" # Take the right most element as pivot pivot = arr[right] # i tracks the smallest element, currently invalid i = left - 1 for j in range(left, right): # Check if the cur...
identifier_body
QuickSort.py
""" Author: Maneesh Divana <mdaneeshd77@gmail.com> Interpreter: Python 3.6.8 Quick Sort Worst Case: O(n^2) Average Case: O(nlog n) Best Case: O(nlog n) """ from random import shuffle def partition(arr: list, left: int, right: int) -> int: """Partitions the given array based on a pivot element, then sorts the...
# One final swap to put pivot element at its correct position arr[i + 1], arr[right] = arr[right], arr[i + 1] # Return the partition index return i + 1 def qsort(arr: list, left: int, right: int) -> None: """Recursively partitions the given array and sorts based on QuickSort algorithm.""" ...
if arr[j] <= pivot: i += 1 # If so, swap the smallest element and the current element arr[i], arr[j] = arr[j], arr[i]
conditional_block
QuickSort.py
""" Author: Maneesh Divana <mdaneeshd77@gmail.com> Interpreter: Python 3.6.8 Quick Sort Worst Case: O(n^2) Average Case: O(nlog n) Best Case: O(nlog n) """ from random import shuffle def partition(arr: list, left: int, right: int) -> int: """Partitions the given array based on a pivot element, then sorts the...
print("\nSorted array:", ARR, "\n")
random_line_split
propertoolbar.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _toolbar = require('./components/toolbar'); var _toolbar2 = _interopRequireDefault(_toolbar); var _item = require('./components/item'); var _item2 = _interopRequireDefault(_item); var _button = require('./components/items/button'); ...
(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } if (process.env.APP_ENV === 'browser-env') { require("../css/style.scss"); } exports['default'] = ProperToolbar = { Toolbar: _toolbar2['default'], Item: _item2['default'], Button: _button2['default'], Separator: _separator2['default'], Link: _li...
_interopRequireDefault
identifier_name
propertoolbar.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _toolbar = require('./components/toolbar'); var _toolbar2 = _interopRequireDefault(_toolbar); var _item = require('./components/item'); var _item2 = _interopRequireDefault(_item); var _button = require('./components/items/button'); ...
exports['default'] = ProperToolbar = { Toolbar: _toolbar2['default'], Item: _item2['default'], Button: _button2['default'], Separator: _separator2['default'], Link: _link2['default'] }; module.exports = exports['default'];
{ require("../css/style.scss"); }
conditional_block
propertoolbar.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _toolbar = require('./components/toolbar'); var _toolbar2 = _interopRequireDefault(_toolbar); var _item = require('./components/item'); var _item2 = _interopRequireDefault(_item); var _button = require('./components/items/button'); ...
Separator: _separator2['default'], Link: _link2['default'] }; module.exports = exports['default'];
random_line_split
propertoolbar.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _toolbar = require('./components/toolbar'); var _toolbar2 = _interopRequireDefault(_toolbar); var _item = require('./components/item'); var _item2 = _interopRequireDefault(_item); var _button = require('./components/items/button'); ...
if (process.env.APP_ENV === 'browser-env') { require("../css/style.scss"); } exports['default'] = ProperToolbar = { Toolbar: _toolbar2['default'], Item: _item2['default'], Button: _button2['default'], Separator: _separator2['default'], Link: _link2['default'] }; module.exports = exports['default'];
{ return obj && obj.__esModule ? obj : { 'default': obj }; }
identifier_body
errorRibbonPlotMulti.py
import sys import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages sys.path.append('../../') from util import readCSVToMatrix file_path = sys.argv[1] file = open(file_path) def
(x, mu, std, metric, pp): fig, ax = plt.subplots(1) ax.fill_between(x, mu+std, mu-std, facecolor='blue', alpha=0.5, label='$\pm \sigma$') ax.plot(data[:,0], mu, alpha=0.7, label='$\mu$', linewidth=2.0) # ax.set_title(metric + ' convergence', fontsize=22) ax.legend(loc='upper right') ax.set_xlabel('number of scena...
plotErrorRibbon
identifier_name
errorRibbonPlotMulti.py
import sys import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages sys.path.append('../../') from util import readCSVToMatrix file_path = sys.argv[1] file = open(file_path) def plotErrorRibbon(x, mu, std, metric, pp): fig, ax = plt.subplots(1) ax.fill_between(x, mu...
print file data = readCSVToMatrix(file, delimiter=',') print data pp = PdfPages("convergence" + '_plots.pdf') plotErrorRibbon(data[:,0], data[:,1], data[:,5], 'coverage', pp) plotErrorRibbon(data[:,0], data[:,2], data[:,6], 'time', pp) plotErrorRibbon(data[:,0], data[:,3], data[:,7], 'distance', pp) plotE...
conditional_block
errorRibbonPlotMulti.py
import sys import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages sys.path.append('../../') from util import readCSVToMatrix file_path = sys.argv[1] file = open(file_path)
def plotErrorRibbon(x, mu, std, metric, pp): fig, ax = plt.subplots(1) ax.fill_between(x, mu+std, mu-std, facecolor='blue', alpha=0.5, label='$\pm \sigma$') ax.plot(data[:,0], mu, alpha=0.7, label='$\mu$', linewidth=2.0) # ax.set_title(metric + ' convergence', fontsize=22) ax.legend(loc='upper right') ax.set_xlab...
random_line_split
errorRibbonPlotMulti.py
import sys import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages sys.path.append('../../') from util import readCSVToMatrix file_path = sys.argv[1] file = open(file_path) def plotErrorRibbon(x, mu, std, metric, pp):
if __name__ == '__main__': print file data = readCSVToMatrix(file, delimiter=',') print data pp = PdfPages("convergence" + '_plots.pdf') plotErrorRibbon(data[:,0], data[:,1], data[:,5], 'coverage', pp) plotErrorRibbon(data[:,0], data[:,2], data[:,6], 'time', pp) plotErrorRibbon(data[:,0], data[:,3]...
fig, ax = plt.subplots(1) ax.fill_between(x, mu+std, mu-std, facecolor='blue', alpha=0.5, label='$\pm \sigma$') ax.plot(data[:,0], mu, alpha=0.7, label='$\mu$', linewidth=2.0) # ax.set_title(metric + ' convergence', fontsize=22) ax.legend(loc='upper right') ax.set_xlabel('number of scenario samples', fontsize=20) ...
identifier_body
test_build_py.py
"""Tests for distutils.command.build_py.""" import os import sys import StringIO import unittest from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError from distutils.tests import support class
(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_package_data(self): sources = self.mkdtemp() f = open(os.path.join(sources, "__init__.py"), "w") f.write("# Pretend this is a package.") f.close() ...
BuildPyTestCase
identifier_name
test_build_py.py
"""Tests for distutils.command.build_py.""" import os import sys import StringIO import unittest from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError from distutils.tests import support class BuildPyTestCase(support.Te...
def test_suite(): return unittest.makeSuite(BuildPyTestCase) if __name__ == "__main__": unittest.main(defaultTest="test_suite")
pkg_dir, dist = self.create_dist() cmd = build_py(dist) cmd.compile = 1 cmd.optimize = 1 old_dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True try: cmd.byte_compile([]) finally: sys.dont_write_bytecode ...
identifier_body
test_build_py.py
"""Tests for distutils.command.build_py.""" import os import sys import StringIO import unittest from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError
class BuildPyTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_package_data(self): sources = self.mkdtemp() f = open(os.path.join(sources, "__init__.py"), "w") f.write("# Pretend this is a package.") ...
from distutils.tests import support
random_line_split
test_build_py.py
"""Tests for distutils.command.build_py.""" import os import sys import StringIO import unittest from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError from distutils.tests import support class BuildPyTestCase(support.Te...
unittest.main(defaultTest="test_suite")
conditional_block
upload.py
= "/var/www/calibre-ebook.com" DOWNLOADS = PREFIX+"/htdocs/downloads" BETAS = DOWNLOADS +'/betas' USER_MANUAL = '/var/www/localhost/htdocs/' HTML2LRF = "calibre/ebooks/lrf/html/demo" TXT2LRF = "src/calibre/ebooks/lrf/txt/demo" STAGING_HOST = '67.207.135.179' STAGING_USER = 'root' STAGING_DIR = '/root/staging' def in...
(self, opts): opts.replace = True def run(self, opts): for x in installers(): if os.path.exists(x): os.remove(x) # }}} # Data {{{ def get_google_data(): with open(os.path.expanduser('~/work/kde/conf/googlecodecalibre'), 'rb') as f: gc_password, ga_un, pw = f...
pre_sub_commands
identifier_name
upload.py
" DOWNLOADS = PREFIX+"/htdocs/downloads" BETAS = DOWNLOADS +'/betas' USER_MANUAL = '/var/www/localhost/htdocs/' HTML2LRF = "calibre/ebooks/lrf/html/demo" TXT2LRF = "src/calibre/ebooks/lrf/txt/demo" STAGING_HOST = '67.207.135.179' STAGING_USER = 'root' STAGING_DIR = '/root/staging' def installers(): installers = l...
with open(f, 'wb') as f: f.write(os.urandom(100)) f.write(b'a'*1000000)
conditional_block
upload.py
= "/var/www/calibre-ebook.com" DOWNLOADS = PREFIX+"/htdocs/downloads" BETAS = DOWNLOADS +'/betas' USER_MANUAL = '/var/www/localhost/htdocs/' HTML2LRF = "calibre/ebooks/lrf/html/demo" TXT2LRF = "src/calibre/ebooks/lrf/txt/demo" STAGING_HOST = '67.207.135.179' STAGING_USER = 'root' STAGING_DIR = '/root/staging' def in...
# }}} class UploadToServer(Command): # {{{ description = 'Upload miscellaneous data to calibre server' def run(self, opts): check_call('ssh divok rm -f %s/calibre-\*.tar.xz'%DOWNLOADS, shell=True) #check_call('scp dist/calibre-*.tar.xz divok:%s/'%DOWNLOADS, shell=True) check_call('gp...
check_call( '''ebook-convert %s/demo.html /tmp/html2lrf.lrf ''' '''--title='Demonstration of html2lrf' --authors='Kovid Goyal' ''' '''--header ''' '''--serif-family "/usr/share/fonts/corefonts, Times New Roman" ''' '''--mono-family "/usr/share/fonts/corefonts, And...
identifier_body
upload.py
return 'Windows installer' if fname.endswith('.dmg'): return 'OS X dmg' if fname.endswith('.zip'): return 'Calibre Portable' return 'Unknown file' class ReUpload(Command): # {{{ description = 'Re-uplaod any installers present in dist/' sub_commands = ['upload_installers'] ...
print ('\nDoing re-upload') run_remote_upload(['--replace']+args) raw_input('Press Enter to proceed:')
random_line_split
AddressIconMenuItem.tsx
import { Account } from '@emeraldplatform/ui'; import MenuItem from '@material-ui/core/MenuItem'; import * as React from 'react'; interface Props { onChange: Function; address: string; } class AddressIconMenuItem extends React.Component<Props> { public static muiName = 'MenuItem'; constructor (props: Props)
public onClick () { this.props.onChange(this.props.address); } public render () { const menuStyle = { paddingBottom: '5px', paddingTop: '5px', minHeight: 'auto', height: 'auto' }; return ( <MenuItem onClick={this.onClick} style={menuStyle}> <Account ...
{ super(props); this.onClick = this.onClick.bind(this); }
identifier_body
AddressIconMenuItem.tsx
import { Account } from '@emeraldplatform/ui'; import MenuItem from '@material-ui/core/MenuItem';
} class AddressIconMenuItem extends React.Component<Props> { public static muiName = 'MenuItem'; constructor (props: Props) { super(props); this.onClick = this.onClick.bind(this); } public onClick () { this.props.onChange(this.props.address); } public render () { const menuStyle = { ...
import * as React from 'react'; interface Props { onChange: Function; address: string;
random_line_split
AddressIconMenuItem.tsx
import { Account } from '@emeraldplatform/ui'; import MenuItem from '@material-ui/core/MenuItem'; import * as React from 'react'; interface Props { onChange: Function; address: string; } class AddressIconMenuItem extends React.Component<Props> { public static muiName = 'MenuItem'; constructor (props: Props) ...
() { this.props.onChange(this.props.address); } public render () { const menuStyle = { paddingBottom: '5px', paddingTop: '5px', minHeight: 'auto', height: 'auto' }; return ( <MenuItem onClick={this.onClick} style={menuStyle}> <Account identityProps={...
onClick
identifier_name
C_AniLinearGradient.js
/** * Created by hebao on 2017/5/27. * this component's main job is to change LinearGradient in animated , * relay on two lib: * 1 react-native-linear-gradient // realize linear gradient Git: https://github.com/react-native-community/react-native-linear-gradient * Git: https://github.com/react-native-community...
* if provide one argument, it will set to be the targetColors * if provide two arguments, it will set to be the initColors and targetColors */ startChange() { let _argArrLength = arguments.length; let {initColors} = this.props; let {gradientNum} = this.state; if (_argArrLength == 1) { t...
* to start gradient linear animation, * have one or two argument
random_line_split
C_AniLinearGradient.js
/** * Created by hebao on 2017/5/27. * this component's main job is to change LinearGradient in animated , * relay on two lib: * 1 react-native-linear-gradient // realize linear gradient Git: https://github.com/react-native-community/react-native-linear-gradient * Git: https://github.com/react-native-community...
shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } componentWillUnmount() { clearTimeout(this._changeColorHandle); } /** * this component's API * to start gradient linear animation, * have one or two argument * if provide one argument, it...
{ super(props); let _gradientNum = Math.ceil(props.aniDuration / this._gradientTime); this.state = { startColors: Chroma.scale([props.initColors[0], props.targetColors[0]]).colors(_gradientNum), endColors: Chroma.scale([props.initColors[1], props.targetColors[1]]).colors(_gradientNum), gra...
identifier_body
C_AniLinearGradient.js
/** * Created by hebao on 2017/5/27. * this component's main job is to change LinearGradient in animated , * relay on two lib: * 1 react-native-linear-gradient // realize linear gradient Git: https://github.com/react-native-community/react-native-linear-gradient * Git: https://github.com/react-native-community...
else { this.state.colorIndex = 0; } }); } render() { Util.log(debugKeyWord + 'render!!!'); let {startColors, endColors, colorIndex} = this.state; return ( <LinearGradient start={{x: 0.0, y: 0.0}} end={{x: 1.0, y: 1.0}} colors={[startColors[colorIndex], end...
{ this._changeColorHandle = setTimeout(() => { this.startAni(); }, this._gradientTime); }
conditional_block
C_AniLinearGradient.js
/** * Created by hebao on 2017/5/27. * this component's main job is to change LinearGradient in animated , * relay on two lib: * 1 react-native-linear-gradient // realize linear gradient Git: https://github.com/react-native-community/react-native-linear-gradient * Git: https://github.com/react-native-community...
(props) { super(props); let _gradientNum = Math.ceil(props.aniDuration / this._gradientTime); this.state = { startColors: Chroma.scale([props.initColors[0], props.targetColors[0]]).colors(_gradientNum), endColors: Chroma.scale([props.initColors[1], props.targetColors[1]]).colors(_gradientNum), ...
constructor
identifier_name
main.rs
#![allow(clippy::unnecessary_fold)] fn
() { let numbers = [1, 2, 3, 4, 5]; let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); } #[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a ...
main
identifier_name
main.rs
#![allow(clippy::unnecessary_fold)] fn main()
#[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); } #[test] fn test_product() { let product = [1, 2, 3, 4, 5].iter().fold(1, |a, n| a * n); assert_eq!(product, 120); } }
{ let numbers = [1, 2, 3, 4, 5]; let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); }
identifier_body
main.rs
#![allow(clippy::unnecessary_fold)]
let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); } #[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); }...
fn main() { let numbers = [1, 2, 3, 4, 5];
random_line_split
automlapi.ts
// Controls model type. For more options, see: // https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models#imageclassificationmodelmetadata const DEFAULT_MODEL_TYPE = 'mobile-high-accuracy-1'; const DEFAULT_TRAIN_BUDGET = 1; const DATASET_NAME_REGEX = new RegExp('^[a-zA-Z_0-9]...
/** * List all datasets */ app.get('/datasets', async (req, res, next) => { try { const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] }); const url = `${AUTOML_API_URL}/datasets`; const resp = await authClient.request({ url }); res.json(resp.data); } catch (err) { console.er...
{ const inputConfig = { gcsSource: { inputUris: [`${AUTOML_BUCKET_URL}/${displayName}/${labels}`], }, }; return client .importData({ name, inputConfig }) .then((responses: any[]) => responses[1]); // initial api response with operation metadata }
identifier_body
automlapi.ts
(); // Controls model type. For more options, see: // https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models#imageclassificationmodelmetadata const DEFAULT_MODEL_TYPE = 'mobile-high-accuracy-1'; const DEFAULT_TRAIN_BUDGET = 1; const DATASET_NAME_REGEX = new RegExp('^[a-zA-Z...
(automlId: string): Promise<string | null> { return client.listDatasets({ parent }).then((responses: any[]) => { const datasets = responses[0]; for (const dataset of datasets) { if (extractIdFromName(dataset['name']) === automlId) { return dataset['name']; } } return null; }); } ...
getDatasetName
identifier_name
automlapi.ts
// Controls model type. For more options, see: // https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models#imageclassificationmodelmetadata const DEFAULT_MODEL_TYPE = 'mobile-high-accuracy-1'; const DEFAULT_TRAIN_BUDGET = 1; const DATASET_NAME_REGEX = new RegExp('^[a-zA-Z_0-9]...
if (!displayName.match(DATASET_NAME_REGEX)) { res .status(400) .send( 'The displayName contains a not allowed character, the' + ' only allowed ones are ASCII Latin letters A-Z and a-z, an underscore (_),' + ' and ASCII digits 0-9' ); return; ...
{ res.status(400).send('Expected a dataset `displayName`'); return; }
conditional_block
automlapi.ts
(); // Controls model type. For more options, see: // https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models#imageclassificationmodelmetadata const DEFAULT_MODEL_TYPE = 'mobile-high-accuracy-1'; const DEFAULT_TRAIN_BUDGET = 1; const DATASET_NAME_REGEX = new RegExp('^[a-zA-Z...
* * Note the model will be generated in a folder with timestamp as name. For * more, refer to * https://cloud.google.com/vision/automl/alpha/docs/deploy#deployment_on_mobile_models_not_core_ml */ app.post('/export', async (req, res, next) => { const { modelId, gcsPath } = req.body; if (!modelId) { res.stat...
* Exports a model in tflite format to a gcspath * * modelId - AutoML model ID: "ICN1119584480450950787", * gcsPath - Path to which model is exported * "gs://${AUTOML_BUCKET}/models/on-device/<folder_name>"
random_line_split
openhmis.js
for template tags. _.templateSettings = { evaluate: /<\?(.+?)\?>/g, interpolate: /<\?=(.+?)\?>/g }; var openhmis = window.openhmis || {}; openhmis.templates = {}; openhmis.url.getPage = function (moduleBaseName) { return openhmis.url.page + openhmis.url[moduleBaseName]; }; //TODO: Better sys...
}; if (!(model instanceof Backbone.Model)) { if (model.responseText) handleErrorResp(model.responseText); else handleErrorResp(model); } else if (resp !== undefined) { handleErrorResp(resp.responseText); //var str = ""; //for (var i in resp) { // if (str.length > 0) str += "...
{ var firstLfPos = o.detail.indexOf('\n'); if (firstLfPos !== -1) o.detail = o.detail.substring(0, firstLfPos); alert('An error occurred during the request.\n\n' + o.message + '\n\nCode: ' + o.code + '\n\n' + o.detail); }
conditional_block
openhmis.js
openhmis.url.backboneBase + 'js/lib/jquery', openhmis.url.backboneBase + 'js/lib/underscore', openhmis.url.backboneBase + 'js/lib/backbone', openhmis.url.backboneBase + 'js/lib/i18n', openhmis.url.backboneBase + 'js/lib/backbone-forms' ], function($, _, Backbone, __) { // Use <? ?> for template tags. _...
define(openhmis.url.backboneBase + "js/openhmis", [
random_line_split
fetchImage.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var bufferToImage_1 = require("./bufferToImage"); var fetchOrThrow_1 = require("./fetchOrThrow"); function fetchImage(uri)
exports.fetchImage = fetchImage; //# sourceMappingURL=fetchImage.js.map
{ return tslib_1.__awaiter(this, void 0, void 0, function () { var res, blob; return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, fetchOrThrow_1.fetchOrThrow(uri)]; case 1: res = _a.sent(); ...
identifier_body
fetchImage.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var bufferToImage_1 = require("./bufferToImage"); var fetchOrThrow_1 = require("./fetchOrThrow"); function fetchImage(uri) { return tslib_1.__awaiter(this, void 0, void 0, function () { var res, blob...
return [2 /*return*/, bufferToImage_1.bufferToImage(blob)]; } }); }); } exports.fetchImage = fetchImage; //# sourceMappingURL=fetchImage.js.map
{ throw new Error("fetchImage - expected blob type to be of type image/*, instead have: " + blob.type + ", for url: " + res.url); }
conditional_block
fetchImage.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var bufferToImage_1 = require("./bufferToImage"); var fetchOrThrow_1 = require("./fetchOrThrow"); function fetchImage(uri) { return tslib_1.__awaiter(this, void 0, void 0, function () { var res, blob...
}); } exports.fetchImage = fetchImage; //# sourceMappingURL=fetchImage.js.map
} return [2 /*return*/, bufferToImage_1.bufferToImage(blob)]; } });
random_line_split
fetchImage.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var bufferToImage_1 = require("./bufferToImage"); var fetchOrThrow_1 = require("./fetchOrThrow"); function
(uri) { return tslib_1.__awaiter(this, void 0, void 0, function () { var res, blob; return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, fetchOrThrow_1.fetchOrThrow(uri)]; case 1: res = _a.se...
fetchImage
identifier_name
component-names-generator.ts
import fs = require('fs'); import path = require('path'); export default class ComponentNamesGenerator { private _encoding = 'utf8'; private _config; constructor(config) { this._config = config; } prepareTagName(fileName: string) { return ` '${fileName.replace('.ts', '')}'`; ...
generate() { let directoryPath = this._config.componentFilesPath; let files = fs.readdirSync(directoryPath); let fileList = files .filter(fileName => !fs.lstatSync(path.join(directoryPath, fileName)).isFile() && this.validateFileName(fileName)) .map(fileName => this....
validateFileName(fileName: string) { return this._config.excludedFileNames.indexOf(fileName) < 0; }
random_line_split
component-names-generator.ts
import fs = require('fs'); import path = require('path'); export default class ComponentNamesGenerator { private _encoding = 'utf8'; private _config; constructor(config) { this._config = config; } prepareTagName(fileName: string) { return ` '${fileName.replace('.ts', '')}'`; ...
generate() { let directoryPath = this._config.componentFilesPath; let files = fs.readdirSync(directoryPath); let fileList = files .filter(fileName => !fs.lstatSync(path.join(directoryPath, fileName)).isFile() && this.validateFileName(fileName)) .map(fileName => this...
{ return this._config.excludedFileNames.indexOf(fileName) < 0; }
identifier_body
component-names-generator.ts
import fs = require('fs'); import path = require('path'); export default class ComponentNamesGenerator { private _encoding = 'utf8'; private _config;
(config) { this._config = config; } prepareTagName(fileName: string) { return ` '${fileName.replace('.ts', '')}'`; } validateFileName(fileName: string) { return this._config.excludedFileNames.indexOf(fileName) < 0; } generate() { let directoryPath = this._co...
constructor
identifier_name
generate_gles_conformance_tests.py
import os import re import sys def ReadFileAsLines(filename): """Reads a file, removing blank lines and lines that start with #""" file = open(filename, "r") raw_lines = file.readlines() file.close() lines = [] for line in raw_lines: line = line.strip() if len(line) > 0 and not...
def main(argv): tests = GenerateTestList(argv[0], argv[1]) tests.sort() output = open(argv[2], 'wb') GenerateTests(output, tests) output.close() return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
tests = [] fileName, fileExtension = os.path.splitext(sourceFile) if fileExtension == ".run": lines = ReadFileAsLines(sourceFile) for line in lines: tests += GenerateTestList(os.path.join(os.path.dirname(sourceFile), line), rootDir) elif fileExtension == ".test": tests.ap...
identifier_body
generate_gles_conformance_tests.py
import os import re import sys def ReadFileAsLines(filename): """Reads a file, removing blank lines and lines that start with #""" file = open(filename, "r") raw_lines = file.readlines() file.close() lines = [] for line in raw_lines: line = line.strip() if len(line) > 0 and not...
(testName): return testName[:testName.find("/")] def GetTestName(testName): replacements = {".test": "", ".": "_"} splitTestName = testName.split("/") cleanName = splitTestName[-2] + "_" + splitTestName[-1] for replaceKey in replacements: cleanName = cleanName.replace(replaceKey, replaceme...
GetSuiteName
identifier_name
generate_gles_conformance_tests.py
import os import re import sys def ReadFileAsLines(filename): """Reads a file, removing blank lines and lines that start with #""" file = open(filename, "r") raw_lines = file.readlines() file.close() lines = [] for line in raw_lines: line = line.strip() if len(line) > 0 and not...
def GenerateTestList(sourceFile, rootDir): tests = [] fileName, fileExtension = os.path.splitext(sourceFile) if fileExtension == ".run": lines = ReadFileAsLines(sourceFile) for line in lines: tests += GenerateTestList(os.path.join(os.path.dirname(sourceFile), line), rootDir) ...
outFile.write(" run(\"" + test + "\");\n") outFile.write("}\n\n")
random_line_split
generate_gles_conformance_tests.py
import os import re import sys def ReadFileAsLines(filename): """Reads a file, removing blank lines and lines that start with #""" file = open(filename, "r") raw_lines = file.readlines() file.close() lines = [] for line in raw_lines:
return lines def GetSuiteName(testName): return testName[:testName.find("/")] def GetTestName(testName): replacements = {".test": "", ".": "_"} splitTestName = testName.split("/") cleanName = splitTestName[-2] + "_" + splitTestName[-1] for replaceKey in replacements: cleanName = cle...
line = line.strip() if len(line) > 0 and not line.startswith("#"): lines.append(line)
conditional_block
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { p...
(op: *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PySlice_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, leng...
PySlice_Check
identifier_name