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 |
|---|---|---|---|---|
StahnuTo.py | # -*- coding: utf-8 -*-
import re
from pyload.plugin.Account import Account
class StahnuTo(Account):
__name = "StahnuTo"
__type = "account"
__version = "0.05"
__description = """StahnuTo account plugin"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
... | self.wrongPassword() | random_line_split | |
StahnuTo.py | # -*- coding: utf-8 -*-
import re
from pyload.plugin.Account import Account
class StahnuTo(Account):
__name = "StahnuTo"
__type = "account"
__version = "0.05"
__description = """StahnuTo account plugin"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
... | html = req.load("http://www.stahnu.to/login.php",
post={"username": user,
"password": data['password'],
"submit": "Login"},
decode=True)
if not '<a href="logout.php">' in html:
self.wrongPass... | identifier_body | |
StahnuTo.py | # -*- coding: utf-8 -*-
import re
from pyload.plugin.Account import Account
class StahnuTo(Account):
__name = "StahnuTo"
__type = "account"
__version = "0.05"
__description = """StahnuTo account plugin"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
... | (self, user, data, req):
html = req.load("http://www.stahnu.to/login.php",
post={"username": user,
"password": data['password'],
"submit": "Login"},
decode=True)
if not '<a href="logout.php">' in... | login | identifier_name |
operators.py | import numpy as np
from scipy.sparse import csr_matrix
from .symbolic import Operator
SPARSITY_N_CUTOFF = 600 # TODO lower after fixing sparse matrices
def sparsify(mat):
assert SPARSITY_N_CUTOFF > 5, 'The SPARSITY_N_CUTOFF is set to a very low number.'
if min(mat.shape) > SPARSITY_N_CUTOFF:
return cs... | return Operator('σ_z', 2, s_z) | random_line_split | |
operators.py | import numpy as np
from scipy.sparse import csr_matrix
from .symbolic import Operator
SPARSITY_N_CUTOFF = 600 # TODO lower after fixing sparse matrices
def sparsify(mat):
assert SPARSITY_N_CUTOFF > 5, 'The SPARSITY_N_CUTOFF is set to a very low number.'
if min(mat.shape) > SPARSITY_N_CUTOFF:
return cs... | ef sigmax():
return Operator('σ_x', 2, s_x)
def sigmay():
return Operator('σ_y', 2, s_y)
def sigmaz():
return Operator('σ_z', 2, s_z)
| eturn Operator('σ_+', 2, s_p)
d | identifier_body |
operators.py | import numpy as np
from scipy.sparse import csr_matrix
from .symbolic import Operator
SPARSITY_N_CUTOFF = 600 # TODO lower after fixing sparse matrices
def sparsify(mat):
assert SPARSITY_N_CUTOFF > 5, 'The SPARSITY_N_CUTOFF is set to a very low number.'
if min(mat.shape) > SPARSITY_N_CUTOFF:
return cs... | ():
return Operator('σ_-', 2, s_m)
def sigmap():
return Operator('σ_+', 2, s_p)
def sigmax():
return Operator('σ_x', 2, s_x)
def sigmay():
return Operator('σ_y', 2, s_y)
def sigmaz():
return Operator('σ_z', 2, s_z)
| sigmam | identifier_name |
operators.py | import numpy as np
from scipy.sparse import csr_matrix
from .symbolic import Operator
SPARSITY_N_CUTOFF = 600 # TODO lower after fixing sparse matrices
def sparsify(mat):
assert SPARSITY_N_CUTOFF > 5, 'The SPARSITY_N_CUTOFF is set to a very low number.'
if min(mat.shape) > SPARSITY_N_CUTOFF:
|
return mat
def destroy(N):
return Operator('{a}_{%d}'%N,
N,
sparsify(np.diag(np.arange(1,N,dtype=complex)**0.5,k=1)))
def create(N): #TODO name prints ugly
return Operator('{a^\dagger}_{%d}'%N,
N,
sparsify(np.diag(np.arange(... | return csr_matrix(mat) | conditional_block |
v6Data.rs | pub fn | () -> [f64; 81] {
let mut v6List: [f64; 81] = [0.0; 81];
// index is wavelengths of light, stepped by 5, from 380 to 780
v6List[0] = -0.0809279;
v6List[1] = -0.0830999;
v6List[2] = -0.0746431;
v6List[3] = -0.0487062;
v6List[4] = -0.0232402;
v6List[5] = 0.000270005;
v6List[6] = 0.015... | v6Data | identifier_name |
v6Data.rs | pub fn v6Data() -> [f64; 81] | v6List[16] = -0.128604;
v6List[17] = -0.114038;
v6List[18] = -0.103359;
v6List[19] = -0.0675493;
v6List[20] = -0.0231118;
v6List[21] = 0.0393885;
v6List[22] = 0.0926205;
v6List[23] = 0.177201;
v6List[24] = 0.153455;
v6List[25] = 0.0860555;
v6List[26] = 0.219497;
v6List[27... | {
let mut v6List: [f64; 81] = [0.0; 81];
// index is wavelengths of light, stepped by 5, from 380 to 780
v6List[0] = -0.0809279;
v6List[1] = -0.0830999;
v6List[2] = -0.0746431;
v6List[3] = -0.0487062;
v6List[4] = -0.0232402;
v6List[5] = 0.000270005;
v6List[6] = 0.0151724;
v6List... | identifier_body |
v6Data.rs | pub fn v6Data() -> [f64; 81] {
let mut v6List: [f64; 81] = [0.0; 81];
// index is wavelengths of light, stepped by 5, from 380 to 780
v6List[0] = -0.0809279;
v6List[1] = -0.0830999;
v6List[2] = -0.0746431;
v6List[3] = -0.0487062;
v6List[4] = -0.0232402;
v6List[5] = 0.000270005;
v6Li... | v6List[40] = 0.0477786;
v6List[41] = 0.116347;
v6List[42] = 0.196124;
v6List[43] = 0.204762;
v6List[44] = 0.235425;
v6List[45] = 0.202082;
v6List[46] = 0.160728;
v6List[47] = 0.0858789;
v6List[48] = 0.115125;
v6List[49] = 0.0809753;
v6List[50] = -0.0104571;
v6List[51] = -... | v6List[36] = -0.223687;
v6List[37] = -0.107916;
v6List[38] = -0.126467;
v6List[39] = -0.0135333; | random_line_split |
conversion_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def test_convert_entity_to_ast_multiple_lambdas_ambiguous_definitions(self):
a, b = 1, 2
f, _ = (lambda x: a * x, lambda x: b * x)
program_ctx = self._simple_program_ctx()
with self.assertRaises(ValueError):
conversion.convert_entity_to_ast(f, program_ctx)
def test_convert_entity_to_ast_la... | a, b = 1, 2
f, _ = (lambda x: a * x, lambda y: b * y)
program_ctx = self._simple_program_ctx()
(fn_node,), name, entity_info = conversion.convert_entity_to_ast(
f, program_ctx)
self.assertIsInstance(fn_node, gast.Assign)
self.assertIsInstance(fn_node.value, gast.Lambda)
self.assertEqual... | identifier_body |
conversion_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (TestBase):
def __init__(self, y):
super(TestSubclass, self).__init__('sub')
self.y = y
def foo(self):
return self.y
def baz(self):
return self.y
program_ctx = self._simple_program_ctx()
with self.assertRaisesRegex(NotImplementedError, 'classes.*whitelisted'... | TestSubclass | identifier_name |
conversion_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | test.main() | conditional_block | |
conversion_test.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | def test_convert_entity_to_ast_function_with_defaults(self):
b = 2
c = 1
def f(a, d=c + 1):
return a + b + d
program_ctx = self._simple_program_ctx()
nodes, name, _ = conversion.convert_entity_to_ast(f, program_ctx)
fn_node, = nodes
self.assertIsInstance(fn_node, gast.FunctionDef)
... | self.assertIsInstance(fn_node, gast.FunctionDef)
self.assertEqual('tf__f', name)
self.assertIs(info.namespace['b'], b)
| random_line_split |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn | () -> MaxHeap{
let heap = BinaryHeap::new();
let count = 0;
MaxHeap {
heap,
count
}
}
fn push(&mut self, new_value: u64) {
self.count = self.count + 1;
self.heap.push(new_value);
}
fn top(&self) -> u64 {
let v = self.heap.... | new | identifier_name |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn new() -> MaxHeap |
fn push(&mut self, new_value: u64) {
self.count = self.count + 1;
self.heap.push(new_value);
}
fn top(&self) -> u64 {
let v = self.heap.peek().expect("max heap underflow");
v.clone()
}
fn pop(&mut self) -> u64 {
let v = self.heap.pop().expect("max heap... | {
let heap = BinaryHeap::new();
let count = 0;
MaxHeap {
heap,
count
}
} | identifier_body |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn new() -> MaxHeap{
let heap = BinaryHeap::new();
... |
else {
if max_heap.count > min_heap.count {
let mut diff = max_heap.count - min_heap.count;
while diff > 1 {
let v = max_heap.pop();
min_heap.push(v);
diff = max_heap.count - min_heap.count;
}
}
}
}
/*
#[test]
... | {
let mut diff = min_heap.count - max_heap.count;
while diff > 1 {
let v = min_heap.pop();
max_heap.push(v);
diff = min_heap.count - max_heap.count;
}
} | conditional_block |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn new() -> MaxHeap{
let heap = BinaryHeap::new();
... | let mut v = Vec::new();
for line in reader.lines() {
let line = line.unwrap();
let value = u64::from_str(&line).expect("error parsing value");
v.push(value);
}
Ok(median_sum(&v))
}
fn main() {
for arg in std::env::args().skip(1) {
let value = print_medians(&arg)... | let f = File::open(file_name)?;
let reader = BufReader::new(f); | random_line_split |
nickTracker.py | import re
import lib.slack.config as config
import lib.slack.util as util
def nick_tracker(log_dict):
"""
Tracks all nicks and the identifies nicks which point to same user
Args:
log_dict(dictionary): with key as dateTime.date object and value as {"data":datalist,"channel_name":channels name... | for index in xrange(config.MAX_EXPECTED_DIFF_NICKS):
if nick in nick_same_list[index]:
break
if not nick_same_list[index]:
nick_same_list[index].append(nick)
break
if config.DEBUGGER:
print "========> 30 on {} nicks".format(len... | for nick in nicks: | random_line_split |
nickTracker.py | import re
import lib.slack.config as config
import lib.slack.util as util
def nick_tracker(log_dict):
| for day_content_all_channels in log_dict.values():
# traverse over data of different channels for that day
for day_content in day_content_all_channels:
day_logs = day_content["log_data"]
for day_log in day_logs:
# use regex to get the string between <> and ap... | """
Tracks all nicks and the identifies nicks which point to same user
Args:
log_dict(dictionary): with key as dateTime.date object and value as {"data":datalist,"channel_name":channels name}
Returns:
nicks(list): all nicks
nick_same_list(list): list of lists with each list corr... | identifier_body |
nickTracker.py | import re
import lib.slack.config as config
import lib.slack.util as util
def nick_tracker(log_dict):
"""
Tracks all nicks and the identifies nicks which point to same user
Args:
log_dict(dictionary): with key as dateTime.date object and value as {"data":datalist,"channel_name":channels name... | (nick, nicks):
if nick not in nicks:
nicks.append(nick)
return nicks
for day_content_all_channels in log_dict.values():
# traverse over data of different channels for that day
for day_content in day_content_all_channels:
day_logs = day_content["log_data"]
... | nick_append | identifier_name |
nickTracker.py | import re
import lib.slack.config as config
import lib.slack.util as util
def nick_tracker(log_dict):
"""
Tracks all nicks and the identifies nicks which point to same user
Args:
log_dict(dictionary): with key as dateTime.date object and value as {"data":datalist,"channel_name":channels name... |
for nick in nicks:
for index in xrange(config.MAX_EXPECTED_DIFF_NICKS):
if nick in nick_same_list[index]:
break
if not nick_same_list[index]:
nick_same_list[index].append(nick)
break
if config.DEBUGGER:
print "========> 3... | if old_nick in nick_same_list[i] or new_nick in nick_same_list[i]:
if old_nick not in nick_same_list[i]:
nick_same_list[i].append(old_nick)
if new_nick not in nick_same_list[i]:
nick_same_list[i].appe... | conditional_block |
emailChange.controller.js | (function(){
'use strict';
angular
.module('users')
.controller('EmailChangeCtrl', ['$rootScope', '$scope', '$state', '$location', '$translate', 'restFulService', 'config', 'errorService', function($rootScope, $scope, $state, $location, $translate, restFulService, config, errorService){
$scope.show = {
... | $scope.show.message = true;
})
.catch(function(err){
$location.path('error/' + err.status);
});
}]);
}()); | $rootScope.user.email = response.email; | random_line_split |
checkContentRules.js |
/**
* A processor that can run arbitrary checking rules against properties of documents
* The configuration for the processor is via the `docTypeRules`.
* This is a hash of docTypes to rulesets.
* Each rules set is a hash of properties to rule functions.
*
* The processor will run each rule function against eac... | (docs) {
const logMessage = this.failOnContentErrors ? log.error.bind(log) : log.warn.bind(log);
const errors = [];
docs.forEach(doc => {
const docErrors = [];
const rules = this.docTypeRules[doc.docType] || {};
if (rules) {
Object.keys(rules).forEach(property => {
... | $process | identifier_name |
checkContentRules.js |
/**
* A processor that can run arbitrary checking rules against properties of documents
* The configuration for the processor is via the `docTypeRules`.
* This is a hash of docTypes to rulesets.
* Each rules set is a hash of properties to rule functions.
*
* The processor will run each rule function against eac... |
}
};
};
| {
logMessage('Content contains errors');
errors.forEach(docError => {
const errors = docError.errors.join('\n ');
logMessage(createDocMessage(errors + '\n ', docError.doc));
});
if (this.failOnContentErrors) {
throw new Error('Stopping due to c... | conditional_block |
checkContentRules.js | /**
* A processor that can run arbitrary checking rules against properties of documents
* The configuration for the processor is via the `docTypeRules`.
* This is a hash of docTypes to rulesets.
* Each rules set is a hash of properties to rule functions.
*
* The processor will run each rule function against each... | failOnContentErrors: false,
$runAfter: ['tags-extracted'],
$runBefore: [],
$process(docs) {
const logMessage = this.failOnContentErrors ? log.error.bind(log) : log.warn.bind(log);
const errors = [];
docs.forEach(doc => {
const docErrors = [];
const rules = this.docTypeR... | */
docTypeRules: {}, | random_line_split |
checkContentRules.js |
/**
* A processor that can run arbitrary checking rules against properties of documents
* The configuration for the processor is via the `docTypeRules`.
* This is a hash of docTypes to rulesets.
* Each rules set is a hash of properties to rule functions.
*
* The processor will run each rule function against eac... | });
if (errors.length) {
logMessage('Content contains errors');
errors.forEach(docError => {
const errors = docError.errors.join('\n ');
logMessage(createDocMessage(errors + '\n ', docError.doc));
});
if (this.failOnContentErrors) {
... | {
const logMessage = this.failOnContentErrors ? log.error.bind(log) : log.warn.bind(log);
const errors = [];
docs.forEach(doc => {
const docErrors = [];
const rules = this.docTypeRules[doc.docType] || {};
if (rules) {
Object.keys(rules).forEach(property => {
... | identifier_body |
xgboostPredictClassification.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | """
:param X: Matrix of feature vectors we want to predict (X_test)
:param M: The model created at xgboost
:param learning_rate: the learning rate used in the model
:return: 'OperationNode' containing the predictions of the samples using the given xgboost model. (y_prediction)
"""
params_dict =... | identifier_body | |
xgboostPredictClassification.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | (X: Matrix,
M: Matrix,
learning_rate: float):
"""
:param X: Matrix of feature vectors we want to predict (X_test)
:param M: The model created at xgboost
:param learning_rate: the learning rate used in the model
:return: 'OperationNode... | xgboostPredictClassification | identifier_name |
xgboostPredictClassification.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | """
params_dict = {'X': X, 'M': M, 'learning_rate': learning_rate}
return Matrix(X.sds_context,
'xgboostPredictClassification',
named_input_nodes=params_dict) | random_line_split | |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... |
}
| {
} | identifier_body |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... | (&mut self, state: &State) {
}
}
| render | identifier_name |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... |
if self.timestamp >= frame.timestamp().unwrap() {
return;
}
self.timestamp = frame.timestamp().unwrap();
if let Some(source) = self.music.as_mut() {
source.push(frame.channels(), frame.plane::<i16>(0), frame.rate()).unwrap();
if source.state() != source::State::Playing {
source.play();
}
... | {
self.music = Some(self.listener.source().unwrap().stream());
} | conditional_block |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... |
pub fn render(&mut self, state: &State) {
}
} | random_line_split | |
treeview.js |
},
check: {
enable: true
},
data: {
key: {
title: "title",
name: "text" // 节点的name属性替换成text
},
simpleData: {
enable: true // 可以穿id,pid属性的对象数组... | // treeNode.icon = "";
// zTree.updateNode(treeNode);
}
function ajaxGetNodes
(treeNode, reloadType) {
var zTree = self.nodes;
if (reloadType == "refresh") {
zTree.updateNode(treeNode); // 刷新一下当前节点,如果treeNode.xxx被改了的话
}
... | ode.count || 0;
// 尝试去获取下一组节点,若获取值为空数组,表示获取完成
// TODO by GUY
if (treeNode.children.length > totalCount) {
treeNode.count = treeNode.children.length;
BI.delay(function () {
ajaxGetNodes(treeNode);
}, perTime);
... | identifier_body |
treeview.js | 参数
},
check: {
enable: true
},
data: {
key: {
title: "title",
name: "text" // 节点的name属性替换成text
},
simpleData: {
enable: true // 可以穿id,pid属性的对象... | // 尝试去获取下一组节点,若获取值为空数组,表示获取完成
// TODO by GUY
if (treeNode.children.length > totalCount) {
treeNode.count = treeNode.children.length;
BI.delay(function () {
ajaxGetNodes(treeNode);
}, perTime);
} else {
... | }
var zTree = self.nodes;
var totalCount = treeNode.count || 0;
| random_line_split |
treeview.js | return "&" + param;
}
function beforeExpand (treeId, treeNode) {
if (!treeNode.isAjaxing) {
if (!treeNode.children) {
treeNode.times = 1;
ajaxGetNodes(treeNode, "refresh");
}
return true;
... | r hasNext = !!res.hasNext, nodes = res.items || [];
| conditional_block | |
treeview.js |
},
check: {
enable: true
},
data: {
key: {
title: "title",
name: "text" // 节点的name属性替换成text
},
simpleData: {
enable: true // 可以穿id,pid属性的对象数组... | esult = result.concat([this._getNodeValue(parentNode)]);
return result;
},
_getNodeValue: function (node) {
// 去除标红
return node.value == null ? BI.replaceAll(node.text.replace(/<[^>]+>/g, ""), " ", " ") : node.value;
},
// 获取半选框值
_getHalfSelectedValues: function (map, ... | r | identifier_name |
linux_ssh.py | from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging ... |
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
"""Can't exit from root (if root)"""
if self.username == "root":
exit_config_mode = False
return super(CiscoSSHConnection, self).send_config_set(config_commands=config_commands,
... | """Determine base prompt."""
return super(CiscoSSHConnection, self).set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor) | identifier_body |
linux_ssh.py | from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging ... | (self, exit_command='exit'):
"""Exit enable mode."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
time.sleep(.3 * delay_factor)
self.set_base_promp... | exit_enable_mode | identifier_name |
linux_ssh.py | from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging ... | def check_config_mode(self, check_string='#'):
"""Verify root"""
return self.check_enable_mode(check_string=check_string)
def config_mode(self, config_command='sudo su'):
"""Attempt to become root."""
return self.enable(cmd=config_command)
def exit_config_mode(self, exit_co... | exit_config_mode=exit_config_mode,
**kwargs)
| random_line_split |
linux_ssh.py | from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging ... |
self.set_base_prompt()
except socket.timeout:
raise NetMikoTimeoutException("Timed-out reading channel, data not available.")
if not self.check_enable_mode():
msg = "Failed to enter enable mode. Please ensure you pass " \
"th... | self.write_channel(self.normalize_cmd(self.secret)) | conditional_block |
tests.py | from operator import attrgetter
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.backends.db import SessionStore
from django.db.models import Count
from django.db.models.loading import cache
from django.test import TestCase
from models import (ResolveThis, Item, RelatedItem, Chi... |
def test_resolve_columns(self):
rt = ResolveThis.objects.create(num=5.0, name='Foobar')
qs = ResolveThis.objects.defer('num')
self.assertEqual(1, qs.count())
self.assertEqual('Foobar', qs[0].name)
| proxy = Proxy.objects.create(name="proxy", value=42)
msg = 'QuerySet.only() return bogus results with proxy models'
dp = Proxy.objects.only('other_value').get(pk=proxy.pk)
self.assertEqual(dp.name, proxy.name, msg=msg)
self.assertEqual(dp.value, proxy.value, msg=msg)
# also tes... | identifier_body |
tests.py | from operator import attrgetter
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.backends.db import SessionStore
from django.db.models import Count
from django.db.models.loading import cache
from django.test import TestCase
from models import (ResolveThis, Item, RelatedItem, Chi... | "Leaf_Deferred_value",
"Proxy",
"RelatedItem",
"RelatedItem_Deferred_",
"RelatedItem_Deferred_item_id",
"ResolveThis",
"SimpleItem",
]
)
# Regression for #16409 - make sure defer(... | random_line_split | |
tests.py | from operator import attrgetter
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.backends.db import SessionStore
from django.db.models import Count
from django.db.models.loading import cache
from django.test import TestCase
from models import (ResolveThis, Item, RelatedItem, Chi... | (TestCase):
def test_basic(self):
# Deferred fields should really be deferred and not accidentally use
# the field's default value just because they aren't passed to __init__
Item.objects.create(name="first", value=42)
obj = Item.objects.only("name", "other_value").get(name="first")... | DeferRegressionTest | identifier_name |
template.js | //For more information, check phaser documentation
//If you have learned to use phaser, then you can easily underatnd the following content.
//Declaring the game object
var game = new Phaser.Game(640, 520, Phaser.AUTO, 'gamingArea', { preload: preload, create: create, update: update });
function preload()
|
// Declare your global variables here
// The predefined function to create the Gaming area
function create()
{
//Adding the preloaded content in the game area.
//You can reuse the code from previous games for commonly used assets.(eg: Play pause buttons, LifeLine smileys etc.,)
//Next line will display timer in t... | {
//Importing the asset(s) required for the game
//For example:
//game.load.image('start_screen' , 'assets/images/startScreen_640_520.jpg');
//game.load.image('Name of your image for further reference goes here' , 'relative location of your image/spritesheet');
//You can also import spritesheets
} | identifier_body |
template.js | //For more information, check phaser documentation
//If you have learned to use phaser, then you can easily underatnd the following content.
//Declaring the game object
var game = new Phaser.Game(640, 520, Phaser.AUTO, 'gamingArea', { preload: preload, create: create, update: update });
function preload()
{
//Impo... | //Next line will display timer in the mentioned absolute position. 505,19
//timer = game.add.text(505, 19, '00:00' ,{font : "15px Arial" , fill : "white"});
}
// The predefined function to be called at the rate of 10 frames per second.
function update()
{
//updateTimer();
}
//The above mentioned are the predefine... | function create()
{
//Adding the preloaded content in the game area.
//You can reuse the code from previous games for commonly used assets.(eg: Play pause buttons, LifeLine smileys etc.,) | random_line_split |
template.js | //For more information, check phaser documentation
//If you have learned to use phaser, then you can easily underatnd the following content.
//Declaring the game object
var game = new Phaser.Game(640, 520, Phaser.AUTO, 'gamingArea', { preload: preload, create: create, update: update });
function | ()
{
//Importing the asset(s) required for the game
//For example:
//game.load.image('start_screen' , 'assets/images/startScreen_640_520.jpg');
//game.load.image('Name of your image for further reference goes here' , 'relative location of your image/spritesheet');
//You can also import spritesheets
}
// Declare ... | preload | identifier_name |
xarray.py | # Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Vendor core functionality used from xarray.
This code has been reproduced with modification under the terms of the Apache License, Version
2.0 (notice included below).
Copyr... | (pos_kwargs, kw_kwargs, func_name):
"""Ensure dict-like argument from either positional or keyword arguments."""
if pos_kwargs is not None:
if not is_dict_like(pos_kwargs):
raise ValueError('the first argument to .{} must be a '
'dictionary'.format(func_name))
... | either_dict_or_kwargs | identifier_name |
xarray.py | # Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Vendor core functionality used from xarray.
This code has been reproduced with modification under the terms of the Apache License, Version
2.0 (notice included below).
Copyr... |
else:
new_key.append(slice(None))
else:
new_key.append(k)
if len(new_key) > ndim:
raise IndexError('too many indices')
new_key.extend((ndim - len(new_key)) * [slice(None)])
return tuple(new_key)
def is_dict_like(value):
"""Check if value is dict... | new_key.extend((ndim + 1 - len(key)) * [slice(None)])
found_ellipsis = True | conditional_block |
xarray.py | # Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Vendor core functionality used from xarray.
This code has been reproduced with modification under the terms of the Apache License, Version
2.0 (notice included below).
Copyr... | return hasattr(value, 'keys') and hasattr(value, '__getitem__')
def either_dict_or_kwargs(pos_kwargs, kw_kwargs, func_name):
"""Ensure dict-like argument from either positional or keyword arguments."""
if pos_kwargs is not None:
if not is_dict_like(pos_kwargs):
raise ValueError('the fi... |
def is_dict_like(value):
"""Check if value is dict-like.""" | random_line_split |
xarray.py | # Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Vendor core functionality used from xarray.
This code has been reproduced with modification under the terms of the Apache License, Version
2.0 (notice included below).
Copyr... | """Ensure dict-like argument from either positional or keyword arguments."""
if pos_kwargs is not None:
if not is_dict_like(pos_kwargs):
raise ValueError('the first argument to .{} must be a '
'dictionary'.format(func_name))
if kw_kwargs:
raise Va... | identifier_body | |
ErrorModal.tsx | import * as React from 'react'
import { openModal, IModalProps } from '../Modals';
import * as Navigator from '../Navigator';
import { Dic } from '../Globals';
import { ServiceError, ValidationError } from '../Services';
import { JavascriptMessage, NormalWindowMessage } from '../Signum.Entities'
import { Exceptio... | })</span>}
</span>
);
}
function renderValidationTitle(ve: ValidationError) {
return (
<span>
<FontAwesomeIcon icon="exclamation-triangle" /> {NormalWindowMessage.ThereAreErrors.niceToString()}
</span>
);
}
function renderServiceMessage(se: ServiceE... | <FontAwesomeIcon icon={se.defaultIcon} /> <span>{se.httpError.exceptionType}</span>
{se.httpError.exceptionId && <span>({
Navigator.isViewable(ExceptionEntity) ?
<a href={Navigator.navigateRoute(newLite(ExceptionEntity, se.httpError.exceptionId!))}>{se.httpError.exceptionI... | random_line_split |
ErrorModal.tsx | import * as React from 'react'
import { openModal, IModalProps } from '../Modals';
import * as Navigator from '../Navigator';
import { Dic } from '../Globals';
import { ServiceError, ValidationError } from '../Services';
import { JavascriptMessage, NormalWindowMessage } from '../Signum.Entities'
import { Exceptio... |
function handleOnExited() {
p.onExited!(undefined);
}
function handleCloseClicked() {
setShow(false);
}
const e = p.error;
const se = e instanceof ServiceError ? (e as ServiceError) : undefined;
const ve = e instanceof ValidationError ? (e as ValidationError) : undefined;
... | {
e.preventDefault();
setShowDetails(!showDetails);
} | identifier_body |
ErrorModal.tsx | import * as React from 'react'
import { openModal, IModalProps } from '../Modals';
import * as Navigator from '../Navigator';
import { Dic } from '../Globals';
import { ServiceError, ValidationError } from '../Services';
import { JavascriptMessage, NormalWindowMessage } from '../Signum.Entities'
import { Exceptio... | (p: ErrorModalProps) {
const [show, setShow] = React.useState(true);
const [showDetails, setShowDetails] = React.useState(false);
function handleShowStackTrace(e: React.MouseEvent<any>) {
e.preventDefault();
setShowDetails(!showDetails);
}
function handleOnExited() {
p.onExited!(unde... | ErrorModal | identifier_name |
xbox-remote-power.py | import sys, socket, select, time
from optparse import OptionParser
XBOX_PORT = 5050
XBOX_PING = "dd00000a000000000000000400000002"
XBOX_POWER = "dd02001300000010"
help_text = "xbox-remote-power.py -a <ip address> -i <live id>"
py3 = sys.version_info[0] > 2
def main():
parser = OptionParser()
parser.add_opti... | (text):
response = ""
while response == "":
if py3:
response = input(text)
else:
response = raw_input(text)
return response
if __name__ == "__main__":
main()
| user_input | identifier_name |
xbox-remote-power.py | import sys, socket, select, time
from optparse import OptionParser
XBOX_PORT = 5050
XBOX_PING = "dd00000a000000000000000400000002"
XBOX_POWER = "dd02001300000010"
help_text = "xbox-remote-power.py -a <ip address> -i <live id>"
py3 = sys.version_info[0] > 2
def main():
parser = OptionParser()
parser.add_opti... |
ping = False
if not opts.live_id:
print("No Live ID given, do you want to attempt to ping the Xbox for it?")
result = ""
while result not in ("y", "n"):
result = user_input("(y/n): ").lower()
if result == "y":
ping = True
elif result == "n":
... | opts.ip_addr = user_input("Enter the IP address: ") | conditional_block |
xbox-remote-power.py | import sys, socket, select, time
from optparse import OptionParser
XBOX_PORT = 5050
XBOX_PING = "dd00000a000000000000000400000002"
XBOX_POWER = "dd02001300000010"
help_text = "xbox-remote-power.py -a <ip address> -i <live id>"
py3 = sys.version_info[0] > 2
def main():
parser = OptionParser()
parser.add_opti... | response = ""
while response == "":
if py3:
response = input(text)
else:
response = raw_input(text)
return response
if __name__ == "__main__":
main() |
s.close()
def user_input(text): | random_line_split |
xbox-remote-power.py | import sys, socket, select, time
from optparse import OptionParser
XBOX_PORT = 5050
XBOX_PING = "dd00000a000000000000000400000002"
XBOX_POWER = "dd02001300000010"
help_text = "xbox-remote-power.py -a <ip address> -i <live id>"
py3 = sys.version_info[0] > 2
def main():
parser = OptionParser()
parser.add_opti... |
if __name__ == "__main__":
main()
| response = ""
while response == "":
if py3:
response = input(text)
else:
response = raw_input(text)
return response | identifier_body |
parser.rs | ;
}
}
// Per-revision flags
bitflags! {
pub struct IdxFlags: u16 {
const OCTOPUS_MERGE = 1 << 12;
const EXTSTORED = 1 << 13;
const CENSORED = 1 << 15;
}
}
/// Revlog version number
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Version {
Revlog0 = 0,
RevlogN... | named!(remains_owned<Vec<u8>>, map!(remains, |x: &[u8]| x.into()));
// Parse some literal data, possibly compressed
named!(pub literal<Vec<u8> >,
alt!(
do_parse!(peek!(tag!(b"\0")) >> d: remains >> (d.into())) |
do_parse!(peek!(tag!(b"x")) >> d: apply!(zlib_decompress, remains_owned) >> (d)) |
... | random_line_split | |
parser.rs | }
}
// Per-revision flags
bitflags! {
pub struct IdxFlags: u16 {
const OCTOPUS_MERGE = 1 << 12;
const EXTSTORED = 1 << 13;
const CENSORED = 1 << 15;
}
}
/// Revlog version number
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Version {
Revlog0 = 0,
RevlogNG ... | () -> usize {
6 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 32
}
// Parse an "NG" revlog entry
named!(pub indexng<Entry>,
do_parse!(
offset: return_error!(ErrorKind::Custom(Badness::IO), be_u48) >> // XXX if first, then only 2 bytes, implied 0 in top 4
flags: return_error!(ErrorKind::Custom(Badness::IO), ... | indexng_size | identifier_name |
parser.rs | }
}
// Per-revision flags
bitflags! {
pub struct IdxFlags: u16 {
const OCTOPUS_MERGE = 1 << 12;
const EXTSTORED = 1 << 13;
const CENSORED = 1 << 15;
}
}
/// Revlog version number
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Version {
Revlog0 = 0,
RevlogNG ... |
// Parse an "NG" revlog entry
named!(pub indexng<Entry>,
do_parse!(
offset: return_error!(ErrorKind::Custom(Badness::IO), be_u48) >> // XXX if first, then only 2 bytes, implied 0 in top 4
flags: return_error!(ErrorKind::Custom(Badness::IO), be_u16) >> // ?
compressed_length: return_... | {
6 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 32
} | identifier_body |
arrayAccess.ts | import { SingleValuePort } from "../ports/single";
import { Scope } from "../scopes/scope";
import * as Types from "../types";
import { checkType } from "../types/check";
import * as Values from "../values";
import { Node } from "./node";
export class ArrayAccess extends Node {
private nodes: Node[];
constructor(... | import * as AST from "../../ast/expression";
import { nodeFromExpression } from "../create"; | random_line_split | |
arrayAccess.ts | import * as AST from "../../ast/expression";
import { nodeFromExpression } from "../create";
import { SingleValuePort } from "../ports/single";
import { Scope } from "../scopes/scope";
import * as Types from "../types";
import { checkType } from "../types/check";
import * as Values from "../values";
import { Node } fro... | extends Node {
private nodes: Node[];
constructor(arraySource: Node, defintion: AST.ArrayAccess, scope: Scope) {
super("ArrayAccess", defintion);
this.nodes = [];
this.nodes.push(arraySource);
this.nodes.push(nodeFromExpression(defintion.index, scope));
this.addInPorts(this.nodes);
this.... | ArrayAccess | identifier_name |
arrayAccess.ts | import * as AST from "../../ast/expression";
import { nodeFromExpression } from "../create";
import { SingleValuePort } from "../ports/single";
import { Scope } from "../scopes/scope";
import * as Types from "../types";
import { checkType } from "../types/check";
import * as Values from "../values";
import { Node } fro... |
const integerIndex = index as Values.Integer;
const arrayValue = array as Values.Array;
if (!arrayValue.values[integerIndex.value]) {
return new Values.ErrorValue("Array index is out of bounds: " + integerIndex.value);
}
return arrayValue.values[integerIndex.value];
}
}
| {
return new Values.ErrorValue("Incompartible type: " +
subType.toString() + ", " + type.toString());
} | conditional_block |
setup.py | #!/usr/bin/env python
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def | (fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
# only compile quack when none of these options are chosen
if (all([e not in argv for e in ['egg_info', 'sdist', 'register']]) and
platform == 'darwin'):
try:
call(['make', ... | read | identifier_name |
setup.py | #!/usr/bin/env python
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def read(fname):
|
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
# only compile quack when none of these options are chosen
if (all([e not in argv for e in ['egg_info', 'sdist', 'register']]) and
platform == 'darwin'):
try:
call(['make', '-C', 'src/bg_daemon/'])
SCRIPTS.append("src/bg_daemon/quack")
exce... | return open(os.path.join(os.path.dirname(__file__), fname)).read() | identifier_body |
setup.py | #!/usr/bin/env python
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
# only compile quack when none of these options are chosen... | data_files=[('bg_daemon', ['src/bg_daemon/settings.json',
'src/bg_daemon/mac-update.sh'])],
long_description=read("README.md"),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Topic :: Utilities",
"License :: ",
"Environment :: No Input/Ou... | random_line_split | |
setup.py | #!/usr/bin/env python
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
# only compile quack when none of these options are chosen... |
setup(
name="bg_daemon",
version="0.0.1",
author="Santiago Torres",
author_email="torresariass@gmail.com",
description=("An extensible set of classes that can programmatically "
"update the desktop wallpaper"),
license="GPLv2",
keywords="imgur desktop wallpaper background... | try:
call(['make', '-C', 'src/bg_daemon/'])
SCRIPTS.append("src/bg_daemon/quack")
except OSError as e:
print "Can't compile quack, reason {}".format(str(e)) | conditional_block |
options.ts | import * as request from 'request';
import { INotice } from './notice';
import { Processor } from './processor/processor';
type Reporter = (notice: INotice) => Promise<INotice>; | export interface IInstrumentationOptions {
onerror?: boolean;
fetch?: boolean;
history?: boolean;
console?: boolean;
xhr?: boolean;
}
export interface IOptions {
projectId: number;
projectKey: string;
environment?: string;
host?: string;
apmHost?: string;
remoteConfigHost?: string;
remoteConfig... | random_line_split | |
js.js | and the MIT License
*/
Element.Events.extend({
'wheelup': {
type: Element.Events.mousewheel.type,
map: function(event){
event = new Event(event);
if (event.wheel >= 0) this.fireEvent('wheelup', event)
}
},
'wheeldown': {
type: Element.Events.mousewheel.type,
map: function(event){
event = new E... | this.registerMousewheelHandler( eNavigator ); // allow to use the srcoll
this.navigatorItems.each( function(item,index) {
item.addEvent( this.setting.navigatorEvent, function(){
this.jumping( index, true );
this.setNavActive( index, item );
}.bind(this) );
item.setSty... | random_line_split | |
js.js | the MIT License
*/
Element.Events.extend({
'wheelup': {
type: Element.Events.mousewheel.type,
map: function(event){
event = new Event(event);
if (event.wheel >= 0) this.fireEvent('wheelup', event)
}
},
'wheeldown': {
type: Element.Events.mousewheel.type,
map: function(event){
event = new Event... |
},
__getStyleMode:function(){
switch( this.setting.direction ){
case 'opacity': this.maxSize=0; this.minSize=1; return ['opacity','opacity'];
case 'vrup': this.maxSize=this.maxHeight; return ['top','height'];
case 'vrdown': this.maxSize=-this.maxHeight; return ['top','height'];
case 'hr... | {
this.navigatorItems.removeClass('active');
this.navigatorItems[index].addClass('active');
this.navivationAnimate( this.currentNo );
} | conditional_block |
income_tract.py | """income_tract.py
Extract the household income per tract for each cbsa, using the
crosswalk between CBSA and Tracts.
"""
import csv
import os
# Income file comprises estimates and margin of error
income_rows = [5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35]
#
# Import data
#
## CBSA to tract
tr_to_cbsa = {}
w... | tr_to_cbsa[rows[1]] = rows[0]
## Income data at blockgroup level
incomes = {}
with open('data/income/us/ACS_14_5YR_B19001.csv', 'r') as source:
reader = csv.reader(source, delimiter=',')
reader.next()
reader.next()
for rows in reader:
incomes[rows[1]] = [int(rows[i]) for i in income_row... | random_line_split | |
income_tract.py | """income_tract.py
Extract the household income per tract for each cbsa, using the
crosswalk between CBSA and Tracts.
"""
import csv
import os
# Income file comprises estimates and margin of error
income_rows = [5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35]
#
# Import data
#
## CBSA to tract
tr_to_cbsa = {}
w... |
## Save
with open('data/income/cbsa/%s/%s_income_tract.txt'%(cbsa, cbsa), 'w') as output:
output.write("TRACT FIP\tLess than $10000\t$10000-$14999\t$15000-$19999\t$20000-$24999\t$25000-$29999\t$30000-$34999\t$35000-$39999\t$40000-$44999\t$45000-$49999\t$50000-$59999\t$60000-$74999\t$75000-$99999\t... | os.mkdir('data/income/cbsa/%s'%cbsa) | conditional_block |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
... | );
}
}
}
} | }
CoverageKind::Unreachable => {
bx.add_coverage_unreachable(
instance,
code_region.expect("unreachable regions always have code regions"), | random_line_split |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) | // but do inject the counter intrinsic.
bx.add_coverage_counter(instance, id, code_region);
}
let coverageinfo = bx.tcx().coverageinfo(instance.def);
let fn_name = bx.get_pgo_func_name_var(instance);
... | {
// Determine the instance that coverage data was originally generated for.
let scope_data = &self.mir.source_scopes[scope];
let instance = if let Some((inlined_instance, _)) = scope_data.inlined {
self.monomorphize(inlined_instance)
} else if let Some(inlined_scope) = scope... | identifier_body |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn | (&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
// Determine the instance that coverage data was originally generated for.
let scope_data = &self.mir.source_scopes[scope];
let instance = if let Some((inlined_instance, _)) = scope_data.inlined {
self.monomorphize(inline... | codegen_coverage | identifier_name |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
... | bx.instrprof_increment(fn_name, hash, num_counters, index);
}
}
CoverageKind::Expression { id, lhs, op, rhs } => {
bx.add_coverage_counter_expression(instance, id, lhs, op, rhs, code_region);
}
CoverageKind::Unreachable... | {
// If `set_function_source_hash()` returned true, the coverage map is enabled,
// so continue adding the counter.
if let Some(code_region) = code_region {
// Note: Some counters do not have code regions, but may still be referenced
... | conditional_block |
eth.rs | self.sync.clone(), self.on_demand.clone());
Box::new(self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| {
if hdr.transactions_root() == KECCAK_NULL_RLP {
Either::A(future::ok(Some(U256::from(0).into())))
} else {
sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()... | compile_lll | identifier_name | |
eth.rs | ::default())
}
fn gas_price(&self) -> Result<RpcU256> {
Ok(self.cache.lock().gas_price_corpus()
.and_then(|c| c.median().cloned())
.map(RpcU256::from)
.unwrap_or_else(Default::default))
}
fn accounts(&self, meta: Metadata) -> Result<Vec<RpcH160>> {
let dapp: DappId = meta.dapp_id().into();
self.ac... | {
let eip86 = self.client.eip86_transition();
Box::new(self.fetcher().block(BlockId::Hash(hash.into())).map(move |block| {
light_fetch::extract_transaction_at_index(block, idx.value(), eip86)
}))
} | identifier_body | |
eth.rs | .sync.is_major_importing() {
let chain_info = self.client.chain_info();
let current_block = U256::from(chain_info.best_block_number);
let highest_block = self.sync.highest_block().map(U256::from)
.unwrap_or_else(|| current_block.clone());
Ok(SyncStatus::Info(SyncInfo {
starting_block: U256::from(se... | }
}))
}
fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> { | random_line_split | |
componentRegistry.js | /**
* @module lib/componentRegistry
* @memberof lux-lib
*/
import { isFunction, isString } from '../lib/is';
const registry = {};
/**
* Store a new component in the registry for later retrieval.
*
* @param {String} path - the identifier
* @param {Function} fn - the component definition
* @param {Boolean... |
if (fn && !isFunction(fn)) {
throw new Error('Components must be functions.');
}
if (arguments.length > 3) {
throw new Error('Too many arguments provided to componentRegistry.');
}
const saveToRegistry = registry[path] ? overwrite : true;
if (arguments.length > 1 && saveToRegistry) {
regist... | {
throw new Error('Component identifiers are required and must be strings.');
} | conditional_block |
componentRegistry.js | /**
* @module lib/componentRegistry
* @memberof lux-lib
*/
import { isFunction, isString } from '../lib/is';
const registry = {};
/**
* Store a new component in the registry for later retrieval.
*
* @param {String} path - the identifier
* @param {Function} fn - the component definition
* @param {Boolean... | * @return {any} - could be anything but typically would be a function or
* framework component
*
* @example
* import registry from './componentRegistry';
*
* // store a new component in the registry; overwrite if it already exists
* registry('Home', HomeComponent);
*
* // retrieve a registered component if it... | * registry component or not
* | random_line_split |
componentRegistry.js | /**
* @module lib/componentRegistry
* @memberof lux-lib
*/
import { isFunction, isString } from '../lib/is';
const registry = {};
/**
* Store a new component in the registry for later retrieval.
*
* @param {String} path - the identifier
* @param {Function} fn - the component definition
* @param {Boolean... | }
export default componentRegistry;
| {
if (!isString(path) || path === '') {
throw new Error('Component identifiers are required and must be strings.');
}
if (fn && !isFunction(fn)) {
throw new Error('Components must be functions.');
}
if (arguments.length > 3) {
throw new Error('Too many arguments provided to componentRegistry.');... | identifier_body |
componentRegistry.js | /**
* @module lib/componentRegistry
* @memberof lux-lib
*/
import { isFunction, isString } from '../lib/is';
const registry = {};
/**
* Store a new component in the registry for later retrieval.
*
* @param {String} path - the identifier
* @param {Function} fn - the component definition
* @param {Boolean... | (path, fn, overwrite = true) {
if (!isString(path) || path === '') {
throw new Error('Component identifiers are required and must be strings.');
}
if (fn && !isFunction(fn)) {
throw new Error('Components must be functions.');
}
if (arguments.length > 3) {
throw new Error('Too many arguments prov... | componentRegistry | identifier_name |
selectnav.spec.js | /*global describe, it, before, beforeEach, after, afterEach, browser: true, chai, selectnav*/
var assert = chai.assert;
var sandbox = document.createElement('div');
sandbox.setAttribute('id', 'sandbox');
document.body.appendChild(sandbox);
describe('selectnav', function () {
var result;
beforeEach(function () ... | describe.skip('when "label" option is set to false', function () {
beforeEach(function () {
result = selectnav('foo', {label: false});
});
it('do not include label', function () {
assert.lengthOf(result.children, 2);
});
});
describe('when "activeclass" option is set', function () ... | random_line_split | |
doxygen.py | s = "\nXED ERROR: mfile.py could not find mbuild." + \
" Should be a sibling of the xed2 directory.\n\n"
sys.stderr.write(s)
sys.exit(1)
###########################################################################
## DOXYGEN SUPPORT
#######################################################################... |
def _make_doxygen_reference_manual(env, doxygen_inputs, subs, work_queue,
hash_file_name='dox'):
"""Install the doxygen reference manual the doyxgen_output_dir
directory. doxygen_inputs is a list of files """
dox_dag = dag.dag_t(hash_file_name,env=env)
# so... | """return True if the directory d does not exist or if it contains no
files/subdirectories."""
if not os.path.exists(d):
return True
for (root, subdirs, subfiles) in os.walk(d):
if len(subfiles) or len(subdirs):
return False
return True | identifier_body |
doxygen.py | s = "\nXED ERROR: mfile.py could not find mbuild." + \
" Should be a sibling of the xed2 directory.\n\n"
sys.stderr.write(s)
sys.exit(1)
###########################################################################
## DOXYGEN SUPPORT
#######################################################################... |
except:
base.die("Doxygen required by the command line options " +
"but no doxygen found")
return (doxygen_cmd, doxygen_okay)
def _replace_match(istring, mtch, newstring, group_name):
"""This is a lame way of avoiding regular expression backslashing
... | for o in output:
base.msgb("Doxygen-version-check STDOUT", o)
if error_output:
for line in error_output:
base.msgb("STDERR ",line.rstrip()) | conditional_block |
doxygen.py | s = "\nXED ERROR: mfile.py could not find mbuild." + \
" Should be a sibling of the xed2 directory.\n\n"
sys.stderr.write(s)
sys.exit(1)
###########################################################################
## DOXYGEN SUPPORT
#######################################################################... | (env, subs):
"""Change the $(*) strings to the proper value in the config file.
Returns True on success"""
# doxygen wants quotes around paths with spaces
for k,s in iter(subs.items()):
if re.search(' ',s):
if not re.search('^".*"$',s):
base.die("Doxygen requires q... | _customize_doxygen_file | identifier_name |
doxygen.py | s = "\nXED ERROR: mfile.py could not find mbuild." + \
" Should be a sibling of the xed2 directory.\n\n"
sys.stderr.write(s)
sys.exit(1)
###########################################################################
## DOXYGEN SUPPORT
#####################################################################... | return False
def _find_doxygen(env):
"""Find the right version of doxygen. Return a tuple of the
command name and a boolean indicating whether or not the version
checked out."""
if env['doxygen_cmd'] == '':
doxygen_cmd_intel = "/usr/intel/bin/doxygen"
doxygen_cmd_cygwin = "C:/cygw... | random_line_split | |
test_need_two_invoices.py | # Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any la... |
def test_so_mto_need_one_invoice(self):
self.so.order_policy = 'picking'
self.sol.route_id = self.mto_route.id
self.so.action_button_confirm()
procurements = self.so.procurement_group_id.procurement_ids
procurements.run()
po = procurements.filtered('purchase_id')[:1... | self.so.order_policy = 'picking'
self.so.action_button_confirm()
po = self.so.procurement_group_id.procurement_ids.purchase_id
self.assertTrue(po)
po.signal_workflow('purchase_confirm')
picking = po.picking_ids
self.assertEqual(1, len(picking))
picking.action_don... | identifier_body |
test_need_two_invoices.py | # Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any la... | (TransactionCase):
def test_so_and_po_on_delivery_need_two_invoices(self):
self.so.order_policy = 'picking'
self.so.action_button_confirm()
po = self.so.procurement_group_id.procurement_ids.purchase_id
self.assertTrue(po)
po.invoice_method = 'picking'
po.signal_work... | TestNeedTwoInvoices | identifier_name |
test_need_two_invoices.py | # Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any la... |
picking = po.picking_ids
self.assertEqual(1, len(picking))
picking.action_done()
wizard = self.Wizard.with_context({
'active_id': picking.id,
'active_ids': [picking.id],
}).create({})
self.assertIs(False, wizard._need_two_invoices())
def tes... | self.so.action_button_confirm()
po = self.so.procurement_group_id.procurement_ids.purchase_id
self.assertTrue(po)
po.signal_workflow('purchase_confirm') | random_line_split |
githubIssues.ts | import * as fs from 'fs';
import * as path from 'path';
import * as GitHub from 'github';
import { copy } from 'copy-paste';
import { fill } from 'git-credential-node';
import { Event, EventEmitter, TreeDataProvider, TreeItem, ExtensionContext, Uri, TreeItemCollapsibleState, window, workspace, commands } from 'vscode... |
const params = { q, sort: 'created', order: 'asc', per_page: 100 };
const res = await this.github.search.issues(<any>params);
issues.push(...res.data.items.map(item => {
const issue = new Issue(`${item.title} (#${item.number})`, item);
issue.iconPath = {
light: this.context.asAbsolutePath(... | {
q += ` milestone:"${milestone}"`;
} | conditional_block |
githubIssues.ts | import * as fs from 'fs';
import * as path from 'path';
import * as GitHub from 'github';
import { copy } from 'copy-paste';
import { fill } from 'git-credential-node';
import { Event, EventEmitter, TreeDataProvider, TreeItem, ExtensionContext, Uri, TreeItemCollapsibleState, window, workspace, commands } from 'vscode... |
getTreeItem(element: TreeItem): TreeItem {
return element;
}
async getChildren(element?: TreeItem): Promise<TreeItem[]> {
if (element instanceof Milestone) {
return element.issues;
}
if (!this.children) {
this.fetching = true;
this.lastFetch = Date.now();
this.children = this.fetchChildren();... | {
context.subscriptions.push(commands.registerCommand('githubIssues.refresh', this.refresh, this));
context.subscriptions.push(commands.registerCommand('githubIssues.openIssue', this.openIssue, this));
context.subscriptions.push(commands.registerCommand('githubIssues.copyNumber', this.copyNumber, this));
contex... | identifier_body |
githubIssues.ts | import * as fs from 'fs';
import * as path from 'path';
import * as GitHub from 'github';
import { copy } from 'copy-paste';
import { fill } from 'git-credential-node';
import { Event, EventEmitter, TreeDataProvider, TreeItem, ExtensionContext, Uri, TreeItemCollapsibleState, window, workspace, commands } from 'vscode... | milestones.push(milestone);
}
milestone.issues.push(issue);
}
if (milestones.length === 1 && milestones[0].label === 'No Milestone') {
return milestones[0].issues;
}
return milestones;
}
private openIssue(issue: Issue) {
commands.executeCommand('vscode.open', Uri.parse(issue.item.html_url));... | let milestone = milestoneIndex[milestoneLabel];
if (!milestone) {
milestone = new Milestone(milestoneLabel);
milestoneIndex[milestoneLabel] = milestone; | random_line_split |
githubIssues.ts | import * as fs from 'fs';
import * as path from 'path';
import * as GitHub from 'github';
import { copy } from 'copy-paste';
import { fill } from 'git-credential-node';
import { Event, EventEmitter, TreeDataProvider, TreeItem, ExtensionContext, Uri, TreeItemCollapsibleState, window, workspace, commands } from 'vscode... | implements TreeDataProvider<TreeItem> {
private _onDidChangeTreeData = new EventEmitter<TreeItem | undefined>();
readonly onDidChangeTreeData = this._onDidChangeTreeData.event;
private github = new GitHub();
private fetching = false;
private lastFetch: number;
private children: Promise<TreeItem[]>;
construc... | GitHubIssuesProvider | identifier_name |
p2p-feefilter.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from te... | FeeFilterTest().main() | conditional_block | |
p2p-feefilter.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from te... | (self):
super().__init__()
self.num_nodes = 2
self.setup_clean_chain = False
def setup_network(self):
# Node1 will be used to generate txs which should be relayed from Node0
# to our test node
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdi... | __init__ | identifier_name |
p2p-feefilter.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from te... | self.txinvs = []
def send_filter(self, feerate):
self.send_message(msg_feefilter(feerate))
self.sync_with_ping()
class FeeFilterTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 2
self.setup_clean_chain = False
def set... | with mininode_lock: | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.