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
list_property.py
# -*- coding: utf-8 -*- """ InaSAFE Disaster risk assessment tool developed by AusAid - **metadata module.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 Sof...
elif self.python_type is NoneType: return '' else: raise RuntimeError('self._allowed_python_types and self.xml_value' 'are out of sync. This should never happen')
return json.dumps(self.value)
conditional_block
list_property.py
# -*- coding: utf-8 -*- """ InaSAFE Disaster risk assessment tool developed by AusAid - **metadata module.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 Sof...
try: return json.loads(value) except ValueError as e: raise MetadataCastError(e) @property def xml_value(self): if self.python_type is list: return json.dumps(self.value) elif self.python_type is NoneType: return '' else: ...
def is_valid(cls, value): return True def cast_from_str(self, value):
random_line_split
list_property.py
# -*- coding: utf-8 -*- """ InaSAFE Disaster risk assessment tool developed by AusAid - **metadata module.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 Sof...
(self, value): try: return json.loads(value) except ValueError as e: raise MetadataCastError(e) @property def xml_value(self): if self.python_type is list: return json.dumps(self.value) elif self.python_type is NoneType: return '' ...
cast_from_str
identifier_name
regex.rs
#![allow(unused)] #![warn(clippy::invalid_regex, clippy::trivial_regex)] extern crate regex; use regex::bytes::{Regex as BRegex, RegexBuilder as BRegexBuilder, RegexSet as BRegexSet}; use regex::{Regex, RegexBuilder, RegexSet}; const OPENING_PAREN: &str = "("; const NOT_A_REAL_REGEX: &str = "foobar"; fn syntax_erro...
{ syntax_error(); trivial_regex(); }
in()
identifier_name
regex.rs
#![allow(unused)] #![warn(clippy::invalid_regex, clippy::trivial_regex)] extern crate regex; use regex::bytes::{Regex as BRegex, RegexBuilder as BRegexBuilder, RegexSet as BRegexSet}; use regex::{Regex, RegexBuilder, RegexSet}; const OPENING_PAREN: &str = "("; const NOT_A_REAL_REGEX: &str = "foobar"; fn syntax_erro...
let trivial_eq_builder = RegexBuilder::new("^foobar$"); let trivial_starts_with = Regex::new("^foobar"); let trivial_ends_with = Regex::new("foobar$"); let trivial_contains = Regex::new("foobar"); let trivial_contains = Regex::new(NOT_A_REAL_REGEX); let trivial_backslash = Regex::new("a\\.b...
fn trivial_regex() { let trivial_eq = Regex::new("^foobar$");
random_line_split
regex.rs
#![allow(unused)] #![warn(clippy::invalid_regex, clippy::trivial_regex)] extern crate regex; use regex::bytes::{Regex as BRegex, RegexBuilder as BRegexBuilder, RegexSet as BRegexSet}; use regex::{Regex, RegexBuilder, RegexSet}; const OPENING_PAREN: &str = "("; const NOT_A_REAL_REGEX: &str = "foobar"; fn syntax_erro...
]); let set_error = RegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let bset_error = BRegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let raw_string_error = Regex::new(r"[...\/...]"); let raw_string_error = Regex::new(r#"[...\/...]"#); } fn trivial_regex() { let trivial_...
{ let pipe_in_wrong_position = Regex::new("|"); let pipe_in_wrong_position_builder = RegexBuilder::new("|"); let wrong_char_ranice = Regex::new("[z-a]"); let some_unicode = Regex::new("[é-è]"); let some_regex = Regex::new(OPENING_PAREN); let binary_pipe_in_wrong_position = BRegex::new("|"); ...
identifier_body
randoms.py
__author__ = 'jkonieczny' from books.models import * import random import datetime from django.core.management.base import BaseCommand, CommandError _names1 = [ "JAKUB", "KACPER", "SZYMON", "MATEUSZ", "FILIP", "MICHAŁ", "BARTOSZ", "WIKTOR", "PIOTR", "DAWID", "ADAM", "M...
s, **options): authors = [] for i in range(30): a = Author() name = _names1[int(random.random()*len(_names1))] name +=' ' + _names1[int(random.random()*len(_names1))] a.name = name a.born = datetime.date(1980, 1, 1) a.save() ...
le(self, *arg
identifier_name
randoms.py
__author__ = 'jkonieczny' from books.models import * import random import datetime from django.core.management.base import BaseCommand, CommandError _names1 = [ "JAKUB", "KACPER", "SZYMON", "MATEUSZ", "FILIP", "MICHAŁ", "BARTOSZ", "WIKTOR", "PIOTR", "DAWID", "ADAM", "M...
p.per_week = i p.save() pricing.append(p) for title in titles[:-5]: for _e in range(1+int(min(0,random.normalvariate(0,1)))): edition = BookEdition() edition.publisher = publisher[int(random.random()*len(publisher))] ...
random_line_split
randoms.py
__author__ = 'jkonieczny' from books.models import * import random import datetime from django.core.management.base import BaseCommand, CommandError _names1 = [ "JAKUB", "KACPER", "SZYMON", "MATEUSZ", "FILIP", "MICHAŁ", "BARTOSZ", "WIKTOR", "PIOTR", "DAWID", "ADAM", "M...
t.save() for i in range(1+int(max(0, random.normalvariate(0, 1)))): t.author.add(authors[int(random.random()*len(authors))]) for i in range(1+int(max(0, random.normalvariate(0, 1)))): t.genre.add(genres[int(random.random()*len(genres))]) ti...
= Author() name = _names1[int(random.random()*len(_names1))] name +=' ' + _names1[int(random.random()*len(_names1))] a.name = name a.born = datetime.date(1980, 1, 1) a.save() authors.append(a) genres = [] for i in _genres: ...
identifier_body
randoms.py
__author__ = 'jkonieczny' from books.models import * import random import datetime from django.core.management.base import BaseCommand, CommandError _names1 = [ "JAKUB", "KACPER", "SZYMON", "MATEUSZ", "FILIP", "MICHAŁ", "BARTOSZ", "WIKTOR", "PIOTR", "DAWID", "ADAM", "M...
): edition = BookEdition() edition.publisher = publisher[int(random.random()*len(publisher))] edition.isbn = '' edition.release = (datetime.datetime.now() - datetime.timedelta(days=random.random()*365*10)).date() edition.title = title ...
conditional_block
production.py
from decouple import Csv, config from dj_database_url import parse as db_url from .base import * # noqa DEBUG = False SECRET_KEY = config('SECRET_KEY') DATABASES = { 'default': config('DATABASE_URL', cast=db_url), } DATABASES['default']['ATOMIC_REQUESTS'] = True ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=C...
EMAIL_PORT = 587 EMAIL_USE_TLS = True # Security SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER...
EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = config('SENDGRID_USERNAME') EMAIL_HOST_PASSWORD = config('SENDGRID_PASSWORD')
random_line_split
json_item.py
from json import loads as json_loads import collections from .text_item import AbstractTextItem from .tree_item import AbstractTreeItem from .. import register @register class
(AbstractTextItem, AbstractTreeItem): extensions = ("json",) mime_type = "text/x-json" new_item_order_preference = 1.62 type_description = lambda: "JSON (JavaScript Object Notation)" new_item_content = lambda name: "{\n \"_title\" : \"" + name + "\"\n}\n" @property def json(self): ...
JsonItem
identifier_name
json_item.py
from json import loads as json_loads import collections from .text_item import AbstractTextItem from .tree_item import AbstractTreeItem from .. import register @register class JsonItem(AbstractTextItem, AbstractTreeItem): extensions = ("json",) mime_type = "text/x-json" new_item_order_preference = 1.62...
return self._json def _repr_html_(self): try: json = self.json return self._tree_to_html(json) except: return "<b>Invalid JSON:</b><pre>{0}</pre>".format(self.text)
self._json = json_loads(self.text, object_pairs_hook=collections.OrderedDict)
conditional_block
json_item.py
from json import loads as json_loads import collections from .text_item import AbstractTextItem from .tree_item import AbstractTreeItem from .. import register @register class JsonItem(AbstractTextItem, AbstractTreeItem): extensions = ("json",) mime_type = "text/x-json" new_item_order_preference = 1.62...
def json(self): if not "_json" in dir(self): self._json = json_loads(self.text, object_pairs_hook=collections.OrderedDict) return self._json def _repr_html_(self): try: json = self.json return self._tree_to_html(json) except: retur...
type_description = lambda: "JSON (JavaScript Object Notation)" new_item_content = lambda name: "{\n \"_title\" : \"" + name + "\"\n}\n" @property
random_line_split
json_item.py
from json import loads as json_loads import collections from .text_item import AbstractTextItem from .tree_item import AbstractTreeItem from .. import register @register class JsonItem(AbstractTextItem, AbstractTreeItem):
except: return "<b>Invalid JSON:</b><pre>{0}</pre>".format(self.text)
extensions = ("json",) mime_type = "text/x-json" new_item_order_preference = 1.62 type_description = lambda: "JSON (JavaScript Object Notation)" new_item_content = lambda name: "{\n \"_title\" : \"" + name + "\"\n}\n" @property def json(self): if not "_json" in dir(self): ...
identifier_body
Gruntfile.js
/** * Created by Tivie on 12-11-2014. */ module.exports = function (grunt) { // Project configuration. var config = { pkg: grunt.file.readJSON('package.json'), concat: { options: { sourceMap: true, banner: ';/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %...
options: { globals: ['should'], timeout: 3000, ignoreLeaks: false, reporter: 'spec' } }, browser: { src: 'test/browser/**/*.js', options: { reporter: 'spec' } } } }; grunt.initConfig(conf...
karlcow: { src: 'test/node/testsuite.karlcow.js',
random_line_split
cmdi2html.js
/* * Copyright (C) 2015 Max Planck Institute for Psycholinguistics * * 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 3 of the License, or * (at your option) any later versi...
() { $(".searchword").parents('.IMDI_group.cmdi').removeClass('collapsed'); $(".searchword").parents('.IMDI_group.cmdi').addClass('expanded'); } $(document).ready(init_cmdi);
expand_highlighted_cmdi
identifier_name
cmdi2html.js
/* * Copyright (C) 2015 Max Planck Institute for Psycholinguistics * * 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 3 of the License, or * (at your option) any later versi...
$(document).ready(init_cmdi);
{ $(".searchword").parents('.IMDI_group.cmdi').removeClass('collapsed'); $(".searchword").parents('.IMDI_group.cmdi').addClass('expanded'); }
identifier_body
cmdi2html.js
/* * Copyright (C) 2015 Max Planck Institute for Psycholinguistics * * 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 3 of the License, or * (at your option) any later versi...
* * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ function init_cmdi() { $("a.toggle").click(function () { $(this).parent().parent().toggleClass('collapsed'); $(this).parent().parent().toggleClass('ex...
* * 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.
random_line_split
index.js
(function (root, factory) { if (typeof define === 'function' && define.amd)
else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.C = factory(); } }(this, function () { function runAndWaitOn(func) { return function (value) { var handlerRes = func(value); if (handlerRes && typeof handlerRe...
{ define([], factory); }
conditional_block
index.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.C = factory(); } }(this, function () { function runAndWaitOn(func) { ...
(func) { return new C(null, promise, function (arr) { if (!Array.isArray(arr)) { return func.call(null, arr); } return func.apply(null, arr); }); } function _then(onFulfilled, onRejected) { return ne...
_spread
identifier_name
index.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.C = factory(); } }(this, function () { function runAndWaitOn(func) { ...
switch (arguments.length) { case 2: constructor = arguments[0]; handler = arguments[1]; break; case 1: handler = arguments[0]; break; default: ...
{ var promise = optionalPromise ? optionalPromise.then(wrap(onFulfilled), wrap(onRejected)) : new Promise(handler); var _u = this; function wrap(func){ return typeof func === 'function' ? function() { var res = func.apply(undefined, arguments); if (r...
identifier_body
index.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.C = factory(); } }(this, function () { function runAndWaitOn(func) { ...
var handler; var constructor; switch (arguments.length) { case 2: constructor = arguments[0]; handler = arguments[1]; break; case 1: handler = arguments[0]; ...
return res; } : undefined; } function _catch(){
random_line_split
htmlstyleelement.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 cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } if self.upcast::<Node>().i...
random_line_split
htmlstyleelement.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 cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
if tree_in_doc { self.parse_own_css(); } } }
{ s.bind_to_tree(tree_in_doc); }
conditional_block
htmlstyleelement.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 cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
#[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, ...
{ HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DOMRefCell::new(None), } }
identifier_body
htmlstyleelement.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 cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let win = window_from_node(node); let url = win.get_url(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let mq_str = match mq_att...
parse_own_css
identifier_name
Changes.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2011 Thomas Schreiber # # 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) any l...
self, parent): """Initialize ChangeWin. :param parent: Caller. """ QDialog.__init__(self, parent) self.ui=Ui_changeSummary() self.ui.setupUi(self) def setChanges(self, changeDict): """Add changes to ChangeWin. :param changeDict: Dictionary of changes...
_init__(
identifier_name
Changes.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2011 Thomas Schreiber # # 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) any l...
def setChanges(self, changeDict): """Add changes to ChangeWin. :param changeDict: Dictionary of changes. """ installString = '' upgradeString = '' removeString = '' for app in changeDict['repoInstalls']: installString += app + ' ' for app...
""Initialize ChangeWin. :param parent: Caller. """ QDialog.__init__(self, parent) self.ui=Ui_changeSummary() self.ui.setupUi(self)
identifier_body
Changes.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2011 Thomas Schreiber # # 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) any l...
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # by Thomas Schreiber <ubiquill@gmail.com> # from PyQt4....
# # 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
random_line_split
Changes.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2011 Thomas Schreiber # # 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) any l...
for app in changeDict['aurBuildDeps']: installString += app + ' ' for app in changeDict['aurDeps']: installString += app + ' ' for app in changeDict['repoUpgrades']: upgradeString += app + ' ' for app in changeDict['aurUpgrades']: upgradeSt...
nstallString += app + ' '
conditional_block
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = F...
TestFs::create(&entities) }
random_line_split
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = F...
{ TestFs::create(&entities) }
identifier_body
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = F...
&FsEntity::File(ref pb) => { File::create(pb).unwrap(); } } } TestFs {} } } pub fn pb<P: AsRef<Path>>(p: P) -> PathBuf { let mut pb = PathBuf::from("it/"); pb.push(p); pb } pub fn td<P: AsRef<Path>>(p: P) -> FsEntity { ...
{ fs::create_dir_all(pb).unwrap(); }
conditional_block
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = F...
<P: AsRef<Path>>(p: P) -> PathBuf { let mut pb = PathBuf::from("it/"); pb.push(p); pb } pub fn td<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::Dir(pb(p)) } pub fn tf<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::File(pb(p)) } pub fn setup(entities: &[FsEntity]) -> TestFs { TestFs::create(&ent...
pb
identifier_name
sonar.js
// Derived and adapted from // https://github.com/rwldrn/duino/blob/development/lib/ping.js var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function Sonar( opts )
this.freq = opts.freq || 100; this.voltage = null; // Set the pin to ANALOG mode this.firmata.pinMode( this.pin, this.mode ); this.firmata.analogRead( this.pin, function( data ) { this.voltage = data; samples.push( data ); }.bind(this)); // Throttle setInterval(function() { var err; ...
{ if ( !(this instanceof Sonar) ) { return new Sonar( opts ); } var last, samples, median; last = null; samples = []; opts = Board.options( opts ); // Hardware instance properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; this.mode = this.firmata.MODES.ANALOG; t...
identifier_body
sonar.js
// Derived and adapted from // https://github.com/rwldrn/duino/blob/development/lib/ping.js var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function Sonar( opts ) { if ( !(this instanceof Sonar) )
var last, samples, median; last = null; samples = []; opts = Board.options( opts ); // Hardware instance properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; this.mode = this.firmata.MODES.ANALOG; this.pin = opts.pin || 0; // Sonar instance properties this.freq = o...
{ return new Sonar( opts ); }
conditional_block
sonar.js
// Derived and adapted from // https://github.com/rwldrn/duino/blob/development/lib/ping.js var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function Sonar( opts ) { if ( !(this instanceof Sonar) ) { return new Sonar( opts ); } var last, samples, median; ...
// http://www.sensorpedia.com/blog/how-to-interface-an-ultrasonic-rangefinder-with-sensorpedia-via-twitter-guide-2/
random_line_split
sonar.js
// Derived and adapted from // https://github.com/rwldrn/duino/blob/development/lib/ping.js var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function
( opts ) { if ( !(this instanceof Sonar) ) { return new Sonar( opts ); } var last, samples, median; last = null; samples = []; opts = Board.options( opts ); // Hardware instance properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; this.mode = this.firmata.MODES.AN...
Sonar
identifier_name
header.js
const assert = require("assert").ok; const constants = require("./constants"); const crypto = require("runtime-node-crypto"); const structures = require("./structures"); function
() { console.log(crypto); this.magic = constants.headerMagic; this.version = constants.version; this.hostname = "127.0.0.1"; this.port = 23; this.authMethod = 0; this.updateMS = 10000; this.key = crypto.createHash("sha512").digest("ascii"); } Header.prototype.fromBuffer = function(buffe...
Header
identifier_name
header.js
const assert = require("assert").ok; const constants = require("./constants"); const crypto = require("runtime-node-crypto"); const structures = require("./structures"); function Header() { console.log(crypto); this.magic = constants.headerMagic; this.version = constants.version; this.hostname = "127.0...
Header.prototype.fromBuffer = function(buffer) { assert(buffer instanceof Buffer,"buffer is not a Buffer Object"); var header = structures.header.unpack(buffer); assert(header.magic == constants.headerMagic,"Invalid Magic Header"); assert(header.version == constants.version,"Invalid Version"); for(v...
random_line_split
header.js
const assert = require("assert").ok; const constants = require("./constants"); const crypto = require("runtime-node-crypto"); const structures = require("./structures"); function Header()
Header.prototype.fromBuffer = function(buffer) { assert(buffer instanceof Buffer,"buffer is not a Buffer Object"); var header = structures.header.unpack(buffer); assert(header.magic == constants.headerMagic,"Invalid Magic Header"); assert(header.version == constants.version,"Invalid Version"); for...
{ console.log(crypto); this.magic = constants.headerMagic; this.version = constants.version; this.hostname = "127.0.0.1"; this.port = 23; this.authMethod = 0; this.updateMS = 10000; this.key = crypto.createHash("sha512").digest("ascii"); }
identifier_body
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for...
getblockcount
identifier_name
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode ...
word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word)))
conditional_block
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
# hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0...
static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') tar...
identifier_body
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['...
if 'hashmeter' not in settings:
random_line_split
serveurApplications.ts
import * as express from 'express'; import * as http from 'http'; import * as sysFichier from 'fs'; import { creerDateMaintenant } from "./types" import { Server } from 'ws'; /* Serveur utilisant Express http://expressjs.com/en/api.html
*/ export class Interaction { private _requete: express.Request; private _reponse: express.Response; private _suite: express.NextFunction; constructor(requete: express.Request, reponse: express.Response, suite: express.NextFunction) { this._requete = requete; this._reponse = reponse; ...
*/ /* Classe à développer
random_line_split
serveurApplications.ts
import * as express from 'express'; import * as http from 'http'; import * as sysFichier from 'fs'; import { creerDateMaintenant } from "./types" import { Server } from 'ws'; /* Serveur utilisant Express http://expressjs.com/en/api.html */ /* Classe à développer */ export class Interaction { private _requete...
servirContenuSimple(contenu: string) { this._reponse.send(contenu); } } export class ServeurApplications { private appli: express.Application; private port: number; private serveur : http.Server; constructor(port: number) { this.appli = express(); this.port = port; }...
let options = { root: chemin, }; this._reponse.sendFile(fichier, options); }
identifier_body
serveurApplications.ts
import * as express from 'express'; import * as http from 'http'; import * as sysFichier from 'fs'; import { creerDateMaintenant } from "./types" import { Server } from 'ws'; /* Serveur utilisant Express http://expressjs.com/en/api.html */ /* Classe à développer */ export class Interaction { private _requete...
ort: number) { this.appli = express(); this.port = port; } serveurHttp(): http.Server { return this.serveur; } demarrer(): void { let ceServeur = this; this.serveur = this.appli.listen(this.port, () => { console.log("* " + creerDateMa...
nstructor(p
identifier_name
sample.py
################################################################################ # Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. # # Leap Motion proprietary and confidential. Not for distribution. # # Use subject to the terms of the Leap Motion SDK Agreement available at ...
(self, controller): # Note: not dispatched when running in a debugger. print "Disconnected" def on_exit(self, controller): print "Exited" def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() pr...
on_disconnect
identifier_name
sample.py
################################################################################ # Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. # # Leap Motion proprietary and confidential. Not for distribution. # # Use subject to the terms of the Leap Motion SDK Agreement available at ...
if state == Leap.Gesture.STATE_STOP: return "STATE_STOP" if state == Leap.Gesture.STATE_INVALID: return "STATE_INVALID" def main(): # Create a sample listener and controller listener = SampleListener() controller = Leap.Controller() # Have the sample listener...
return "STATE_UPDATE"
conditional_block
sample.py
################################################################################ # Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. # # Leap Motion proprietary and confidential. Not for distribution. # # Use subject to the terms of the Leap Motion SDK Agreement available at ...
controller.add_listener(listener) # Keep this process running until Enter is pressed print "Press Enter to quit..." try: sys.stdin.readline() except KeyboardInterrupt: pass finally: # Remove the sample listener when done controller.remove_listener(listener) if ...
listener = SampleListener() controller = Leap.Controller() # Have the sample listener receive events from the controller
random_line_split
sample.py
################################################################################ # Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. # # Leap Motion proprietary and confidential. Not for distribution. # # Use subject to the terms of the Leap Motion SDK Agreement available at ...
def main(): # Create a sample listener and controller listener = SampleListener() controller = Leap.Controller() # Have the sample listener receive events from the controller controller.add_listener(listener) # Keep this process running until Enter is pressed print "Press Enter to quit.....
if state == Leap.Gesture.STATE_START: return "STATE_START" if state == Leap.Gesture.STATE_UPDATE: return "STATE_UPDATE" if state == Leap.Gesture.STATE_STOP: return "STATE_STOP" if state == Leap.Gesture.STATE_INVALID: return "STATE_INVALID"
identifier_body
msid.rs
#[doc = "Register `MSID[%s]` reader"] pub struct R(crate::R<MSID_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MSID_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MSID_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MSI...
(&self) -> INDEX_R { INDEX_R::new((self.bits & 0x3f) as u8) } } #[doc = "Message Index Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msid](index.html) module"] pub struct MSI...
index
identifier_name
msid.rs
#[doc = "Register `MSID[%s]` reader"] pub struct R(crate::R<MSID_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MSID_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MSID_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MSI...
INDEX_R::new((self.bits & 0x3f) as u8) } } #[doc = "Message Index Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msid](index.html) module"] pub struct MSID_SPEC; impl crate::R...
#[inline(always)] pub fn index(&self) -> INDEX_R {
random_line_split
json.py
import datetime import re import sys from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType from typing import Any, Callable, Dict, Typ...
def timedelta_isoformat(td: datetime.timedelta) -> str: """ ISO 8601 encoding for timedeltas. """ minutes, seconds = divmod(td.seconds, 60) hours, minutes = divmod(minutes, 60) return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
for base in obj.__class__.__mro__[:-1]: try: encoder = type_encoders[base] except KeyError: continue return encoder(obj) else: # We have exited the for loop without finding a suitable encoder return pydantic_encoder(obj)
identifier_body
json.py
import datetime import re import sys from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType from typing import Any, Callable, Dict, Typ...
from .color import Color from .types import SecretBytes, SecretStr __all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat' def isoformat(o: Union[datetime.date, datetime.time]) -> str: return o.isoformat() def decimal_encoder(dec_value: Decimal) -> Union[int, float]: """ Encode...
Pattern = re.compile('a').__class__
conditional_block
json.py
import datetime import re import sys from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType from typing import Any, Callable, Dict, Typ...
frozenset: list, deque: list, GeneratorType: list, IPv4Address: str, IPv4Interface: str, IPv4Network: str, IPv6Address: str, IPv6Interface: str, IPv6Network: str, Path: str, Pattern: lambda o: o.pattern, SecretBytes: str, SecretStr: str, set: list, UUID: str, ...
datetime.time: isoformat, datetime.timedelta: lambda td: td.total_seconds(), Decimal: decimal_encoder, Enum: lambda o: o.value,
random_line_split
json.py
import datetime import re import sys from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType from typing import Any, Callable, Dict, Typ...
(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any: # Check the class type and its superclasses for a matching encoder for base in obj.__class__.__mro__[:-1]: try: encoder = type_encoders[base] except KeyError: continue return encoder(obj) ...
custom_pydantic_encoder
identifier_name
camette.js
// RaspiCam module via node.js var rootDirectory = '/var/www/' var imageDirectory = '/timelapse_movies/' var defaultDirectory = 'default' var picturesName = 'snapshot%04d.jpg' var currentWebDirectory = imageDirectory + defaultDirectory; var fs=require('fs'); var projectName ="default"; var RaspiCam = require('raspica...
child_process.stdout.on('data', function (data) { socket.emit('mencoderStdout', data); console.log(data); dout = data; }); child_process.stderr.on('data', function (data) { console.log('stderr: ' + data); derr = data; }); child_process.on('close', function (code) { // Tell client renderi...
workingDirectory = rootDirectory + currentWebDirectory; spawn = require("child_process").spawn; var child_process = spawn('mencoder', ['mf://'+ workingDirectory +'/*.jpg', '-mf', 'fps=' + data.fps, '-o', workingDirectory+'/' + projectName + 'movie.avi', '-ovc', 'x264', '-x264encopts', 'bitrate='+data.bitrate]);
random_line_split
camette.js
// RaspiCam module via node.js var rootDirectory = '/var/www/' var imageDirectory = '/timelapse_movies/' var defaultDirectory = 'default' var picturesName = 'snapshot%04d.jpg' var currentWebDirectory = imageDirectory + defaultDirectory; var fs=require('fs'); var projectName ="default"; var RaspiCam = require('raspica...
else console.log('stopped'); console.log(projectName); // Get the project name socket.on('getProjectName', function(){ socket.emit('projectName', projectName); }); // Timelapse command socket.on('startTimelaps', function(conf){ if(!camera.lock){ var workingDirectory; currentWebDirectory = imageDir...
{ console.log('started'); socket.emit('stillWorking'); }
conditional_block
conf.js
/** * Swift-Cardinal Object Notation * https://github.com/norstone-tech/scon * * Copyright (c) BlueStone Technological Enterprises Inc., 2016-2019 * Copyright (c) Norstone Technologies 2021 * Licensed under the GNU GPLv3 license. */ /* eslint-disable no-magic-numbers, no-mixed-operators, sort-keys */ "use strict...
DATE_S: 32, DATE_MS: 33 }, OBJECT: { // Parsing variant 0 OBJECT: 0, STRING_KEY_MAP_ALT: 1, STRING_KEY_MAP: 2, // Parsing variant 1 ARRAY: 0, SET: 1, ANY_KEY_MAP: 2 } }; const VARINT_RAGES = { FLOAT_64_SAFE_INT: { MIN_VALUE: BigInt(Number.MIN_SAFE_INTEGER), MAX_VALUE: BigInt(Number.MAX_SAFE_...
UINT256: 12, SINT256: 13, INF_INT: 16, // Default
random_line_split
crumbs.js
//站点路径 js (function ($) {
var divsionClass = "gt"; //分隔符样式 var divsionChartper = "/";//分隔符字符 var crumbsClassPrefix = "level";//面包屑样式前缀 var crumbs = function(){ //判断是否启用 if(this.attr("data-enable") == "false") return; this.addClass("crumbs"); var paths = getNode(); var divsion = "<span class='"+ divsionClass +"'>"+ divs...
//配置样式 var pathStartWith = "web"; //从哪一级路径开始匹配
random_line_split
crumbs.js
//站点路径 js (function ($) { //配置样式 var pathStartWith = "web"; //从哪一级路径开始匹配 var divsionClass = "gt"; //分隔符样式 var divsionChartper = "/";//分隔符字符 var crumbsClassPrefix = "level";//面包屑样式前缀 var crumbs = function(){ //判断是否启用 if(this.attr("data-enable") == "false") return; this.addClass("crumbs"); ...
=path.split('/'); var status = 0; for(var i=0;i<arr.length;i++){ if(status==1){ nodes.push(arr[i]); } if(arr[i].indexOf(pathStartWith) != -1){ status = 1; } } return nodes; } $.fn.crumbs = crumbs; })(jQuery);
ay = function(path){ pathStartWith = pathStartWith.toLocaleLowerCase(); var nodes = []; var arr=new Array(); arr
conditional_block
grove_electricity_sensor.py
#!/usr/bin/env python # # GrovePi Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Grove_-_Electricity_Sensor) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this examp...
try: # Get sensor value sensor_value = grovepi.analogRead(sensor) # Calculate amplitude current (mA) amplitude_current = (float)(sensor_value / 1024 * grove_vcc / 800 * 2000000) # Calculate effective value (mA) effective_value = amplitude_current / 1.414 # mini...
conditional_block
grove_electricity_sensor.py
#!/usr/bin/env python # # GrovePi Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Grove_-_Electricity_Sensor) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this examp...
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ...
in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
random_line_split
main.rs
use std::error; use std::io; fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>> { let numbers = input .split_whitespace() .map(|number| number.parse()) .collect::<Result<Vec<i32>, _>>()?; if numbers.len() == 2
else { Err("Please enter 2 integers".into()) } } fn main() -> Result<(), Box<dyn error::Error>> { let mut input = String::new(); io::stdin().read_line(&mut input)?; let sum = get_sum(input)?; println!("{}", sum); Ok(()) } #[cfg(test)] mod tests { use super::get_sum; #[test] ...
{ Ok(numbers.iter().sum()) }
conditional_block
main.rs
use std::error; use std::io; fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>> { let numbers = input .split_whitespace() .map(|number| number.parse()) .collect::<Result<Vec<i32>, _>>()?; if numbers.len() == 2 { Ok(numbers.iter().sum()) } else { Err("Pl...
let output = get_sum(input); assert_eq!(output.is_err(), true); } }
let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "".to_string();
random_line_split
main.rs
use std::error; use std::io; fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>>
fn main() -> Result<(), Box<dyn error::Error>> { let mut input = String::new(); io::stdin().read_line(&mut input)?; let sum = get_sum(input)?; println!("{}", sum); Ok(()) } #[cfg(test)] mod tests { use super::get_sum; #[test] fn integer_sum_test() { let input = "2 2".to_stri...
{ let numbers = input .split_whitespace() .map(|number| number.parse()) .collect::<Result<Vec<i32>, _>>()?; if numbers.len() == 2 { Ok(numbers.iter().sum()) } else { Err("Please enter 2 integers".into()) } }
identifier_body
main.rs
use std::error; use std::io; fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>> { let numbers = input .split_whitespace() .map(|number| number.parse()) .collect::<Result<Vec<i32>, _>>()?; if numbers.len() == 2 { Ok(numbers.iter().sum()) } else { Err("Pl...
() { let input = "2 1T".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "2 2.4".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); } #[test] fn bad_length_test() { let input = "2 1 1"...
bad_parsing_test
identifier_name
appLoader.js
/* Copyright (c) 2017 Jirtdan Team and other collaborators Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, ...
}); $('#btn-unselect').click(function(event) { board.unselect(); }); });
{ board.deleteSelected(); }
conditional_block
appLoader.js
/* Copyright (c) 2017 Jirtdan Team and other collaborators Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, ...
}); $('#btn-unselect').click(function(event) { board.unselect(); }); });
board.deleteSelected(); }
random_line_split
boot.browser.ts
import 'bootstrap'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module.browser'; import { SnotifyService } from "ng-snotify"; import { AuthService } from "./app/services/auth.service"; import { AuthGuard...
///<reference types="webpack-env" /> import 'reflect-metadata'; import 'zone.js';
random_line_split
boot.browser.ts
///<reference types="webpack-env" /> import 'reflect-metadata'; import 'zone.js'; import 'bootstrap'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module.browser'; import { SnotifyService } from "ng-snoti...
else { enableProdMode(); } // Note: @ng-tools/webpack looks for the following expression when performing production // builds. Don't change how this line looks, otherwise you may break tree-shaking. const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule, { providers: [SnotifyService, AuthService...
{ module.hot.accept(); module.hot.dispose(() => { // Before restarting the app, we create a new root element and dispose the old one const oldRootElem = document.querySelector('app'); const newRootElem = document.createElement('app'); oldRootElem!.parentNode!.insertBefore(newRoot...
conditional_block
fn.rs
struct S(A); // Concrete type `S`. struct SGen<T>(T); // Generic type `SGen`. // The following functions all take ownership of the variable passed into // them and immediately go out of scope, freeing the variable. // Define a function `reg_fn` that takes an argument `_s` of type `S`. // This has no `<T>` so th...
struct A; // Concrete type `A`.
random_line_split
fn.rs
struct
; // Concrete type `A`. struct S(A); // Concrete type `S`. struct SGen<T>(T); // Generic type `SGen`. // The following functions all take ownership of the variable passed into // them and immediately go out of scope, freeing the variable. // Define a function `reg_fn` that takes an argument `_s` of typ...
A
identifier_name
json_parser.py
import json import copy formtable = {"name":[u'name'], "gender":[u'gender'], "contact":[u'contact'], "address":[u'address']} def is_reserved_layer(dict,reserved_word): for key in dict: if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]: ...
elif type(source)==list: for item in source: if(type(item)==dict): json_reduce_structure(item) def json_write(source,list,reserved_word): if(len(source)==1): #if the source is the list item in the source list, append it to the dest list list.append(source[0]...
for key in source: if(type(source[key])==list and len(source[key])==1): source[key] = source[key][0] json_reduce_structure(source[key])
conditional_block
json_parser.py
import json import copy formtable = {"name":[u'name'], "gender":[u'gender'], "contact":[u'contact'], "address":[u'address']} def is_reserved_layer(dict,reserved_word): for key in dict: if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]: ...
for item in newlist: print item thelist = [[u'Patient', 'PRIVACY_POLICY_JSON_PARSOR_LAYER_MARK0', 'PRIVACY_POLICY_JSON_PARSOR_LAYER_MARK0', u'name'], [u'Patient', 'PRIVACY_POLICY_JSON_PARSOR_LAYER_MARK0', 'PRIVACY_POLICY_JSON_PARSOR_LAYER_MARK2', u'text'], [u'Patient', 'PRIVACY_POLICY_JSON_PARSOR_LAYER...
reserved_word = 'PRIVACY_POLICY_JSON_PARSOR_LAYER_MARK' s = json.loads( ''' { "resourceType": "Patient", "text": { "status": "generated", "div": "<div><p>Freda Penn</p ></div>" }, "name": { "text": "Protected data due to privacy policy" }, "gender": "female" ...
identifier_body
json_parser.py
import json import copy formtable = {"name":[u'name'], "gender":[u'gender'], "contact":[u'contact'], "address":[u'address']} def is_reserved_layer(dict,reserved_word): for key in dict: if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]: ...
(policy, raw): ''' :param policy: a list to identify a item of patient's info, the policy[-1] is the attribute of the item :param raw: result of json2list() :return: return processed patient's info ''' newlist = policy not_found_flag = True for item in raw: if listequal(policy[...
retrieve
identifier_name
json_parser.py
import json import copy
formtable = {"name":[u'name'], "gender":[u'gender'], "contact":[u'contact'], "address":[u'address']} def is_reserved_layer(dict,reserved_word): for key in dict: if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]: return True ...
random_line_split
main.js
let _ = require('lodash') let co = require('co') let requireAll = require('require-all') /* global VERSION */ let commands = requireAll({ dirname: `${__dirname}/commands` }) let HELPTEXT = ` Thinker ${VERSION} ============================== A RethinkDB command line tool. Commands: thinker clone ...
else { console.log(HELPTEXT) } process.exit() }) .catch(function (err) { console.log('ERROR') console.log(err) }) }
{ yield commands[command](argv) }
conditional_block
main.js
let _ = require('lodash') let co = require('co') let requireAll = require('require-all') /* global VERSION */ let commands = requireAll({ dirname: `${__dirname}/commands` }) let HELPTEXT = ` Thinker ${VERSION} ============================== A RethinkDB command line tool. Commands: thinker clone ...
}) }
random_line_split
stickyMojo.js
(function($) { $.fn.extend({ stickyMojo: function(options) { // Exit if there are no elements to avoid errors: if (this.length === 0) { return this; } var settings = $.extend({ 'footerID': '', 'contentID': '', 'orientation': $(this).css('float'...
} ieVersion() && errors.push("NO IE 7"); return errors; } function ieVersion() { if(document.querySelector) { return false; } else { return true; } } } }); })(jQuery);
{ errors.push(settings[key]); }
conditional_block
stickyMojo.js
(function($) { $.fn.extend({ stickyMojo: function(options) { // Exit if there are no elements to avoid errors: if (this.length === 0) { return this; } var settings = $.extend({ 'footerID': '', 'contentID': '', 'orientation': $(this).css('float'...
() { var errors = []; for (var key in settings) { if (!settings[key]) { errors.push(settings[key]); } } ieVersion() && errors.push("NO IE 7"); return errors; } function ieVersion() { if(document.querySelector) { ...
checkSettings
identifier_name
stickyMojo.js
(function($) { $.fn.extend({ stickyMojo: function(options) { // Exit if there are no elements to avoid errors: if (this.length === 0) { return this; } var settings = $.extend({ 'footerID': '', 'contentID': '', 'orientation': $(this).css('float'...
} } // sets sidebar to a static positioned element function setStaticSidebar() { sticky.el.css({ 'position': 'static', 'margin-left': '0px' }); settings.contentID.css('margin-left', '0px'); } // initiated to stop the sidebar...
random_line_split
stickyMojo.js
(function($) { $.fn.extend({ stickyMojo: function(options) { // Exit if there are no elements to avoid errors: if (this.length === 0) { return this; } var settings = $.extend({ 'footerID': '', 'contentID': '', 'orientation': $(this).css('float'...
// initiated to stop the sidebar from intersecting the footer function setLimitedSidebar(diff) { sticky.el.css({ top: diff }); } //determines whether sidebar should stick and applies appropriate settings to make it stick function stick() { va...
{ sticky.el.css({ 'position': 'static', 'margin-left': '0px' }); settings.contentID.css('margin-left', '0px'); }
identifier_body
bigquery_sensor.py
# -*- coding: utf-8 -*- # # 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 #...
from airflow.gcp.sensors.bigquery import BigQueryTableSensor # noqa warnings.warn( "This module is deprecated. Please use `airflow.gcp.sensors.bigquery`.", DeprecationWarning, stacklevel=2 )
random_line_split
utils.js
/* * This file is part of the Doodle3D project (http://doodle3d.com). * * Copyright (c) 2013, Doodle3D * This software is licensed under the terms of the GNU GPL v2 or later. * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. */ // http://stackoverflow.com/questions/14...
else { returnBool = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini|Windows Mobile/i.test(navigator.userAgent) } return returnBool; } function distance(x1, y1, x2, y2) { return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); }
{ var w = $(window).width() / window.devicePixelRatio; console.log("Android device >> ratio'd width: " + w); if (w < 480) { returnBool = true; } }
conditional_block
utils.js
/* * This file is part of the Doodle3D project (http://doodle3d.com). * * Copyright (c) 2013, Doodle3D * This software is licensed under the terms of the GNU GPL v2 or later. * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. */ // http://stackoverflow.com/questions/14...
(name) { return decodeURI( (new RegExp('[&?]'+name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] ); } // returns true for all smartphones and tablets function isMobileDevice() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Mobile/i.test(navigator.userAgent); } // ...
getURLParameter
identifier_name
utils.js
/* * This file is part of the Doodle3D project (http://doodle3d.com). * * Copyright (c) 2013, Doodle3D * This software is licensed under the terms of the GNU GPL v2 or later. * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. */ // http://stackoverflow.com/questions/14...
function distance(x1, y1, x2, y2) { return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); }
{ var returnBool = false; if( /Android/i.test(navigator.userAgent) && window.devicePixelRatio > 1) { var w = $(window).width() / window.devicePixelRatio; console.log("Android device >> ratio'd width: " + w); if (w < 480) { returnBool = true; } } else { returnBool = /Android|webOS|iPhone|...
identifier_body
utils.js
/* * This file is part of the Doodle3D project (http://doodle3d.com). * * Copyright (c) 2013, Doodle3D * This software is licensed under the terms of the GNU GPL v2 or later. * See file LICENSE.txt or visit http://www.gnu.org/licenses/gpl.html for full license details. */ // http://stackoverflow.com/questions/14...
function distance(x1, y1, x2, y2) { return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); }
random_line_split
issue-8898.rs
// Copyright 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-MIT or ...
let slice = &x[0..1]; assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); assert_repr_eq(&x[], "[(), ()]".to_string()); assert_repr_eq(slice, "[()]".to_string()); assert_repr_eq(&x[], "[(), ()]".to_string()); }
random_line_split
issue-8898.rs
// Copyright 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-MIT or ...
{ let abc = [1i, 2, 3]; let tf = [true, false]; let x = [(), ()]; let slice = &x[0..1]; assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); assert_repr_eq(&x[], "[(), ()]".to_string()); assert_repr_eq(slice, "[()]".to_string()); a...
identifier_body
issue-8898.rs
// Copyright 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-MIT or ...
() { let abc = [1i, 2, 3]; let tf = [true, false]; let x = [(), ()]; let slice = &x[0..1]; assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); assert_repr_eq(&x[], "[(), ()]".to_string()); assert_repr_eq(slice, "[()]".to_string()); ...
main
identifier_name
singleton.rs
extern crate qmlrs; extern crate libc; use qmlrs::*; #[test] pub fn
() { let mut engine = qmlrs::Engine::new("name"); extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) { println!("id: {}",id); if id == 2 { Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]); } } ...
singleton_test
identifier_name
singleton.rs
extern crate qmlrs; extern crate libc; use qmlrs::*; #[test] pub fn singleton_test()
obj.as_ptr() } register_singleton_type(&"Test",1,2,&"Person",singleton); engine.load_local_file("tests/singleton.qml"); engine.exec(); }
{ let mut engine = qmlrs::Engine::new("name"); extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) { println!("id: {}",id); if id == 2 { Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]); } } ...
identifier_body
singleton.rs
extern crate qmlrs; extern crate libc; use qmlrs::*; #[test] pub fn singleton_test() { let mut engine = qmlrs::Engine::new("name"); extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) { println!("id: {}",id); if id == 2
} extern "C" fn singleton(_: *mut ffi::QQmlEngine, _: *mut ffi::QJSEngine) -> *mut ffi::QObject { let mut metaobj = MetaObject::new("Person",slot); assert_eq!(metaobj.add_signal("nameChanged()"),0); assert_eq!(metaobj.add_signal("testSignal(QString)"),1); metaobj.add_property("...
{ Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]); }
conditional_block
singleton.rs
extern crate qmlrs; extern crate libc; use qmlrs::*; #[test] pub fn singleton_test() { let mut engine = qmlrs::Engine::new("name"); extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) { println!("id: {}",id); if id == 2 { ...
assert_eq!(metaobj.add_signal("testSignal(QString)"),1); metaobj.add_property("name","QString",Some("nameChanged()")); assert_eq!(metaobj.add_method("test()","void"),2); let mut obj = metaobj.instantiate(); obj.set_property("name",Variant::String("Kai".to_string())); obj...
} extern "C" fn singleton(_: *mut ffi::QQmlEngine, _: *mut ffi::QJSEngine) -> *mut ffi::QObject { let mut metaobj = MetaObject::new("Person",slot); assert_eq!(metaobj.add_signal("nameChanged()"),0);
random_line_split
browse.js
import Browsable from 'appkit/libs/browsable'; var LtiAppBrowseController = Ember.ObjectController.extend({ isLoaded : true, targetRoute: 'ltiApp.browseDetails', showDashboard: function() { return Ember.isEmpty(Ember.ENV.TOOL_ID); }.property('Ember.ENV.TOOL_ID'), parentFolderChain: function() { if ...
}, goUpFolder: function() { var newFolderChain = this.get('parentFolderChain'); this.transitionToRoute('ltiApp.browse', { folderChain: newFolderChain }); }, goToItem: function(item) { this.transitionToRoute('ltiApp.browseDetails', { folderChain: this.get('folderChain'), item: item })...
random_line_split
browse.js
import Browsable from 'appkit/libs/browsable'; var LtiAppBrowseController = Ember.ObjectController.extend({ isLoaded : true, targetRoute: 'ltiApp.browseDetails', showDashboard: function() { return Ember.isEmpty(Ember.ENV.TOOL_ID); }.property('Ember.ENV.TOOL_ID'), parentFolderChain: function() { if ...
}.property('folderChain'), currentFolder: function() { return this.get('folderChain').split('.').pop(); }.property('folderChain'), loadData: function() { var _this = this; this.set('isLoaded', false); Browsable.findFolder( this.get('ltiApp.toolId'), this.get('currentFolder'), ...
{ return this.get('folderChain').split('.').pop(); }
conditional_block