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
add_poem.py
#!/usr/bin/env python3 """ Copyright 2015 Stefano Benvenuti <ste.benve86@gmail.com> 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 ...
if f is not None: f.close()
random_line_split
add_poem.py
#!/usr/bin/env python3 """ Copyright 2015 Stefano Benvenuti <ste.benve86@gmail.com> 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 ...
if len(sys.argv) is not 2: print(""" USAGE: ./add_poem.py JSON_DELTA_FILE_PATH """) sys.exit(1) conf_file = os.path.join("..","poems","poems.json") # reads old configuration file and new content content = read_file(conf_file) new_content = read_file(sys.argv[1]) # merge the values content.update(new_content) # w...
f = None try: f = open(filename) content = json.load(f) except Exception as e: print("File \"%s\" cannot be opened or read: %s", filename, e) sys.exit(1) finally: if f is not None: f.close() return content
identifier_body
add_poem.py
#!/usr/bin/env python3 """ Copyright 2015 Stefano Benvenuti <ste.benve86@gmail.com> 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 ...
return content if len(sys.argv) is not 2: print(""" USAGE: ./add_poem.py JSON_DELTA_FILE_PATH """) sys.exit(1) conf_file = os.path.join("..","poems","poems.json") # reads old configuration file and new content content = read_file(conf_file) new_content = read_file(sys.argv[1]) # merge the values content.update(...
f.close()
conditional_block
add_poem.py
#!/usr/bin/env python3 """ Copyright 2015 Stefano Benvenuti <ste.benve86@gmail.com> 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 ...
(filename): f = None try: f = open(filename) content = json.load(f) except Exception as e: print("File \"%s\" cannot be opened or read: %s", filename, e) sys.exit(1) finally: if f is not None: f.close() return content if len(sys.argv) is not 2: print(""" USAGE: ./add_poem.py JSON_DELTA_FILE_PATH "...
read_file
identifier_name
theme-loader.js
/** * @file theme loader * * @desc 向每个.vue文件中注入样式相关的变量,不需要手动import * @author echaoo(1299529160@qq.com) */ /* eslint-disable fecs-no-require, fecs-prefer-destructure */ 'use strict'; const theme = require('../../config/theme'); const loaderUtils = require('loader-utils'); const STYLE_TAG_REG = /(\<style.*?lang=...
urce; };
conditional_block
theme-loader.js
/** * @file theme loader * * @desc 向每个.vue文件中注入样式相关的变量,不需要手动import * @author echaoo(1299529160@qq.com) */ /* eslint-disable fecs-no-require, fecs-prefer-destructure */ 'use strict'; const theme = require('../../config/theme'); const loaderUtils = require('loader-utils'); const STYLE_TAG_REG = /(\<style.*?lang=...
error: '$red.accent-2', success: '$green.base' }, materialDesign: { 'bg-color': '#fff', 'fg-color': '#000', 'text-color': '#000', 'primary-text-percent': .87, 'secondary-text-percent': .54, 'disabledORhints-text-percent': .38, 'divider-perc...
warning: '$amber.base',
random_line_split
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct UpdateImage; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw...
let animation = draw.animation.as_str(); let sprite_resource = sprites.get(&unit_type.name); if let Some(sprite) = sprite_resource { let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic...
{
random_line_split
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct
; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw>, ReadStorage<'a, AnimationState>, ReadStorage<'a, UnitType>, WriteStorage<'a, State>, ); fn run( &mut self, (sprite_data, mut draw, animati...
UpdateImage
identifier_name
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct UpdateImage; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw...
} } } }
{ let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic!("{} not found in yaml", animation)); match &animation.order { None => { draw.frame = ...
conditional_block
scenemanager.py
import serial from threading import Thread from menu import Menu from time import sleep import settings as s import pygame from pygame import * ser = serial.Serial('/dev/ttyACM0', 9600, timeout=.025) current_mark = None def worker(): global current_mark while True: read_serial = ser.readline().strip...
def main(): pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() pygame.mixer.quit() pygame.mixer.init(44100, -16, 2, 512) screen = pygame.display.set_mode((s.DISPLAY_WIDTH, s.DISPLAY_HEIGHT), pygame.FULLSCREEN) timer = pygame.time.Clock() running = True manager = SceneMananger() t.start() gl...
self.scene = scene self.scene.manager = self
identifier_body
scenemanager.py
import serial from threading import Thread from menu import Menu from time import sleep import settings as s import pygame from pygame import * ser = serial.Serial('/dev/ttyACM0', 9600, timeout=.025) current_mark = None def worker(): global current_mark while True: read_serial = ser.readline().strip...
: def __init__(self): self.go_to(Menu()) def go_to(self, scene): self.scene = scene self.scene.manager = self def main(): pygame.mixer.pre_init(44100, -16, 2, 512) pygame.init() pygame.mixer.quit() pygame.mixer.init(44100, -16, 2, 512) screen = pygame.display.set_mode((s.DISPLAY_WIDTH, s.DIS...
SceneMananger
identifier_name
scenemanager.py
from threading import Thread from menu import Menu from time import sleep import settings as s import pygame from pygame import * ser = serial.Serial('/dev/ttyACM0', 9600, timeout=.025) current_mark = None def worker(): global current_mark while True: read_serial = ser.readline().strip() if len(re...
import serial
random_line_split
scenemanager.py
import serial from threading import Thread from menu import Menu from time import sleep import settings as s import pygame from pygame import * ser = serial.Serial('/dev/ttyACM0', 9600, timeout=.025) current_mark = None def worker(): global current_mark while True: read_serial = ser.readline().strip...
manager.scene.on_event(pygame.event.get()) manager.scene.render_all() timer.tick(60) if __name__ == "__main__": main()
manager.scene.on_gpio(current_mark) manager.scene.render_all() current_mark = None
conditional_block
chunk_by_time.py
#! /usr/bin/env python """ Script to split a dataset into chunks of equal time """ import argparse from argparse import RawTextHelpFormatter import casacore.tables as pt import numpy as np import sys import os import shutil def main(dataset, blockl, local_dir=None, clobber=True): """ Split dataset into time c...
t.close() nchunks = int(np.ceil((np.float(nsamples) / np.float(blockl)))) # Don't allow more than 15 chunks for performance reasons while nchunks > 15: blockl *= 2 nchunks = int(np.ceil((np.float(nsamples) / np.float(blockl)))) tlen = timepersample * np.float(blockl) / 3600.0 # l...
timepersample = t2[1]['TIME']-t2[0]['TIME'] # sec nsamples = t2.nrows() break
conditional_block
chunk_by_time.py
#! /usr/bin/env python """ Script to split a dataset into chunks of equal time """ import argparse from argparse import RawTextHelpFormatter import casacore.tables as pt import numpy as np import sys import os import shutil def main(dataset, blockl, local_dir=None, clobber=True): """ Split dataset into time c...
if os.path.exists(msout): if clobber: os.system('rm -rf {0}'.format(msout)) else: return msout_original = msout if local_dir is not None: msout = os.path.join(local_dir, os.path.basename(msout_original)) if os.path.exists(msout): os.system...
""" Splits an MS between start and end times in hours relative to first time Parameters ---------- msin : str Name of MS file to split msout : str Name of output MS file start_out : float Start time in hours relative to first time end_out : float End time in ...
identifier_body
chunk_by_time.py
#! /usr/bin/env python """ Script to split a dataset into chunks of equal time """ import argparse from argparse import RawTextHelpFormatter import casacore.tables as pt import numpy as np import sys import os import shutil def
(dataset, blockl, local_dir=None, clobber=True): """ Split dataset into time chunks Parameters ---------- dataset : str Name of MS file to split blockl : int Number of time slots per chunk local_dir : str, optional Path to local directory for output of t1.copy(). The...
main
identifier_name
chunk_by_time.py
#! /usr/bin/env python """ Script to split a dataset into chunks of equal time """ import argparse from argparse import RawTextHelpFormatter import casacore.tables as pt import numpy as np import sys
import shutil def main(dataset, blockl, local_dir=None, clobber=True): """ Split dataset into time chunks Parameters ---------- dataset : str Name of MS file to split blockl : int Number of time slots per chunk local_dir : str, optional Path to local directory for ...
import os
random_line_split
commands.js
'use strict' const thunk = require('thunks')() const tool = require('./tool') const sendCommand = require('./connection').sendCommand // (Disque 0.0.1) `disque command` // `node check-commands.js` const commandsInfo = { ackjob: [-1, ['write', 'fast'], 0, 0, 0], addjob: [-4, ['write', 'denyoom', 'fast'], 0, 0, 0],...
(args) { return Array.isArray(args[0]) ? args[0] : args } function toHash (array) { // disque returned (nil) if (!array) return null let hash = {} for (let i = 0, len = array.length; i < len; i += 2) { hash[array[i]] = array[i + 1] } return hash } function formatInfo (info) { let hash = {} ...
adjustArgs
identifier_name
commands.js
'use strict' const thunk = require('thunks')() const tool = require('./tool') const sendCommand = require('./connection').sendCommand // (Disque 0.0.1) `disque command` // `node check-commands.js` const commandsInfo = { ackjob: [-1, ['write', 'fast'], 0, 0, 0], addjob: [-4, ['write', 'denyoom', 'fast'], 0, 0, 0],...
hash[name] = line.slice(index + 1) }) return hash }
info.toString().split('\r\n').map((line) => { let index = line.indexOf(':') if (index === -1) return let name = line.slice(0, index)
random_line_split
commands.js
'use strict' const thunk = require('thunks')() const tool = require('./tool') const sendCommand = require('./connection').sendCommand // (Disque 0.0.1) `disque command` // `node check-commands.js` const commandsInfo = { ackjob: [-1, ['write', 'fast'], 0, 0, 0], addjob: [-4, ['write', 'denyoom', 'fast'], 0, 0, 0],...
{ let hash = {} info.toString().split('\r\n').map((line) => { let index = line.indexOf(':') if (index === -1) return let name = line.slice(0, index) hash[name] = line.slice(index + 1) }) return hash }
identifier_body
default.rs
// Copyright 2012-2013 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...
Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) ...
{ let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref sum...
identifier_body
default.rs
// Copyright 2012-2013 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...
(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> Gc<Expr> { let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, defaul...
default_substructure
identifier_name
default.rs
// Copyright 2012-2013 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...
}).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation conti...
let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span))
random_line_split
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
pub fn facebook_login() -> Result<Credentials, ()> { let (tx, rx) = mpsc::channel(); let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>(); let handler = ServerHandler { token_tx: Mutex::new(tx), csrf: csrf.clone() }; let ssl = ssl_context().unwrap(); ...
{ let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send().unwrap(); let mut body = String::new(); response.read_to_string(&mut body).unwrap(); let mut result : BTreeMap<String, String> = ...
identifier_body
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
} else { hyper::status::StatusCode::NotFound } } } fn facebook_get_me_id(token: &str) -> Result<String, ()> { let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send()....
{ hyper::status::StatusCode::NotFound }
conditional_block
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
let mut server = hyper::Server::new(listener).handle(handler).unwrap(); println!("Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.", csrf, port); let token = rx.recv().unwrap(); let user_id = facebook_get_me_id(&token)...
random_line_split
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode { let token = params.get("access_token").unwrap(); let csrf = params.get("csrf").unwrap(); if *csrf == self.csrf { self.token_tx.lock().unwrap().send(token.to_owned()).unwrap(); hyper::status::Status...
handle_login
identifier_name
rosbridge_udp.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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...
(): reactor.stop() if __name__ == "__main__": rospy.init_node("rosbridge_websocket") rospy.on_shutdown(shutdown_hook) # register shutdown hook to stop the server ################################################## # Parameter handling # ############################...
shutdown_hook
identifier_name
rosbridge_udp.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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...
################################################## # Done with parameter handling # ################################################## rospy.loginfo("Rosbridge UDP server started on port %d", port) reactor.listenUDP(port, RosbridgeUdpFactory(), interface=interface) reactor.r...
idx = sys.argv.index("--max_message_size") + 1 if idx < len(sys.argv): value = sys.argv[idx] if value == "None": RosbridgeUdpSocket.max_message_size = None else: RosbridgeUdpSocket.max_message_size = int(value) else: print "...
conditional_block
rosbridge_udp.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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...
if __name__ == "__main__": rospy.init_node("rosbridge_websocket") rospy.on_shutdown(shutdown_hook) # register shutdown hook to stop the server ################################################## # Parameter handling # ##################################################...
reactor.stop()
identifier_body
rosbridge_udp.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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...
if idx < len(sys.argv): RosbridgeUdpSocket.delay_between_messages = float(sys.argv[idx]) else: print "--delay_between_messages argument provided without a value." sys.exit(-1) if "--max_message_size" in sys.argv: idx = sys.argv.index("--max_message_size")...
random_line_split
huang_darwiche.py
'''The Example from Huang and Darwiche's Procedural Guide''' from __future__ import division from bayesian.factor_graph import * from bayesian.utils import make_key def f_a(a): return 1 / 2 def f_b(a, b): tt = dict( tt=0.5, ft=0.4, tf=0.5, ff=0.6) return tt[make_key(a, b)...
(c, g): tt = dict( tt=0.8, tf=0.2, ft=0.1, ff=0.9) return tt[make_key(c, g)] def f_h(e, g, h): tt = dict( ttt=0.05, ttf=0.95, tft=0.95, tff=0.05, ftt=0.95, ftf=0.05, fft=0.95, fff=0.05) return tt[make_key(e, g, h)] if __name__ == '__main__': g = bu...
f_g
identifier_name
huang_darwiche.py
'''The Example from Huang and Darwiche's Procedural Guide''' from __future__ import division from bayesian.factor_graph import * from bayesian.utils import make_key def f_a(a): return 1 / 2 def f_b(a, b): tt = dict( tt=0.5, ft=0.4, tf=0.5, ff=0.6) return tt[make_key(a, b)...
def f_h(e, g, h): tt = dict( ttt=0.05, ttf=0.95, tft=0.95, tff=0.05, ftt=0.95, ftf=0.05, fft=0.95, fff=0.05) return tt[make_key(e, g, h)] if __name__ == '__main__': g = build_graph( f_a, f_b, f_c, f_d, f_e, f_f, f_g, f_h) g.n_samples = 1000 g.q()
tt = dict( tt=0.8, tf=0.2, ft=0.1, ff=0.9) return tt[make_key(c, g)]
identifier_body
huang_darwiche.py
'''The Example from Huang and Darwiche's Procedural Guide''' from __future__ import division from bayesian.factor_graph import * from bayesian.utils import make_key def f_a(a): return 1 / 2 def f_b(a, b): tt = dict( tt=0.5, ft=0.4, tf=0.5, ff=0.6) return tt[make_key(a, b)...
g = build_graph( f_a, f_b, f_c, f_d, f_e, f_f, f_g, f_h) g.n_samples = 1000 g.q()
conditional_block
huang_darwiche.py
'''The Example from Huang and Darwiche's Procedural Guide''' from __future__ import division from bayesian.factor_graph import * from bayesian.utils import make_key def f_a(a): return 1 / 2 def f_b(a, b): tt = dict( tt=0.5, ft=0.4, tf=0.5, ff=0.6) return tt[make_key(a, b)...
tt = dict( ttt=0.05, ttf=0.95, tft=0.95, tff=0.05, ftt=0.95, ftf=0.05, fft=0.95, fff=0.05) return tt[make_key(e, g, h)] if __name__ == '__main__': g = build_graph( f_a, f_b, f_c, f_d, f_e, f_f, f_g, f_h) g.n_samples = 1000 g.q()
def f_h(e, g, h):
random_line_split
quickevent.cs_CZ.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="cs_CZ"> <context> <name>AppCliOptions</name> <message> <source>Application locale</source> <translation>Regionální nastavení aplikace</translation> </message> <message> <source>Application profile, s...
<source>Quick Event ver. %1</source> <translation>Quick Event ver. %1</translation> </message> <message> <source>Application log</source> <translation>Záznam činnosti aplikace</translation> </message> </context> </TS>
</context> <context> <name>MainWindow</name> <message>
random_line_split
GetAllBulkMutateJobs.js
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
*/ google.ads.adwords.examples.v201008.GetAllBulkMutateJobs = function() { google.ads.adwords.examples.ExampleBase.call(this); /** * Example description. * @type {string} */ this.description = 'This code example gets all bulk mutate jobs in the ' + 'account. To add a bulk mutate job, run Perform...
* @constructor
random_line_split
GetAllBulkMutateJobs.js
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
} else if (bulkMutateJob.status == google.ads.adwords.v201008. BasicJobStatus.FAILED) { this.writeOutput(' Failure reason: %s.', bulkMutateJob.failureReason.Item); } } } else { this.writeOutput('No bulk mutate ...
{ var bulkMutateJob = bulkMutateJobs[i]; this.writeOutput('Bulk mutate job with id "%d" and status "%s" ' + 'was found.', bulkMutateJob.id, bulkMutateJob.status); if (bulkMutateJob.status == google.ads.adwords.v201008. BasicJobStatus.PENDING) { ...
conditional_block
__init__.py
from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields im...
(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): ...
get_attname
identifier_name
__init__.py
from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields im...
'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_v...
'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name),
random_line_split
__init__.py
from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields im...
class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") ...
kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs)
identifier_body
__init__.py
from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields im...
def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle ...
value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value
conditional_block
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis developers // // 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 o...
use themis::secure_cell::SecureCell; fn main() { let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg...
use clap::clap_app;
random_line_split
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis developers // // 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 o...
() { let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or de...
main
identifier_name
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis developers // // 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 o...
}) .seal(); match mode { "enc" => { let encrypted = cell .encrypt_with_context(&message, &context) .unwrap_or_else(|error| { eprintln!("failed to encrypt message: {}", error); exit(1); }); ...
{ let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or decry...
identifier_body
hex2dump.py
#!/usr/bin/python # Copyright (c) 2008,2010,2011,2012,2013 Alexander Belchenko # 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 retain # the above cop...
(argv=None): import getopt if argv is None: argv = sys.argv[1:] start = None end = None try: opts, args = getopt.getopt(sys.argv[1:], "hvp:r:", ["help", "version", "range="]) for o, a in opts: if o in ("-h", "--help"): ...
main
identifier_name
hex2dump.py
#!/usr/bin/python # Copyright (c) 2008,2010,2011,2012,2013 Alexander Belchenko # 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 retain # the above cop...
def main(argv=None): import getopt if argv is None: argv = sys.argv[1:] start = None end = None try: opts, args = getopt.getopt(sys.argv[1:], "hvp:r:", ["help", "version", "range="]) for o, a in opts: if o in ("-h", "--help"...
import intelhex if hexfile == '-': hexfile = sys.stdin try: ih = intelhex.IntelHex(hexfile) except (IOError, intelhex.IntelHexError), e: sys.stderr.write('Error reading file: %s\n' % e) return 1 if not (start is None and end is None): ih = ih[slice(start,end)] ...
identifier_body
hex2dump.py
#!/usr/bin/python # Copyright (c) 2008,2010,2011,2012,2013 Alexander Belchenko # 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 retain # the above cop...
start = None end = None try: opts, args = getopt.getopt(sys.argv[1:], "hvp:r:", ["help", "version", "range="]) for o, a in opts: if o in ("-h", "--help"): print(USAGE) return 0 elif o in ("-v", "--ve...
argv = sys.argv[1:]
conditional_block
hex2dump.py
#!/usr/bin/python # Copyright (c) 2008,2010,2011,2012,2013 Alexander Belchenko # 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 retain # the above cop...
Arguments: HEXFILE name of hex file for processing (use '-' to read from stdin) ''' import sys def hex2dump(hexfile, start=None, end=None): import intelhex if hexfile == '-': hexfile = sys.stdin try: ih = intelhex.IntelHex(hexfile) except (IOError, intelhex.Inte...
-r, --range=START:END specify address range for dumping (ascii hex value). Range can be in form 'START:' or ':END'.
random_line_split
xmlrpc.d.ts
// Type definitions for xmlrpc 1.3.2 // Project: https://github.com/baalexander/node-xmlrpc // Definitions by: Andrew Short <http://ajshort.me> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../node/node.d.ts" /> declare module 'xmlrpc' { import { EventEmitter } from 'even...
host?: string; path?: string; port?: number; url?: string; cookies?: boolean; headers?: { [header: string]: string }; basic_auth?: { user: string, pass: string }; method?: string; } interface ServerOptions { host?: string; path?: s...
import { Server as HttpServer } from 'http'; import { Server as HttpsServer } from 'https'; import { TlsOptions } from 'tls'; interface ClientOptions {
random_line_split
xmlrpc.d.ts
// Type definitions for xmlrpc 1.3.2 // Project: https://github.com/baalexander/node-xmlrpc // Definitions by: Andrew Short <http://ajshort.me> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../node/node.d.ts" /> declare module 'xmlrpc' { import { EventEmitter } from 'even...
{ get(name: string): string; set(name: string, value: string, options?: { secure: boolean, expires: Date }): void; toString(): string; } namespace xmlrpc { function createClient(options: string | ClientOptions): Client; function createSecureClient(options: string | Clie...
Cookies
identifier_name
loan_actions_card_test.ts
// Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
{ device = DEVICE; onReturned() {} onDamaged(reason: string) {} } describe('LoanActionsCardComponent', () => { beforeEach(() => { TestBed .configureTestingModule({ declarations: [ AllButtonsComponent, TwoButtonsComponent, ], imports: [ ...
TwoButtonsComponent
identifier_name
loan_actions_card_test.ts
// Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
onGuestModeEnabled() {} onReturned() {} onDamaged(reason: string) {} onLost() {} } @Component({ template: ` <loaner-loan-actions-card [device]="device"> <loan-button returnButton (done)="onReturned()"></loan-button> <loan-button damagedButton (done)="onDamaged($event)"></loan-button> <loan-but...
{}
identifier_body
loan_actions_card_test.ts
// Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
}) .compileComponents(); }); it('renders all buttons defined.', () => { const fixture: ComponentFixture<AllButtonsComponent> = TestBed.createComponent(AllButtonsComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySel...
],
random_line_split
0027_fix_collection_path_collation.py
# -*- coding: utf-8 -*- from django.db import migrations def set_collection_path_collation(apps, schema_editor): """ Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to th...
(migrations.Migration): dependencies = [ ('wagtailcore', '0026_group_collection_permission'), ] operations = [ migrations.RunPython( set_collection_path_collation, migrations.RunPython.noop ), ]
Migration
identifier_name
0027_fix_collection_path_collation.py
# -*- coding: utf-8 -*- from django.db import migrations def set_collection_path_collation(apps, schema_editor): """ Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to th...
set_collection_path_collation, migrations.RunPython.noop ), ]
random_line_split
0027_fix_collection_path_collation.py
# -*- coding: utf-8 -*- from django.db import migrations def set_collection_path_collation(apps, schema_editor): """ Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to th...
class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0026_group_collection_permission'), ] operations = [ migrations.RunPython( set_collection_path_collation, migrations.RunPython.noop ), ]
schema_editor.execute(""" ALTER TABLE wagtailcore_collection ALTER COLUMN path TYPE VARCHAR(255) COLLATE "C" """)
conditional_block
0027_fix_collection_path_collation.py
# -*- coding: utf-8 -*- from django.db import migrations def set_collection_path_collation(apps, schema_editor):
class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0026_group_collection_permission'), ] operations = [ migrations.RunPython( set_collection_path_collation, migrations.RunPython.noop ), ]
""" Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters. To avoid this, we explicitly set the collation for the 'path' column to the (non-locale-specific) 'C' collation. See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ "...
identifier_body
build-dist.ts
// tslint:disable-next-line:no-var-requires const project = require('../aurelia.json'); // tslint:disable-next-line:no-var-requires const autoprefix = require('gulp-autoprefixer'); import * as gulp from 'gulp'; import * as path from 'path'; import * as plumber from 'gulp-plumber'; import * as notify from 'gulp-notify';...
() { return gulp.src('src/bridge/**/*.scss') .pipe(plumber({ errorHandler: notify['onError']('Error: <%= error.message %>') })) .pipe(sass({ outputStyle: 'compressed', includePaths: SASS_INCLUDE_PATHS }).on('error', sass.logError)) .pipe(autoprefix(AUTOPREFIXER_BROWSERS)) .pipe(gulp.de...
buildScss
identifier_name
build-dist.ts
// tslint:disable-next-line:no-var-requires const project = require('../aurelia.json'); // tslint:disable-next-line:no-var-requires const autoprefix = require('gulp-autoprefixer'); import * as gulp from 'gulp'; import * as path from 'path'; import * as plumber from 'gulp-plumber'; import * as notify from 'gulp-notify';...
.pipe(gulp.dest('dist/es2015/')) .pipe(gulp.dest('dist/es2017/')) .pipe(gulp.dest('dist/native-modules/')) .pipe(gulp.dest('dist/system/')); } export default gulp.series( copyFiles, buildPug, buildScss );
random_line_split
build-dist.ts
// tslint:disable-next-line:no-var-requires const project = require('../aurelia.json'); // tslint:disable-next-line:no-var-requires const autoprefix = require('gulp-autoprefixer'); import * as gulp from 'gulp'; import * as path from 'path'; import * as plumber from 'gulp-plumber'; import * as notify from 'gulp-notify';...
function copyFiles() { return gulp.src('src/bridge/**/*.{html,css,json,js}') .pipe(plumber({ errorHandler: notify['onError']('Error: <%= error.message %>') })) .pipe(gulp.dest('dist/amd/')) .pipe(gulp.dest('dist/commonjs/')) .pipe(gulp.dest('dist/es2015/')) .pipe(gulp.dest('dist/es2017/')) ....
{ return gulp.src('src/bridge/**/*.scss') .pipe(plumber({ errorHandler: notify['onError']('Error: <%= error.message %>') })) .pipe(sass({ outputStyle: 'compressed', includePaths: SASS_INCLUDE_PATHS }).on('error', sass.logError)) .pipe(autoprefix(AUTOPREFIXER_BROWSERS)) .pipe(gulp.dest(...
identifier_body
get_folder.py
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable from ..util import MNS, create_element from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element class GetFolder(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exch...
def get_payload(self, folders, additional_fields, shape): payload = create_element(f"m:{self.SERVICE_NAME}") payload.append( shape_element( tag="m:FolderShape", shape=shape, additional_fields=additional_fields, version=self.account.version ) ) ...
if isinstance(elem, Exception): yield elem continue yield parse_folder_elem(elem=elem, folder=folder, account=self.account)
conditional_block
get_folder.py
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable from ..util import MNS, create_element from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element class GetFolder(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exch...
(self, elems): for folder, elem in zip(self.folders, elems): if isinstance(elem, Exception): yield elem continue yield parse_folder_elem(elem=elem, folder=folder, account=self.account) def get_payload(self, folders, additional_fields, shape): ...
_elems_to_objs
identifier_name
get_folder.py
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable from ..util import MNS, create_element from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element class GetFolder(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exch...
def _elems_to_objs(self, elems): for folder, elem in zip(self.folders, elems): if isinstance(elem, Exception): yield elem continue yield parse_folder_elem(elem=elem, folder=folder, account=self.account) def get_payload(self, folders, additional_...
"""Take a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements fo...
identifier_body
get_folder.py
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable from ..util import MNS, create_element from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element class GetFolder(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exch...
) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.folders = [] # A hack to communicate parsing args to _elems_to_objs() def call(self, folders, additional_fields, shape): """Take a folder ID and returns the full information for that folder. :pa...
element_container_name = f"{{{MNS}}}Folders" ERRORS_TO_CATCH_IN_RESPONSE = EWSAccountService.ERRORS_TO_CATCH_IN_RESPONSE + ( ErrorFolderNotFound, ErrorNoPublicFolderReplicaAvailable, ErrorInvalidOperation,
random_line_split
LaunchDarkly.test.tsx
import React from "react"; import { configure, shallow } from "enzyme"; import LaunchDarkly from "../../src/components/LaunchDarkly"; import Adapter from "enzyme-adapter-react-16"; configure({ adapter: new Adapter() }); describe("components/LaunchDarkly", () => { it("sets props to the context provider value", () =>...
const subject = shallow( <LaunchDarkly clientId="080808" user={{key: "zeke"}}> <div>Hi</div> </LaunchDarkly> ); const child = subject.find("div"); expect(child.text()).toEqual("Hi"); }); describe("when either clientId or user are missing", () => { it("broadcasts null", () =...
it("renders the children", () => {
random_line_split
setup_for_centos7.py
#!/usr/bin/env python import sys import os import subprocess import shutil import fix_rocks_network import json pxelinux_kernels_dir='/tftpboot/pxelinux/'; centos7_templates_dir='./centos7_ks' centos7_dir='/export/rocks/install/centos7/'; centos7_ks_scripts_dir=centos7_dir+'/scripts/'; centos7_pxeboot_dir=centos7_dir...
def setup_for_centos7(params): if(not os.path.isdir(centos7_dir)): sys.stderr.write('ERROR: the contents of a CentOS-7 iso must be unpacked in the directory: '+centos7_dir+'\n'); raise Exception('Missing directory containing CentOS-7 iso contents'); try: os.mkdir(centos7_ks_scripts_dir, 0755); exce...
shutil.copy(centos7_pxeboot_dir+'/vmlinuz', pxelinux_kernels_dir+'/vmlinuz-centos7'); shutil.copy(centos7_pxeboot_dir+'/initrd.img', pxelinux_kernels_dir+'/initrd.img-centos7'); ks_host = fix_rocks_network.get_rocks_attr('Kickstart_PrivateKickstartHost'); ks_base_dir = fix_rocks_network.get_rocks_attr('Kick...
identifier_body
setup_for_centos7.py
#!/usr/bin/env python import sys import os import subprocess import shutil import fix_rocks_network import json pxelinux_kernels_dir='/tftpboot/pxelinux/'; centos7_templates_dir='./centos7_ks' centos7_dir='/export/rocks/install/centos7/'; centos7_ks_scripts_dir=centos7_dir+'/scripts/'; centos7_pxeboot_dir=centos7_dir...
try: os.mkdir(centos7_ks_scripts_dir, 0755); except OSError: pass #PXE boot changes fix_pxe_bug(); fix_install_action(); #ssh public key shutil.rmtree(centos7_ks_scripts_dir+'/ssh_public_keys', ignore_errors=True); try: os.remove(centos7_ks_scripts_dir+'/ssh_public_keys'); except Exceptio...
sys.stderr.write('ERROR: the contents of a CentOS-7 iso must be unpacked in the directory: '+centos7_dir+'\n'); raise Exception('Missing directory containing CentOS-7 iso contents');
conditional_block
setup_for_centos7.py
#!/usr/bin/env python import sys import os import subprocess import shutil import fix_rocks_network import json pxelinux_kernels_dir='/tftpboot/pxelinux/'; centos7_templates_dir='./centos7_ks' centos7_dir='/export/rocks/install/centos7/'; centos7_ks_scripts_dir=centos7_dir+'/scripts/'; centos7_pxeboot_dir=centos7_dir...
(): shutil.copy('/usr/share/syslinux/chain.c32', pxelinux_kernels_dir); subprocess.call('rocks add bootaction action=os kernel="com32 chain.c32" args="hd0"', shell=True); def fix_install_action(): shutil.copy(centos7_pxeboot_dir+'/vmlinuz', pxelinux_kernels_dir+'/vmlinuz-centos7'); shutil.copy(centos7_...
fix_pxe_bug
identifier_name
setup_for_centos7.py
#!/usr/bin/env python import sys import os import subprocess import shutil import fix_rocks_network import json pxelinux_kernels_dir='/tftpboot/pxelinux/'; centos7_templates_dir='./centos7_ks' centos7_dir='/export/rocks/install/centos7/'; centos7_ks_scripts_dir=centos7_dir+'/scripts/'; centos7_pxeboot_dir=centos7_dir...
cmd = 'sed -i -e \'s/Kickstart_PrivateKickstartHost/'+ks_host+'/g\' -e \'s/Kickstart_PrivateKickstartBasedir/'+ks_base_dir+'/g\' '+centos7_ks_scripts_dir+'/post_install.sh '+centos7_ks_scripts_dir+'/pre_install.sh '+centos7_dir+'/ks.cfg'; status = subprocess.call(cmd, shell=True); if(status != 0): sys.stderr....
ks_base_dir = fix_rocks_network.get_rocks_attr('Kickstart_PrivateKickstartBasedir');
random_line_split
authentication.js
/* eslint-disable camelcase */ import {Response} from 'ember-cli-mirage'; import {isBlank} from 'ember-utils'; import $ from 'jquery'; export default function mockAuthentication(server)
expires_in: 3600, refresh_token: 'XP13eDjwV5mxOcrq1jkIY9idhdvN3R1Br5vxYpYIub2P5Hdc8pdWMOGmwFyoUshiEB62JWHTl8H1kACJR18Z8aMXbnk5orG28br2kmVgtVZKqOSoiiWrQoeKTqrRV0t7ua8uY5HdDUaKpnYKyOdpagsSPn3WEj8op4vHctGL3svOWOjZhq6F2XeVPMR7YsbiwBE8fjT3VhTB3KRlBtWZd1rE0Qo2EtSplWyjGKv1liAEiL0ndQoLeeSOCH4rTP...
{ server.post('/authentication/token', function ({roles, users}, {requestBody}) { let params = $.deparam(requestBody); if (params.grant_type === 'authorization_code') { // OAuth sign-in if (!users.all().models.length) { let role = roles.findBy({name: 'Owner'}...
identifier_body
authentication.js
/* eslint-disable camelcase */ import {Response} from 'ember-cli-mirage'; import {isBlank} from 'ember-utils'; import $ from 'jquery'; export default function
(server) { server.post('/authentication/token', function ({roles, users}, {requestBody}) { let params = $.deparam(requestBody); if (params.grant_type === 'authorization_code') { // OAuth sign-in if (!users.all().models.length) { let role = roles.findBy({name:...
mockAuthentication
identifier_name
authentication.js
/* eslint-disable camelcase */ import {Response} from 'ember-cli-mirage'; import {isBlank} from 'ember-utils'; import $ from 'jquery'; export default function mockAuthentication(server) { server.post('/authentication/token', function ({roles, users}, {requestBody}) { let params = $.deparam(requestBody); ...
attrs.roles = [role]; if (!isBlank(attrs.email)) { attrs.slug = attrs.email.split('@')[0].dasherize(); } // NOTE: server does not use the user factory to fill in blank fields return users.create(attrs); }); server.get('/authentication/setup/', function () {...
}
random_line_split
authentication.js
/* eslint-disable camelcase */ import {Response} from 'ember-cli-mirage'; import {isBlank} from 'ember-utils'; import $ from 'jquery'; export default function mockAuthentication(server) { server.post('/authentication/token', function ({roles, users}, {requestBody}) { let params = $.deparam(requestBody); ...
return { access_token: '5JhTdKI7PpoZv4ROsFoERc6wCHALKFH5jxozwOOAErmUzWrFNARuH1q01TYTKeZkPW7FmV5MJ2fU00pg9sm4jtH3Z1LjCf8D6nNqLYCfFb2YEKyuvG7zHj4jZqSYVodN2YTCkcHv6k8oJ54QXzNTLIDMlCevkOebm5OjxGiJpafMxncm043q9u1QhdU9eee3zouGRMVVp8zkKVoo5zlGMi3zvS2XDpx7xsfk8hKHpUgd7EDDQxmMueifWv7hv6n', ...
{ let role = roles.findBy({name: 'Owner'}); server.create('user', {email: 'oauthtest@example.com', roles: [role]}); }
conditional_block
ErrorUtils.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This mock only provides short-circuited methods of applyWithGuard and guard. // A lot of modules rely on these two functions. This mo...
var ErrorUtils = { apply: jest.fn(execute), applyWithGuard: jest.fn(execute), guard: jest.fn(callback => callback), inGuard: jest.fn().mockReturnValue(true), reportError: jest.fn(reportError), setGlobalHandler: jest.fn(), }; module.exports = ErrorUtils;
{ throw error; }
identifier_body
ErrorUtils.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This mock only provides short-circuited methods of applyWithGuard and guard. // A lot of modules rely on these two functions. This mo...
function execute(fun, context, args) { return fun.apply(context, args); } function reportError(error) { throw error; } var ErrorUtils = { apply: jest.fn(execute), applyWithGuard: jest.fn(execute), guard: jest.fn(callback => callback), inGuard: jest.fn().mockReturnValue(true), reportError: jest.fn(repor...
random_line_split
ErrorUtils.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This mock only provides short-circuited methods of applyWithGuard and guard. // A lot of modules rely on these two functions. This mo...
(fun, context, args) { return fun.apply(context, args); } function reportError(error) { throw error; } var ErrorUtils = { apply: jest.fn(execute), applyWithGuard: jest.fn(execute), guard: jest.fn(callback => callback), inGuard: jest.fn().mockReturnValue(true), reportError: jest.fn(reportError), setGlo...
execute
identifier_name
evalrational.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 a...
( P, Q, x ) { var len; var s1; var s2; var i; len = P.length; if ( len === 0 ) { return NaN; } if ( len !== Q.length ) { return NaN; } if ( x === 0.0 || len === 1 ) { return P[ 0 ] / Q[ 0 ]; } // Use Horner's method... if ( abs( x ) <= 1.0 ) { s1 = P[ len-1 ]; s2 = Q[ len-1 ]; for ( i = len-2;...
evalrational
identifier_name
evalrational.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 a...
// EXPORTS // module.exports = evalrational;
random_line_split
evalrational.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 a...
for ( i = len-2; i >= 0; --i ) { s1 *= x; s2 *= x; s1 += P[ i ]; s2 += Q[ i ]; } } else { x = 1.0 / x; // use inverse to avoid overflow s1 = P[ 0 ]; s2 = Q[ 0 ]; for ( i = 1; i < len; ++i ) { s1 *= x; s2 *= x; s1 += P[ i ]; s2 += Q[ i ]; } } return s1 / s2; } // EXPORTS // m...
{ var len; var s1; var s2; var i; len = P.length; if ( len === 0 ) { return NaN; } if ( len !== Q.length ) { return NaN; } if ( x === 0.0 || len === 1 ) { return P[ 0 ] / Q[ 0 ]; } // Use Horner's method... if ( abs( x ) <= 1.0 ) { s1 = P[ len-1 ]; s2 = Q[ len-1 ];
identifier_body
evalrational.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 a...
else { x = 1.0 / x; // use inverse to avoid overflow s1 = P[ 0 ]; s2 = Q[ 0 ]; for ( i = 1; i < len; ++i ) { s1 *= x; s2 *= x; s1 += P[ i ]; s2 += Q[ i ]; } } return s1 / s2; } // EXPORTS // module.exports = evalrational;
{ s1 = P[ len-1 ]; s2 = Q[ len-1 ]; for ( i = len-2; i >= 0; --i ) { s1 *= x; s2 *= x; s1 += P[ i ]; s2 += Q[ i ]; } }
conditional_block
serializer.js
/* * Clearest Framework * Provided under MIT License. * Copyright (c) 2012-2015 Illya Kokshenev <sou@illya.com.br> */ /** * Created by M0nZDeRR on 30/10/2015. */ var chai = require("chai"), expect = chai.expect, commons = require("../../core/commons"), inside = commons.inside, Serializer = requi...
expect(ser.serialize(f)).to.be.equal(f.toString()); expect(ser.serialize({})).to.be.equal('{}'); expect(ser.serialize({foo:42})).to.be.equal('{foo:42}'); expect(ser.serialize({foo:"42"})).to.be.equal('{foo:"42"}'); var o={}; inside(o).serialize = function(ser){return ser....
var f = function (a,b,c){return a+b+c};
random_line_split
multi_reporter_spec.ts
import { afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, } from 'angular2/test_lib'; import {PromiseWrapper, Promise} from 'angular2/src/core/facade/async'; import {DateWrapper} from 'angular2/src/core/facade/lang'; import {Reporter, MultiReporter, bin...
describe('multi reporter', () => { it('should reportMeasureValues to all', inject([AsyncTestCompleter], (async) => { var mv = new MeasureValues(0, DateWrapper.now(), {}); createReporters(['m1', 'm2']) .then((r) => r.reportMeasureValues(mv)) .then((values) => { ...
{ var r = Injector.resolveAndCreate([ ids.map(id => bind(id).toValue(new MockReporter(id))), MultiReporter.createBindings(ids) ]) .get(MultiReporter); return PromiseWrapper.resolve(r); }
identifier_body
multi_reporter_spec.ts
import { afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, } from 'angular2/test_lib'; import {PromiseWrapper, Promise} from 'angular2/src/core/facade/async'; import {DateWrapper} from 'angular2/src/core/facade/lang'; import {Reporter, MultiReporter, bin...
(ids: any[]) { var r = Injector.resolveAndCreate([ ids.map(id => bind(id).toValue(new MockReporter(id))), MultiReporter.createBindings(ids) ]) .get(MultiReporter); return PromiseWrapper.resolve(r); } describe('multi reporter', ...
createReporters
identifier_name
multi_reporter_spec.ts
import { afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, } from 'angular2/test_lib'; import {PromiseWrapper, Promise} from 'angular2/src/core/facade/async'; import {DateWrapper} from 'angular2/src/core/facade/lang'; import {Reporter, MultiReporter, bin...
reportMeasureValues(values: MeasureValues): Promise<{[key: string]: any}> { return PromiseWrapper.resolve({'id': this._id, 'values': values}); } reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise<{[key: string]: any}> { return PromiseWrapper.resolve( ...
constructor(private _id: string) { super(); }
random_line_split
socket-for-test.js
import Ember from 'ember'; import { module, test } from 'qunit'; import SocketsService from 'dummy/services/websockets'; var component; var ConsumerComponent; var originalWebSocket; var mockServerFoo; var mockServerBar; module('Sockets Service - socketFor', { setup() { originalWebSocket = window.WebSocket; ...
() { this.socketService.closeSocketFor('ws://localhost:7000/'); this.socketService.closeSocketFor('ws://localhost:7001/'); } }); }, teardown() { window.WebSocket = originalWebSocket; Ember.run(() => { component.destroy(); mockServerFoo.close(); mockServerBar.clos...
willDestroy
identifier_name
socket-for-test.js
import Ember from 'ember'; import { module, test } from 'qunit'; import SocketsService from 'dummy/services/websockets'; var component; var ConsumerComponent; var originalWebSocket; var mockServerFoo; var mockServerBar; module('Sockets Service - socketFor', { setup() { originalWebSocket = window.WebSocket; ...
this.socketService.closeSocketFor('ws://localhost:7000/'); this.socketService.closeSocketFor('ws://localhost:7001/'); } }); }, teardown() { window.WebSocket = originalWebSocket; Ember.run(() => { component.destroy(); mockServerFoo.close(); mockServerBar.close(); ...
willDestroy() {
random_line_split
socket-for-test.js
import Ember from 'ember'; import { module, test } from 'qunit'; import SocketsService from 'dummy/services/websockets'; var component; var ConsumerComponent; var originalWebSocket; var mockServerFoo; var mockServerBar; module('Sockets Service - socketFor', { setup() { originalWebSocket = window.WebSocket; ...
}); test('that socketFor works correctly', assert => { var done = assert.async(); assert.expect(2); component = ConsumerComponent.extend({ init() { this._super.apply(this, arguments); var socketService = this.socketService; assert.deepEqual(socketService.socketFor('ws://localhost:7000/')...
{ window.WebSocket = originalWebSocket; Ember.run(() => { component.destroy(); mockServerFoo.close(); mockServerBar.close(); }); }
identifier_body
reporte_list.js
$(document).ready(function() { $('#servicio_ingreso').select2({ width: '60%', placeholder:'Seleccione...', allowClear:true }); $("#fecha_inicio").datepicker().mask("99-99-9999"); $("#fecha_fin").datepicker().mask("99-99-9999"); $("#emitir_informe").click(function() { if...
else if( $("#fecha_inicio").datepicker("getDate") > $("#fecha_fin").datepicker("getDate")){ ($('#error')) ? $('#error').remove() : ''; var elem = $("<div id='error' title='Error de llenado'><center>" + "La fecha de inicio debe de ser menor que la fecha fin." ...
{ ($('#error')) ? $('#error').remove() : ''; var elem = $("<div id='error' title='Error de llenado'><center>" + "Debe de seleccionar ambas fechas para generar el reporte." + "</center></div>"); elem.insertAfter($("#pacientesIngresados")); ...
conditional_block
reporte_list.js
$(document).ready(function() { $('#servicio_ingreso').select2({ width: '60%', placeholder:'Seleccione...', allowClear:true }); $("#fecha_inicio").datepicker().mask("99-99-9999"); $("#fecha_fin").datepicker().mask("99-99-9999"); $("#emitir_informe").click(function() { if...
else $("#fecha_fin").focus(); } }); } else if( $("#fecha_inicio").datepicker("getDate") > $("#fecha_fin").datepicker("getDate")){ ($('#error')) ? $('#error').remove() : ''; var elem = $("<div id='error' title='Error ...
$("#error").dialog({ close: function() { if ($("#fecha_inicio").val() == '') $("#fecha_inicio").focus();
random_line_split
StrStrHashMapSerializer.py
""" # Licensed to the Apache Software Foundation (ASF) under one * # or more contributor license agreements. See the NOTICE file * # distributed with this work for additional information * # regarding copyright ownership. The ASF licenses this file * # to you under the Apache License, Version 2.0 (the...
def exportValue(self, vf, value): m = StrStrHashMap(value) keysAndValues = [] for i in m.keys(): keysAndValues.append(i) keysAndValues.append(m[i]) struct = StructValue(self.__type, vf) struct.put(self.__field, keysAndValues) ret...
m = StrStrHashMap() keysAndValues = struct.get(self.__field) for i in range(0, len(keysAndValues), 2): m[keysAndValues[i]] = keysAndValues[i+1] return m
identifier_body
StrStrHashMapSerializer.py
""" # Licensed to the Apache Software Foundation (ASF) under one * # or more contributor license agreements. See the NOTICE file * # distributed with this work for additional information * # regarding copyright ownership. The ASF licenses this file * # to you under the Apache License, Version 2.0 (the...
return m def exportValue(self, vf, value): m = StrStrHashMap(value) keysAndValues = [] for i in m.keys(): keysAndValues.append(i) keysAndValues.append(m[i]) struct = StructValue(self.__type, vf) struct.put(self.__field, keysAndVa...
m[keysAndValues[i]] = keysAndValues[i+1]
conditional_block
StrStrHashMapSerializer.py
""" # Licensed to the Apache Software Foundation (ASF) under one * # or more contributor license agreements. See the NOTICE file * # distributed with this work for additional information * # regarding copyright ownership. The ASF licenses this file * # to you under the Apache License, Version 2.0 (the...
(self, struct): m = StrStrHashMap() keysAndValues = struct.get(self.__field) for i in range(0, len(keysAndValues), 2): m[keysAndValues[i]] = keysAndValues[i+1] return m def exportValue(self, vf, value): m = StrStrHashMap(value) keysAndValues = [] ...
importHelper
identifier_name
StrStrHashMapSerializer.py
""" # Licensed to the Apache Software Foundation (ASF) under one * # or more contributor license agreements. See the NOTICE file * # distributed with this work for additional information * # regarding copyright ownership. The ASF licenses this file * # to you under the Apache License, Version 2.0 (the...
return struct
keysAndValues.append(i) keysAndValues.append(m[i]) struct = StructValue(self.__type, vf) struct.put(self.__field, keysAndValues)
random_line_split
utils.py
import random import time import datetime from consts import * __all__ = ['gen_valid_id', 'gen_list_page', 'log'] def gen_valid_id(collection): def gen_id(): _id = '' for i in range(4): _id += random.choice('0123456789') return _id id = gen_id() while collection.find_...
left = (page - 1) * 15 right = left + 15 all = collection.find({'status': status}).sort([('id', 1)]) max_page = int((all.count()-1) / 15) + 1 if all.count() else 0 if page > max_page: return PAGE_NOT_EXIST elif page < 1: return ARGS_INCORRECT header = '===== {0}/{1} =====\n...
random_line_split
utils.py
import random import time import datetime from consts import * __all__ = ['gen_valid_id', 'gen_list_page', 'log'] def gen_valid_id(collection): def gen_id(): _id = '' for i in range(4): _id += random.choice('0123456789') return _id id = gen_id() while collection.find_...
elif page < 1: return ARGS_INCORRECT header = '===== {0}/{1} =====\n'.format(page, max_page) selected = all[left:right] return header + '\n'.join([ '{id} {title} ({comment})'.format(**i) for i in selected]) def log(m): with open('log', 'a') as f: if m.type == 'text': exp=...
return PAGE_NOT_EXIST
conditional_block
utils.py
import random import time import datetime from consts import * __all__ = ['gen_valid_id', 'gen_list_page', 'log'] def gen_valid_id(collection): def gen_id(): _id = '' for i in range(4): _id += random.choice('0123456789') return _id id = gen_id() while collection.find_...
(collection, status, page=1): page = int(page) left = (page - 1) * 15 right = left + 15 all = collection.find({'status': status}).sort([('id', 1)]) max_page = int((all.count()-1) / 15) + 1 if all.count() else 0 if page > max_page: return PAGE_NOT_EXIST elif page < 1: return ...
gen_list_page
identifier_name
utils.py
import random import time import datetime from consts import * __all__ = ['gen_valid_id', 'gen_list_page', 'log'] def gen_valid_id(collection): def gen_id(): _id = '' for i in range(4): _id += random.choice('0123456789') return _id id = gen_id() while collection.find_...
def log(m): with open('log', 'a') as f: if m.type == 'text': exp=m.content elif m.type == 'image': exp=m.img elif m.type == 'link': exp=';'.join([m.title, m.description, m.url]) else: exp=str(dict(m)) f.write(LOG.format(datetime.datetime.fromtimestamp( time.time...
page = int(page) left = (page - 1) * 15 right = left + 15 all = collection.find({'status': status}).sort([('id', 1)]) max_page = int((all.count()-1) / 15) + 1 if all.count() else 0 if page > max_page: return PAGE_NOT_EXIST elif page < 1: return ARGS_INCORRECT header = '====...
identifier_body
update_default_servers.py
#!/usr/bin/env python3 # This script prints a new "servers.json" to stdout. # It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions), # and adds new servers from provided file(s) of candidate servers. # A file of new candidate servers can be created via e.g.: # $ ./electrum_ltc/...
return res_hostmap # testnet? #constants.set_testnet() config = SimpleConfig({'testnet': False}) loop, stopping_fut, loop_thread = create_and_start_event_loop() network = Network(config) network.start() @log_exceptions async def f(): try: # prune existing servers old_servers_all = constants...
with open(fname2) as f: dict2 = json.loads(f.read()) common_set = set.intersection(set(res_hostmap), set(dict2)) res_hostmap = {k: v for k, v in res_hostmap.items() if k in common_set}
conditional_block
update_default_servers.py
#!/usr/bin/env python3 # This script prints a new "servers.json" to stdout. # It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions), # and adds new servers from provided file(s) of candidate servers. # A file of new candidate servers can be created via e.g.: # $ ./electrum_ltc/...
network.start() @log_exceptions async def f(): try: # prune existing servers old_servers_all = constants.net.DEFAULT_SERVERS old_servers_online = await network.prune_offline_servers(constants.net.DEFAULT_SERVERS) # add new servers newly_added_servers = get_newly_added_server...
#constants.set_testnet() config = SimpleConfig({'testnet': False}) loop, stopping_fut, loop_thread = create_and_start_event_loop() network = Network(config)
random_line_split