file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
App.js | 'use strict';
import React,{ Component } from 'react';
import { StyleSheet, AppState, Dimensions, Image } from 'react-native';
import CodePush from 'react-native-code-push';
import { Container, Text, View, InputGroup, Input, Icon } from 'native-base';
import Modal from 'react-native-modalbox';
import AppNavigator fr... | () {
if(this.state.showDownloadingModal)
return (
<View style={{backgroundColor: theme.brandSecondary}}>
<InputGroup
borderType='rounded'
>
<Icon name='ios-person-outline' />
... | render | identifier_name |
App.js | 'use strict';
import React,{ Component } from 'react';
import { StyleSheet, AppState, Dimensions, Image } from 'react-native';
import CodePush from 'react-native-code-push';
import { Container, Text, View, InputGroup, Input, Icon } from 'native-base';
import Modal from 'react-native-modalbox';
import AppNavigator fr... |
}
export default App
| {
if(this.state.showDownloadingModal)
return (
<View style={{backgroundColor: theme.brandSecondary}}>
<InputGroup
borderType='rounded'
>
<Icon name='ios-person-outline' />
... | identifier_body |
timer.rs | //! Timing and measurement functions.
//!
//! ggez does not try to do any framerate limitation by default. If
//! you want to run at anything other than full-bore max speed all the
//! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)
//! (or [`timer::yield_now()`](fn.yield_now.... |
}
/// A convenience function to convert a Rust `Duration` type
/// to a (less precise but more useful) `f64`.
///
/// Does not make sure that the `Duration` is within the bounds
/// of the `f64`.
pub fn duration_to_f64(d: time::Duration) -> f64 {
let seconds = d.as_secs() as f64;
let nanos = f64::from(d.subse... | {
sum / u32::try_from(tc.frame_durations.samples).unwrap()
} | conditional_block |
timer.rs | //! Timing and measurement functions.
//!
//! ggez does not try to do any framerate limitation by default. If
//! you want to run at anything other than full-bore max speed all the
//! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)
//! (or [`timer::yield_now()`](fn.yield_now.... | frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt),
residual_update_dt: time::Duration::from_secs(0),
frame_count: 0,
}
}
/// Update the state of the `TimeContext` to record that
/// another frame has taken place. Necessary for the FPS
/// tracking... | let initial_dt = time::Duration::from_millis(16);
TimeContext {
init_instant: time::Instant::now(),
last_instant: time::Instant::now(), | random_line_split |
timer.rs | //! Timing and measurement functions.
//!
//! ggez does not try to do any framerate limitation by default. If
//! you want to run at anything other than full-bore max speed all the
//! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)
//! (or [`timer::yield_now()`](fn.yield_now.... | () -> TimeContext {
let initial_dt = time::Duration::from_millis(16);
TimeContext {
init_instant: time::Instant::now(),
last_instant: time::Instant::now(),
frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt),
residual_update_dt: time::Duration::fr... | new | identifier_name |
volumetric_data.py | """Module for reading volumetric data from VASP calculations.
Charge density and dipole moment
Local potential
Electron localization function
"""
import os
import numpy as np
from ase.calculators.vasp import Vasp, VaspChargeDensity
from POTCAR import get_ZVAL
def get_volumetric_data(self, filename='CHG', **kwargs):
... | n0, n1, n2 = data[0].shape
s0 = np.linspace(0, 1, num=n0, endpoint=False)
s1 = np.linspace(0, 1, num=n1, endpoint=False)
s2 = np.linspace(0, 1, num=n2, endpoint=False)
X, Y, Z = np.meshgrid(s0, s1, s2)
C = np.column_stack([X.ravel(),
Y.ravel(),
... | atoms = self.get_atoms()
vd = VaspChargeDensity(filename)
data = np.array(vd.chg) | random_line_split |
volumetric_data.py | """Module for reading volumetric data from VASP calculations.
Charge density and dipole moment
Local potential
Electron localization function
"""
import os
import numpy as np
from ase.calculators.vasp import Vasp, VaspChargeDensity
from POTCAR import get_ZVAL
def get_volumetric_data(self, filename='CHG', **kwargs):
... | (self, spin=0, scaled=True):
"""Returns center of electron density.
If scaled, use scaled coordinates, otherwise use cartesian
coordinates.
"""
atoms = self.get_atoms()
x, y, z, cd = self.get_charge_density(spin)
n0, n1, n2 = cd.shape
nelements = n0 * n1 * n2
voxel_volume = atoms... | get_electron_density_center | identifier_name |
volumetric_data.py | """Module for reading volumetric data from VASP calculations.
Charge density and dipole moment
Local potential
Electron localization function
"""
import os
import numpy as np
from ase.calculators.vasp import Vasp, VaspChargeDensity
from POTCAR import get_ZVAL
def get_volumetric_data(self, filename='CHG', **kwargs):
... |
Vasp.get_charge_density = get_charge_density
def get_local_potential(self):
"""Returns x, y, z, and local potential arrays
is there a spin for this?
We multiply the data by the volume because we are reusing the
charge density code which divides by volume.
"""
x, y, z, data = get_volumetri... | """Returns x, y, and z coordinate and charge density arrays.
Supported file formats: CHG, CHGCAR
:param int spin: an integer
:returns: x, y, z, charge density arrays
:rtype: 3-d numpy arrays
Relies on :func:`ase.calculators.vasp.VaspChargeDensity`.
"""
x, y, z, data = get_volumetric_data... | identifier_body |
volumetric_data.py | """Module for reading volumetric data from VASP calculations.
Charge density and dipole moment
Local potential
Electron localization function
"""
import os
import numpy as np
from ase.calculators.vasp import Vasp, VaspChargeDensity
from POTCAR import get_ZVAL
def get_volumetric_data(self, filename='CHG', **kwargs):
... |
def get_dipole_moment(self, atoms=None):
"""Tries to return the dipole vector of the unit cell in atomic units.
Returns None when CHG file is empty/not-present.
To get the dipole moment, use this formula:
dipole_moment = ((dipole_vector**2).sum())**0.5/Debye
"""
if atoms is None:
... | return electron_density_center | conditional_block |
reference.rs | use crate::real_std::{any::Any, fmt, marker::PhantomData, sync::Mutex};
use crate::{
api::{generic::A, Generic, Unrooted, Userdata, WithVM, IO},
gc::{CloneUnrooted, GcPtr, GcRef, Move, Trace},
thread::ThreadInternal,
value::{Cloner, Value},
vm::Thread,
ExternModule, Result,
};
#[derive(VmType)... | pub mod reference {
pub use crate::reference as prim;
}
}
pub fn load(vm: &Thread) -> Result<ExternModule> {
let _ = vm.register_type::<Reference<A>>("std.reference.Reference", &["a"]);
ExternModule::new(
vm,
record! {
type Reference a => Reference<A>,
(s... | mod std { | random_line_split |
reference.rs | use crate::real_std::{any::Any, fmt, marker::PhantomData, sync::Mutex};
use crate::{
api::{generic::A, Generic, Unrooted, Userdata, WithVM, IO},
gc::{CloneUnrooted, GcPtr, GcRef, Move, Trace},
thread::ThreadInternal,
value::{Cloner, Value},
vm::Thread,
ExternModule, Result,
};
#[derive(VmType)... | (a: WithVM<Generic<A>>) -> IO<Reference<A>> {
// SAFETY The returned, unrooted value gets pushed immediately to the stack
unsafe {
IO::Value(Reference {
value: Mutex::new(a.value.get_value().clone_unrooted()),
thread: GcPtr::from_raw(a.vm),
_marker: PhantomData,
... | make_ref | identifier_name |
plugins.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | filename: "_specRunner.html",
template: path.join(configOptions.railsRoot, "spec", "webpack", "_specRunner.html.ejs"),
jasmineJsFiles: _.map(jasmineFiles.jsFiles.concat(jasmineFiles.bootFiles), (file) => {
return `__jasmine/${file}`;
}),
jasmineCssFiles: _.map(jasmineFiles.cssFiles... | inject: true,
xhtml: true, | random_line_split |
plugins.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
}
plugins.push(new HtmlWebpackPlugin(jasmineIndexPage));
plugins.push(new JasmineAssetsPlugin());
// in Windows Server Core containers, this causes webpack to hang indefinitely.
// it's not critical for builds anyway, just a nice dev utility.
if (process.platform !== "win32") {
plugins.... | {
compiler.hooks.emit.tapAsync("JasmineAssetsPlugin",
(compilation: webpack.compilation.Compilation, callback: () => any) => {
const allJasmineAssets = jasmineFiles.jsFiles.concat(jasmineFiles.bootFiles)
... | identifier_body |
plugins.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
}
return plugins;
}
| {
plugins.push(new WebpackBuildNotifierPlugin({
suppressSuccess: true,
suppressWarning: true
})
);
} | conditional_block |
plugins.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | (configOptions: ConfigOptions): webpack.Plugin[] {
const plugins = [
new ESLintPlugin({
extensions: ["js", "msx"],
exclude: ["node_modules", "webpack/gen"],
failOnWarning: true,
threads: true
}),
new CleanWebpackPlugin(),
new UnusedWebpackPlugin({
... | plugins | identifier_name |
test_transport.py | import unittest
from node.openbazaar_daemon import OpenBazaarContext
import mock
from node import transport
def get_mock_open_bazaar_context():
return OpenBazaarContext.create_default_instance()
class TestTransportLayerCallbacks(unittest.TestCase):
"""Test the callback features of the TransportLayer class.... | self.transport_layer = transport.TransportLayer(ob_ctx, guid, nickname)
self.transport_layer.add_callback('section_one', {'cb': self.callback1, 'validator_cb': self.validator1})
self.transport_layer.add_callback('section_one', {'cb': self.callback2, 'validator_cb': self.validator2})
self... | ob_ctx.nat_status = {'nat_type': 'Restric NAT'}
guid = 1
nickname = None
| random_line_split |
test_transport.py | import unittest
from node.openbazaar_daemon import OpenBazaarContext
import mock
from node import transport
def get_mock_open_bazaar_context():
|
class TestTransportLayerCallbacks(unittest.TestCase):
"""Test the callback features of the TransportLayer class."""
def setUp(self):
# For testing sections
self.callback1 = mock.Mock()
self.callback2 = mock.Mock()
self.callback3 = mock.Mock()
self.validator1 = mock.Mo... | return OpenBazaarContext.create_default_instance() | identifier_body |
test_transport.py | import unittest
from node.openbazaar_daemon import OpenBazaarContext
import mock
from node import transport
def get_mock_open_bazaar_context():
return OpenBazaarContext.create_default_instance()
class TestTransportLayerCallbacks(unittest.TestCase):
"""Test the callback features of the TransportLayer class.... | (self):
# For testing sections
self.callback1 = mock.Mock()
self.callback2 = mock.Mock()
self.callback3 = mock.Mock()
self.validator1 = mock.Mock()
self.validator2 = mock.Mock()
self.validator3 = mock.Mock()
ob_ctx = get_mock_open_bazaar_context()
... | setUp | identifier_name |
test_transport.py | import unittest
from node.openbazaar_daemon import OpenBazaarContext
import mock
from node import transport
def get_mock_open_bazaar_context():
return OpenBazaarContext.create_default_instance()
class TestTransportLayerCallbacks(unittest.TestCase):
"""Test the callback features of the TransportLayer class.... | unittest.main() | conditional_block | |
also-watched.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AlsoWatchedComponent } from './also-watched.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { Response, ResponseOptions, Http, ConnectionBackend, BaseRe... | import { SearchPageComponent } from '../search-page/search-page.component';
import { FilmsService } from '../films.service';
describe('AlsoWatchedComponent', () => {
let component: AlsoWatchedComponent;
let fixture: ComponentFixture<AlsoWatchedComponent>;
beforeEach(async(() => {
TestBed.configureTestingMo... | import { MyLibraryComponent } from '../my-library/my-library.component'; | random_line_split |
translator.js | 'use strict';
var messages = {
chinese : {
"Device not initialized or passphrase request cancelled" : "设备未初始化或已取消输入密码",
"Invalid signature" : "无效的签名",
"Not enough funds" : "资金不足",
"PIN Cancelled" : "PIN码输入已取消",
"Invalid PIN" : "PIN码错误",
"PIN removal cancelled" : "PIN码删除已取消",
"Ping cancelled" :... |
module.exports = translator; | return key;
}
};
| random_line_split |
translator.js | 'use strict';
var messages = {
chinese : {
"Device not initialized or passphrase request cancelled" : "设备未初始化或已取消输入密码",
"Invalid signature" : "无效的签名",
"Not enough funds" : "资金不足",
"PIN Cancelled" : "PIN码输入已取消",
"Invalid PIN" : "PIN码错误",
"PIN removal cancelled" : "PIN码删除已取消",
"Ping cancelled" :... | conditional_block | ||
eval_kanungo_est.py | import env
import numpy as np
import metaomr
import metaomr.kanungo as kan
from metaomr.page import Page
import glob
import pandas as pd
import itertools
import os.path
import sys
from datetime import datetime
from random import random, randint
IDEAL = [path for path in sorted(glob.glob('testset/modern/*.png'))
... |
columns = pd.MultiIndex.from_product([['real', 'estimate'], 'nu a0 a b0 b k'.split()])
columns = columns.append(pd.MultiIndex.from_product([['estimate'],['stat','time','status','nfev']]))
cols = []
results = []
fun = 'ks'
method = 'Nelder-Mead'
for image in IDEAL:
name = os.path.basename(image).split('.')[0]
... | if random() < 0.25:
nu = 0
else:
nu = random() * 0.05
if random() < 0.25:
a0 = a = 0
else:
a0 = random() * 0.2
a = 0.5 + random() * 2
if random() < 0.25:
b0 = b = 0
else:
b0 = random() * 0.2
b = 0.5 + random() * 2
k = randint(0, 4)
... | identifier_body |
eval_kanungo_est.py | import env
import numpy as np
import metaomr
import metaomr.kanungo as kan
from metaomr.page import Page
import glob
import pandas as pd
import itertools
import os.path
import sys
from datetime import datetime
from random import random, randint
IDEAL = [path for path in sorted(glob.glob('testset/modern/*.png'))
... |
else:
nu = random() * 0.05
if random() < 0.25:
a0 = a = 0
else:
a0 = random() * 0.2
a = 0.5 + random() * 2
if random() < 0.25:
b0 = b = 0
else:
b0 = random() * 0.2
b = 0.5 + random() * 2
k = randint(0, 4)
return nu, a0, a, b0, b, k
co... | nu = 0 | conditional_block |
eval_kanungo_est.py | import env
import numpy as np
import metaomr
import metaomr.kanungo as kan
from metaomr.page import Page
import glob
import pandas as pd
import itertools
import os.path
import sys
from datetime import datetime
from random import random, randint
IDEAL = [path for path in sorted(glob.glob('testset/modern/*.png'))
... | ():
if random() < 0.25:
nu = 0
else:
nu = random() * 0.05
if random() < 0.25:
a0 = a = 0
else:
a0 = random() * 0.2
a = 0.5 + random() * 2
if random() < 0.25:
b0 = b = 0
else:
b0 = random() * 0.2
b = 0.5 + random() * 2
k = randin... | random_params | identifier_name |
eval_kanungo_est.py | import env
import numpy as np
import metaomr
import metaomr.kanungo as kan
from metaomr.page import Page
import glob
import pandas as pd
import itertools
import os.path
import sys
from datetime import datetime
from random import random, randint
IDEAL = [path for path in sorted(glob.glob('testset/modern/*.png'))
... | res.index = pd.MultiIndex.from_tuples(cols)
res.index.names = 'doc test maxfev num'.split()
res.to_csv('kanungo_eval.csv')
sys.stderr.write('\n') | res = pd.DataFrame(results, columns=columns) | random_line_split |
SimpleSidebarListItemHeader.tsx | import { ReactNode, useRef } from 'react';
import { noop } from '@proton/shared/lib/helpers/function';
import Icon from '../icon/Icon';
import { classnames } from '../../helpers';
import SidebarListItem from './SidebarListItem';
import { HotkeyTuple, useHotkeys } from '../../hooks';
interface Props {
toggle: boole... | <SidebarListItem className="navigation-link-header-group">
<div className="flex flex-nowrap">
<button
ref={buttonRef}
className="text-uppercase flex-item-fluid text-left navigation-link-header-group-link"
type="button"
... | return ( | random_line_split |
remove.rs | use cli::parse_args;
use Slate;
use message::Message;
use results::CommandResult;
use errors::CommandError;
const USAGE: &'static str = "
Slate: Remove an element.
Usage:
slate remove ([options] | <key>)
Options:
-h --help Show this screen.
-a --all Remove all keys.
Examples:
slate remove --all
#=> A... | (slate: &Slate, argv: &Vec<String>) -> CommandResult {
let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit());
if args.flag_all {
try!(slate.clear());
Ok(Some(Message::Info("All keys have been removed".to_string())))
} else {
let key: String = match args.arg_key {
... | run | identifier_name |
remove.rs | use cli::parse_args;
use Slate;
use message::Message;
use results::CommandResult;
use errors::CommandError;
const USAGE: &'static str = "
Slate: Remove an element.
Usage:
slate remove ([options] | <key>)
Options:
-h --help Show this screen.
-a --all Remove all keys.
Examples:
slate remove --all
#=> A... | {
let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit());
if args.flag_all {
try!(slate.clear());
Ok(Some(Message::Info("All keys have been removed".to_string())))
} else {
let key: String = match args.arg_key {
Some(string) => string,
None => ... | identifier_body | |
remove.rs | use cli::parse_args;
use Slate;
use message::Message;
use results::CommandResult;
use errors::CommandError;
const USAGE: &'static str = "
Slate: Remove an element.
Usage:
slate remove ([options] | <key>)
Options:
-h --help Show this screen.
-a --all Remove all keys.
Examples: |
slate remove foo
#=> The key has been removed
";
#[derive(Debug, Deserialize)]
struct Args {
arg_key: Option<String>,
flag_all: bool,
}
pub fn run(slate: &Slate, argv: &Vec<String>) -> CommandResult {
let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit());
if args.flag_all {
... | slate remove --all
#=> All keys have been removed | random_line_split |
majority_voting_test.py | #to get some base functionality for free, including the methods get_params and set_params
#to set and return the classifier's parameters as well as the score method to calculate the
#prediction accuracy,respectively
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.preprocess... | plt.ylabel('True Positive Rate')
plt.show()
#tune the inverse regularization parameter C of the logistic regression classifier and the decision tree
#depth via a grid search for demonstration purposes
from sklearn.grid_search import GridSearchCV
params = {'decisiontreeclassifier__max_depth':[1,2],'pipeline-1__clf__C':... | plt.plot([0, 1], [0, 1],linestyle='--',color='gray',linewidth=2)
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.grid()
plt.xlabel('False Positive Rate') | random_line_split |
majority_voting_test.py | #to get some base functionality for free, including the methods get_params and set_params
#to set and return the classifier's parameters as well as the score method to calculate the
#prediction accuracy,respectively
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.preprocess... |
def predict_proba(self, X):
""" Predict class probabilities for X.
Parameters
----------
X : {array-like, sparse matrix},
shape = [n_samples, n_features]
Training vectors, where n_samples is
the number of samples and
n_features is the number of feat... | """ Predict class labels for X.
Parameters
----------
X : {array-like, sparse matrix},
Shape = [n_samples, n_features]
Matrix of training samples
Returns
----------
maj_vote : array-like, shape = [n_samples]
Predicted class labels.
... | identifier_body |
majority_voting_test.py | #to get some base functionality for free, including the methods get_params and set_params
#to set and return the classifier's parameters as well as the score method to calculate the
#prediction accuracy,respectively
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.preprocess... | (self, X, y):
""" Fit classifiers.
Parameters
----------
X : {array-like, sparse matrix},
shape = [n_samples, n_features]
Matrix of training samples.
y : array-like, shape = [n_samples]
Vector of target class labels.
Returns
... | fit | identifier_name |
majority_voting_test.py | #to get some base functionality for free, including the methods get_params and set_params
#to set and return the classifier's parameters as well as the score method to calculate the
#prediction accuracy,respectively
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.preprocess... |
#combine the individual classifiers for majority rule voting in our MajorityVoteClassifier
#import os
#pwd = os.getcwd()
#os.chdir('E:\\machine-learning\\19-Ensemble Learning\\')
#from majority_voting import MajorityVoteClassifier
mv_clf = MajorityVoteClassifier(classifiers=[pipe1, clf2, pipe3])
clf_labels += ['Majo... | scores = cross_val_score(estimator = clf,
X=X_train,
y=y_train,
cv=10,
scoring = 'roc_auc')
print ("ROC AUC: %0.2f (+/- %0.2f) [%s]" % (scores.mean(),scores.std(),label)) | conditional_block |
yarrharr.py | # -*- coding: utf-8 -*-
# Copyright © 2013, 2014, 2017, 2020 Tom Most <twm@freecog.net>
#
# 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) a... | argv=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Yarrharr feed reader")
parser.add_argument("--version", action="version", version=yarrharr.__version__)
parser.parse_args(argv)
os.environ["DJANGO_SETTINGS_MODULE"] = "yarrharr.settings"
from yarrharr.application import run
run(... | ain( | identifier_name |
yarrharr.py | # -*- coding: utf-8 -*-
# Copyright © 2013, 2014, 2017, 2020 Tom Most <twm@freecog.net>
#
# 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) a... | arser = argparse.ArgumentParser(description="Yarrharr feed reader")
parser.add_argument("--version", action="version", version=yarrharr.__version__)
parser.parse_args(argv)
os.environ["DJANGO_SETTINGS_MODULE"] = "yarrharr.settings"
from yarrharr.application import run
run()
| identifier_body | |
yarrharr.py | # -*- coding: utf-8 -*-
# Copyright © 2013, 2014, 2017, 2020 Tom Most <twm@freecog.net>
#
# 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) a... | # the resulting work. Corresponding Source for a non-source form of
# such a combination shall include the source code for the parts of
# OpenSSL used as well as that of the covered work.
from __future__ import absolute_import
import argparse
import os
import sys
import yarrharr
def main(argv=sys.argv[1:]):
p... | random_line_split | |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn to_transform(&self) -> ma... |
}
| {
let transform = self.to_transform();
transformable.transform(&transform);
} | identifier_body |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn | (&self) -> math::Transform {
match *self {
Transform::Translate { value } => {
math::Transform::new(math::Matrix4::translate(value[0], value[1], value[2]))
}
Transform::Scale { value } => {
math::Transform::new(math::Matrix4::scale(value[0], va... | to_transform | identifier_name |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn to_transform(&self) -> ma... |
Transform::RotateX { value } => math::Transform::new(math::Matrix4::rot_x(value)),
Transform::RotateY { value } => math::Transform::new(math::Matrix4::rot_y(value)),
Transform::RotateZ { value } => math::Transform::new(math::Matrix4::rot_z(value)),
}
}
pub fn perfor... | {
math::Transform::new(math::Matrix4::scale(value[0], value[1], value[2]))
} | conditional_block |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn to_transform(&self) -> ma... |
pub fn perform(&self, transformable: &mut dyn Transformable) {
let transform = self.to_transform();
transformable.transform(&transform);
}
} | random_line_split | |
textbox.js | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* th... | (){
try {
if (!fTimer || document.activeElement != _self.$input) {
_self.$input.focus();
}
else {
clearInterval(fTimer);
return;
}
}
catch(e) {}
if... | delay | identifier_name |
textbox.js | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* th... | ;
if ((!e || e.mouse) && apf.isIE) {
clearInterval(fTimer);
fTimer = setInterval(delay, 1);
}
else
delay();
};
this.$blur = function(e){
if (!this.$ext)
return;
if (!this.realtime)
this.change(this.get... | {
try {
if (!fTimer || document.activeElement != _self.$input) {
_self.$input.focus();
}
else {
clearInterval(fTimer);
return;
}
}
catch(e) {}
if (... | identifier_body |
textbox.js | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* th... | // get key pressed
var which = -1;
if (e.which)
which = e.which;
else if (e.keyCode)
which = e.keyCode;
// get shift status
var shift_status = false;
if (e.shiftKey)
shift_status = e.shif... | random_line_split | |
index_object.py | import numpy as np
import pandas.util.testing as tm
from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,
Float64Index)
from .pandas_vb_common import setup # noqa
class SetOperations(object):
goal_time = 0.2
params = (['datetime', 'date_string', 'int', 'strings'],
... | self.idx_dec = RangeIndex(start=10**7, stop=-1, step=-3)
def time_max(self):
self.idx_inc.max()
def time_max_trivial(self):
self.idx_dec.max()
def time_min(self):
self.idx_dec.min()
def time_min_trivial(self):
self.idx_inc.min()
class IndexAppend(object):
... |
goal_time = 0.2
def setup(self):
self.idx_inc = RangeIndex(start=0, stop=10**7, step=3) | random_line_split |
index_object.py | import numpy as np
import pandas.util.testing as tm
from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,
Float64Index)
from .pandas_vb_common import setup # noqa
class SetOperations(object):
goal_time = 0.2
params = (['datetime', 'date_string', 'int', 'strings'],
... |
def time_get_loc(self):
self.ind.get_loc(0)
| N = 100000
a = np.arange(N)
self.ind = Float64Index(a * 4.8000000418824129e-08) | identifier_body |
index_object.py | import numpy as np
import pandas.util.testing as tm
from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,
Float64Index)
from .pandas_vb_common import setup # noqa
class SetOperations(object):
goal_time = 0.2
params = (['datetime', 'date_string', 'int', 'strings'],
... | (self, dtype):
self.non_unique_sorted.get_loc(self.key)
class Float64IndexMethod(object):
# GH 13166
goal_time = 0.2
def setup(self):
N = 100000
a = np.arange(N)
self.ind = Float64Index(a * 4.8000000418824129e-08)
def time_get_loc(self):
self.ind.get_loc(0)
| time_get_loc_non_unique_sorted | identifier_name |
index_object.py | import numpy as np
import pandas.util.testing as tm
from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,
Float64Index)
from .pandas_vb_common import setup # noqa
class SetOperations(object):
goal_time = 0.2
params = (['datetime', 'date_string', 'int', 'strings'],
... |
def time_append_range_list(self):
self.range_idx.append(self.range_idxs)
def time_append_int_list(self):
self.int_idx.append(self.int_idxs)
def time_append_obj_list(self):
self.obj_idx.append(self.object_idxs)
class Indexing(object):
goal_time = 0.2
params = ['String',... | r_idx = RangeIndex(i * 100, (i + 1) * 100)
self.range_idxs.append(r_idx)
i_idx = r_idx.astype(int)
self.int_idxs.append(i_idx)
o_idx = i_idx.astype(str)
self.object_idxs.append(o_idx) | conditional_block |
ut_daemon.py | #!/usr/bin/env python3
"""
test/unit_tests_d/ut_daemon.py: unit test for the MMGen suite's Daemon class
"""
from subprocess import run,DEVNULL
from mmgen.common import *
from mmgen.daemon import *
from mmgen.protocol import init_proto
def test_flags():
d = CoinDaemon('eth')
vmsg(f'Available opts: {fmt_list(d.avail... |
class unit_tests:
win_skip = ('start','status','stop')
def flags(self,name,ut):
qmsg_r('Testing flags and opts...')
vmsg('')
daemons = test_flags()
qmsg('OK')
qmsg_r('Testing error handling for flags and opts...')
vmsg('')
test_flags_err(ut,daemons)
qmsg('OK')
return True
def cmds(self,name... | if daemon_id in arm_skip_daemons:
continue
for network in data.networks:
if opt.no_altcoin_deps and coin != 'BTC':
continue
d = CoinDaemon(
proto=init_proto(coin=coin,network=network),
daemon_id = daemon_id,
test_suite = test_suite )
if op == 'print':
for cmd in d.s... | conditional_block |
ut_daemon.py | #!/usr/bin/env python3
"""
test/unit_tests_d/ut_daemon.py: unit test for the MMGen suite's Daemon class
"""
from subprocess import run,DEVNULL
from mmgen.common import *
from mmgen.daemon import *
from mmgen.protocol import init_proto
def test_flags():
d = CoinDaemon('eth')
vmsg(f'Available opts: {fmt_list(d.avail... | ():
for opts,flags,val in (
(None,None, vals(False,False,False)),
(None,['keep_cfg_file'], vals(False,False,True)),
(['online'],['keep_cfg_file'], vals(True,False,True)),
(['online','no_daemonize'],['keep_cfg_file'], vals(True,True,... | gen | identifier_name |
ut_daemon.py | #!/usr/bin/env python3
"""
test/unit_tests_d/ut_daemon.py: unit test for the MMGen suite's Daemon class
"""
from subprocess import run,DEVNULL
from mmgen.common import *
from mmgen.daemon import *
from mmgen.protocol import init_proto
def test_flags():
d = CoinDaemon('eth')
vmsg(f'Available opts: {fmt_list(d.avail... | proto=init_proto(coin=coin,network=network),
daemon_id = daemon_id,
test_suite = test_suite )
if op == 'print':
for cmd in d.start_cmds:
vmsg(' '.join(cmd))
elif op == 'check':
try:
cp = run([d.exec_fn,'--help'],stdout=PIPE,stderr=PIPE)
except:
die(2,f'... | continue
d = CoinDaemon( | random_line_split |
ut_daemon.py | #!/usr/bin/env python3
"""
test/unit_tests_d/ut_daemon.py: unit test for the MMGen suite's Daemon class
"""
from subprocess import run,DEVNULL
from mmgen.common import *
from mmgen.daemon import *
from mmgen.protocol import init_proto
def test_flags():
d = CoinDaemon('eth')
vmsg(f'Available opts: {fmt_list(d.avail... |
def bad7(): d[1].flag.keep_cfg_file = True
ut.process_bad_data((
('flag (1)', 'ClassFlagsError', 'unrecognized flag', bad1 ),
('opt (1)', 'ClassFlagsError', 'unrecognized opt', bad2 ),
('opt (2)', 'AttributeError', 'is read-only', bad3 ),
('flag (2)', 'AssertionError', 'not boolean', bad4 ),... | d[0].flag.keep_cfg_file = False | identifier_body |
driver.py | """
Dummy Salesforce driver that simulates some parts of DB API 2
https://www.python.org/dev/peps/pep-0249/
should be independent on Django.db
and if possible should be independent on django.conf.settings
Code at lower level than DB API should be also here.
"""
from collections import namedtuple
import requests
import... |
def rollback(self):
log.info("Rollback is not implemented.")
# DB API function
def connect(**params):
return Connection()
# LOW LEVEL
def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0):
"""Patched 'getaddrinfo' with default family IPv4 (enabled by settin... | pass | identifier_body |
driver.py | """
Dummy Salesforce driver that simulates some parts of DB API 2
https://www.python.org/dev/peps/pep-0249/
should be independent on Django.db
and if possible should be independent on django.conf.settings
Code at lower level than DB API should be also here.
"""
from collections import namedtuple
import requests
import... | import beatbox
except ImportError:
beatbox = None
import logging
log = logging.getLogger(__name__)
apilevel = "2.0"
# threadsafety = ...
# uses '%s' style parameters
paramstyle = 'format'
API_STUB = '/services/data/v35.0'
request_count = 0 # global counter
# All error types described in DB API 2 are impl... | random_line_split | |
driver.py | """
Dummy Salesforce driver that simulates some parts of DB API 2
https://www.python.org/dev/peps/pep-0249/
should be independent on Django.db
and if possible should be independent on django.conf.settings
Code at lower level than DB API should be also here.
"""
from collections import namedtuple
import requests
import... |
if(data['errorCode'] == 'INVALID_FIELD'):
raise SalesforceError(data['message'], data, response, verbose)
elif(data['errorCode'] == 'MALFORMED_QUERY'):
raise SalesforceError(data['message'], data, response, verbose)
elif(data['errorCode'] == 'INVALID_FIELD_FOR_INSERT_UPDATE'):
raise... | raise SalesforceError("Couldn't connect to API (404): %s, URL=%s"
% (response.text, url), data, response, verbose
) | conditional_block |
driver.py | """
Dummy Salesforce driver that simulates some parts of DB API 2
https://www.python.org/dev/peps/pep-0249/
should be independent on Django.db
and if possible should be independent on django.conf.settings
Code at lower level than DB API should be also here.
"""
from collections import namedtuple
import requests
import... | (object):
# close and commit can be safely ignored because everything is
# committed automatically and REST is stateles.
def close(self):
pass
def commit(self):
pass
def rollback(self):
log.info("Rollback is not implemented.")
# DB API function
def connect(**params):
... | Connection | identifier_name |
test_favicon.py | from django.test import TestCase
from django.test.utils import override_settings | """
Tests of the courseware favicon.
"""
shard = 1
def test_favicon_redirect(self):
resp = self.client.get("/favicon.ico")
self.assertEqual(resp.status_code, 301)
self.assertRedirects(
resp,
"/static/images/favicon.ico",
status_code=301, t... |
from util.testing import UrlResetMixin
class FaviconTestCase(UrlResetMixin, TestCase): | random_line_split |
test_favicon.py | from django.test import TestCase
from django.test.utils import override_settings
from util.testing import UrlResetMixin
class FaviconTestCase(UrlResetMixin, TestCase):
"""
Tests of the courseware favicon.
"""
shard = 1
def test_favicon_redirect(self):
resp = self.client.get("/favicon.ico... | (self):
self.reset_urls()
resp = self.client.get("/favicon.ico")
self.assertEqual(resp.status_code, 301)
self.assertRedirects(
resp,
"/static/images/foo.ico",
status_code=301, target_status_code=404 # @@@ how to avoid 404?
)
| test_favicon_redirect_with_favicon_path_setting | identifier_name |
test_favicon.py | from django.test import TestCase
from django.test.utils import override_settings
from util.testing import UrlResetMixin
class FaviconTestCase(UrlResetMixin, TestCase):
"""
Tests of the courseware favicon.
"""
shard = 1
def test_favicon_redirect(self):
|
@override_settings(FAVICON_PATH="images/foo.ico")
def test_favicon_redirect_with_favicon_path_setting(self):
self.reset_urls()
resp = self.client.get("/favicon.ico")
self.assertEqual(resp.status_code, 301)
self.assertRedirects(
resp,
"/static/images/foo... | resp = self.client.get("/favicon.ico")
self.assertEqual(resp.status_code, 301)
self.assertRedirects(
resp,
"/static/images/favicon.ico",
status_code=301, target_status_code=404 # @@@ how to avoid 404?
) | identifier_body |
aspirasi.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common'; |
import { routing } from './aspirasi.routing';
import { Aspirasi } from './aspirasi.component';
import { Tables } from './components/tables/tables.component';
import { CustomEditorComponent } from '../../shared/custom-editor.component';
import { CustomRenderComponent } from '../../shared/custom-render.component'... | import { FormsModule } from '@angular/forms';
import { NgaModule } from '../../theme/nga.module';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { DropdownModule} from 'ng2-bootstrap'; | random_line_split |
aspirasi.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgaModule } from '../../theme/nga.module';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { DropdownModule} from 'ng2-bootstrap';
import { routing } ... | {}
| AspirasiModule | identifier_name |
recover.py | # This file is part of VoltDB.
# Copyright (C) 2008-2014 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a... | (runner):
runner.go()
| recover | identifier_name |
recover.py | # This file is part of VoltDB.
# Copyright (C) 2008-2014 VoltDB Inc.
#
# This file contains original code and/or modifications of original code. | # Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without lim... | random_line_split | |
recover.py | # This file is part of VoltDB.
# Copyright (C) 2008-2014 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a... | runner.go() | identifier_body | |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | assert_initialized_main_thread!();
unsafe { ffi::gdk_screen_height_mm() }
}
pub fn beep() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_flush() }
}
pub fn error_trap_push() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_error_trap_push() }
}
pub fn error_trap_pop() -> i32 {
... | unsafe { ffi::gdk_screen_width_mm() }
}
pub fn screen_height_mm() -> i32 { | random_line_split |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | -> Option<String> {
assert_initialized_main_thread!();
unsafe {
from_glib_none(ffi::gdk_get_display_arg_name())
}
}
pub fn notify_startup_complete() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_notify_startup_complete() }
}
pub fn notify_startup_complete_with_id(startup_id: &str... | t_display_arg_name() | identifier_name |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | else if is_initialized() {
panic!("Attempted to initialize GDK from two different threads.");
}
INITIALIZED.store(true, Ordering::Release);
IS_MAIN_THREAD.with(|c| c.set(true));
}
pub fn init() {
assert_not_initialized!();
unsafe {
ffi::gdk_init(ptr::null_mut(), ptr::null_mut());... | return;
}
| conditional_block |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | pub fn init() {
assert_not_initialized!();
unsafe {
ffi::gdk_init(ptr::null_mut(), ptr::null_mut());
set_initialized();
}
}
pub fn get_display_arg_name() -> Option<String> {
assert_initialized_main_thread!();
unsafe {
from_glib_none(ffi::gdk_get_display_arg_name())
}
}
... | skip_assert_initialized!();
if is_initialized_main_thread() {
return;
}
else if is_initialized() {
panic!("Attempted to initialize GDK from two different threads.");
}
INITIALIZED.store(true, Ordering::Release);
IS_MAIN_THREAD.with(|c| c.set(true));
}
| identifier_body |
cpNbnet.py | #!/usr/bin/env python
# coding:utf-8
import select
import socket
from nbNetUtils import DEBUG, dbgPrint
__all__ = ["nbNet"]
class STATE:
def __init__(self):
self.state = "accept" # 定义状态
self.have_read = 0 # 记录读了的字节
self.need_read = 10 # 头文件需要读取10个字节
self.have_write = 0 # 记录读了... | 0报错
raise socket.error
sock_state.buff_read += one_read # 把读取数据存到读缓存中
sock_state.have_read += len(one_read) # 已经读取完的数据量
sock_state.need_read -= len(one_read) # 还需要读取数据的量
sock_state.printState()
if sock_state.have_read == 10: # 10字节为头文件处理
... | ad) == 0: # 读取数据为 | conditional_block |
cpNbnet.py | #!/usr/bin/env python
# coding:utf-8
import select
import socket
from nbNetUtils import DEBUG, dbgPrint
__all__ = ["nbNet"]
class STATE:
def __init__(self):
self.state = "accept" # 定义状态
self.have_read = 0 # 记录读了的字节
self.need_read = 10 # 头文件需要读取10个字节
self.have_write = 0 # 记录读了... | sock_state.printState()
if sock_state.have_read == 10: # 10字节为头文件处理
header_said_need_read = int(sock_state.have_read) # 读取数据的量
if header_said_need_read <= 0: # 如果还需读0字节报错
raise socket.error
sock_state.need_read += header_said... | raise socket.error
sock_state.buff_read += one_read # 把读取数据存到读缓存中
sock_state.have_read += len(one_read) # 已经读取完的数据量
sock_state.need_read -= len(one_read) # 还需要读取数据的量 | random_line_split |
cpNbnet.py | #!/usr/bin/env python
# coding:utf-8
import select
import socket
from nbNetUtils import DEBUG, dbgPrint
__all__ = ["nbNet"]
class STATE:
def __init__(self):
self.state = "accept" # 定义状态
self.have_read = 0 # 记录读了的字节
self.need_read = 10 # 头文件需要读取10个字节
self.have_write = 0 # 记录读了... | self.conn_state[fd].state = 'closing' # 状态为closing关闭连接
self.state_machine(fd)
else:
raise Exception("impossible state returned by self.read")
def write2read(self, fd):
try:
write_ret = self.write(fd) # 函数write返回值
except socket.error, msg: # 出错关闭连接... | read_ret = self.read(fd) # read函数返回值
except (Exception), msg:
dbgPrint(msg)
read_ret = "closing"
if read_ret == "process": # 读取完成,转换到process
self.process(fd)
elif read_ret == "readcontent": # readcontent、readmore、retry 继续读取
pass
elif r... | identifier_body |
cpNbnet.py | #!/usr/bin/env python
# coding:utf-8
import select
import socket
from nbNetUtils import DEBUG, dbgPrint
__all__ = ["nbNet"]
class | :
def __init__(self):
self.state = "accept" # 定义状态
self.have_read = 0 # 记录读了的字节
self.need_read = 10 # 头文件需要读取10个字节
self.have_write = 0 # 记录读了的字节
self.need_write = 0 # 需要写的字节
self.buff_read = "" # 读缓存
self.buff_write = "" # 写缓存
self.sock_obj = ""... | STATE | identifier_name |
basic_client.rs | // use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::ffi::CString;
use std::thread;
use std::str;
extern crate mbedtls;
use mbedtls::mbed;
use mbedtls::mbed::ssl::error::SSLError;
const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n";
fn main() {
let mut stream = TcpStream::connect("... |
stream.shutdown(Shutdown::Both).unwrap();
}
fn attempt_io<I, F: FnMut() -> Result<I, SSLError>>(mut f: F) -> I {
loop {
match f() {
Ok(i) => return i,
Err(SSLError::WantRead) | Err(SSLError::WantWrite) => {
thread::sleep_ms(100);
continue
... | );
attempt_io(|| ssl_context.close_notify());
} | random_line_split |
basic_client.rs | // use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::ffi::CString;
use std::thread;
use std::str;
extern crate mbedtls;
use mbedtls::mbed;
use mbedtls::mbed::ssl::error::SSLError;
const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n";
fn | () {
let mut stream = TcpStream::connect("216.58.210.78:443").unwrap();
{
let mut entropy = mbedtls::mbed::entropy::EntropyContext::new();
let mut entropy_func = |d : &mut[u8] | entropy.entropy_func(d);
let mut ctr_drbg = mbed::ctr_drbg::CtrDrbgContext::with_seed(
&mut entr... | main | identifier_name |
basic_client.rs | // use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::ffi::CString;
use std::thread;
use std::str;
extern crate mbedtls;
use mbedtls::mbed;
use mbedtls::mbed::ssl::error::SSLError;
const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n";
fn main() {
let mut stream = TcpStream::connect("... | {
loop {
match f() {
Ok(i) => return i,
Err(SSLError::WantRead) | Err(SSLError::WantWrite) => {
thread::sleep_ms(100);
continue
},
Err(e) => panic!("Got error: {}", e),
}
}
} | identifier_body | |
tests.py | from datetime import datetime, timedelta
import time
import unittest
from django.http import HttpRequest, HttpResponse, parse_cookie
from django.core.handlers.wsgi import WSGIRequest
from django.core.handlers.modpython import ModPythonRequest
from django.utils.http import cookie_date
class RequestsTests(unittest.Test... | def test_httprequest(self):
request = HttpRequest()
self.assertEqual(request.GET.keys(), [])
self.assertEqual(request.POST.keys(), [])
self.assertEqual(request.COOKIES.keys(), [])
self.assertEqual(request.META.keys(), [])
def test_wsgirequest(self):
request = WSGIReq... | identifier_body | |
tests.py | from datetime import datetime, timedelta
import time
import unittest
from django.http import HttpRequest, HttpResponse, parse_cookie
from django.core.handlers.wsgi import WSGIRequest
from django.core.handlers.modpython import ModPythonRequest
from django.utils.http import cookie_date
class RequestsTests(unittest.Test... | (self):
"Cookie will expire if max_age is provided"
response = HttpResponse()
response.set_cookie('max_age', max_age=10)
max_age_cookie = response.cookies['max_age']
self.assertEqual(max_age_cookie['max-age'], 10)
self.assertEqual(max_age_cookie['expires'], cookie_date(ti... | test_max_age_expiration | identifier_name |
tests.py | from datetime import datetime, timedelta
import time
import unittest
from django.http import HttpRequest, HttpResponse, parse_cookie
from django.core.handlers.wsgi import WSGIRequest
from django.core.handlers.modpython import ModPythonRequest
from django.utils.http import cookie_date
class RequestsTests(unittest.Test... | "Cookie will expire when an near expiration time is provided"
response = HttpResponse()
# There is a timing weakness in this test; The
# expected result for max-age requires that there be
# a very slight difference between the evaluated expiration
# time, and the time eva... | def test_near_expiration(self): | random_line_split |
group___f_l_a_s_h___exported___constants.js | var group___f_l_a_s_h___exported___constants =
[
[ "Flash_Latency", "group___flash___latency.html", "group___flash___latency" ],
[ "Half_Cycle_Enable_Disable", "group___half___cycle___enable___disable.html", "group___half___cycle___enable___disable" ],
[ "Prefetch_Buffer_Enable_Disable", "group___prefetch__... | ]; | random_line_split | |
node.py | """ EPYNET Classes """
from . import epanet2
from .objectcollection import ObjectCollection
from .baseobject import BaseObject, lazy_property
from .pattern import Pattern
class Node(BaseObject):
""" Base EPANET Node class """
static_properties = {'elevation': epanet2.EN_ELEVATION}
properties = {'head': ep... |
class Tank(Node):
""" EPANET Tank Class """
node_type = "Tank"
static_properties = {'elevation': epanet2.EN_ELEVATION, 'basedemand': epanet2.EN_BASEDEMAND,
'initvolume': epanet2.EN_INITVOLUME, 'diameter': epanet2.EN_TANKDIAM,
'minvolume': epanet2.EN_MINVO... | """ EPANET Junction Class """
static_properties = {'elevation': epanet2.EN_ELEVATION, 'basedemand': epanet2.EN_BASEDEMAND, 'emitter': epanet2.EN_EMITTER}
properties = {'head': epanet2.EN_HEAD, 'pressure': epanet2.EN_PRESSURE, 'demand': epanet2.EN_DEMAND}
node_type = "Junction"
@property
def pattern... | identifier_body |
node.py | """ EPYNET Classes """
from . import epanet2
from .objectcollection import ObjectCollection
from .baseobject import BaseObject, lazy_property
from .pattern import Pattern
class Node(BaseObject):
""" Base EPANET Node class """
static_properties = {'elevation': epanet2.EN_ELEVATION}
properties = {'head': ep... | (self):
pattern_index = int(self.get_property(epanet2.EN_PATTERN))
uid = self.network().ep.ENgetpatternid(pattern_index)
return Pattern(uid, self.network())
@pattern.setter
def pattern(self, value):
if isinstance(value, int):
pattern_index = value
elif isinst... | pattern | identifier_name |
node.py | """ EPYNET Classes """
from . import epanet2
from .objectcollection import ObjectCollection
from .baseobject import BaseObject, lazy_property
from .pattern import Pattern
class Node(BaseObject):
""" Base EPANET Node class """
static_properties = {'elevation': epanet2.EN_ELEVATION}
properties = {'head': ep... |
elif isinstance(value, str):
pattern_index = self.network().ep.ENgetpatternindex(value)
else:
pattern_index = value.index
self.network().solved = False
self.set_object_value(epanet2.EN_PATTERN, pattern_index)
class Tank(Node):
""" EPANET Tank Class """
... | pattern_index = value | conditional_block |
node.py | """ EPYNET Classes """
from . import epanet2
from .objectcollection import ObjectCollection
from .baseobject import BaseObject, lazy_property
from .pattern import Pattern
class Node(BaseObject):
""" Base EPANET Node class """
static_properties = {'elevation': epanet2.EN_ELEVATION}
properties = {'head': ep... | raise ValueError("This method is only supported for steady state simulations")
links = ObjectCollection()
for link in self.links:
if (link.to_node == self and link.flow >= 1e-3) or (link.from_node == self and link.flow < -1e-3):
links[link.uid] = link
ret... | def upstream_links(self):
""" return a list of upstream links """
if self.results != {}: | random_line_split |
procGOME_L2.py | #!/usr/bin/env python
import numpy.ma as ma
import os,sys, subprocess, math, datetime
from os.path import basename
import numpy as np
import time as tt
import gdal
import h5py
from datetime import timedelta
from gdalconst import GDT_Float32, GA_Update
from osgeo import ogr, osr
import logging
#TODO: change for handli... | data_ds = None
window = str(stepSize)+'x'+str(ySize)
processes.append((subprocess.Popen([workingDir + '/bin/remap', '-i', filename, '-o', filenameOutput, '-a', filenameCoords,'-q','-s', str(pixelSize),'-w',window ,'-f','80000','-n','-9999'], stdout=open(os.devnull, 'wb')), filenameOutput,timeSta... | band[band == fillValue] = -9999
maxValue=np.max(ma.masked_equal(band,-9999))
minValue=np.min(ma.masked_equal(band,-9999))
data_ds.GetRasterBand(1).WriteArray(band) | random_line_split |
procGOME_L2.py | #!/usr/bin/env python
import numpy.ma as ma
import os,sys, subprocess, math, datetime
from os.path import basename
import numpy as np
import time as tt
import gdal
import h5py
from datetime import timedelta
from gdalconst import GDT_Float32, GA_Update
from osgeo import ogr, osr
import logging
#TODO: change for handli... |
instrument = metadata['InstrumentID'][0]
level = 'L'+metadata['ProcessingLevel'][0]
fillValue = dataAttributes['FillValue'][0]
satellite = metadata['SatelliteID'][0]
dataType = GDT_Float32
stepSize = 1500
cnt = 0
ySize = 1
workingDir = os.path.dirname(os.path.real... | time_computed.append(tt.mktime((datetime.datetime(1950, 1, 1)+timedelta(days=int(time['Day'][i]))+timedelta(milliseconds=int(time['MillisecondOfDay'][i]))).timetuple())) | conditional_block |
procGOME_L2.py | #!/usr/bin/env python
import numpy.ma as ma
import os,sys, subprocess, math, datetime
from os.path import basename
import numpy as np
import time as tt
import gdal
import h5py
from datetime import timedelta
from gdalconst import GDT_Float32, GA_Update
from osgeo import ogr, osr
import logging
#TODO: change for handli... |
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit('\nUsage: %s GOME_file \n' % sys.argv[0] )
else:
if not os.path.exists(sys.argv[1]):
sys.exit('\nERROR: File %s was not found!\n' % sys.argv[1])
fileAbsPath = sys.argv[1]
createImgGOME_L2(fileAbsPa... | hdf = h5py.File(fileAbsPath, 'r')
driver = gdal.GetDriverByName('GTiff')
lat = np.array(hdf['/GEOLOCATION/LatitudeCentre'])
lon = np.array(hdf['/GEOLOCATION/LongitudeCentre'])
lon = -180*(lon.astype(int)/180) + (lon%180)
time = np.array(hdf['/GEOLOCATION/Time'])
data = np.array(hdf... | identifier_body |
procGOME_L2.py | #!/usr/bin/env python
import numpy.ma as ma
import os,sys, subprocess, math, datetime
from os.path import basename
import numpy as np
import time as tt
import gdal
import h5py
from datetime import timedelta
from gdalconst import GDT_Float32, GA_Update
from osgeo import ogr, osr
import logging
#TODO: change for handli... | (fileAbsPath, pixelSize=0.25):
hdf = h5py.File(fileAbsPath, 'r')
driver = gdal.GetDriverByName('GTiff')
lat = np.array(hdf['/GEOLOCATION/LatitudeCentre'])
lon = np.array(hdf['/GEOLOCATION/LongitudeCentre'])
lon = -180*(lon.astype(int)/180) + (lon%180)
time = np.array(hdf['/GEOLOCAT... | createImgGOME_L2 | identifier_name |
app.js | /**
* @ngdoc overview
* @name hciApp
* @description
* # hciApp
*
* Main module of the application.
*/
angular
.module('hciApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.bootstrap',
'ngMaterial'
])
.config(function ($routeProvider) {
... | 'use strict';
| random_line_split | |
map.spec.ts | import { map } from './map';
describe('map function', () => {
const input = [1, 2, 3, 4, 5];
const incr: (x: number) => number = x => 1 + x;
test('is a pure function', () => {
map(incr)(input);
expect(input).toMatchSnapshot();
}); |
test('[1, 2, 3, 4, 5] |> map(incr) === [2, 3, 4, 5, 6]', () => {
expect(map(incr)(input)).toMatchSnapshot();
});
test('[] |> map(incr) === []', () => {
expect(map(incr)([])).toMatchSnapshot();
});
test('call the iteree callback with correct inputs', () => {
const cb = jest.fn((x: number) => 1 +... | random_line_split | |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... |
while let Some(p) = self.iter.next() {
let p: T = FromPrimitive::from_u64(p).unwrap();
if p.clone() * p.clone() > self.num {
let n = mem::replace(&mut self.num, One::one());
return Some((n, 1));
}
if self.num.is_multiple_of(&p) {... | {
return None;
} | conditional_block |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... | (&mut self, n: T) {
for (b, e) in n.factorize(self.ps) {
match self.map.entry(b) {
Vacant(entry) => {
let _ = entry.insert(e);
}
Occupied(entry) => {
let p = entry.into_mut();
*p = cmp::max(e,... | lcm_with | identifier_name |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... |
#[test]
fn multi_iter() {
let ps = PrimeSet::new();
for (p1, p2) in ps.iter().zip(ps.iter()).take(500) {
assert_eq!(p1, p2);
}
}
#[test]
fn clone_clones_data() {
let p1 = PrimeSet::new_empty();
let p2 = p1.clone();
let _ = p1.nth(5000);
... | {
let ps = PrimeSet::new();
assert!(!ps.contains(0));
assert!(!ps.contains(1));
assert!(ps.contains(2));
assert!(ps.contains(3));
assert!(!ps.contains(4));
assert!(ps.contains(5));
assert!(!ps.contains(6));
assert!(ps.contains(7));
assert!(... | identifier_body |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... | (48, 10),
(60, 12),
(50, 6),
];
let ps = PrimeSet::new();
for &(n, num_div) in pairs {
assert_eq!(num_div, n.num_of_divisor(&ps));
assert_eq!(num_div, (-n).num_of_divisor(&ps));
}
}
#[test]
fn sum_of_divisor() {
... | (24, 8),
(36, 9), | random_line_split |
wavetable.js | // Copyright 2011, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of condition... | (name, context) {
this.name = name;
this.context = context;
this.sampleRate = context.sampleRate;
this.url = "wave-tables/" + this.name;
this.waveTableSize = 4096; // hard-coded for now
this.buffer = 0;
this.numberOfResampleRanges = kDefaultNumberOfResampleRanges;
}
WaveTable.prototype.getW... | WaveTable | identifier_name |
wavetable.js | // Copyright 2011, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of condition... |
WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) {
var nyquist = 0.5 * this.sampleRate;
var lowestNumPartials = this.getNumberOfPartialsForRange(0);
var lowestFundamental = nyquist / lowestNumPartials;
// Find out pitch range
var ratio = pitchFrequency / lowestFundamental;
v... | {
this.name = name;
this.context = context;
this.sampleRate = context.sampleRate;
this.url = "wave-tables/" + this.name;
this.waveTableSize = 4096; // hard-coded for now
this.buffer = 0;
this.numberOfResampleRanges = kDefaultNumberOfResampleRanges;
} | identifier_body |
wavetable.js | // Copyright 2011, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of condition... | this.sampleRate = context.sampleRate;
this.url = "wave-tables/" + this.name;
this.waveTableSize = 4096; // hard-coded for now
this.buffer = 0;
this.numberOfResampleRanges = kDefaultNumberOfResampleRanges;
}
WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) {
var nyquist = 0.5 *... |
function WaveTable(name, context) {
this.name = name;
this.context = context; | random_line_split |
grid.js | //TODO: encapsulate back to private function when card design is done
//typical sizes:
/*
portrait:
iPhone 4,5 375px
iPhone 6 320px
iPhone 6+ 414px
Galaxy S3 360px
landscape:
iPhone 4 480px
iPhone 5 568px
iPhone 6 667px (574px container)
iPhone 6+ ... | ,
getContainerWidth(browserWidth) {
//should match variables from bootstrap
if (browserWidth <= ContainerWidth.SM) {
return browserWidth //container becomes fluid for small size
} else if (browserWidth > ContainerWidth.SM && browserWidth < Breakpoints.MD) {
return ContainerWidth.SM
} el... | {
return browserWidth - getGutter(browserWidth)
} | identifier_body |
grid.js | //TODO: encapsulate back to private function when card design is done
//typical sizes:
/*
portrait:
iPhone 4,5 375px
iPhone 6 320px
iPhone 6+ 414px
Galaxy S3 360px
landscape:
iPhone 4 480px
iPhone 5 568px
iPhone 6 667px (574px container)
iPhone 6+ ... | (containerWidth) {
return {
//returns width in px of Container's content area (width without paddings)
getColumnContentWidth({numberOfCols}) {
const oneColPercent = (100 / COLUMNS) / 100
const containerGutter = containerWidth >= Breakpoints.SM ? getGutter(containerWidth) : 0
retu... | init | identifier_name |
grid.js | //TODO: encapsulate back to private function when card design is done
//typical sizes:
/*
portrait:
iPhone 4,5 375px
iPhone 6 320px
iPhone 6+ 414px
Galaxy S3 360px
landscape:
iPhone 4 480px
iPhone 5 568px
iPhone 6 667px (574px container)
iPhone 6+ ... | else if (browserWidth > ContainerWidth.SM && browserWidth < Breakpoints.MD) {
return ContainerWidth.SM
} else if (browserWidth >= Breakpoints.MD && browserWidth < Breakpoints.LG) {
return ContainerWidth.MD
} else if (browserWidth >= Breakpoints.LG && browserWidth < Breakpoints.XL) {
return Co... | {
return browserWidth //container becomes fluid for small size
} | conditional_block |
grid.js | //TODO: encapsulate back to private function when card design is done
//typical sizes:
/*
portrait:
iPhone 4,5 375px
iPhone 6 320px
iPhone 6+ 414px
Galaxy S3 360px
landscape:
iPhone 4 480px
iPhone 5 568px
iPhone 6 667px (574px container)
iPhone 6+ ... |
if (browserWidth <= ContainerWidth.SM) {
return browserWidth //container becomes fluid for small size
} else if (browserWidth > ContainerWidth.SM && browserWidth < Breakpoints.MD) {
return ContainerWidth.SM
} else if (browserWidth >= Breakpoints.MD && browserWidth < Breakpoints.LG) {
retu... |
getContainerWidth(browserWidth) {
//should match variables from bootstrap
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.