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
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
} notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void { this.clearThrottle(); } notifyComplete(): void { this.clearThrottle(); } }
{ this.value = null; this.hasValue = false; this.destination.next(value); }
conditional_block
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
} /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ class AuditSubscriber<T, R> extends OuterSubscriber<T, R> { private value: T; private hasValue: boolean = false; private throttled: Subscription; constructor(destination: Subscriber<T>, private durati...
{ return source.subscribe(new AuditSubscriber<T, T>(subscriber, this.durationSelector)); }
identifier_body
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
() { const { value, hasValue, throttled } = this; if (throttled) { this.remove(throttled); this.throttled = null; throttled.unsubscribe(); } if (hasValue) { this.value = null; this.hasValue = false; this.destination.next(value); } } notifyNext(outerValue: T, ...
clearThrottle
identifier_name
scene_system.rs
use std::sync::{Arc, Mutex}; use render::camera::Camera; #[derive(Clone,Debug)] pub struct SceneManager { pub inner: Arc<Mutex<u8>>, cameras: Arc<Mutex<Vec<Camera>>>, } impl SceneManager{ fn new() -> Self { SceneManager { inner: Arc::new(Mutex::new(0)), cameras: Arc::new(M...
}
mod tests { use super::*; fn test_load_obj() { }
random_line_split
scene_system.rs
use std::sync::{Arc, Mutex}; use render::camera::Camera; #[derive(Clone,Debug)] pub struct SceneManager { pub inner: Arc<Mutex<u8>>, cameras: Arc<Mutex<Vec<Camera>>>, } impl SceneManager{ fn new() -> Self { SceneManager { inner: Arc::new(Mutex::new(0)), cameras: Arc::new(M...
// fn process_input(&self, event: &glutin::Event) { // (self.cameras.lock().unwrap())[0].process_input(event) // } } #[cfg(test)] mod tests { use super::*; fn test_load_obj() { } }
{ (self.cameras.lock().unwrap())[0].update() }
identifier_body
scene_system.rs
use std::sync::{Arc, Mutex}; use render::camera::Camera; #[derive(Clone,Debug)] pub struct SceneManager { pub inner: Arc<Mutex<u8>>, cameras: Arc<Mutex<Vec<Camera>>>, } impl SceneManager{ fn new() -> Self { SceneManager { inner: Arc::new(Mutex::new(0)), cameras: Arc::new(M...
(&self) { (self.cameras.lock().unwrap())[0].update() } // fn process_input(&self, event: &glutin::Event) { // (self.cameras.lock().unwrap())[0].process_input(event) // } } #[cfg(test)] mod tests { use super::*; fn test_load_obj() { } }
update
identifier_name
TabstoppingTest.ts
import { ApproxStructure, Assertions } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock'; import * as Behaviour from 'ephox/alloy/api/behaviour/Behaviour'; import { Tabstopping } from 'ephox/alloy/api/behaviour/Tabstopping'; import * as GuiFactory from 'ephox/alloy/api/component/GuiFactory'; import { Conta...
'data-alloy-tabstop': str.is('true') } }); }), component.element() ) ]; }, () => { success(); }, failure); });
Assertions.sAssertStructure( 'Check initial tabstopping values', ApproxStructure.build((s, str, arr) => { return s.element('div', { attrs: {
random_line_split
parrot_utils.py
# # Copyright (C) 2012-2014 The Paparazzi Team # # This file is part of Paparazzi. # # Paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # P...
return running[1:] # Check the filesystem def check_filesystem(tn): return execute_command(tn, 'df -h') # Reboot the drone def reboot(tn): execute_command(tn, 'reboot') # Upload ftp and catch memory-full error def uploadfile(ftp, filename, content): try: ftp.storbinary("STOR " + filename, co...
running += ' GStreamer (gst-launch)'
conditional_block
parrot_utils.py
# # Copyright (C) 2012-2014 The Paparazzi Team # # This file is part of Paparazzi. # # Paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # P...
(tn, ftp): tn.close() ftp.close()
disconnect
identifier_name
parrot_utils.py
# # Copyright (C) 2012-2014 The Paparazzi Team # # This file is part of Paparazzi. # # Paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # P...
# Helper function def split_into_path_and_file(name): if name.count('/') <= 0: return ["./", name] return name.rsplit('/', 1) # Execute a command def execute_command(tn, command): tn.write(command + '\n') return tn.read_until('# ')[len(command) + 2:-4] # Check the version def check_version(tn,...
random_line_split
parrot_utils.py
# # Copyright (C) 2012-2014 The Paparazzi Team # # This file is part of Paparazzi. # # Paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # P...
# Close the telnet and ftp def disconnect(tn, ftp): tn.close() ftp.close()
try: tn = telnetlib.Telnet(host, timeout=3) ftp = FTP(host) ftp.login() tn.read_until('# ') return tn, ftp except: print('Could not connect to Parrot UAV (host: ' + host + ')') exit(2)
identifier_body
wsgidav_app.py
8080, "ext_servers": [ # "paste", # "cherrypy", # "wsgiref", "cherrypy-bundled", "wsgidav", ], "add_header_MS_Author_Via": True, "unquote_path_info": False, # See #8 # "use_text_f...
"enable_loggers": [ ], # Verbose Output "verbose": 1, # 0 - no output (excepting application exceptions) # 1 - show single line request summaries (for HTTP logging) # 2 - show additional events ...
random_line_split
wsgidav_app.py
share = "/" + share.strip("/") # We allow a simple string as 'provider'. In this case we interpret # it as a file system root folder that is published. if isinstance(provider, basestring): provider = FilesystemProvider(provider) asse...
userInfo = environ.get("http_authenticator.username") if not userInfo: userInfo = "(anonymous)" threadInfo = "" if self._verbose >= 1: threadInfo = "<%s> " % threading._get_ident() extra = [] i...
conditional_block
wsgidav_app.py
8080, "ext_servers": [ # "paste", # "cherrypy", # "wsgiref", "cherrypy-bundled", "wsgidav", ], "add_header_MS_Author_Via": True, "unquote_path_info": False, # See #8 # "use_text_fi...
locksManager = LockManager(lockStorage) propsManager = config.get("propsmanager") if not propsManager: # Normalize False, 0 to None propsManager = None elif propsManager is True: propsManager = PropertyManager() mount_p...
def __init__(self, config): self.config = config util.initLogging(config["verbose"], config.get("enable_loggers", [])) util.log("Default encoding: %s (file system: %s)" % (sys.getdefaultencoding(), sys.getfilesystemencoding())) # Evaluate configuration and set d...
identifier_body
wsgidav_app.py
8080, "ext_servers": [ # "paste", # "cherrypy", # "wsgiref", "cherrypy-bundled", "wsgidav", ], "add_header_MS_Author_Via": True, "unquote_path_info": False, # See #8 # "use_text_f...
(config): mandatoryFields = ["provider_mapping", ] for field in mandatoryFields: if not field in config: raise ValueError("Invalid configuration: missing required field '%s'" % field) #======================================================================...
_checkConfig
identifier_name
class-exports.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { assert_eq!(cat("Spreckles".to_string()).get_name(), "Spreckles".to_string()); }
meows: 0 } } }
random_line_split
class-exports.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ assert_eq!(cat("Spreckles".to_string()).get_name(), "Spreckles".to_string()); }
identifier_body
class-exports.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ meows: usize, name: String, } impl cat { pub fn get_name(&self) -> String { self.name.clone() } } pub fn cat(in_name: String) -> cat { cat { name: in_name, meows: 0 } } } pub fn main() { assert_eq!(cat("Spreckles".to_string()).g...
cat
identifier_name
3160-spec.ts
import { Chart } from '../../src'; import { createDiv, removeDom } from '../util/dom'; describe('#3160', () => { const div = createDiv(); const chart = new Chart({ container: div, // 指定图表容器 ID height: 300, // 指定图表高度 autoFit: true, }); chart.coordinate('theta'); const data = [ { type: '1', it...
const label1 = labels.find((l) => l.get('id') === `1-${data[0].type}`); const label2 = labels.find((l) => l.get('id') === `1-${data[1].type}`); const label3 = labels.find((l) => l.get('id') === `1-${data[2].type}`); const label4 = labels.find((l) => l.get('id') === `1-${data[3].type}`); // @ts-igno...
.adjust('stack'); chart.render(); const labels = chart.geometries[0].labelsContainer.getChildren();
random_line_split
train-slim-fcn.py
(): def resnet_arg_scope (weight_decay=0.0001): print_red("Patching resnet_v2 arg_scope when training from scratch") return resnet_utils.resnet_arg_scope(weight_decay=weight_decay, batch_norm_decay=0.9, batch_norm_epsilon=5e-4, batch_norm_...
patch_arg_scopes
identifier_name
train-slim-fcn.py
_200'] = resnet_arg_scope pass augments = None #from . config import * #if os.path.exists('config.py'): def print_red (txt): print('\033[91m' + txt + '\033[0m') def print_green (txt): print('\033[92m' + txt + '\033[0m') print(augments) flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('db', ...
# probability of class 1 -- not very useful if FLAGS.classes > 2 probs = tf.squeeze(tf.slice(tf.nn.softmax(logits), [0,0,0,1], [-1,-1,-1,1]), 3) loss, metrics = fcn_loss(logits, Y) metric_names = [x.name[:-2] for x in metrics] def format_metrics (avg): return ' '.join(['%s=%.3f' % (a, b) f...
logits = slim.conv2d_transpose(ft, FLAGS.classes, 32, 16) logits = tf.identity(logits, name='logits')
random_line_split
train-slim-fcn.py
nets_factory.arg_scopes_map['resnet_v1_50'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v1_101'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v1_152'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v1_200'] = resnet_arg_scope nets_factory.arg_scopes_map['resnet_v2_50'] ...
print_red("Patching resnet_v2 arg_scope when training from scratch") return resnet_utils.resnet_arg_scope(weight_decay=weight_decay, batch_norm_decay=0.9, batch_norm_epsilon=5e-4, batch_norm_scale=False)
identifier_body
train-slim-fcn.py
_200'] = resnet_arg_scope pass augments = None #from . config import * #if os.path.exists('config.py'): def print_red (txt): print('\033[91m' + txt + '\033[0m') def print_green (txt): print('\033[92m' + txt + '\033[0m') print(augments) flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('db', ...
if FLAGS.finetune or FLAGS.vgg: print_red("finetune, using RGB with vgg pixel means") COLORSPACE = 'RGB' PIXEL_MEANS = VGG_PIXEL_MEANS X = tf.placeholder(tf.float32, shape=(None, None, None, FLAGS.channels), name="images") # ground truth labels Y = tf.placeholder(tf.int32, sha...
try: os.makedirs(FLAGS.model) except: pass
conditional_block
config.rs
toml; use crate::db::Database; use crate::errors::*; use crate::repos; use crate::users; pub struct Config { pub main: MainConfig, pub admin: Option<AdminConfig>, pub metrics: Option<MetricsConfig>, pub github: GithubConfig, pub slack: SlackConfig, pub jira: Option<JiraConfig>, pub ldap: ...
pub pass_hash: String, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct SlackConfig { pub bot_token: String, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct GithubConfig { pub webhook_secret: String, pub host: String, pub api_token: Option<String>, pub app_id: Option<u...
pub struct MetricsConfig { pub salt: String,
random_line_split
config.rs
toml; use crate::db::Database; use crate::errors::*; use crate::repos; use crate::users; pub struct Config { pub main: MainConfig, pub admin: Option<AdminConfig>, pub metrics: Option<MetricsConfig>, pub github: GithubConfig, pub slack: SlackConfig, pub jira: Option<JiraConfig>, pub ldap: ...
} pub fn resolved_states(&self) -> Vec<String> { if let Some(ref states) = self.resolved_states { states.clone() // hmm. do these w/o a clone? } else { vec!["Resolved".into(), "Done".into()] } } pub fn fixed_resolutions(&self) -> Vec<String> { i...
{ vec!["Pending Review".into()] }
conditional_block
config.rs
toml; use crate::db::Database; use crate::errors::*; use crate::repos; use crate::users; pub struct Config { pub main: MainConfig, pub admin: Option<AdminConfig>, pub metrics: Option<MetricsConfig>, pub github: GithubConfig, pub slack: SlackConfig, pub jira: Option<JiraConfig>, pub ldap: ...
(&self) -> Vec<String> { if let Some(ref states) = self.progress_states { states.clone() // hmm. do these w/o a clone? } else { vec!["In Progress".into()] } } pub fn review_states(&self) -> Vec<String> { if let Some(ref states) = self.review_states { ...
progress_states
identifier_name
index.test.js
/* eslint-env jest */ import fs from 'fs-extra' import { join } from 'path' import { killApp, findPort, launchApp, nextStart, nextBuild, fetchViaHTTP, } from 'next-test-utils' import webdriver from 'next-webdriver' import cheerio from 'cheerio' jest.setTimeout(1000 * 60 * 2) const appDir = join(__dirname...
, onStdout(msg) { stdout += msg }, }) }) afterAll(() => killApp(app)) it('should not show pages/404 GIP error if _app has GIP', async () => { const res = await fetchViaHTTP(appPort, '/abc') expect(res.status).toBe(404) const $ = cheerio.load(await res.text(...
{ stderr += msg }
identifier_body
index.test.js
/* eslint-env jest */ import fs from 'fs-extra' import { join } from 'path' import { killApp, findPort, launchApp, nextStart, nextBuild, fetchViaHTTP, } from 'next-test-utils' import webdriver from 'next-webdriver' import cheerio from 'cheerio' jest.setTimeout(1000 * 60 * 2) const appDir = join(__dirname...
}) })
random_line_split
index.test.js
/* eslint-env jest */ import fs from 'fs-extra' import { join } from 'path' import { killApp, findPort, launchApp, nextStart, nextBuild, fetchViaHTTP, } from 'next-test-utils' import webdriver from 'next-webdriver' import cheerio from 'cheerio' jest.setTimeout(1000 * 60 * 2) const appDir = join(__dirname...
(msg) { stderr += msg }, onStdout(msg) { stdout += msg }, }) }) afterAll(() => killApp(app)) it('should not show pages/404 GIP error if _app has GIP', async () => { const res = await fetchViaHTTP(appPort, '/abc') expect(res.status).toBe(404) ...
onStderr
identifier_name
code.py
import math import re from collections import defaultdict def matches(t1, t2): t1r = "".join([t[-1] for t in t1]) t2r = "".join([t[-1] for t in t2]) t1l = "".join([t[0] for t in t1]) t2l = "".join([t[0] for t in t2]) t1_edges = [t1[0], t1[-1], t1r, t1l] t2_edges = [t2[0], t2[-1], t2[0][::-1],...
(t): return [l[::-1] for l in t] # https://stackoverflow.com/a/34347121 def rotate(t): return [*map("".join, zip(*reversed(t)))] def set_corner(cor, right, down): rr = "".join([t[-1] for t in right]) dr = "".join([t[-1] for t in down]) rl = "".join([t[0] for t in right]) dl = "".join([t[0] f...
flip
identifier_name
code.py
import math import re from collections import defaultdict def matches(t1, t2): t1r = "".join([t[-1] for t in t1]) t2r = "".join([t[-1] for t in t2]) t1l = "".join([t[0] for t in t1]) t2l = "".join([t[0] for t in t2]) t1_edges = [t1[0], t1[-1], t1r, t1l] t2_edges = [t2[0], t2[-1], t2[0][::-1],...
break image[0][0] = corner added = {corner} for y in range(1, sz): pos = connected[image[0][y - 1]] for cand in pos: if cand not in added and len(connected[cand]) < 4: image[0][y] = cand added.add(cand) break for ...
corner = i
random_line_split
code.py
import math import re from collections import defaultdict def matches(t1, t2): t1r = "".join([t[-1] for t in t1]) t2r = "".join([t[-1] for t in t2]) t1l = "".join([t[0] for t in t1]) t2l = "".join([t[0] for t in t2]) t1_edges = [t1[0], t1[-1], t1r, t1l] t2_edges = [t2[0], t2[-1], t2[0][::-1],...
# https://stackoverflow.com/a/34347121 def rotate(t): return [*map("".join, zip(*reversed(t)))] def set_corner(cor, right, down): rr = "".join([t[-1] for t in right]) dr = "".join([t[-1] for t in down]) rl = "".join([t[0] for t in right]) dl = "".join([t[0] for t in down]) r_edges = [right...
return [l[::-1] for l in t]
identifier_body
code.py
import math import re from collections import defaultdict def matches(t1, t2): t1r = "".join([t[-1] for t in t1]) t2r = "".join([t[-1] for t in t2]) t1l = "".join([t[0] for t in t1]) t2l = "".join([t[0] for t in t2]) t1_edges = [t1[0], t1[-1], t1r, t1l] t2_edges = [t2[0], t2[-1], t2[0][::-1],...
with open("output.txt", "w+") as f: for l in rotate(rotate(rotate(image))): f.write(l + "\n") print(sum([l.count("#") for l in image])) if __name__ == "__main__": part1() part2()
image = flip(image) for _ in range(4): image = rotate(image) for x in range(0, len(image) - kx): for y in range(0, len(image) - ky): parts = [] for i, p in enumerate(monster): dx = x + p[0] ...
conditional_block
htmlulistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLUListElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::...
pub fn SetType(&mut self, _type: &DOMString) -> ErrorResult { Ok(()) } }
{ None }
identifier_body
htmlulistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLUListElementBinding;
use dom::element::HTMLUListElementTypeId; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node, ScriptView}; pub struct HTMLUListElement { htmlelement: HTMLElement } impl HTMLUListElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLUListElement { HTMLULi...
use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument;
random_line_split
htmlulistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLUListElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::...
{ htmlelement: HTMLElement } impl HTMLUListElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLUListElement { HTMLUListElement { htmlelement: HTMLElement::new(HTMLUListElementTypeId, localName, document) } } pub fn new(localName: ~str, docume...
HTMLUListElement
identifier_name
Video.js
function Video(questionIndex){ var self = Ti.UI.createWindow({ backgroundColor:'white', barColor:'#940315' }); /* var webVideo = Ti.UI.createWebView({ url:'http://www.youtube.com/watch?v=3ovGokorQhA', height: Ti.UI.SIZE, width:Ti.UI.SIZE });*/ var caseVideo; if(questionIndex ===0){ caseVide...
return self; }; module.exports = Video;
mediaControlStyle: Titanium.Media.VIDEO_CONTROL_DEFAULT }); self.add(videoPlayer); //self.add(webVideo);
random_line_split
Video.js
function Video(questionIndex)
caseVideo = '/videos/clip2.mp4'; } else if (questionIndex===2){ caseVideo = '/videos/clip3.mp4'; }; var videoPlayer = Titanium.Media.createVideoPlayer({ top: '25%', url: caseVideo, autoplay: true, backgroundColor: 'blue', height: '50%', width: '100%', mediaControlStyle: Titanium.Media.VIDEO_CONT...
{ var self = Ti.UI.createWindow({ backgroundColor:'white', barColor:'#940315' }); /* var webVideo = Ti.UI.createWebView({ url:'http://www.youtube.com/watch?v=3ovGokorQhA', height: Ti.UI.SIZE, width:Ti.UI.SIZE });*/ var caseVideo; if(questionIndex ===0){ caseVideo = '/videos/clip1.mp4'; } ...
identifier_body
Video.js
function
(questionIndex){ var self = Ti.UI.createWindow({ backgroundColor:'white', barColor:'#940315' }); /* var webVideo = Ti.UI.createWebView({ url:'http://www.youtube.com/watch?v=3ovGokorQhA', height: Ti.UI.SIZE, width:Ti.UI.SIZE });*/ var caseVideo; if(questionIndex ===0){ caseVideo = '/videos/c...
Video
identifier_name
profile_extras.py
from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from usermgmt import utils register = template.Library() @register.filter(is_safe=True) @stringfilter def render_attributes(value, autoes...
"""A filter for changing a list of user attributes into a list of links, data, etc. """ # TODO # @makyo 2016-11-06 #63 if value == '': return 'No attributes' to_return = '<dl>' for attribute in value.split('\n'): k, v = attribute.split('=', 1) if k in utils.ATTRIBUTES...
identifier_body
profile_extras.py
from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from usermgmt import utils register = template.Library() @register.filter(is_safe=True) @stringfilter def render_attributes(value, autoes...
return 'No attributes' to_return = '<dl>' for attribute in value.split('\n'): k, v = attribute.split('=', 1) if k in utils.ATTRIBUTES: to_return += '<dt>{}</dt>'.format(utils.ATTRIBUTES[k]['dt']) to_return += '<dd>{}</dd>'.format( utils.ATTRIBUTES[...
""" # TODO # @makyo 2016-11-06 #63 if value == '':
random_line_split
profile_extras.py
from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from usermgmt import utils register = template.Library() @register.filter(is_safe=True) @stringfilter def
(value, autoescape=True): """A filter for changing a list of user attributes into a list of links, data, etc. """ # TODO # @makyo 2016-11-06 #63 if value == '': return 'No attributes' to_return = '<dl>' for attribute in value.split('\n'): k, v = attribute.split('=', 1) ...
render_attributes
identifier_name
profile_extras.py
from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from usermgmt import utils register = template.Library() @register.filter(is_safe=True) @stringfilter def render_attributes(value, autoes...
to_return += '</dl>' return mark_safe(to_return)
to_return += '<dt>{}</dt>'.format(utils.ATTRIBUTES[k]['dt']) to_return += '<dd>{}</dd>'.format( utils.ATTRIBUTES[k]['dd'].format(value=conditional_escape(v)))
conditional_block
ng_class.ts
import {isPresent, isString, StringWrapper, isBlank} from 'angular2/src/facade/lang'; import {Directive, LifecycleEvent} from 'angular2/metadata'; import {ElementRef} from 'angular2/core'; import {Renderer} from 'angular2/src/render/api'; import { KeyValueDiffer, IterableDiffer, IterableDiffers, KeyValueDiffers...
else { this._differ = this._keyValueDiffers.find(v).create(null); this._mode = 'keyValue'; } } else { this._differ = null; } } onCheck(): void { if (isPresent(this._differ)) { var changes = this._differ.diff(this._rawClass); if (isPresent(changes)) { if ...
{ this._differ = this._iterableDiffers.find(v).create(null); this._mode = 'iterable'; }
conditional_block
ng_class.ts
import {isPresent, isString, StringWrapper, isBlank} from 'angular2/src/facade/lang'; import {Directive, LifecycleEvent} from 'angular2/metadata'; import {ElementRef} from 'angular2/core'; import {Renderer} from 'angular2/src/render/api'; import { KeyValueDiffer, IterableDiffer, IterableDiffers, KeyValueDiffers...
(className: string, enabled): void { this._renderer.setElementClass(this._ngEl, className, enabled); } }
_toggleClass
identifier_name
ng_class.ts
import {isPresent, isString, StringWrapper, isBlank} from 'angular2/src/facade/lang'; import {Directive, LifecycleEvent} from 'angular2/metadata'; import {ElementRef} from 'angular2/core'; import {Renderer} from 'angular2/src/render/api'; import { KeyValueDiffer, IterableDiffer, IterableDiffers, KeyValueDiffers...
v = v.split(' '); } this._rawClass = v; if (isPresent(v)) { if (isListLikeIterable(v)) { this._differ = this._iterableDiffers.find(v).create(null); this._mode = 'iterable'; } else { this._differ = this._keyValueDiffers.find(v).create(null); this._mode = 'ke...
random_line_split
supports_rule.rs
for SupportsRule { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { let rules = self.rules.read_with(guard); SupportsRule { condition: self.condition.clone(), rules: ...
RawSelector
identifier_name
supports_rule.rs
heap usage. #[cfg(feature = "gecko")] pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { // Measurement of other fields may be added later. self.rules.unconditional_shallow_size_of(ops) + self.rules.read_with(guard).size_of(guard, ops) } }...
} } } #[cfg(feature = "gecko")] fn eval_moz_bool_pref(name: &CStr, cx: &ParserContext) -> bool { use crate::gecko_bindings::bindings; if !cx.in_ua_or_chrome_sheet() { return false; } unsafe { bindings::Gecko_GetBoolPrefValue(name.as_ptr()) } } #[cfg(feature = "servo")] fn eval_moz_...
random_line_split
base64mime.py
# Copyright (C) 2002-2007 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Base64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit ch...
encoded = b64encode(header_bytes).decode("ascii") return '=?%s?b?%s?=' % (charset, encoded) def body_encode(s, maxlinelen=76, eol=NL): r"""Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will en...
header_bytes = header_bytes.encode(charset)
conditional_block
base64mime.py
# Copyright (C) 2002-2007 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Base64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit ch...
def body_encode(s, maxlinelen=76, eol=NL): r"""Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this ...
"""Encode a single header line with Base64 encoding in a given charset. charset names the character set to use to encode the header. It defaults to iso-8859-1. Base64 encoding is defined in RFC 2045. """ if not header_bytes: return "" if isinstance(header_bytes, str): header_bytes...
identifier_body
base64mime.py
# Copyright (C) 2002-2007 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Base64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit ch...
'header_encode', 'header_length', ] from base64 import b64encode from binascii import b2a_base64, a2b_base64 CRLF = '\r\n' NL = '\n' EMPTYSTRING = '' # See also Charset.py MISC_LEN = 7 # Helpers def header_length(bytearray): """Return the length of s when it is encoded with base64.""" groups_of_3, ...
'decodestring',
random_line_split
base64mime.py
# Copyright (C) 2002-2007 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Base64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit ch...
(header_bytes, charset='iso-8859-1'): """Encode a single header line with Base64 encoding in a given charset. charset names the character set to use to encode the header. It defaults to iso-8859-1. Base64 encoding is defined in RFC 2045. """ if not header_bytes: return "" if isinstanc...
header_encode
identifier_name
index.js
'use strict'; var path = require('path'); var hof = require('hof'); var i18n = hof.i18n({ path: path.resolve(__dirname, '../apps/common/translations/__lng__/__ns__.json') }); var config = require('../config'); var logger = require('../lib/logger'); // eslint-disable-next-line no-unused-vars module.exports = functio...
err.template = 'error'; content.title = content.title || i18n.translate('errors.default.title'); content.message = content.message || i18n.translate('errors.default.message'); res.statusCode = err.status || 500; logger.error(err.message || err.error, err); res.render(err.template, { error: err, ...
{ err.status = 403; content.title = i18n.translate('errors.cookies-required.title'); content.message = i18n.translate('errors.cookies-required.message'); }
conditional_block
index.js
'use strict'; var path = require('path'); var hof = require('hof'); var i18n = hof.i18n({ path: path.resolve(__dirname, '../apps/common/translations/__lng__/__ns__.json') }); var config = require('../config'); var logger = require('../lib/logger'); // eslint-disable-next-line no-unused-vars module.exports = functio...
content.message = i18n.translate('errors.session.message'); } if (err.code === 'NO_COOKIES') { err.status = 403; content.title = i18n.translate('errors.cookies-required.title'); content.message = i18n.translate('errors.cookies-required.message'); } err.template = 'error'; content.title = con...
random_line_split
myservo.py
import pigpio import time from multiprocessing import Process, Queue, Lock #----------------------- SERVO 1 ---------------------------- speed = .1 minP = 30 maxP = 180 currentP = 90 newP = 90 q = Queue() #queue for the new position q.put(newP) q2 = Queue() #queue for the current position q2.put(currentP) l = Lock()...
(dist): global newP_2 l_2.acquire() if not q_2.empty(): newP_2 = q_2.get() newP_2 = newP_2+dist if newP_2 > maxP_2 : newP_2 = maxP_2 q_2 .put(newP_2 ) l_2 .release() def turnUp(dist): global newP_2 l_2 .acquire() if not q_2 .empty(): newP_2 = q_2 ...
turnDw
identifier_name
myservo.py
import pigpio import time from multiprocessing import Process, Queue, Lock #----------------------- SERVO 1 ---------------------------- speed = .1 minP = 30 maxP = 180 currentP = 90 newP = 90 q = Queue() #queue for the new position q.put(newP) q2 = Queue() #queue for the current position q2.put(currentP) l = Lock()...
print 'Process P1 terminated.' except: print 'Error!!Process P1 terminated' pi_2.stop()
try: servoPin_2=17 pi_2 = pigpio.pi() _newP_2 = 90 while not proc.empty(): l_2.acquire() if not q_2.empty(): _newP_2 = q_2.get() _currentP_2 = q2_2.get() while _currentP_2 < _newP_2: #move the motor _currentP_2 += 1 pi_2.set...
identifier_body
myservo.py
import pigpio import time from multiprocessing import Process, Queue, Lock #----------------------- SERVO 1 ---------------------------- speed = .1 minP = 30 maxP = 180 currentP = 90 newP = 90 q = Queue() #queue for the new position q.put(newP) q2 = Queue() #queue for the current position q2.put(currentP) l = Lock()...
def turnDw(dist): global newP_2 l_2.acquire() if not q_2.empty(): newP_2 = q_2.get() newP_2 = newP_2+dist if newP_2 > maxP_2 : newP_2 = maxP_2 q_2 .put(newP_2 ) l_2 .release() def turnUp(dist): global newP_2 l_2 .acquire() if not q_2 .empty(): new...
q2_2.put(currentP_2) l_2 = Lock()
random_line_split
myservo.py
import pigpio import time from multiprocessing import Process, Queue, Lock #----------------------- SERVO 1 ---------------------------- speed = .1 minP = 30 maxP = 180 currentP = 90 newP = 90 q = Queue() #queue for the new position q.put(newP) q2 = Queue() #queue for the current position q2.put(currentP) l = Lock()...
q2.put(_currentP) l.release() pi.stop() print 'Process P0 terminated.' except: print 'Error!!Process P0 terminated:' pi.stop() # ----------------------------- SERVO 2 ------------------ speed = .1 minP_2 = 80 maxP_2 = 100 currentP_2 = 90 newP_2 = 90 q_2 = Queue() #queue for the new ...
_currentP -= 1 pi.set_servo_pulsewidth(servoPin,g2q(_currentP))
conditional_block
decodeJPEGLossless.js
"use strict"; (function (cornerstoneWADOImageLoader) { function
(dataSet, frame) { var pixelDataElement = dataSet.elements.x7fe00010; var bitsAllocated = dataSet.uint16('x00280100'); var pixelRepresentation = dataSet.uint16('x00280103'); var frameData = dicomParser.readEncapsulatedPixelData(dataSet, pixelDataElement, frame); var byteOutput = bitsAllocated <= 8 ?...
decodeJPEGLossless
identifier_name
decodeJPEGLossless.js
"use strict"; (function (cornerstoneWADOImageLoader) { function decodeJPEGLossless(dataSet, frame)
} // module exports cornerstoneWADOImageLoader.decodeJPEGLossless = decodeJPEGLossless; }(cornerstoneWADOImageLoader));
{ var pixelDataElement = dataSet.elements.x7fe00010; var bitsAllocated = dataSet.uint16('x00280100'); var pixelRepresentation = dataSet.uint16('x00280103'); var frameData = dicomParser.readEncapsulatedPixelData(dataSet, pixelDataElement, frame); var byteOutput = bitsAllocated <= 8 ? 1 : 2; //con...
identifier_body
decodeJPEGLossless.js
"use strict"; (function (cornerstoneWADOImageLoader) { function decodeJPEGLossless(dataSet, frame) { var pixelDataElement = dataSet.elements.x7fe00010; var bitsAllocated = dataSet.uint16('x00280100'); var pixelRepresentation = dataSet.uint16('x00280103'); var frameData = dicomParser.readEncapsulatedP...
else { // untested! return new Uint8Array(decompressedData.buffer); } } else { return new Int16Array(decompressedData.buffer); } } // module exports cornerstoneWADOImageLoader.decodeJPEGLossless = decodeJPEGLossless; }(cornerstoneWADOImageLoader));
{ return new Uint16Array(decompressedData.buffer); }
conditional_block
decodeJPEGLossless.js
"use strict"; (function (cornerstoneWADOImageLoader) {
function decodeJPEGLossless(dataSet, frame) { var pixelDataElement = dataSet.elements.x7fe00010; var bitsAllocated = dataSet.uint16('x00280100'); var pixelRepresentation = dataSet.uint16('x00280103'); var frameData = dicomParser.readEncapsulatedPixelData(dataSet, pixelDataElement, frame); var byte...
random_line_split
ffi.rs
#![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use std::os::raw::c_ulong; pub type dssim_px_t = f32; #[link(name = "Accelerate", kind = "framework")] #[cfg(target_os = "macos")] extern "C" { pub fn vImageConvolve_PlanarF(src: *const vImage_Buffer<*const f32>, ...
<T> { pub data: T, pub height: vImagePixelCount, pub width: vImagePixelCount, pub rowBytes: usize, }
vImage_Buffer
identifier_name
ffi.rs
#![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use std::os::raw::c_ulong; pub type dssim_px_t = f32; #[link(name = "Accelerate", kind = "framework")] #[cfg(target_os = "macos")] extern "C" { pub fn vImageConvolve_PlanarF(src: *const vImage_Buffer<*const f32>, ...
/* Use the nearest pixel for missing pixels. */ kvImageEdgeExtend = 8, /* Pass to turn off internal tiling and disable internal multithreading. Use this if you want to do your own tiling, or to use the Min/Max filters in place. */ kvImageDoNotTile = 16, /* Use a higher quality, slower re...
random_line_split
toMQL.js
define(function (require) { var test = require('intern!object'), assert = require('intern/chai!assert'), toMQL = require('intern/dojo/node!../../lib/toMQL'), Query = require('intern/dojo/node!rql/query').Query; test({ name: 'cayley-perstore toMQL', beforeEach: function () { }, 'is a function': functi...
'parsed query': function () { var query = 'eq(foo,bar)', expected = { foo: 'bar' }, actual = toMQL(query); assert.deepEqual(actual, expected, 'stringified queries are parsed'); }, 'special values': { 'null values (match any)': function () { var query = new Query().eq('foo', null), expe...
},
random_line_split
TableGridTest.ts
import { Fun } from '@ephox/katamari'; import * as Structs from 'ephox/snooker/api/Structs'; import TableGrid from 'ephox/snooker/model/TableGrid'; import { UnitTest, assert } from '@ephox/bedrock'; import { Element } from '@ephox/sugar'; UnitTest.test('TableGrid.subgrid test', function () { const r = Structs.rowcel...
]; check({ colspan: 3, rowspan: 1 }, 0, 0, world); check({ colspan: 2, rowspan: 1 }, 0, 1, world); check({ colspan: 2, rowspan: 1 }, 1, 0, world); check({ colspan: 1, rowspan: 1 }, 2, 0, world); });
const world = [ r([ en('a', false), en('a', false), en('a', false) ], 'thead'), r([ en('b', false), en('b', false), en('c', false) ], 'tbody'), r([ en('d', false), en('e', false), en('c', false) ], 'tfoot')
random_line_split
index.ts
* One of `"bar"`, `"circle"`, `"square"`, `"tick"`, `"line"`, `"area"`, `"point"`, `"rule"`, and `"text"`. * TODO: Update tpe to be a string literal union of those types, rather than `string`. */ readonly mark?: string; /** * Represents the size of the visualization, if it has been specifie...
* Union of all channel kinds - this is more fine-grained than is declared by the vega-lite specification */ export type ChannelDef = FieldChannelDef | ValueChannelDef; /** * Contains the settings for the scale of a channel * TODO: ScaleDef is dependent on field type, and different definitions should exist for each...
/**
random_line_split
test_driver_model.py
# Copyright (c) 2015 OpenStack Foundation # # 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 ...
context = { "driver_id": "invalid-id" } self.assertRaises(webservice.DataModelException, self.driver_model.get_item, 'invalid-id', {}, context)
identifier_body
test_driver_model.py
# Copyright (c) 2015 OpenStack Foundation # # 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 ...
(self): context = { "driver_id": "fake_datasource" } expected_ret = { "config": { "auth_url": "required", "endpoint": "(optional)", "password": "required", "poll_time": "(optional)", "region":...
test_driver_details
identifier_name
test_driver_model.py
# Copyright (c) 2015 OpenStack Foundation # # 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 ...
expected_ret = { "config": { "auth_url": "required", "endpoint": "(optional)", "password": "required", "poll_time": "(optional)", "region": "(optional)", "tenant_name": "required", "userna...
"driver_id": "fake_datasource" }
random_line_split
views.py
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use t...
def rdp(args, **kvargs): return views.rdp(args, **kvargs) class AdminUpdateView(views.UpdateView): workflow_class = update_instance.AdminUpdateInstance class AdminIndexView(tables.DataTableView): table_class = project_tables.AdminInstancesTable template_name = 'admin/instances/index.html' def h...
def spice(args, **kvargs): return views.spice(args, **kvargs) # re-use rdp from project.instances.views to make reflection work
random_line_split
views.py
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use t...
redirect_url = 'horizon:admin:instances:index'
identifier_body
views.py
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use t...
return filters class LiveMigrateView(forms.ModalFormView): form_class = project_forms.LiveMigrateForm template_name = 'admin/instances/live_migrate.html' context_object_name = 'instance' success_url = reverse_lazy("horizon:admin:instances:index") def get_context_data(self, **kwargs): ...
filters[filter_field] = filter_string
conditional_block
views.py
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use t...
(self, filters): filter_field = self.table.get_filter_field() filter_action = self.table._meta._filter_action if filter_action.is_api_filter(filter_field): filter_string = self.table.get_filter_string() if filter_field and filter_string: filters[filter_fie...
get_filters
identifier_name
key-handling.ts
import * as Hammer from 'hammerjs'; import { pointEquals } from '../interfaces/point'; import settings from '../settings'; import { placePiece, stopLockTimeout } from './gameloop'; import { copyMatrix, getUnstuckPosition, matrixEquals } from './matrix-calculations'; import { pauseGame, restartGame } from './pause-game'...
(deltaX: number, reset: boolean): void { const canvasWidth = panel.canvas.offsetWidth; const tileWidth = canvasWidth / board.size.width; if (reset || typeof colStart === 'undefined') { colStart = player.position.x - deltaX / tileWidth; } const newCol = Math.floor(colStart + deltaX / tileW...
movePiece
identifier_name
key-handling.ts
import * as Hammer from 'hammerjs'; import { pointEquals } from '../interfaces/point'; import settings from '../settings'; import { placePiece, stopLockTimeout } from './gameloop'; import { copyMatrix, getUnstuckPosition, matrixEquals } from './matrix-calculations'; import { pauseGame, restartGame } from './pause-game'...
function handlePlayerMovement(keyCode: string, repeated: boolean): boolean { if (paused.value) return false; let newPosition = { x: player.position.x, y: player.position.y }; const beforeMatrix = copyMatrix(player.shape.blocks); let triggered = true; let hardDropped = false; ...
} }
random_line_split
key-handling.ts
import * as Hammer from 'hammerjs'; import { pointEquals } from '../interfaces/point'; import settings from '../settings'; import { placePiece, stopLockTimeout } from './gameloop'; import { copyMatrix, getUnstuckPosition, matrixEquals } from './matrix-calculations'; import { pauseGame, restartGame } from './pause-game'...
else if (keyCode === 'Escape') { pauseGame(); } }); document.addEventListener('keyup', e => { if (keysDown.contains(e.code)) { keysDown.remove(e.code); if (keysDown.count === 0) { keyThresholdTimer.stop(); keyInterval.stop();...
{ if (keyCode === 'Escape' || keyCode === 'Space') { restartGame(); } }
conditional_block
key-handling.ts
import * as Hammer from 'hammerjs'; import { pointEquals } from '../interfaces/point'; import settings from '../settings'; import { placePiece, stopLockTimeout } from './gameloop'; import { copyMatrix, getUnstuckPosition, matrixEquals } from './matrix-calculations'; import { pauseGame, restartGame } from './pause-game'...
} } } function handlePlayerMovement(keyCode: string, repeated: boolean): boolean { if (paused.value) return false; let newPosition = { x: player.position.x, y: player.position.y }; const beforeMatrix = copyMatrix(player.shape.blocks); let triggered = true; let ha...
{ const canvasWidth = panel.canvas.offsetWidth; const tileWidth = canvasWidth / board.size.width; if (reset || typeof colStart === 'undefined') { colStart = player.position.x - deltaX / tileWidth; } const newCol = Math.floor(colStart + deltaX / tileWidth); if (newCol === colStart) ret...
identifier_body
nested-matchs.rs
// Copyright 2012 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 ...
} } pub fn main() { foo(); }
random_line_split
nested-matchs.rs
// Copyright 2012 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 ...
() -> ! { panic!(); } fn foo() { match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{}", bar); } None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
baz
identifier_name
nested-matchs.rs
// Copyright 2012 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 ...
} pub fn main() { foo(); }
{ match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{}", bar); } None::<int> => { println!("hello"); } }
identifier_body
11_vs_11_hard_deterministic.py
# coding=utf-8 # Copyright 2019 Google LLC # 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 ...
(builder): builder.config().game_duration = 3000 builder.config().right_team_difficulty = 0.95 builder.config().deterministic = True if builder.EpisodeNumber() % 2 == 0: first_team = Team.e_Left second_team = Team.e_Right else: first_team = Team.e_Right second_team = Team.e_Left builder.SetT...
build_scenario
identifier_name
11_vs_11_hard_deterministic.py
# coding=utf-8 # Copyright 2019 Google LLC # 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 ...
builder.AddPlayer(-0.500000, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.422000, 0.195760, e_PlayerRole_RB) builder.AddPlayer(-0.184212, -0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.267574, 0.000000, e_PlayerRole_CM) builder.AddPlayer(-0.184212, 0.105680, e_PlayerRole_CM) builder.AddPlayer(-0.010000,...
builder.AddPlayer(0.000000, 0.020000, e_PlayerRole_RM) builder.AddPlayer(0.000000, -0.020000, e_PlayerRole_CF) builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.500000, -0.06356, e_PlayerRole_CB)
random_line_split
11_vs_11_hard_deterministic.py
# coding=utf-8 # Copyright 2019 Google LLC # 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 ...
else: first_team = Team.e_Right second_team = Team.e_Left builder.SetTeam(first_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.AddPlayer(0.000000, 0.020000, e_PlayerRole_RM) builder.AddPlayer(0.000000, -0.020000, e_PlayerRole_CF) builder.AddPlayer(-0.422000, -0.19576, e_Play...
first_team = Team.e_Left second_team = Team.e_Right
conditional_block
11_vs_11_hard_deterministic.py
# coding=utf-8 # Copyright 2019 Google LLC # 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 ...
builder.AddPlayer(-0.010000, -0.21610, e_PlayerRole_LM) builder.SetTeam(second_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.AddPlayer(-0.050000, 0.000000, e_PlayerRole_RM) builder.AddPlayer(-0.010000, 0.216102, e_PlayerRole_CF) builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB)...
builder.config().game_duration = 3000 builder.config().right_team_difficulty = 0.95 builder.config().deterministic = True if builder.EpisodeNumber() % 2 == 0: first_team = Team.e_Left second_team = Team.e_Right else: first_team = Team.e_Right second_team = Team.e_Left builder.SetTeam(first_tea...
identifier_body
3vilTwin-Attacker.py
#!/usr/bin/env python2.7 #The MIT License (MIT) #Copyright (c) 2015-2016 mh4x0f P0cL4bs Team #Permission is hereby granted, free of charge, to any person obtaining a copy of #this software and associated documentation files (the "Software"), to deal in #the Software without restriction, including without limitation the...
#the Software, and to permit persons to whom the Software is furnished to do so, #subject to the following conditions: #The above copyright notice and this permission notice shall be included in all #copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS...
#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
random_line_split
3vilTwin-Attacker.py
#!/usr/bin/env python2.7 #The MIT License (MIT) #Copyright (c) 2015-2016 mh4x0f P0cL4bs Team #Permission is hereby granted, free of charge, to any person obtaining a copy of #this software and associated documentation files (the "Software"), to deal in #the Software without restriction, including without limitation the...
(): check_dependencies() root = QApplication(argv) app = Initialize() app.setWindowIcon(QIcon('rsc/icon.ico')) app.center(),app.show() exit(root.exec_()) if __name__ == '__main__': if not getuid() == 0: app2 = QApplication(argv) priv = frm_privelege() priv.setWindowI...
ExecRootApp
identifier_name
3vilTwin-Attacker.py
#!/usr/bin/env python2.7 #The MIT License (MIT) #Copyright (c) 2015-2016 mh4x0f P0cL4bs Team #Permission is hereby granted, free of charge, to any person obtaining a copy of #this software and associated documentation files (the "Software"), to deal in #the Software without restriction, including without limitation the...
ExecRootApp()
app2 = QApplication(argv) priv = frm_privelege() priv.setWindowIcon(QIcon('rsc/icon.ico')) priv.show(),app2.exec_() exit(Refactor.threadRoot(priv.Editpassword.text()))
conditional_block
3vilTwin-Attacker.py
#!/usr/bin/env python2.7 #The MIT License (MIT) #Copyright (c) 2015-2016 mh4x0f P0cL4bs Team #Permission is hereby granted, free of charge, to any person obtaining a copy of #this software and associated documentation files (the "Software"), to deal in #the Software without restriction, including without limitation the...
if __name__ == '__main__': if not getuid() == 0: app2 = QApplication(argv) priv = frm_privelege() priv.setWindowIcon(QIcon('rsc/icon.ico')) priv.show(),app2.exec_() exit(Refactor.threadRoot(priv.Editpassword.text())) ExecRootApp()
check_dependencies() root = QApplication(argv) app = Initialize() app.setWindowIcon(QIcon('rsc/icon.ico')) app.center(),app.show() exit(root.exec_())
identifier_body
file_logger.rs
use std::io::Write; use std::fs::{File, OpenOptions}; use {Logger, MessageType, format_message}; /// Write log to text file. pub struct FileLogger { log_file: String } impl FileLogger { pub fn
(file_path: &str) -> FileLogger { File::create(file_path).unwrap(); FileLogger { log_file: file_path.to_string() } } } impl Logger for FileLogger { fn log(&self, msg_type:MessageType, message:&str) { let mut file = OpenOptions::new() .append(true) .write(true) .open(...
new
identifier_name
file_logger.rs
use std::io::Write; use std::fs::{File, OpenOptions};
/// Write log to text file. pub struct FileLogger { log_file: String } impl FileLogger { pub fn new(file_path: &str) -> FileLogger { File::create(file_path).unwrap(); FileLogger { log_file: file_path.to_string() } } } impl Logger for FileLogger { fn log(&self, msg_type:MessageType, message:&str) { ...
use {Logger, MessageType, format_message};
random_line_split
file_logger.rs
use std::io::Write; use std::fs::{File, OpenOptions}; use {Logger, MessageType, format_message}; /// Write log to text file. pub struct FileLogger { log_file: String } impl FileLogger { pub fn new(file_path: &str) -> FileLogger { File::create(file_path).unwrap(); FileLogger { log_file: file_path.to_string...
{ let logger = FileLogger::new("test.log"); logger.info("Test info message."); logger.warn("Test warn message."); logger.error("Test error message."); }
identifier_body
train_lstm.py
#!/usr/local/bin/python2.7 from sys import exit from os import environ, system environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import utils import signal from keras.layers import Input, Dense, Dropout, concatenate, LSTM, BatchNormalization from keras.models import Model from keras.callbacks import Model...
''' Now we train both models ''' if ADV > 0: print 'TRAINING ADVERSARIAL NETWORK' system('mv logs/train_lstm.log logs/train_lstm.log.old') flog = open('logs/train_lstm.log','w') callback = LambdaCallback( on_batch_end=lambda batch, logs: flog.write('batch=%i,logs=%s\n'%(batch,str(logs))) )...
print '###################################'
random_line_split
train_lstm.py
#!/usr/local/bin/python2.7 from sys import exit from os import environ, system environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import utils import signal from keras.layers import Input, Dense, Dropout, concatenate, LSTM, BatchNormalization from keras.models import Model from keras.callbacks import Model...
def save_and_exit(signal=None, frame=None, name='classifier', model=classifier): save_classifier(name, model) flog.close() exit(1) signal.signal(signal.SIGINT, save_and_exit) ''' now build the adversarial setup ''' # set up data train_gen = obj.generatePF(data, partition='train', batch=1000, decorr_...
model.save('models/%s.h5'%name)
identifier_body
train_lstm.py
#!/usr/local/bin/python2.7 from sys import exit from os import environ, system environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import utils import signal from keras.layers import Input, Dense, Dropout, concatenate, LSTM, BatchNormalization from keras.models import Model from keras.callbacks import Model...
(fpath): coll = obj.PFSVCollection() coll.add_categories(['singletons', 'pf'], fpath) return coll top = make_coll('/fastscratch/snarayan/pandaarrays/v1//PARTITION/ZpTT_*_CATEGORY.npy') qcd = make_coll('/fastscratch/snarayan/pandaarrays/v1//PARTITION/QCD_*_CATEGORY.npy') data = [top, qcd] # preload some...
make_coll
identifier_name
train_lstm.py
#!/usr/local/bin/python2.7 from sys import exit from os import environ, system environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import utils import signal from keras.layers import Input, Dense, Dropout, concatenate, LSTM, BatchNormalization from keras.models import Model from keras.callbacks import Model...
# callbacks=[callback, tb], validation_data=classifier_validation_gen, validation_steps=100) save_classifier(name='classifier')
print 'TRAINING CLASSIFIER ONLY' system('mv logs/train_lstmnoreg.log logs/train_lstmnoreg.log.old') flog = open('logs/train_lstmnoreg.log','w') callback = LambdaCallback( on_batch_end=lambda batch, logs: flog.write('batch=%i,logs=%s\n'%(batch,str(logs))) ) tb = TensorBoard( log_dir...
conditional_block
input-base.ts
.subscribe((textInputHasFocus: any) => { this.focusChange(textInputHasFocus); this.checkHasValue(nativeInput.getValue()); if (!textInputHasFocus) { this.onTouched(textInputHasFocus); } }); this.checkHasValue(nativeInput.getValue()); this.setDisabled(this._disabled); var...
registerOnTouched
identifier_name
input-base.ts
we need to clear the text input if clearOnEdit is enabled * @private */ checkClearOnEdit(inputValue: string) { if (!this._clearOnEdit) { return; } // Did the input value change after it was blurred and edited? if (this._didBlurAfterEdit && this.hasValue()) { // Clear the input ...
{ this._scrollView.clearScrollPaddingFocusOut(); }
conditional_block
input-base.ts
if (this._usePadding) { this._scrollView.clearScrollPaddingFocusOut(); } return; } if (this._usePadding) { // add padding to the bottom of the scroll view (if needed) scrollView.addScrollPadding(scrollData.scrollPadding); } // manually scroll the text...
{ distanceToScroll = Math.abs(distanceToScroll); let duration = distanceToScroll / SCROLL_ASSIST_SPEED; return Math.min(400, Math.max(150, duration)); }
identifier_body
input-base.ts
.touched); element.setElementClass('ng-pristine', control.pristine); element.setElementClass('ng-dirty', control.dirty); element.setElementClass('ng-valid', control.valid); element.setElementClass('ng-invalid', !control.valid); } setValue(val: any) { this._value = val; this.checkHasValue(va...
console.debug(`input-base, initFocus(), scrollView: ${!!scrollView}`); if (scrollView) { // this input is inside of a scroll view // find out if text input should be manually scrolled into view // get container of this input, probably an ion-item a few nodes up let ele: HTMLElement = t...
// begin the process of setting focus to the inner input element const scrollView = this._scrollView;
random_line_split