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
twit.py
import sys, os import tweepy # File with colon-separaten consumer/access token and secret consumer_file='twitter.consumer' access_file='twitter.access' def
(file): if os.path.exists(file): with open(file) as f: tokens = f.readline().replace('\n','').replace('\r','').split(':') if len(tokens) == 2: return tokens[0],tokens[1] else: raise ValueError("Expecting two colon-separated tokens") else: raise...
__load_auth
identifier_name
twit.py
import sys, os import tweepy # File with colon-separaten consumer/access token and secret consumer_file='twitter.consumer' access_file='twitter.access' def __load_auth(file): if os.path.exists(file): with open(file) as f: tokens = f.readline().replace('\n','').replace('\r','').split(':') ...
def twit(message, secret_dir='/secret'): # # Load the twitter consumer and access tokens and secrets consumer_token, consumer_secret = __load_auth(os.path.join(secret_dir, consumer_file)) access_token, access_secret = __load_auth(os.path.join(secret_dir, access_file)) # # Perform OAuth authentic...
random_line_split
twit.py
import sys, os import tweepy # File with colon-separaten consumer/access token and secret consumer_file='twitter.consumer' access_file='twitter.access' def __load_auth(file): if os.path.exists(file):
else: raise IOError("File not found: %s" % file) def twit(message, secret_dir='/secret'): # # Load the twitter consumer and access tokens and secrets consumer_token, consumer_secret = __load_auth(os.path.join(secret_dir, consumer_file)) access_token, access_secret = __load_auth(os.path.joi...
with open(file) as f: tokens = f.readline().replace('\n','').replace('\r','').split(':') if len(tokens) == 2: return tokens[0],tokens[1] else: raise ValueError("Expecting two colon-separated tokens")
conditional_block
preprocess.rs
} fn env_pop() { ENV.with(|c| { let prev = c.borrow().prev.clone(); if prev.is_some() {
} }) } fn env_output() -> Vec<Token> { ENV.with(|c| { return c.borrow().output.clone(); }) } fn macros_get(key: &String) -> Option<Macro> { MACROS.with(|m| { match m.borrow().get(key) { Some(v) => Some(v.clone()), None => None, } }) } fn mac...
*c.borrow_mut() = *prev.unwrap();
random_line_split
preprocess.rs
fn env_pop() { ENV.with(|c| { let prev = c.borrow().prev.clone(); if prev.is_some() { *c.borrow_mut() = *prev.unwrap(); } }) } fn env_output() -> Vec<Token> { ENV.with(|c| { return c.borrow().output.clone(); }) } fn
(key: &String) -> Option<Macro> { MACROS.with(|m| { match m.borrow().get(key) { Some(v) => Some(v.clone()), None => None, } }) } fn macros_put(key: String, value: Macro) { MACROS.with(|m| { m.borrow_mut().insert(key, value); }) } #[derive(Clone, Debug)] ...
macros_get
identifier_name
preprocess.rs
new(); ctx.input = input; if prev.is_none() { ctx.prev = None; } else { ctx.prev = Some(Box::new(prev.unwrap())); } return ctx; } #[derive(Clone, Debug, PartialEq)] enum MacroType { OBJLIKE, FUNCLIKE, } #[derive(Clone, Debug)] struct Macro { ty: MacroType, tokens: V...
{ include(); }
conditional_block
preprocess.rs
fn env_pop() { ENV.with(|c| { let prev = c.borrow().prev.clone(); if prev.is_some() { *c.borrow_mut() = *prev.unwrap(); } }) } fn env_output() -> Vec<Token> { ENV.with(|c| { return c.borrow().output.clone(); }) } fn macros_get(key: &String) -> Option<Macro> ...
} fn new_env(prev: Option<Env>, input: Vec<Token>) -> Env { let mut ctx = Env::new(); ctx.input = input; if prev.is_none() { ctx.prev = None; } else { ctx.prev = Some(Box::new(prev.unwrap())); } return ctx; } #[derive(Clone, Debug, PartialEq)] enum MacroType { OBJLIKE, ...
{ Env { input: Vec::new(), output: Vec::new(), pos: 0, prev: None, } }
identifier_body
FromEventObservable.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Observable_1 = require('../Observable'); var...
(sourceObj) { return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; } function isJQueryStyleEventEmitter(sourceObj) { return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; } function isNodeList(sourceObj) {...
isNodeStyleEventEmmitter
identifier_name
FromEventObservable.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Observable_1 = require('../Observable'); var...
else if (isNodeStyleEventEmmitter(sourceObj)) { sourceObj.addListener(eventName, handler); unsubscribe = function () { return sourceObj.removeListener(eventName, handler); }; } subscriber.add(new Subscription_1.Subscription(unsubscribe)); }; FromEventObservable.p...
{ sourceObj.on(eventName, handler); unsubscribe = function () { return sourceObj.off(eventName, handler); }; }
conditional_block
FromEventObservable.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __()
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Observable_1 = require('../Observable'); var tryCatch_1 = require('../util/tryCatch'); var errorObject_1 = require('../util/errorObject'); var Subscription_1 = require('../Subscription'); function isNodeStyleEventEmmitter(...
{ this.constructor = d; }
identifier_body
FromEventObservable.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); };
var Subscription_1 = require('../Subscription'); function isNodeStyleEventEmmitter(sourceObj) { return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; } function isJQueryStyleEventEmitter(sourceObj) { return !!sourceObj && typeof sourceObj.on === 'fu...
var Observable_1 = require('../Observable'); var tryCatch_1 = require('../util/tryCatch'); var errorObject_1 = require('../util/errorObject');
random_line_split
F.simulateTree.js
 (function() { function getParentIndex(levels, level, index) { if (level > 0) { for (var i = index - 1; i >= 0; i--) { if (levels[i] == level - 1) { return i; } } } return -1; } function hasL...
})();
};
random_line_split
F.simulateTree.js
 (function() { function getParentIndex(levels, level, index) { if (level > 0) { for (var i = index - 1; i >= 0; i--) { if (levels[i] == level - 1) { return i; } } } return -1; } function hasL...
F.simulateTree = { transform: function(datas) { if (!datas.length || datas[0].length < 4) { return datas; } //// store: new Ext.data.ArrayStore({ fields: ['value', 'text', 'enabled', 'prefix'] }) //// Sample data: ...
var tempdata = tempdatas[index]; var level = tempdata.level; var prefix = []; for (var i = level; i > 0; i--) { prefix.push(getPrefixInner(tempdatas, tempdata, i)); } return prefix.join(''); }
identifier_body
F.simulateTree.js
 (function() { function getParentIndex(levels, level, index) { if (level > 0) { for (var i = index - 1; i >= 0; i--) { if (levels[i] == level - 1) { return i; } } } return -1; } function hasL...
else { return '<div class="x-elbow-empty"></div>'; } } return ""; } function getPrefix(tempdatas, index) { var tempdata = tempdatas[index]; var level = tempdata.level; var prefix = []; for (var i = level; i > 0; ...
return '<div class="x-elbow-line"></div>'; }
conditional_block
F.simulateTree.js
 (function() { function getParentIndex(levels, level, index) { if (level > 0) { for (var i = index - 1; i >= 0; i--) { if (levels[i] == level - 1) { return i; } } } return -1; } function hasL...
empdatas, tempdata, prefixIndex) { for (var i = 0; i < prefixIndex - 1; i++) { tempdata = tempdatas[tempdata.parentIndex]; } return tempdata; } function getPrefixInner(tempdatas, tempdata, prefixIndex) { // If level = 3, then prefixIndex array will be: [3, 2,...
tParentTempData(t
identifier_name
mod.rs
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"))] use Api; use BuilderAttribs; use ContextError; use CreationError; use GlContext; use PixelFormat; use libc; use api::osmesa::{self, OsMesaContext}; #[cfg(feature = "window")] pub use self::api_dispatch::{Window, WindowProxy, MonitorID,...
(OsMesaContext); impl HeadlessContext { pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { match OsMesaContext::new(builder) { Ok(c) => return Ok(HeadlessContext(c)), Err(osmesa::OsMesaCreationError::NotSupported) => (), Err(osmesa::OsMesaCre...
HeadlessContext
identifier_name
mod.rs
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"))] use Api; use BuilderAttribs; use ContextError; use CreationError; use GlContext; use PixelFormat; use libc; use api::osmesa::{self, OsMesaContext}; #[cfg(feature = "window")] pub use self::api_dispatch::{Window, WindowProxy, MonitorID,...
fn get_api(&self) -> Api { self.0.get_api() } #[inline] fn get_pixel_format(&self) -> PixelFormat { self.0.get_pixel_format() } }
#[inline]
random_line_split
strx.rs
pub fn remove_to<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_from(pos + 1), None => s } } #[allow(dead_code)] pub fn remove_from_last<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_to(pos), None => s, } } ...
use super::remove_to; use super::remove_from_last; use super::remove_prefix; use super::remove_suffix; #[test] fn test_remove_to() { assert_eq!("aaa", remove_to("aaa", '.')); assert_eq!("bbb", remove_to("aaa.bbb", '.')); assert_eq!("ccc", remove_to("aaa.bbb.ccc", '.')); ...
random_line_split
strx.rs
pub fn remove_to<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_from(pos + 1), None => s } } #[allow(dead_code)] pub fn remove_from_last<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_to(pos), None => s, } } ...
#[test] fn test_remove_prefix() { assert_eq!("aaa", remove_prefix("bbbaaa", "bbb")); } #[test] #[should_fail] fn test_remove_prefix_fail() { remove_prefix("aaa", "bbb"); } #[test] fn test_remove_suffix() { assert_eq!("bbb", remove_suffix("bbbaaa", "aaa"));...
{ assert_eq!("aaa", remove_from_last("aaa", '.')); assert_eq!("aaa", remove_from_last("aaa.bbb", '.')); assert_eq!("aaa.bbb", remove_from_last("aaa.bbb.ccc", '.')); }
identifier_body
strx.rs
pub fn remove_to<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_from(pos + 1), None => s } } #[allow(dead_code)] pub fn remove_from_last<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_to(pos), None => s, } } ...
<'s>(s: &'s str, prefix: &str) -> &'s str { if !s.starts_with(prefix) { panic!(); } s.slice_from(prefix.len()) } #[cfg(test)] mod test { use super::remove_to; use super::remove_from_last; use super::remove_prefix; use super::remove_suffix; #[test] fn test_remove_to() { ...
remove_prefix
identifier_name
strx.rs
pub fn remove_to<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_from(pos + 1), None => s } } #[allow(dead_code)] pub fn remove_from_last<'s>(s: &'s str, c: char) -> &'s str { match s.rfind(c) { Some(pos) => s.slice_to(pos), None => s, } } ...
s.slice_to(s.len() - suffix.len()) } pub fn remove_prefix<'s>(s: &'s str, prefix: &str) -> &'s str { if !s.starts_with(prefix) { panic!(); } s.slice_from(prefix.len()) } #[cfg(test)] mod test { use super::remove_to; use super::remove_from_last; use super::remove_prefix; use s...
{ panic!(); }
conditional_block
align_faces.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Philipp Wagner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must...
nx,ny = x,y = center sx=sy=1.0 if new_center: (nx,ny) = new_center if scale: (sx,sy) = (scale, scale) cosine = math.cos(angle) sine = math.sin(angle) a = cosine/sx b = sine/sx c = x-nx*a-ny*b d = -sine/sy e = cosine/sy f = y-nx*d-ny*e return image.transform(image.size, Image.AFFINE, (...
return image.rotate(angle=angle, resample=resample)
conditional_block
align_faces.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Philipp Wagner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must...
(p1,p2): dx = p2[0] - p1[0] dy = p2[1] - p1[1] return math.sqrt(dx*dx+dy*dy) def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None, resample=Image.BICUBIC): if (scale is None) and (center is None): return image.rotate(angle=angle, resample=resample) nx,ny = x,y = center ...
Distance
identifier_name
align_faces.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Philipp Wagner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must...
return image if __name__ == "__main__": f = open(sys.argv[1], 'r') csv = open(sys.argv[2], "w") for line in f: lineArray = line.split(";") fileName = lineArray[0] label = lineArray[1] print "aligning %s to aligned" % (fileName) aligned_file_name = "aligned/%s" % fileName face = f...
offset_h = math.floor(float(offset_pct[0])*dest_sz[0]) offset_v = math.floor(float(offset_pct[1])*dest_sz[1]) # get the direction eye_direction = (eye_right[0] - eye_left[0], eye_right[1] - eye_left[1]) # calc rotation angle in radians rotation = -math.atan2(float(eye_direction[1]),float(eye_direction[0])) ...
identifier_body
align_faces.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Philipp Wagner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must...
dy = p2[1] - p1[1] return math.sqrt(dx*dx+dy*dy) def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None, resample=Image.BICUBIC): if (scale is None) and (center is None): return image.rotate(angle=angle, resample=resample) nx,ny = x,y = center sx=sy=1.0 if new_center: ...
def Distance(p1,p2): dx = p2[0] - p1[0]
random_line_split
example_02.py
#! /usr/bin/env python #/* # * example_02.c: sample gnome-print code # * # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU Library General Public License # * as published by the Free Software Foundation; either version 2 of # * the License, or (at your optio...
def my_print_image_from_memory(gpc): pixels = NUMBER_OF_PIXELS; # Create the image in memory color_image = [] for y in xrange(pixels): for x in xrange(pixels): color_image.append(struct.pack("BBB", (x + y) >> 1, (x + (pixels - 1 - y)) >> 1, ((pixels - 1 - x) + y) >> 1...
pixbuf = gtk.gdk.pixbuf_new_from_file("sample-image.png") # Save the graphic context, scale, print the image and restore gpc.gsave() gpc.scale(144, 144) my_print_image_from_pixbuf(gpc, pixbuf) gpc.grestore()
identifier_body
example_02.py
#! /usr/bin/env python #/* # * example_02.c: sample gnome-print code # * # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU Library General Public License # * as published by the Free Software Foundation; either version 2 of # * the License, or (at your optio...
gpc.translate(0, 150) my_print_image_from_disk(gpc) gpc.showpage() def my_print(): job = gnomeprint.Job(gnomeprint.config_default()) gpc = job.get_context() my_draw(gpc) job.close() job.print_() my_print() print "Done..."
my_print_image_from_memory(gpc)
random_line_split
example_02.py
#! /usr/bin/env python #/* # * example_02.c: sample gnome-print code # * # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU Library General Public License # * as published by the Free Software Foundation; either version 2 of # * the License, or (at your optio...
(): job = gnomeprint.Job(gnomeprint.config_default()) gpc = job.get_context() my_draw(gpc) job.close() job.print_() my_print() print "Done..."
my_print
identifier_name
example_02.py
#! /usr/bin/env python #/* # * example_02.c: sample gnome-print code # * # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU Library General Public License # * as published by the Free Software Foundation; either version 2 of # * the License, or (at your optio...
# All images in postscript are printed on a 1 x 1 square, since we # want an image which has a size of 2" by 2" inches, we have to scale # the CTM (Current Transformation Matrix). Save the graphic state and # restore it after we are done so that our scaling does not affect the # drawing calls that ...
for x in xrange(pixels): color_image.append(struct.pack("BBB", (x + y) >> 1, (x + (pixels - 1 - y)) >> 1, ((pixels - 1 - x) + y) >> 1))
conditional_block
typeref.rs
/* automatically generated by rust-bindgen */ #![allow(non_snake_case)] #[repr(C)] pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>); impl <T> __BindgenUnionField<T> { #[inline] pub fn new() -> Self { __BindgenUnionField(::std::marker::PhantomData) } #[inline] pub unsafe fn as_ref(&se...
#[derive(Debug, Copy)] pub struct Position { pub _address: u8, } #[test] fn bindgen_test_layout_Position() { assert_eq!(::std::mem::size_of::<Position>() , 1usize); assert_eq!(::std::mem::align_of::<Position>() , 1usize); } impl Clone for Position { fn clone(&self) -> Self { *self } } #[repr(C)] #[deriv...
fn clone(&self) -> Self { *self } } #[repr(C)]
random_line_split
typeref.rs
/* automatically generated by rust-bindgen */ #![allow(non_snake_case)] #[repr(C)] pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>); impl <T> __BindgenUnionField<T> { #[inline] pub fn new() -> Self { __BindgenUnionField(::std::marker::PhantomData) } #[inline] pub unsafe fn as_ref(&se...
() { assert_eq!(::std::mem::size_of::<Position>() , 1usize); assert_eq!(::std::mem::align_of::<Position>() , 1usize); } impl Clone for Position { fn clone(&self) -> Self { *self } } #[repr(C)] #[derive(Debug, Copy)] pub struct Bar { pub mFoo: *mut nsFoo, } #[test] fn bindgen_test_layout_Bar() { asse...
bindgen_test_layout_Position
identifier_name
archive.py
import os import six from aleph.util import checksum class Archive(object): def _get_file_path(self, meta): ch = meta.content_hash if ch is None: raise ValueError("No content hash available.") path = os.path.join(ch[:2], ch[2:4], ch[4:6], ch) file_name = 'data' ...
def upgrade(self): """Run maintenance on the store.""" pass def archive_file(self, filename, meta, move=False): """Import the given file into the archive. Return an updated metadata object. If ``move`` is given, the original file will not exist afterwards. """...
meta.content_hash = checksum(filename) return meta
identifier_body
archive.py
import os import six from aleph.util import checksum class Archive(object): def _get_file_path(self, meta): ch = meta.content_hash if ch is None: raise ValueError("No content hash available.") path = os.path.join(ch[:2], ch[2:4], ch[4:6], ch) file_name = 'data' ...
return os.path.join(six.text_type(path), six.text_type(file_name)) def _update_metadata(self, filename, meta): meta.content_hash = checksum(filename) return meta def upgrade(self): """Run maintenance on the store.""" pass def archive_file(self, filename, meta, mov...
if meta.extension is not None: file_name = '%s.%s' % (file_name, meta.extension)
conditional_block
archive.py
import os import six from aleph.util import checksum class Archive(object): def _get_file_path(self, meta): ch = meta.content_hash if ch is None: raise ValueError("No content hash available.") path = os.path.join(ch[:2], ch[2:4], ch[4:6], ch) file_name = 'data' ...
meta.content_hash = checksum(filename) return meta def upgrade(self): """Run maintenance on the store.""" pass def archive_file(self, filename, meta, move=False): """Import the given file into the archive. Return an updated metadata object. If ``move`` is given...
def _update_metadata(self, filename, meta):
random_line_split
archive.py
import os import six from aleph.util import checksum class Archive(object): def
(self, meta): ch = meta.content_hash if ch is None: raise ValueError("No content hash available.") path = os.path.join(ch[:2], ch[2:4], ch[4:6], ch) file_name = 'data' if meta.file_name is not None: file_name = meta.file_name else: if m...
_get_file_path
identifier_name
base.py
# Create a new Part object to associate to the message object. # (You can't just set block.message, because if block is an # attachment on an existing message, that would dissociate it from # the existing message.) part = Part(block=block) part.content_id = block.public_id if is_inline else Non...
_set_reply_headers
identifier_name
base.py
self).__init__( message, http_code, server_error, failures) def get_sendmail_client(account): from inbox.sendmail import module_registry sendmail_mod = module_registry.get(account.provider) sendmail_cls = getattr(sendmail_mod, sendmail_mod.SENDMAIL_CLS) sendmail_client = sendmail_cls(acc...
else: # If this isn't a reply to anything, create a new thread object for # the draft. We specialize the thread class so that we can, for # example, add the g_thrid for Gmail later if we reconcile a synced # message with this one. This is a huge hack, but works....
message.is_reply = True thread = reply_to_thread # Construct the in-reply-to and references headers from the last # message currently in the thread. previous_messages = [m for m in thread.messages if not m.is_draft] if previous_messages: last_m...
conditional_block
base.py
def get_sendmail_client(account): from inbox.sendmail import module_registry sendmail_mod = module_registry.get(account.provider) sendmail_cls = getattr(sendmail_mod, sendmail_mod.SENDMAIL_CLS) sendmail_client = sendmail_cls(account) return sendmail_client def create_draft_from_mime(account, r...
self.message = message self.http_code = http_code self.server_error = server_error self.failures = failures super(SendMailException, self).__init__( message, http_code, server_error, failures)
identifier_body
base.py
one item") if msg.reply_to and len(msg.reply_to) > 1: raise InputError("reply_to field can have at most one item") if msg.subject is not None and not \ isinstance(msg.subject, basestring): raise InputError('"subject" should be a string') if not isinstan...
db_session.commit() return draft
random_line_split
wrappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
(Blueprint): """A Blueprint implementation that allows prefixing URLs with `!` to ignore the url_prefix of the blueprint. It also supports automatically creating rules in two versions - with and without a prefix. :param event_feature: If set, this blueprint will raise `NotFound` ...
IndicoBlueprint
identifier_name
wrappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): from indico.web.rh import RHSimple # Endpoints from Flask-Multipass need to be wrapped in the RH # logic to get the autocommit logic and error handling for code # running inside the identity handler. if...
json_encoder = IndicoJSONEncoder request_class = IndicoRequest session_interface = IndicoSessionInterface() test_client_class = IndicoFlaskClient jinja_environment = IndicoEnvironment jinja_options = dict(Flask.jinja_options, undefined=StrictUndefined) @property def session_cookie_name(self...
identifier_body
wrappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
return templates def get_source(self, environment, template): if self.virtual_path: if not template.startswith(self.virtual_path): raise TemplateNotFound(template) template = template[len(self.virtual_path):] return super().get_source(environment, te...
templates = [os.path.join(self.virtual_path, t) for t in templates]
conditional_block
wrappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
customization_dir = os.path.join(config.CUSTOMIZATION_DIR, 'templates') if config.CUSTOMIZATION_DIR else [] return CustomizationLoader(default_loader, customization_dir, config.CUSTOMIZATION_DEBUG) def add_url_rule(self, rule, endpoint=None, view_func=None, **options): from indico.web.rh im...
# use an empty list if there's no global customization dir so we can # add directories of plugins later once they are available
random_line_split
actiongroup.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) a...
action = self.get_action(action_tuple[0]) action.set_icon_name(action_tuple[1])
conditional_block
actiongroup.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) a...
(self, action_list, **kwargs): Gtk.ActionGroup.add_toggle_actions(self, action_list, **kwargs) self.fix_icon_name(action_list) def add_radio_actions(self, action_list, **kwargs): Gtk.ActionGroup.add_radio_actions(self, action_list, **kwargs) self.fix_icon_name(action_list) def ...
add_toggle_actions
identifier_name
actiongroup.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) a...
def add_toggle_actions(self, action_list, **kwargs): Gtk.ActionGroup.add_toggle_actions(self, action_list, **kwargs) self.fix_icon_name(action_list) def add_radio_actions(self, action_list, **kwargs): Gtk.ActionGroup.add_radio_actions(self, action_list, **kwargs) self.fix_icon...
Gtk.ActionGroup.add_actions(self, action_list, **kwargs) self.fix_icon_name(action_list)
identifier_body
actiongroup.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015 Nick Hall #
# (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of...
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or
random_line_split
measure_control.py
# -*- coding: utf-8 -*- from branca.element import MacroElement from folium.elements import JSCSSMixin from folium.utilities import parse_options from jinja2 import Template class MeasureControl(JSCSSMixin, MacroElement): """ Add a measurement widget on the map. Parameters ---------- position: str...
{% endmacro %} """) # noqa default_js = [ ('leaflet_measure_js', 'https://cdn.jsdelivr.net/gh/ljagis/leaflet-measure@2.1.7/dist/leaflet-measure.min.js') ] default_css = [ ('leaflet_measure_css', 'https://cdn.jsdelivr.net/gh/ljagis/leaflet-measure@2.1.7/d...
random_line_split
measure_control.py
# -*- coding: utf-8 -*- from branca.element import MacroElement from folium.elements import JSCSSMixin from folium.utilities import parse_options from jinja2 import Template class MeasureControl(JSCSSMixin, MacroElement): """ Add a measurement widget on the map. Parameters ---------- position: str...
(self, position='topright', primary_length_unit='meters', secondary_length_unit='miles', primary_area_unit='sqmeters', secondary_area_unit='acres', **kwargs): super(MeasureControl, self).__init__() self._name = 'MeasureControl' self.options = parse_options( ...
__init__
identifier_name
measure_control.py
# -*- coding: utf-8 -*- from branca.element import MacroElement from folium.elements import JSCSSMixin from folium.utilities import parse_options from jinja2 import Template class MeasureControl(JSCSSMixin, MacroElement): """ Add a measurement widget on the map. Parameters ---------- position: str...
super(MeasureControl, self).__init__() self._name = 'MeasureControl' self.options = parse_options( position=position, primary_length_unit=primary_length_unit, secondary_length_unit=secondary_length_unit, primary_area_unit=primary_area_unit, se...
identifier_body
user.service.ts
import { Injectable } from '@angular/core'; import { Http,Response,Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Observable'; import { GLOBAL } from './global'; @Injectable() export class UserService{ public identity; public token; public url: string; construc...
updateUser(user_to_update){ let params = JSON.stringify(user_to_update); let headers = new Headers({ 'Content-Type':'application/json', 'Authorization': this.getToken() }); return this._http.put(this.url+'update-user/'+user_to_update._id, params,{headers: headers}) ...
{ let params = JSON.stringify(user_to_register); let headers = new Headers({'Content-Type':'application/json'}); return this._http.post(this.url+'register', params,{headers: headers}) .map(res => res.json()); }
identifier_body
user.service.ts
import { Injectable } from '@angular/core'; import { Http,Response,Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Observable'; import { GLOBAL } from './global'; @Injectable() export class UserService{ public identity; public token; public url: string; construc...
(){ let identity = JSON.parse(localStorage.getItem('identity')); if(identity != "undefined"){ this.identity = identity; }else{ this.identity = null; } return this.identity; } getToken(){ let token = localStorage.getItem('token'); if(token != "undefined"){ this.token ...
getIdentity
identifier_name
user.service.ts
import { Injectable } from '@angular/core'; import { Http,Response,Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Observable'; import { GLOBAL } from './global'; @Injectable() export class UserService{ public identity; public token; public url: string; construc...
return this.identity; } getToken(){ let token = localStorage.getItem('token'); if(token != "undefined"){ this.token = token; }else{ this.token = null; } return this.token; } }
{ this.identity = null; }
conditional_block
user.service.ts
import { Injectable } from '@angular/core'; import { Http,Response,Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Observable'; import { GLOBAL } from './global'; @Injectable() export class UserService{ public identity; public token; public url: string; construc...
this.token = token; }else{ this.token = null; } return this.token; } }
getToken(){ let token = localStorage.getItem('token'); if(token != "undefined"){
random_line_split
script_msg.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 canvas_traits::CanvasMsg; use euclid::point::Point2D; use euclid::size::Size2D; use ipc_channel::ipc::IpcSende...
{ /// Indicates whether this pipeline is currently running animations. ChangeRunningAnimationsState(PipelineId, AnimationState), /// Layout task failure. Failure(Failure), /// Requests that the constellation inform the compositor of the a cursor change. SetCursor(Cursor), /// Notifies the c...
LayoutMsg
identifier_name
script_msg.rs
use canvas_traits::CanvasMsg; use euclid::point::Point2D; use euclid::size::Size2D; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::{AnimationState, DocumentState, IframeLoadInfo, NavigationDirection}; use msg::constellation_msg::{Failure, MozBrowserEvent, PipelineId}; use msg::constellation_msg::{LoadData...
/* 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/. */
random_line_split
multiselectdemo.ts
import {Component} from '@angular/core'; import {SelectItem} from '../../../components/common/api'; @Component({ templateUrl: './multiselectdemo.html' }) export class
{ cars: SelectItem[]; selectedCars: string[] = []; constructor() { this.cars = []; this.cars.push({label: 'Audi', value: 'Audi'}); this.cars.push({label: 'BMW', value: 'BMW'}); this.cars.push({label: 'Fiat', value: 'Fiat'}); this.cars.push({label: 'Ford', value: '...
MultiSelectDemo
identifier_name
multiselectdemo.ts
import {Component} from '@angular/core'; import {SelectItem} from '../../../components/common/api'; @Component({ templateUrl: './multiselectdemo.html' }) export class MultiSelectDemo { cars: SelectItem[]; selectedCars: string[] = []; constructor() { this.cars = [];
this.cars.push({label: 'Audi', value: 'Audi'}); this.cars.push({label: 'BMW', value: 'BMW'}); this.cars.push({label: 'Fiat', value: 'Fiat'}); this.cars.push({label: 'Ford', value: 'Ford'}); this.cars.push({label: 'Honda', value: 'Honda'}); this.cars.push({label: 'Jaguar',...
random_line_split
settings.py
import os import sys from flask import render_template # load a bunch of environment DEBUG = os.getenv('DEBUG') in ['True', 'true', '1', 'yes'] if DEBUG:
TESTING = os.getenv('TESTING') in ['True', 'true', '1', 'yes'] SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI') or os.getenv('DATABASE_URL') SQLALCHEMY_TRACK_MODIFICATIONS = False LOG_LEVEL = os.getenv('LOG_LEVEL') or 'debug' SECRET_KEY = os.getenv('SECRET_KEY') or '' HASHIDS_SALT = os.getenv('HASHIDS...
SQLALCHEMY_ECHO = True
conditional_block
settings.py
import os import sys from flask import render_template # load a bunch of environment DEBUG = os.getenv('DEBUG') in ['True', 'true', '1', 'yes'] if DEBUG: SQLALCHEMY_ECHO = True TESTING = os.getenv('TESTING') in ['True', 'true', '1', 'yes'] SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI') or os.gete...
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY') or STRIPE_TEST_SECRET_KEY STRIPE_WEBHOOK_SECRET = os.getenv('STRIPE_WEBHOOK_SECRET') GA_KEY = os.getenv('GA_KEY') or '123456' RECAPTCHA_SECRET = os.getenv('RECAPTCHA_SECRET') RECAPTCHA_KEY = os.getenv('RECAPTCHA_KEY') RATE_LIMIT = os.getenv('RATE_LIMIT', '30 per hou...
random_line_split
dummy.py
ÆÄÀÏ »èÁ¦¸¦ À§ÇØ import import kernel #--------------------------------------------------------------------- # KavMain Ŭ·¡½º # ŰÄÞ¹é½Å ¿£Áø ¸ðµâÀÓÀ» ³ªÅ¸³»´Â Ŭ·¡½ºÀÌ´Ù. # ÀÌ Å¬·¡½º°¡ ¾øÀ¸¸é ¹é½Å ¿£Áø Ä¿³Î ¸ðµâ¿¡¼­ ·ÎµùÇÏÁö ¾Ê´Â´Ù. #--------------------------------------------------------------------- class KavMain...
---------- # scan(self, filehandle, filename) # ¾Ç¼ºÄڵ带 °Ë»çÇÑ´Ù. # ÀÎÀÚ°ª : mmhandle - ÆÄÀÏ mmap ÇÚµé # : scan_file_struct - ÆÄÀÏ ±¸Á¶Ã¼ # : format - ¹Ì¸® ºÐ¼®µÈ ÆÄÀÏ Æ÷¸Ë # ¸®Åϰª : (¾Ç¼ºÄÚµå ¹ß°ß ¿©ºÎ, ¾Ç¼ºÄÚµå À̸§, ¾Ç¼ºÄÚµå ID) µîµî #------------------...
------
identifier_name
dummy.py
ÆÄÀÏ »èÁ¦¸¦ À§ÇØ import import kernel #--------------------------------------------------------------------- # KavMain Ŭ·¡½º # ŰÄÞ¹é½Å ¿£Áø ¸ðµâÀÓÀ» ³ªÅ¸³»´Â Ŭ·¡½ºÀÌ´Ù. # ÀÌ Å¬·¡½º°¡ ¾øÀ¸¸é ¹é½Å ¿£Áø Ä¿³Î ¸ðµâ¿¡¼­ ·ÎµùÇÏÁö ¾Ê´Â´Ù. #--------------------------------------------------------------------- class KavMain...
¯½º ¹ß°ß ¿©ºÎ ret_value['virus_name'] = self.virus_name # ¹ÙÀÌ·¯½º À̸§ ret_value['scan_state'] = kernel.INFECTED# 0:¾øÀ½, 1:°¨¿°, 2:ÀǽÉ, 3:°æ°í ret_value['virus_id'] = 0 # ¹ÙÀÌ·¯½º ID return ret_value except : pass ...
# ¹ÙÀÌ·
conditional_block
dummy.py
³ªÅ¸³»´Â Ŭ·¡½ºÀÌ´Ù. # ÀÌ Å¬·¡½º°¡ ¾øÀ¸¸é ¹é½Å ¿£Áø Ä¿³Î ¸ðµâ¿¡¼­ ·ÎµùÇÏÁö ¾Ê´Â´Ù. #--------------------------------------------------------------------- class KavMain : #----------------------------------------------------------------- # init(self, plugins) # ¹é½Å ¿£Áø ¸ðµâÀÇ ÃʱâÈ­ ÀÛ¾÷À» ¼öÇàÇÑ´Ù. #...
identifier_body
dummy.py
ÆÄÀÏ »èÁ¦¸¦ À§ÇØ import import kernel #--------------------------------------------------------------------- # KavMain Ŭ·¡½º # ŰÄÞ¹é½Å ¿£Áø ¸ðµâÀÓÀ» ³ªÅ¸³»´Â Ŭ·¡½ºÀÌ´Ù. # ÀÌ Å¬·¡½º°¡ ¾øÀ¸¸é ¹é½Å ¿£Áø Ä¿³Î ¸ðµâ¿¡¼­ ·ÎµùÇÏÁö ¾Ê´Â´Ù. #--------------------------------------------------------------------- class KavMain...
# ¾Ç¼ºÄÚµå ÆÐÅÏÀÌ °®´Ù¸é °á°ú °ªÀ» ¸®ÅÏÇÑ´Ù. ret_value['result'] = True # ¹ÙÀÌ·¯½º ¹ß°ß ¿©ºÎ ret_value['virus_name'] = self.virus_name # ¹ÙÀÌ·¯½º À̸§ ret_value['scan_state'] = kernel.INFECTED# 0:¾øÀ½, 1:°¨¿°, 2:ÀǽÉ, 3:°æ°í ...
# ¾Ç¼ºÄÚµå ÆÐÅÏÀ» ºñ±³ÇÑ´Ù. if buf == self.dummy_pattern :
random_line_split
estados.schema.ts
import { AuditPlugin } from '@andes/mongoose-plugin-audit'; import { Document, model, Model, Schema, SchemaTypes, Types } from 'mongoose'; import { SnomedConcept } from '../schemas/snomed-concept'; const EstadoKey = String; type IEstadoKey = String; export interface IEstados { organizacion: Types.ObjectId; am...
} return false; }; EstadoSchema.plugin(AuditPlugin); export const Estados: Model<IEstadosDocument> = model('internacionEstados', EstadoSchema, 'internacionEstados');
{ return true; }
conditional_block
estados.schema.ts
import { AuditPlugin } from '@andes/mongoose-plugin-audit'; import { Document, model, Model, Schema, SchemaTypes, Types } from 'mongoose'; import { SnomedConcept } from '../schemas/snomed-concept'; const EstadoKey = String; type IEstadoKey = String; export interface IEstados { organizacion: Types.ObjectId; am...
secciones: [{ concepto: SnomedConcept, color: String, icono: String, registro: SnomedConcept }] } } }); EstadoSchema.methods.check = function (origen, destino) { if (origen === destino) { return true; } ...
tipoPrestacion: SnomedConcept,
random_line_split
coherence_inherent.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 ...
mod Lib { pub trait TheTrait { fn the_fn(&self); } pub struct TheStruct; impl TheTrait for TheStruct { fn the_fn(&self) {} } } mod Import { // Trait is in scope here: use Lib::TheStruct; use Lib::TheTrait; fn call_the_fn(s: &TheStruct) { s.the_fn(); } ...
// unless the trait is imported.
random_line_split
coherence_inherent.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 ...
(s: &TheStruct) { s.the_fn(); //~ ERROR no method named `the_fn` found } } fn main() {}
call_the_fn
identifier_name
coherence_inherent.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 ...
} mod NoImport { // Trait is not in scope here: use Lib::TheStruct; fn call_the_fn(s: &TheStruct) { s.the_fn(); //~ ERROR no method named `the_fn` found } } fn main() {}
{ s.the_fn(); }
identifier_body
lib.rs
ipc_channel; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate msg; #[macro_use] extern crate serde; extern crate servo_url; extern crate time; use hyper::header::Headers; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use s...
pub name: String, pub start_time: PreciseTime, pub start_stack: Option<Vec<()>>, pub end_time: PreciseTime, pub end_stack: Option<Vec<()>>, } #[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)] pub enum TimelineMarkerType { Reflow, DOMEvent, } /// The propert...
start_stack: Option<Vec<()>>, } #[derive(Debug, Deserialize, Serialize)] pub struct TimelineMarker {
random_line_split
lib.rs
ipc_channel; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate msg; #[macro_use] extern crate serde; extern crate servo_url; extern crate time; use hyper::header::Headers; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use s...
{ HttpRequest(HttpRequest), HttpResponse(HttpResponse),
NetworkEvent
identifier_name
mnist_cnn.py
import theano import numpy as np from sklearn.preprocessing import OneHotEncoder from sklearn import cross_validation, metrics, datasets from neupy import algorithms, layers, environment environment.reproducible() theano.config.floatX = 'float32' mnist = datasets.fetch_mldata('MNIST original') target_scaler = OneHo...
) network.architecture() network.train(x_train, y_train, x_test, y_test, epochs=6) y_predicted = network.predict(x_test) y_test_labels = np.asarray(y_test.argmax(axis=1)).reshape(len(y_test)) print(metrics.classification_report(y_test_labels, y_predicted)) score = metrics.accuracy_score(y_test_labels, y_predicted) pr...
epochs_step_minimizator=8, addons=[algorithms.SimpleStepMinimization],
random_line_split
addShape.js
function addShape(name, shape, color, x, y, z, rx, ry, rz, s)
var geometry = shape.createPointsGeometry(); var material = new THREE.LineBasicMaterial({ linewidth: 10, color: 0x333333, transparent: true }); var line = new THREE.Line(geometry, material); line.position.set(x, y, z); line.rotation.set(rx, ry, rz); l...
{ var ROOT = this; ROOT.group = new THREE.Group(); var geometry = new THREE.ShapeGeometry(shape); var material = new THREE.MeshBasicMaterial({ color: color, overdraw: 0.5 }); ROOT.mesh = new THREE.Mesh(geometry, material); ROOT.mesh.position.set(x, y, z); ...
identifier_body
addShape.js
function
(name, shape, color, x, y, z, rx, ry, rz, s) { var ROOT = this; ROOT.group = new THREE.Group(); var geometry = new THREE.ShapeGeometry(shape); var material = new THREE.MeshBasicMaterial({ color: color, overdraw: 0.5 }); ROOT.mesh = new THREE.Mesh(geometry, materia...
addShape
identifier_name
addShape.js
function addShape(name, shape, color, x, y, z, rx, ry, rz, s) { var ROOT = this; ROOT.group = new THREE.Group(); var geometry = new THREE.ShapeGeometry(shape); var material = new THREE.MeshBasicMaterial({ color: color, overdraw: 0.5 });
ROOT.mesh.scale.set(s, s, s); ROOT.group.add(ROOT.mesh); // line var geometry = shape.createPointsGeometry(); var material = new THREE.LineBasicMaterial({ linewidth: 10, color: 0x333333, transparent: true }); var line = new THREE.Line(geometry, mate...
ROOT.mesh = new THREE.Mesh(geometry, material); ROOT.mesh.position.set(x, y, z); ROOT.mesh.rotation.set(rx, ry, rz);
random_line_split
dppcm_specification.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE all_variables = [] specification = {} specification = { #"_definition_": all_variables, -2:{ "equation_ids":(1, 2), # 1:accepted; 2:una...
#"plogsum2=person.disaggregate(psrc.zone.trip_weighted_average_logsum_hbw_am_income_2, intermediates=[household])":(0, "beta2_logsum2"), #"plogsum3=person.disaggregate(psrc.zone.trip_weighted_average_logsum_hbw_am_income_3, intermediates=[household])":(0, "beta2_logsum3"), #"pl...
#"kemp30m=person.disaggregate(urbansim_parcel.zone.employment_within_30_minutes_travel_time_hbw_am_drive_alone, intermediates=[household])/1000":(0, "beta2_kemp30m"), #"hlogsum=person.disaggregate(psrc_parcel.household.trip_weighted_average_logsum_hbw_am_from_residence)":(0, "beta2_hlogsum"), ...
random_line_split
angular-locale_dua-cm.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "idi\u0253a", "eby\u...
{ n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; }
identifier_body
angular-locale_dua-cm.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
"CURRENCY_SYM": "FCFA", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { ...
}, "NUMBER_FORMATS": {
random_line_split
angular-locale_dua-cm.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
return PLURAL_CATEGORY.OTHER;} }); }]);
{ return PLURAL_CATEGORY.ONE; }
conditional_block
angular-locale_dua-cm.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide....
getDecimals
identifier_name
__init__.py
import logging from contextlib import contextmanager from ..errors import CompilerError from .state import State from .core import Context, Object, BoundObject, SoftScope, Scope, Type from .module import Module from .closure import Closure, ClosedLink, ClosedTarget from .function import Function, FunctionType, Functi...
backend_builtins = backend.builtins(logger) builtins = State.builtins.context["_builtins"] with forward.target([(builtins, backend_builtins)], False): yield
identifier_body
__init__.py
import logging from contextlib import contextmanager from ..errors import CompilerError from .state import State from .core import Context, Object, BoundObject, SoftScope, Scope, Type from .module import Module from .closure import Closure, ClosedLink, ClosedTarget from .function import Function, FunctionType, Functi...
(source, frontend, backend, logger = logging.getLogger(), opt_level = 0): module = _verify(source, frontend, logger) logger.info("Running") return backend.run(module) def verify(module:Module, logger = logging.getLogger()): # Set up the initial state before verifying State.init(logger.getChild("le...
run
identifier_name
__init__.py
import logging from contextlib import contextmanager from ..errors import CompilerError from .state import State from .core import Context, Object, BoundObject, SoftScope, Scope, Type from .module import Module from .closure import Closure, ClosedLink, ClosedTarget from .function import Function, FunctionType, Functi...
except CompilerError as e: e.format() raise e @contextmanager def use(frontend, backend, logger = logging.getLogger()): with useFrontend(frontend, logger), useBackend(backend, logger): yield @contextmanager def useFrontend(frontend, logger = logging.getLogger()): builtins = fronten...
random_line_split
build_tfidf.py
import pandas as pd import numpy as np import re from gensim import corpora, models, similarities from gensim.parsing.preprocessing import STOPWORDS def
(text): ''' Split the input text into words/tokens; ignoring stopwords and empty strings ''' delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t" regexPattern = '|'.join(map(re.escape, delimiters)) return [word for word in re.split(regexPattern, text.lower()) if word not in STOPWORDS and word != ""] d...
split
identifier_name
build_tfidf.py
import pandas as pd import numpy as np import re from gensim import corpora, models, similarities from gensim.parsing.preprocessing import STOPWORDS def split(text): ''' Split the input text into words/tokens; ignoring stopwords and empty strings ''' delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t" ...
main()
conditional_block
build_tfidf.py
import pandas as pd import numpy as np import re from gensim import corpora, models, similarities from gensim.parsing.preprocessing import STOPWORDS def split(text): '''
return [word for word in re.split(regexPattern, text.lower()) if word not in STOPWORDS and word != ""] def main(): # Load data df_train = pd.read_csv('data/train.csv', encoding="ISO-8859-1") df_desc = pd.read_csv('data/product_descriptions.csv', encoding="ISO-8859-1") df_attr = pd.read_csv('data/attributes_c...
Split the input text into words/tokens; ignoring stopwords and empty strings ''' delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t" regexPattern = '|'.join(map(re.escape, delimiters))
random_line_split
build_tfidf.py
import pandas as pd import numpy as np import re from gensim import corpora, models, similarities from gensim.parsing.preprocessing import STOPWORDS def split(text): ''' Split the input text into words/tokens; ignoring stopwords and empty strings ''' delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t" ...
dictionary = corpora.Dictionary(texts) dictionary.save('homedepot.dict') print dictionary # actually build a bag-of-words corpus corpus = [dictionary.doc2bow(text) for text in texts] corpora.MmCorpus.serialize('homedepot.mm', corpus) # build Tf-idf model tfidf = models.TfidfModel(corpus) tfidf.save(...
df_train = pd.read_csv('data/train.csv', encoding="ISO-8859-1") df_desc = pd.read_csv('data/product_descriptions.csv', encoding="ISO-8859-1") df_attr = pd.read_csv('data/attributes_combined.csv', encoding="ISO-8859-1") # split the texts titles = [split(line) for line in df_train["product_title"]] descs = [...
identifier_body
updater.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import re import json import tempfile import toml import os class RequirementsTXTUpdater(object): SUB_REGEX = r"^{}(?=\s*\r?\n?$)" @classmethod def update(cls, content, dependency, version, spec="==", hashes...
try: from pipenv.project import Project except ImportError: raise ImportError("Updating a Pipfile requires the pipenv extra to be installed. Install it with " "pip install dparse[pipenv]") pipfile = tempfile.NamedTemporaryFile(delete=False) ...
data[package_type][dependency.full_name] = "{spec}{version}".format( spec=spec, version=version )
conditional_block
updater.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import re import json import tempfile import toml import os class RequirementsTXTUpdater(object): SUB_REGEX = r"^{}(?=\s*\r?\n?$)" @classmethod def update(cls, content, dependency, version, spec="==", hashes...
new_line += " \\" # if this is a hashed requirement, add the hashes if hashes: for n, new_hash in enumerate(hashes): new_line += "\n --hash={method}:{hash}".format( method=new_hash['method'], hash=new_hash['hash'] ...
# if this is a hashed requirement, add a multiline break before the comment if dependency.hashes and not new_line.endswith("\\"):
random_line_split
updater.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import re import json import tempfile import toml import os class RequirementsTXTUpdater(object): SUB_REGEX = r"^{}(?=\s*\r?\n?$)" @classmethod def update(cls, content, dependency, version, spec="==", hashes...
class PipfileLockUpdater(object): @classmethod def update(cls, content, dependency, version, spec="==", hashes=()): data = json.loads(content) if data: for package_type in ['default', 'develop']: if package_type in data: if dependency.full_name ...
data = toml.loads(content) if data: for package_type in ['packages', 'dev-packages']: if package_type in data: if dependency.full_name in data[package_type]: data[package_type][dependency.full_name] = "{spec}{version}".format( ...
identifier_body
updater.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import re import json import tempfile import toml import os class RequirementsTXTUpdater(object): SUB_REGEX = r"^{}(?=\s*\r?\n?$)" @classmethod def update(cls, content, dependency, version, spec="==", hashes...
(CondaYMLUpdater): pass class SetupCFGUpdater(CondaYMLUpdater): pass class PipfileUpdater(object): @classmethod def update(cls, content, dependency, version, spec="==", hashes=()): data = toml.loads(content) if data: for package_type in ['packages', 'dev-packages']: ...
ToxINIUpdater
identifier_name
malemotion.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ) class
(InfoExtractor): _VALID_URL = r'^(?:https?://)?malemotion\.com/video/(.+?)\.(?P<id>.+?)(#|$)' _TEST = { 'url': 'http://malemotion.com/video/bien-dur.10ew', 'file': '10ew.mp4', 'md5': 'b3cc49f953b107e4a363cdff07d100ce', 'info_dict': { "title": "Bien dur", "...
MalemotionIE
identifier_name
malemotion.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ) class MalemotionIE(InfoExtractor):
# Extract video URL video_url = compat_urllib_parse.unquote( self._search_regex(r'<source type="video/mp4" src="(.+?)"', webpage, 'video URL')) # Extract title video_title = self._html_search_regex( r'<title>(.*?)</title', webpage, 'title') # Extract vid...
_VALID_URL = r'^(?:https?://)?malemotion\.com/video/(.+?)\.(?P<id>.+?)(#|$)' _TEST = { 'url': 'http://malemotion.com/video/bien-dur.10ew', 'file': '10ew.mp4', 'md5': 'b3cc49f953b107e4a363cdff07d100ce', 'info_dict': { "title": "Bien dur", "age_limit": 18, ...
identifier_body
malemotion.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ) class MalemotionIE(InfoExtractor): _VALID_URL = r'^(?:https?://)?malemotion\.com/video/(.+?)\.(?P<id>.+?)(#|$)' _TEST = { 'url': 'http://malemotion.com/video/bien-dur.1...
'age_limit': 18, }
'description': None,
random_line_split
uart.rs
/* * MIT License * * Copyright (c) 2018 Andre Richter <andre.o.richter@gmail.com> * * 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 th...
}
{ unsafe { &*self.ptr() } }
identifier_body
uart.rs
/* * MIT License * * Copyright (c) 2018 Andre Richter <andre.o.richter@gmail.com> * * 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 th...
asm::nop(); } // write the character to the buffer self.DR.set(c as u32); } fn wait_cycles(&self, cyc: u32) { for _ in 0..cyc { asm::nop(); } } } impl ops::Deref for Uart { type Target = RegisterBlock; fn deref(&self) -> &Self::Ta...
{ break; }
conditional_block
uart.rs
/* * MIT License * * Copyright (c) 2018 Andre Richter <andre.o.richter@gmail.com> * * 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 th...
/// Returns a pointer to the register block fn ptr(&self) -> *const RegisterBlock { self.base_addr as *const _ } ///Set baud rate and characteristics (115200 8N1) and map to GPIO pub fn init(&self, mbox: &mut mbox::Mbox, gpio: &gpio::GPIO) -> Result<(), &'static str> { // turn off U...
}
random_line_split
uart.rs
/* * MIT License * * Copyright (c) 2018 Andre Richter <andre.o.richter@gmail.com> * * 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 th...
{ DR: ReadWrite<u32>, __reserved_0: [u32; 5], FR: ReadOnly<u32, FR::Register>, __reserved_1: [u32; 2], IBRD: WriteOnly<u32, IBRD::Register>, FBRD: WriteOnly<u32, FBRD::Register>, LCRH: WriteOnly<u32, LCRH::Register>, CR: WriteOnly<u32, CR::Register>, __reserved_2: [u32; 4], ICR:...
RegisterBlock
identifier_name
tachybradycardia.py
:param hr: (ndarray) heart rate- used to determine when bradycardia occurred in ECG trace :param lowerthresh: (int or double) lower threshold for determining bradycardia- user input or default 60 bpm :return: brady: (ndarray) 1 for bradycardia, 0 otherwise """ import numpy as np brady...
def bradycardia(hr, lowerthresh): """ This module determines when in the ECG data there is bradycardia
random_line_split
tachybradycardia.py
def bradycardia(hr, lowerthresh): """ This module determines when in the ECG data there is bradycardia :param hr: (ndarray) heart rate- used to determine when bradycardia occurred in ECG trace :param lowerthresh: (int or double) lower threshold for determining bradycardia- user input or defa...
return brady def tachycardia(hr, upperthresh): """ This module determines when in the ECG data there is tachycardia :param hr: (ndarray) heart rate- used to determine when tachycardia occurred in ECG trace :param upperthresh: (int or double) upper threshold for determining tachycardia...
brady[i] = 1
conditional_block