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
049_group_anagrams.py
"""Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
[ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. """ from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: store =...
Output:
random_line_split
049_group_anagrams.py
"""Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"] Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of y...
(self, strs: List[str]) -> List[List[str]]: store = {} for item in strs: key = ''.join(sorted(item)) if key in store: store[key].append(item) else: store[key] = [item] return store.values() if __name__ == '__main__': cas...
groupAnagrams
identifier_name
049_group_anagrams.py
"""Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"] Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of y...
if __name__ == '__main__': cases = [ ( ["eat", "tea", "tan", "ate", "nat", "bat"], [ ["ate", "eat", "tea"], ["nat", "tan"], ["bat"] ] ), ] # yapf: disable for case in cases: for S in [Solution]: ...
store = {} for item in strs: key = ''.join(sorted(item)) if key in store: store[key].append(item) else: store[key] = [item] return store.values()
identifier_body
settings.py
""" Django settings for sw_tts project. Generated by 'django-admin startproject' using Django 1.9.8. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # ...
('frontend', os.path.join(BASE_DIR, 'frontend')), ) LANGUAGE_CODE = 'ru-Ru' OUTPUT_DIR = os.path.join(BASE_DIR, 'generated') MAX_SOUND_LIFE = 60*60*12 # seconds of sound file storing SOCIAL_AUTH_VK_OPENAPI_ID = '5596606' SOCIAL_AUTH_VK_APP_SECRET = 'jBx8nnH7pzevq7UA3hH0' SOCIAL_AUTH_VK_APP_USER_MODE = 2 VK_A...
STATIC_URL = '/static/' STATICFILES_DIRS = (
random_line_split
md.enter.ts
import { Animation } from '../../../interface'; import { createAnimation } from '../../../utils/animation/animation'; /** * Md Popover Enter Animation */ export const mdEnterAnimation = (baseEl: HTMLElement, ev?: Event): Animation => { const POPOVER_MD_BODY_PADDING = 12; const doc = (baseEl.ownerDocument as any)...
.addElement(baseEl.querySelector('.popover-viewport')!) .fromTo('opacity', 0.01, 1); return baseAnimation .addElement(baseEl) .easing('cubic-bezier(0.36,0.66,0.04,1)') .duration(300) .addAnimation([backdropAnimation, wrapperAnimation, contentAnimation, viewportAnimation]); };
viewportAnimation
random_line_split
md.enter.ts
import { Animation } from '../../../interface'; import { createAnimation } from '../../../utils/animation/animation'; /** * Md Popover Enter Animation */ export const mdEnterAnimation = (baseEl: HTMLElement, ev?: Event): Animation => { const POPOVER_MD_BODY_PADDING = 12; const doc = (baseEl.ownerDocument as any)...
else if (targetTop + targetHeight + contentHeight > bodyHeight) { contentEl.style.bottom = POPOVER_MD_BODY_PADDING + 'px'; } const baseAnimation = createAnimation(); const backdropAnimation = createAnimation(); const wrapperAnimation = createAnimation(); const contentAnimation = createAnimation(); con...
{ popoverCSS.top = targetTop - contentHeight - targetHeight; baseEl.className = baseEl.className + ' popover-bottom'; originY = 'bottom'; // If there isn't room for it to pop up above the target cut it off }
conditional_block
geo-util.js
define([ 'gmaps', 'config',
'app-state' ], function (gmaps, config, L, leafletPip, appState) { "use strict"; var geocoder = new gmaps.Geocoder(), // simplifies place name for geocoder to get better results locationAddress = function(place_name, district_name) { district_name = district_name || config.defaultDistrictNam...
'leaflet', 'leaflet-pip',
random_line_split
geo-util.js
define([ 'gmaps', 'config', 'leaflet', 'leaflet-pip', 'app-state' ], function (gmaps, config, L, leafletPip, appState) { "use strict"; var geocoder = new gmaps.Geocoder(), // simplifies place name for geocoder to get better results locationAddress = function(place_name, district_name) { ...
} return isValid; } ; return { geoLocate: geoLocate, locationAddress: locationAddress, isValidLocation: isValidLocation }; });
// district model already in the collection if (district.has('geometry')) { // pointInLayer returns array of matched layers; empty array if nothing was matched isValid = (leafletPip.pointInLayer(latLng, L.geoJson(district.get('geometry')), true).length > 0); } ...
conditional_block
repoclosure.py
# repoclosure.py # DNF plugin adding a command to display a list of unresolved dependencies # for repositories. # # Copyright (C) 2015 Igor Gnatenko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Publi...
pkgs.intersection_update(checkpkgs) # --best not applied earlier due to --check, so do it now if self.base.conf.best: available = available.latest() for pkg in pkgs: unresolved[pkg] = set() for req in pkg.requires: req...
checkpkgs.add(pkgs_filtered)
conditional_block
repoclosure.py
# repoclosure.py # DNF plugin adding a command to display a list of unresolved dependencies # for repositories. # # Copyright (C) 2015 Igor Gnatenko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Publi...
(dnf.Plugin): name = "repoclosure" def __init__(self, base, cli): super(RepoClosure, self).__init__(base, cli) if cli is None: return cli.register_command(RepoClosureCommand) class RepoClosureCommand(dnf.cli.Command): aliases = ("repoclosure",) summary = _("Displa...
RepoClosure
identifier_name
repoclosure.py
# repoclosure.py # DNF plugin adding a command to display a list of unresolved dependencies # for repositories. # # Copyright (C) 2015 Igor Gnatenko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Publi...
@staticmethod def set_argparser(parser): parser.add_argument("--arch", default=[], action="append", dest='arches', help=_("check packages of the given archs, can be " "specified multiple times")) parser.add_argument("--check", defau...
return {k: v for k, v in unresolved_transition.items() if v}
random_line_split
repoclosure.py
# repoclosure.py # DNF plugin adding a command to display a list of unresolved dependencies # for repositories. # # Copyright (C) 2015 Igor Gnatenko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Publi...
def _get_unresolved(self, arch=None): unresolved = {} deps = set() available = self.base.sack.query().available() if self.base.conf.best and not self.opts.check: available = available.latest() elif self.opts.newest or self.base.conf.best: available ...
if self.opts.arches: unresolved = self._get_unresolved(self.opts.arches) else: unresolved = self._get_unresolved() for pkg in sorted(unresolved.keys()): print("package: {} from {}".format(str(pkg), pkg.reponame)) print(" unresolved deps:") for...
identifier_body
our_corner_kick.py
import standard_play import behavior import skills import tactics import robocup import constants import main import enum class OurCornerKick(standard_play.StandardPlay): MinChipRange = 0.3 MaxChipRange = 3.0 ChipperPower = 0.5 TargetSegmentWidth = 1.5 MaxKickSpeed = 0.5 MaxKickAccel = 0.5 ...
(self): self.kicker = skills.line_kick.LineKick() self.kicker.use_chipper = True self.kicker.chip_power = OurCornerKick.ChipperPower # TODO: base this on the target dist from the bot self.kicker.min_chip_range = OurCornerKick.MinChipRange self.kicker.max_chip_range = OurCornerKi...
on_enter_running
identifier_name
our_corner_kick.py
import standard_play import behavior import skills import tactics import robocup import constants import main import enum class OurCornerKick(standard_play.StandardPlay): MinChipRange = 0.3 MaxChipRange = 3.0 ChipperPower = 0.5 TargetSegmentWidth = 1.5
def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') self.kicker = skills.line_kick.LineKick() self.add_transit...
MaxKickSpeed = 0.5 MaxKickAccel = 0.5
random_line_split
our_corner_kick.py
import standard_play import behavior import skills import tactics import robocup import constants import main import enum class OurCornerKick(standard_play.StandardPlay): MinChipRange = 0.3 MaxChipRange = 3.0 ChipperPower = 0.5 TargetSegmentWidth = 1.5 MaxKickSpeed = 0.5 MaxKickAccel = 0.5 ...
@classmethod def is_restart(cls): return True def on_enter_running(self): self.kicker = skills.line_kick.LineKick() self.kicker.use_chipper = True self.kicker.chip_power = OurCornerKick.ChipperPower # TODO: base this on the target dist from the bot self.kicker.min...
return float("inf")
conditional_block
our_corner_kick.py
import standard_play import behavior import skills import tactics import robocup import constants import main import enum class OurCornerKick(standard_play.StandardPlay): MinChipRange = 0.3 MaxChipRange = 3.0 ChipperPower = 0.5 TargetSegmentWidth = 1.5 MaxKickSpeed = 0.5 MaxKickAccel = 0.5 ...
@classmethod def is_restart(cls): return True def on_enter_running(self): self.kicker = skills.line_kick.LineKick() self.kicker.use_chipper = True self.kicker.chip_power = OurCornerKick.ChipperPower # TODO: base this on the target dist from the bot self.kicker.min...
gs = main.game_state() if gs.is_ready_state() and gs.is_our_direct() and main.ball().pos.y > ( constants.Field.Length - 1.0): return 1 else: return float("inf")
identifier_body
tickerytab.py
# Copyright 2010 Fluidinfo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(TickeryTab): # Define these in subclasses instructions = None instructionsTitle = None tabName = None defaultQuery = None def __init__(self, topPanel): TickeryTab.__init__(self, topPanel) # Get the query string and wanted tab, if any, from URL args. args = Window.getLo...
LargeQueryTab
identifier_name
tickerytab.py
# Copyright 2010 Fluidinfo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def clearCheckResult(self): self.checkResult.clear() def onClick(self, sender): if sender == self.db: width = (Window.getClientWidth() - POPUP_WIDTH) / 2.0 self.popup.setPopupPosition(width, 100) self.popup.show() else: self.process() ...
self.results.clear()
identifier_body
tickerytab.py
# Copyright 2010 Fluidinfo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
else: return 'Results set is empty.' class TickeryTab(VerticalPanel): process = None # Define in subclass. def __init__(self, topPanel, **kwargs): VerticalPanel.__init__(self, HorizontalAlignment=HasAlignment.ALIGN_LEFT, Sty...
nUsers = len(users) if nUsers > 1: plural = 's' else: plural = '' return 'Your query matches %s user%s:' % (nUsers, plural)
conditional_block
tickerytab.py
# Copyright 2010 Fluidinfo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def __init__(self, topPanel, **kwargs): VerticalPanel.__init__(self, HorizontalAlignment=HasAlignment.ALIGN_LEFT, StyleName='tickery-tab', **kwargs) self.topPanel = topPanel # don't add this yet! se...
random_line_split
perf-index.ts
/* Copyright (C) 2017 Jayesh Salvi, Blue Math Software Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
return points; } window.onload = () => { let POINTS_DATA = new bm.NDArray(generateData()); let npoints = POINTS_DATA.shape[0]; let Y = POINTS_DATA.slice(':',1); Y.reshape([npoints]); let X = POINTS_DATA.slice(':',0); let A = new bm.NDArray({shape:[npoints,2]}); A.fill(1); for(let i=0; i<npoints; i++...
{ let y = m*x+c; points.push([ x+Math.random()*NOISE_WEIGHT, y+Math.random()*NOISE_WEIGHT ]); }
conditional_block
perf-index.ts
/* Copyright (C) 2017 Jayesh Salvi, Blue Math Software Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
y+Math.random()*NOISE_WEIGHT ]); } return points; } window.onload = () => { let POINTS_DATA = new bm.NDArray(generateData()); let npoints = POINTS_DATA.shape[0]; let Y = POINTS_DATA.slice(':',1); Y.reshape([npoints]); let X = POINTS_DATA.slice(':',0); let A = new bm.NDArray({shape:[npoints,2]...
for(let x=xmin; x<=xmax; x+=step) { let y = m*x+c; points.push([ x+Math.random()*NOISE_WEIGHT,
random_line_split
perf-index.ts
/* Copyright (C) 2017 Jayesh Salvi, Blue Math Software Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
window.onload = () => { let POINTS_DATA = new bm.NDArray(generateData()); let npoints = POINTS_DATA.shape[0]; let Y = POINTS_DATA.slice(':',1); Y.reshape([npoints]); let X = POINTS_DATA.slice(':',0); let A = new bm.NDArray({shape:[npoints,2]}); A.fill(1); for(let i=0; i<npoints; i++) { A.set(i,0,P...
{ let m = LINE_SLOPE; let c = Y_INTERCEPT; let points = []; let xmin = -5; let xmax = 5; let nsamples = 100000; let step = (xmax-xmin)/nsamples; for(let x=xmin; x<=xmax; x+=step) { let y = m*x+c; points.push([ x+Math.random()*NOISE_WEIGHT, y+Math.random()*NOISE_WEIGHT ]); } ...
identifier_body
perf-index.ts
/* Copyright (C) 2017 Jayesh Salvi, Blue Math Software Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
() { let m = LINE_SLOPE; let c = Y_INTERCEPT; let points = []; let xmin = -5; let xmax = 5; let nsamples = 100000; let step = (xmax-xmin)/nsamples; for(let x=xmin; x<=xmax; x+=step) { let y = m*x+c; points.push([ x+Math.random()*NOISE_WEIGHT, y+Math.random()*NOISE_WEIGHT ]); ...
generateData
identifier_name
mem.rs
ABI-required minimum alignment of a type /// /// This is the alignment used for struct fields. It may be smaller /// than the preferred alignment. #[inline] #[stable] pub fn min_align_of<T>() -> uint { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the v...
/// Convert an u64 from little endian to the target's endianness. /// /// On little endian, this is a no-op. On big endian, the bytes are swapped. #[inline] #[deprecated = "use `Int::from_le` instead"] pub fn from_le64(x: u64) -> u64 { Int::from_le(x) } /// Convert an u16 from big endian to the target's endianness....
{ Int::from_le(x) }
identifier_body
mem.rs
the ABI-required minimum alignment of a type /// /// This is the alignment used for struct fields. It may be smaller /// than the preferred alignment. #[inline] #[stable] pub fn min_align_of<T>() -> uint { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of t...
/// /// On little endian, this is a no-op. On big endian, the bytes are swapped. #[inline] #[deprecated = "use `Int::from_le` instead"] pub fn from_le32(x: u32) -> u32 { Int::from_le(x) } /// Convert an u64 from little endian to the target's endianness. /// /// On little endian, this is a no-op. On big endian, the b...
pub fn from_le16(x: u16) -> u16 { Int::from_le(x) } /// Convert an u32 from little endian to the target's endianness.
random_line_split
mem.rs
ABI-required minimum alignment of a type /// /// This is the alignment used for struct fields. It may be smaller /// than the preferred alignment. #[inline] #[stable] pub fn min_align_of<T>() -> uint { unsafe { intrinsics::min_align_of::<T>() } } /// Returns the ABI-required minimum alignment of the type of the v...
(x: u16) -> u16 { x.to_le() } /// Convert an u32 to little endian from the target's endianness. /// /// On little endian, this is a no-op. On big endian, the bytes are swapped. #[inline] #[deprecated = "use `Int::to_le` instead"] pub fn to_le32(x: u32) -> u32 { x.to_le() } /// Convert an u64 to little endian from th...
to_le16
identifier_name
traits-assoc-type-in-supertrait.rs
// Copyright 2015 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 ...
fn main() { let x = sum_foo(vec![11, 10, 1].into_iter()); assert_eq!(x, 22); }
{ f.fold(0, |a,b| a + b) }
identifier_body
traits-assoc-type-in-supertrait.rs
// Copyright 2015 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 ...
fn main() { let x = sum_foo(vec![11, 10, 1].into_iter()); assert_eq!(x, 22); }
random_line_split
traits-assoc-type-in-supertrait.rs
// Copyright 2015 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 x = sum_foo(vec![11, 10, 1].into_iter()); assert_eq!(x, 22); }
main
identifier_name
replace_ctf.py
# Replaces the ctf values in input star file with the values in a reference star file import argparse import os from star import * def parse_args(): parser = argparse.ArgumentParser(description="Replaces the ctf values in input star file with the values in a reference star file.") parser.add_argument('--input', me...
(reference_path,input_path): # parameters that are relevant to the CTF estimation ctf_params = ['DefocusU','DefocusV','DefocusAngle','CtfFigureOfMerit','SphericalAberration','AmplitudeContrast'] # dictionary of micrograph name to ctf values # key = micrograph name # value = ctf values in 4-ple: DefocusU, Defocu...
main
identifier_name
replace_ctf.py
# Replaces the ctf values in input star file with the values in a reference star file import argparse import os from star import * def parse_args(): parser = argparse.ArgumentParser(description="Replaces the ctf values in input star file with the values in a reference star file.") parser.add_argument('--input', me...
print "Reading input file" input_star = starFromPath(input_path) output += input_star.textHeader() fields_to_replace = input_star.numsOf( params_to_replace ) for line in input_star.body: values = line.split() mic_root = rootname(input_star.valueOf('MicrographName',line)) for index,field in enumerate...
mic_to_ctf[mic_root] = ref_star.valuesOf(params_to_replace, line)
conditional_block
replace_ctf.py
# Replaces the ctf values in input star file with the values in a reference star file import argparse import os from star import * def parse_args(): parser = argparse.ArgumentParser(description="Replaces the ctf values in input star file with the values in a reference star file.") parser.add_argument('--input', me...
print "Reading input file" input_star = starFromPath(input_path) output += input_star.textHeader() fields_to_replace = input_star.numsOf( params_to_replace ) for line in input_star.body: values = line.split() mic_root = rootname(input_star.valueOf('MicrographName',line)) for index,field in enumerate(f...
continue else: mic_to_ctf[mic_root] = ref_star.valuesOf(params_to_replace, line)
random_line_split
replace_ctf.py
# Replaces the ctf values in input star file with the values in a reference star file import argparse import os from star import * def parse_args():
def main(reference_path,input_path): # parameters that are relevant to the CTF estimation ctf_params = ['DefocusU','DefocusV','DefocusAngle','CtfFigureOfMerit','SphericalAberration','AmplitudeContrast'] # dictionary of micrograph name to ctf values # key = micrograph name # value = ctf values in 4-ple: Defoc...
parser = argparse.ArgumentParser(description="Replaces the ctf values in input star file with the values in a reference star file.") parser.add_argument('--input', metavar='f1', type=str, nargs=1, required=True, help="particle file whose ctf values will be changed") parser.add_argument('--reference', metavar='f2', ty...
identifier_body
line_iterator.rs
pub struct LineIterator<'a> { data: &'a str, line_number: usize, line_start: usize, line_end: usize, done: bool } impl<'a> LineIterator<'a> { pub fn new(data: &str) -> LineIterator { LineIterator{ data, line_number: 0, line_start: 0, line_...
else { self.line_number += 1; } line } } #[cfg(test)] mod tests { use super::LineIterator; #[test] fn next_produces_a_value_for_empty_data() { let mut lines = LineIterator::new(""); assert_eq!(Some((0, "")), lines.next()); } #[test] fn next_in...
{ self.done = true; }
conditional_block
line_iterator.rs
pub struct LineIterator<'a> { data: &'a str, line_number: usize, line_start: usize, line_end: usize, done: bool } impl<'a> LineIterator<'a> { pub fn new(data: &str) -> LineIterator { LineIterator{ data, line_number: 0, line_start: 0, line_...
() { let mut lines = LineIterator::new("line\nanother line\n"); assert_eq!(Some((0, "line\n")), lines.next()); assert_eq!(Some((1, "another line\n")), lines.next()); assert_eq!(Some((2, "")), lines.next()); } #[test] fn next_stops_at_end_of_data() { let mut lines = L...
next_includes_trailing_newlines
identifier_name
line_iterator.rs
pub struct LineIterator<'a> { data: &'a str, line_number: usize, line_start: usize, line_end: usize, done: bool } impl<'a> LineIterator<'a> { pub fn new(data: &str) -> LineIterator { LineIterator{ data, line_number: 0, line_start: 0, line_...
#[test] fn next_includes_trailing_newlines() { let mut lines = LineIterator::new("line\nanother line\n"); assert_eq!(Some((0, "line\n")), lines.next()); assert_eq!(Some((1, "another line\n")), lines.next()); assert_eq!(Some((2, "")), lines.next()); } #[test] fn next...
random_line_split
line_iterator.rs
pub struct LineIterator<'a> { data: &'a str, line_number: usize, line_start: usize, line_end: usize, done: bool } impl<'a> LineIterator<'a> { pub fn new(data: &str) -> LineIterator
fn out_of_data(&self) -> bool { self.line_end == self.data.len() } } impl<'a> Iterator for LineIterator<'a> { type Item = (usize, &'a str); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } // Move the range beyond its previous posit...
{ LineIterator{ data, line_number: 0, line_start: 0, line_end: 0, done: false } }
identifier_body
sched.rs
use std::mem; use libc::{c_int, c_uint, c_void, c_ulong, pid_t}; use errno::Errno; use {Result, Error}; pub type CloneFlags = c_uint; pub static CLONE_VM: CloneFlags = 0x00000100; pub static CLONE_FS: CloneFlags = 0x00000200; pub static CLONE_FILES: CloneFlags = 0x00000400; pub static...
} pub fn clone(mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags) -> Result<pid_t> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let ptr = stack.as_mut_ptr().offset(stack.len() as isiz...
{ Ok(()) }
conditional_block
sched.rs
use std::mem; use libc::{c_int, c_uint, c_void, c_ulong, pid_t}; use errno::Errno; use {Result, Error}; pub type CloneFlags = c_uint; pub static CLONE_VM: CloneFlags = 0x00000100; pub static CLONE_FS: CloneFlags = 0x00000200; pub static CLONE_FILES: CloneFlags = 0x00000400; pub static...
self.cpu_mask[word] = cpuset_attribs::clear_cpu_mask_flag(self.cpu_mask[word], bit); } } mod ffi { use libc::{c_void, c_int, pid_t, size_t}; use super::CpuSet; pub type CloneCb = extern "C" fn (data: *const super::CloneCb) -> c_int; // We cannot give a proper #[repr(C)] to super::CloneCb ...
random_line_split
sched.rs
use std::mem; use libc::{c_int, c_uint, c_void, c_ulong, pid_t}; use errno::Errno; use {Result, Error}; pub type CloneFlags = c_uint; pub static CLONE_VM: CloneFlags = 0x00000100; pub static CLONE_FS: CloneFlags = 0x00000200; pub static CLONE_FILES: CloneFlags = 0x00000400; pub static...
(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let ptr = stack.as_mut_ptr().offset(stack.len() as isize); ffi::clone(mem::transmute(callback), ptr as *mut c_void, flags, &mut cb) }; if res < 0 { ...
callback
identifier_name
sched.rs
use std::mem; use libc::{c_int, c_uint, c_void, c_ulong, pid_t}; use errno::Errno; use {Result, Error}; pub type CloneFlags = c_uint; pub static CLONE_VM: CloneFlags = 0x00000100; pub static CLONE_FS: CloneFlags = 0x00000200; pub static CLONE_FILES: CloneFlags = 0x00000400; pub static...
pub fn set(&mut self, field: usize) { let word = field / cpuset_attribs::CPU_MASK_BITS; let bit = field % cpuset_attribs::CPU_MASK_BITS; self.cpu_mask[word] = cpuset_attribs::set_cpu_mask_flag(self.cpu_mask[word], bit); } pub fn unset(&mut self, field: usize) { let word =...
{ CpuSet { cpu_mask: unsafe { mem::zeroed() } } }
identifier_body
FileDriver.ts
import * as fs from 'fs'; import * as glob from 'glob'; import * as path from 'path'; import { IDatabase } from '../interfaces/IDatabase'; import { IExtractor } from '../interfaces/IExtractor'; type fs = typeof fs; type glob = typeof glob; type path = typeof path; type extractorFactory = (fileContent: string) => IExt...
(table: string) { const globPattern = path.resolve(this.cwd, `resources/${table}/*`); return this.glob.sync(globPattern) .map((file) => { const fileContent = this.readFile(file); return this.extractData(fileContent); }); } public getById(id: string, table: string) { const f...
getAll
identifier_name
FileDriver.ts
import * as fs from 'fs'; import * as glob from 'glob'; import * as path from 'path'; import { IDatabase } from '../interfaces/IDatabase'; import { IExtractor } from '../interfaces/IExtractor'; type fs = typeof fs; type glob = typeof glob; type path = typeof path; type extractorFactory = (fileContent: string) => IExt...
{ return new FileDriver( { fs, glob, path }, extractor, cwd, ); }
identifier_body
FileDriver.ts
import * as fs from 'fs'; import * as glob from 'glob'; import * as path from 'path';
type path = typeof path; type extractorFactory = (fileContent: string) => IExtractor; export interface IDependencies { fs: fs; glob: glob; path: path; } export class FileDriver implements IDatabase { private fs: fs; private glob: glob; private path: path; private extractor: extractorFactory; private c...
import { IDatabase } from '../interfaces/IDatabase'; import { IExtractor } from '../interfaces/IExtractor'; type fs = typeof fs; type glob = typeof glob;
random_line_split
main.user.js
// ==UserScript== // @name Forvo links // @namespace http://gubnota.github.io/fenki_js_helpers/plugin/monkey/forvo/ // @version 0.0.2 // @downloadURL http://gubnota.github.io/fenki_js_helpers/plugin/monkey/forvo/main.user.js // @description Forvo links // @include http://*.forvo.com/* // @include ...
a[i].setAttribute('onclick','window.open(\'//audio00.forvo.com/mp3/'+atob(g[1])+'\')'); } } } })(window);
conditional_block
main.user.js
// ==UserScript== // @name Forvo links // @namespace http://gubnota.github.io/fenki_js_helpers/plugin/monkey/forvo/ // @version 0.0.2
// @include http://*.forvo.com/* // @include https://*.forvo.com/* // @include http://forvo.com/* // @include https://forvo.com/* // @copyright 2018+, Larry Moore // @author Larry Moore // @grant none // @run-at document-end // ==/UserScript== (function(window, undefined){ var w = ...
// @downloadURL http://gubnota.github.io/fenki_js_helpers/plugin/monkey/forvo/main.user.js // @description Forvo links
random_line_split
ContentDbDict.py
import time import os import ContentDb from Debug import Debug from Config import config class ContentDbDict(dict): def __init__(self, site, *args, **kwargs): s = time.time() self.site = site self.cached_keys = [] self.log = self.site.log self.db = ContentDb.getContentDb()...
return back def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default except Exception as err: self.site.bad_files[key] = self.site.bad_files.get(key, 1) dict.__delitem__(self, key) ...
if not val: try: val = self.loadItem(key) except Exception: continue back.append(val)
conditional_block
ContentDbDict.py
import time import os import ContentDb from Debug import Debug from Config import config class ContentDbDict(dict): def __init__(self, site, *args, **kwargs): s = time.time() self.site = site self.cached_keys = [] self.log = self.site.log self.db = ContentDb.getContentDb()...
def getItemSize(self, key): return self.site.storage.getSize(key) # Only keep last 10 accessed json in memory def checkLimit(self): if len(self.cached_keys) > 10: key_deleted = self.cached_keys.pop(0) dict.__setitem__(self, key_deleted, False) def addCachedKey...
try: self.num_loaded += 1 if self.num_loaded % 100 == 0: if config.verbose: self.log.debug("Loaded json: %s (latest: %s) called by: %s" % (self.num_loaded, key, Debug.formatStack())) else: self.log.debug("Loaded json: %s (la...
identifier_body
ContentDbDict.py
import time import os import ContentDb from Debug import Debug from Config import config class ContentDbDict(dict): def __init__(self, site, *args, **kwargs): s = time.time() self.site = site self.cached_keys = [] self.log = self.site.log self.db = ContentDb.getContentDb()...
(self, key): self.db.deleteContent(self.site, key) dict.__delitem__(self, key) try: self.cached_keys.remove(key) except ValueError: pass def iteritems(self): for key in dict.keys(self): try: val = self[key] exce...
__delitem__
identifier_name
ContentDbDict.py
import time import os import ContentDb from Debug import Debug from Config import config class ContentDbDict(dict): def __init__(self, site, *args, **kwargs): s = time.time() self.site = site self.cached_keys = [] self.log = self.site.log self.db = ContentDb.getContentDb()...
for key in dict.keys(self): try: val = self[key] except Exception as err: self.log.warning("Error loading %s: %s" % (key, err)) continue yield key, val def items(self): back = [] for key in dict.keys(self): ...
except ValueError: pass def iteritems(self):
random_line_split
redis_hash_layer.py
import redis from hashlib import sha1 class RedisHashLayer(object): """ A more memory-efficient way to store many small values in redis using hashes. See http://antirez.com/post/redis-weekly-update-7.html Note: add these config value to redis: hash-max-zipmap-entries 512 hash-max-zipmap-value ...
return False def add(self,key): hashkey,field = self._get_hashname(key) self.connection.hset(hashkey,field,field) return def delete(self,key): hashkey,field = self._get_hashname(key) self.connection.hset(hashkey,field,field) self.connection.hdel(hashkey...
return True
conditional_block
redis_hash_layer.py
import redis from hashlib import sha1 class RedisHashLayer(object): """ A more memory-efficient way to store many small values in redis using hashes. See http://antirez.com/post/redis-weekly-update-7.html Note: add these config value to redis: hash-max-zipmap-entries 512 hash-max-zipmap-value ...
def delete(self,key): hashkey,field = self._get_hashname(key) self.connection.hset(hashkey,field,field) self.connection.hdel(hashkey,field) return def clear(self): pipeline = self.connection.pipeline() keys = self.connection.keys(self.name+"*") for k in ...
random_line_split
redis_hash_layer.py
import redis from hashlib import sha1 class RedisHashLayer(object): """ A more memory-efficient way to store many small values in redis using hashes. See http://antirez.com/post/redis-weekly-update-7.html Note: add these config value to redis: hash-max-zipmap-entries 512 hash-max-zipmap-value ...
(self,key): hashkey,field = self._get_hashname(key) self.connection.hset(hashkey,field,field) self.connection.hdel(hashkey,field) return def clear(self): pipeline = self.connection.pipeline() keys = self.connection.keys(self.name+"*") for k in keys: ...
delete
identifier_name
redis_hash_layer.py
import redis from hashlib import sha1 class RedisHashLayer(object): """ A more memory-efficient way to store many small values in redis using hashes. See http://antirez.com/post/redis-weekly-update-7.html Note: add these config value to redis: hash-max-zipmap-entries 512 hash-max-zipmap-value ...
def delete(self,key): hashkey,field = self._get_hashname(key) self.connection.hset(hashkey,field,field) self.connection.hdel(hashkey,field) return def clear(self): pipeline = self.connection.pipeline() keys = self.connection.keys(self.name+"*") for k in...
hashkey,field = self._get_hashname(key) self.connection.hset(hashkey,field,field) return
identifier_body
spawn_pinned.rs
let pool = Arc::new(LocalPool { workers }); LocalPoolHandle { pool } } /// Spawn a task onto a worker thread and pin it there so it can't be moved /// off of the thread. Note that the future is not [`Send`], but the /// [`FnOnce`] which creates it is. /// /// # Examples /// ``` ...
{ break; }
conditional_block
spawn_pinned.rs
used for spawning `!Send` tasks. #[derive(Clone)] pub struct LocalPoolHandle { pool: Arc<LocalPool>, } impl LocalPoolHandle { /// Create a new pool of threads to handle `!Send` tasks. Spawn tasks onto this /// pool via [`LocalPoolHandle::spawn_pinned`]. /// /// # Panics /// Panics if the pool ...
{ return (worker, JobCountGuard(Arc::clone(&worker.task_count))); } } } } /// Automatically decrements a worker's job count when a job finishes (when /// this gets dropped). struct JobCountGuard(Arc<AtomicUsize>); impl Drop for JobCountGuard { fn drop(&mut self...
{ loop { let (worker, task_count) = self .workers .iter() .map(|worker| (worker, worker.task_count.load(Ordering::SeqCst))) .min_by_key(|&(_, count)| count) .expect("There must be more than one worker"); // ...
identifier_body
spawn_pinned.rs
used for spawning `!Send` tasks. #[derive(Clone)] pub struct LocalPoolHandle { pool: Arc<LocalPool>, } impl LocalPoolHandle { /// Create a new pool of threads to handle `!Send` tasks. Spawn tasks onto this /// pool via [`LocalPoolHandle::spawn_pinned`]. /// /// # Panics /// Panics if the pool ...
(pool_size: usize) -> LocalPoolHandle { assert!(pool_size > 0); let workers = (0..pool_size) .map(|_| LocalWorkerHandle::new_worker()) .collect(); let pool = Arc::new(LocalPool { workers }); LocalPoolHandle { pool } } /// Spawn a task onto a worker thr...
new
identifier_name
spawn_pinned.rs
, used for spawning `!Send` tasks. #[derive(Clone)] pub struct LocalPoolHandle { pool: Arc<LocalPool>, } impl LocalPoolHandle { /// Create a new pool of threads to handle `!Send` tasks. Spawn tasks onto this /// pool via [`LocalPoolHandle::spawn_pinned`]. /// /// # Panics /// Panics if the pool...
/// ``` pub fn spawn_pinned<F, Fut>(&self, create_task: F) -> JoinHandle<Fut::Output> where F: FnOnce() -> Fut, F: Send + 'static, Fut: Future + 'static, Fut::Output: Send + 'static, { self.pool.spawn_pinned(create_task) } } impl Debug for LocalPoolHandle { ...
random_line_split
ProgramsPolicy.ts
'use strict'; import acl from 'acl'; class ProgramsPolicy { public static getInstance() { return this.instance || (this.instance = new this()); } private static instance: ProgramsPolicy; private aclMem = new acl(new acl.memoryBackend()); private constructor() {} public invokeRolesPolicies = () => { this...
// Check for user roles this.aclMem.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), (err, isAllowed) => { if (err) { // An authorization error occurred return res.status(500).send('Unexpected authorization error'); } else { if (isAllowed) { // Access granted! Invoke next...
{ return next(); }
conditional_block
ProgramsPolicy.ts
'use strict'; import acl from 'acl'; class
{ public static getInstance() { return this.instance || (this.instance = new this()); } private static instance: ProgramsPolicy; private aclMem = new acl(new acl.memoryBackend()); private constructor() {} public invokeRolesPolicies = () => { this.aclMem.allow([ { roles: ['admin', 'gov'], allow...
ProgramsPolicy
identifier_name
ProgramsPolicy.ts
'use strict'; import acl from 'acl'; class ProgramsPolicy { public static getInstance() { return this.instance || (this.instance = new this()); } private static instance: ProgramsPolicy; private aclMem = new acl(new acl.memoryBackend()); private constructor() {} public invokeRolesPolicies = () => { this...
permissions: '*' }, { resources: '/api/new/program', permissions: ['get'] }, { resources: '/api/programs/members/:programId', permissions: ['get'] }, { resources: '/api/programs/requests/:programId', permissions: ['get'] }, { resour...
allows: [ { resources: '/api/programs',
random_line_split
Repository.py
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # import os import jasy.core.Console as Console import jasy.core.Util as Util import jasy.vcs.Git as Git import jasy.vcs.Svn as Svn def isUrl(url): """ Figures out whether the given string is a valid Git repository URL. :param url: URL t...
if cur == os.getcwd(): break os.chdir(old) return revision def clean(path=None): """ Cleans repository from untracked files. :param url: Path to the local repository :type url: string """ old = os.getcwd() Console.info("Cleaning repository (clean)...") ...
"""Returns the current revision of the repository in the given path.""" old = os.getcwd() revision = None if path is not None: os.chdir(path) while True: if os.path.exists(".git"): revision = Git.getBranch(path) + "-" + Git.getShortRevision(path) break ...
identifier_body
Repository.py
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # import os import jasy.core.Console as Console import jasy.core.Util as Util import jasy.vcs.Git as Git import jasy.vcs.Svn as Svn def isUrl(url): """ Figures out whether the given string is a valid Git repository URL. :param url: URL t...
(url, version=None, path=None, update=True): """ Clones the given repository URL (optionally with overriding/update features) :param url: URL to the repository :type url: string :param version: Version to clone :type url: string :param version: Destination path :type url: string :pa...
update
identifier_name
Repository.py
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # import os import jasy.core.Console as Console import jasy.core.Util as Util import jasy.vcs.Git as Git import jasy.vcs.Svn as Svn def isUrl(url): """ Figures out whether the given string is a valid Git repository URL. :param url: URL t...
Returns the target folder name based on the URL and version using SHA1 checksums. :param url: URL to the repository :type url: string :param version: Version to use :type url: string """ if Git.isUrl(url): version = Git.expandVersion(version) folder = url[url.rindex("/")...
return None def getTargetFolder(url, version=None): """
random_line_split
Repository.py
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # import os import jasy.core.Console as Console import jasy.core.Util as Util import jasy.vcs.Git as Git import jasy.vcs.Svn as Svn def isUrl(url): """ Figures out whether the given string is a valid Git repository URL. :param url: URL t...
cur = os.getcwd() os.chdir(os.pardir) if cur == os.getcwd(): break os.chdir(old) return revision def clean(path=None): """ Cleans repository from untracked files. :param url: Path to the local repository :type url: string """ old = os.getcwd...
revision = Svn.getBranch(path) + "-" + Svn.getRevision(path) break
conditional_block
__manifest__.py
# Copyright 2020 initOS GmbH # Copyright 2012-2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{ "name": "LDAP groups assignment", "version": "11.0.1.0.0", "depends": ["auth_ldap"], "author": "initOS GmbH, Therp BV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "summary": "Adds user accounts to groups based on rules defined "...
random_line_split
index.ts
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ // This file is meant to mimics the functionality of Predicate and Predicates from Googl...
(): PredicateResponse { return new PredicateResponse(true, ''); } public static false(): PredicateResponse { return new PredicateResponse(false, 'GENERAL ERROR'); } }
true
identifier_name
index.ts
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ // This file is meant to mimics the functionality of Predicate and Predicates from Googl...
return new PredicateResponse(result, message); } public static true(): PredicateResponse { return new PredicateResponse(true, ''); } public static false(): PredicateResponse { return new PredicateResponse(false, 'GENERAL ERROR'); } }
random_line_split
index.ts
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ // This file is meant to mimics the functionality of Predicate and Predicates from Googl...
}
{ return new PredicateResponse(false, 'GENERAL ERROR'); }
identifier_body
grunt-spritesmith.js
var format = formatObj[lowerExt]; return format; } }; // Create img and css formats var imgFormats = new ExtFormat(); var cssFormats = new ExtFormat(); // Add our img formats imgFormats.add('.png', 'png'); imgFormats.add('.jpg', 'jpeg'); imgFormats.add('.jpeg', 'jpeg'); // Add our css formats cssFormats.ad...
module.exports = function gruntSpritesmith (grunt) { // Create a SpriteMaker function function SpriteMaker() { // Grab the raw configuration var data = this.data; // If we were invoked via `grunt-newer`, re-localize the info if (data.src === undefined && data.files) { data = data.files[0] |...
{ // Extract the image name (exlcuding extension) var fullname = path.basename(filepath); var nameParts = fullname.split('.'); // If there is are more than 2 parts, pop the last one if (nameParts.length >= 2) { nameParts.pop(); } // Return our modified filename return nameParts.join('.'); }
identifier_body
grunt-spritesmith.js
get: function (filepath) { // Grab the extension from the filepath var ext = path.extname(filepath); var lowerExt = ext.toLowerCase(); // Look up the file extenion from our format object var formatObj = this.formatObj; var format = formatObj[lowerExt]; return format; } }; // Create img...
this.formatObj[name] = val; },
random_line_split
grunt-spritesmith.js
var format = formatObj[lowerExt]; return format; } }; // Create img and css formats var imgFormats = new ExtFormat(); var cssFormats = new ExtFormat(); // Add our img formats imgFormats.add('.png', 'png'); imgFormats.add('.jpg', 'jpeg'); imgFormats.add('.jpeg', 'jpeg'); // Add our css formats cssFormats.ad...
// Otherwise, write out the result to destImg var result = resultArr[0]; var destImgDir = path.dirname(destImg); grunt.file.mkdir(destImgDir); fs.writeFileSync(destImg, result.image, 'binary'); // Generate a listing of CSS variables var coordinates = result.coordinates; ...
{ grunt.fatal(err); return cb(err); }
conditional_block
grunt-spritesmith.js
var format = formatObj[lowerExt]; return format; } }; // Create img and css formats var imgFormats = new ExtFormat(); var cssFormats = new ExtFormat(); // Add our img formats imgFormats.add('.png', 'png'); imgFormats.add('.jpg', 'jpeg'); imgFormats.add('.jpeg', 'jpeg'); // Add our css formats cssFormats.ad...
() { // Grab the raw configuration var data = this.data; // If we were invoked via `grunt-newer`, re-localize the info if (data.src === undefined && data.files) { data = data.files[0] || {}; } // Determine the origin and destinations var src = data.src; var destImg = data.dest; ...
SpriteMaker
identifier_name
auditTime.d.ts
import { MonoTypeOperatorFunction, SchedulerLike } from '../types'; /** * Ignores source values for `duration` milliseconds, then emits the most recent * value from the source Observable, then repeats this process. * * <span class="informal">When it sees a source values, it ignores that plus * the next ones for `d...
* @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for * managing the timers that handle the rate-limiting behavior. * @return {Observable<T>} An Observable that performs rate-limiting of * emissions from the source Observable. * @method auditTime * @owner Observable */ export declare fu...
* @param {number} duration Time to wait before emitting the most recent source * value, measured in milliseconds or the time unit determined internally * by the optional `scheduler`.
random_line_split
EnvDatabaseFields.py
print "loading arcpy" import arcpy import os inFolder = r"C:\temp\shapes" intersectFolder = os.path.join(inFolder, "int") gridFile = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb\grid" arcpy.env.workspace = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb" layerName = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb...
print e try: print "calculating proportional area" gridFilename = os.path.basename(gridFile).split(os.extsep)[0] arcpy.CalculateField_management(layerName, newfieldName, "[" + str(oldfieldName) + ".area]/[" + gridFilename + ".Shape_Area]", ...
except BaseException as e:
random_line_split
EnvDatabaseFields.py
print "loading arcpy" import arcpy import os inFolder = r"C:\temp\shapes" intersectFolder = os.path.join(inFolder, "int") gridFile = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb\grid" arcpy.env.workspace = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb" layerName = r"C:\Users\Jonah\Documents\ArcGIS\Default.gdb...
newfieldName = os.path.basename(gridFile).split(os.extsep)[0] + "." + f.split(os.extsep)[0] fieldList = [f.baseName for f in arcpy.ListFields(gridFile)] if oldfieldName not in fieldList: try: print "adding shapefile name field to grid" arcpy.AddFi...
print "processing", f inFile = os.path.join(inFolder, f) intFile = os.path.join(intersectFolder, f) if not os.path.exists(intFile): try: print "intersecting", f arcpy.Intersect_analysis([inFile, gridFile], intFile, "ALL") except Base...
conditional_block
iceberg.py
# -*- coding: utf-8 -*- import json from django import template from django.conf import settings register = template.Library() from django_iceberg.auth_utils import init_iceberg @register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True) def iceberg_javascript_sdk(context): """ To Fi...
(context, seller_id): api_handler = init_iceberg(context['request']) if hasattr(api_handler, '_sso_response'): return { "modules": json.dumps(['client', 'seller']), 'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE, "sso_data": json.dumps(api_handler._ss...
iceberg_sso_with_seller
identifier_name
iceberg.py
# -*- coding: utf-8 -*- import json from django import template from django.conf import settings register = template.Library() from django_iceberg.auth_utils import init_iceberg @register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True) def iceberg_javascript_sdk(context): """ To Fi...
@register.inclusion_tag('django_iceberg/sso.html', takes_context=True) def iceberg_sso_with_seller(context, seller_id): api_handler = init_iceberg(context['request']) if hasattr(api_handler, '_sso_response'): return { "modules": json.dumps(['client', 'seller']), 'appNamespace...
return {}
conditional_block
iceberg.py
# -*- coding: utf-8 -*- import json from django import template from django.conf import settings register = template.Library() from django_iceberg.auth_utils import init_iceberg @register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True) def iceberg_javascript_sdk(context): """ To Fi...
if hasattr(api_handler, '_sso_response'): return { "modules": json.dumps(['client', 'seller']), 'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE, "sso_data": json.dumps(api_handler._sso_response), "seller": json.dumps({"id": seller_id}), ...
api_handler = init_iceberg(context['request'])
random_line_split
iceberg.py
# -*- coding: utf-8 -*- import json from django import template from django.conf import settings register = template.Library() from django_iceberg.auth_utils import init_iceberg @register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True) def iceberg_javascript_sdk(context): """ To Fi...
api_handler = init_iceberg(context['request']) if hasattr(api_handler, '_sso_response'): return { "modules": json.dumps(['client', 'seller']), 'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE, "sso_data": json.dumps(api_handler._sso_response), "...
identifier_body
react-scripts.js
#!/usr/bin/env node /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same direct...
process.exit(result.status); break; default: console.log('Unknown script "' + script + '".'); console.log('Perhaps you need to update react-scripts?'); console.log( 'See: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/templates/app/README.md#updatin...
{ if (result.signal === 'SIGKILL') { console.log( 'The build failed because the process exited too early. ' + 'This probably means the system ran out of memory or someone called ' + '`kill -9` on the process.' ); } else if (result.signal === 'SIGTERM') { ...
conditional_block
react-scripts.js
#!/usr/bin/env node /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same direct...
var args = process.argv.slice(3); switch (script) { case 'build': case 'eject': case 'start': case 'test': case 'generate-component': var result = spawn.sync( 'node', [require.resolve('../scripts/' + script)].concat(args), { stdio: 'inherit' } ); if (result.signal) { if (r...
var spawn = require('cross-spawn'); var script = process.argv[2];
random_line_split
test_vmutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # 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.ap...
mock_vm.path_.return_value = self._FAKE_VM_PATH return mock_vm def test_set_vm_memory_static(self): self._test_set_vm_memory_dynamic(1.0) def test_set_vm_memory_dynamic(self): self._test_set_vm_memory_dynamic(2.0) def _test_set_vm_memory_dynamic(self, dynamic_memory_ratio)...
self._vmutils._lookup_vm_check = mock.MagicMock( return_value=mock_vm)
random_line_split
test_vmutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # 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.ap...
(self): self._vmutils = vmutils.VMUtils() self._vmutils._conn = mock.MagicMock() super(VMUtilsTestCase, self).setUp() def test_enable_vm_metrics_collection(self): self.assertRaises(NotImplementedError, self._vmutils.enable_vm_metrics_collection, ...
setUp
identifier_name
test_vmutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # 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.ap...
else: self.assertFalse(mock_s.DynamicMemoryEnabled)
self.assertTrue(mock_s.DynamicMemoryEnabled)
conditional_block
test_vmutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # 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.ap...
def _lookup_vm(self): mock_vm = mock.MagicMock() self._vmutils._lookup_vm_check = mock.MagicMock( return_value=mock_vm) mock_vm.path_.return_value = self._FAKE_VM_PATH return mock_vm def test_set_vm_memory_static(self): self._test_set_vm_memory_dynamic(1.0)...
self.assertRaises(NotImplementedError, self._vmutils.enable_vm_metrics_collection, self._FAKE_VM_NAME)
identifier_body
const.py
"""Constants for the Vilfo Router integration.""" from __future__ import annotations from dataclasses import dataclass from homeassistant.components.sensor import SensorEntityDescription from homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE DOMAIN = "vilfo" ATTR_API_DATA_FIELD_LOAD = "load" ATTR_API_DA...
@dataclass class VilfoSensorEntityDescription(SensorEntityDescription, VilfoRequiredKeysMixin): """Describes Vilfo sensor entity.""" SENSOR_TYPES: tuple[VilfoSensorEntityDescription, ...] = ( VilfoSensorEntityDescription( key=ATTR_LOAD, name="Load", native_unit_of_measurement=PERCEN...
"""Mixin for required keys.""" api_key: str
identifier_body
const.py
"""Constants for the Vilfo Router integration.""" from __future__ import annotations from dataclasses import dataclass from homeassistant.components.sensor import SensorEntityDescription from homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE DOMAIN = "vilfo" ATTR_API_DATA_FIELD_LOAD = "load" ATTR_API_DA...
api_key=ATTR_API_DATA_FIELD_BOOT_TIME, device_class=DEVICE_CLASS_TIMESTAMP, ), )
key=ATTR_BOOT_TIME, name="Boot time", icon="mdi:timer-outline",
random_line_split
const.py
"""Constants for the Vilfo Router integration.""" from __future__ import annotations from dataclasses import dataclass from homeassistant.components.sensor import SensorEntityDescription from homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE DOMAIN = "vilfo" ATTR_API_DATA_FIELD_LOAD = "load" ATTR_API_DA...
(SensorEntityDescription, VilfoRequiredKeysMixin): """Describes Vilfo sensor entity.""" SENSOR_TYPES: tuple[VilfoSensorEntityDescription, ...] = ( VilfoSensorEntityDescription( key=ATTR_LOAD, name="Load", native_unit_of_measurement=PERCENTAGE, icon="mdi:memory", api_key...
VilfoSensorEntityDescription
identifier_name
index.tsx
import * as React from "react"; import * as ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { applyMiddleware, createStore } from "redux"; import thunk from "redux-thunk"; import * as Actions from "./actions"; import Homepage from "./containers/Homepage"; import { helloApp } from "./reducers";...
unsubscribe(); const mount: Element | null = document.querySelector("#app"); if (mount !== null) { ReactDOM.render( <Provider store={store}> <Homepage /> </Provider>, mount, ); } else { console.error(`#app not found in document`); }
store.dispatch(Actions.getRandomChuckNorrisJoke()); // unsubscribe from store updates
random_line_split
index.tsx
import * as React from "react"; import * as ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { applyMiddleware, createStore } from "redux"; import thunk from "redux-thunk"; import * as Actions from "./actions"; import Homepage from "./containers/Homepage"; import { helloApp } from "./reducers";...
else { console.error(`#app not found in document`); }
{ ReactDOM.render( <Provider store={store}> <Homepage /> </Provider>, mount, ); }
conditional_block
trace_code_map.js
/** Copyright 2015 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. **/ require("./trace_code_entry.js"); 'use strict'; global.tr.exportTo('tr.e.importer', function() { // This code is a tracification of: // devtools/fron...
() { this.banks_ = new Map(); } TraceCodeMap.prototype = { addEntry: function(addressHex, size, name, scriptId) { var entry = new tr.e.importer.TraceCodeEntry( this.getAddress_(addressHex), size, name, scriptId); this.addEntry_(addressHex, entry); }, moveEntry: function(oldA...
TraceCodeMap
identifier_name
trace_code_map.js
/** Copyright 2015 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. **/ require("./trace_code_entry.js"); 'use strict'; global.tr.exportTo('tr.e.importer', function() { // This code is a tracification of: // devtools/fron...
++index; this.entries_.splice(index, lastIndex - index, newEntry); } }; return { TraceCodeMap: TraceCodeMap }; });
{ var entry = this.entries_[index]; var entryEndAddress = entry.address + entry.size; if (entryEndAddress <= newEntry.address) break; }
conditional_block
trace_code_map.js
/** Copyright 2015 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. **/ require("./trace_code_entry.js"); 'use strict'; global.tr.exportTo('tr.e.importer', function() { // This code is a tracification of: // devtools/fron...
TraceCodeBank.prototype = { removeEntry: function(address) { // findLowIndexInSortedArray returns 1 for empty. Just handle the // empty list and bail early. if (this.entries_.length === 0) return undefined; var index = tr.b.findLowIndexInSortedArray( this.entries_, fun...
{ this.entries_ = []; }
identifier_body
trace_code_map.js
/** Copyright 2015 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. **/ require("./trace_code_entry.js"); 'use strict'; global.tr.exportTo('tr.e.importer', function() { // This code is a tracification of: // devtools/fron...
this.entries_.splice(index, lastIndex - index, newEntry); } }; return { TraceCodeMap: TraceCodeMap }; });
random_line_split
fcktoolbarfontformatcombo.js
/* * FCKeditor - The text editor for internet * Copyright (C) 2003-2006 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * "Support Op...
else { if ( this._LastValue == value ) return ; combo.SelectItemByLabel( value, true ) ; } this._LastValue = value ; } }
if ( combo.Label != '&nbsp;' ) combo.DeselectAll(true) ; }
conditional_block
fcktoolbarfontformatcombo.js
/* * FCKeditor - The text editor for internet * Copyright (C) 2003-2006 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * "Support Op...
if ( value == this.NormalLabel ) { if ( combo.Label != '&nbsp;' ) combo.DeselectAll(true) ; } else { if ( this._LastValue == value ) return ; combo.SelectItemByLabel( value, true ) ; } this._LastValue = value ; } }
FCKToolbarFontFormatCombo.prototype.RefreshActiveItems = function( combo, value ) { // FCKDebug.Output( 'FCKToolbarFontFormatCombo Value: ' + value ) ; // IE returns normal for DIV and P, so to avoid confusion, we will not show it if normal.
random_line_split
config-mode.js
/* Known Modes: - neutral - walkaway - Enable walkaway option - play-by-play - Enable play-by-play popup window showing the history of this game - condition-random - Utilize a random condition provided by the auth server - condition - Utilize a specific condition provided by the auth server - ...
}, '2014-02-04': { 'mode': 'condition', 'slug': 'condition-political' }, '2014-02-05': { 'mode': 'walkaway' }, '2014-02-07': { 'mode': 'play-by-play' }, '2014-02-08': { 'mode': 'condition', 'slug': 'condition-transportation' }, '2014-02-09': { 'mode': 'condition', 'slug': 'co...
'2014-02-02': { 'mode': 'condition', 'slug': 'condition-color'
random_line_split
vextracti32x4.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn
() { run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM5)), operand2: Some(Direct(ZMM0)), operand3: Some(Literal8(65)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 125, 202, ...
vextracti32x4_1
identifier_name