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
spot_launcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import boto.ec2 from boto.ec2.blockdevicemapping import BlockDeviceType from boto.ec2.blockdevicemapping import BlockDeviceMapping import time import copy import argparse import sys import pprint import os import yaml BASE_PATH = os.path.dirname(os.path.abspath(__file__))...
def create_mapping(config): if 'mapping' not in config: return None mapping = BlockDeviceMapping() for ephemeral_name, device_path in config['mapping'].iteritems(): ephemeral = BlockDeviceType() ephemeral.ephemeral_name = ephemeral_name mapping[device_path] = ephemeral ...
config_file = open(os.path.join(CONFIG_PATH, config_file_name)) config_dict = yaml.load(config_file.read()) return config_dict
identifier_body
spot_launcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import boto.ec2 from boto.ec2.blockdevicemapping import BlockDeviceType from boto.ec2.blockdevicemapping import BlockDeviceMapping import time import copy import argparse import sys import pprint import os import yaml BASE_PATH = os.path.dirname(os.path.abspath(__file__))...
return instance_ids def get_config(config_file_name): config_file = open(os.path.join(CONFIG_PATH, config_file_name)) config_dict = yaml.load(config_file.read()) return config_dict def create_mapping(config): if 'mapping' not in config: return None mapping = BlockDeviceMapping() ...
tag_instances(conn, instance_ids, config['tags'])
conditional_block
publish_test.js
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.i...
before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'); }); before(function() { Ironium.configure(getAWSConfig()); process.env.NODE_ENV = 'production'; }); before(function() { snsSubscribedQueue.eachJob(processJob); }); before(function() { ...
{ const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); }
identifier_body
publish_test.js
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.i...
const randomValue = Crypto.randomBytes(32).toString('hex'); function processJob(notification) { const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); } before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'...
// We test that publish works by consuming from this queue // (which must be subscribed to the topic). let snsSubscribedQueue; const processedJobs = [];
random_line_split
publish_test.js
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.i...
(notification) { const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); } before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'); }); before(function() { Ironium.configure(getAWSConfig()); process.env.N...
processJob
identifier_name
submissions.js
app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) { $scope.stats = {}; $scope.getUrlLanguages = function(gitUrlId){ globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){ $scope.stats[git...
if (!_new || !_new_name) { $scope.showWarning = true; return; } var _newUrl = globalHelpers.getLocation(_new); var pathArray = _newUrl.pathname.split('/'); isCommit = pathArray.indexOf('commit') > -1; isPR = pathArray.indexOf('pull') > -1; ...
{ $scope.showWarning = true; return; }
conditional_block
submissions.js
app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) { $scope.stats = {}; $scope.getUrlLanguages = function(gitUrlId){ globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){ $scope.stats[git...
var obj = JSON.parse('{"github_user": "' + $scope.github_user + '", "name": "' + _new_name + '", "url": "' + _new + '"}'); for (var i=0; i < $scope.existing.length; i++){ if (Object.keys($scope.existing[i])[0] == _new){ return; } } ...
if (_newUrl.hostname != "github.com" || (!isCommit && !isPR)){ $scope.showGithubWarning = true; return; }
random_line_split
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--disable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_organization_id_too_big(self): invalid_organization_id = 2**64 actual = update_gcp_set...
test_initialize_command_line_args_disable_ingestion
identifier_name
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
unittest.main()
conditional_block
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
if __name__ == "__main__": unittest.main()
mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=200) update_gcp_settings.update_gcp_settings(mock_session, 123, True)
identifier_body
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
class UpdateGCPSettingsTest(unittest.TestCase): def test_initialize_command_line_args_enable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--enable"]) self.assertIsNotNone(actual) def test_initialize_command_...
from google.auth.transport import requests from . import update_gcp_settings
random_line_split
sokoban.rs
#![crate_type = "bin"] #![allow(unused_must_use)] //extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod ...
{ let args = os::args(); let contents; if args.len() > 1 { contents = File::open(&Path::new(args[1].as_slice())).read_to_str(); println!("Reading from file."); } else { contents = stdin().read_to_str(); println!("Reading from stdin."); } let board: SokoBoard = FromStr::from_str( contents.un...
identifier_body
sokoban.rs
#![crate_type = "bin"]
//extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod sokoboard; mod sokoannotatedboard; fn main() { le...
#![allow(unused_must_use)]
random_line_split
sokoban.rs
#![crate_type = "bin"] #![allow(unused_must_use)] //extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod ...
() { let args = os::args(); let contents; if args.len() > 1 { contents = File::open(&Path::new(args[1].as_slice())).read_to_str(); println!("Reading from file."); } else { contents = stdin().read_to_str(); println!("Reading from stdin."); } let board: SokoBoard = FromStr::from_str( contents...
main
identifier_name
sokoban.rs
#![crate_type = "bin"] #![allow(unused_must_use)] //extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod ...
let board: SokoBoard = FromStr::from_str( contents.unwrap() ) .expect("Invalid sokoban board"); let annotated = SokoAnnotatedBoard::fromSokoBoard(board); do_sylvan(&annotated); }
{ contents = stdin().read_to_str(); println!("Reading from stdin."); }
conditional_block
ibm2.py
on the counts from the E step
j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the target sentence s: A word in the source language t: A word in the target language References: Philipp Koehn. 2010. Statistical Machine Transl...
Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence
random_line_split
ibm2.py
0 (for NULL), 1, 2, ..., length of source sentence j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the target sentence s: A word in the source language t: A word in the target language Referen...
_align_all(
identifier_name
ibm2.py
the counts from the E step Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in...
0.0 >>> print(ibm2.alignment_table[1][1][2][2]) 0.938... >>> print(round(ibm2.alignment_table[1][2][2][2], 3)) 0.0 >>> print(round(ibm2.alignment_table[2][2][4][5], 3)) 1.0 >>> test_sentence = bitext[2] >>> test_sentence.words ['das', 'buch', 'ist', 'ja', 'klein'] >>> test_...
""" Lexical translation model that considers word order >>> bitext = [] >>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big'])) >>> bitext.append(AlignedSent(...
identifier_body
ibm2.py
counts from the E step Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the...
return alignment_prob_for_t def prob_alignment_point(self, i, j, src_sentence, trg_sentence): """ Probability that position j in ``trg_sentence`` is aligned to position i in the ``src_sentence`` """ l = len(src_sentence) - 1 m = len(trg_sentence) - 1 ...
lignment_prob_for_t[t] += self.prob_alignment_point( i, j, src_sentence, trg_sentence)
conditional_block
config.rs
use errors::*; use modules::{centerdevice, pocket, slack}; use std::fs::File; use std::io::Read; use std::path::Path; use toml; #[derive(Debug, Deserialize)] #[serde(tag = "format")] #[derive(PartialOrd, PartialEq, Eq)] #[derive(Clone, Copy)] pub enum OutputFormat { JSON, HUMAN, } impl<'a> From<&'a str> for ...
(format: &'a str) -> Self { let format_sane: &str = &format.to_string().to_uppercase(); match format_sane { "JSON" => OutputFormat::JSON, _ => OutputFormat::HUMAN } } } #[derive(Debug, Deserialize)] #[serde(tag = "verbosity")] #[derive(PartialOrd, PartialEq, Eq)] #[d...
from
identifier_name
config.rs
use errors::*; use modules::{centerdevice, pocket, slack}; use std::fs::File; use std::io::Read; use std::path::Path;
#[derive(PartialOrd, PartialEq, Eq)] #[derive(Clone, Copy)] pub enum OutputFormat { JSON, HUMAN, } impl<'a> From<&'a str> for OutputFormat { fn from(format: &'a str) -> Self { let format_sane: &str = &format.to_string().to_uppercase(); match format_sane { "JSON" => OutputFormat:...
use toml; #[derive(Debug, Deserialize)] #[serde(tag = "format")]
random_line_split
label_image.py
import tensorflow as tf, sys image_path = sys.argv[1] # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("/cellule/retrained_labels.txt")] # Unpersists graph from ...
# To run the program - docker run -it -v ~/Desktop/cellule/:/cellule/ gcr.io/tensorflow/tensorflow:latest-devel # Enter the above line of code in the docker command prompt # Then enter - python /cellule/label_image.py <image_location> next to the # in the docker command prompt
human_string = label_lines[node_id] score = predictions[0][node_id] print('%s (score = %.5f)' % (human_string, score))
conditional_block
label_image.py
import tensorflow as tf, sys image_path = sys.argv[1] # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("/cellule/retrained_labels.txt")] # Unpersists graph from ...
# To run the program - docker run -it -v ~/Desktop/cellule/:/cellule/ gcr.io/tensorflow/tensorflow:latest-devel # Enter the above line of code in the docker command prompt # Then enter - python /cellule/label_image.py <image_location> next to the # in the docker command prompt
random_line_split
pt-br.js
Add": "Adicionar", "btnModify": "Modificar", "btnUp": "Para cima", "btnDown": "Para baixo", "btnSetValue": "Definir como selecionado", "btnDelete": "Remover" }, "textarea": {"title": "Formatar Área de Texto", "cols": "Colunas", "rows": "Linhas"...
"preview": {"preview": "Visualizar"},
random_line_split
method-two-trait-defer-resolution-2.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 ...
fn main() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
{ let mut x = Vec::new(); let y = x.foo(); x.push(box 0i); y }
identifier_body
method-two-trait-defer-resolution-2.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) -> int {2} } fn call_foo_copy() -> int { let mut x = Vec::new(); let y = x.foo(); x.push(0u); y } fn call_foo_other() -> int { let mut x = Vec::new(); let y = x.foo(); x.push(box 0i); y } fn main() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
foo
identifier_name
cli.js
#!/usr/bin/env node // Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE 'use strict'; const sysPath = require('path'); const fs = require('fs'); const yargs = require('yargs'); const PWMetrics = require('../lib/index'); const { getConfigFromFile } = requir...
}) .option('disable-cpu-throttling', { 'describe': 'Disable CPU throttling', 'type': 'boolean', 'default': false }) .epilogue('For more Lighthouse CLI options see https://github.com/GoogleChrome/lighthouse/#lighthouse-cli-options') .argv; const config = getConfigFromFile(cliFlags.config); //Merg...
'describe': 'Path to config file', 'type': 'string',
random_line_split
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: retur...
self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <folding> # <name>apply</name> # <src name="ant"> # <bgf:production> # ... # </bgf:production> # </src> # </folding> class Folding (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('state/'+slpsns.bgf_('production')+'/nont...
random_line_split
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: retur...
+= 'n('+self.nt+')' if self.sep: s += ', n('+self.sep+')' return s # <selectables> # <src name="..."> # <bgf:production> # ... # <marked> # ... # </marked> # ... # </bgf:production> # </src> # </selectables> class Selectables (SrcProdModel): def __init__(self, xml): self.parse(xml) def...
'['+self.label+'], ' s
conditional_block
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: retur...
def parsebasic(self, xml): global cx if 'id' in xml.attrib: self.id = xml.attrib['id'] else: if self.who() in cx: cx[self.who()] += 1 else: cx[self.who()] = 1 self.id = self.who()+str(cx[self.who()]) if 'depends' in xml.attrib: self.depends = xml.attrib['depends'] else: self.depend...
return self.__class__.__name__
identifier_body
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: retur...
rodModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <top-choice> # <name>ops</name> # <src name="ant">horizontal</src> # <src name="dcg,sdf,rsc">vertical</src> # </top-choice> class TopChoice (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') se...
bel (SrcP
identifier_name
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word...
return embedding_matrix #transfer each word to word id def transfer_data(word_vec, word_dict): vec = [] for word in word_vec: if not word in word_dict: word_dict[word] = len(word_dict) vec.append(word_dict[word]) return vec def sim_max(sentence, labelId, embedding_matrix): ...
ids = word_dict[terms[0]] embedding_vec = np.asarray(terms[1:], dtype='float32') embedding_matrix[ids] = embedding_vec
conditional_block
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word...
(sentence, labelId, embedding_matrix): max_sim = 0.0 for ids in sentence: embedding = embedding_matrix[ids] simlarity = 1.0 - cosine(embedding, embedding_matrix[labelId]) if max_sim < simlarity: max_sim = simlarity return max_sim def avg_embedding(sentences, embedding_mat...
sim_max
identifier_name
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word...
tag_map = {} tag_file = open(TAG_FILE_PATH, 'rb') for line in tag_file: tag = line.rstrip() add = True for item in tag_map.keys(): if item == tag: #replacy by similarity() function later add = False break if add: tag_map...
# Read tag file ################################################################### TAG_FILE_PATH = "./tag.list"
random_line_split
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word...
def avg_embedding(sentences, embedding_matrix): word_embeddings = [] for sentence in sentences: for ids in sentence: embedding = embedding_matrix[ids] word_embeddings.append(embedding) return np.mean(word_embeddings, axis = 0) #select sentences def filter_dataset_seq(labelI...
max_sim = 0.0 for ids in sentence: embedding = embedding_matrix[ids] simlarity = 1.0 - cosine(embedding, embedding_matrix[labelId]) if max_sim < simlarity: max_sim = simlarity return max_sim
identifier_body
instr_pminsb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn pminsb_1() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XM...
() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 5...
pminsb_2
identifier_name
instr_pminsb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*;
use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn pminsb_1() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: No...
random_line_split
instr_pminsb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn pminsb_1()
#[test] fn pminsb_2() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: Non...
{ run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword) }
identifier_body
day_4.rs
use std::str::Chars; use self::DisplayResult::{Output, NotANumber}; use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum
{ Output(Vec<Number>), NotANumber } impl From<Chars<'static>> for DisplayResult { fn from(chars: Chars) -> DisplayResult { let len = chars.as_str().len(); let mut vec = Vec::with_capacity(len); for c in chars { if c < '0' || c > '9' { return NotANumber;...
DisplayResult
identifier_name
day_4.rs
use std::str::Chars; use self::DisplayResult::{Output, NotANumber}; use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum DisplayResult { Output(Vec<Number>), NotANumber } impl From<Chars<'static>> for DisplayResult { fn from(chars: Chars) -...
input: None } } pub fn output(&self) -> DisplayResult { match self.input { Some(data) => DisplayResult::from(data.chars()), None => Output(vec![]), } } pub fn input(&mut self, data: &'static str) { self.input = Some(data); } }
pub fn new() -> Display { Display {
random_line_split
day_4.rs
use std::str::Chars; use self::DisplayResult::{Output, NotANumber}; use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum DisplayResult { Output(Vec<Number>), NotANumber } impl From<Chars<'static>> for DisplayResult { fn from(chars: Chars) -...
}
{ self.input = Some(data); }
identifier_body
init.rs
Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` var...
create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("content"); create_dir(&content).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remo...
{ remove_dir_all(&dir).expect("Could not free test directory"); }
conditional_block
init.rs
Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` var...
#[test] fn init_quasi_empty_directory() { let mut dir = temp_dir(); dir.push("test_quasi_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mu...
{ let mut dir = temp_dir(); dir.push("test_non_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("conte...
identifier_body
init.rs
Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` var...
() { let mut dir = temp_dir(); dir.push("test_non_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("co...
init_non_empty_directory
identifier_name
init.rs
# Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` va...
); } }; // If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error if entries.any(|x| match x { Ok(file) => !file .file_name() .to_str() .expect("Could not convert filename to &...
Err(e) => { bail!( "Could not read `{}` because of error: {}", path.to_string_lossy().to_string(), e
random_line_split
assignment_tracker.rs
use common::*; use disassembler::*; use instruction_graph::*; pub struct AssignmentTracker; impl AssignmentTracker { // NOTE: expects reversed graph pub fn find( graph: &InstructionGraph, address: u64, register: Reg, try_match: &mut FnMut(&Insn, Reg) -> bool, ) -> Option<u64...
} None } }
} }
random_line_split
assignment_tracker.rs
use common::*; use disassembler::*; use instruction_graph::*; pub struct
; impl AssignmentTracker { // NOTE: expects reversed graph pub fn find( graph: &InstructionGraph, address: u64, register: Reg, try_match: &mut FnMut(&Insn, Reg) -> bool, ) -> Option<u64> { let mut skipped_initial_instruction = false; let mut stack = vec![addre...
AssignmentTracker
identifier_name
assignment_tracker.rs
use common::*; use disassembler::*; use instruction_graph::*; pub struct AssignmentTracker; impl AssignmentTracker { // NOTE: expects reversed graph pub fn find( graph: &InstructionGraph, address: u64, register: Reg, try_match: &mut FnMut(&Insn, Reg) -> bool, ) -> Option<u64...
let insn = graph.get_vertex(&address); if try_match(insn, register) { match insn.operands[1] { Operand::Register(_, r) => { return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| { if let Opera...
{ let mut skipped_initial_instruction = false; let mut stack = vec![address]; while !stack.is_empty() { let address = stack.pop().unwrap(); for pair in graph.get_adjacent(&address).into_iter().rev() { if let Ok((addr, link)) = pair { m...
identifier_body
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2...
function next_test() { if (tests.length == 0) do_test_finished(); else { asyncOpenCacheEntry(URL, "FTP", Components.interfaces.nsICache.STORE_ANYWHERE, Components.interfaces.nsICache.ACCESS_READ_WRITE, storeDat...
{ do_check_eq(status, Components.results.NS_OK); entry.setMetaDataElement("servertype", "0"); var os = entry.openOutputStream(0); var written = os.write(tests[0][0], tests[0][0].length); if (written != tests[0][0].length) { do_throw("os.write has not written all data!\n" + " Expected: " + w...
identifier_body
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2...
os.close(); entry.close(); var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); var channel = ios.newChannel(URL, "", null); channel.asyncOpen(new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); } function next_test() {...
{ do_throw("os.write has not written all data!\n" + " Expected: " + written + "\n" + " Actual: " + tests[0][0].length + "\n"); }
conditional_block
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2...
do_check_eq(status, Components.results.NS_OK); entry.setMetaDataElement("servertype", "0"); var os = entry.openOutputStream(0); var written = os.write(tests[0][0], tests[0][0].length); if (written != tests[0][0].length) { do_throw("os.write has not written all data!\n" + " Expected: " + wri...
next_test(); } function storeData(status, entry) {
random_line_split
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2...
() { do_execute_soon(next_test); do_test_pending(); }
run_test
identifier_name
unwind.rs
// taken from https://github.com/thepowersgang/rust-barebones-kernel #[lang="panic_fmt"] #[no_mangle] pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { // 'args' will print to the formatted string passed to panic! log!("file='{}', line={} :: {}", file, line, args...
() -> ! { loop {} } #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] pub enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_FOREIGN_EXCEPTION_CAUGHT = 1, _URC_FATAL_PHASE2_ERROR = 2, _URC_FATAL_PHASE1_ERROR = 3, _URC_NORMAL_STOP = 4, _URC_END_OF_STACK = 5, _URC_HANDLER_...
__morestack
identifier_name
unwind.rs
// taken from https://github.com/thepowersgang/rust-barebones-kernel #[lang="panic_fmt"] #[no_mangle] pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { // 'args' will print to the formatted string passed to panic! log!("file='{}', line={} :: {}", file, line, args...
loop {} } #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] pub enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_FOREIGN_EXCEPTION_CAUGHT = 1, _URC_FATAL_PHASE2_ERROR = 2, _URC_FATAL_PHASE1_ERROR = 3, _URC_NORMAL_STOP = 4, _URC_END_OF_STACK = 5, _URC_HANDLER_FOUND = 6,...
#[lang="stack_exhausted"] #[no_mangle] pub extern "C" fn __morestack() -> ! {
random_line_split
unwind.rs
// taken from https://github.com/thepowersgang/rust-barebones-kernel #[lang="panic_fmt"] #[no_mangle] pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { // 'args' will print to the formatted string passed to panic! log!("file='{}', line={} :: {}", file, line, args...
#[no_mangle] #[allow(non_snake_case)] pub extern "C" fn _Unwind_Resume() { loop {} }
{ loop {} }
identifier_body
Interface.js
.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> *...
}, /** * Asserts that the given object implements all the methods defined in the * interface. This method throws an exception if the object does not * implement the interface. * * @param object {qx.core.Object} Object to check interface for * @param iface {Interface} The inter...
{ for (var key in iface.$$events) { if (!qx.util.OOUtil.supportsEvent(clazz, key)) { throw new Error( 'The event "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } }
conditional_block
Interface.js
qx.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> ...
} } else { // Create empty interface var iface = {}; } // Add Basics iface.$$type = "Interface"; iface.name = name; // Attach toString iface.toString = this.genericToString; // Assign to namespace iface.basename = qx.Bootstrap....
iface.$$events = config.events;
random_line_split
Interface.js
("qx.debug")) { this.__validateConfig(name, config); } // Create interface from statics var iface = config.statics ? config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) ...
wrappedFunction
identifier_name
Interface.js
config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) { iface.$$properties = config.properties; } if (config.members) { iface.$$members = config.members; } ...
{ // call precondition preCondition.apply(this, arguments); // call original function return origFunction.apply(this, arguments); }
identifier_body
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import Pac...
def output_package_listing_columns(self, data, header): # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: ...
logger.info(format_for_json(packages, options))
conditional_block
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import Pac...
data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: ...
identifier_body
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import Pac...
def tabulate(vals): # From pfmoore on GitHub: # https://github.com/pypa/pip/issues/3651#issuecomment-216932564 assert len(vals) > 0 sizes = [0] * max(len(x) for x in vals) for row in vals: sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)] result = [] for row in va...
for val in pkg_strings: logger.info(val)
random_line_split
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import Pac...
(self, packages, options): dep_keys = set() for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) return {pkg for pkg in packages if pkg.key not in dep_keys} def iter_packages_latest_infos(self, packages, options): index_urls = [option...
get_not_required
identifier_name
search.js
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); }; Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; ...
else if (value != this.lastQuery) { this.lastQuery = value; this.$result.attr('aria-busy', 'true'); this.$result.attr('aria-expanded', 'true'); this.firstRun = true; this.searcher.find(value); } }; this.addResults = function(results, isLast) { var target = this.$result.ge...
{ this.lastQuery = value; this.$result.empty(); this.$result.attr('aria-expanded', 'false'); this.setNavigationActive(false); }
conditional_block
search.js
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); }; Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; ...
replace(/\u0001/g, '<em>'). replace(/\u0002/g, '</em>'); }; this.escapeHTML = function(html) { return html.replace(/[&<>]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } });
return true; }; this.hlt = function(html) { return this.escapeHTML(html).
random_line_split
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expec...
'93.95.227.222' ] self.report['expected_results'] = self.expected_results with open('/etc/resolv.conf') as f: for line in f: if line.startswith('nameserver'): sel...
self.expected_results = [] self.dns_servers = [] if self.input: self.hostname = self.input elif self.localOptions['target']: self.hostname = self.localOptions['target'] else: self.hostname = "torproject.org" if self.localOptions['expected']: ...
identifier_body
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expec...
(self): """ Googles 8.8.8.8 server is queried, in order to generate control data. """ results = yield self.performALookup(self.hostname, ("8.8.8.8", 53) ) if results: self.report['control_results'] = results
test_control_results
identifier_name
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expec...
if self.localOptions['expected']: with open (self.localOptions['expected']) as file: for line in file: self.expected_results.append(line.strip()) else: self.expected_results = [ '154.35.132.70', ...
else: self.hostname = "torproject.org"
random_line_split
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expec...
return True @defer.inlineCallbacks def test_dns_comparison(self): """ Performs A lookup on specified host and matches the results against a set of expected results. When not specified, host and expected results default to "torproject.org" and ['38.229.72....
return False
conditional_block
gcccuda.py
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
"""Compiler toolchain with GCC and CUDA.""" NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
identifier_body
gcccuda.py
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
(GccToolchain, Cuda): """Compiler toolchain with GCC and CUDA.""" NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
GccCUDA
identifier_name
gcccuda.py
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
random_line_split
platform.d.ts
/* tslint:disable:class-name */ /** * Contains all kinds of information about the device, its operating system and software. */ declare module "platform" { /* * Enum holding platform names. */ export module platformNames { export var android: string; export var ios: string; } ...
* The logical density of the display. This is a scaling factor for the Density Independent Pixel unit. */ scale: number; } /** * An object describing general information about a display. */ export class screen { /** * Gets information about the main scre...
/**
random_line_split
platform.d.ts
/* tslint:disable:class-name */ /** * Contains all kinds of information about the device, its operating system and software. */ declare module "platform" { /* * Enum holding platform names. */ export module platformNames { export var android: string; export var ios: string; } ...
{ /** * Gets the manufacturer of the device. * For example: "Apple" or "HTC" or "Samsung". */ static manufacturer: string; /** * Gets the model of the device. * For example: "Nexus 5" or "iPhone". */ static model: string; /...
device
identifier_name
player-name-check.js
'use strict'; /** * Confirm new player name */ module.exports = (srcPath) => { const EventUtil = require(srcPath + 'EventUtil'); return { event: state => (socket, args) => { const say = EventUtil.genSay(socket); const write = EventUtil.genWrite(socket); write(`<bold>${args.name} doesn't e...
if (confirmation === 'n') { say(`Let's try again...`); return socket.emit('create-player', socket, args); } return socket.emit('finish-player', socket, args); }); } }; };
return socket.emit('player-name-check', socket, args); }
random_line_split
player-name-check.js
'use strict'; /** * Confirm new player name */ module.exports = (srcPath) => { const EventUtil = require(srcPath + 'EventUtil'); return { event: state => (socket, args) => { const say = EventUtil.genSay(socket); const write = EventUtil.genWrite(socket); write(`<bold>${args.name} doesn't e...
if (confirmation === 'n') { say(`Let's try again...`); return socket.emit('create-player', socket, args); } return socket.emit('finish-player', socket, args); }); } }; };
{ return socket.emit('player-name-check', socket, args); }
conditional_block
test_qcut.py
import os import numpy as np import pytest from pandas import ( Categorical, DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pan...
@pytest.mark.parametrize( "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)] ) @pytest.mark.parametrize("length", [1, 2]) @pytest.mark.parametrize("labels", [None, False]) def test_single_quantile(data, start, end, length, labels): # see gh-15431 ser = Series([data] * length)...
result = qcut(values, 3, **kwargs) expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)]) tm.assert_index_equal(result.categories, expected)
conditional_block
test_qcut.py
import os import numpy as np import pytest from pandas import ( Categorical, DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pan...
def test_qcut_nas(): arr = np.random.randn(100) arr[:20] = np.nan result = qcut(arr, 4) assert isna(result[:20]).all() def test_qcut_index(): result = qcut([0, 2], 2) intervals = [Interval(-0.001, 1), Interval(1, 2)] expected = Categorical(intervals, ordered=True) tm.assert_catego...
values = np.arange(10) ii = qcut(values, 4) ex_levels = IntervalIndex( [ Interval(-0.001, 2.25), Interval(2.25, 4.5), Interval(4.5, 6.75), Interval(6.75, 9), ] ) tm.assert_index_equal(ii.categories, ex_levels)
identifier_body
test_qcut.py
import os import numpy as np import pytest from pandas import (
DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pandas.core.algorithms import quantile import pandas.util.testing as tm from pandas.t...
Categorical,
random_line_split
test_qcut.py
import os import numpy as np import pytest from pandas import ( Categorical, DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pan...
(datapath): # see gh-1978, gh-1979 cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv")) arr = np.loadtxt(cut_file) result = qcut(arr, 20) starts = [] ends = [] for lev in np.unique(result): s = lev.left e = lev.right assert s != e starts.app...
test_qcut_binning_issues
identifier_name
lint.py
to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not config_path or not processed_config_path: return if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content = f.re...
if not os.path.exists(result_path): raise # Sometimes produces empty (almost) files: if os.path.getsize(result_path) < 10: if can_fail_build: raise elif not silent: traceback.print_exc() return # There are actual lint issues try: ...
stderr_filter=stderr_filter) except build_utils.CalledProcessError: # There is a problem with lint usage
random_line_split
lint.py
to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def
(): if not config_path or not processed_config_path: return if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_pa...
_ProcessConfigFile
identifier_name
lint.py
.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(res...
sources = build_utils.ParseGypList(args.java_files)
conditional_block
lint.py
def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsB...
def _RelativizePath(path): """Returns relative path to top-level src dir. Args: path: A path relative to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not config_path or not processed_config_path: return if not build_utils.IsTimeSt...
identifier_body
test_update.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
elf.data['postponement'] = "0" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (without report)."))
identifier_body
test_update.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
self): self.data['postponement'] = "0" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (withou...
est_update_message_without_report(
identifier_name
test_update.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core bu...
learning_container_year__container_type=EXTERNAL, learning_container_year__requirement_entity=cls.entity, learning_container_year__allocation_entity=cls.entity, ) cls.data = get_valid_external_learning_unit_form_data(cls.academic_year, cls.luy, cls.entity) cl...
acronym="EFAC1000",
random_line_split
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ ...
(originalArray, count) { for (var key in originalArray) { if (key == 'cssStyles') { originalArray[key] = fixArray(originalArray[key], count); } else if (originalArray[key].length == count) { originalArray[key] = originalArray[key][0]; } e...
fixArray
identifier_name
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ ...
case 'slideOut': btOptions['hideTip'] = function(box, callback) { var width = $("body").width(); $(box).animate({"left": "+=" + width + "px"}, "slow", callback); } break; } return btOptions; } })(jQuery);
{ switch (animations['on']) { case 'none': break; case 'fadeIn': btOptions['showTip'] = function(box) { $(box).fadeIn(500); }; break; case 'slideIn': break; } switch (animations['off']) { case 'none': break; case 'fadeOu...
identifier_body
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ ...
return; } $(box).hide(); callback(); } } // Run any java script that needs to be run when the page loads if (beautytips[key]['contentSelector'] && beautytips[key]['preEval']) { $(beautytips[key]['cssSelect']).each(fu...
random_line_split
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ ...
return false; } function beautytipsAddAnimations(animations, btOptions) { switch (animations['on']) { case 'none': break; case 'fadeIn': btOptions['showTip'] = function(box) { $(box).fadeIn(500); }; break; case 'slideIn': break; } ...
{ $(element).addClass('beautytips-module-processed'); }
conditional_block
cond-macro.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { assert_eq!(clamp(1, 2, 4), 2); assert_eq!(clamp(8, 2, 4), 4); assert_eq!(clamp(3, 2, 4), 3); }
{ cond!( (x > mx) { mx } (x < mn) { mn } _ { x } ) }
identifier_body
cond-macro.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// except according to those terms. fn clamp<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T { cond!( (x > mx) { mx } (x < mn) { mn } _ { x } ) } fn main() { assert_eq!(clamp(1, 2, 4), 2); assert_eq!(clamp(8, 2, 4), 4); assert_eq!(clamp(3, 2, 4), 3); }
random_line_split
cond-macro.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T { cond!( (x > mx) { mx } (x < mn) { mn } _ { x } ) } fn main() { assert_eq!(clamp(1, 2, 4), 2); assert_eq!(clamp(8, 2, 4), 4); assert_eq!(clamp(3, 2, 4), 3); }
clamp
identifier_name
result.rs
//! A module describing Lox-specific Result and Error types use object::Object; use std::result; use std::error; use std::fmt; use std::io; /// A Lox-Specific Result Type pub type Result<T> = result::Result<T, Error>; /// A Lox-Specific Error #[derive(Debug)] pub enum
{ /// Returned if the CLI command is used incorrectly Usage, /// Returned if there is an error reading from a file or stdin IO(io::Error), /// Returned if the scanner encounters an error Lexical(u64, String, String), /// Returned if the parser encounters an error Parse(u64, String, Stri...
Error
identifier_name
result.rs
//! A module describing Lox-specific Result and Error types
use std::fmt; use std::io; /// A Lox-Specific Result Type pub type Result<T> = result::Result<T, Error>; /// A Lox-Specific Error #[derive(Debug)] pub enum Error { /// Returned if the CLI command is used incorrectly Usage, /// Returned if there is an error reading from a file or stdin IO(io::Error), ...
use object::Object; use std::result; use std::error;
random_line_split
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3])...
def _start(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._start(forked_branch) else: stage.start() def _shutdown(self, stages: list): for st...
for i in range(1, len(stages)): if type(stages[i]) == PipelineFork: self._link_pipeline_fork(stages, i) else: stages[i - 1].add_queue_out(stages[i].queue_in) if issubclass(type(stages[-1]), PipelineStage): output_queue = StoppableQueue(PIPELINE...
identifier_body
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3])...
def start(self): """Start all pipelines stages.""" self._start(self._stages) def shutdown(self): """ shutdowns every child thread (PipelineStage)""" self._shutdown(self._stages) def join(self): """Ensure every thread (PipelineStage) of the pipeline are done""" ...
def read_output_queue(self, queue_index=0): """Wait to read a data in a queue given by queue_index""" return self._output_queues[queue_index].get()
random_line_split
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3])...
else: stage.start() def _shutdown(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._shutdown(forked_branch) else: stage.shutdown...
self._start(forked_branch)
conditional_block
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3])...
(self, *branches): self.forked_branches: list = list(branches) class Pipeline(): """ This class create a multithreaded pipeline. It automatically links together every contiguous stages. E.g.: Pipeline(Signal(), PipelineStage(), PipelineFork([PipelineStage(), PipelineStage()], [PipelineStage()] )) ...
__init__
identifier_name