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
fakead3p.js
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
}
{ dev().assert(data.container == data.ad_container, 'wrong container'); }
conditional_block
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
(ty: LLVMTypeRef) -> Self { assert!(!ty.is_null()); Type { ty, _marker: PhantomData, } } // REVIEW: LLVM 5.0+ seems to have removed this function in release mode // and so will fail to link when used. I've decided to remove it from 5.0+ // for now. We sh...
new
identifier_name
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
fn size_of(self) -> Option<IntValue<'ctx>> { if !self.is_sized() { return None; } unsafe { Some(IntValue::new(LLVMSizeOf(self.ty))) } } fn print_to_string(self) -> LLVMString { unsafe { LLVMString::new(LLVMPrintTypeToString(self...
{ unsafe { LLVMTypeIsSized(self.ty) == 1 } }
identifier_body
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
unsafe { Some(IntValue::new(LLVMSizeOf(self.ty))) } } fn print_to_string(self) -> LLVMString { unsafe { LLVMString::new(LLVMPrintTypeToString(self.ty)) } } pub fn get_element_type(self) -> AnyTypeEnum<'ctx> { unsafe { AnyTyp...
{ return None; }
conditional_block
mod.rs
//! A type is a classification which determines how data is used. #[deny(missing_docs)] mod array_type; mod enums; #[deny(missing_docs)] mod float_type; #[deny(missing_docs)] mod fn_type; #[deny(missing_docs)] mod int_type; #[deny(missing_docs)] mod metadata_type; #[deny(missing_docs)] mod ptr_type; #[deny(missing_doc...
_ => LLVMConstNull(self.ty) } } } fn ptr_type(self, address_space: AddressSpace) -> PointerType<'ctx> { unsafe { PointerType::new(LLVMPointerType(self.ty, address_space as u32)) } } fn vec_type(self, size: u32) -> VectorType<'ctx> { ...
unsafe { match LLVMGetTypeKind(self.ty) { LLVMTypeKind::LLVMMetadataTypeKind => LLVMConstPointerNull(self.ty),
random_line_split
cms_plugins.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import get_language, to_locale from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .conf import settings from .models import FacebookComments class FacebookCommentsPlugin(CMSPluginBase):...
: css = { 'all': ('css/djangocms_fbcomments/admin/djangocms_fbcomments.css',) } js = ('js/djangocms_fbcomments/admin/djangocms_fbcomments.js',) plugin_pool.register_plugin(FacebookCommentsPlugin)
Media
identifier_name
cms_plugins.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import get_language, to_locale from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .conf import settings from .models import FacebookComments class FacebookCommentsPlugin(CMSPluginBase):...
return context class Media: css = { 'all': ('css/djangocms_fbcomments/admin/djangocms_fbcomments.css',) } js = ('js/djangocms_fbcomments/admin/djangocms_fbcomments.js',) plugin_pool.register_plugin(FacebookCommentsPlugin)
context['page_url'] = request.build_absolute_uri(location=request.path_info)
random_line_split
cms_plugins.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import get_language, to_locale from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .conf import settings from .models import FacebookComments class FacebookCommentsPlugin(CMSPluginBase):...
plugin_pool.register_plugin(FacebookCommentsPlugin)
css = { 'all': ('css/djangocms_fbcomments/admin/djangocms_fbcomments.css',) } js = ('js/djangocms_fbcomments/admin/djangocms_fbcomments.js',)
identifier_body
ethcore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
(&self, _: Params) -> Result<Value, Error> { to_value(&take_weak!(self.miner).minimal_gas_price()) } fn extra_data(&self, _: Params) -> Result<Value, Error> { to_value(&Bytes::new(take_weak!(self.miner).extra_data())) } fn gas_floor_target(&self, _: Params) -> Result<Value, Error> { to_value(&take_weak!(sel...
min_gas_price
identifier_name
ethcore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
fn min_gas_price(&self, _: Params) -> Result<Value, Error> { to_value(&take_weak!(self.miner).minimal_gas_price()) } fn extra_data(&self, _: Params) -> Result<Value, Error> { to_value(&Bytes::new(take_weak!(self.miner).extra_data())) } fn gas_floor_target(&self, _: Params) -> Result<Value, Error> { to_va...
{ from_params::<(Address,)>(params).and_then(|(author,)| { take_weak!(self.miner).set_author(author); to_value(&true) }) }
identifier_body
ethcore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
pub struct EthcoreClient<M> where M: MinerService, { miner: Weak<M>, } impl<M> EthcoreClient<M> where M: MinerService, { /// Creates new `EthcoreClient`. pub fn new(miner: &Arc<M>) -> Self { EthcoreClient { miner: Arc::downgrade(miner) } } } impl<M> Ethcore for EthcoreClient<M> where M: MinerService + ...
use v1::traits::Ethcore; use v1::types::Bytes; /// Ethcore implementation.
random_line_split
meteolux.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.compileSituation = exports.current = exports.get = undefined; var _requests = require('../../requests'); function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (res...
return step("next"); }); }; } const get = exports.get = (() => { var _ref = _asyncToGenerator(function* () { var raw = yield (0, _requests.meteolux)(); var lines = raw.trim().split('\r\n'); var result = {}; for (var i = 0; i < lines.length; i++) { var lineParts = line...
{ try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } }
identifier_body
meteolux.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.compileSituation = exports.current = exports.get = undefined; var _requests = require('../../requests'); function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (res...
(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } const get = ...
step
identifier_name
meteolux.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.compileSituation = exports.current = exports.get = undefined; var _requests = require('../../requests'); function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (res...
else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } const get = exports.get = (() => { var _ref = _asyncToGenerator(function* () { var raw = yield (0, _requests.meteolux)(); var lines = raw...
{ resolve(value); }
conditional_block
meteolux.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.compileSituation = exports.current = exports.get = undefined; var _requests = require('../../requests'); function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (res...
humidity: parseInt(situation.humidity), temp_min: null, temp_max: null }, visibility: visibility, wind: { speed: parseInt(situation.wind_force), deg: windDirection }, clouds: { all: null }, dt...
base: null, main: { temp: parseInt(situation.temp), pressure: parseInt(situation.pressure),
random_line_split
dc_weather_data.py
from cdo_api_py import Client import pandas as pd from datetime import datetime from pprint import pprint # initialize a client with a developer token , # note 5 calls per second and 1000 calls per day limit for each token token = "my token here!" my_client = Client(token, default_units=None, default_limit=1000) # the...
extent = { "north": 39.14, "south": 38.68, "east": -76.65, "west": -77.35, } # lets define the date range we're interested in as well, December 2016 startdate = datetime(2016, 12, 1) enddate = datetime(2016, 12, 31) # after examining the available datasets, we decided 'GHCND' is the one we want, # an...
# there are more than 1000 datatypes, but you can see them all with pprint(my_client.list_datatypes()) # define the extent we are interested in. in this case the DC metro area.
random_line_split
dc_weather_data.py
from cdo_api_py import Client import pandas as pd from datetime import datetime from pprint import pprint # initialize a client with a developer token , # note 5 calls per second and 1000 calls per day limit for each token token = "my token here!" my_client = Client(token, default_units=None, default_limit=1000) # the...
# Now we can do whatever we want with our big dataframe. Lets sort it by date and save it print(big_df) big_df = big_df.sort_values(by='date').reset_index() big_df.to_csv('dc_ghcnd_example_output.csv')
station_data = my_client.get_data_by_station( datasetid=datasetid, stationid=station['id'], # remember this is a pandas dataframe startdate=startdate, enddate=enddate, return_dataframe=True, # this defaults to True include_station_meta=True # flatten station metadat...
conditional_block
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, o...
Err(format!("RPC URL '{}' could not be parsed.", v)) } pub fn build_cli<'a>() -> App<'a, 'a> { App::new(NAME) .version(VERSION) .author(AUTHORS) .about(DESCRIPTION) .arg( Arg::with_name("uname") .short("u") .long("username") ...
{ return Ok(()); }
conditional_block
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, o...
pub fn build_cli<'a>() -> App<'a, 'a> { App::new(NAME) .version(VERSION) .author(AUTHORS) .about(DESCRIPTION) .arg( Arg::with_name("uname") .short("u") .long("username") .help("Bitcoin Core RPC username.") ...
{ if Uri::from_str(&v).is_ok() { return Ok(()); } Err(format!("RPC URL '{}' could not be parsed.", v)) }
identifier_body
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, o...
(v: String) -> Result<(), String> { if Uri::from_str(&v).is_ok() { return Ok(()); } Err(format!("RPC URL '{}' could not be parsed.", v)) } pub fn build_cli<'a>() -> App<'a, 'a> { App::new(NAME) .version(VERSION) .author(AUTHORS) .about(DESCRIPTION) .arg( ...
validate_uri
identifier_name
cli.rs
// bitcoin-donation - Generate a Bitcoin address for donations. // Copyright (C) 2017 Cooper Paul EdenDay // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, o...
.validator(validate_uri), ) .arg( Arg::with_name("no_conf") .short("n") .long("no-config") .help("Ignore the RPC password from the Bitcoin Core config file") .takes_value(false), ) }
.multiple(false) .empty_values(false) .value_name("URL") .default_value("http://localhost:18332/")
random_line_split
testTFIDF.py
from tfidf import * import psycopg2 import psycopg2.extensions import math def cos_sim(A,B): def dot_product(a,b): sum = 0.0 for key in a.keys():
return sum return dot_product(A,B)/(math.sqrt(dot_product(A,A)) * math.sqrt(dot_product(B,B))) conn = psycopg2.connect("host=localhost dbname=SOFTFile user=AUREA password=AUREA") conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) c = conn.cursor() qry = "SELECT dataset_id, dataset_ti...
if key in b: sum += a[key]*b[key]
conditional_block
testTFIDF.py
from tfidf import * import psycopg2 import psycopg2.extensions import math def cos_sim(A,B): def
(a,b): sum = 0.0 for key in a.keys(): if key in b: sum += a[key]*b[key] return sum return dot_product(A,B)/(math.sqrt(dot_product(A,A)) * math.sqrt(dot_product(B,B))) conn = psycopg2.connect("host=localhost dbname=SOFTFile user=AUREA password=AUREA") conn.set_iso...
dot_product
identifier_name
testTFIDF.py
from tfidf import * import psycopg2 import psycopg2.extensions
def dot_product(a,b): sum = 0.0 for key in a.keys(): if key in b: sum += a[key]*b[key] return sum return dot_product(A,B)/(math.sqrt(dot_product(A,A)) * math.sqrt(dot_product(B,B))) conn = psycopg2.connect("host=localhost dbname=SOFTFile user=AUREA password=A...
import math def cos_sim(A,B):
random_line_split
testTFIDF.py
from tfidf import * import psycopg2 import psycopg2.extensions import math def cos_sim(A,B): def dot_product(a,b):
return dot_product(A,B)/(math.sqrt(dot_product(A,A)) * math.sqrt(dot_product(B,B))) conn = psycopg2.connect("host=localhost dbname=SOFTFile user=AUREA password=AUREA") conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) c = conn.cursor() qry = "SELECT dataset_id, dataset_title, dataset_descri...
sum = 0.0 for key in a.keys(): if key in b: sum += a[key]*b[key] return sum
identifier_body
rectangle_overlap.py
import numpy as np template = np.zeros((500,500,3),np.uint8) template[:,:,0] = 255 template[:,:,1] = 255 template[:,:,2] = 255 x = [50,250,250,50,50] y = [50,50,250,250,50] cnt = np.asarray(zip(x,y)) cv2.drawContours(template,[cnt],0,0,1) x = [100,200,200,100,100] y = [300,300,150,150,300] cnt = np.asarray(zip(x,y...
import cv2
random_line_split
asteroid-calendar.el.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="el">
<location filename="../src/EventDialog.qml" line="43"/> <source>New Event</source> <translation>Νέο Συμβάν</translation> </message> <message id="id-edit-event"> <location filename="../src/EventDialog.qml" line="45"/> <source>Edit Event</source> <translation>Επεξερ...
<context> <name></name> <message id="id-new-event">
random_line_split
test_customer_information.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import pytest from django.conf impo...
# Test POSTing form = extract_form_fields(soup) new_email = "nyyppa@example.shoop.io" form["contact-email"] = new_email form["contact-country"] = "FI" for prefix in ("billing", "shipping"): form["%s-city" % prefix] = "test-city" form["%s-email" % prefix] = new_email form...
assert soup.find(attrs={"name": "contact-name"})["value"] == user.get_full_name()
random_line_split
test_customer_information.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import pytest from django.conf impo...
et_default_shop() # Front middleware needs a Shop to exists response = SmartClient().get(reverse("shoop:customer_edit"), follow=False) assert response.status_code == 302 # Redirection ("Found") assert resolve_url(settings.LOGIN_URL) in response.url
identifier_body
test_customer_information.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import pytest from django.conf impo...
): get_default_shop() # Front middleware needs a Shop to exists response = SmartClient().get(reverse("shoop:customer_edit"), follow=False) assert response.status_code == 302 # Redirection ("Found") assert resolve_url(settings.LOGIN_URL) in response.url
est_customer_edit_redirects_to_login_if_not_logged_in(
identifier_name
test_customer_information.py
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import pytest from django.conf impo...
response, soup = client.response_and_soup(customer_edit_url, form, "post") assert response.status_code == 302 assert get_user_model().objects.get(pk=user.pk).email == new_email @pytest.mark.django_db def test_customer_edit_redirects_to_login_if_not_logged_in(): get_default_shop() # Front middleware...
orm["%s-city" % prefix] = "test-city" form["%s-email" % prefix] = new_email form["%s-street" % prefix] = "test-street" form["%s-country" % prefix] = "FI"
conditional_block
remove_input_state.py
''' This is a one-off command aimed at fixing a temporary problem encountered where input_state was added to the same dict object in capa problems, so was accumulating. The fix is simply to remove input_state entry from state for all problems in the affected date range. ''' import json import logging from optparse im...
(self, *args, **options): '''Handle management command request''' if len(args) != 1: raise CommandError("missing idlist file") idlist_path = args[0] save_changes = options['save_changes'] LOG.info("Starting run: reading from idlist file {0}; save_changes = {1}".forma...
handle
identifier_name
remove_input_state.py
''' This is a one-off command aimed at fixing a temporary problem encountered where input_state was added to the same dict object in capa problems, so was accumulating. The fix is simply to remove input_state entry from state for all problems in the affected date range. ''' import json import logging from optparse im...
else: # don't make the change, but increment the count indicating the change would be made self.num_changed += 1 @transaction.autocommit def remove_studentmodulehistory_input_state(self, module, save_changes): ''' Fix the grade assigned to a StudentModule''' mod...
''' Fix the grade assigned to a StudentModule''' module_state = module.state if module_state is None: # not likely, since we filter on it. But in general... LOG.info("No state found for {type} module {id} for student {student} in course {course_id}" .format(...
identifier_body
remove_input_state.py
''' This is a one-off command aimed at fixing a temporary problem encountered where input_state was added to the same dict object in capa problems, so was accumulating. The fix is simply to remove input_state entry from state for all problems in the affected date range. ''' import json import logging from optparse im...
LOG.info(" Progress: updated {0} of {1} student history modules".format(self.num_hist_changed, self.num_hist_visited)) @transaction.autocommit def remove_studentmodule_input_state(self, module, save_changes)...
self.remove_studentmodulehistory_input_state(hist_module, save_changes) if self.num_visited % 1000 == 0: LOG.info(" Progress: updated {0} of {1} student modules".format(self.num_changed, self.num_visited))
random_line_split
remove_input_state.py
''' This is a one-off command aimed at fixing a temporary problem encountered where input_state was added to the same dict object in capa problems, so was accumulating. The fix is simply to remove input_state entry from state for all problems in the affected date range. ''' import json import logging from optparse im...
else: # don't make the change, but increment the count indicating the change would be made self.num_hist_changed += 1 def handle(self, *args, **options): '''Handle management command request''' if len(args) != 1: raise CommandError("missing idlist file")...
del state_dict['input_state'] module.state = json.dumps(state_dict) module.save() self.num_hist_changed += 1
conditional_block
tasks.py
import csv import datetime import logging import os from celery.task import task from django.conf import settings from django.contrib.auth import get_user_model from django.utils.timezone import now from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \ REMINDER_LAST_REPORT, REMINDER_CLOSE fr...
else: msg = PollingDayReportReminderMessage(message_number, reminder_number) batch.add_messages(msg.get_phone_numbers_to_send_to()) batch.status = Batch.APPROVED batch.reviewed_by = user batch.save() # update the message for the broadcast. broadcast...
msg = CheckinReminderMessage(message_number, reminder_number)
conditional_block
tasks.py
import csv import datetime import logging import os from celery.task import task from django.conf import settings from django.contrib.auth import get_user_model from django.utils.timezone import now from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \ REMINDER_LAST_REPORT, REMINDER_CLOSE fr...
def get_phone_numbers_to_send_to(self): """ Generator that yields (phone_number, message_text, from_shortcode) tuples for the phone numbers that we need to send this reminder to. """ # Get the phone numbers we want to send to, excluding those that have # already don...
context = {'message_number': self.message_number, 'reminder_number': self.reminder_number} return get_message(self.get_message_code()).msg.format(**context)
identifier_body
tasks.py
import csv import datetime import logging import os from celery.task import task from django.conf import settings from django.contrib.auth import get_user_model from django.utils.timezone import now from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \ REMINDER_LAST_REPORT, REMINDER_CLOSE fr...
(self): """Return list of phone numbers to exclude""" reporting_period = self.message_number - 3 one_day_ago = now() - datetime.timedelta(hours=24) return PollingReport.objects.filter( period_number=reporting_period, creation_date__gte=one_day_ago, ).valu...
to_exclude
identifier_name
tasks.py
import csv import datetime import logging import os from celery.task import task from django.conf import settings from django.contrib.auth import get_user_model from django.utils.timezone import now from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \ REMINDER_LAST_REPORT, REMINDER_CLOSE fr...
(Do not instantiate, use the subclasses.) """ def __init__(self, message_number, reminder_number): self.message_number = message_number self.reminder_number = reminder_number def get_message_code(self): raise NotImplementedError def get_message_text(self): context =...
random_line_split
dnd-utils.ts
_FROM_NAME_INCREMENT = [cd.ElementEntitySubType.Icon, cd.ElementEntitySubType.Text]; export const incrementNameForEntity = ( instance: cd.IComponentInstance, entity: cd.ComponentIdentity, props: cd.ElementPropertiesMap ): string => { if (EXCLUDE_FROM_NAME_INCREMENT.includes(entity as cd.ElementEntitySubType)) ...
setOffset
identifier_name
dnd-utils.ts
'items'; const LAYERS_TREE_DROP_TARGET_ROWS = 3; const EXCLUDE_FROM_NAME_INCREMENT = [cd.ElementEntitySubType.Icon, cd.ElementEntitySubType.Text]; export const incrementNameForEntity = ( instance: cd.IComponentInstance, entity: cd.ComponentIdentity, props: cd.ElementPropertiesMap ): string => { if (EXCLUDE_FR...
const dragItem = dragAdditions && dragAdditions[0]; if (dragItem) return dragItem.name; return ''; }; export const isDropTargetAnEmptyBoard = ( dropTargetId: string, propsMap: cd.ElementPropertiesMap ): boolean => { const elem = propsMap[dropTargetId]; return !!elem && dropTargetId === elem.rootId; }; ...
// else use name of single drag item as label. const id = ids?.[0]; const element = id && propsMap[id]; if (element) return element.name;
random_line_split
lib.rs
use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use std; use std::fmt; use std::collections::HashMap; use std::convert::TryInto; extern crate num; use std::ops::{AddAssign, SubAssign}; use num::{Zero,One}; type Position =...
return true; } self.memory.write(self.input.read().into()); self.input.fwd(); }, '.' => { self.output.write(self.memory.read().try_into().unwrap()); self.output.fwd(); }, _ => (), ...
',' => { if self.input.ptr == self.input.len() {
random_line_split
lib.rs
use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use std; use std::fmt; use std::collections::HashMap; use std::convert::TryInto; extern crate num; use std::ops::{AddAssign, SubAssign}; use num::{Zero,One}; type Position =...
(program: &[u8]) -> JumpMap { let mut stack: Vec<usize> = Vec::new(); let mut jumps = JumpMap::new(); let plen = program.len(); let mut pos: Position = 0; while pos < plen { let opcode = program[pos] as char; match opcode { '[' => stack.pu...
_find_jumps
identifier_name
lib.rs
use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use std; use std::fmt; use std::collections::HashMap; use std::convert::TryInto; extern crate num; use std::ops::{AddAssign, SubAssign}; use num::{Zero,One}; type Position =...
pub fn dec(&mut self) { self.buf[self.ptr] -= T::one(); } pub fn read(&self) -> T { self.buf[self.ptr] } pub fn write(&mut self, val: T) { self.buf[self.ptr] = val; } } #[wasm_bindgen] pub struct Interpreter { program: Buffer<u8>, jumps: JumpMap, memory: ...
{ self.buf[self.ptr] += T::one(); }
identifier_body
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
return db_version_control(1) except AssertionError: return db_version_control(0) def db_version_control(version=None): repo_path = _find_migrate_repo() versioning_api.version_control(FLAGS.sql_connection, repo_path, version) return version def _find_migrate_repo(): "...
assert table in meta.tables
conditional_block
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
def _find_migrate_repo(): """Get the path for the migrate repository.""" path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') assert os.path.exists(path) return path
repo_path = _find_migrate_repo() versioning_api.version_control(FLAGS.sql_connection, repo_path, version) return version
identifier_body
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
(): """Get the path for the migrate repository.""" path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') assert os.path.exists(path) return path
_find_migrate_repo
identifier_name
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration.
random_line_split
test_threadable.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python.threadable}. """ from __future__ import division, absolute_import import sys, pickle try: import threading except ImportError: threadingSkip = "Platform lacks thread support" else: threadingSkip = None...
def testPickling(self): lock = threadable.XLock() lockType = type(lock) lockPickle = pickle.dumps(lock) newLock = pickle.loads(lockPickle) self.assertTrue(isinstance(newLock, lockType)) if threadingSkip is not None: testPickling.skip = threadingSkip def testUnp...
identifier_body
test_threadable.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python.threadable}. """ from __future__ import division, absolute_import import sys, pickle try: import threading except ImportError: threadingSkip = "Platform lacks thread support" else: threadingSkip = None...
except AssertionError as e: errors.append(str(e)) threads = [] for x in range(5): t = threading.Thread(target=callMethodLots) threads.append(t) t.start() for t in threads: t.join() if errors: rais...
o.aMethod()
conditional_block
test_threadable.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python.threadable}. """ from __future__ import division, absolute_import import sys, pickle try: import threading except ImportError: threadingSkip = "Platform lacks thread support" else: threadingSkip = None...
threads = [] for x in range(5): t = threading.Thread(target=callMethodLots) threads.append(t) t.start() for t in threads: t.join() if errors: raise unittest.FailTest(errors) if threadingSkip is not None: testThre...
for i in range(1000): o.aMethod() except AssertionError as e: errors.append(str(e))
random_line_split
test_threadable.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python.threadable}. """ from __future__ import division, absolute_import import sys, pickle try: import threading except ImportError: threadingSkip = "Platform lacks thread support" else: threadingSkip = None...
(self): """ The name of a synchronized method is inaffected by the synchronization decorator. """ self.assertEqual("aMethod", TestObject.aMethod.__name__) def test_isInIOThread(self): """ L{threadable.isInIOThread} returns C{True} if and only if it is called...
test_synchronizedName
identifier_name
backend.rs
use redis::{self, Connection, Commands}; use chrono::Duration; use cache::{CacheError, CacheResult}; use cache::context::CacheContext; // Redis abstraction pub struct CacheBackend { conn: Connection, one_day: i64 } impl CacheBackend { pub fn new(conn: Connection) -> Self { CacheBackend { ...
(&mut self, context: &CacheContext) -> CacheResult<bool> { self.conn.exists(context.get_key()).map_err(CacheError::Redis) } pub fn load_entries(&mut self, context: &CacheContext) -> CacheResult<Vec<String>> { self.conn.lrange(context.get_key(), 0, -1).map_err(CacheError::Redis) } }
is_stored
identifier_name
backend.rs
use redis::{self, Connection, Commands}; use chrono::Duration; use cache::{CacheError, CacheResult}; use cache::context::CacheContext; // Redis abstraction pub struct CacheBackend {
impl CacheBackend { pub fn new(conn: Connection) -> Self { CacheBackend { conn: conn, one_day: Duration::days(1).num_seconds() } } pub fn add_entries(&mut self, context: &CacheContext, items: Vec<String>) -> CacheResult<()> { let mut pipe = redis::pipe(); ...
conn: Connection, one_day: i64 }
random_line_split
backend.rs
use redis::{self, Connection, Commands}; use chrono::Duration; use cache::{CacheError, CacheResult}; use cache::context::CacheContext; // Redis abstraction pub struct CacheBackend { conn: Connection, one_day: i64 } impl CacheBackend { pub fn new(conn: Connection) -> Self { CacheBackend { ...
}
{ self.conn.lrange(context.get_key(), 0, -1).map_err(CacheError::Redis) }
identifier_body
supafly_flycatcher.js
var name = "Supafly Flycatcher"; var collection_type = 0; var is_secret = 0; var desc = "Caught 501 perfectly perfect jars of Fireflies"; var status_text = "Yes! 501 perfect jars of Fireflies, making you a certifiably Supafly Flycatcher. Tell all your friends."; var last_published = 1348802871; var is_shareworthy =...
(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_le...
onComplete
identifier_name
supafly_flycatcher.js
var name = "Supafly Flycatcher"; var collection_type = 0; var is_secret = 0; var desc = "Caught 501 perfectly perfect jars of Fireflies"; var status_text = "Yes! 501 perfect jars of Fireflies, making you a certifiably Supafly Flycatcher. Tell all your friends."; var last_published = 1348802871; var is_shareworthy =...
var conditions = { 512 : { type : "counter", group : "firefly_jar", label : "full", value : "501" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier();...
{ }
identifier_body
supafly_flycatcher.js
var name = "Supafly Flycatcher"; var collection_type = 0; var is_secret = 0; var desc = "Caught 501 perfectly perfect jars of Fireflies"; var status_text = "Yes! 501 perfect jars of Fireflies, making you a certifiably Supafly Flycatcher. Tell all your friends."; var last_published = 1348802871; var is_shareworthy =...
} var rewards = { "xp" : 800, "favor" : { "giant" : "mab", "points" : 175 } }; // generated ok (NO DATE)
{ pc.buffs_remove('silvertongue'); }
conditional_block
supafly_flycatcher.js
var name = "Supafly Flycatcher"; var collection_type = 0; var is_secret = 0; var desc = "Caught 501 perfectly perfect jars of Fireflies"; var status_text = "Yes! 501 perfect jars of Fireflies, making you a certifiably Supafly Flycatcher. Tell all your friends."; var last_published = 1348802871; var is_shareworthy =...
} var rewards = { "xp" : 800, "favor" : { "giant" : "mab", "points" : 175 } }; // generated ok (NO DATE)
random_line_split
execution-context.d.ts
declare module ExecutionContext { interface Executor { execute(routines: Array<Function>): Promise<void>; } /** * Executes arbitrary code asynchronously and concurrently. * * const executor = new ImmediateExecutor() * const context = new ExecutionContext(executor); * const result =...
*/ export class IdleCallbackExecutor implements Executor { constructor(timeout: number); execute(routines: Array<Function>): Promise<void>; } /** * Schedules a routine execution on the next event loop */ export class ImmediateExecutor implements Executor { constructor(concurrent: number); ...
* https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback
random_line_split
execution-context.d.ts
declare module ExecutionContext { interface Executor { execute(routines: Array<Function>): Promise<void>; } /** * Executes arbitrary code asynchronously and concurrently. * * const executor = new ImmediateExecutor() * const context = new ExecutionContext(executor); * const result =...
{ isCancelled: boolean; cancel(): void; } /** * Schedules a routine execution using `requestAnimationFrame` * https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame */ export class AnimationFrameExecutor implements Executor { maxDeadline: number; constructor(targe...
CancelToken
identifier_name
_lib.js
function setupTest( target, event, dataToPaste, externalPassCondition ){ var logNode=document.getElementsByTagName('p')[0].firstChild; logNode.data=''; if( typeof target==='string' ){ if( target.indexOf('.')>-1 ){ // for example "myElementID.firstChild" var tmp=target.split('.'); target=document.getEl...
logNode.parentNode.appendChild(document.createTextNode('Note: copy all body text from ')); var tmp=logNode.parentNode.appendChild(document.createElement('a')); tmp.href='support/html_file.htm'; tmp.appendChild(document.createTextNode('this support file')); logNode.parentNode.appendChild(document...
logNode.data+='Please place the following text on the clipboard before continuing the test: "'+(dataToPaste || 'clipboard text' )+'"\n'; logNode.parentNode.style.whiteSpace='pre'; if(dataToPaste.indexOf('{')==0){ // sorry about the content sniffing, this is likely a JSON string with alternate clipboard forma...
random_line_split
_lib.js
function setupTest( target, event, dataToPaste, externalPassCondition ){ var logNode=document.getElementsByTagName('p')[0].firstChild; logNode.data=''; if( typeof target==='string' ){ if( target.indexOf('.')>-1 ){ // for example "myElementID.firstChild" var tmp=target.split('.'); target=document.getEl...
{ var logNode=document.getElementsByTagName('p')[0].firstChild; if( testResult === true || testResult === false ){ logNode.data= testResult ? 'PASSED' : 'FAILED'; }else if( typeof testResult ==='string' ){ logNode.data=testResult; }else if( typeof externalPassCondition==='string' ){ logNode.data='\nThi...
identifier_body
_lib.js
function setupTest( target, event, dataToPaste, externalPassCondition ){ var logNode=document.getElementsByTagName('p')[0].firstChild; logNode.data=''; if( typeof target==='string' ){ if( target.indexOf('.')>-1 ){ // for example "myElementID.firstChild" var tmp=target.split('.'); target=document.getEl...
(e){ e=e||window.event; if(!e.target)e.target=e.srcElement; if(typeof window.clipboardData != 'undefined' && typeof e.clipboardData=='undefined' )e.clipboardData=window.clipboardData; try{ var testResult=test(e); result(testResult); }catch(e){ result('exception: '+e); } } /* if @a...
intermediateListener
identifier_name
SoupCan.js
'use strict'; var React = require('react'); var IconBase = require(__dirname + 'components/IconBase/IconBase'); var SoupCan = React.createClass({ displayName: 'SoupCan', render: function render() { return React.createElement( IconBase, null, React.createElement( 'g', null, React.createElemen...
});
random_line_split
test_pickle_api.py
from .._pickle_api import pickle_dumps, pickle_loads def test_pickle_dumps():
def test_pickle_loads(): msg = pickle_dumps({"hello": "world", "test": 123}) data = pickle_loads(msg) assert len(data) == 2 assert data["hello"] == "world" assert data["test"] == 123
data = {"hello": "world", "test": 123} expected = [ b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.", b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x04test\x94K{\x8c\x05hello\x94\x8c\x05world\x94u.", b"\x80\x02}q\x00(X\x04...
identifier_body
test_pickle_api.py
from .._pickle_api import pickle_dumps, pickle_loads
def test_pickle_dumps(): data = {"hello": "world", "test": 123} expected = [ b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.", b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x04test\x94K{\x8c\x05hello\x94\x8c\x05world\x94u.",...
random_line_split
test_pickle_api.py
from .._pickle_api import pickle_dumps, pickle_loads def test_pickle_dumps(): data = {"hello": "world", "test": 123} expected = [ b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.", b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8...
(): msg = pickle_dumps({"hello": "world", "test": 123}) data = pickle_loads(msg) assert len(data) == 2 assert data["hello"] == "world" assert data["test"] == 123
test_pickle_loads
identifier_name
gulpfile.js
/** * Eco gulpfile */ /* global require */ // For auto-transpiling spec files require("babel-register")({ presets: ["es2015"] }); const gulp = require("gulp"); const plugins = require("gulp-load-plugins")(); function
(task) { return require(`./gulp-tasks/${task}`)(gulp, plugins); } // Run source code through eslint gulp.task("lint", getTask("lint")); // Builds the project into dist/eco.min.js gulp.task("build", gulp.parallel("lint", getTask("build").build)); // Builds the project and rebuilds when changes are made gulp.task("w...
getTask
identifier_name
gulpfile.js
/** * Eco gulpfile */ /* global require */ // For auto-transpiling spec files require("babel-register")({ presets: ["es2015"]
const gulp = require("gulp"); const plugins = require("gulp-load-plugins")(); function getTask(task) { return require(`./gulp-tasks/${task}`)(gulp, plugins); } // Run source code through eslint gulp.task("lint", getTask("lint")); // Builds the project into dist/eco.min.js gulp.task("build", gulp.parallel("lint", g...
});
random_line_split
gulpfile.js
/** * Eco gulpfile */ /* global require */ // For auto-transpiling spec files require("babel-register")({ presets: ["es2015"] }); const gulp = require("gulp"); const plugins = require("gulp-load-plugins")(); function getTask(task)
// Run source code through eslint gulp.task("lint", getTask("lint")); // Builds the project into dist/eco.min.js gulp.task("build", gulp.parallel("lint", getTask("build").build)); // Builds the project and rebuilds when changes are made gulp.task("watch", gulp.series("build", getTask("build").watch)); // Runs the ...
{ return require(`./gulp-tasks/${task}`)(gulp, plugins); }
identifier_body
theoretical.py
# 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/. """ Define the Expansion Valve component. """ from scr.logic.components.component import Component as Cmp from scr.logi...
(self, id_, inlet_nodes_id, outlet_nodes_id, component_data): super().__init__(id_, inlet_nodes_id, outlet_nodes_id, component_data) """ Fundamental properties equations """ @fundamental_equation() # function name can be arbitrary. Return a single vector with each side of the equation evaluated. ...
__init__
identifier_name
theoretical.py
# 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/. """ Define the Expansion Valve component.
""" from scr.logic.components.component import Component as Cmp from scr.logic.components.component import ComponentInfo as CmpInfo from scr.logic.components.component import component, fundamental_equation def update_saved_data_to_last_version(orig_data, orig_version): return orig_data @component('theoretical...
random_line_split
theoretical.py
# 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/. """ Define the Expansion Valve component. """ from scr.logic.components.component import Component as Cmp from scr.logi...
""" Fundamental properties equations """ @fundamental_equation() # function name can be arbitrary. Return a single vector with each side of the equation evaluated. def _eval_intrinsic_equations(self): id_inlet_node = self.get_id_inlet_nodes()[0] inlet_node = self.get_inlet_node(id_inle...
super().__init__(id_, inlet_nodes_id, outlet_nodes_id, component_data)
identifier_body
inflater.ts
function _inflaterTargetPropertyLookup(target : View, attribute : string) { var callEnd = attribute.length - 2; if (attribute.lastIndexOf("()") === callEnd) { var name = attribute.substr(0, callEnd); return target[name](); } else { return target[attribute]; } } function _in...
_sortProperties(properties : any) : string[] { var sorted = []; for (var prop in properties) { sorted.push(prop); } sorted.sort(); return sorted; } _buildView(properties : LayoutData, parent : View, root : View) : View { var classType = ...
{ return this._buildView(view, root, root); }
identifier_body
inflater.ts
function _inflaterTargetPropertyLookup(target : View, attribute : string) { var callEnd = attribute.length - 2; if (attribute.lastIndexOf("()") === callEnd) { var name = attribute.substr(0, callEnd); return target[name](); } else { return target[attribute]; } } function _inf...
} } else { if (typeof(prop) === "function") { if (propName.indexOf("on") !== 0) { //TODO Shoul look up if the undecorated property name exists in the view. Log("Warning, hooking an unknown functio...
} } } view[propName](prop);
random_line_split
inflater.ts
function _inflaterTargetPropertyLookup(target : View, attribute : string) { var callEnd = attribute.length - 2; if (attribute.lastIndexOf("()") === callEnd) { var name = attribute.substr(0, callEnd); return target[name](); } else { return target[attribute]; } } function _in...
{ inflate(view : LayoutData, root : View) : View { return this._buildView(view, root, root); } _sortProperties(properties : any) : string[] { var sorted = []; for (var prop in properties) { sorted.push(prop); } sorted.sort(); return sorted; ...
Inflater
identifier_name
inflater.ts
function _inflaterTargetPropertyLookup(target : View, attribute : string) { var callEnd = attribute.length - 2; if (attribute.lastIndexOf("()") === callEnd) { var name = attribute.substr(0, callEnd); return target[name](); } else { return target[attribute]; } } function _in...
if (typeof(prop) !== typeof(viewPropValue)) { prop = _inflaterLookupProperty(root, view, prop); if (typeof(prop) !== typeof(viewPropValue)) { Log("Type mismatch: " + propName + " = "...
{ prop = (<_ViewRef>prop).command; }
conditional_block
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any ...
// along with this program. If not, see <http://www.gnu.org/licenses/>. //! This module returns a `MemoryRegion` of the data segment, so that it can be //! search as well. use std::env; use std::fs; use std::io::{self, Read}; use communication::{Address, MemoryRegion}; /// Represents the data segment of the cur...
// GNU General Public License for more details. // // You should have received a copy of the GNU General Public License
random_line_split
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any ...
{ pub address: Address, pub memory_region: MemoryRegion, } /// loads the current binary into memory so that its header can be parsed. /// We probably could parse the header from memory, because the program is /// already running, but that would require different code for Linux and /// Windows. fn load_current...
DataSegment
identifier_name
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any ...
#[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use self::linux::get_data_segment; #[cfg(target_os = "windows")] pub use self::windows::get_data_segment;
{ let current_program = env::current_exe()?; let mut file = fs::File::open(current_program)?; let mut program = vec![]; file.read_to_end(&mut program)?; Ok(program) }
identifier_body
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
} impl Clock for FakeAbsoluteClock { type Instant = Instant; fn now(&self) -> Self::Instant { *self.now.lock() } } /// The monotonic clock implemented by [`Instant`]. #[derive(Clone, Debug, Default)] pub struct MonotonicClock(); impl Reference for Instant { fn duration_since(&self, earlier:...
{ *(self.now.lock()) += by }
identifier_body
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
else { Duration::new(0, 0) } } fn saturating_sub(&self, duration: Duration) -> Self { self.checked_sub(duration).unwrap_or(*self) } } impl Clock for MonotonicClock { type Instant = Instant; fn now(&self) -> Self::Instant { Instant::now() } } /// The non-m...
{ *self - earlier }
conditional_block
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
type Instant = Instant; fn now(&self) -> Self::Instant { Instant::now() } } /// The non-monotonic clock implemented by [`SystemTime`]. #[derive(Clone, Debug, Default)] pub struct SystemClock(); impl Reference for SystemTime { /// Returns the difference in times between the two /// SystemT...
} } impl Clock for MonotonicClock {
random_line_split
with_std.rs
use super::{Clock, Reference}; use crate::lib::*; use parking_lot::Mutex; use std::time::SystemTime; /// The default clock that reports [`Instant`]s. pub type DefaultClock = MonotonicClock; /// A mock implementation of a clock tracking [`Instant`]s. All it /// does is keep track of what "now" is by allowing the progr...
(&self, duration: Duration) -> Self { self.checked_sub(duration).unwrap_or(*self) } } impl Clock for MonotonicClock { type Instant = Instant; fn now(&self) -> Self::Instant { Instant::now() } } /// The non-monotonic clock implemented by [`SystemTime`]. #[derive(Clone, Debug, Default)]...
saturating_sub
identifier_name
boundbutton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """""" import tkinter as tk from tkinter import ttk # link __title__ = "BoundButton" __version__ = "1.0.3" __author__ = "DeflatedPickle" class BoundButton(ttk.Button): """ -----DESCRIPTION----- A ttk Button that can be bound to any key to run any fu...
root = tk.Tk() bbutton = BoundButton(root, text="Press F", key="f", command=function) bbutton.pack(expand=True, padx=5, pady=5) variable = tk.StringVar() variable.set("foo") label = ttk.Label(root, textvariable=variable).pack(expand=True, padx=5, pady=5) root.mainloop()
variable.set("foo")
conditional_block
boundbutton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """""" import tkinter as tk from tkinter import ttk # link __title__ = "BoundButton" __version__ = "1.0.3" __author__ = "DeflatedPickle" class BoundButton(ttk.Button): """ -----DESCRIPTION----- A ttk Button that can be bound to any key to run any fu...
variable = tk.StringVar() variable.set("foo") label = ttk.Label(root, textvariable=variable).pack(expand=True, padx=5, pady=5) root.mainloop()
variable.set("foo") root = tk.Tk() bbutton = BoundButton(root, text="Press F", key="f", command=function) bbutton.pack(expand=True, padx=5, pady=5)
random_line_split
boundbutton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """""" import tkinter as tk from tkinter import ttk # link __title__ = "BoundButton" __version__ = "1.0.3" __author__ = "DeflatedPickle" class BoundButton(ttk.Button): """ -----DESCRIPTION----- A ttk Button that can be bound to any key to run any fu...
(event): if variable.get() == "foo": variable.set("bar") elif variable.get() == "bar": variable.set("foo") root = tk.Tk() bbutton = BoundButton(root, text="Press F", key="f", command=function) bbutton.pack(expand=True, padx=5, pady=5) variable = tk.StringVar() ...
function
identifier_name
boundbutton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """""" import tkinter as tk from tkinter import ttk # link __title__ = "BoundButton" __version__ = "1.0.3" __author__ = "DeflatedPickle" class BoundButton(ttk.Button): """ -----DESCRIPTION----- A ttk Button that can be bound to any key to run any fu...
################################################## if __name__ == "__main__": def function(event): if variable.get() == "foo": variable.set("bar") elif variable.get() == "bar": variable.set("foo") root = tk.Tk() bbutton = BoundButton(root, text="Press F", key="f"...
ttk.Button.__init__(self, parent, default="active", text=text, command=command, *args) self.parent = parent self._text = text self._key = key self._command = command self.bind("<{}>".format(key), command) self.focus()
identifier_body
day_3.rs
pub use tdd_kata::map_kata::day_3::HashMap; #[test] fn it_should_create_a_new_empty_map() { let map = HashMap::new(10); assert!(map.is_empty()); assert_eq!(map.size(), 0); } #[test] fn
() { let mut map = HashMap::new(10); let old_size = map.size(); map.put(1,1); assert_eq!(map.size(), old_size+1); } #[test] #[ignore] fn it_should_contain_put_value() { let mut map = HashMap::new(10); map.put(1,1); assert!(map.contains(1)); } #[test] #[ignore] fn it_should_not_increase_...
it_should_increase_map_size_when_put
identifier_name
day_3.rs
pub use tdd_kata::map_kata::day_3::HashMap; #[test] fn it_should_create_a_new_empty_map() { let map = HashMap::new(10); assert!(map.is_empty()); assert_eq!(map.size(), 0); } #[test] fn it_should_increase_map_size_when_put() { let mut map = HashMap::new(10); let old_size = map.size(); map.put...
{ let mut map = HashMap::new(10); map.put(1,1); let old_size = map.size(); map.put(1,2); assert_eq!(map.size(), old_size); }
identifier_body
day_3.rs
pub use tdd_kata::map_kata::day_3::HashMap; #[test] fn it_should_create_a_new_empty_map() { let map = HashMap::new(10); assert!(map.is_empty()); assert_eq!(map.size(), 0);
#[test] fn it_should_increase_map_size_when_put() { let mut map = HashMap::new(10); let old_size = map.size(); map.put(1,1); assert_eq!(map.size(), old_size+1); } #[test] #[ignore] fn it_should_contain_put_value() { let mut map = HashMap::new(10); map.put(1,1); assert!(map.contains(1));...
}
random_line_split
runtests.py
#!/usr/bin/python import os import re import shutil import sys import tempfile import time import unittest from clienttests import ClientConfigTests from sitetests import SiteConfigTests from arbtests import ArbitratorConfigTests if __name__ == '__main__': if os.geteuid() == 0: sys.stderr.write("Mus...
test_run_path = tempfile.mkdtemp(prefix='%d.' % time.time(), dir=tmp_path) suite = unittest.TestSuite() testclasses = [ SiteConfigTests, #ArbitratorConfigTests, ClientConfigTests, ] for testclass in testclasses: testclass.test_run_path = test_run_path ...
os.makedirs(tmp_path)
conditional_block
runtests.py
#!/usr/bin/python import os import re import shutil import sys import tempfile import time import unittest from clienttests import ClientConfigTests from sitetests import SiteConfigTests from arbtests import ArbitratorConfigTests if __name__ == '__main__': if os.geteuid() == 0: sys.stderr.write("Mus...
os.system("killall boothd") runner = unittest.TextTestRunner(**runner_args) result = runner.run(suite) if result.wasSuccessful(): shutil.rmtree(test_run_path) sys.exit(0) else: print "Left %s for debugging" % test_run_path sys.exit(1)
runner_args['failfast'] = True pass # not root anymore, so safe # needed because old instances might still use the UDP port.
random_line_split
bankAccountInquiry.page.js
'use strict'; var BankAccountInquiryPage = function() { browser.ignoreSynchronization = true; var page = this; this.pageElements = function() { page.account = element(by.name('bank_account')); page.dateFrom = element(by.name('TransAfterDate')); page.dateTo = element(by.name('TransToDate')); page...
text: cellElement.getText() }; }); return items; }; this.getBalance = function() { this.pageElements(); var items = element.all(by.css('div#trans_tbl tr.inquirybg')) .get(1) .all(by.tagName('td')) .map(function(cellElement, cellIndex) { return { column: cellI...
.map(function(cellElement, cellIndex) { return { column: cellIndex,
random_line_split
mapStateModelValueInStrict.common.js
/** * vuex-mapstate-modelvalue-instrict- v0.0.4 * (c) 2017 fsy0718 * @license MIT */ 'use strict'; var push = Array.prototype.push; var pop = Array.prototype.pop; var _mapStateModelValueInStrict = function (modelValue, stateName, type, opts, setWithPayload, copts) { if ( opts === void 0 ) opts = {}; if ( copts...
} return this.$store.state[stateName] }, set: function set (value) { var mutation = setWithPayload ? ( obj = {}, obj[stateName] = value, obj ) : value; var obj; var _type = modulePath ? (modulePath + "/" + type) : type; this.$store.commit(_type, mutation, modulePath ? opts.pa...
result = undefined; } return result
random_line_split
mocha.ts
/// <reference path="../externals.d.ts" /> export import chai = require('chai'); export import sinon = require("sinon"); export import sinonChai = require('sinon-chai'); export import mocha = require('mocha'); export var expect = chai.expect; export var spy = sinon.spy; chai.use(sinonChai); declare var require:(nam...
{ var sdk = new SDK({ server: 'http://whatever', appKey: 'whatever', appSecret: 'whatever', client: client, pubnubFactory: pubnub }); sdk.platform().auth().forceAuthentication(); return sdk; }
identifier_body
mocha.ts
/// <reference path="../externals.d.ts" /> export import chai = require('chai'); export import sinon = require("sinon"); export import sinonChai = require('sinon-chai'); export import mocha = require('mocha'); export var expect = chai.expect; export var spy = sinon.spy; chai.use(sinonChai); declare var require:(nam...
() { var sdk = new SDK({ server: 'http://whatever', appKey: 'whatever', appSecret: 'whatever', client: client, pubnubFactory: pubnub }); sdk.platform().auth().forceAuthentication(); return sdk; }
getSDK
identifier_name
mocha.ts
/// <reference path="../externals.d.ts" /> export import chai = require('chai'); export import sinon = require("sinon"); export import sinonChai = require('sinon-chai'); export import mocha = require('mocha'); export var expect = chai.expect; export var spy = sinon.spy; chai.use(sinonChai); declare var require:(nam...
pubnubFactory: pubnub }); sdk.platform().auth().forceAuthentication(); return sdk; }
appKey: 'whatever', appSecret: 'whatever', client: client,
random_line_split
android_bitmap.rs
use core::prelude::*; use core::raw; use core::{ptr, mem}; use core::borrow::IntoCow; use libc::c_void; use jni::{jobject, jclass, jmethodID, JNIEnv}; use jni_constants::{JNI_TRUE, JNI_FALSE}; use android::bitmap::{AndroidBitmap_getInfo, AndroidBitmap_lockPixels, AndroidBitmap_unlockPixels, AndroidBitmapInfo}; use andr...
(&self) -> GLResult<&[u8]> { match self.as_slice_unsafe() { Ok(ok) => Ok(&*ok), Err(err) => Err(err), } } pub unsafe fn set_premultiplied(&mut self, premultiplied: bool) -> bool { if let Some(set_premultiplied) = SET_PREMULTIPLIED { let pm = if premul...
as_slice
identifier_name