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
tweet-dump.py
""" Copyright (c) 2012 Casey Dunham <casey.dunham@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
(Exception): @property def message(self): return self.args[0] class RateLimitError(TweetDumpError): pass API_URL = "https://api.twitter.com/1/statuses/user_timeline.json?%s" # we are not authenticating so this will return the rate limit based on our IP # see (https://dev.twitter.com/docs/api/1/g...
TweetDumpError
identifier_name
tweet-dump.py
""" Copyright (c) 2012 Casey Dunham <casey.dunham@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
break print "[*] %d tweets dumped!" % tweet_count
(remaining, rst_time_s, rst_time) = get_initial_rate_info() while remaining > 0: try: (remaining, tweets) = get_tweets(screen_name, count, maxid) except RateLimitError: pass except TweetDumpError, e: pass else: ...
conditional_block
tweet-dump.py
""" Copyright (c) 2012 Casey Dunham <casey.dunham@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
while True: # get initial rate information (remaining, rst_time_s, rst_time) = get_initial_rate_info() while remaining > 0: try: (remaining, tweets) = get_tweets(screen_name, count, maxid) except RateLimitError: pass except...
random_line_split
post.js
(function() { var Post, create, edit; Post = function() { this.title = ""; this.content = ""; this.author = ""; this.categories = []; this.tags = []; this.date = ""; this.modified = ""; return this.published = true; }; create = function(title, content, categories, tags, publish...
tags = tags; published = published; modified = Date.now(); return post; }; exports.create = create; exports.edit = edit; }).call(this);
content = content; categories = categories;
random_line_split
rscope.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, _: Span, count: uint) -> Result<Vec<ty::Region>,()> { Ok(Vec::from_elem(count, self.region.clone())) } }
anon_regions
identifier_name
rscope.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
random_line_split
parser.js
//process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); }); var fs = require('fs'); (function () { function slugify(text) { text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); return text; } var DocGen = { ...
self.fileLoaded(); }); }, sortFunctions: function (fun1, fun2) { var name1 = fun1.name.toLowerCase(); var name2 = fun2.name.toLowerCase(); if (name1 < name2) { return -1; } else if (name1 > name2) { return 1; } else { return 0; } }, ...
random_line_split
parser.js
//process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); }); var fs = require('fs'); (function () { function slugify(text)
var DocGen = { filesArr: null, files: {}, functions: [], nbLoaded: 0, init: function (files) { this.filesArr = files; }, start: function () { for (var i=0, len=this.filesArr.length; i<len; i++) { var file = this.filesArr[i]; this.processFile(file); ...
{ text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); return text; }
identifier_body
parser.js
//process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); }); var fs = require('fs'); (function () { function
(text) { text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); return text; } var DocGen = { filesArr: null, files: {}, functions: [], nbLoaded: 0, init: function (files) { this.filesArr = files; }, start:...
slugify
identifier_name
parser.js
//process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); }); var fs = require('fs'); (function () { function slugify(text) { text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); return text; } var DocGen = { ...
return signatures; }, extractInfos: function (m) { var self = this; var fun = m[2]; var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi; var isFun = rFun.exec(fun); if (!isFun) { rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\...
{ var params = []; var rParam = /(\w+):(\w+)/gi; while (param = rParam.exec(sig[1])) { var name = param[1]; var type = param[2]; params.push({ name: name, type: type }); } if (params.length >= 1) { ret = params.pop(); ...
conditional_block
player.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Rodrigo Silva (MestreLion) <linux@rodrigosilva.com> # # 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, ...
@property def metabolism(self): '''How much food is consumed every turn. Depends on current food, worn rings and screen width. Some rings have random consumption, so this value may change on every read! ''' deltafood = 1 if self.food <= HUNG...
return "" # All fine :)
conditional_block
player.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Rodrigo Silva (MestreLion) <linux@rodrigosilva.com> # # 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, ...
(self, dr, dc): row = self.row + dr col = self.col + dc if not self.level.is_passable(row, col): return # Update current tile self.level.reveal(self.row, self.col) # Update to new position self.row = row self.col = col self.level.dra...
move
identifier_name
player.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Rodrigo Silva (MestreLion) <linux@rodrigosilva.com> # # 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, ...
# Map and position self.level = None self.row = 0 self.col = 0 # Items self.armor = None # Worn armor self.weapon = None # Wielded weapon self.ringright = None # Ring on right hand self.ringleft = None # Ring on left hand self...
# Input and output self.screen = screen
random_line_split
player.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Rodrigo Silva (MestreLion) <linux@rodrigosilva.com> # # 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, ...
self.str = 16 # Current strength self.strmax = 16 # Maximum strength self.gold = 0 # Gold (purse) self.xp = 0 # Experience points self.xplevel = 1 # Experience level # Food left in stomach. Fixed 1250 in Unix self.food = r...
self.name = name # Input and output self.screen = screen # Map and position self.level = None self.row = 0 self.col = 0 # Items self.armor = None # Worn armor self.weapon = None # Wielded weapon self.ringright = None # Ring on ...
identifier_body
cli_options.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export declare class CliOptions { basePath: string; constructor({basePath}: { basePath?: string; ...
extends CliOptions { i18nFormat: string | null; locale: string | null; outFile: string | null; constructor({i18nFormat, locale, outFile}: { i18nFormat?: string; locale?: string; outFile?: string; }); } export declare class NgcCliOptions extends CliOptions { i18nFormat: s...
I18nExtractionCliOptions
identifier_name
cli_options.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export declare class CliOptions { basePath: string; constructor({basePath}: { basePath?: string; ...
}); } export declare class NgcCliOptions extends CliOptions { i18nFormat: string; i18nFile: string; locale: string; missingTranslation: string; constructor({i18nFormat, i18nFile, locale, missingTranslation, basePath}: { i18nFormat?: string; i18nFile?: string; locale?: str...
locale?: string; outFile?: string;
random_line_split
edit-rule-setformat.component.ts
You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See...
Public Method - API |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * When timestamp format is selected * @param data */ public selectItem(data) { this.selectedTimestamp = data.value; } /** * Get timestamp formats from server */ private getTimestampFormats() { if (!this.isG...
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= |
identifier_body
edit-rule-setformat.component.ts
may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the...
d or this.selectedTimestamp is not empty this.selectedTimestamp = this.tempTimetampValue; if (cols.length > 0 || '' !== this.tempTimetampValue) { if ('' === this.tempTimetampValue && this.selectedFields[0]) { const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name...
r: false, matchValue: result[keyList[0]][i]}) } } // When at least one column is selecte
conditional_block
edit-rule-setformat.component.ts
You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See...
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Before component is shown * @protected */ protected beforeShowComp() { this.fields = this.fields.filter((item) => { return item.type === 'TIMESTAMP' }); ...
this.isFocus = isShow; } // function - showHidePatternLayer
random_line_split
edit-rule-setformat.component.ts
may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the...
electedFields = data.selectedList; this.selectedTimestamp = ''; if (0 === this.selectedFields.length) { // if theres nothing selected this.selectedTimestamp = ''; this.defaultIndex = -1; } else { this.getTimestampFormats(); } } // function - changeFields /** * 패턴 정보 레이어 표시 ...
{ this.s
identifier_name
treena.js
(function($) { var digestQueued = false; var digestRunning = false; var queueDigest = function() { if (!digestQueued) { digestQueued = true; if (!digestRunning) { setTimeout(function() { var maxIters = 10; digestRunnin...
treena.settable = function(name, onchange) { var statev = undefined; return function (n) { if (arguments.length === 0) { return statev; } else if (statev !== n) { statev = n; onchange && onchange(); treena.digest...
}); };
random_line_split
treena.js
(function($) { var digestQueued = false; var digestRunning = false; var queueDigest = function() { if (!digestQueued) { digestQueued = true; if (!digestRunning) { setTimeout(function() { var maxIters = 10; digestRunnin...
} return $e; }; var nodeNames = [ 'table', 'tbody','thead', 'tr', 'th', 'td', 'a', 'strong', 'div', 'img', 'br', 'b', 'span', 'li', 'ul', 'ol', 'iframe', 'form', 'h1', 'input', 'h2', 'h3', 'h4','h5','h6', 'p', 'br', 'select', 'option', 'optgroup', ...
{ $e.click(f); }
conditional_block
borrowck-borrow-overloaded-auto-deref-mut.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn deref_imm_field(x: Own<Point>) { let _i = &x.y; } fn deref_mut_field1(x: Own<Point>) { let _i = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Own<Point>) { let _i = &mut x.y; } fn deref_extend_field<'a>(x: &'a Own<Point>) -> &'a int { &x.y } fn deref_extend_mut_field1<'a>(x: ...
{ &mut self.y }
identifier_body
borrowck-borrow-overloaded-auto-deref-mut.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(x: &'a mut Own<Point>) { x.y = 3; } fn assign_field4<'a>(x: &'a mut Own<Point>) { let _p: &mut Point = &mut **x; x.y = 3; //~ ERROR cannot borrow } // FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut. /* fn deref_imm_method(x: Own<Point>) { let _i = x.get(); } */ fn deref_mut_method1...
assign_field3
identifier_name
borrowck-borrow-overloaded-auto-deref-mut.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn assign_method1<'a>(x: Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Own<Point>) { *x.y_mut() = 3; } pub fn main() {}
fn deref_extend_mut_method2<'a>(x: &'a mut Own<Point>) -> &'a mut int { x.y_mut() }
random_line_split
test_t1197_telem.py
import json import pytest from common.utils.attack_utils import ScanStatus from infection_monkey.model import VictimHost from infection_monkey.telemetry.attack.t1197_telem import T1197Telem DOMAIN_NAME = "domain-name" IP = "127.0.0.1" MACHINE = VictimHost(IP, DOMAIN_NAME) STATUS = ScanStatus.USED USAGE_STR = "[Usage...
def test_T1197_send(T1197_telem_test_instance, spy_send_telemetry): T1197_telem_test_instance.send() expected_data = { "status": STATUS.value, "technique": "T1197", "machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP}, "usage": USAGE_STR, } expected_data = json.dumps(ex...
random_line_split
test_t1197_telem.py
import json import pytest from common.utils.attack_utils import ScanStatus from infection_monkey.model import VictimHost from infection_monkey.telemetry.attack.t1197_telem import T1197Telem DOMAIN_NAME = "domain-name" IP = "127.0.0.1" MACHINE = VictimHost(IP, DOMAIN_NAME) STATUS = ScanStatus.USED USAGE_STR = "[Usage...
(): return T1197Telem(STATUS, MACHINE, USAGE_STR) def test_T1197_send(T1197_telem_test_instance, spy_send_telemetry): T1197_telem_test_instance.send() expected_data = { "status": STATUS.value, "technique": "T1197", "machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP}, "us...
T1197_telem_test_instance
identifier_name
test_t1197_telem.py
import json import pytest from common.utils.attack_utils import ScanStatus from infection_monkey.model import VictimHost from infection_monkey.telemetry.attack.t1197_telem import T1197Telem DOMAIN_NAME = "domain-name" IP = "127.0.0.1" MACHINE = VictimHost(IP, DOMAIN_NAME) STATUS = ScanStatus.USED USAGE_STR = "[Usage...
T1197_telem_test_instance.send() expected_data = { "status": STATUS.value, "technique": "T1197", "machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP}, "usage": USAGE_STR, } expected_data = json.dumps(expected_data, cls=T1197_telem_test_instance.json_encoder) assert spy_...
identifier_body
contact.py
def post(self): to = self.request.get("to") user_name = self.request.get("name") user_address = self.request.get("email") subject = self.request.get("subject") body = self.request.get("message") behalf_of = user_name + " <" + user_address +">" sender_address ...
from google.appengine.api import mail import json import webapp2 class SendEmail(webapp2.RequestHandler):
random_line_split
contact.py
from google.appengine.api import mail import json import webapp2 class SendEmail(webapp2.RequestHandler): def post(self): to = self.request.get("to") user_name = self.request.get("name") user_address = self.request.get("email") subject = self.request.get("subject") body = se...
mail.send_mail(sender= sender_address, to = to, #cc = behalf_of, reply_to = behalf_of, subject = subject+" | "+user_name+" | "+user_address, body = body, headers = {"On-Behalf-Of":behalf_of}) self.respons...
return
conditional_block
contact.py
from google.appengine.api import mail import json import webapp2 class SendEmail(webapp2.RequestHandler): def
(self): to = self.request.get("to") user_name = self.request.get("name") user_address = self.request.get("email") subject = self.request.get("subject") body = self.request.get("message") behalf_of = user_name + " <" + user_address +">" sender_address ="CB Contact...
post
identifier_name
contact.py
from google.appengine.api import mail import json import webapp2 class SendEmail(webapp2.RequestHandler):
headers = {"On-Behalf-Of":behalf_of}) self.response.out.write(json.dumps({"done":"true"}))
def post(self): to = self.request.get("to") user_name = self.request.get("name") user_address = self.request.get("email") subject = self.request.get("subject") body = self.request.get("message") behalf_of = user_name + " <" + user_address +">" sender_address ="CB...
identifier_body
get.rs
use super::with_path; use util::*; use hyper::client::Response; use hyper::status::StatusCode; fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) { with_path(&format!("/get?{}", query), f) } fn assert_accepted(query: &str) { with_query(query, |res| { let s = read_body_to_string(res); ...
() { assert_accepted("state=valid&state=foo") } } mod rejects { use super::assert_rejected; #[test] fn invalid() { assert_rejected("state=foo") } #[test] fn other_keys() { assert_rejected("valid=valid") } #[test] fn empty() { assert_rejected(""...
first_valid
identifier_name
get.rs
use super::with_path; use util::*; use hyper::client::Response; use hyper::status::StatusCode; fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) { with_path(&format!("/get?{}", query), f) } fn assert_accepted(query: &str) { with_query(query, |res| { let s = read_body_to_string(res); ...
} mod rejects { use super::assert_rejected; #[test] fn invalid() { assert_rejected("state=foo") } #[test] fn other_keys() { assert_rejected("valid=valid") } #[test] fn empty() { assert_rejected("") } #[test] fn second_valid() { assert...
{ assert_accepted("state=valid&state=foo") }
identifier_body
get.rs
use super::with_path; use util::*; use hyper::client::Response; use hyper::status::StatusCode; fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) { with_path(&format!("/get?{}", query), f) } fn assert_accepted(query: &str) { with_query(query, |res| { let s = read_body_to_string(res); ...
#[test] fn invalid() { assert_rejected("state=foo") } #[test] fn other_keys() { assert_rejected("valid=valid") } #[test] fn empty() { assert_rejected("") } #[test] fn second_valid() { assert_rejected("state=foo&state=valid") } }
use super::assert_rejected;
random_line_split
test_drive.py
import os, sys import tempfile import unittest as unittest0 try: unittest0.skipUnless unittest0.skip except AttributeError: import unittest2 as unittest else: unittest = unittest0 del unittest0 import win32file from winsys import fs class TestDrive (unittest.TestCase): # # The name of the drive should b...
# pass if __name__ == "__main__": unittest.main () if sys.stdout.isatty (): raw_input ("Press enter...")
# # Likewise difficult to test because destructive
random_line_split
test_drive.py
import os, sys import tempfile import unittest as unittest0 try: unittest0.skipUnless unittest0.skip except AttributeError: import unittest2 as unittest else: unittest = unittest0 del unittest0 import win32file from winsys import fs class TestDrive (unittest.TestCase): # # The name of the drive should b...
@unittest.skip ("Skip destructive test") def test_mount (self): # # Difficult to test because it's not possible # to mount a volume on two drive letters simultaneously. # Try to find something unimportant, like a CDROM, and # dismount it before remounting it. # pass @unittest.skip (...
self.assertEquals (fs.drive ("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint ("C:\\"))
identifier_body
test_drive.py
import os, sys import tempfile import unittest as unittest0 try: unittest0.skipUnless unittest0.skip except AttributeError: import unittest2 as unittest else: unittest = unittest0 del unittest0 import win32file from winsys import fs class TestDrive (unittest.TestCase): # # The name of the drive should b...
raw_input ("Press enter...")
conditional_block
test_drive.py
import os, sys import tempfile import unittest as unittest0 try: unittest0.skipUnless unittest0.skip except AttributeError: import unittest2 as unittest else: unittest = unittest0 del unittest0 import win32file from winsys import fs class TestDrive (unittest.TestCase): # # The name of the drive should b...
(self): self.assertEquals (fs.drive ("C:").type, win32file.GetDriveTypeW ("C:")) def test_DriveRoot (self): self.assertEquals (fs.drive ("C:").root, fs.dir ("C:\\")) def test_volume (self): self.assertEquals (fs.drive ("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint ("C:\\")) @unitte...
test_DriveType
identifier_name
test_protocols.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc import RPCErrorResponse @pytest.fixture(params=['jsonrpc']) def protocol(request): if 'jsonrpc': return JSONRPCProtocol() raise RuntimeError('Bad protocol name in test case...
def test_one_way(protocol): req = protocol.create_request('foo', None, {'a': 'b'}, True) assert req.respond(None) == None def test_raises_on_args_and_kwargs(protocol): with pytest.raises(Exception): protocol.create_request('foo', ['arg1', 'arg2'], {'kw_key': 'kw_value'}) def test_supports_no_ar...
random_line_split
test_protocols.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc import RPCErrorResponse @pytest.fixture(params=['jsonrpc']) def protocol(request): if 'jsonrpc': return JSONRPCProtocol() raise RuntimeError('Bad protocol name in test case...
def test_default_id_generator(): from tinyrpc.protocols import default_id_generator g = default_id_generator(1) assert next(g) == 1 assert next(g) == 2 assert next(g) == 3
req = protocol.create_request('foo', ['bar']) err_rep = req.error_respond(Exception('foo')) parsed = protocol.parse_reply(err_rep.serialize()) assert hasattr(parsed, 'error')
identifier_body
test_protocols.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc import RPCErrorResponse @pytest.fixture(params=['jsonrpc']) def protocol(request): if 'jsonrpc': return JSONRPCProtocol() raise RuntimeError('Bad protocol name in test case...
(protocol): req = protocol.create_request('foo', ['bar']) err_rep = req.error_respond(Exception('foo')) parsed = protocol.parse_reply(err_rep.serialize()) assert hasattr(parsed, 'error') def test_default_id_generator(): from tinyrpc.protocols import default_id_generator g = default_id_generat...
test_parses_error_response
identifier_name
test_protocols.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc import RPCErrorResponse @pytest.fixture(params=['jsonrpc']) def protocol(request): if 'jsonrpc':
raise RuntimeError('Bad protocol name in test case') def test_protocol_returns_bytes(protocol): req = protocol.create_request('foo', ['bar']) assert isinstance(req.serialize(), bytes) def test_procotol_responds_bytes(protocol): req = protocol.create_request('foo', ['bar']) rep = req.respond(42...
return JSONRPCProtocol()
conditional_block
create-post.component.ts
import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material'; import { CreatePost, File } from '../../model'; import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services'; import { Creat...
(value: boolean) { this.internalIsLoading = value; } public set postText(value: string) { this.internalPostText = value; } public get postText(): string { return this.internalPostText; } public onFilePreview(): void { if (this.selectedFile) { this.isLoading = true; this.fileSe...
isLoading
identifier_name
create-post.component.ts
import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material'; import { CreatePost, File } from '../../model'; import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services'; import { Creat...
} public onNoClick(): void { this.dialogRef.close(-1); } public closeDialog(): void { this.dialogRef.close(-1); } public removeFile(): void { this.selectedFile = undefined; } public addFile(): void { const dialogRef = this.dialog.open(CreateFileComponent, { width: '60%' })...
{ this.isLoading = true; this.fileService.getFile(this.selectedFile).then(x => { this.isLoading = false; this.dialog.open(FileDialogComponent, { width: '70%', data: { file: <File>x } }); }); }
conditional_block
create-post.component.ts
import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material'; import { CreatePost, File } from '../../model'; import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services'; import { Creat...
}
{ const location = await this.locationService.getLocation(); return new CreatePost(this.postText, <number>location['latitude'], <number>location['longitude']); }
identifier_body
create-post.component.ts
import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material'; import { CreatePost, File } from '../../model'; import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services'; import { Creat...
selector: 'app-create-post', templateUrl: './create-post.component.html', styleUrls: ['./create-post.component.css'] }) export class CreatePostComponent { private internalIsLoading = false; private internalPostText = ''; private selectedFile: number | undefined = undefined; @Output() private postCreated...
@Component({
random_line_split
bounty.py
when reward is 0) TDL -- More to be defined in later versions """ def __repr__(self): """Gives a string representation of the bounty""" output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward) output = output + ", id=" + str(self.ide...
(address): try: import socket socket.getaddrinfo(*address) a = len(address[0].split(":")) == 1 # Make sure it's not ipv6 b = len(address[0].split(".")) == 4 # Make sure it's not shortened return a and b and address[1] in range(49152) except: return False def v...
checkIPAddressValid
identifier_name
bounty.py
when reward is 0) TDL -- More to be defined in later versions """ def __repr__(self): """Gives a string representation of the bounty""" output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward) output = output + ", id=" + str(self.ide...
def __le__(self, other): """Determines whether this bounty has a lower priority or is equal""" boolean = self.__lt__(other) if boolean: return boolean else: return self.__eq__(other) def __ge__(self, other): """Determines whether this bounty has...
"""Determines whether this bounty has a higher priority""" try: if self.reward > other.reward: return True elif self.timeout > other.timeout: return True else: return False except: return other is None
identifier_body
bounty.py
output = output + ", id=" + str(self.ident) + ", timeout=" + str(self.timeout) output = output + ", author=" + str(self.data.get('author')) if self.data.get('reqs') != {} and isinstance(self.data.get('reqs'), dict): output = output + ", reqs=" + str(sorted(self.data.get('reqs').items...
"""Handles the potential errors in unpickling a bounty""" if isinstance(string, Bounty): return string
random_line_split
bounty.py
when reward is 0) TDL -- More to be defined in later versions """ def __repr__(self): """Gives a string representation of the bounty""" output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward) output = output + ", id=" + str(self.ide...
def __hash__(self): return hash((self.__repr__(), str(self.data))) def __init__(self, ipAddress, btcAddress, rewardAmount, **kargs): """Initialize a Bounty; constructor""" self.ip = ipAddress self.btc = btcAddress self.reward = rewardAmount self.ident = '' ...
return self.__eq__(other)
conditional_block
record_type.rs
use crate::library; #[derive(PartialEq, Eq)] pub enum
{ /// Boxed record that use g_boxed_copy, g_boxed_free. /// Must have glib_get_type function AutoBoxed, /// Boxed record with custom copy/free functions Boxed, /// Referencecounted record Refcounted, //TODO: detect and generate direct records //Direct, } impl RecordType { pub f...
RecordType
identifier_name
record_type.rs
use crate::library; #[derive(PartialEq, Eq)] pub enum RecordType { /// Boxed record that use g_boxed_copy, g_boxed_free. /// Must have glib_get_type function AutoBoxed, /// Boxed record with custom copy/free functions Boxed, /// Referencecounted record Refcounted, //TODO: detect and gen...
if has_ref && has_unref { RecordType::Refcounted } else if has_copy && has_free { RecordType::Boxed } else { RecordType::AutoBoxed } } }
{ let mut has_copy = false; let mut has_free = false; let mut has_ref = false; let mut has_unref = false; let mut has_destroy = false; for func in &record.functions { match &func.name[..] { "copy" => has_copy = true, "free" => h...
identifier_body
record_type.rs
use crate::library; #[derive(PartialEq, Eq)] pub enum RecordType { /// Boxed record that use g_boxed_copy, g_boxed_free. /// Must have glib_get_type function AutoBoxed, /// Boxed record with custom copy/free functions Boxed, /// Referencecounted record Refcounted, //TODO: detect and gen...
}
} else { RecordType::AutoBoxed } }
random_line_split
stache.js
// RequireJS Mustache template plugin // http://github.com/jfparadis/requirejs-mustache // // An alternative to https://github.com/millermedeiros/requirejs-hogan-plugin // // Using Mustache Logic-less templates at http://mustache.github.com // Using and RequireJS text.js at http://requirejs.org/docs/api.html#text // @a...
buildMap[moduleName] = function( view, partials) { return Mustache.render( source, view, partials); }; onload(buildMap[moduleName]); } }, config); } }, wri...
onload(); } else { Mustache.parse(source);
random_line_split
stache.js
// RequireJS Mustache template plugin // http://github.com/jfparadis/requirejs-mustache // // An alternative to https://github.com/millermedeiros/requirejs-hogan-plugin // // Using Mustache Logic-less templates at http://mustache.github.com // Using and RequireJS text.js at http://requirejs.org/docs/api.html#text // @a...
}, config); } }, write: function (pluginName, moduleName, write, config) { var source = sourceMap[moduleName], content = source && text.jsEscape(source); if (content) { write.asModule(pluginName + '!' + moduleName, ...
{ Mustache.parse(source); buildMap[moduleName] = function( view, partials) { return Mustache.render( source, view, partials); }; onload(buildMap[moduleName]); }
conditional_block
base64.artifact.ts
import { module } from 'angular'; import { ArtifactTypePatterns } from 'core/artifact'; import { IArtifact } from 'core/domain/IArtifact'; import { Registry } from 'core/registry'; import './base64.artifact.less'; export const BASE64_ARTIFACT = 'spinnaker.core.pipeline.trigger.artifact.base64'; module(BASE64_ARTIFAC...
class="form-control input-sm" ng-model="ctrl.artifact.name" /> </div> </div> </div> `, }); });
<div class="col-md-8"> <input type="text" placeholder="base64-artifact"
random_line_split
signup.ts
/* * MIT License * * Copyright (c) 2017 David Garcia <dgarcia360@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the ri...
{ private signupForm : FormGroup; private qrService: QRService; constructor(public app: App, private wallet: WalletProvider, private loading: LoadingController, private alertCtrl: AlertController, private alert: AlertProvider, public translate: TranslateService, ...
SignupPrivateKeyPage
identifier_name
signup.ts
/* * MIT License * * Copyright (c) 2017 David Garcia <dgarcia360@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the ri...
import {WalletProvider} from '../../providers/wallet/wallet.provider'; import {LoginPage} from '../login/login'; import {Password, QRService, SimpleWallet} from "nem-library"; import {FormControl, FormGroup, Validators} from "@angular/forms"; import {PasswordValidation} from "../../validators/password.validator"; impor...
import {BarcodeScanner} from '@ionic-native/barcode-scanner'; import {TranslateService} from '@ngx-translate/core'; import {AlertProvider} from '../../providers/alert/alert.provider';
random_line_split
signup.ts
/* * MIT License * * Copyright (c) 2017 David Garcia <dgarcia360@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the ri...
}); }); }, err => console.log(err)); } }
{ try { const createdWallet = SimpleWallet .createWithPrivateKey(form.name, new Password(form.password), form.privateKey); this.wallet.storeWallet(createdWallet).then(ignored => { ...
conditional_block
signup.ts
/* * MIT License * * Copyright (c) 2017 David Garcia <dgarcia360@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the ri...
}); } catch (e) { loader.dismiss(); this.alert.showInvalidPrivateKey(); } } }); }); }, err => co...
{ const form = this.signupForm.value; this.translate .get('PLEASE_WAIT', {}) .subscribe((res: string) => { let loader = this.loading.create({content: res}); loader.present().then(ignored => { this.wallet.checkIfWalletNameExist...
identifier_body
lib.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] //!Load Cifar10 //! //!Cifar10 Simple Loader //! //!Use image crate in CifarImage. //! //!##Examples //! //! Download CIFAR-10 binary version and extract. //! //!``` //!# extern crate cifar_10_loader; //!# use cifar_10_l...
mod test;
random_line_split
base.py
""" Project main settings file. These settings are common to the project if you need to override something do it in local.pt """ from sys import path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os # PATHS # Path containing the django project BASE_DIR = os.path.dirname(os.path.dirna...
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public/media') # URL that handles the media served from MEDIA_ROOT. Use a trailing slash. # https://docs.djangoproject.com/en/1.10/ref/settings/#media-url MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this d...
# MEDIA AND STATIC SETTINGS # Absolute filesystem path to the directory that will hold user-uploaded files. # https://docs.djangoproject.com/en/1.10/ref/settings/#media-root
random_line_split
complex_query.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use rustorm::query::Query; use rustorm::query::{Filter,Equality}; use rustorm::dao::{Dao,IsDao}; use gen::bazaar::Product; use gen::bazaar::product; use gen::bazaar::Photo; use gen::bazaar::photo; use gen::bazaar::Review; use g...
) .GROUP_BY(&[category::name]) .HAVING(COUNT(&"*").GT(&1)) .HAVING(COUNT(&product::product_id).GT(&1)) .ORDER_BY(&[product::name.ASC(), product::created.DESC()]) .build(db.as_ref()); let expected = " SELECT * FROM bazaar.product LEFT JOIN bazaar.product_cat...
random_line_split
complex_query.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use rustorm::query::Query; use rustorm::query::{Filter,Equality}; use rustorm::dao::{Dao,IsDao}; use gen::bazaar::Product; use gen::bazaar::product; use gen::bazaar::Photo; use gen::bazaar::photo; use gen::bazaar::Review; use g...
) .GROUP_BY(&[category::name]) .HAVING(COUNT(&"*").GT(&1)) .HAVING(COUNT(&product::product_id).GT(&1)) .ORDER_BY(&[product::name.ASC(), product::created.DESC()]) .build(db.as_ref()); let expected = " SELECT * FROM bazaar.product LEFT JOIN bazaar.product_cat...
{ let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap(); let db = pool.connect().unwrap(); let frag = SELECT_ALL().FROM(&bazaar::product) .LEFT_JOIN(bazaar::product_category .ON( product_category::product_id.EQ(&product::product_id) ...
identifier_body
complex_query.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use rustorm::query::Query; use rustorm::query::{Filter,Equality}; use rustorm::dao::{Dao,IsDao}; use gen::bazaar::Product; use gen::bazaar::product; use gen::bazaar::Photo; use gen::bazaar::photo; use gen::bazaar::Review; use g...
(){ let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap(); let db = pool.connect().unwrap(); let frag = SELECT_ALL().FROM(&bazaar::product) .LEFT_JOIN(bazaar::product_category .ON( product_category::product_id.EQ(&product::product_id) ...
main
identifier_name
ofx.py
from datetime import datetime from hashlib import sha1 from xml.sax.saxutils import escape as xml_escape from .common import CHARSET def xml_template(template, data): """
return template % escaped_data class OFXExporter(object): HEADER = """ENCODING:UTF-8 OFXHEADER:100 DATA:OFXSGML VERSION:211 SECURITY:NONE CHARSET:UTF-8 COMPRESSION:NONE OLDFILEUID:NONE NEWFILEUID:NONE <OFX> <BANKMSGSRSV1> <STMTTRNRS> <TRNUID>0</TRNUID> <STMTRS> <CURDEF>EUR</CURDEF> ...
return template % data but with proper escaping """ escaped_data = {} for key, value in data.items(): escaped_data[key] = xml_escape(value)
random_line_split
ofx.py
from datetime import datetime from hashlib import sha1 from xml.sax.saxutils import escape as xml_escape from .common import CHARSET def xml_template(template, data): """ return template % data but with proper escaping """ escaped_data = {} for key, value in data.items(): escaped_data[key] ...
}) if not earliest_tx or earliest_tx > unixtime: earliest_tx = unixtime if not latest_tx or latest_tx < unixtime: latest_tx = unixtime header = xml_template(self.HEADER, { 'acctid': self.account_id, 'dtstart': self.unix...
earliest_tx = None latest_tx = None transactions = "" for guid, unixtime, memo, amount in self.transactions: if reverse: if amount[0] == '-': amount = amount[1:] else: amount = '-' + amount ofxdate = ...
identifier_body
ofx.py
from datetime import datetime from hashlib import sha1 from xml.sax.saxutils import escape as xml_escape from .common import CHARSET def xml_template(template, data): """ return template % data but with proper escaping """ escaped_data = {} for key, value in data.items():
return template % escaped_data class OFXExporter(object): HEADER = """ENCODING:UTF-8 OFXHEADER:100 DATA:OFXSGML VERSION:211 SECURITY:NONE CHARSET:UTF-8 COMPRESSION:NONE OLDFILEUID:NONE NEWFILEUID:NONE <OFX> <BANKMSGSRSV1> <STMTTRNRS> <TRNUID>0</TRNUID> <STMTRS> <CURDEF>EUR</CURDEF> ...
escaped_data[key] = xml_escape(value)
conditional_block
ofx.py
from datetime import datetime from hashlib import sha1 from xml.sax.saxutils import escape as xml_escape from .common import CHARSET def xml_template(template, data): """ return template % data but with proper escaping """ escaped_data = {} for key, value in data.items(): escaped_data[key] ...
(self, unixtime): dt = datetime.fromtimestamp(unixtime) return dt.strftime("%Y%m%d%H%M%S") def generate(self, reverse=False): earliest_tx = None latest_tx = None transactions = "" for guid, unixtime, memo, amount in self.transactions: if reverse: ...
unixtime2ofx
identifier_name
atomic_usize.rs
use std::cell::UnsafeCell; use std::fmt; use std::ops; /// `AtomicUsize` providing an additional `load_unsync` function. pub(crate) struct AtomicUsize { inner: UnsafeCell<std::sync::atomic::AtomicUsize>, } unsafe impl Send for AtomicUsize {} unsafe impl Sync for AtomicUsize {} impl AtomicUsize { pub(crate) c...
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R { // safety: we have mutable access f(unsafe { (*self.inner.get()).get_mut() }) } } impl ops::Deref for AtomicUsize { type Target = std::sync::atomic::AtomicUsize; fn deref(&self) -> &Self::Target { // ...
}
random_line_split
atomic_usize.rs
use std::cell::UnsafeCell; use std::fmt; use std::ops; /// `AtomicUsize` providing an additional `load_unsync` function. pub(crate) struct AtomicUsize { inner: UnsafeCell<std::sync::atomic::AtomicUsize>, } unsafe impl Send for AtomicUsize {} unsafe impl Sync for AtomicUsize {} impl AtomicUsize { pub(crate) c...
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R { // safety: we have mutable access f(unsafe { (*self.inner.get()).get_mut() }) } } impl ops::Deref for AtomicUsize { type Target = std::sync::atomic::AtomicUsize; fn deref(&self) -> &Self::Target { //...
{ *(*self.inner.get()).get_mut() }
identifier_body
atomic_usize.rs
use std::cell::UnsafeCell; use std::fmt; use std::ops; /// `AtomicUsize` providing an additional `load_unsync` function. pub(crate) struct AtomicUsize { inner: UnsafeCell<std::sync::atomic::AtomicUsize>, } unsafe impl Send for AtomicUsize {} unsafe impl Sync for AtomicUsize {} impl AtomicUsize { pub(crate) c...
(&mut self) -> &mut Self::Target { // safety: we hold `&mut self` unsafe { &mut *self.inner.get() } } } impl fmt::Debug for AtomicUsize { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(fmt) } }
deref_mut
identifier_name
EventWindow.js
true, layout: 'fit', formPanelConfig: { border: false }, // private initComponent: function(){ this.addEvents({ /** * @event eventadd * Fires after a new event is added * @param {Extensible.calendar.form.EventWindow} this ...
{ this.activeRecord.reject(); }
conditional_block
EventWindow.js
.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was updated * @param {Ext.Element} el The target element */ eventupdate: true, /** * @event eventdelete * Fires after an event is deleted ...
// // rec.beginEdit(); // // //TODO: This block is copied directly from BasicForm.updateRecord.
random_line_split
scheduledprogram.py
# Copyright (c) 2016 Sebastian Kanis # This file is part of pi-led-control. # pi-led-control 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 ve...
(self): now = datetime.datetime.now() secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second if secondsInCurrentDay < self._timeOfDay: sleepDuration = self._timeOfDay - secondsInCurrentDay else: sleepDuration = self._timeOfDay + 3600 * 24 - secondsIn...
run
identifier_name
scheduledprogram.py
# Copyright (c) 2016 Sebastian Kanis # This file is part of pi-led-control. # pi-led-control 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 ve...
now = datetime.datetime.now() secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second if secondsInCurrentDay < self._timeOfDay: sleepDuration = self._timeOfDay - secondsInCurrentDay else: sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentD...
def run(self):
random_line_split
scheduledprogram.py
# Copyright (c) 2016 Sebastian Kanis # This file is part of pi-led-control. # pi-led-control 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 ve...
else: sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds") self._waitIfNotStopped(sleepDuration) self._program.run() def setThreadStopEvent(self, threadStopEvent): sel...
sleepDuration = self._timeOfDay - secondsInCurrentDay
conditional_block
scheduledprogram.py
# Copyright (c) 2016 Sebastian Kanis # This file is part of pi-led-control. # pi-led-control 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 ve...
def setColorSetter(self, colorSetter): self._colorSetter = colorSetter self._program.setColorSetter(colorSetter) def getCurrentColor(self): return self._program.getCurrentColor() def setLastColor(self, lastColor): self._program.setLastColor(lastColor)
self.threadStopEvent = threadStopEvent self._program.setThreadStopEvent(threadStopEvent)
identifier_body
parameters.ts
import { IConfig } from '../config'; function
(content: string, index: number): number { let angleBracketCount = 0; while (index < content.length) { if (content[index] === '<') { angleBracketCount++; } if (content[index] === '>' && angleBracketCount > 0) { angleBracketCount--; } i...
findParameterEnd
identifier_name
parameters.ts
import { IConfig } from '../config'; function findParameterEnd(content: string, index: number): number { let angleBracketCount = 0; while (index < content.length) { if (content[index] === '<') { angleBracketCount++; } if (content[index] === '>' && angleBracketCount...
export function parameters(config: IConfig, content: string): IConfig { return { ...config, parameters: [...config.parameters, ...parseParameters(content)] }; }
{ let index = 0; const result: string[] = []; while (index < content.length) { const end = findParameterEnd(content, index); const parameter = content.substr(index, end - index).trim(); if (parameter.length) { result.push(parameter); } index = e...
identifier_body
parameters.ts
import { IConfig } from '../config'; function findParameterEnd(content: string, index: number): number { let angleBracketCount = 0; while (index < content.length) { if (content[index] === '<') { angleBracketCount++; } if (content[index] === '>' && angleBracketCount...
break; } index++; } return index; } function parseParameters(content: string): string[] { let index = 0; const result: string[] = []; while (index < content.length) { const end = findParameterEnd(content, index); const parameter = content.su...
angleBracketCount--; } if (content[index] === ',' && angleBracketCount === 0) {
random_line_split
parameters.ts
import { IConfig } from '../config'; function findParameterEnd(content: string, index: number): number { let angleBracketCount = 0; while (index < content.length) { if (content[index] === '<') { angleBracketCount++; } if (content[index] === '>' && angleBracketCount...
index++; } return index; } function parseParameters(content: string): string[] { let index = 0; const result: string[] = []; while (index < content.length) { const end = findParameterEnd(content, index); const parameter = content.substr(index, end - index).trim...
{ break; }
conditional_block
settings.py
""" Django settings for channel_worm project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build...
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media') MEDIA_URL = '/media/'
), )
random_line_split
RangeHTTPServer.py
#!/usr/bin/python ''' Use this in the same way as Python's http.server / SimpleHTTPServer: python -m RangeHTTPServer [port] The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports 'Range:' headers to load portions of files. This is helpful for doing local web development with genomi...
BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$') def parse_byte_range(byte_range): '''Returns the two numbers in 'bytes=123-456' or throws ValueError. The last number or both numbers may be None. ''' if byte_range.strip() == '': return None, None m = BYTE_RANGE_RE.match(byte_range) ...
to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize) buf = infile.read(to_read) if not buf: break outfile.write(buf)
conditional_block
RangeHTTPServer.py
#!/usr/bin/python ''' Use this in the same way as Python's http.server / SimpleHTTPServer: python -m RangeHTTPServer [port] The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports 'Range:' headers to load portions of files. This is helpful for doing local web development with genomi...
# Mirroring SimpleHTTPServer.py here path = self.translate_path(self.path) f = None ctype = self.guess_type(path) try: f = open(path, 'rb') except IOError: self.send_error(404, 'File not found') return None fs = os.fstat(f.fil...
random_line_split
RangeHTTPServer.py
#!/usr/bin/python ''' Use this in the same way as Python's http.server / SimpleHTTPServer: python -m RangeHTTPServer [port] The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports 'Range:' headers to load portions of files. This is helpful for doing local web development with genomi...
fs = os.fstat(f.fileno()) file_len = fs[6] if first >= file_len: self.send_error(416, 'Requested Range Not Satisfiable') return None self.send_response(206) self.send_header('Content-type', ctype) self.send_header('Accept-Ranges', 'bytes') ...
if 'Range' not in self.headers: self.range = None return SimpleHTTPRequestHandler.send_head(self) try: self.range = parse_byte_range(self.headers['Range']) except ValueError as e: self.send_error(400, 'Invalid byte range') return None f...
identifier_body
RangeHTTPServer.py
#!/usr/bin/python ''' Use this in the same way as Python's http.server / SimpleHTTPServer: python -m RangeHTTPServer [port] The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports 'Range:' headers to load portions of files. This is helpful for doing local web development with genomi...
(self, source, outputfile): if not self.range: return SimpleHTTPRequestHandler.copyfile(self, source, outputfile) # SimpleHTTPRequestHandler uses shutil.copyfileobj, which doesn't let # you stop the copying before the end of the file. start, stop = self.range # set in send_...
copyfile
identifier_name
webpack-dev.config.js
entry: [ 'webpack-dev-server/client?http://0.0.0.0:8080', './src/index.js' ], output: { publicPath: '/', path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel', query: { prese...
var path = require('path'); module.exports = {
random_line_split
error.rs
ExceptionMethods; use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::conversions::root_from_object; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::...
(cx: *mut JSContext, global: &GlobalScope, result: Error) { #[cfg(feature = "js_backtrace")] { capture_stack!(in(cx) let stack); let js_stack = stack.and_then(|s| s.as_string(None)); let rust_stack = Backtrace::new(); LAST_EXCEPTION_BACKTRACE.with(|backtrace| { *backt...
throw_dom_exception
identifier_name
error.rs
FromException; use js::rust::wrappers::JS_GetPendingException; use js::rust::wrappers::JS_SetPendingException; use libc::c_uint; use std::slice::from_raw_parts; /// An optional stringified JS backtrace and stringified native backtrace from the /// the last DOM exception that was reported. #[cfg(feature = "js_backtrace...
{ debug_assert!(!JS_IsExceptionPending(cx)); let error = format!( "\"this\" object does not implement interface {}.", proto_id_to_name(proto_id) ); throw_type_error(cx, &error); }
identifier_body
error.rs
ExceptionMethods; use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::conversions::root_from_object; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::...
let filename = { let filename = (*report)._base.filename as *const u8; if !filename.is_null() { let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap(); let filename = from_raw_parts(filename, length as usize); String::from_ut...
{ return None; }
conditional_block
error.rs
ExceptionMethods; use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::conversions::root_from_object; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::...
let filename = from_raw_parts(filename, length as usize); String::from_utf8_lossy(filename).into_owned() } else { "none".to_string() } }; let lineno = (*report)._base.lineno; let column = (*report)._base.column; le...
let filename = (*report)._base.filename as *const u8; if !filename.is_null() { let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
random_line_split
client_activity.py
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from django.db.models import Count, QuerySet from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_use...
else: arg = options['arg'] try: # Report activity for a user. user_profile = get_user_profile_by_email(arg) self.compute_activity(UserActivity.objects.filter( user_profile=user_profile)) except UserProfi...
self.compute_activity(UserActivity.objects.all())
conditional_block
client_activity.py
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from django.db.models import Count, QuerySet from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_use...
(BaseCommand): help = """Report rough client activity globally, for a realm, or for a user Usage examples: ./manage.py client_activity ./manage.py client_activity zulip.com ./manage.py client_activity jesstess@zulip.com""" def add_arguments(self, parser): # type: (ArgumentParser) -> None pars...
Command
identifier_name
client_activity.py
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from django.db.models import Count, QuerySet from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_use...
else: arg = options['arg'] try: # Report activity for a user. user_profile = get_user_profile_by_email(arg) self.compute_activity(UserActivity.objects.filter( user_profile=user_profile)) except UserProfil...
if options['arg'] is None: # Report global activity. self.compute_activity(UserActivity.objects.all())
random_line_split
client_activity.py
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from django.db.models import Count, QuerySet from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_use...
# client recently. For example, this might be useful to get a sense of # how popular different versions of a desktop client are. # # Importantly, this does NOT tell you anything about the relative # volumes of requests from clients. threshold = datetime.datetime.now() - d...
help = """Report rough client activity globally, for a realm, or for a user Usage examples: ./manage.py client_activity ./manage.py client_activity zulip.com ./manage.py client_activity jesstess@zulip.com""" def add_arguments(self, parser): # type: (ArgumentParser) -> None parser.add_argument('ar...
identifier_body
iadfa.py
from fsa import * from nameGenerator import * class IncrementalAdfa(Dfa): """This class is an Acyclic Deterministic Finite State Automaton constructed by a list of words. """ def __init__(self, words, nameGenerator = None, sorted = False): if nameGenerator is None: nameGenerator ...
(self, stateName): return stateName in self.register def markAsRegistered(self, stateName): self.register[stateName] = True def equivalentRegisteredState(self, stateName): equivatentState = None for state in list(self.register.keys()): if self.areEquiv...
markedAsRegistered
identifier_name
iadfa.py
from fsa import * from nameGenerator import * class IncrementalAdfa(Dfa): """This class is an Acyclic Deterministic Finite State Automaton constructed by a list of words. """ def __init__(self, words, nameGenerator = None, sorted = False): if nameGenerator is None: nameGenerator ...
return (stateName, word[index:]) def hasChildren(self, stateName): okay = False if [s for s in list(self.states[stateName].transitions.values()) if s]: okay = True return okay def addSuffix(self, stateName, currentSuffix): lastState = stateName ...
nextStateName = None
conditional_block
iadfa.py
from fsa import * from nameGenerator import * class IncrementalAdfa(Dfa): """This class is an Acyclic Deterministic Finite State Automaton constructed by a list of words. """ def __init__(self, words, nameGenerator = None, sorted = False): if nameGenerator is None: nameGenerator ...
def createFromSortedListOfWords(self, words): self.register = {} self.finalStates = [] self.startState = self.nameGenerator.generate() self.states = {self.startState : State(self.startState)} lastWord = None for word in words: if word.endswith('\n'): ...
childs = nextChilds
random_line_split