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
artifacts.py
import re from django import template from django.template.loader import get_template from django.template import RequestContext register = template.Library() INSTALLED_ARTIFACTS = dict() def install(artifact_class): INSTALLED_ARTIFACTS[artifact_class.key] = artifact_class def find(data): from fir_artifa...
else: return context.flatten() def correlated_count(self): return len(self._correlated)
return template.render(context.flatten(), request)
conditional_block
artifacts.py
import re from django import template from django.template.loader import get_template from django.template import RequestContext register = template.Library() INSTALLED_ARTIFACTS = dict() def install(artifact_class): INSTALLED_ARTIFACTS[artifact_class.key] = artifact_class def find(data):
def after_save(type, value, event): return INSTALLED_ARTIFACTS[type].after_save(value, event) def incs_for_art(art_string): from fir_artifacts.models import Artifact artifacts = Artifact.objects.filter(value__contains=art_string) incs = [] for a in artifacts: incs.extend(a.relations.all(...
from fir_artifacts.models import ArtifactBlacklistItem result = dict() for key in INSTALLED_ARTIFACTS: blacklist = ArtifactBlacklistItem.objects.filter(type=key).values_list('value', flat=True) values = INSTALLED_ARTIFACTS[key].find(data) values = [v for v in values if v not in blacklis...
identifier_body
artifacts.py
import re from django import template from django.template.loader import get_template from django.template import RequestContext register = template.Library() INSTALLED_ARTIFACTS = dict() def install(artifact_class): INSTALLED_ARTIFACTS[artifact_class.key] = artifact_class def find(data): from fir_artifa...
(self): return self.artifact.id @property def pk(self): return self.artifact.pk self._artifacts = [ArtifactDisplay(artifact, user) for artifact in artifacts] self._event = event self._correlated = [] for artifact in self._artifac...
id
identifier_name
employee_birthday.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ def execute(filters=None):
def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date of Birth")+ ":Date:100", _("Branch") + ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Gender") + "::60", _("Company") + ":Link/Company:120" ] def ge...
if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data
identifier_body
employee_birthday.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def get_columns(...
] def get_employees(filters): conditions = get_conditions(filters) return frappe.db.sql("""select name, employee_name, date_of_birth, branch, department, designation, gender, company from tabEmployee where status = 'Active' %s""" % conditions, as_list=1) def get_conditions(filters): conditions = "" if filters....
_("Designation") + ":Link/Designation:120", _("Gender") + "::60", _("Company") + ":Link/Company:120"
random_line_split
employee_birthday.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def get_columns(...
return conditions
conditions += " and company = '%s'" % \ filters["company"].replace("'", "\\'")
conditional_block
employee_birthday.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def
(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date of Birth")+ ":Date:100", _("Branch") + ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Gender") + "::60", _("Company") + ":Link/Company:120" ] def get_employees(filte...
get_columns
identifier_name
ButtonBase.d.ts
import * as React from 'react'; import { SxProps } from '@material-ui/system'; import { Theme } from '../styles'; import { TouchRippleProps } from './TouchRipple'; import { OverrideProps, OverridableComponent, OverridableTypeMap } from '../OverridableComponent'; export interface ButtonBaseTypeMap<P = {}, D extends Rea...
*/ disableRipple?: boolean; /** * If `true`, the touch ripple effect is disabled. * @default false */ disableTouchRipple?: boolean; /** * If `true`, the base button will have a keyboard focus ripple. * @default false */ focusRipple?: boolean; /** * This pr...
random_line_split
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
fn create_id_from_clispec(create: &ArgMatches, diaryname: &str, timed_type: Timed) -> DiaryId { use std::str::FromStr; let get_hourly_id = |create: &ArgMatches| -> DiaryId { let time = DiaryId::now(String::from(diaryname)); let hr = create .value_of("hour") .map(|v| { de...
random_line_split
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
else { debug!("Editing new diary entry"); entry.edit_content(rt) .chain_err(|| DEK::DiaryEditError) }; if let Err(e) = res { trace_error_exit(&e, 1); } else { info!("Ok!"); } } fn create_entry<'a>(diary: &'a Store, diaryname: &str, rt: &Runtime) -> FileLock...
{ debug!("Not editing new diary entry"); Ok(()) }
conditional_block
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(rt: &Runtime) { let diaryname = get_diary_name(rt) .unwrap_or_else( || warn_exit("No diary selected. Use either the configuration file or the commandline option", 1)); let mut entry = create_entry(rt.store(), &diaryname, rt); let res = if rt.cli().subcommand_matches("create").unwrap().is_present(...
create
identifier_name
create.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
let id = create_id_from_clispec(&create, &diaryname, timed); diary.retrieve(id).chain_err(|| DEK::StoreReadError) }, None => { debug!("Creating non-timed entry"); diary.new_entry_today(diaryname) } }; match entry { Err(e) => trace...
{ use util::parse_timed_string; let create = rt.cli().subcommand_matches("create").unwrap(); let create_timed = create.value_of("timed") .map(|t| parse_timed_string(t, diaryname).map_err_trace_exit_unwrap(1)) .map(Some) .unwrap_or_else(|| match get_diary_timed_config(rt, diaryname)...
identifier_body
imports-on-top.js
const BaseChecker = require('./../base-checker') const ruleId = 'imports-on-top' const meta = { type: 'order', docs: { description: `Import statements must be on top.`, category: 'Style Guide Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class ImportsOnTo...
_error(node) { this.error(node, 'Import statements must be on top') } } module.exports = ImportsOnTopChecker
if (hasContractDef && curItem.type === 'ImportDirective') { this._error(curItem) } } }
random_line_split
imports-on-top.js
const BaseChecker = require('./../base-checker') const ruleId = 'imports-on-top' const meta = { type: 'order', docs: { description: `Import statements must be on top.`, category: 'Style Guide Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class ImportsOnTo...
} module.exports = ImportsOnTopChecker
{ this.error(node, 'Import statements must be on top') }
identifier_body
imports-on-top.js
const BaseChecker = require('./../base-checker') const ruleId = 'imports-on-top' const meta = { type: 'order', docs: { description: `Import statements must be on top.`, category: 'Style Guide Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class ImportsOnTo...
} } _error(node) { this.error(node, 'Import statements must be on top') } } module.exports = ImportsOnTopChecker
{ this._error(curItem) }
conditional_block
imports-on-top.js
const BaseChecker = require('./../base-checker') const ruleId = 'imports-on-top' const meta = { type: 'order', docs: { description: `Import statements must be on top.`, category: 'Style Guide Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class ImportsOnTo...
(reporter) { super(reporter, ruleId, meta) } SourceUnit(node) { let hasContractDef = false for (let i = 0; node.children && i < node.children.length; i += 1) { const curItem = node.children[i] if (curItem.type === 'ContractDefinition') { hasContractDef = true } if (has...
constructor
identifier_name
lib.rs
use blocking::unblock; use futures::lock::Mutex; use futures::{Future, TryStreamExt}; use futures_timer::Delay; use log::trace; use mobc::{async_trait, Manager}; use reql::cmd::connect::Options; use reql::cmd::run::{self, Arg}; use reql::types::{Change, ServerStatus}; use reql::{r, Command, Connection, Driver, Error, R...
fn to_reql(error: mobc::Error<Error>) -> Error { match error { mobc::Error::Inner(error) => error, mobc::Error::Timeout => io::Error::from(io::ErrorKind::TimedOut).into(), mobc::Error::BadConn => Driver::ConnectionBroken.into(), } }
{ if res != msg { return Err(Driver::ConnectionBroken.into()); } Ok(()) }
identifier_body
lib.rs
use blocking::unblock; use futures::lock::Mutex; use futures::{Future, TryStreamExt}; use futures_timer::Delay; use log::trace; use mobc::{async_trait, Manager}; use reql::cmd::connect::Options; use reql::cmd::run::{self, Arg}; use reql::types::{Change, ServerStatus}; use reql::{r, Command, Connection, Driver, Error, R...
type Connection = reql::Session; type Error = Error; async fn connect(&self) -> Result<Self::Connection> { let opts = &self.opts; let servers = &self.servers.lock().await; if servers.is_empty() { trace!( "no discovered servers; host: {}, port: {}", ...
random_line_split
lib.rs
use blocking::unblock; use futures::lock::Mutex; use futures::{Future, TryStreamExt}; use futures_timer::Delay; use log::trace; use mobc::{async_trait, Manager}; use reql::cmd::connect::Options; use reql::cmd::run::{self, Arg}; use reql::types::{Change, ServerStatus}; use reql::{r, Command, Connection, Driver, Error, R...
(&self) -> Result<Session> { Ok(Session { conn: self.get().await.map_err(to_reql)?, }) } } pub struct Session { conn: mobc::Connection<SessionManager>, } impl Deref for Session { type Target = reql::Session; fn deref(&self) -> &Self::Target { &self.conn } } im...
session
identifier_name
light.py
"""Support for Nanoleaf Lights.""" import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSIT...
else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error("Could not generate the auth token, did you press " ...
token = conf[host]['token']
conditional_block
light.py
"""Support for Nanoleaf Lights.""" import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSIT...
return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get('token'): token = conf[host]['token'] else: host = config[CONF_HOST] name = config[CONF_NAME] token =...
host = discovery_info['host'] name = discovery_info['hostname'] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]:
random_line_split
light.py
"""Support for Nanoleaf Lights.""" import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSIT...
(self): """Return the list of supported effects.""" return self._effects_list @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" return 154 @property def max_mireds(self): """Return the warmest color_temp that this ligh...
effect_list
identifier_name
light.py
"""Support for Nanoleaf Lights.""" import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSIT...
else: # If no transition is occurring, turn on the light self._light.on = True if brightness: self._light.brightness = int(brightness / 2.55) if effect: self._light.effect = effect def turn_off(self, **kwargs): """Instruct the light to ...
"""Instruct the light to turn on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) hs_color = kwargs.get(ATTR_HS_COLOR) color_temp_mired = kwargs.get(ATTR_COLOR_TEMP) effect = kwargs.get(ATTR_EFFECT) transition = kwargs.get(ATTR_TRANSITION) if hs_color: hue, satur...
identifier_body
labler.js
const storage = require("./storage"); const recognition = require("./recognition"); async function labelPictures(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); for (const file of fileNames) { console.log(`Retrieve labels for fi...
main(process.argv[2]);
{ throw new Error("Please specify a bucket name"); }
conditional_block
labler.js
const storage = require("./storage"); const recognition = require("./recognition"); async function labelPictures(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); for (const file of fileNames) { console.log(`Retrieve labels for fi...
if (process.argv.length < 3) { throw new Error("Please specify a bucket name"); } main(process.argv[2]);
{ try { await labelPictures(bucketName); } catch (error) { console.error(error); } }
identifier_body
labler.js
const storage = require("./storage"); const recognition = require("./recognition"); async function labelPictures(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); for (const file of fileNames) { console.log(`Retrieve labels for fi...
} main(process.argv[2]);
random_line_split
labler.js
const storage = require("./storage"); const recognition = require("./recognition"); async function
(bucketName) { const bucket = await storage.getOrCreateBucket(bucketName); const fileNames = await storage.ls(bucket); for (const file of fileNames) { console.log(`Retrieve labels for file ${file.name}`); try { const labels = await recognition.getLabels(file.metadata.mediaLink);...
labelPictures
identifier_name
mihome_energy_monitor.py
# mihome_energy_monitor.py 28/05/2016 D.J.Whale # # A simple demo of monitoring and logging energy usage of mihome devices # # Logs all messages to screen and to a file energenie.csv # Any device that has a switch, it toggles it every 2 seconds. # Any device that offers a power reading, it displays it. import energe...
switch_state = not switch_state # For all devices in the registry, if they have a get_power(), call it print("Checking device status") for d in energenie.registry.devices(): print(d) try: p = d.get_power() print("Power: %s" % str(p)) except: ...
d.set_switch(switch_state)
conditional_block
mihome_energy_monitor.py
# mihome_energy_monitor.py 28/05/2016 D.J.Whale # # A simple demo of monitoring and logging energy usage of mihome devices # # Logs all messages to screen and to a file energenie.csv # Any device that has a switch, it toggles it every 2 seconds. # Any device that offers a power reading, it displays it. import energe...
(): global switch_state # Process any received messages from the real radio energenie.loop() # For all devices in the registry, if they have a switch, toggle it for d in energenie.registry.devices(): if d.has_switch(): d.set_switch(switch_state) switch_state = not switch_st...
energy_monitor_loop
identifier_name
mihome_energy_monitor.py
# mihome_energy_monitor.py 28/05/2016 D.J.Whale # # A simple demo of monitoring and logging energy usage of mihome devices # # Logs all messages to screen and to a file energenie.csv # Any device that has a switch, it toggles it every 2 seconds. # Any device that offers a power reading, it displays it. import energe...
time.sleep(APP_DELAY) if __name__ == "__main__": print("Starting energy monitor example") energenie.init() # provide a default incoming message handler, useful for logging every message def incoming(address, message): print("\nIncoming from %s" % str(address)) Logger.logMessag...
global switch_state # Process any received messages from the real radio energenie.loop() # For all devices in the registry, if they have a switch, toggle it for d in energenie.registry.devices(): if d.has_switch(): d.set_switch(switch_state) switch_state = not switch_state ...
identifier_body
mihome_energy_monitor.py
# mihome_energy_monitor.py 28/05/2016 D.J.Whale # # A simple demo of monitoring and logging energy usage of mihome devices # # Logs all messages to screen and to a file energenie.csv # Any device that has a switch, it toggles it every 2 seconds. # Any device that offers a power reading, it displays it. import energe...
try: while True: energy_monitor_loop() finally: energenie.finished() # END
def incoming(address, message): print("\nIncoming from %s" % str(address)) Logger.logMessage(message) energenie.fsk_router.when_incoming(incoming) print("Logging to file:%s" % Logger.LOG_FILENAME)
random_line_split
grain.rs
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by app...
p.a = 0xff; *out = p; }
random_line_split
util.js
var path = require('path'); var fs = require('fs'); var spawn = require('child_process').spawn; function noop() {} exports.noop = noop; if (process.env.HTTP2_LOG) { var logOutput = process.stderr; if (process.stderr.isTTY) { var bin = path.resolve(path.dirname(require.resolve('bunyan')), '..', 'bin', 'bunyan'...
var concatenated = new Buffer(size); for (var cursor = 0, j = 0; j < buffers.length; cursor += buffers[j].length, j++) { buffers[j].copy(concatenated, cursor); } return concatenated; }; exports.random = function random(min, max) { return min + Math.floor(Math.random() * (max - min + 1)); }; // Concate...
var size = 0; for (var i = 0; i < buffers.length; i++) { size += buffers[i].length; }
random_line_split
util.js
var path = require('path'); var fs = require('fs'); var spawn = require('child_process').spawn; function
() {} exports.noop = noop; if (process.env.HTTP2_LOG) { var logOutput = process.stderr; if (process.stderr.isTTY) { var bin = path.resolve(path.dirname(require.resolve('bunyan')), '..', 'bin', 'bunyan'); if(bin && fs.existsSync(bin)) { logOutput = spawn(bin, ['-o', 'short'], { stdio: [null, p...
noop
identifier_name
util.js
var path = require('path'); var fs = require('fs'); var spawn = require('child_process').spawn; function noop()
exports.noop = noop; if (process.env.HTTP2_LOG) { var logOutput = process.stderr; if (process.stderr.isTTY) { var bin = path.resolve(path.dirname(require.resolve('bunyan')), '..', 'bin', 'bunyan'); if(bin && fs.existsSync(bin)) { logOutput = spawn(bin, ['-o', 'short'], { stdio: [null, proces...
{}
identifier_body
util.js
var path = require('path'); var fs = require('fs'); var spawn = require('child_process').spawn; function noop() {} exports.noop = noop; if (process.env.HTTP2_LOG) { var logOutput = process.stderr; if (process.stderr.isTTY) { var bin = path.resolve(path.dirname(require.resolve('bunyan')), '..', 'bin', 'bunyan'...
var concatenated = new Buffer(size); for (var cursor = 0, j = 0; j < buffers.length; cursor += buffers[j].length, j++) { buffers[j].copy(concatenated, cursor); } return concatenated; }; exports.random = function random(min, max) { return min + Math.floor(Math.random() * (max - min + 1)); }; // Concat...
{ size += buffers[i].length; }
conditional_block
ts_plugin_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {LanguageService} from '../../language_service'; import {getExternalFiles} from '../../ts_plugin'; import {AP...
ngLS.getSemanticDiagnostics(APP_COMPONENT); // Now that global analysis is run, we should have all the typecheck files externalFiles = getExternalFiles(project); expect(externalFiles.length).toBe(1); expect(externalFiles[0].endsWith('app.component.ngtypecheck.ts')).toBeTrue(); }); });
// a global analysis expect(externalFiles).toEqual([]); // Trigger global analysis const ngLS = new LanguageService(project, tsLS, {});
random_line_split
test_ext.py
import time CALENDAR_URL = 'https://calendar.google.com/calendar' BUTTONS_CLASS = 'gcal-unlim-weeks-adjust-weeks' ADD_BUTTON_CLASS = 'gcal-unlim-weeks-add-week' REMOVE_BUTTON_CLASS = 'gcal-unlim-weeks-remove-week' def get_num_weeks(selenium): weeks = selenium.find_elements_by_class_name('month-row') return l...
def test_load_with_no_button_checked(selenium, authed_get, is_headless): # this hash leaves the toolbar without any buttons checked no_checked_buttons_url = \ 'https://calendar.google.com/calendar/render#main_7%7Ccustom,28' authed_get(no_checked_buttons_url) if is_headless: inject_exte...
time.sleep(1) jquery_js = open('ext/src/inject/jquery.min.js').read() selenium.execute_script(jquery_js) inject_js = open('ext/src/inject/compiled.min.js').read() selenium.execute_script(inject_js) time.sleep(1)
identifier_body
test_ext.py
import time CALENDAR_URL = 'https://calendar.google.com/calendar' BUTTONS_CLASS = 'gcal-unlim-weeks-adjust-weeks' ADD_BUTTON_CLASS = 'gcal-unlim-weeks-add-week' REMOVE_BUTTON_CLASS = 'gcal-unlim-weeks-remove-week' def get_num_weeks(selenium): weeks = selenium.find_elements_by_class_name('month-row') return l...
time.sleep(1) def test_load_with_no_button_checked(selenium, authed_get, is_headless): # this hash leaves the toolbar without any buttons checked no_checked_buttons_url = \ 'https://calendar.google.com/calendar/render#main_7%7Ccustom,28' authed_get(no_checked_buttons_url) if is_headless: ...
random_line_split
test_ext.py
import time CALENDAR_URL = 'https://calendar.google.com/calendar' BUTTONS_CLASS = 'gcal-unlim-weeks-adjust-weeks' ADD_BUTTON_CLASS = 'gcal-unlim-weeks-add-week' REMOVE_BUTTON_CLASS = 'gcal-unlim-weeks-remove-week' def get_num_weeks(selenium): weeks = selenium.find_elements_by_class_name('month-row') return l...
else: button = add_button for _ in range(abs(delta)): button.click() num_weeks = get_num_weeks(selenium) assert num_weeks == old_num_weeks + delta old_num_weeks = num_weeks
button = remove_button
conditional_block
test_ext.py
import time CALENDAR_URL = 'https://calendar.google.com/calendar' BUTTONS_CLASS = 'gcal-unlim-weeks-adjust-weeks' ADD_BUTTON_CLASS = 'gcal-unlim-weeks-add-week' REMOVE_BUTTON_CLASS = 'gcal-unlim-weeks-remove-week' def get_num_weeks(selenium): weeks = selenium.find_elements_by_class_name('month-row') return l...
(selenium, authed_get, is_headless): authed_get(CALENDAR_URL) if is_headless: inject_extension(selenium) add_button = selenium.find_element_by_class_name(ADD_BUTTON_CLASS) remove_button = selenium.find_element_by_class_name(REMOVE_BUTTON_CLASS) # reset to a known state # click the cust...
test_ext
identifier_name
error.rs
use std::{self, io, net, str}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { Io(io::Error), Utf8(str::Utf8Error), Addr(net::AddrParseError), /// `224.0.0.0` ~ `239.255.255.255` /// // `ff00::/8` IpIsMulticast, /// `0.0.0.0` IpIsUnspecified, ...
} impl From<str::Utf8Error> for Error { fn from(e: str::Utf8Error) -> Self { Error::Utf8(e) } } impl From<net::AddrParseError> for Error { fn from(e: net::AddrParseError) -> Self { Error::Addr(e) } }
{ Error::Io(e) }
identifier_body
error.rs
use std::{self, io, net, str}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { Io(io::Error), Utf8(str::Utf8Error), Addr(net::AddrParseError), /// `224.0.0.0` ~ `239.255.255.255` /// // `ff00::/8` IpIsMulticast, /// `0.0.0.0` IpIsUnspecified, ...
NotFound, } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::Io(e) } } impl From<str::Utf8Error> for Error { fn from(e: str::Utf8Error) -> Self { Error::Utf8(e) } } impl From<net::AddrParseError> for Error { fn from(e: net::AddrParseError) -> Self { ...
///3. `192.168.0.0/16` IpIsPrivate, /// Unsupport Ipv6 Now UnsupportIpv6,
random_line_split
error.rs
use std::{self, io, net, str}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { Io(io::Error), Utf8(str::Utf8Error), Addr(net::AddrParseError), /// `224.0.0.0` ~ `239.255.255.255` /// // `ff00::/8` IpIsMulticast, /// `0.0.0.0` IpIsUnspecified, ...
(e: io::Error) -> Self { Error::Io(e) } } impl From<str::Utf8Error> for Error { fn from(e: str::Utf8Error) -> Self { Error::Utf8(e) } } impl From<net::AddrParseError> for Error { fn from(e: net::AddrParseError) -> Self { Error::Addr(e) } }
from
identifier_name
RequestState.js
/** * State of the request. * * @enum {Number} */ var RequestState = { /** * Initial unissued state. * * @type Number * @constant */ UNISSUED: 0, /** * Issued but not yet active. Will become active when open slots are available. * * @type Number * @constant */ ISSUED: 1, /*...
/** * Request was cancelled, either explicitly or automatically because of low priority. * * @type Number * @constant */ CANCELLED: 4, /** * Request failed. * * @type Number * @constant */ FAILED: 5, }; export default Object.freeze(RequestState);
*/ RECEIVED: 3,
random_line_split
errors.rs
//! The rpeek library. //! //! # License //! //! Copyright (c) 2015 by Stacy Prowell. All rights reserved. //! //! Licensed under the BSD 2-Clause license. See the file LICENSE //! that is part of this distribution. This file may not be copied, //! modified, or distributed except according to those terms. use std; ...
} /// Define the kind of errors that can occur when parsing. pub type ParseResult<T> = std::result::Result<T, ParseError>;
Stalled, /// A general IO error happened. IOError(std::io::Error), /// Some other error happened. OtherError(Box<std::error::Error>),
random_line_split
errors.rs
//! The rpeek library. //! //! # License //! //! Copyright (c) 2015 by Stacy Prowell. All rights reserved. //! //! Licensed under the BSD 2-Clause license. See the file LICENSE //! that is part of this distribution. This file may not be copied, //! modified, or distributed except according to those terms. use std; ...
{ /// Lookahead value specified is too large. This occurs when the user asks to peek ahead /// too far. LookaheadTooLarge, /// Reading seems to have stalled at the end of file. StalledAtEof, /// Reading has stalled with no forward progress. Stalled, /// A general IO error happened. ...
ParseError
identifier_name
main.rs
extern crate rand; extern crate time; use std::io; use std::f64; use std::io::prelude::*; fn trapezoids_v1<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let mut sum: f64 = 0.0; let h = (b - a) / n as f64; let xk = |k: i64| a + k as f64 * h; for i in 0..n...
fn simpson<F>(data: (f64, f64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b) = data; ((b - a) / 6.0) * (f(a) + 4.0 * f(0.5 * (a + b)) + f(b)) } fn simpson_kosates<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let h = (b - a) / n as f64; let xk...
{ let (mut s_left, mut s_middle, mut s_right) = (0.0, 0.0, 0.0); let rectangle_left = |x0: f64, x1: f64| f(x0) * (x1 - x0); let rectangle_middle = |x0: f64, x1: f64| f(0.5 * (x0 + x1)) * (x1 - x0); let rectangle_right = |x0: f64, x1: f64| f(x0) * (x0 - x1); let (a, b, n) = data; let h = (b - a) ...
identifier_body
main.rs
extern crate rand; extern crate time; use std::io; use std::f64; use std::io::prelude::*; fn trapezoids_v1<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let mut sum: f64 = 0.0; let h = (b - a) / n as f64; let xk = |k: i64| a + k as f64 * h; for i in 0..n...
<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { use rand::distributions::{IndependentSample, Range}; use rand::thread_rng; let (a, b, n) = data; let between = Range::new(a, b); let mut rng = rand::thread_rng(); let mut sum = 0.0; for _ in 0..n { let x = between....
monte_carlo
identifier_name
main.rs
extern crate rand; extern crate time; use std::io; use std::f64; use std::io::prelude::*; fn trapezoids_v1<F>(data: (f64, f64, i64), f: F) -> f64 where F: Fn(f64) -> f64 { let (a, b, n) = data; let mut sum: f64 = 0.0; let h = (b - a) / n as f64; let xk = |k: i64| a + k as f64 * h; for i in 0..n...
let (a, b) = (0.0, 1.0); let mut buffer = String::new(); print!("Enter iteration count: "); io::stdout() .flush() .expect("Couldn't flush to stdout!"); io::stdin() .read_line(&mut buffer) .expect("Couldn't read line!"); let n = match buffer.trim().parse() { ...
fn main() {
random_line_split
rss.rs
use std::error::Error; use async_trait::async_trait; use futures::{StreamExt, TryFutureExt}; use rss::Channel; use bytes::Bytes; use chrono::DateTime; use itertools::Itertools; use super::Provider; use crate::utils::{Json, Map, hash, IteratorEx}; use crate::config::ConfigFeedEntry; use crate::feeds::{Feed, Entry};
pub struct RssProvider; impl RssProvider { pub fn new(_config: Json) -> Result<Self, Box<dyn Error>> { Ok(RssProvider) } } #[async_trait(?Send)] impl Provider for RssProvider { async fn fetch(&mut self, config: Map<&ConfigFeedEntry>) -> Map<Feed> { // Url -> Feed let data = config.values() ...
const MAX_CON_REQUESTS: usize = 10;
random_line_split
rss.rs
use std::error::Error; use async_trait::async_trait; use futures::{StreamExt, TryFutureExt}; use rss::Channel; use bytes::Bytes; use chrono::DateTime; use itertools::Itertools; use super::Provider; use crate::utils::{Json, Map, hash, IteratorEx}; use crate::config::ConfigFeedEntry; use crate::feeds::{Feed, Entry}; co...
(_config: Json) -> Result<Self, Box<dyn Error>> { Ok(RssProvider) } } #[async_trait(?Send)] impl Provider for RssProvider { async fn fetch(&mut self, config: Map<&ConfigFeedEntry>) -> Map<Feed> { // Url -> Feed let data = config.values() .map(|entry| entry.provider_data.as_str()) ...
new
identifier_name
rss.rs
use std::error::Error; use async_trait::async_trait; use futures::{StreamExt, TryFutureExt}; use rss::Channel; use bytes::Bytes; use chrono::DateTime; use itertools::Itertools; use super::Provider; use crate::utils::{Json, Map, hash, IteratorEx}; use crate::config::ConfigFeedEntry; use crate::feeds::{Feed, Entry}; co...
feed.notifications.push(entry); } feed }, Ok(Err(err)) => Feed::from_err(&format!("Unable to parse {}", url), &err.to_string()), Err(err) => Feed::from_err(&format!("Unable to fetch {}", url), &err.to_string()), } }
{ let parsed = response.map(|content| Channel::read_from(&*content)); match parsed { Ok(Ok(chan)) => { let mut feed = Feed::new(); for item in chan.items() { let title = item.title().clone().unwrap_or("<No Title>"); let timestamp = item.pub_date() .and_then(|time| DateTim...
identifier_body
error.rs
decoder::DecoderError; use rodio::PlayError; /// An enum containing all kinds of game framework errors. #[derive(Debug, Clone)] pub enum GameError { /// An error in the filesystem layout FilesystemError(String), /// An error in the config file ConfigError(String), /// Happens when an `winit::event_...
} impl From<DecoderError> for GameError { fn from(e: DecoderError) -> GameError { let errstr = format!("Audio decoder error: {:?}", e); GameError::AudioError(errstr) } } impl From<PlayError> for GameError { fn from(e: PlayError) -> GameError { let errstr = format!("Audio playing e...
{ let errstr = format!("Zip error: {}", e.to_string()); GameError::ResourceLoadError(errstr) }
identifier_body
error.rs
decoder::DecoderError; use rodio::PlayError; /// An enum containing all kinds of game framework errors. #[derive(Debug, Clone)] pub enum GameError { /// An error in the filesystem layout FilesystemError(String), /// An error in the config file ConfigError(String), /// Happens when an `winit::event_...
(e: zip::result::ZipError) -> GameError { let errstr = format!("Zip error: {}", e.to_string()); GameError::ResourceLoadError(errstr) } } impl From<DecoderError> for GameError { fn from(e: DecoderError) -> GameError { let errstr = format!("Audio decoder error: {:?}", e); GameErro...
from
identifier_name
error.rs
decoder::DecoderError; use rodio::PlayError; /// An enum containing all kinds of game framework errors. #[derive(Debug, Clone)] pub enum GameError { /// An error in the filesystem layout FilesystemError(String), /// An error in the config file ConfigError(String), /// Happens when an `winit::event_...
"Resource not found: {}, searched in paths {:?}", s, paths ), GameError::WindowError(ref e) => write!(f, "Window creation error: {}", e), GameError::CustomError(ref s) => write!(f, "Custom error: {}", s), GameError::CanvasMSAAError => write...
GameError::ResourceLoadError(ref s) => write!(f, "Error loading resource: {}", s), GameError::ResourceNotFound(ref s, ref paths) => write!( f,
random_line_split
main.rs
#[macro_use] extern crate diesel;
#[macro_use] extern crate log; mod database; pub mod models; pub mod routes; mod schema; pub mod util; use crate::routes::rest; use crate::routes::rest::izettle::IZettleNotifier; use crate::util::{catchers, FileResponder}; use clap::Parser; use dotenv::dotenv; use rocket::routes; #[derive(Default, Parser)] pub stru...
random_line_split
main.rs
#[macro_use] extern crate diesel; #[macro_use] extern crate log; mod database; pub mod models; pub mod routes; mod schema; pub mod util; use crate::routes::rest; use crate::routes::rest::izettle::IZettleNotifier; use crate::util::{catchers, FileResponder}; use clap::Parser; use dotenv::dotenv; use rocket::routes; ...
{ /// Database url specified as a postgres:// uri #[clap(long, short, env = "DATABASE_URL")] database: String, /// Run database migrations on startup #[clap(long, short = 'm', env = "RUN_MIGRATIONS")] run_migrations: bool, /// Enable HTTP cache control of statically served files #[cla...
Opt
identifier_name
main.rs
#[macro_use] extern crate diesel; #[macro_use] extern crate log; mod database; pub mod models; pub mod routes; mod schema; pub mod util; use crate::routes::rest; use crate::routes::rest::izettle::IZettleNotifier; use crate::util::{catchers, FileResponder}; use clap::Parser; use dotenv::dotenv; use rocket::routes; ...
let rocket = rocket::build() .manage(db_pool) .manage(IZettleNotifier::default()) .register("/", catchers()) .attach(FileResponder { folder: "www", enable_cache: opt.static_file_cache, max_age: opt.max_age, }) .mount( ...
{ database::run_migrations(&db_pool); }
conditional_block
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HeadComponent } from '....
declarations: [ AppComponent, HeadComponent, NavComponent, PlayComponent, IndexComponent, LoginrComponent, PictureChooserComponent ], imports: [ BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([ { path: 'play', component: PlayComponent }, { path...
@NgModule({
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HeadComponent } from '....
{ }
AppModule
identifier_name
mod.rs
use std::sync::Arc; use crate::AppState; mod actions; mod devices; mod ws; use actions::*; use devices::*; use anyhow::Result; use warp::Filter; use self::ws::ws; pub fn with_state( app_state: &Arc<AppState>, ) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone
// Example of warp usage: https://github.com/seanmonstar/warp/blob/master/examples/todos.rs pub fn init_api(app_state: &Arc<AppState>) -> Result<()> { let api = warp::path("api") .and(warp::path("v1")) .and(devices(app_state).or(actions(app_state))); let ws = ws(app_state); tokio::spawn(...
{ let app_state = app_state.clone(); warp::any().map(move || app_state.clone()) }
identifier_body
mod.rs
use std::sync::Arc; use crate::AppState; mod actions; mod devices; mod ws; use actions::*; use devices::*; use anyhow::Result; use warp::Filter; use self::ws::ws; pub fn with_state( app_state: &Arc<AppState>, ) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone { let app_...
(app_state: &Arc<AppState>) -> Result<()> { let api = warp::path("api") .and(warp::path("v1")) .and(devices(app_state).or(actions(app_state))); let ws = ws(app_state); tokio::spawn(async move { warp::serve(ws.or(api)).run(([127, 0, 0, 1], 45289)).await; }); Ok(()) }
init_api
identifier_name
mod.rs
use std::sync::Arc; use crate::AppState; mod actions; mod devices; mod ws; use actions::*; use devices::*; use anyhow::Result; use warp::Filter; use self::ws::ws; pub fn with_state( app_state: &Arc<AppState>, ) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone { let app_...
}
random_line_split
nrvo.rs
// run-pass // When the NRVO is applied, the return place (`_0`) gets treated like a normal local. For example, // its address may be taken and it may be written to indirectly. Ensure that MIRI can handle this. #![feature(const_mut_refs)] #[inline(never)] // Try to ensure that MIR optimizations don't optimize this a...
const fn nrvo() -> [u8; 1024] { let mut buf = [0; 1024]; init(&mut buf); buf } const BUF: [u8; 1024] = nrvo(); fn main() { assert_eq!(BUF[33], 3); assert_eq!(BUF[19], 0); assert_eq!(BUF[444], 4); }
{ buf[33] = 3; buf[444] = 4; }
identifier_body
nrvo.rs
// run-pass // When the NRVO is applied, the return place (`_0`) gets treated like a normal local. For example, // its address may be taken and it may be written to indirectly. Ensure that MIRI can handle this. #![feature(const_mut_refs)] #[inline(never)] // Try to ensure that MIR optimizations don't optimize this a...
(buf: &mut [u8; 1024]) { buf[33] = 3; buf[444] = 4; } const fn nrvo() -> [u8; 1024] { let mut buf = [0; 1024]; init(&mut buf); buf } const BUF: [u8; 1024] = nrvo(); fn main() { assert_eq!(BUF[33], 3); assert_eq!(BUF[19], 0); assert_eq!(BUF[444], 4); }
init
identifier_name
nrvo.rs
// run-pass
#![feature(const_mut_refs)] #[inline(never)] // Try to ensure that MIR optimizations don't optimize this away. const fn init(buf: &mut [u8; 1024]) { buf[33] = 3; buf[444] = 4; } const fn nrvo() -> [u8; 1024] { let mut buf = [0; 1024]; init(&mut buf); buf } const BUF: [u8; 1024] = nrvo(); fn mai...
// When the NRVO is applied, the return place (`_0`) gets treated like a normal local. For example, // its address may be taken and it may be written to indirectly. Ensure that MIRI can handle this.
random_line_split
lint-plugin-forbid-cmdline.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 ...
() { } //~ ERROR item is named 'lintme' #[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint) pub fn main() { lintme(); }
lintme
identifier_name
lint-plugin-forbid-cmdline.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 ...
//~ ERROR item is named 'lintme' #[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint) pub fn main() { lintme(); }
{ }
identifier_body
lint-plugin-forbid-cmdline.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 ...
#[plugin] #[no_link] extern crate lint_plugin_test; fn lintme() { } //~ ERROR item is named 'lintme' #[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint) pub fn main() { lintme(); }
// ignore-stage1 // compile-flags: -F test-lint #![feature(plugin)]
random_line_split
TabSet.js
import React, { Fragment } from 'react' import noop from '@utils/noop' const DEFAULT_TAB = { id: 'blank', onClick: noop, renderTab: () => <div />, renderContents: () => <div />, } const TabSet = ({ activeTabId, buttons, onTabClicked = noop, showTabs = true, tabs = [] }) => { if (tabs.length === 0) tabs.push...
activeTab.id === tab.id && 'is-active', ].filter(Boolean).join(' ') return <li key={tab.id} className={liClassName} onClick={tab.onClick}>{tab.tab}</li> })} <li className="buttons">{buttons}</li> </ul> </Fragment> } <div ...
const liClassName = [ 'tab', tab.className, tab.id,
random_line_split
landing-controller.js
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed...
}; $scope.addAppDefinition = function() { _internalCreateModal({ template: 'views/modal/add-app-definition-modal.html', scope: $scope }, $modal, $scope); }; $scope.deleteApp = function(app) { if(app && app.id) { ...
{ $window.location.href = app.fixedUrl; }
conditional_block
landing-controller.js
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed...
if(index >= 0) { $scope.model.apps.splice(index, 1); } }); } }; $scope.loadApps(); }] );
}
random_line_split
info_test_case.rs
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors use super::super::super::*; use alloc::string::String; use alloc::vec::Vec; #[derive(Default)] pub(super) struct InstrInfoTestCase { pub(super) line_number: u32, pub(super) bitness: u32, pub(super) hex_bytes: String, pu...
pub(super) stack_pointer_increment: i32, pub(super) is_privileged: bool, pub(super) is_stack_instruction: bool, pub(super) is_save_restore_instruction: bool, pub(super) is_special: bool, pub(super) used_registers: Vec<UsedRegister>, pub(super) used_memory: Vec<UsedMemory>, pub(super) flow_control: FlowControl, ...
pub(super) rflags_undefined: u32, pub(super) rflags_written: u32, pub(super) rflags_cleared: u32, pub(super) rflags_set: u32,
random_line_split
info_test_case.rs
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors use super::super::super::*; use alloc::string::String; use alloc::vec::Vec; #[derive(Default)] pub(super) struct
{ pub(super) line_number: u32, pub(super) bitness: u32, pub(super) hex_bytes: String, pub(super) code: Code, pub(super) decoder_options: u32, pub(super) encoding: EncodingKind, pub(super) cpuid_features: Vec<CpuidFeature>, pub(super) rflags_read: u32, pub(super) rflags_undefined: u32, pub(super) rflags_writt...
InstrInfoTestCase
identifier_name
064-minimum-path-sum.py
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [] for _ in range(m): dp.append([None] * (n)) ...
else: cost = grid[row][col] + min(solve(row, col+1), solve(row+1, col)) dp[row][col] = cost # print 'dp(%s,%s) is %s' % (row, col, ans) return cost return solve(0, 0)
cost = grid[row][col] + solve(row+1, col)
conditional_block
064-minimum-path-sum.py
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [] for _ in range(m): dp.append([None] * (n)) ...
cost = grid[row][col] + min(solve(row, col+1), solve(row+1, col)) dp[row][col] = cost # print 'dp(%s,%s) is %s' % (row, col, ans) return cost return solve(0, 0)
cost = grid[row][col] + solve(row, col+1) elif col == n-1: cost = grid[row][col] + solve(row+1, col) else:
random_line_split
064-minimum-path-sum.py
class Solution(object):
cost = grid[row][col] + solve(row, col+1) elif col == n-1: cost = grid[row][col] + solve(row+1, col) else: cost = grid[row][col] + min(solve(row, col+1), solve(row+1, col)) dp[row][col] = cost # print 'dp(%s,%s) is %s' % (ro...
def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [] for _ in range(m): dp.append([None] * (n)) dp[m-1][n-1] = grid...
identifier_body
064-minimum-path-sum.py
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [] for _ in range(m): dp.append([None] * (n)) ...
(row, col): if dp[row][col] is not None: return dp[row][col] if row == m-1: cost = grid[row][col] + solve(row, col+1) elif col == n-1: cost = grid[row][col] + solve(row+1, col) else: cost = grid[row][col] + m...
solve
identifier_name
main.rs
extern crate wire; extern crate ctfcommon; extern crate rustc_serialize; extern crate docopt; use ctfcommon::request::CTFRequest; use ctfcommon::response::CTFResponse; use ctfcommon::constants::{SERVER_WRITE_LIMIT, SERVER_READ_LIMIT, PORT, ADDRESS}; use docopt::Docopt; use wire::SizeLimit; mod formatting; static USA...
"; #[derive(RustcDecodable, Debug)] struct Args { flag_p: Option<u16>, arg_flag_id: String, arg_flag_number: usize, arg_username: String, arg_start: usize, arg_end: usize, cmd_claim: bool, cmd_leaderboard: bool, } fn main() { highscores_request(0, 5, PORT); let args: Args = Do...
Options: -p <port> TCP port to connect to (optional). The default port is the right one.
random_line_split
main.rs
extern crate wire; extern crate ctfcommon; extern crate rustc_serialize; extern crate docopt; use ctfcommon::request::CTFRequest; use ctfcommon::response::CTFResponse; use ctfcommon::constants::{SERVER_WRITE_LIMIT, SERVER_READ_LIMIT, PORT, ADDRESS}; use docopt::Docopt; use wire::SizeLimit; mod formatting; static USA...
(id: usize, flag: String, user: String, port: u16) { // Create a request to check a flag // TODO: Get rid of this cloning let flag_offer = CTFRequest::verify_flag(id, flag, user.clone()); // Print statuses! if let Some(CTFResponse::FlagVerified(_, verified, taken)) = send(&flag_offer, port) { ...
flag_verify_request
identifier_name
main.rs
extern crate wire; extern crate ctfcommon; extern crate rustc_serialize; extern crate docopt; use ctfcommon::request::CTFRequest; use ctfcommon::response::CTFResponse; use ctfcommon::constants::{SERVER_WRITE_LIMIT, SERVER_READ_LIMIT, PORT, ADDRESS}; use docopt::Docopt; use wire::SizeLimit; mod formatting; static USA...
i.into_blocking_iter().next() }
{ // Control max size of incoming and outgoing messages. // Values are flipped beacuse we are on the client side. let read_limit = SizeLimit::Bounded(SERVER_WRITE_LIMIT); let write_limit = SizeLimit::Bounded(SERVER_READ_LIMIT); // Try to connect to the flag server... let (i, mut o) = match wir...
identifier_body
load.js
function loadfs() { //check if browser supports file api and filereader features if (window.File && window.FileReader && window.FileList && window.Blob) { //this is not completely neccesary, just a nice function I found to make the //file size format friendlier //http://stackoverflow.com/questions/10420352/co...
//this function is called when the input loads an image function renderDB(file){ var reader = new FileReader(); reader.onload = function(event){ // console.log("event") // console.log(event) source = event.target // console.log("source") // console.log(source) ...
{ var thresh = si ? 1000 : 1024; if(bytes < thresh) return bytes + ' B'; var units = si ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']; var u = -1; do { bytes /= thresh; ++u; } while(bytes >= th...
identifier_body
load.js
function
() { //check if browser supports file api and filereader features if (window.File && window.FileReader && window.FileList && window.Blob) { //this is not completely neccesary, just a nice function I found to make the //file size format friendlier //http://stackoverflow.com/questions/10420352/converting-file-s...
loadfs
identifier_name
load.js
function loadfs() { //check if browser supports file api and filereader features if (window.File && window.FileReader && window.FileList && window.Blob) { //this is not completely neccesary, just a nice function I found to make the //file size format friendlier //http://stackoverflow.com/questions/10420352/co...
}
{ alert('The File APIs are not fully supported in this browser.'); }
conditional_block
load.js
function loadfs() { //check if browser supports file api and filereader features if (window.File && window.FileReader && window.FileList && window.Blob) { //this is not completely neccesary, just a nice function I found to make the //file size format friendlier //http://stackoverflow.com/questions/10420352/co...
} }
random_line_split
users.py
# -*- coding: utf-8 -*- import webapp2 from boilerplate import models from boilerplate import forms from boilerplate.handlers import BaseHandler from google.appengine.datastore.datastore_query import Cursor from google.appengine.ext import ndb from google.appengine.api import users as googleusers from collections impor...
class EditProfileForm(forms.EditProfileForm): activated = fields.BooleanField('Activated') class List(BaseHandler): def get(self): p = self.request.get('p') q = self.request.get('q') c = self.request.get('c') forward = True if p not in ['prev'] else False cursor = Curso...
random_line_split
users.py
# -*- coding: utf-8 -*- import webapp2 from boilerplate import models from boilerplate import forms from boilerplate.handlers import BaseHandler from google.appengine.datastore.datastore_query import Cursor from google.appengine.ext import ndb from google.appengine.api import users as googleusers from collections impor...
self.view.prev_cursor = cursor.reversed() else: users, next_cursor, more = qry.order(-models.User.key).fetch_page(PAGE_SIZE, start_cursor=cursor) users = list(reversed(users)) if next_cursor and more: self.view.prev_cursor = next_cursor ...
def get(self): p = self.request.get('p') q = self.request.get('q') c = self.request.get('c') forward = True if p not in ['prev'] else False cursor = Cursor(urlsafe=c) if q: qry = models.User.query(ndb.OR(models.User.last_name == q, ...
identifier_body
users.py
# -*- coding: utf-8 -*- import webapp2 from boilerplate import models from boilerplate import forms from boilerplate.handlers import BaseHandler from google.appengine.datastore.datastore_query import Cursor from google.appengine.ext import ndb from google.appengine.api import users as googleusers from collections impor...
(forms.EditProfileForm): activated = fields.BooleanField('Activated') class List(BaseHandler): def get(self): p = self.request.get('p') q = self.request.get('q') c = self.request.get('c') forward = True if p not in ['prev'] else False cursor = Cursor(urlsafe=c) ...
EditProfileForm
identifier_name
users.py
# -*- coding: utf-8 -*- import webapp2 from boilerplate import models from boilerplate import forms from boilerplate.handlers import BaseHandler from google.appengine.datastore.datastore_query import Cursor from google.appengine.ext import ndb from google.appengine.api import users as googleusers from collections impor...
def pager_url(p, cursor): params = OrderedDict() if q: params['q'] = q if p in ['prev']: params['p'] = p if cursor: params['c'] = cursor.urlsafe() return self.uri_for('user-list', **params) se...
users, next_cursor, more = qry.order(-models.User.key).fetch_page(PAGE_SIZE, start_cursor=cursor) users = list(reversed(users)) if next_cursor and more: self.view.prev_cursor = next_cursor self.view.next_cursor = cursor.reversed()
conditional_block
mod.rs
//! Parsing and interpretation for unoptimized Brainfuck abstract syntax trees. //! //! In `bfi` by default, this pass runs before run-length encoding and peephole optimization. To //! run the unoptimized AST directly and skip all optimization, pass `--ast` flag. //! //! In this module, BF programs are represented by t...
}
random_line_split
mod.rs
//! Parsing and interpretation for unoptimized Brainfuck abstract syntax trees. //! //! In `bfi` by default, this pass runs before run-length encoding and peephole optimization. To //! run the unoptimized AST directly and skip all optimization, pass `--ast` flag. //! //! In this module, BF programs are represented by t...
{ /// A non-loop command. /// /// # Invariants /// /// The `Command` cannot be `Begin` or `End`. Cmd(Command), /// A loop surrounding a sequence of instructions. Loop(Box<[Statement]>), }
Statement
identifier_name
pyplot03.py
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import re rootPath = "/Users/jeff/work/debug/20181216_hard_fe2k_15fps/" finalLogFile = "rosout.log.2" def appendTimestamps(arr, start, stop, flag): #flag = True d = stop - start if flag or (d > -10 and d < 2000): arr.append...
print("===length: ", len(delays[0]),len(delays[1]),len(delays[2]),len(delays[3]),len(delays[4])) delayavg = [0,0,0,0,0,0] if len(delays[0]) == 0: print("empty delay array") quit() for i in range(len(delays[0])): delayavg[0] = delayavg[0] + delays[0][i] delayavg[1] = delayavg[1] + delays[1][i] d...
appendTimestamps(delays[1], stamps[0][i], stamps[1][i * 4], True) # OA appendTimestamps(delays[2], stamps[1][i * 4], stamps[2][i], True) # Fusion appendTimestamps(delays[3], stamps[2][i], stamps[3][i], True) # Flink appendTimestamps(delays[4], stamps[3][i], stamps[4][i], True) # V2x ...
conditional_block
pyplot03.py
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import re rootPath = "/Users/jeff/work/debug/20181216_hard_fe2k_15fps/" finalLogFile = "rosout.log.2" def appendTimestamps(arr, start, stop, flag): #flag = True d = stop - start if flag or (d > -10 and d < 2000): arr.append...
stamps[3].append(long(ret[0][1])) # flink stamps[4].append(long(ret[0][4])) # v2x # oa oastamps = ret[0][3].split(',') t1 = long(oastamps[0]) t2 = long(oastamps[1]) t3 = long(oastamps[2]) mi = t1 ma = t1 if mi > t2: mi = t2 ...
stamps[2].append(long(ret[0][2])) # fusion
random_line_split
pyplot03.py
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import re rootPath = "/Users/jeff/work/debug/20181216_hard_fe2k_15fps/" finalLogFile = "rosout.log.2" def appendTimestamps(arr, start, stop, flag): #flag = True
## camera -> OA(ObjectAanalytics) -> Fusion -> Flink -> V2X stamps = [[],[],[],[],[]] log = open(rootPath + finalLogFile) lines = log.readlines() log.close() for i in range(0, len(lines)): line = lines[i].rstrip('\n').strip() ret = re.findall(r'\"camera_output_ts\":(\d+),.*\"flink_output_ts\":(\d+),.*\"fusi...
d = stop - start if flag or (d > -10 and d < 2000): arr.append(d) return True return False
identifier_body
pyplot03.py
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import re rootPath = "/Users/jeff/work/debug/20181216_hard_fe2k_15fps/" finalLogFile = "rosout.log.2" def
(arr, start, stop, flag): #flag = True d = stop - start if flag or (d > -10 and d < 2000): arr.append(d) return True return False ## camera -> OA(ObjectAanalytics) -> Fusion -> Flink -> V2X stamps = [[],[],[],[],[]] log = open(rootPath + finalLogFile) lines = log.readlines() log.close(...
appendTimestamps
identifier_name
overloaded-deref.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 ...
let p = Rc::new(RefCell::new(Point {x: 1, y: 2})); (*(*p).borrow_mut()).x = 3; (*(*p).borrow_mut()).y += 3; assert_eq!(*(*p).borrow(), Point {x: 3, y: 5}); let v = Rc::new(RefCell::new(vec!(1, 2, 3))); (*(*v).borrow_mut())[0] = 3; (*(*v).borrow_mut())[1] += 3; assert_eq!(((*(*v).borrow...
random_line_split
overloaded-deref.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 ...
() { assert_eq!(*Rc::new(5), 5); assert_eq!(***Rc::new(Box::new(Box::new(5))), 5); assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4}); let i = Rc::new(RefCell::new(2)); let i_value = *(*i).borrow(); *(*i).borrow_mut() = 5; assert_eq!((i_value, *(*i).borrow()), (2, 5)); let s ...
main
identifier_name
020_stack_action.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
meta = sqlalchemy.MetaData(bind=migrate_engine) stack = sqlalchemy.Table('stack', meta, autoload=True) stack.c.action.drop()
identifier_body
020_stack_action.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
(migrate_engine): meta = sqlalchemy.MetaData(bind=migrate_engine) stack = sqlalchemy.Table('stack', meta, autoload=True) # Align with action/status now used in the event/resource tables action = sqlalchemy.Column('action', sqlalchemy.String(length=255)) action.create(...
upgrade
identifier_name