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
transform_hex_multine.py
#! /usr/bin/python3 import sys MAXLINELEN = 80 TABLEN = 8 # 3 for two quotes and a comma FIRSTLINELEN = MAXLINELEN - TABLEN - 3 OTHERLINELEN = FIRSTLINELEN - 2 * TABLEN FIRSTLINEBYTES = FIRSTLINELEN // 2 OTHERLINEBYTES = OTHERLINELEN // 2 def
(line): return "".join("\\x{}".format(line[i:i + 2].decode()) for i in range(0, len(line), 2)) def main(): with open(sys.argv[1], "rb") as f: data = f.read().strip().splitlines() with sys.stdout as f: f.write("#define INPUTLEN {}\n".format(len(data[0]) // 2)) f.write("\n") f.write("static const unsigned cha...
fix_line
identifier_name
transform_hex_multine.py
#! /usr/bin/python3 import sys MAXLINELEN = 80 TABLEN = 8 # 3 for two quotes and a comma FIRSTLINELEN = MAXLINELEN - TABLEN - 3 OTHERLINELEN = FIRSTLINELEN - 2 * TABLEN FIRSTLINEBYTES = FIRSTLINELEN // 2 OTHERLINEBYTES = OTHERLINELEN // 2 def fix_line(line):
def main(): with open(sys.argv[1], "rb") as f: data = f.read().strip().splitlines() with sys.stdout as f: f.write("#define INPUTLEN {}\n".format(len(data[0]) // 2)) f.write("\n") f.write("static const unsigned char input[][INPUTLEN + 1] = {\n") for line in data: f.write("\t\"{}\"".format(fix_line(line[...
return "".join("\\x{}".format(line[i:i + 2].decode()) for i in range(0, len(line), 2))
identifier_body
classification_train.py
"""Classification training""" import os, sys sys.path.append('../') sys.path.append('../models/') sys.path.append('../util/') import time import json import importlib import argparse import tensorflow as tf import numpy as np from input_data import Data def optimization(learning_rate, loss): """Defines the opt...
(logits, labels): """Defines loss function""" cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) return tf.reduce_mean(cross_entropy) def compute_accuracy(logits, labels): """Computes classification accuracy""" correct_prediction = tf.equal(tf.argmax(logits,1), tf...
cross_entropy
identifier_name
classification_train.py
"""Classification training""" import os, sys sys.path.append('../') sys.path.append('../models/') sys.path.append('../util/') import time import json import importlib import argparse import tensorflow as tf import numpy as np from input_data import Data def optimization(learning_rate, loss): """Defines the opt...
if i % 100 == 0: step_time = time.time() - initial_time print(i, 'iterations: took {0:.2f}s'.format(step_time)) elapsed_time += step_time initial_time = time.time() if i % 500 == 0: valid_images, valid_labels = valid_data.next_batch(batch_siz...
train_images, train_labels = train_data.next_batch(batch_size) train_step.run(feed_dict={model.x: train_images, model.labels: train_labels, model.dropout_prob: dropout})
random_line_split
classification_train.py
"""Classification training""" import os, sys sys.path.append('../') sys.path.append('../models/') sys.path.append('../util/') import time import json import importlib import argparse import tensorflow as tf import numpy as np from input_data import Data def optimization(learning_rate, loss): """Defines the opt...
main()
conditional_block
classification_train.py
"""Classification training""" import os, sys sys.path.append('../') sys.path.append('../models/') sys.path.append('../util/') import time import json import importlib import argparse import tensorflow as tf import numpy as np from input_data import Data def optimization(learning_rate, loss): """Defines the opt...
valid_data = Data(config['data']['valid']) train_data.shuffle_data() # Snapshot setup snapshot_filename = model_name + '.npy' snapshot_path = os.path.join(args.model_snapshot_dir, model_name, snapshot_filename) # Importing and c...
parser = argparse.ArgumentParser("Classification training.") parser.add_argument('model_config_file') parser.add_argument('num_iters', type=int) parser.add_argument('learning_rate', type=float) parser.add_argument('--model_snapshot_dir', default='../snapshots') args = parser.parse_args() # Loa...
identifier_body
editor_plugin.js
/** * http://abricos.org, https://github.com/abricos/tinymce-prettify-plugin * @license Dual licensed under the MIT or GPL Version 3 licenses. * @version 0.1 * @author Alexander Kuzmin <roosit@abricos.org> * @package TinyMCE * @name prettify * GPL 3 LICENCES */ (function() { tinymc...
} }, _removeSpanElementsInPreElementsForWebKit: function(ed, node){ var spanElements = ed.dom.select('code span', node); var space; for (var i=0; i<spanElements.length; i++) { space = ed.getDoc().createTextNode(spanElements[i].innerHTML); ...
for (var i=0; i<brElements.length; i++){ newline = ed.getDoc().createTextNode(newlineChar); ed.dom.insertAfter(newline, brElements[i]); ed.dom.remove(brElements[i]);
random_line_split
editor_plugin.js
/** * http://abricos.org, https://github.com/abricos/tinymce-prettify-plugin * @license Dual licensed under the MIT or GPL Version 3 licenses. * @version 0.1 * @author Alexander Kuzmin <roosit@abricos.org> * @package TinyMCE * @name prettify * GPL 3 LICENCES */ (function() { tinymc...
if (tinymce.isGecko || tinymce.isOpera) { ed.onKeyDown.add(function(ed, e) { var selection = ed.selection; if (e.keyCode == 9 && selection.getNode().nodeName === 'CODE') { selection.setContent('\t', {format : 'raw'}...
{ ed.onKeyDown.add(function(ed, e) { var brElement; var selection = ed.selection; if (e.keyCode == 13 && selection.getNode().nodeName === 'CODE') { selection.setContent('<br id="__prettify" /> ', {format : 'raw'}); // Do not re...
conditional_block
StrategyForm.styles.ts
import { makeStyles } from '@material-ui/core/styles'; export const useStyles = makeStyles(theme => ({ container: { maxWidth: 400, }, form: { display: 'flex', flexDirection: 'column', height: '100%', }, input: { width: '100%', marginBottom: '1rem' }, selectInput:...
color: theme.palette.grey[600], top: '-13px', position: 'relative', }, formHeader: { fontWeight: 'normal', marginTop: '0', }, header: { fontWeight: 'normal', }, errorMessage: { fontSize: theme.fontSizes.smallBody, color: theme.palet...
}, typeDescription: { fontSize: theme.fontSizes.smallBody,
random_line_split
zt.megamenu.js
var ZTMenu = function(boxTimer, xOffset, yOffset, smartBoxSuffix, smartBoxClose, isub, xduration, xtransition) { var smartBoxes = $(document.body).getElements('[id$=' + smartBoxSuffix + ']'); var closeElem = $(document.body).getElements('.' + smartBoxClose); var closeBoxes = function() { smartBoxes.setStyle('di...
var WindowX = window.getWidth(); var boxSize = item.getSize(); var inputPOS = $(currentBox).getCoordinates(); var inputCOOR = $(currentBox).getPosition(); var inputSize = $(currentBox).getSize(); var inputBottomPOS = inputPOS.top + inputSize.y; var inputBottomPOSAdjust = in...
item.setStyles({ display: 'block', position: 'absolute' });
random_line_split
zt.megamenu.js
var ZTMenu = function(boxTimer, xOffset, yOffset, smartBoxSuffix, smartBoxClose, isub, xduration, xtransition) { var smartBoxes = $(document.body).getElements('[id$=' + smartBoxSuffix + ']'); var closeElem = $(document.body).getElements('.' + smartBoxClose); var closeBoxes = function() { smartBoxes.setStyle('di...
else{ item.setStyle('left', (inputPOS.right - boxSize.x) - xOffset + 10); }; } else { if((inputLeftPOS + boxSize.x + inputSize.x - WindowX) < 0) { var space = inputLeftPOS - boxSize.x - inputSize.x; var left = (space > inputSize.x) ? space : inputSize.x; item.setStyle('left', left); ...
{ item.setStyle('left', leftOffset - 10); }
conditional_block
vmware.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' VMWARE external inventory script ================================= shamelessly copied from existing inventory scripts. This script and it's ini can be used more than once, i.e vmware.py/vmware_colo.ini vmware_idf.py/vmware_idf.ini (script can be link) so if you don'...
return False def get_host_info(host): ''' Get variables about a specific host ''' hostinfo = { 'vmware_name' : host.name, 'vmware_tag' : host.tag, 'vmware_parent': host.parent.name, } for k in host.capability.__dict__.keys(): if k...
if (existing.st_mtime - int(time.time())) <= maxage: return True
random_line_split
vmware.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' VMWARE external inventory script ================================= shamelessly copied from existing inventory scripts. This script and it's ini can be used more than once, i.e vmware.py/vmware_colo.ini vmware_idf.py/vmware_idf.ini (script can be link) so if you don'...
(client, config): ''' Reads the inventory from cache or vmware api ''' if cache_available('inventory', config): inv = get_cache('inventory',config) else: inv= { 'all': {'hosts': []}, '_meta': { 'hostvars': {} } } default_group = os.path.basename(sys.argv[0]).rstrip('.py') i...
get_inventory
identifier_name
vmware.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' VMWARE external inventory script ================================= shamelessly copied from existing inventory scripts. This script and it's ini can be used more than once, i.e vmware.py/vmware_colo.ini vmware_idf.py/vmware_idf.ini (script can be link) so if you don'...
if config.has_option('defaults','vm_group'): vm_group = config.get('defaults','vm_group') else: vm_group = default_group + '_vm' inv[vm_group] = [] # Loop through physical hosts: hosts = HostSystem.all(client) for host in hosts: if n...
if config.has_option('defaults','hw_group'): hw_group = config.get('defaults','hw_group') else: hw_group = default_group + '_hw' inv[hw_group] = []
conditional_block
vmware.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' VMWARE external inventory script ================================= shamelessly copied from existing inventory scripts. This script and it's ini can be used more than once, i.e vmware.py/vmware_colo.ini vmware_idf.py/vmware_idf.ini (script can be link) so if you don'...
def get_host_info(host): ''' Get variables about a specific host ''' hostinfo = { 'vmware_name' : host.name, 'vmware_tag' : host.tag, 'vmware_parent': host.parent.name, } for k in host.capability.__dict__.keys(): if k.startswith('_'):...
''' checks if we have a 'fresh' cache available for item requested ''' if config.has_option('defaults', 'cache_dir'): dpath = config.get('defaults', 'cache_dir') try: existing = os.stat( '/'.join([dpath,cache_item])) except: # cache doesn't exist or isn't accessible...
identifier_body
root.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
stream: &mut TcpStream) -> Result<bool, ()> { Ok(match msg_type { "listAddons" => { let actor = ErrorReply { from: "root".to_string(), error: "noAddons".to_string(), message: "This root actor has no bro...
fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, _msg: &json::Object,
random_line_split
root.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
}; stream.write_json_packet(&actor); true } _ => false }) } } impl RootActor { pub fn encodable(&self) -> RootActorMsg { RootActorMsg { from: "root".to_string(), applicationType: "browser".to_strin...
{ Ok(match msg_type { "listAddons" => { let actor = ErrorReply { from: "root".to_string(), error: "noAddons".to_string(), message: "This root actor has no browser addons.".to_string(), }; stre...
identifier_body
root.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
_ => false }) } } impl RootActor { pub fn encodable(&self) -> RootActorMsg { RootActorMsg { from: "root".to_string(), applicationType: "browser".to_string(), traits: ActorTraits { sources: true, highlightable: tru...
{ let actor = ListTabsReply { from: "root".to_string(), selected: 0, tabs: self.tabs.iter().map(|tab| { registry.find::<TabActor>(tab).encodable() }).collect() }; strea...
conditional_block
root.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
(&self) -> String { "root".to_string() } fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, _msg: &json::Object, stream: &mut TcpStream) -> Result<bool, ()> { Ok(match msg_type { ...
name
identifier_name
helper.ts
import * as os from "os"; import * as crypto from "crypto"; import * as fse from "fs-extra"; const originalCwd = process.cwd(); const createdDirectories: string[] = []; process.on("exit", () => { // In case something went wrong and some temp // directories are still on the disk. createdDirectories.forEach(path ...
return path.replace(/\\/g, "/"); } export default { setCleanTestCwd, switchBackToCorrectCwd, parseMode, osSep };
{ return path.replace(/\//g, "\\"); }
conditional_block
helper.ts
import * as os from "os"; import * as crypto from "crypto"; import * as fse from "fs-extra"; const originalCwd = process.cwd(); const createdDirectories: string[] = []; process.on("exit", () => { // In case something went wrong and some temp // directories are still on the disk. createdDirectories.forEach(path ...
(path: any): any { if (Array.isArray(path)) { return path.map(osSep); } if (process.platform === "win32") { return path.replace(/\//g, "\\"); } return path.replace(/\\/g, "/"); } export default { setCleanTestCwd, switchBackToCorrectCwd, parseMode, osSep };
osSep
identifier_name
helper.ts
import * as fse from "fs-extra"; const originalCwd = process.cwd(); const createdDirectories: string[] = []; process.on("exit", () => { // In case something went wrong and some temp // directories are still on the disk. createdDirectories.forEach(path => { fse.removeSync(path); }); }); const setCleanTest...
import * as os from "os"; import * as crypto from "crypto";
random_line_split
helper.ts
import * as os from "os"; import * as crypto from "crypto"; import * as fse from "fs-extra"; const originalCwd = process.cwd(); const createdDirectories: string[] = []; process.on("exit", () => { // In case something went wrong and some temp // directories are still on the disk. createdDirectories.forEach(path ...
export default { setCleanTestCwd, switchBackToCorrectCwd, parseMode, osSep };
{ if (Array.isArray(path)) { return path.map(osSep); } if (process.platform === "win32") { return path.replace(/\//g, "\\"); } return path.replace(/\\/g, "/"); }
identifier_body
submit_util.py
''' Created on Aug 21, 2014 @author: Dean4Devil ''' import mysql.connector from pycore.sql_util import MySQLHelper class SubmitTree(): 'A tree of all submits to that standard. I.e. OpenDriver is a tree, OpenDriver 0.2 is a submit.' def __init__(self, identifier): 'Create a new Tree in memory.' ...
'Submit element'
identifier_body
submit_util.py
''' Created on Aug 21, 2014 @author: Dean4Devil ''' import mysql.connector from pycore.sql_util import MySQLHelper class SubmitTree(): 'A tree of all submits to that standard. I.e. OpenDriver is a tree, OpenDriver 0.2 is a submit.' def __init__(self, identifier): 'Create a new Tree in memory.' ...
else: # First submit in that tree. Table does not exist yet. table = ( "CREATE TABLE IF NOT EXISTS `{}` (".format(identifier), "`id` int(11) NOT NULL AUTO_INCREMENT,", "`version` varchar(32) COLLATE utf8mb4_bin NOT NULL", "`...
self.tree = self.sql_helper.query_data(identifier, "*", delimiter="", order="id", row_num=0)
random_line_split
submit_util.py
''' Created on Aug 21, 2014 @author: Dean4Devil ''' import mysql.connector from pycore.sql_util import MySQLHelper class SubmitTree(): 'A tree of all submits to that standard. I.e. OpenDriver is a tree, OpenDriver 0.2 is a submit.' def __init__(self, identifier): 'Create a new Tree in memory.' ...
class Submit(): 'Submit element'
table = ( "CREATE TABLE IF NOT EXISTS `{}` (".format(identifier), "`id` int(11) NOT NULL AUTO_INCREMENT,", "`version` varchar(32) COLLATE utf8mb4_bin NOT NULL", "`comment` text COLLATE utf8mb4_bin NOT NULL,", "`content` text COLLATE utf8mb4...
conditional_block
submit_util.py
''' Created on Aug 21, 2014 @author: Dean4Devil ''' import mysql.connector from pycore.sql_util import MySQLHelper class SubmitTree(): 'A tree of all submits to that standard. I.e. OpenDriver is a tree, OpenDriver 0.2 is a submit.' def __init__(self, identifier): 'Create a new Tree in memory.' ...
(): 'Submit element'
Submit
identifier_name
toodle_sync.py
''' Simple pull of account info ''' import requests import datetime import pickle import json import time import sys account_url = 'https://api.toodledo.com/3/account/get.php?access_token=' tasks_get_url = 'https://api.toodledo.com/3/tasks/get.php?access_token=' ''' Fields you can use to filter when you get tasks: ht...
(epoch_time): completion = time.strftime('%A, %b %d, %Y', time.gmtime(epoch_time)) return completion def display_tasks(task_dump, context_pickle, days=4): task_dump = parse_to_json(task_dump) contexts = make_context_hash(context_pickle) start_date = datetime.date.today() - datetime.timedelta(days=days) start_dat...
arrange_date
identifier_name
toodle_sync.py
''' Simple pull of account info ''' import requests import datetime import pickle import json import time import sys account_url = 'https://api.toodledo.com/3/account/get.php?access_token=' tasks_get_url = 'https://api.toodledo.com/3/tasks/get.php?access_token=' ''' Fields you can use to filter when you get tasks: ht...
def format_task(task): ''' Take a dictionary formatted task from display tasks and print it out to something human readable. ''' comp_date = arrange_date(task['completed']) print 'Completed Task : {}, Completed {}'.format(task['title'], comp_date) def get_completed_tasks(): query = query_tasks('auth_token.pkl'...
task_dump = parse_to_json(task_dump) contexts = make_context_hash(context_pickle) start_date = datetime.date.today() - datetime.timedelta(days=days) start_date = datetime.date.strftime(start_date, '%A, %b %d, %Y') end_date = datetime.date.today() end_date = datetime.date.strftime(end_date, '%A, %b %d, %Y') print ...
identifier_body
toodle_sync.py
''' Simple pull of account info ''' import requests import datetime import pickle import json import time import sys account_url = 'https://api.toodledo.com/3/account/get.php?access_token=' tasks_get_url = 'https://api.toodledo.com/3/tasks/get.php?access_token=' ''' Fields you can use to filter when you get tasks: ht...
#test = display_tasks('tasks_queried.pkl', 4) def format_task(task): ''' Take a dictionary formatted task from display tasks and print it out to something human readable. ''' comp_date = arrange_date(task['completed']) print 'Completed Task : {}, Completed {}'.format(task['title'], comp_date) def get_completed...
pass
conditional_block
toodle_sync.py
''' Simple pull of account info ''' import requests import datetime import pickle import json import time import sys account_url = 'https://api.toodledo.com/3/account/get.php?access_token=' tasks_get_url = 'https://api.toodledo.com/3/tasks/get.php?access_token=' ''' Fields you can use to filter when you get tasks: ht...
def query_tasks(token, days, completion_state='1', fields='tag,context,goal'): token = load_token(token) # Get Tasks from Monday (ie 4 days ago since we cron for friday) start_date = datetime.date.today() - datetime.timedelta(days=days) # Make it Epoch Time start_date = int(time.mktime(start_date.timetuple())) s...
random_line_split
no_0037_sudoku_solver.rs
struct
; impl Solution { pub fn solve_sudoku(board: &mut Vec<Vec<char>>) { // 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。 let mut line = vec![0_u16; 9]; // 9 列 let mut column = vec![0_u16; 9]; // 3 x 3 的块 let mut block = vec![vec![0_u16; 3]; 3]; // 如果不是空格,就将对应的位置设置成...
Solution
identifier_name
no_0037_sudoku_solver.rs
struct Solution; impl Solution { pub fn solve_sudoku(board: &mut Vec<Vec<char>>) { // 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。 let mut line = vec![0_u16; 9]; // 9 列 let mut column = vec![0_u16; 9]; // 3 x 3 的块 let mut block = vec![vec![0_u16; 3]; 3]; // 如果...
line[i] ^= 1 << digit; column[j] ^= 1 << digit; block[i / 3][j / 3] ^= 1 << digit; } fn dfs( spaces: &Vec<(usize, usize)>, pos: usize, line: &mut Vec<u16>, column: &mut Vec<u16>, block: &mut Vec<Vec<u16>>, board: &mut Vec<Vec<char>>, )...
i: usize, j: usize, digit: u8, ) {
conditional_block
no_0037_sudoku_solver.rs
struct Solution; impl Solution { pub fn solve_sudoku(board: &mut Vec<Vec<char>>) { // 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。 let mut line = vec![0_u16; 9]; // 9 列 let mut column = vec![0_u16; 9]; // 3 x 3 的块 let mut block = vec![vec![0_u16; 3]; 3]; // 如果...
}
'.', '3', '.', '.', '1'], vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'], ]; Solution::solve_sudoku...
identifier_body
no_0037_sudoku_solver.rs
struct Solution; impl Solution { pub fn solve_sudoku(board: &mut Vec<Vec<char>>) { // 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。 let mut line = vec![0_u16; 9]; // 9 列 let mut column = vec![0_u16; 9]; // 3 x 3 的块 let mut block = vec![vec![0_u16; 3]; 3]; // 如果...
vec!['3', '4', '5', '2', '8', '6', '1', '7', '9'], ]; assert_eq!(board, want); } }
vec!['9', '6', '1', '5', '3', '7', '2', '8', '4'], vec!['2', '8', '7', '4', '1', '9', '6', '3', '5'],
random_line_split
ops.py
import scipy.sparse as ss import warnings warnings.simplefilter('ignore', ss.SparseEfficiencyWarning) from sparray import FlatSparray class Operations(object): params = [['FlatSparray', 'csr_matrix']] param_names = ['arr_type'] def setup(self, arr_type): mat = ss.rand(3000, 4000, density=0.1, format='csr'...
def time_getitem_scalar(self, arr_type): self.arr[154, 145] def time_getitem_subarray(self, arr_type): self.arr[:5, :5] def time_getitem_row(self, arr_type): self.arr[876] def time_getitem_col(self, arr_type): self.arr[:,273] def time_diagonal(self, arr_type): self.arr.diagonal() c...
self.arr.sum()
identifier_body
ops.py
import scipy.sparse as ss import warnings warnings.simplefilter('ignore', ss.SparseEfficiencyWarning) from sparray import FlatSparray class
(object): params = [['FlatSparray', 'csr_matrix']] param_names = ['arr_type'] def setup(self, arr_type): mat = ss.rand(3000, 4000, density=0.1, format='csr') if arr_type == 'FlatSparray': self.arr = FlatSparray.from_spmatrix(mat) else: self.arr = mat def time_scalar_multiplication(self...
Operations
identifier_name
ops.py
import scipy.sparse as ss import warnings warnings.simplefilter('ignore', ss.SparseEfficiencyWarning) from sparray import FlatSparray class Operations(object): params = [['FlatSparray', 'csr_matrix']] param_names = ['arr_type'] def setup(self, arr_type): mat = ss.rand(3000, 4000, density=0.1, format='csr'...
mat = ss.rand(3000, 4000, density=0.1, format='csr') if arr_type == 'FlatSparray': self.arr = FlatSparray.from_spmatrix(mat) else: self.arr = mat def time_setdiag(self, arr_type): self.arr.setdiag(99)
def setup(self, arr_type):
random_line_split
ops.py
import scipy.sparse as ss import warnings warnings.simplefilter('ignore', ss.SparseEfficiencyWarning) from sparray import FlatSparray class Operations(object): params = [['FlatSparray', 'csr_matrix']] param_names = ['arr_type'] def setup(self, arr_type): mat = ss.rand(3000, 4000, density=0.1, format='csr'...
else: self.arr = mat def time_setdiag(self, arr_type): self.arr.setdiag(99)
self.arr = FlatSparray.from_spmatrix(mat)
conditional_block
textarea.js
bind(this)); Fabrik.addEvent('fabrik.form.elements.added', function (form) { if (form.isMultiPage()) { this.refreshEditor(); } }.bind(this)); Fabrik.addEvent('fabrik.form.submit.start', function (form) { if (this.options.wysiwyg && form.options.ajax) { if (typeof tinyMCE !== 'undefined') { ...
}, _getTinyInstance: function () { return tinyMCE.majorVersion.toInt() >= 4 ? tinyMCE.get(this.element.id) : tinyMCE.getInstanceById(this.element.id); }, _addTinyEditor: function(id) { if (tinyMCE.majorVersion.toInt() >= 4) { tinyMCE.execCommand('mceAddEditor', false, id); } else { tinyMCE.execC...
{ if (typeof WFEditor !== 'undefined') { WFEditor.init(WFEditor.settings); } else if (typeof tinymce !== 'undefined') { tinyMCE.init(tinymce.settings); } // Need to re-observe the editor this.watchTextContainer(); }
conditional_block
textarea.js
Extends: FbElement, initialize: function (element, options) { this.plugin = 'fabriktextarea'; this.parent(element, options); // $$$ rob need to slightly delay this as if lots of js loaded (eg maps) // before the editor then the editor may not yet be loaded this.periodFn = function () { // Seems that ...
* @license: GNU/GPL http://www.gnu.org/copyleft/gpl.html */ var FbTextarea = new Class({
random_line_split
interface.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 interface Position { readonly offset: number; readonly line: number; readonly character: number; } ex...
export function isJsonArray(value: JsonValue): value is JsonArray { return Array.isArray(value); }
{ return value != null && typeof value === 'object' && !Array.isArray(value); }
identifier_body
interface.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 interface Position { readonly offset: number; readonly line: number; readonly character: number; } ex...
(value: JsonValue): value is JsonObject { return value != null && typeof value === 'object' && !Array.isArray(value); } export function isJsonArray(value: JsonValue): value is JsonArray { return Array.isArray(value); }
isJsonObject
identifier_name
interface.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 interface Position { readonly offset: number; readonly line: number; readonly character: number; } ex...
} export interface JsonAstConstantTrue extends JsonAstNodeBase { readonly kind: 'true'; readonly value: true; } // Loose mode AST. export interface JsonAstMultilineComment extends JsonAstNodeBase { readonly kind: 'multicomment'; readonly content: string; } export interface JsonAstComment extends JsonAstNode...
export interface JsonAstConstantNull extends JsonAstNodeBase { readonly kind: 'null'; readonly value: null;
random_line_split
lib.rs
#[derive(Debug, PartialEq)] pub enum Comparison { Equal, Sublist, Superlist, Unequal, } pub fn sublist<T: PartialEq>(list1: &[T], list2: &[T]) -> Comparison { if list1.len() == list2.len() { if list1 == list2 { return Comparison::Equal; } else { return Compar...
}
random_line_split
lib.rs
#[derive(Debug, PartialEq)] pub enum Comparison { Equal, Sublist, Superlist, Unequal, } pub fn sublist<T: PartialEq>(list1: &[T], list2: &[T]) -> Comparison { if list1.len() == list2.len() { if list1 == list2 { return Comparison::Equal; } else { return Compar...
Comparison::Unequal; }
{ let mut slice = &list1[..]; while slice.len() >= list2.len() { if list2 == &slice[..list2.len()] { return Comparison::Superlist; } slice = &slice[1..]; } }
conditional_block
lib.rs
#[derive(Debug, PartialEq)] pub enum
{ Equal, Sublist, Superlist, Unequal, } pub fn sublist<T: PartialEq>(list1: &[T], list2: &[T]) -> Comparison { if list1.len() == list2.len() { if list1 == list2 { return Comparison::Equal; } else { return Comparison::Unequal; } } else if list1.le...
Comparison
identifier_name
simpleStreaming.js
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===============================================...
console.log("...Streaming ended.".cyan); }); }
{ var streamingOptions = { vehicle_id: options.vehicle_id, authToken: options.authToken }; console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green); console.log("\nStreaming starting...".cyan); console.log("Columns: timestamp," + tjs.s...
identifier_body
simpleStreaming.js
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===============================================...
// display the streaming results console.log(body); console.log("...Streaming ended.".cyan); }); }
{ console.log(error); return; }
conditional_block
simpleStreaming.js
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===============================================...
console.log(body); console.log("...Streaming ended.".cyan); }); }
// display the streaming results
random_line_split
simpleStreaming.js
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===============================================...
(tjs, options) { var streamingOptions = { vehicle_id: options.vehicle_id, authToken: options.authToken }; console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green); console.log("\nStreaming starting...".cyan); console.log("Columns: time...
sampleMain
identifier_name
test_raw_nop.py
#- # Copyright (c) 2011 Robert N. M. Watson # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # License...
(self): '''Test that registers are unmodified after NOP''' for i in range(32): self.assertRegisterExpected(i, i, "Modified register after NOP")
test_raw_nop
identifier_name
test_raw_nop.py
#- # Copyright (c) 2011 Robert N. M. Watson # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # License...
# @BERI_LICENSE_HEADER_END@ # from beritest_tools import BaseBERITestCase class test_raw_nop(BaseBERITestCase): def test_raw_nop(self): '''Test that registers are unmodified after NOP''' for i in range(32): self.assertRegisterExpected(i, i, "Modified register after NOP")
#
random_line_split
test_raw_nop.py
#- # Copyright (c) 2011 Robert N. M. Watson # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # License...
self.assertRegisterExpected(i, i, "Modified register after NOP")
conditional_block
test_raw_nop.py
#- # Copyright (c) 2011 Robert N. M. Watson # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # License...
'''Test that registers are unmodified after NOP''' for i in range(32): self.assertRegisterExpected(i, i, "Modified register after NOP")
identifier_body
git_db.py
import os _hook = """#!/bin/sh cd .. env -i git reset --hard > /dev/null 2>&1 env -i git update-index > /dev/null 2>&1 """ def _do_commit(repo, path, content, commit_msg=None): """ Do a commit """ # Create the blob object stream = StringIO(content.encode('utf-8')) stream.seek(0, 2) streamlen = ...
os.chmod(post_receive, 0775) # Create the initial commit _do_commit(repo, u'{0}.md'.format(settings.WIKI_INDEX), '# Home', commit_msg=ugettext(u'Initialize')) return cls(gitdir) def __init__(self, gitdir): """ Initialize repository. """ self.repo = Repo(gitdir.enc...
""" Repository object. """ @classmethod def new(cls, gitdir): """ Initialize a repository and create the root commit """ # Create repository if os.path.exists(gitdir.encode('utf-8')): return cls(gitdir) repo = Repo.init(gitdir.encode('utf-8')) repo.config_w...
identifier_body
git_db.py
import os _hook = """#!/bin/sh cd .. env -i git reset --hard > /dev/null 2>&1 env -i git update-index > /dev/null 2>&1 """ def _do_commit(repo, path, content, commit_msg=None): """ Do a commit """ # Create the blob object stream = StringIO(content.encode('utf-8')) stream.seek(0, 2) streamlen = ...
def rm_content(self, path): """ Remove file located at ``path``. """ self.repo.index.remove([path.encode('utf-8')]) self.repo.index.commit(ugettext(u'Update Wiki: {0} deleted'.format(path)).encode('utf-8')) self.parse() def commit(self, message): """ Create an empty ...
return blob.data_stream.read(), blob.name, blob.mime_type
conditional_block
git_db.py
import os _hook = """#!/bin/sh cd .. env -i git reset --hard > /dev/null 2>&1 env -i git update-index > /dev/null 2>&1 """ def _do_commit(repo, path, content, commit_msg=None): """ Do a commit """ # Create the blob object stream = StringIO(content.encode('utf-8')) stream.seek(0, 2) streamlen = ...
repo.index.add([IndexEntry.from_blob(blob)]) if not commit_msg: commit_msg = ugettext(u'Update Wiki: {0}').format(path).encode('utf-8') repo.index.commit(commit_msg) class Repository(object): """ Repository object. """ @classmethod def new(cls, gitdir): """ Initialize a repo...
# Add blob to the index
random_line_split
git_db.py
import os _hook = """#!/bin/sh cd .. env -i git reset --hard > /dev/null 2>&1 env -i git update-index > /dev/null 2>&1 """ def _do_commit(repo, path, content, commit_msg=None): """ Do a commit """ # Create the blob object stream = StringIO(content.encode('utf-8')) stream.seek(0, 2) streamlen = s...
(self, path): """ Get mimetype of file stored in ``path``. """ if self.is_dir(path): return 'inode/directory' for blob in self.blobs: if blob.path == path: return blob.mime_type def set_content(self, path, content, commit_msg=None): ...
get_file_mimetype
identifier_name
ses_lib.py
from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string class SesLib(object): """ A wrapper around Django's EmailMultiAlternatives that renders txt and html templates. Example Usage: >>> email = Email(to='oz@example....
__author__ = 'radu'
random_line_split
ses_lib.py
__author__ = 'radu' from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string class SesLib(object): """ A wrapper around Django's EmailMultiAlternatives that renders txt and html templates. Example Usage: >>> email = ...
if isinstance(self.to, basestring): self.to = [self.to] if not from_addr: from_addr = getattr(settings, 'EMAIL_FROM_ADDR') msg = EmailMultiAlternatives( self.subject, self._text, from_addr, self.to ) if self._html: ...
identifier_body
ses_lib.py
__author__ = 'radu' from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string class SesLib(object): """ A wrapper around Django's EmailMultiAlternatives that renders txt and html templates. Example Usage: >>> email = ...
msg.send(fail_silently)
msg.attach_alternative(self._html, 'text/html')
conditional_block
ses_lib.py
__author__ = 'radu' from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string class SesLib(object): """ A wrapper around Django's EmailMultiAlternatives that renders txt and html templates. Example Usage: >>> email = ...
(self, template, context): self._text = self._render(template, context) def send(self, from_addr=None, fail_silently=False): if isinstance(self.to, basestring): self.to = [self.to] if not from_addr: from_addr = getattr(settings, 'EMAIL_FROM_ADDR') msg = Email...
text
identifier_name
customauth.service.ts
import * as Auth0 from 'auth0-js'; import { Injectable } from '@angular/core'; import { tokenNotExpired } from 'angular2-jwt'; import { Router } from '@angular/router'; import { AngularFireAuth } from 'angularfire2'; @Injectable() export class { auth0 = new Auth0({ domain: 'rcosonline.auth0.com', c...
}); } public authenticated() { // Check if there's an unexpired JWT // This searches for an item in localStorage with key == 'id_token' return tokenNotExpired(); } public logout() { // Remove token from localStorage localStorage.removeItem('id_token'); this.router.navigate(['\logi...
{ alert("something went wrong: " + err.message); }
conditional_block
customauth.service.ts
import * as Auth0 from 'auth0-js'; import { Injectable } from '@angular/core'; import { tokenNotExpired } from 'angular2-jwt'; import { Router } from '@angular/router'; import { AngularFireAuth } from 'angularfire2'; @Injectable() export class { auth0 = new Auth0({ domain: 'rcosonline.auth0.com', c...
} }
random_line_split
ILifecycleListenerError.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
/** @property {Adaptive.ILifecycleListenerError} [Runtime='Runtime'] */ static Runtime = new ILifecycleListenerError("Runtime"); /** @property {Adaptive.ILifecycleListenerError} [Implementation='Implementation'] */ static Implementa...
{return this.value;}
identifier_body
ILifecycleListenerError.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
return retValue; } } }
{ retValue = ILifecycleListenerError[object.value]; }
conditional_block
ILifecycleListenerError.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
} }
retValue = ILifecycleListenerError[object.value]; } return retValue; }
random_line_split
ILifecycleListenerError.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
(public value:string){} toString(){return this.value;} /** @property {Adaptive.ILifecycleListenerError} [Runtime='Runtime'] */ static Runtime = new ILifecycleListenerError("Runtime"); /** @property {Adaptive.ILifecycleListenerError} [Implement...
constructor
identifier_name
koom-valley-goal.js
(function() { var checkVersion = Dagaz.Model.checkVersion; Dagaz.Model.checkVersion = function(design, name, value) { if (name != "koom-valley-goal") { checkVersion(design, name, value); } } var checkGoals = Dagaz.Model.checkGoals; Dagaz.Model.checkGoals = function(design, board, player) { ...
if (p === null) return; var piece = board.getPiece(p); if (piece === null) return; if (piece.player == 2) cnt++; }); if (cnt >= 3) winner = 2; } } if (winner !== null) { if (winner == player) { return 1; ...
var p = design.navigate(board.player, stone, dir);
random_line_split
koom-valley-goal.js
(function() { var checkVersion = Dagaz.Model.checkVersion; Dagaz.Model.checkVersion = function(design, name, value) { if (name != "koom-valley-goal") { checkVersion(design, name, value); } } var checkGoals = Dagaz.Model.checkGoals; Dagaz.Model.checkGoals = function(design, board, player) { ...
return checkGoals(design, board, player); } })();
{ if (winner == player) { return 1; } else { return -1; } }
conditional_block
noReferenceImportRule.ts
/** * @license * Copyright 2017 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by...
} public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new NoReferenceImportWalker(sourceFile, this.ruleName, undefined)); } } class NoReferenceImportWalker extends Lint.AbstractWalker<void> { private imports = new Set<string>(); public walk(sourceFile:...
random_line_split
noReferenceImportRule.ts
/** * @license * Copyright 2017 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by...
(sourceFile: ts.SourceFile) { if (sourceFile.typeReferenceDirectives.length === 0) { return; } this.findImports(sourceFile.statements); for (const ref of sourceFile.typeReferenceDirectives) { if (this.imports.has(ref.fileName)) { this.addFailure(re...
walk
identifier_name
noReferenceImportRule.ts
/** * @license * Copyright 2017 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by...
} }
{ this.imports.add(specifier.text); }
conditional_block
decorators.ts
import 'reflect-metadata'; import { extend, clone, each, sortBy } from 'lodash'; import { HttpMethodException } from './exceptions'; import { HttpMethod } from './http'; // import { IRequest, IResponse } from './interfaces'; const fromParamsKey: string = 'routing:frommethodparams'; export function Route(route?: strin...
(config?: { route?: string }): MethodDecorator { return HttpMethodDecorator(HttpMethod.POST, config); } export function HttpPut(config?: { route?: string }): MethodDecorator { return HttpMethodDecorator(HttpMethod.PUT, config); } export function HttpDelete(config?: { route?: string }): MethodDecorator { return ...
HttpPost
identifier_name
decorators.ts
import 'reflect-metadata'; import { extend, clone, each, sortBy } from 'lodash'; import { HttpMethodException } from './exceptions'; import { HttpMethod } from './http'; // import { IRequest, IResponse } from './interfaces'; const fromParamsKey: string = 'routing:frommethodparams'; export function Route(route?: strin...
; export function HttpGet(config?: { route?: string, order?: number }): MethodDecorator { return HttpMethodDecorator(HttpMethod.GET, config); } export function HttpPost(config?: { route?: string }): MethodDecorator { return HttpMethodDecorator(HttpMethod.POST, config); } export function HttpPut(config?: { route?...
{ return function(target: any): void { route && Reflect.defineMetadata('mvc:route', route, target); }; }
identifier_body
decorators.ts
import 'reflect-metadata'; import { extend, clone, each, sortBy } from 'lodash'; import { HttpMethodException } from './exceptions'; import { HttpMethod } from './http'; // import { IRequest, IResponse } from './interfaces'; const fromParamsKey: string = 'routing:frommethodparams'; export function Route(route?: strin...
} catch (ex) { res.status(500).json({ error: ex }); } } }); }; }
{ promise && promise.then((json: JSON) => res.status(200).json(json)) .catch((error: string) => res.status(500).json({ error: new HttpMethodException(error) })); }
conditional_block
decorators.ts
import 'reflect-metadata'; import { extend, clone, each, sortBy } from 'lodash'; import { HttpMethodException } from './exceptions'; import { HttpMethod } from './http'; // import { IRequest, IResponse } from './interfaces'; const fromParamsKey: string = 'routing:frommethodparams'; export function Route(route?: strin...
_config.param = param = <any>{}; matches && matches[1] && (param.name = matches[1]); matches && matches[2] && (param.type = matches[2]); matches && (_config.route = _config.route.replace(matches[0], `:${matches[1]}`)); } config = extend(config, _config); } return function(target: O...
if (matches) {
random_line_split
category.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; import { RouterModule } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map';...
return this.counters; } }
{ this.counters.push(i); }
conditional_block
category.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; import { RouterModule } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map';...
() { this.categoryName = this.route.snapshot.params['id']; this._articleService.getCategories() .finally(() => { this.id = this.categories.id; this.run(); }) .subscribe(categories => this.categories = categories.find((x:any) => x.shortName == this.categoryName)); } run() { this._articleSe...
ngOnInit
identifier_name
category.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; import { RouterModule } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map';...
</div> <div [innerHTML]="article.aside.fullStory"></div> </aside> </div> </div> `, providers: [ArticleService], styleUrls: ['./app/articles/category.css'] }) export class CategoryComponent { articles: any[] = []; categories: any; id: number; item: string; done: boolean; ...
<div *ngIf="article?.aside.numberOfImages"> <div *ngFor="let item of createRange(article?.aside.numberOfImages)" class="col-md-12 photo"> [ PHOTO ] </div>
random_line_split
server.rs
extern crate serde_json; use std::net::TcpListener; use std::io::{BufReader, BufRead}; use std::thread; use chat::ChatMessage; use chat::ReplyMessage; use std::sync::mpsc::Sender; pub fn listen(sender: Sender<ReplyMessage>) { let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port"); for...
Err(e) => { println!("{:?}", e); } } } }
{ let sender = sender.clone(); thread::spawn(move || { let reader = BufReader::new(stream); for line in reader.lines() { let message: Result<ChatMessage, _> = serde_json::from_str(line.unwrap().as_str()); ...
conditional_block
server.rs
extern crate serde_json; use std::net::TcpListener; use std::io::{BufReader, BufRead}; use std::thread; use chat::ChatMessage; use chat::ReplyMessage; use std::sync::mpsc::Sender;
pub fn listen(sender: Sender<ReplyMessage>) { let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port"); for stream in listener.incoming() { match stream { Ok(stream) => { let sender = sender.clone(); thread::spawn(move || { ...
random_line_split
server.rs
extern crate serde_json; use std::net::TcpListener; use std::io::{BufReader, BufRead}; use std::thread; use chat::ChatMessage; use chat::ReplyMessage; use std::sync::mpsc::Sender; pub fn
(sender: Sender<ReplyMessage>) { let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port"); for stream in listener.incoming() { match stream { Ok(stream) => { let sender = sender.clone(); thread::spawn(move || { let r...
listen
identifier_name
server.rs
extern crate serde_json; use std::net::TcpListener; use std::io::{BufReader, BufRead}; use std::thread; use chat::ChatMessage; use chat::ReplyMessage; use std::sync::mpsc::Sender; pub fn listen(sender: Sender<ReplyMessage>)
Err(e) => { println!("{:?}", e); } } } }
{ let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port"); for stream in listener.incoming() { match stream { Ok(stream) => { let sender = sender.clone(); thread::spawn(move || { let reader = BufReader::new(stream);...
identifier_body
go.js
/* Language: Go Author: Stephan Kountso aka StepLg <steplg@gmail.com> Contributors: Evgeny Stepanischev <imbolk@gmail.com> Description: Google go language (golang). For info about language Website: http://golang.org/ Category: common, system */ function(hljs) { var GO_KEYWORDS = {
literal: 'true false iota nil', built_in: 'append cap close complex copy imag len make new panic print println real recover delete' }; return { aliases: ['golang'], keywords: GO_KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE,...
keyword: 'break default func interface select case map struct chan else goto package switch ' + 'const fallthrough if range type continue for import return var go defer ' + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + 'uint16 uint32 uint64 int uint ...
random_line_split
pas.py
#!/usr/bin/env python """ Main command line script of the pas package. The main function contained in this module is used ai main entry point for the pas command line utility. The script is automatically created by setuptool, but this file can be directly invoked with `python path/to/pas.py` or directly if its execut...
# Check execution result if res: # ...an error occurred, write the logfile buffered_handler.flush() print print "pas exited with a non-zero exit status (%d). A complete log " \ "was stored in the %s file." % (res, LOGFILE) print else: # ...no e...
res = command.execute(args) # Cleanup fabric connections if needed for key in connections.keys(): connections[key].close() del connections[key]
conditional_block
pas.py
#!/usr/bin/env python """ Main command line script of the pas package. The main function contained in this module is used ai main entry point for the pas command line utility. The script is automatically created by setuptool, but this file can be directly invoked with `python path/to/pas.py` or directly if its execut...
(): """ First function called upon command line invocation. Builds the command line parser, parses the arguments, configures logging and invokes the command. """ # Configure logging file_formatter = logging.Formatter("%(asctime)s - %(levelname)10s - " \ ...
main
identifier_name
pas.py
#!/usr/bin/env python """ Main command line script of the pas package. The main function contained in this module is used ai main entry point for the pas command line utility. The script is automatically created by setuptool, but this file can be directly invoked with `python path/to/pas.py` or directly if its execut...
# Capture all logging output and write it to the specified log file file_handler = logging.FileHandler('pas.log', 'w', delay=True) file_handler.setFormatter(file_formatter) file_handler.setLevel(40) logger = logging.getLogger() logger.setLevel(1) logger.addHandler(console_handler) logge...
""" First function called upon command line invocation. Builds the command line parser, parses the arguments, configures logging and invokes the command. """ # Configure logging file_formatter = logging.Formatter("%(asctime)s - %(levelname)10s - " \ "%(mess...
identifier_body
pas.py
#!/usr/bin/env python """ Main command line script of the pas package. The main function contained in this module is used ai main entry point for the pas command line utility. The script is automatically created by setuptool, but this file can be directly invoked with `python path/to/pas.py` or directly if its execut...
LOGFILE = os.getenv('PAS_LOGFILE') or 'pas.log' """Logfile name, settable using the PAS_LOGFILE env variable""" VERBOSITY = logging.INFO """Default verbosity for console output""" def main(): """ First function called upon command line invocation. Builds the command line parser, parses the arguments, ...
# pylint: disable-msg=W0105 # Docstring for variables are not recognized by pylint, but epydoc parses them
random_line_split
data.ts
export const TEST_1_CONTENT = ` import PropTypes from "prop-types"; import React from "react"; type MyComponentProps = {
type MyComponentState = { username: string; password: string; }; class MyComponent extends React.Component<MyComponentProps, MyComponentState> { static propTypes: any; render() { return ( <React.Fragment> <div className="test-container">Well</div> <div className="test-footer" id="an-...
login: any; };
random_line_split
react.js
/* */ "format cjs"; "use strict"; exports.__esModule = true; exports.CallExpression = CallExpression; exports.ModuleDeclaration = ModuleDeclaration; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null)
newObj["default"] = obj; return newObj; } } var _messages = require("../../../messages"); var messages = _interopRequireWildcard(_messages); var _types = require("../../../types"); var t = _interopRequireWildcard(_types); // check if the input Literal `source` is an alternate casing of "react" function check(sour...
{ for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }
conditional_block
react.js
/* */ "format cjs"; "use strict"; exports.__esModule = true; exports.CallExpression = CallExpression; exports.ModuleDeclaration = ModuleDeclaration; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototyp...
(node, parent, scope, file) { if (this.get("callee").isIdentifier({ name: "require" }) && node.arguments.length === 1) { check(node.arguments[0], file); } } function ModuleDeclaration(node, parent, scope, file) { check(node.source, file); }
CallExpression
identifier_name
react.js
/* */ "format cjs"; "use strict"; exports.__esModule = true; exports.CallExpression = CallExpression; exports.ModuleDeclaration = ModuleDeclaration; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototyp...
if (lower === "react" && name !== lower) { throw file.errorWithNode(source, messages.get("didYouMean", "react")); } } } function CallExpression(node, parent, scope, file) { if (this.get("callee").isIdentifier({ name: "require" }) && node.arguments.length === 1) { check(node.arguments[0], file); ...
function check(source, file) { if (t.isLiteral(source)) { var name = source.value; var lower = name.toLowerCase();
random_line_split
react.js
/* */ "format cjs"; "use strict"; exports.__esModule = true; exports.CallExpression = CallExpression; exports.ModuleDeclaration = ModuleDeclaration; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototyp...
function ModuleDeclaration(node, parent, scope, file) { check(node.source, file); }
{ if (this.get("callee").isIdentifier({ name: "require" }) && node.arguments.length === 1) { check(node.arguments[0], file); } }
identifier_body
mouse-push-button.js
/* * default/mouse-push-button.js */ "use strict"; var Q = require('q'), Button = require('./../../button'); var MousePushButton = function (options) { Button.prototype.constructor.call(this, options); this.delay = options.delay > 0 ? options.delay : 0; this.g = null; if(typeof options.g === 'f...
; F.prototype = proto; return new F(); })(Button.prototype); MousePushButton.prototype.constructor = MousePushButton; MousePushButton.prototype.setG = function (g) { if (typeof g !== 'function') throw new Error("Button setG method needs a g function as argument."); this.g = g; return this;...
{}
identifier_body
mouse-push-button.js
/* * default/mouse-push-button.js */ "use strict"; var Q = require('q'), Button = require('./../../button'); var MousePushButton = function (options) { Button.prototype.constructor.call(this, options); this.delay = options.delay > 0 ? options.delay : 0; this.g = null; if(typeof options.g === 'f...
btn.el.ownerDocument.removeEventListener('mouseup', btn, false); }; }; module.exports = MousePushButton;
btn.setActive(false); btn.leftOrEnded = false; btn.el.ownerDocument.removeEventListener('mousemove', btn, false);
random_line_split
mouse-push-button.js
/* * default/mouse-push-button.js */ "use strict"; var Q = require('q'), Button = require('./../../button'); var MousePushButton = function (options) { Button.prototype.constructor.call(this, options); this.delay = options.delay > 0 ? options.delay : 0; this.g = null; if(typeof options.g === 'f...
() {}; F.prototype = proto; return new F(); })(Button.prototype); MousePushButton.prototype.constructor = MousePushButton; MousePushButton.prototype.setG = function (g) { if (typeof g !== 'function') throw new Error("Button setG method needs a g function as argument."); this.g = g; return ...
F
identifier_name
mouse-push-button.js
/* * default/mouse-push-button.js */ "use strict"; var Q = require('q'), Button = require('./../../button'); var MousePushButton = function (options) { Button.prototype.constructor.call(this, options); this.delay = options.delay > 0 ? options.delay : 0; this.g = null; if(typeof options.g === 'f...
} }; MousePushButton.prototype.onMousemove = function (evt) { if(this.active && !this.leftOrEnded) { evt.preventDefault(); if (!this._isInActiveZone(evt)) this.onMouseup(evt); } }; MousePushButton.prototype.onMouseup = function (evt) { if(this.active && !this.leftOrEnded) ...
{ evt.preventDefault(); this.setActive(true); var boundingRect = this.el.getBoundingClientRect(); this.boundaries.minX = boundingRect.left; this.boundaries.maxX = boundingRect.left + boundingRect.width; this.boundaries.minY = boundingRect.top; ...
conditional_block
editor-gtk.py
#! /usr/bin/env python import sys import os import gtk from arithmetic import Parser class Editor(object): 'A minimal editor' def __init__(self): # path to UI file scriptPath = os.path.split( sys.argv[0] )[0] uiFilePath = os.path.join( scriptPath,'editor.ui' ) self.builder = ...
# Insert iter_start = textBuffer.get_iter_at_line_offset( i, start ) textBuffer.insert( iter_start, text ) def calculate( widget, event, textbuffer ): 'Perform arithmetic operations' if event.keyval == gtk.keysyms.F5: parser = ParserGTK() parser.parse( textbuffer ) ...
iter_line = textBuffer.get_iter_at_line( i ) nchars = iter_line.get_chars_in_line() if start > nchars-1: start = nchars-1 iter_start = textBuffer.get_iter_at_line_offset( i, start ) iter_end = textBuffer.get_iter_at_line_offset( i, end ) textBu...
conditional_block