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
main.rs
extern crate term_mux; extern crate termion; extern crate chan_signal; use std::io::{Read, Write, Result}; use std::fs::File; use std::thread; use std::time::Duration; use termion::get_tty; use termion::raw::IntoRawMode; use chan_signal::{notify, Signal}; use term_mux::pty::Pty; use term_mux::tui::{get_terminal_size, ...
fn pipe(input: &mut File, output: &mut File) -> Result<()> { let mut packet = [0; 4096]; let count = input.read(&mut packet)?; let read = &packet[..count]; output.write_all(&read)?; output.flush()?; Ok(()) }
random_line_split
exhibition.js
/** * Created by Mark on 24-3-2016. */ 'use strict' module.exports = function(sequelize, DataTypes) { var Exhibition = sequelize.define('Exhibition', { id: { type: DataTypes.INTEGER, autoIncrement: true,
allowNull: false }, name: { type: DataTypes.STRING, allowNull: false }, description: DataTypes.STRING, street_and_number: DataTypes.STRING(80), city: { type: DataTypes.STRING(40), ...
primaryKey: true,
random_line_split
MergerError.ts
import { encodePointer } from "json-ptr"; import { GlobalScope, MergeFileScope, RootMergeFileScope, ScopeBase, } from "./Scope"; export default class MergerError extends Error { constructor(originalError: Error, scope: ScopeBase) { super(); // Set the prototype explicitly because because new.target ...
return trace; } }
{ const pathEncoded = encodePointer(currentScope.propertyPath); let filePath = ""; if ( currentScope instanceof MergeFileScope || currentScope instanceof RootMergeFileScope ) { filePath = currentScope.sourceFilePath; } trace += ` at ${filePath}#${pathEncode...
conditional_block
MergerError.ts
import { encodePointer } from "json-ptr"; import { GlobalScope, MergeFileScope, RootMergeFileScope, ScopeBase, } from "./Scope"; export default class MergerError extends Error { constructor(originalError: Error, scope: ScopeBase) { super(); // Set the prototype explicitly because because new.target ...
private _createProcessingStackTrace(scope: ScopeBase) { let trace = ""; let currentScope = scope; while (currentScope && !(currentScope instanceof GlobalScope)) { const pathEncoded = encodePointer(currentScope.propertyPath); let filePath = ""; if ( currentScope instanceof Merge...
{ let message = ""; if (scope) { const lastProp = scope.propertyPath[scope.propertyPath.length - 1]; message = `An error occurred while processing the property "${lastProp}"\n`; } return message; }
identifier_body
MergerError.ts
ScopeBase, } from "./Scope"; export default class MergerError extends Error { constructor(originalError: Error, scope: ScopeBase) { super(); // Set the prototype explicitly because because new.target // is not available in ES5 runtime environments. (this as any).__proto__ = MergerError.prototype; ...
import { encodePointer } from "json-ptr"; import { GlobalScope, MergeFileScope, RootMergeFileScope,
random_line_split
MergerError.ts
import { encodePointer } from "json-ptr"; import { GlobalScope, MergeFileScope, RootMergeFileScope, ScopeBase, } from "./Scope"; export default class MergerError extends Error {
(originalError: Error, scope: ScopeBase) { super(); // Set the prototype explicitly because because new.target // is not available in ES5 runtime environments. (this as any).__proto__ = MergerError.prototype; const message = this._createMessage(scope); const stack = this._createProcessingStack...
constructor
identifier_name
tools.py
import sys import inspect import os import numpy as np import time import timeit import collections import subprocess from qtools.qtpy import QtCore, QtGui from qtools.utils import get_application, show_window from functools import wraps from galry import log_debug, log_info, log_warn from collections import OrderedDic...
self.times = collections.deque(maxlen=maxlen) self.fps = 0. self.delta = 0. def tick(self): """Record the current time stamp. To be called by paintGL(). """ self.times.append(timeit.default_timer()) def get_fps(self): ...
maxlen = self.maxlen
conditional_block
tools.py
import sys import inspect import os import numpy as np import time import timeit import collections import subprocess from qtools.qtpy import QtCore, QtGui from qtools.utils import get_application, show_window from functools import wraps from galry import log_debug, log_info, log_warn from collections import OrderedDic...
maxlen = 10 def __init__(self, maxlen=None): if maxlen is None: maxlen = self.maxlen self.times = collections.deque(maxlen=maxlen) self.fps = 0. self.delta = 0. def tick(self): """Record the current time stamp. To be called b...
return x.__array_interface__['data'][0] class FpsCounter(object): """Count FPS.""" # memory for the FPS counter
random_line_split
tools.py
import sys import inspect import os import numpy as np import time import timeit import collections import subprocess from qtools.qtpy import QtCore, QtGui from qtools.utils import get_application, show_window from functools import wraps from galry import log_debug, log_info, log_warn from collections import OrderedDic...
(dir=".", autodestruct=True, condition=None, ignore=[]): """Run all scripts successively.""" if condition is None: condition = lambda file: file.endswith(".py") and not file.startswith("_") os.chdir(dir) files = sorted([file for file in os.listdir(dir) if condition(file)]) for file in files:...
run_all_scripts
identifier_name
tools.py
import sys import inspect import os import numpy as np import time import timeit import collections import subprocess from qtools.qtpy import QtCore, QtGui from qtools.utils import get_application, show_window from functools import wraps from galry import log_debug, log_info, log_warn from collections import OrderedDic...
class FpsCounter(object): """Count FPS.""" # memory for the FPS counter maxlen = 10 def __init__(self, maxlen=None): if maxlen is None: maxlen = self.maxlen self.times = collections.deque(maxlen=maxlen) self.fps = 0. self.delta = 0. def...
"""Return the address of an array data, used to check whether two arrays refer to the same data in memory.""" return x.__array_interface__['data'][0]
identifier_body
instr_kshiftrd.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 kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direc...
{ run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K2)), operand2: Some(Direct(K6)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 214, 43], OperandSize::Qword) }
identifier_body
instr_kshiftrd.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 kshiftrd_1() {
run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K2)), operand2: Some(Direct(K6)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 214, 43], OperandSize::Qword) }
run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 203, 43], OperandSize::Dword) } #[test] fn ...
random_line_split
instr_kshiftrd.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 kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direc...
() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K2)), operand2: Some(Direct(K6)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 214, 43], OperandSize::Qword) }
kshiftrd_2
identifier_name
config.test-functional.ts
import { declareRuntimeEnv } from '@resolve-js/scripts' const testFunctionalConfig = { mode: 'development', runtime: { module: '@resolve-js/runtime-single-process', options: { host: declareRuntimeEnv('HOST', 'localhost'), port: declareRuntimeEnv('PORT', '3000'), },
distDir: 'dist', readModelConnectors: { default: { module: '@resolve-js/readmodel-lite', options: { databaseFile: 'data/read-models-test-functional.db', }, }, }, eventstoreAdapter: { module: '@resolve-js/eventstore-lite', options: { databaseFile: 'data/event-store...
}, rootPath: '', staticPath: 'static', staticDir: 'static',
random_line_split
__init__.py
# -*- encoding: utf-8 -*- ############################################################################## #
# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it wil...
# OpenERP, Open Source Management Solution # # Copyright (C) 2014 Didotech srl (<http://www.didotech.com>). # # All Rights Reserved
random_line_split
frame_tests.py
import unittest import random from ..frame import Frame, decode_frame from ..message import MessageType from ..utilslib.strings import random_bytes class
(unittest.TestCase): MSG_TYPE = MessageType.HELLO PAYLOAD = "Hello World!" def frame_setup(self, msg_type, payload): self.msg_type = msg_type self.payload = payload self.frame = Frame(self.msg_type, self.payload) def setUp(self): self.frame_setup(self.MSG_TYPE, self.PAY...
FrameTestCase
identifier_name
frame_tests.py
import unittest import random from ..frame import Frame, decode_frame from ..message import MessageType from ..utilslib.strings import random_bytes class FrameTestCase(unittest.TestCase): MSG_TYPE = MessageType.HELLO PAYLOAD = "Hello World!" def frame_setup(self, msg_type, payload): self.msg_type...
self.frame_setup(random.choice(MessageType.values()), b"")
identifier_body
frame_tests.py
import unittest import random from ..frame import Frame, decode_frame from ..message import MessageType from ..utilslib.strings import random_bytes class FrameTestCase(unittest.TestCase): MSG_TYPE = MessageType.HELLO PAYLOAD = "Hello World!"
self.payload = payload self.frame = Frame(self.msg_type, self.payload) def setUp(self): self.frame_setup(self.MSG_TYPE, self.PAYLOAD) def tearDown(self): self.msg_type = None self.payload = None self.frame = None def test_eq_at_decode_after_encode(self): ...
def frame_setup(self, msg_type, payload): self.msg_type = msg_type
random_line_split
saveRetrospectiveSurveyResponses.test.js
/* eslint-env mocha */ /* global expect, testContext */ /* eslint-disable prefer-arrow-callback, no-unused-expressions */ import factory from 'src/test/factories' import {resetDB, runGraphQLMutation, useFixture} from 'src/test/helpers' import {Cycle} from 'src/server/services/dataService' import {COMPLETE, PRACTICE} fr...
beforeEach(async function () { await this.buildSurvey() this.user = await factory.build('user', {id: this.project.memberIds[0]}) this.respondentId = this.project.memberIds[0] this.invokeAPI = function () { const responses = this.project.memberIds.slice(1).map(memberId => ({ values: [{su...
random_line_split
tests.py
""" Tests for file field behavior, and specifically #639, in which Model.save() gets called *again* for each FileField. This test will fail if calling a ModelForm's save() method causes Model.save() to be called more than once. """ from __future__ import absolute_import import os import shutil from django.core.files...
""" Make sure to delete the "uploaded" file to avoid clogging /tmp. """ p = Photo.objects.get() p.image.delete(save=False) shutil.rmtree(temp_storage_dir)
def testBug639(self): """ Simulate a file upload and check how many times Model.save() gets called. """ # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.jpg") img = open(filename, "rb").read() # Fake a POST QueryDict a...
identifier_body
tests.py
""" Tests for file field behavior, and specifically #639, in which Model.save() gets called *again* for each FileField. This test will fail if calling a ModelForm's save() method causes Model.save() to be called more than once. """ from __future__ import absolute_import import os import shutil from django.core.files...
(self): """ Simulate a file upload and check how many times Model.save() gets called. """ # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.jpg") img = open(filename, "rb").read() # Fake a POST QueryDict and FILES Multi...
testBug639
identifier_name
tests.py
""" Tests for file field behavior, and specifically #639, in which Model.save() gets called *again* for each FileField. This test will fail if calling a ModelForm's save() method causes Model.save() to be called more than once. """ from __future__ import absolute_import import os import shutil from django.core.files...
called. """ # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.jpg") img = open(filename, "rb").read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} files = {"image": SimpleUploadedFile('t...
def testBug639(self): """ Simulate a file upload and check how many times Model.save() gets
random_line_split
transit.rs
#[derive(Debug, Clone)] pub struct Transit { period: f64, base: f64, depth: f64, duration: f64, decay: f64, phase: f64, } impl Transit {
let k = (time/self.period).floor(); let t = time - k * self.period; if t < self.phase { self.base } else if t < (self.phase + self.decay) { let start = self.phase; let f = (t - start) / self.decay; self.base - f * self.depth } else...
pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit { Transit { period, base, depth, duration, decay, phase } } pub fn value(&self, time: &f64) -> f64 {
random_line_split
transit.rs
#[derive(Debug, Clone)] pub struct Transit { period: f64, base: f64, depth: f64, duration: f64, decay: f64, phase: f64, } impl Transit { pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit { Transit { period, base, depth, duration, decay, ...
}
{ let k = (time/self.period).floor(); let t = time - k * self.period; if t < self.phase { self.base } else if t < (self.phase + self.decay) { let start = self.phase; let f = (t - start) / self.decay; self.base - f * self.depth } el...
identifier_body
transit.rs
#[derive(Debug, Clone)] pub struct
{ period: f64, base: f64, depth: f64, duration: f64, decay: f64, phase: f64, } impl Transit { pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit { Transit { period, base, depth, duration, decay, phase } } pub fn value(&self, tim...
Transit
identifier_name
transit.rs
#[derive(Debug, Clone)] pub struct Transit { period: f64, base: f64, depth: f64, duration: f64, decay: f64, phase: f64, } impl Transit { pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit { Transit { period, base, depth, duration, decay, ...
else if t < (self.phase + self.decay) { let start = self.phase; let f = (t - start) / self.decay; self.base - f * self.depth } else if t < (self.phase + self.decay + self.duration) { self.base - self.depth } else if t < (self.phase + self.decay + self.dur...
{ self.base }
conditional_block
triple_apply_weighted_pagerank.py
import graphlab as gl import time def pagerank_update_fn(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links dst['pagerank'] += src['prev_pagerank'] * edge['weight'] return (src, edge, dst) def sum_weight(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links s...
(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links edge['weight'] /= src['total_weight'] return src, edge, dst def pagerank_triple_apply(input_graph, reset_prob=0.15, threshold=1e-3, max_iterations=20): g = gl.SGraph(input_graph.vertices, input_graph.edg...
normalize_weight
identifier_name
triple_apply_weighted_pagerank.py
import graphlab as gl import time def pagerank_update_fn(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links
return (src, edge, dst) def sum_weight(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links src['total_weight'] += edge['weight'] return src, edge, dst def normalize_weight(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links edge['weight'] /= src['total_...
dst['pagerank'] += src['prev_pagerank'] * edge['weight']
conditional_block
triple_apply_weighted_pagerank.py
import graphlab as gl import time def pagerank_update_fn(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links dst['pagerank'] += src['prev_pagerank'] * edge['weight'] return (src, edge, dst) def sum_weight(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links s...
def pagerank_triple_apply(input_graph, reset_prob=0.15, threshold=1e-3, max_iterations=20): g = gl.SGraph(input_graph.vertices, input_graph.edges) # compute normalized edge weight g.vertices['total_weight'] = 0.0 g = g.triple_apply(sum_weight, ['total_weight']) g = g.tr...
if src['__id'] != dst['__id']: # ignore self-links edge['weight'] /= src['total_weight'] return src, edge, dst
identifier_body
triple_apply_weighted_pagerank.py
import time def pagerank_update_fn(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links dst['pagerank'] += src['prev_pagerank'] * edge['weight'] return (src, edge, dst) def sum_weight(src, edge, dst): if src['__id'] != dst['__id']: # ignore self-links src['total_weight'] += ...
import graphlab as gl
random_line_split
backends.py
# -*- coding: utf-8 -*- import logging import os import re import uuid from django.conf import settings from django.contrib.auth.hashers import check_password import pexpect from ..users.models import User logger = logging.getLogger(__name__) class KerberosAuthenticationBackend(object): """Authenticate using...
# remove all non-alphanumerics username = re.sub('\W', '', username) krb_ticket = self.get_kerberos_ticket(username, password) if not krb_ticket: return None else: logger.debug("Authentication successful") try: user = User.get...
"""Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to authenticate. Returns: `Use...
identifier_body
backends.py
# -*- coding: utf-8 -*- import logging import os import re import uuid from django.conf import settings from django.contrib.auth.hashers import check_password import pexpect from ..users.models import User logger = logging.getLogger(__name__) class KerberosAuthenticationBackend(object): """Authenticate using...
def get_user(self, user_id): """Returns a user, given his or her user id. Required for a custom authentication backend. Args: user_id The user id of the user to fetch. Returns: User or None """ try: return User.get_user...
logger.debug("Authentication successful") try: user = User.get_user(username=username) except User.DoesNotExist: # Shouldn't happen logger.error("User {} successfully authenticated but not found " "in LDAP.".format(username)) user,...
conditional_block
backends.py
# -*- coding: utf-8 -*- import logging import os import re import uuid from django.conf import settings from django.contrib.auth.hashers import check_password import pexpect from ..users.models import User logger = logging.getLogger(__name__) class KerberosAuthenticationBackend(object): """Authenticate using...
class MasterPasswordAuthenticationBackend(object): """Authenticate as any user against a master password whose hash is in secret.py. Forces a simple LDAP bind. """ def authenticate(self, username=None, password=None): """Authenticate a username-password pair. Creates a new user if ...
""" try: return User.get_user(id=user_id) except User.DoesNotExist: return None
random_line_split
backends.py
# -*- coding: utf-8 -*- import logging import os import re import uuid from django.conf import settings from django.contrib.auth.hashers import check_password import pexpect from ..users.models import User logger = logging.getLogger(__name__) class KerberosAuthenticationBackend(object): """Authenticate using...
(self, username=None, password=None): """Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to au...
authenticate
identifier_name
test_data.ts
import { Commit } from '../util'; import { Branch } from '../rpc/status'; import { } from '../rpc-mock/test_data'; const fixedDate = Date.now(); const timestampSinceFixed = (seconds: number = 0) => new Date(fixedDate - 1000 * seconds).toISOString(); const numCommits = 0; function nextTimestamp() { return timestampSi...
ret.push(commit(i + 1, i + 2)); } } return ret; })(), ]; export const complexBranchData: [Array<Branch>, Array<Commit>] = [ [ { name: 'main', head: 'abc0' }, { name: 'branch1', head: 'abc1' }, { name: 'branch2', head: 'abc22' }, { name: 'branch3', head: 'abc3' }, { name: '...
if (i < 6) { ret.push(commit(i + 1, i + 3)); } else if (i === 6) {
random_line_split
test_data.ts
import { Commit } from '../util'; import { Branch } from '../rpc/status'; import { } from '../rpc-mock/test_data'; const fixedDate = Date.now(); const timestampSinceFixed = (seconds: number = 0) => new Date(fixedDate - 1000 * seconds).toISOString(); const numCommits = 0; function nextTimestamp() { return timestampSi...
} return ret; })(), ]; export const complexBranchData: [Array<Branch>, Array<Commit>] = [ [ { name: 'main', head: 'abc0' }, { name: 'branch1', head: 'abc1' }, { name: 'branch2', head: 'abc22' }, { name: 'branch3', head: 'abc3' }, { name: 'Fizz Rolled', head: 'abc20' }, { name: 'Baz...
{ ret.push(commit(i + 1, i + 2)); }
conditional_block
test_data.ts
import { Commit } from '../util'; import { Branch } from '../rpc/status'; import { } from '../rpc-mock/test_data'; const fixedDate = Date.now(); const timestampSinceFixed = (seconds: number = 0) => new Date(fixedDate - 1000 * seconds).toISOString(); const numCommits = 0; function
() { return timestampSinceFixed(10 * numCommits); } const commitTemplate: Commit = { hash: 'abc0', author: 'alice@example.com', parents: ['abc1'], subject: 'current HEAD', body: 'the most recent commit', timestamp: '', shortAuthor: '', shortHash: '', shortSubject: '', issue: '', patchStorage: ''...
nextTimestamp
identifier_name
test_data.ts
import { Commit } from '../util'; import { Branch } from '../rpc/status'; import { } from '../rpc-mock/test_data'; const fixedDate = Date.now(); const timestampSinceFixed = (seconds: number = 0) => new Date(fixedDate - 1000 * seconds).toISOString(); const numCommits = 0; function nextTimestamp() { return timestampSi...
export const singleBranchData: [Array<Branch>, Array<Commit>] = [ [{ name: 'main', head: 'abc0' }], (() => { const ret: Array<Commit> = []; for (let i = 0; i < 20; ++i) { ret.push(commit(i, i + 1)); } return ret; })(), ]; export const doubleBranchData: [Array<Branch>, Array<Commit>] = [ ...
{ return { ...commitTemplate, hash: `abc${curr}`, parents: [`abc${parent}`] }; }
identifier_body
plot_index_loop_seasonal.py
import os import numpy as np import matplotlib.pyplot as plt from matplotlib import cm, colors initDir = '../init/' nlat = 31 nlon = 30 # Dimensions L = 1.5e7 c0 = 2 timeDim = L / c0 / (60. * 60. * 24) H = 200 tau_0 = 1.0922666667e-2 delta_T = 1. sampFreq = 0.35 / 0.06 * 12 # (in year^-1) # Case definition muRng = n...
# Plot fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(freq, np.log10(perioRAVG), '-k') # ax.set_xscale('log') # ax.set_yscale('log') ax.set_xlim(0, 4) #ax.set_ylim(0, vmax) ax.set_xlabel(r...
perioRAVG[iavg] = perio[iavg-nRAVG/2:iavg+nRAVG/2 + 1].mean()\ / nRAVG
conditional_block
plot_index_loop_seasonal.py
import os import numpy as np import matplotlib.pyplot as plt from matplotlib import cm, colors initDir = '../init/' nlat = 31 nlon = 30 # Dimensions L = 1.5e7 c0 = 2 timeDim = L / c0 / (60. * 60. * 24) H = 200 tau_0 = 1.0922666667e-2 delta_T = 1. sampFreq = 0.35 / 0.06 * 12 # (in year^-1) # Case definition muRng = n...
/ nRAVG # Plot fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(freq, np.log10(perioRAVG), '-k') # ax.set_xscale('log') # ax.set_yscale('log') ax.set_xlim(0, 4) #ax.set_ylim...
for iavg in np.arange(nRAVG/2, nfft-nRAVG/2): perioRAVG[iavg] = perio[iavg-nRAVG/2:iavg+nRAVG/2 + 1].mean()\
random_line_split
main.rs
use std::sync::{Arc, Mutex}; use std::thread; use std::sync::mpsc; fn
() { let data = Arc::new(Mutex::new(vec![1u32, 2, 3])); for i in 0..3{ let data = data.clone(); thread::spawn(move||{ let mut data = data.lock().unwrap(); data[i] += 1; }); } thread::sleep_ms(50); let handle = thread::spawn(||{ println!("This is in a thread, not main"); thread::sleep_ms(5000);...
main
identifier_name
main.rs
use std::sync::{Arc, Mutex}; use std::thread; use std::sync::mpsc; fn main()
thread::sleep_ms(5000); println!("{}",handle.join().unwrap()); thread::sleep_ms(5000); println!("Hello, world, in main thread!"); println!("-------------------------------"); let (tx, rx) = mpsc::channel(); for _ in 0..10{ let tx = tx.clone(); thread::spawn(move ||{ let answer = 42u32; tx.send(...
{ let data = Arc::new(Mutex::new(vec![1u32, 2, 3])); for i in 0..3{ let data = data.clone(); thread::spawn(move||{ let mut data = data.lock().unwrap(); data[i] += 1; }); } thread::sleep_ms(50); let handle = thread::spawn(||{ println!("This is in a thread, not main"); thread::sleep_ms(5000); ...
identifier_body
main.rs
use std::sync::{Arc, Mutex}; use std::thread; use std::sync::mpsc; fn main() { let data = Arc::new(Mutex::new(vec![1u32, 2, 3])); for i in 0..3{ let data = data.clone(); thread::spawn(move||{ let mut data = data.lock().unwrap(); data[i] += 1;
let handle = thread::spawn(||{ println!("This is in a thread, not main"); thread::sleep_ms(5000); "return from thread" }); thread::sleep_ms(5000); println!("{}",handle.join().unwrap()); thread::sleep_ms(5000); println!("Hello, world, in main thread!"); println!("-------------------------------"); l...
}); } thread::sleep_ms(50);
random_line_split
security.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::fs; use std::io::Read; use std::path::PathBuf; use collections::HashSet; use encryption_export::EncryptionConfig; use grpcio::{ChannelCredentials, ChannelCredentialsBuilder}; use security::SecurityConfig; pub fn new_security_cfg(cn: Option<H...
.unwrap(); fs::File::open(format!("{}", p.join("data/key.pem").display())) .unwrap() .read_to_string(&mut key) .unwrap(); fs::File::open(format!("{}", p.join("data/ca.pem").display())) .unwrap() .read_to_string(&mut ca) .unwrap(); (ca, cert, key) }
.read_to_string(&mut cert)
random_line_split
security.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::fs; use std::io::Read; use std::path::PathBuf; use collections::HashSet; use encryption_export::EncryptionConfig; use grpcio::{ChannelCredentials, ChannelCredentialsBuilder}; use security::SecurityConfig; pub fn new_security_cfg(cn: Option<H...
() -> ChannelCredentials { let (ca, cert, key) = load_certs(); ChannelCredentialsBuilder::new() .root_cert(ca.into()) .cert(cert.into(), key.into()) .build() } fn load_certs() -> (String, String, String) { let mut cert = String::new(); let mut key = String::new(); let mut ca...
new_channel_cred
identifier_name
security.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::fs; use std::io::Read; use std::path::PathBuf; use collections::HashSet; use encryption_export::EncryptionConfig; use grpcio::{ChannelCredentials, ChannelCredentialsBuilder}; use security::SecurityConfig; pub fn new_security_cfg(cn: Option<H...
pub fn new_channel_cred() -> ChannelCredentials { let (ca, cert, key) = load_certs(); ChannelCredentialsBuilder::new() .root_cert(ca.into()) .cert(cert.into(), key.into()) .build() } fn load_certs() -> (String, String, String) { let mut cert = String::new(); let mut key = Stri...
{ let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); SecurityConfig { ca_path: format!("{}", p.join("data/ca.pem").display()), cert_path: format!("{}", p.join("data/server.pem").display()), key_path: format!("{}", p.join("data/key.pem").display()), override_ssl_target: "".to_owne...
identifier_body
instance.ts
import { computed, reactive } from 'vue'; import { api } from './os'; // TODO: 他のタブと永続化されたstateを同期 type Instance = {
}[]; }; const data = localStorage.getItem('instance'); // TODO: instanceをリアクティブにするかは再考の余地あり export const instance: Instance = reactive(data ? JSON.parse(data) : { // TODO: set default values }); export async function fetchInstance() { const meta = await api('meta', { detail: false }); for (const [k, v] of O...
emojis: { category: string;
random_line_split
instance.ts
import { computed, reactive } from 'vue'; import { api } from './os'; // TODO: 他のタブと永続化されたstateを同期 type Instance = { emojis: { category: string; }[]; }; const data = localStorage.getItem('instance'); // TODO: instanceをリアクティブにするかは再考の余地あり export const instance: Instance = reactive(data ? JSON.parse(data) : { //...
s = new Set(); for (const emoji of instance.emojis) { categories.add(emoji.category); } return Array.from(categories); }); // このファイルに書きたくないけどここに書かないと何故かVeturが認識しない declare module '@vue/runtime-core' { interface ComponentCustomProperties { $instance: typeof instance; } }
nst [k, v] of Object.entries(meta)) { instance[k] = v; } localStorage.setItem('instance', JSON.stringify(instance)); } export const emojiCategories = computed(() => { const categorie
identifier_body
instance.ts
import { computed, reactive } from 'vue'; import { api } from './os'; // TODO: 他のタブと永続化されたstateを同期 type Instance = { emojis: { category: string; }[]; }; const data = localStorage.getItem('instance'); // TODO: instanceをリアクティブにするかは再考の余地あり export const instance: Instance = reactive(data ? JSON.parse(data) : { //...
(const [k, v] of Object.entries(meta)) { instance[k] = v; } localStorage.setItem('instance', JSON.stringify(instance)); } export const emojiCategories = computed(() => { const categories = new Set(); for (const emoji of instance.emojis) { categories.add(emoji.category); } return Array.from(categories); }); ...
e }); for
identifier_name
echo.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "echo"; #[test] fn test_default() { let (_, mut ucmd) = testing(UTIL_NAME); assert_eq!(ucmd.run().stdout, "\n"); } #[test] fn test_no_trailing_newline() { let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-n") .ar...
#[test] fn test_disable_escapes() { let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-E") .arg("\\b\\c\\e"); assert_eq!(ucmd.run().stdout, "\\b\\c\\e\n"); }
{ let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-e") .arg("\\\\\\t\\r"); assert_eq!(ucmd.run().stdout, "\\\t\r\n"); }
identifier_body
echo.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "echo"; #[test] fn test_default() { let (_, mut ucmd) = testing(UTIL_NAME); assert_eq!(ucmd.run().stdout, "\n"); } #[test] fn test_no_trailing_newline() { let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-n") .ar...
() { let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-E") .arg("\\b\\c\\e"); assert_eq!(ucmd.run().stdout, "\\b\\c\\e\n"); }
test_disable_escapes
identifier_name
echo.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "echo"; #[test] fn test_default() { let (_, mut ucmd) = testing(UTIL_NAME);
} #[test] fn test_no_trailing_newline() { let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-n") .arg("hello_world"); assert_eq!(ucmd.run().stdout, "hello_world"); } #[test] fn test_enable_escapes() { let (_, mut ucmd) = testing(UTIL_NAME); ucmd.arg("-e") .arg("\\\\\\t\\r"); ...
assert_eq!(ucmd.run().stdout, "\n");
random_line_split
d2.rs
fn run(program: Vec<usize>) -> usize { let mut arr = program.clone(); let mut i = 0; loop { let op = arr[i]; if op == 99 { return arr[0]; }
let to = arr[i + 3]; if op == 1 { arr[to] = arr[a] + arr[b] } else if op == 2 { arr[to] = arr[a] * arr[b] } i += 4 } } fn main() { let program: Vec<usize> = include_str!("./input.txt") .split(",") .map(|i| i.parse::<usize>().unwrap()) .collect(); // p1 let mut p1 = ...
let a = arr[i + 1]; let b = arr[i + 2];
random_line_split
d2.rs
fn run(program: Vec<usize>) -> usize { let mut arr = program.clone(); let mut i = 0; loop { let op = arr[i]; if op == 99 { return arr[0]; } let a = arr[i + 1]; let b = arr[i + 2]; let to = arr[i + 3]; if op == 1 { arr[to] = arr[a] + arr[b] } else if op == 2 { arr[...
} } }
{ println!("{}", 100 * x + y) }
conditional_block
d2.rs
fn run(program: Vec<usize>) -> usize { let mut arr = program.clone(); let mut i = 0; loop { let op = arr[i]; if op == 99 { return arr[0]; } let a = arr[i + 1]; let b = arr[i + 2]; let to = arr[i + 3]; if op == 1 { arr[to] = arr[a] + arr[b] } else if op == 2 { arr[...
() { let program: Vec<usize> = include_str!("./input.txt") .split(",") .map(|i| i.parse::<usize>().unwrap()) .collect(); // p1 let mut p1 = program.clone(); p1[1] = 12; p1[2] = 2; println!("{}", run(p1)); // p2 for x in 0..100 { for y in 0..100 { let mut p2 = program.clone(); ...
main
identifier_name
d2.rs
fn run(program: Vec<usize>) -> usize { let mut arr = program.clone(); let mut i = 0; loop { let op = arr[i]; if op == 99 { return arr[0]; } let a = arr[i + 1]; let b = arr[i + 2]; let to = arr[i + 3]; if op == 1 { arr[to] = arr[a] + arr[b] } else if op == 2 { arr[...
} } } }
{ let program: Vec<usize> = include_str!("./input.txt") .split(",") .map(|i| i.parse::<usize>().unwrap()) .collect(); // p1 let mut p1 = program.clone(); p1[1] = 12; p1[2] = 2; println!("{}", run(p1)); // p2 for x in 0..100 { for y in 0..100 { let mut p2 = program.clone(); ...
identifier_body
status.js
/** * @version 0.1 * @author Jesus Macias Portela, Fernando Ruiz Hernandez, Mario Izquierdo Rodriguez **/ var bulb; var status; var date; exports._get = function(){ Ti.API.debug('GLEB - Cargando status View'); // create UI components var view = Ti.UI.createView({ backgroundImage: '../../images/statusBar.png'...
push = Ti.UI.createImageView({ top: Ti.App.glebUtils._p(4), left: Ti.App.glebUtils._p(144), width: Ti.App.glebUtils._p(32), height: Ti.App.glebUtils._p(32), image: '../../images/push.png' }); gcm = Ti.UI.createImageView({ top: Ti.App.glebUtils._p(0), ...
left: Ti.App.glebUtils._p(22), width: Ti.App.glebUtils._p(100), height: Ti.App.glebUtils._p(40), image: '../../images/ACS_off.png' });
random_line_split
index.js
const BloomFilter = require('@mixmaxhq/bloom-filter'); /** * `sha.js` is an isomorphic hashing library that implements its hashing functions synchronously. * This is important for our usage of it, as we wish to support this library without resorting to * browser-only or node-only APIs. * * We could use `create...
} /** * Checks whether _user_ (a string identifier similar to those encoded) is allowed * through the gate, either because: * * - they're on the list * - they're part of the first _sample_ users * * Sampling is done by hashing the user string and projecting it onto a sample space * (more on...
options = options || {};
random_line_split
index.js
const BloomFilter = require('@mixmaxhq/bloom-filter'); /** * `sha.js` is an isomorphic hashing library that implements its hashing functions synchronously. * This is important for our usage of it, as we wish to support this library without resorting to * browser-only or node-only APIs. * * We could use `create...
{ // eslint-disable-next-line no-unused-vars constructor(encodedGate, options) { encodedGate = encodedGate || {}; if (encodedGate.list) { encodedGate.list.vData = new Buffer(encodedGate.list.vData.data); this._list = new BloomFilter(encodedGate.list); } this._sample = encodedGate.sampl...
UserGate
identifier_name
jquery.fitvids.js
/*global jQuery */ /*jshint browser:true */ /*! * FitVids 1.1 * * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfp...
var selectors = [ "iframe[src*='player.vimeo.com']", "iframe[src*='youtube.com']", "iframe[src*='youtube-nocookie.com']", "iframe[src*='kickstarter.com'][src*='video.html']", "object", "embed" ]; if (settings.customSelector) { selectors.push(set...
if ( options ) { $.extend( settings, options ); } return this.each(function(){
random_line_split
jquery.fitvids.js
/*global jQuery */ /*jshint browser:true */ /*! * FitVids 1.1 * * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfp...
var $allVideos = $(this).find(selectors.join(',')); $allVideos = $allVideos.not("object object"); // SwfObj conflict patch $allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video. $allVideos.each(function(){ var $this = $(this); if($this.parents(ignoreList).l...
{ ignoreList = ignoreList + ', ' + settings.ignore; }
conditional_block
BasicSprite.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
(self): self.image = pygame.image.load(self.imagepath) self.original = self.image self.image = self.original self.rect = self.image.get_rect() self.rect.center = self.pos center = list(self.rect.center) current = self.image pos = center dx,dy = 0,...
main
identifier_name
BasicSprite.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
if event == "start_right": dx = dx + d if event == "stop_right": dx = dx - d if event == "start_left": dx = dx - d if event == "stop_left": dx = dx + d if dx !=0 or dy != 0: self.pos[0] += dx if self.pos[0] >s...
if event == "stop_up": dy = dy - d if event == "start_down": dy = dy - d if event == "stop_down": dy = dy + d
random_line_split
BasicSprite.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
if dx !=0 or dy != 0: self.pos[0] += dx if self.pos[0] >self.screensize[0]-self.border: self.pos[0] =self.screensize[0]-self.border if self.pos[1] >self.screensize[1]-self.border: self.pos[1] =self.screensize[1]-self.border if self.pos[0] <...
dx = dx + d
conditional_block
BasicSprite.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
def main(self): self.image = pygame.image.load(self.imagepath) self.original = self.image self.image = self.original self.rect = self.image.get_rect() self.rect.center = self.pos center = list(self.rect.center) current = self.image pos = center ...
while 1: yield 1
identifier_body
twitter.js
var exports = exports || this; exports.Twitter = (function(global) { var K = function(){}, isAndroid = Ti.Platform.osname === "android", jsOAuth = require('/ui/common/jsOAuth-1.3.1'); /** * Twitter constructor function * * var client = Twitter({ * consumerKey: "INSERT YOUR KEY HERE", * ...
title: "Back" }); this.webView = webView; webViewWindow.leftNavButton = closeButton; actInd.show(); loadingOverlay.add(actInd); webViewWindow.add(loadingOverlay); webViewWindow.open({modal: true}); webViewWindow.add(webView); closeButton.addEventListene...
{ var self = this, oauth = this.oauthClient, webViewWindow = Ti.UI.createWindow({title: this.windowTitle}), webView = Ti.UI.createWebView(), loadingOverlay = Ti.UI.createView({ backgroundColor: 'black', opacity: 0.7, zIndex: 1 }), actInd ...
identifier_body
twitter.js
var exports = exports || this; exports.Twitter = (function(global) { var K = function(){}, isAndroid = Ti.Platform.osname === "android", jsOAuth = require('/ui/common/jsOAuth-1.3.1'); /** * Twitter constructor function * * var client = Twitter({ * consumerKey: "INSERT YOUR KEY HERE", * ...
() { var self = this, oauth = this.oauthClient, webViewWindow = Ti.UI.createWindow({title: this.windowTitle}), webView = Ti.UI.createWebView(), loadingOverlay = Ti.UI.createView({ backgroundColor: 'black', opacity: 0.7, zIndex: 1 }), actI...
createAuthWindow
identifier_name
twitter.js
var exports = exports || this; exports.Twitter = (function(global) { var K = function(){}, isAndroid = Ti.Platform.osname === "android", jsOAuth = require('/ui/common/jsOAuth-1.3.1'); /** * Twitter constructor function * * var client = Twitter({ * consumerKey: "INSERT YOUR KEY HERE", * ...
if (!options) { options = {}; } self.windowTitle = options.windowTitle || "Twitter Authorization"; self.consumerKey = options.consumerKey; self.consumerSecret = options.consumerSecret; self.authorizeUrl = "https://api.twitter.com/oauth/authorize"; self.accessTokenKey = options.accessTokenK...
{ self = new K(); }
conditional_block
twitter.js
var exports = exports || this; exports.Twitter = (function(global) { var K = function(){}, isAndroid = Ti.Platform.osname === "android", jsOAuth = require('/ui/common/jsOAuth-1.3.1'); /** * Twitter constructor function * * var client = Twitter({ * consumerKey: "INSERT YOUR KEY HERE", * ...
} /* * Requests the user to authorize via Twitter through a modal WebView. */ Twitter.prototype.authorize = function() { var self = this; if (this.authorized) { // TODO: verify access tokens are still valid? // We're putting this fireEvent call inside setTimeout to al...
}); }); } } });
random_line_split
controlgroup-f525e8d53867db2d7a4e30c79b5d800b.js
function _superApply( args ) { return base.prototype[ prop ].apply( this, args ); } return function() { var __super = this._super; var __superApply = this._superApply; var returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, argume...
{ return base.prototype[ prop ].apply( this, arguments ); }
identifier_body
controlgroup-f525e8d53867db2d7a4e30c79b5d800b.js
that._removeClass( value, key ); } ); // We can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .off( this.eventNamespace ) .removeData( this.widgetFullName ); this.widget() .off( this.eventNamespace ) .removeAttr( "aria-disabled" ); /...
_delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler )
random_line_split
controlgroup-f525e8d53867db2d7a4e30c79b5d800b.js
destroy(); $.each( this.classesElementLookup, function( key, value ) { that._removeClass( value, key ); } ); // We can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .off( this.eventNamespace ) .removeData( this.widgetFullName ); this.widget...
handlerProxy
identifier_name
controlgroup-f525e8d53867db2d7a4e30c79b5d800b.js
Key ] || !currentElements || !currentElements.length ) { continue; } // We are doing this to create a new jQuery object because the _removeClass() call // on the next line is going to destroy the reference to the current elements being // tracked. We need to save a copy of this collection so ...
{ element.delay( options.delay ); }
conditional_block
index.js
/* * Test Cases for the Troll Library */ describe('Troll', function() { var troll = require('../'); troll.addStrategies([ troll.PREMADESTRATEGIES.PASSPORT ]); var req = { user: { }, session: { } }; var res = { redirect:function() { thr...
done(); return; } throw e; } throw "Did not throw error"; }); }); describe('#userHasPermission', function() { it('should return an error message', function(done) { var e = troll.userHasPermissi...
troll.shallNotPass('view')(req,res,done); } catch(e) { if (e == "redirected") {
random_line_split
index.js
/* * Test Cases for the Troll Library */ describe('Troll', function() { var troll = require('../'); troll.addStrategies([ troll.PREMADESTRATEGIES.PASSPORT ]); var req = { user: { }, session: { } }; var res = { redirect:function() { thr...
throw e; } throw "Did not throw error"; }); }); describe('#userHasPermission', function() { it('should return an error message', function(done) { var e = troll.userHasPermission(req, 'view', function(error, isAbleToLogin) { if (is...
{ done(); return; }
conditional_block
packet.py
p_decode(data): "always return a list" d = rlp.decode(data) if isinstance(d, str): d = [d] return d def load_packet(packet): return Packeter.load_packet(packet) class Packeter(object): """ Translates between the network and the local data https://github.com/ethereum/wiki/wik...
def dump_Hello(self): # inconsistency here! # spec says CAPABILITIES, LISTEN_PORT but code reverses """ [0x00, PROTOCOL_VERSION, NETWORK_ID, CLIENT_ID, CAPABILITIES, LISTEN_PORT, NODE_ID] First packet sent over the connection, and sent once by both sides. No...
""" 4-byte synchronisation token, (0x22400891), a 4-byte "payload size", to be interpreted as a big-endian integer an N-byte RLP-serialised data structure """ payload = rlp.encode(recursive_int_to_big_endian(data)) packet = ienc4(cls.SYNCHRONIZATION_TOKEN) packet...
identifier_body
packet.py
_decode(data): "always return a list" d = rlp.decode(data) if isinstance(d, str): d = [d] return d def load_packet(packet): return Packeter.load_packet(packet) class Packeter(object): """ Translates between the network and the local data https://github.com/ethereum/wiki/wiki...
cmd = Packeter.cmd_map.get(idec(payload[0])) remain = packet[8 + payload_len:] return True, (header, payload_len, cmd, payload[1:], remain) def load_cmd(self, packet): success, res = self.load_packet(packet) if not success: raise Exception(res) _, _, cm...
return False, 'check cmd failed'
conditional_block
packet.py
_decode(data): "always return a list" d = rlp.decode(data) if isinstance(d, str): d = [d] return d def load_packet(packet): return Packeter.load_packet(packet) class Packeter(object): """ Translates between the network and the local data https://github.com/ethereum/wiki/wiki...
(self, parent_hashes=[], count=1): """ [0x14, Parent1, Parent2, ..., ParentN, Count] Request the peer to send Count (to be interpreted as an integer) blocks in the current canonical block chain that are children of Parent1 (to be interpreted as a SHA3 block hash). If Parent1 is n...
dump_GetChain
identifier_name
packet.py
import sys import signals logger = logging.getLogger(__name__) def lrlp_decode(data): "always return a list" d = rlp.decode(data) if isinstance(d, str): d = [d] return d def load_packet(packet): return Packeter.load_packet(packet) class Packeter(object): """ Translates betwee...
random_line_split
__init__.py
#!/usr/bin/env python
# or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You ma...
# Licensed to the Apache Software Foundation (ASF) under one
random_line_split
warnings.py
(filename, lineno) if line is None else line if line: line = line.strip() if isinstance(s, unicodetype) and isinstance(line, str): line = unicode(line, 'latin1') s += " %s\n" % line if isinstance(s, unicodetype) and isinstance(filename, str): enc = sys.getfilesysteme...
if not issubclass(cat, Warning): raise _OptionError("invalid warning category: %r" % (category,)) return cat # Code typically replaced by _warnings def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a ...
import re if not category: return Warning if re.match("^[a-zA-Z0-9_]+$", category): try: cat = eval(category) except NameError: raise _OptionError("unknown warning category: %r" % (category,)) else: i = category.rfind(".") module = category[:i]...
identifier_body
warnings.py
line = line.strip() if isinstance(s, unicodetype) and isinstance(line, str): line = unicode(line, 'latin1') s += " %s\n" % line if isinstance(s, unicodetype) and isinstance(filename, str): enc = sys.getfilesystemencoding() if enc: try: ...
"line")
random_line_split
warnings.py
action in ("error", "ignore", "always", "default", "module", "once"), "invalid action: %r" % (action,) assert isinstance(lineno, int) and lineno >= 0, \ "lineno must be an int >= 0" item = (action, None, category, None, lineno) if append: filters.append(item) el...
__exit__
identifier_name
warnings.py
, unicodetype) and isinstance(filename, str): enc = sys.getfilesystemencoding() if enc: try: filename = unicode(filename, enc) except UnicodeDecodeError: pass s = "%s:%s" % (filename, s) return s def filterwarnings(action, message="", cate...
setattr(self, attr, local_values[attr])
conditional_block
returnck.rs
use dora_parser::ast::*; use dora_parser::lexer::position::Position; pub fn returns_value(s: &Stmt) -> Result<(), Position> { match *s { Stmt::Return(_) => Ok(()), Stmt::For(ref stmt) => Err(stmt.pos), Stmt::While(ref stmt) => Err(stmt.pos), Stmt::Break(ref stmt) => Err(stmt.pos), ...
(e: &ExprBlockType) -> Result<(), Position> { let mut pos = e.pos; for stmt in &e.stmts { match returns_value(stmt) { Ok(_) => return Ok(()), Err(err_pos) => pos = err_pos, } } if let Some(ref expr) = e.expr { expr_returns_value(expr) } else { ...
expr_block_returns_value
identifier_name
returnck.rs
use dora_parser::ast::*; use dora_parser::lexer::position::Position; pub fn returns_value(s: &Stmt) -> Result<(), Position> { match *s { Stmt::Return(_) => Ok(()), Stmt::For(ref stmt) => Err(stmt.pos), Stmt::While(ref stmt) => Err(stmt.pos), Stmt::Break(ref stmt) => Err(stmt.pos), ...
"fun f(): Int32 { }", pos(1, 16), SemError::ReturnType("Int32".into(), "()".into()), ); err( "fun f(): Int32 { if true { return 1; } }", pos(1, 16), SemError::ReturnType("Int32".into(), "()".into()), ); err( ...
fn returns_int() { err(
random_line_split
returnck.rs
use dora_parser::ast::*; use dora_parser::lexer::position::Position; pub fn returns_value(s: &Stmt) -> Result<(), Position> { match *s { Stmt::Return(_) => Ok(()), Stmt::For(ref stmt) => Err(stmt.pos), Stmt::While(ref stmt) => Err(stmt.pos), Stmt::Break(ref stmt) => Err(stmt.pos), ...
fn expr_if_returns_value(e: &ExprIfType) -> Result<(), Position> { expr_returns_value(&e.then_block)?; match e.else_block { Some(ref block) => expr_returns_value(block), None => Err(e.pos), } } #[cfg(test)] mod tests { use crate::language::error::msg::SemError; use crate::languag...
{ let mut pos = e.pos; for stmt in &e.stmts { match returns_value(stmt) { Ok(_) => return Ok(()), Err(err_pos) => pos = err_pos, } } if let Some(ref expr) = e.expr { expr_returns_value(expr) } else { Err(pos) } }
identifier_body
common.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.website_event.tests.common import TestEventOnlineCommon class TestEventExhibitorCommon(TestEventOnlineCommon):
'hour_from': 8.0, 'hour_to': 18.0, })
@classmethod def setUpClass(cls): super(TestEventExhibitorCommon, cls).setUpClass() # Sponsorship data cls.sponsor_type_0 = cls.env['event.sponsor.type'].create({ 'name': 'GigaTop', 'sequence': 1, }) cls.sponsor_0_partner = cls.env['res.partner'].crea...
identifier_body
common.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.website_event.tests.common import TestEventOnlineCommon class
(TestEventOnlineCommon): @classmethod def setUpClass(cls): super(TestEventExhibitorCommon, cls).setUpClass() # Sponsorship data cls.sponsor_type_0 = cls.env['event.sponsor.type'].create({ 'name': 'GigaTop', 'sequence': 1, }) cls.sponsor_0_partner...
TestEventExhibitorCommon
identifier_name
common.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.website_event.tests.common import TestEventOnlineCommon class TestEventExhibitorCommon(TestEventOnlineCommon): @classmethod def setUpClass(cls): super(TestEventExhibitorCommon, cls).se...
'hour_to': 18.0, })
random_line_split
nrf_matter_device_test.py
# Copyright 2022 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, ...
(self): """Test reboot method with invalid method.""" with self.assertRaisesRegex( errors.DeviceError, r"ValueError: Method invalid_reboot_method not recognized"): self.uut.reboot(method="invalid_reboot_method") if __name__ == "__main__": fake_device_test_case.main()
test_device_reboot_raise_error
identifier_name
nrf_matter_device_test.py
# Copyright 2022 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, ...
self.uut.reboot(method="hard") reboot_fn.assert_called_once() @parameterized.parameters(dict(method="soft"), dict(method="pw_rpc")) @mock.patch.object( pwrpc_common_default.PwRPCCommonDefault, "reboot", autospec=True) def test_device_reboot(self, reboot_fn, method): self.uut.reboot(method) ...
@mock.patch.object( device_power_default.DevicePowerDefault, "cycle", autospec=True) def test_device_reboot_hard(self, reboot_fn):
random_line_split
nrf_matter_device_test.py
# Copyright 2022 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, ...
fake_device_test_case.main()
conditional_block
nrf_matter_device_test.py
# Copyright 2022 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, ...
def test_flash_build_capability(self): """Verifies the initialization of flash_build capability.""" self.assertTrue(self.uut.flash_build) def test_matter_endpoints_capability(self): """Verifies the initialization of matter_endpoints capability.""" self.assertIsNotNone(self.uut.matter_endpoints) ...
"""Verifies persistent properties are set correctly.""" mock_rpc_common.vendor_id = _FAKE_VENDOR_ID mock_rpc_common.product_id = _FAKE_PRODUCT_ID self._test_get_detection_info( console_port_name=_FAKE_DEVICE_ADDRESS, device_class=NrfMatterDeviceStub, persistent_properties=_NRF_CONNEC...
identifier_body
orange_fpgrowth.py
consequents def setSupport(self, supports) : self.support = supports def setConf(self, confidence) : self.conf = confidence def getValue(self) : return(self.value) def getConsequent(self) : return(self.consequent) def getSupport(self) : return(self.support) def getS...
e() for rule in rules] attribute_values = list(chain.from_iterable(attribute_values)) attribute_values = list(set(attribute_values)) combi_attribute_values = combinations(attribute_values,p) count = 0 bunbo = 0 for combi in combi_attribute_values : bunbo += 1 rules_target = [] ...
alues = [rule.getValu
identifier_name
orange_fpgrowth.py
= consequents def setSupport(self, supports) : self.support = supports def setConf(self, confidence) : self.conf = confidence def getValue(self) : return(self.value) def getConsequent(self) : return(self.consequent) def getSupport(self) : return(self.support) def ge...
#print(rules) names = {item: '{}={}'.format(var.name, val) for item, var, val in OneHot.decode(mapping, data_table, mapping)} for ante, cons, supp, conf in rules: print(', '.join(names[i] for i in ante), '-->', names[next(iter(cons))], '(supp: {}, conf: {})'.format(supp, conf)) # induce rules...
ain'+str(iter1)+'-'+str(iter2)+'.basket' data_table = Orange.data.Table(filepath) #print len(data_table) # set parameter num_lines = sum(1 for line in open(filepath)) minsup = float(minsup) / float(num_lines) # #itemsets = frequent_itemsets(data_table, minsup) #print(itemsets) #p...
identifier_body
orange_fpgrowth.py
= consequents def setSupport(self, supports) : self.support = supports def setConf(self, confidence) : self.conf = confidence def getValue(self) : return(self.value) def getConsequent(self) : return(self.consequent) def getSupport(self) : return(self.support) def ge...
rules_target) == 0: bunbo -= 1 # else : consequents = [rule.getConsequent() for rule in rules_target] if len(list(set(consequents))) == 1: count += 1 if bunbo == 0: ans = 0 else: ans = (float(count) / float(bunbo)) return(an...
tValue()))) if matching_count == len(list(combi)) : rules_target.append(rule) # rules_target が空なら評価から外す if len(
conditional_block
orange_fpgrowth.py
= consequents def setSupport(self, supports) : self.support = supports def setConf(self, confidence) : self.conf = confidence def getValue(self) : return(self.value) def getConsequent(self) : return(self.consequent) def getSupport(self) : return(self.support) def ge...
# rule = Rule() # rule.setValue(rule_orange.left.get_metas(str).keys()) # rule.setConsequent(consequent[0]) # rule.setSupport(rule_orange.support) # rule.setConf(rule_orange.confidence) # rules.append(rule) # END #return(rules) # ===============...
# if len(consequent) == 1 and consequent[0] in classes and rule_orange.confidence >= minconf :
random_line_split
main.py
from tkinter import * from PIL import Image, ImageTk from mandelbrot import * from julia_set import * class App(object): def __init__(self, master): # CANVAS self.ulx, self.uly, self.drx, self.dry, self.def_width = default_settings()[ :5] self.image = ImageTk.PhotoImage(make_f...
self.sx, self.sy = event.x, event.y def release(self, event): self.ex, self.ey = event.x, event.y if self.ex == self.sx or self.ey == self.sy: return self.sx, self.ex = sorted([self.ex, self.sx]) self.sy, self.ey = sorted([self.ey, self.sy]) sysw = self...
self.iterslider.grid(row=1, column=1) self.iterslider.bind('<ButtonRelease-1>', self.update_image) def press(self, event):
random_line_split
main.py
from tkinter import * from PIL import Image, ImageTk from mandelbrot import * from julia_set import * class App(object): def __init__(self, master): # CANVAS self.ulx, self.uly, self.drx, self.dry, self.def_width = default_settings()[ :5] self.image = ImageTk.PhotoImage(make_f...
(self, event): self.sx, self.sy = event.x, event.y def release(self, event): self.ex, self.ey = event.x, event.y if self.ex == self.sx or self.ey == self.sy: return self.sx, self.ex = sorted([self.ex, self.sx]) self.sy, self.ey = sorted([self.ey, self.sy]) ...
press
identifier_name