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
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
} fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() ...
\n\ {2}", NAME, VERSION, usage); println!("{}", msg);
random_line_split
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
(usage: &String) { let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", ...
help
identifier_name
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() }...
{ let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", msg); }
identifier_body
sanitize.js
import stringify from 'json-stringify-safe' import validator from 'validator' const OBJLENGTH = 10 const ARRLENGTH = 10 const STRINGLIMIT = 1000 const STRINGTRUNCATE = 200 let sanitizeString = function (str) { if (!str) { return '' } return String(str) .replace(/\./g, '_') .replac...
return val case '[object Array]': const length = val.length if (length > ARRLENGTH) { val = val.slice(0, ARRLENGTH) val.push('(' + (length - ARRLENGTH) + ' more items)') } return val.map(limit) case '[object Object]': const keys = Object....
{ return val.substr(0, STRINGTRUNCATE) + ' ... (' + (val.length - STRINGTRUNCATE) + ' more bytes)' }
conditional_block
sanitize.js
import stringify from 'json-stringify-safe' import validator from 'validator' const OBJLENGTH = 10 const ARRLENGTH = 10 const STRINGLIMIT = 1000 const STRINGTRUNCATE = 200 let sanitizeString = function (str) { if (!str) { return '' } return String(str) .replace(/\./g, '_') .replac...
return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase() } /** * Limit the length of an arbitrary variable of any type, suitable for being logged or displayed * @param {Any} val Any variable * @return {Any} Limited var of same type */ let limit = function (val) { if (!val) return val ...
let css = function (value) { if (!value) { return value }
random_line_split
m_ao_eval_libnao.py
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
(ao, ra, isp, coords): res = np.zeros((ao.sp2norbs[isp],coords.shape[0]), dtype='float64') ao_eval_libnao_(ao, ra, isp, coords, res) return res if __name__ == '__main__': from pyscf.nao.m_system_vars import system_vars_c from pyscf.nao.m_ao_eval import ao_eval from pyscf.nao.m_ao_eval_libnao import ao_eva...
ao_eval_libnao
identifier_name
m_ao_eval_libnao.py
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
Returns: res[norbs,ncoord] : array of atomic orbital values """ #print(res_copy.flags) rat_copy = np.require(rat, dtype=c_double, requirements='C') crd_copy = np.require(crds, dtype=c_double, requirements='C') res_copy = np.require(res, dtype=c_double, requirements='CW') mu2j = np.require(ao.sp...
ao : instance of ao_log_c class rat : vector where the atomic orbitals from "ao" are centered isp : specie index for which we compute crds: coordinates on which we compute
random_line_split
m_ao_eval_libnao.py
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
libnao.ao_eval( c_int64(ao.sp2nmult[isp]), ff.ctypes.data_as(POINTER(c_double)), c_int64(ao.nr), c_double(ao.interp_rr.gammin_jt), c_double(ao.interp_rr.dg_jt), mu2j.ctypes.data_as(POINTER(c_int64)), mu2s.ctypes.data_as(POINTER(c_int64)), mu2rcut.ctypes.data_as(POINTER(c_double)), ...
""" Compute the values of atomic orbitals on given grid points Args: ao : instance of ao_log_c class rat : vector where the atomic orbitals from "ao" are centered isp : specie index for which we compute crds: coordinates on which we compute Returns: res[norbs,ncoord] : array o...
identifier_body
m_ao_eval_libnao.py
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
from pyscf.nao.m_system_vars import system_vars_c from pyscf.nao.m_ao_eval import ao_eval from pyscf.nao.m_ao_eval_libnao import ao_eval_libnao sv = system_vars_c() ra = np.array([0.3, -0.5, 0.77], dtype='float64') #coords = np.array([[0.07716887, 2.82933578, 3.73214881]]) coords = np.random.rand(35580,...
conditional_block
scancode_linux.rs
use super::Key; use super::Key::*; /// Keyboard scancode map for Linux. pub static MAP: [Option<Key>; 97] = [ None, None, None, None, None, None, None, None, None, Some(Escape), Some(Num1), Some(Num2), Some(Num3), Some(Num4), Some(Num5), Some(Num6), S...
Some(Z), Some(X), Some(C), Some(V), Some(B), Some(N), Some(M), Some(Comma), Some(Period), Some(Slash), Some(RightShift), Some(PadMultiply), Some(LeftAlt), Some(Space), Some(CapsLock), Some(F1), Some(F2), Some(F3), Some(F4), Some(F5), So...
Some(Semicolon), Some(Apostrophe), Some(Grave), Some(LeftShift), Some(Backslash),
random_line_split
AirlineSeatFlatAngledTwoTone.js
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime";
}, "0"), /*#__PURE__*/_jsx("path", { d: "M1.5 12.14 8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm8.5 3.05 4 1.44V17h-4v-1.81zm9.84-6.05-8.56-3.09-2.08 5.66 12.36 4.47.69-1.89c.77-2.09-.31-4.39-2.41-5.15zm.53 4.46-.01.02-8.59-3.11.7-1.91 6.69 2.41c.52.19.93.56 1.15 1.05.23.49.25 1.04.06 1.54zM6 10.5c.44 0...
export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "m14 16.64-4-1.45V17h4zM6 8.5c.15 0 .3-.03.44-.1.49-.24.7-.84.46-1.34-.19-.41-.59-.56-.9-.56-.15 0-.3.03-.44.1-.32.16-.45.42-.5.56-.05.15-.12.44.04.77.2.42.59.57.9.57zm13.16 2.52-6.69-2.41-.7 1.91 8.59 3.11.01-.02c.19-.51.17-1.05-.06-1.53-.23-.5-.63-.87-1.1...
random_line_split
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for...
<U: Bar>(&self) { only_foo(&self.x); only_bar::<U>(); } } fn main() { let s = S { x: 5, }; s.dummy_bar::<u32>(); s.dummy_foo(); }
dummy_bar
identifier_name
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for...
}; s.dummy_bar::<u32>(); s.dummy_foo(); }
random_line_split
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for...
} fn main() { let s = S { x: 5, }; s.dummy_bar::<u32>(); s.dummy_foo(); }
{ only_foo(&self.x); only_bar::<U>(); }
identifier_body
TractInfo.py
#!/usr/bin/env python import argparse import logging import os import tractconverter.info as info import tractconverter from tractconverter import FORMATS from tractconverter import EXT_ANAT # Script description DESCRIPTION = """ TractInfo {0}. Print info about a streamlines file. Supported formats are {1} """.forma...
return p def main(): parser = buildArgsParser() args = parser.parse_args() in_filename = args.input if not os.path.isfile(in_filename): parser.error('"{0}" must be an existing file!'.format(in_filename)) if not tractconverter.is_supported(in_filename): parser.error('Input fi...
p = argparse.ArgumentParser(description=DESCRIPTION) p.add_argument('-i', action='store', dest='input', metavar='FILE', required=True, help='input track file ({0})'.format(",".join(FORMATS.keys())))
random_line_split
TractInfo.py
#!/usr/bin/env python import argparse import logging import os import tractconverter.info as info import tractconverter from tractconverter import FORMATS from tractconverter import EXT_ANAT # Script description DESCRIPTION = """ TractInfo {0}. Print info about a streamlines file. Supported formats are {1} """.forma...
main()
conditional_block
TractInfo.py
#!/usr/bin/env python import argparse import logging import os import tractconverter.info as info import tractconverter from tractconverter import FORMATS from tractconverter import EXT_ANAT # Script description DESCRIPTION = """ TractInfo {0}. Print info about a streamlines file. Supported formats are {1} """.forma...
(): p = argparse.ArgumentParser(description=DESCRIPTION) p.add_argument('-i', action='store', dest='input', metavar='FILE', required=True, help='input track file ({0})'.format(",".join(FORMATS.keys()))) return p def main(): parser = buildArgsParser() args = pa...
buildArgsParser
identifier_name
TractInfo.py
#!/usr/bin/env python import argparse import logging import os import tractconverter.info as info import tractconverter from tractconverter import FORMATS from tractconverter import EXT_ANAT # Script description DESCRIPTION = """ TractInfo {0}. Print info about a streamlines file. Supported formats are {1} """.forma...
def main(): parser = buildArgsParser() args = parser.parse_args() in_filename = args.input if not os.path.isfile(in_filename): parser.error('"{0}" must be an existing file!'.format(in_filename)) if not tractconverter.is_supported(in_filename): parser.error('Input file must be o...
p = argparse.ArgumentParser(description=DESCRIPTION) p.add_argument('-i', action='store', dest='input', metavar='FILE', required=True, help='input track file ({0})'.format(",".join(FORMATS.keys()))) return p
identifier_body
test_counter.py
from __future__ import print_function, unicode_literals from datetime import datetime, timedelta import time import unittest from DenyHosts.counter import Counter, CounterRecord class CounterRecordTest(unittest.TestCase): def test_init(self): c = CounterRecord() self.assertEqual(c.get_count(), 0)...
def test_init(self): c = Counter() self.assertEqual(len(c), 0) def test_missing_key(self): c = Counter() key = 'key' value = c[key] self.assertEqual(value.get_count(), 0) self.assertTrue(key in c) def test_existing_key(self): key = 'key' ...
identifier_body
test_counter.py
from __future__ import print_function, unicode_literals from datetime import datetime, timedelta import time import unittest from DenyHosts.counter import Counter, CounterRecord class CounterRecordTest(unittest.TestCase): def test_init(self): c = CounterRecord() self.assertEqual(c.get_count(), 0)...
CounterRecord.__count is intended to be numeric, but any object can be used. Verify that what we pass to the constructor is accessible. """ count = object() c = CounterRecord(count=count) self.assertTrue(c.get_count() is count) def test_str(self): """ ...
def test_init_provided_count(self): """
random_line_split
test_counter.py
from __future__ import print_function, unicode_literals from datetime import datetime, timedelta import time import unittest from DenyHosts.counter import Counter, CounterRecord class CounterRecordTest(unittest.TestCase): def test_init(self): c = CounterRecord() self.assertEqual(c.get_count(), 0)...
(self): """ CounterRecord.__add__ is *horrible* design, but that's how it's been for a very long time. I want test coverage for the current behavior before making any changes. """ c = CounterRecord() orig_date = c.get_date() self.assertEqual(c.get_count(),...
test_add
identifier_name
computeclient.js
/** * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
/** * Inherit from Auth2Client. */ util.inherits(Compute, Auth2Client); /** * Get the initial access token from compute metadata server. * @param {function=} opt_callback Optional callback. */ Compute.prototype.authorize = function(opt_callback) { var that = this; that.refreshToken_(null, function(err, resu...
{ Compute.super_.call(this); }
identifier_body
computeclient.js
/** * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
() { Compute.super_.call(this); } /** * Inherit from Auth2Client. */ util.inherits(Compute, Auth2Client); /** * Get the initial access token from compute metadata server. * @param {function=} opt_callback Optional callback. */ Compute.prototype.authorize = function(opt_callback) { var that = this; that.ref...
Compute
identifier_name
computeclient.js
/** * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
*/ 'use strict'; var Auth2Client = require('./oauth2client.js'); var util = require('util'); /** * Google Compute Engine metadata server token endpoint. * @private */ Compute.GOOGLE_OAUTH2_TOKEN_URL_ = 'http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token'; /** * Google Compute Eng...
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.
random_line_split
computeclient.js
/** * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
opt_callback && opt_callback(err, result); }); }; /** * Refreshes the access token. * @param {object=} ignored_ * @param {function=} opt_callback Optional callback. * @private */ Compute.prototype.refreshToken_ = function(ignored_, opt_callback) { var uri = this.opts.tokenUrl || Compute.GOOGLE_OAUTH2_TOK...
{ that.credentials = result; that.credentials.refresh_token = 'compute-placeholder'; }
conditional_block
webpack.config.dev.js
const path = require('path'); const webpack = require('webpack'); const autoprefixer = require('autoprefixer'); // App files location const PATHS = { app: path.resolve(__dirname, '../src/js'), styles: path.resolve(__dirname, '../src/styles'), build: path.resolve(__dirname, '../build') }; const plugins = [ // ...
loader: sassLoaders.join('!') }, { test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader' }, // Inline base64 URLs for <=8k images, direct URLs for the rest { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/, loader: 'url-loader?limit=8192' ...
loaders: ['react-hot', 'babel'], include: PATHS.app }, { test: /\.scss$/,
random_line_split
mobileme.py
WebService class MobileMe(WebService): loginform_url = 'https://auth.me.com/authenticate' loginform_data = { 'service': 'account', 'ssoNamespace': 'primary-me', 'reauthorize': 'Y', 'returnURL': 'aHR0cHM6Ly9zZWN1cmUubWUuY29tL2FjY291bnQv', } loginform_id = 'LoginForm' ...
device = self.get_device(device_id) self._logger.info('Sending "%s" to device "%s" with%s alarm', msg, device['id'], 'out' if not alarm else '') body = { 'deviceClass': device['class'], 'deviceId': device['id'], 'deviceOsVersion': device['osver'], ...
if resp.code == 200: return Location(resp.read()) self._logger.error('Locate device "%s" failed!', device['id']) def msg_device(self, msg, alarm=False, device_id=None):
random_line_split
mobileme.py
Service class MobileMe(WebService): loginform_url = 'https://auth.me.com/authenticate' loginform_data = { 'service': 'account', 'ssoNamespace': 'primary-me', 'reauthorize': 'Y', 'returnURL': 'aHR0cHM6Ly9zZWN1cmUubWUuY29tL2FjY291bnQv', } loginform_id = 'LoginForm' lo...
def _add_device(self, id, type, cls, osver): self._devices[id] = { 'id': id, 'type': type, 'class': cls, 'osver': osver, } def get_devices(self): return self._devices.keys() def get_device(self, id=None): if id is None: ...
_, id, type, cls, osver, _, _ = match.replace("'", '').split(', ') self._logger.info('Found device "%s"', id) self._add_device(id, type, cls, osver)
conditional_block
mobileme.py
Service class MobileMe(WebService): loginform_url = 'https://auth.me.com/authenticate' loginform_data = { 'service': 'account', 'ssoNamespace': 'primary-me', 'reauthorize': 'Y', 'returnURL': 'aHR0cHM6Ly9zZWN1cmUubWUuY29tL2FjY291bnQv', } loginform_id = 'LoginForm' lo...
(MobileMeAction): keyword = 'msg_device' def setup(self): self.parser.add_argument('-D', '--device', dest='device', help='Device ID', metavar='DEVICE') self.parser.add_argument('-a', '--alarm', dest='alarm', action='store_true', help='Play a sound for 2 minutes with this message') self....
MsgDeviceAction
identifier_name
mobileme.py
Service class MobileMe(WebService): loginform_url = 'https://auth.me.com/authenticate' loginform_data = { 'service': 'account', 'ssoNamespace': 'primary-me', 'reauthorize': 'Y', 'returnURL': 'aHR0cHM6Ly9zZWN1cmUubWUuY29tL2FjY291bnQv', } loginform_id = 'LoginForm' lo...
class LocateDeviceAction(MobileMeAction): keyword = 'locate_device' def setup(self): self.parser.add_argument('-D', '--device', dest='device', help='Device ID', metavar='DEVICE') def main(self): m = MobileMe(self.args.m_user, self.args.m_pass) kwargs = {'device_id': self.args.de...
keyword = 'msg_device' def setup(self): self.parser.add_argument('-D', '--device', dest='device', help='Device ID', metavar='DEVICE') self.parser.add_argument('-a', '--alarm', dest='alarm', action='store_true', help='Play a sound for 2 minutes with this message') self.parser.add_argument('m...
identifier_body
MembersComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Member } from './Member'; import { MemberService } from './MemberService'; @Component({ moduleId: module.id, selector: 'app-members', templateUrl: '/templates/home/members', styleUrls...
onMemberEdit(member: Member): void { this._router.navigate([member.userName], { relativeTo: this._route }); } refreshMembers(): void { this._memberService.getAll().subscribe( (members: Member[]) => this.members = members, () => console.error('Members acquisition fail...
this._memberService.delete(member.userName).subscribe( () => { const index = this.members.indexOf(member); if (index === -1) return; this.members.splice(index, 1); setTimeout(this.refreshMembers(), 100); }, () =...
identifier_body
MembersComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Member } from './Member'; import { MemberService } from './MemberService'; @Component({ moduleId: module.id, selector: 'app-members', templateUrl: '/templates/home/members', styleUrls...
mplements OnInit { members: Member[]; constructor( private _memberService: MemberService, private _route: ActivatedRoute, private _router: Router ) { } ngOnInit(): void { this.refreshMembers(); } onMemberDelete(member: Member): void { this._memberServi...
mbersComponent i
identifier_name
MembersComponent.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Member } from './Member'; import { MemberService } from './MemberService'; @Component({
export class MembersComponent implements OnInit { members: Member[]; constructor( private _memberService: MemberService, private _route: ActivatedRoute, private _router: Router ) { } ngOnInit(): void { this.refreshMembers(); } onMemberDelete(member: Member): v...
moduleId: module.id, selector: 'app-members', templateUrl: '/templates/home/members', styleUrls: ['MembersComponent.css'] })
random_line_split
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the ratin...
/// Returns the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let elo_ranking = EloRanking::new(32); /// assert_eq!(32, elo_ranking.get_k_factor()); /// ``` pub fn get_k_factor(&self) -> usize { return self.k_factor; } /// Internal me...
{ self.k_factor = k; }
identifier_body
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the ratin...
return EloRanking { k_factor: k, } } /// Change the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let mut elo_ranking = EloRanking::new(32); /// elo_ranking.set_k_factor(25); /// ``` pub fn set_k_factor(&mut self, k: usi...
/// ``` pub fn new(k: usize) -> EloRanking {
random_line_split
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the ratin...
<T: Elo>(player_one: &T, player_two: &T) -> f32 { return 1.0f32 / (1.0f32 + 10f32.powf( (player_two.get_rating() - player_one.get_rating()) / 400f32 )); } /// EloRanking. pub struct EloRanking { k_factor: usize, } impl EloRanking { /// Create a new Elo ranking system. /// /// # Example...
expected_rating
identifier_name
cmdline.py
#!/usr/bin/env python import click import json import re from icinga2_api.api import Api from icinga2_api import defaults VALID_ACTIONS = ['create', 'read', 'update', 'delete'] def validate_uri(ctx, param, value): if not value.startswith('/'): raise click.BadParameter('should begin with single /') return va...
click.echo(json.dumps(output_ds, indent=2)) ctx.exit(exit_code) if __name__ == '__main__': icinga2_api()
click.echo(click.style('OK: %s action succeeded' % kwargs['action'], fg='green'))
conditional_block
cmdline.py
#!/usr/bin/env python import click import json import re from icinga2_api.api import Api from icinga2_api import defaults VALID_ACTIONS = ['create', 'read', 'update', 'delete'] def validate_uri(ctx, param, value): if not value.startswith('/'): raise click.BadParameter('should begin with single /') return va...
(ctx, param, value): if value is None: return value try: return json.loads(value) except ValueError as e: raise click.BadParameter('should be valid json') @click.command() @click.option('-c', '--configfile', help='icinga2 API config file. Default: %s' % defaults.CONFIGFILE, ...
validate_data
identifier_name
cmdline.py
#!/usr/bin/env python import click import json import re from icinga2_api.api import Api from icinga2_api import defaults VALID_ACTIONS = ['create', 'read', 'update', 'delete'] def validate_uri(ctx, param, value): if not value.startswith('/'): raise click.BadParameter('should begin with single /') return va...
callback=validate_data, default=None) @click.pass_context def icinga2_api(ctx, **kwargs): """ https://github.com/saurabh-hirani/icinga2_api/blob/master/README.md """ if kwargs['verbose']: print 'args: %s' % kwargs obj = Api(**kwargs) kwargs['uri'] = re.sub("/{2,}", "/", kwarg...
@click.option('-C', '--cert-path', help='verify certificate path - not required if profile specified', default=None) @click.option('-v', '--verbose/--no-verbose', help='verbose. Default: false', default=False) @click.option('-d', '--data', help='json data to pass',
random_line_split
cmdline.py
#!/usr/bin/env python import click import json import re from icinga2_api.api import Api from icinga2_api import defaults VALID_ACTIONS = ['create', 'read', 'update', 'delete'] def validate_uri(ctx, param, value):
def validate_action(ctx, param, value): if value not in VALID_ACTIONS: raise click.BadParameter('should be in %s' % VALID_ACTIONS) return value def validate_data(ctx, param, value): if value is None: return value try: return json.loads(value) except ValueError as e: raise click.BadParameter...
if not value.startswith('/'): raise click.BadParameter('should begin with single /') return value
identifier_body
profile_extras.py
# This file is part of OpenHatch. # Copyright (C) 2010 Parker Phinney # Copyright (C) 2009, 2010 OpenHatch, Inc. # Copyright (C) 2010 John Stumpo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Fou...
# In all cases, I guess we should just buckle up and move on with life. value = unicode(value, 'utf-8') re_capitalized_word = re.compile(r'([A-Z][a-z][a-z]+)', re.UNICODE) words = re_capitalized_word.split(value) re_too_many_letters_in_a_row = re.compile(r'([\w]{%d}|[.\_^/])' % max_word...
logging.warn("Wanted %r to be unicode. Instead it's %s. Moving on with life." % (value, type(value)))
conditional_block
profile_extras.py
# This file is part of OpenHatch. # Copyright (C) 2010 Parker Phinney # Copyright (C) 2009, 2010 OpenHatch, Inc. # Copyright (C) 2010 John Stumpo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Fou...
@register.filter def prepend_http_if_necessary(value): """If someone makes "www.example.org" their homepage, then we need to prepend "http://" so it doesn't link to https://openhatch.org/people/username/www.example.org. This template filter prepends that.""" parsed = urlparse(value) if not parsed.scheme: ...
if type(value) == str: # Django 2.6 sometimes gives us the empty string as '', not u''. # Are there other cases where we do get a byte string, not a Unicode string? if value != '': logging.warn("Wanted %r to be unicode. Instead it's %s. Moving on with life." % (value, type(value))) ...
identifier_body
profile_extras.py
# This file is part of OpenHatch. # Copyright (C) 2010 Parker Phinney # Copyright (C) 2009, 2010 OpenHatch, Inc. # Copyright (C) 2010 John Stumpo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Fou...
@register.filter def prepend_http_if_necessary(value): """If someone makes "www.example.org" their homepage, then we need to prepend "http://" so it doesn't link to https://openhatch.org/people/username/www.example.org. This template filter prepends that.""" parsed = urlparse(value) if not parsed.scheme: ...
broken_words += re_too_many_letters_in_a_row.split(word) broken_words = filter(lambda x: x, broken_words) return "<wbr />".join(broken_words)
random_line_split
profile_extras.py
# This file is part of OpenHatch. # Copyright (C) 2010 Parker Phinney # Copyright (C) 2009, 2010 OpenHatch, Inc. # Copyright (C) 2010 John Stumpo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Fou...
(value, arg): "Returns a boolean of whether the value is less than the argument" return value < int(arg) def gte(value, arg): "Returns a boolean of whether the value is greater than or equal to the argument" return value >= int(arg) def lte(value, arg): "Returns a boolean of whether the value is l...
lt
identifier_name
fronted_index.js
function filterStatus(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status !== filter; }); return filtered; } function getStatus(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status === filter; }); return filtered; ...
}); $filters.on('click', function(event) { event.preventDefault(); showAllResult(); displayFiltered($(this).data("filter")); }); function countStatus(filterString){ var count = getStatus(filterString).length; return count; } $("#showAll").on('click', function(e){ e.preventDefault(); showAllRes...
$.each($filters, function(index, val) { var text = $(this).text(); text += "(" + countStatus(this.dataset.filter) + ")"; $(this).text(text);
random_line_split
fronted_index.js
function filterStatus(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status !== filter; }); return filtered; } function getStatus(filter)
function showAllResult(){ $("td").parent().show(); } function displayFiltered(filterString){ var filtered = filterStatus(filterString); $(filtered).parent().hide(); } var $filters = $('.filters'); $.each($filters, function(index, val) { var text = $(this).text(); text += "(" + countStatus(this.datase...
{ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status === filter; }); return filtered; }
identifier_body
fronted_index.js
function
(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status !== filter; }); return filtered; } function getStatus(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status === filter; }); return filtered; } function showAllRe...
filterStatus
identifier_name
0001_initial.py
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [] operations = [ migrations.CreateModel( fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.CharField(max_length=255),), ('email', models.EmailField(max_length=75),), ('message', models.TextField(),), (...
identifier_body
0001_initial.py
# encoding: utf8 from django.db import models, migrations class
(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.CharField(max_length=255),), ('email', models.EmailField(max_length=75),), ('...
Migration
identifier_name
0001_initial.py
# encoding: utf8 from django.db import models, migrations
class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.CharField(max_length=255),), ('email', models.EmailField(max_...
random_line_split
data-importer.py
#!/usr/bin/env python import sys, json, psycopg2, argparse parser = argparse.ArgumentParser(description='Imports word data into the taboo database.') parser.add_argument('--verified', dest='verified', action='store_true', help='include if these words are verified as good quality') parser.add_argument('--source', dest=...
print e cur.close() conn.close() print 'Inserted ' + str(count) + ' words'
random_line_split
data-importer.py
#!/usr/bin/env python import sys, json, psycopg2, argparse parser = argparse.ArgumentParser(description='Imports word data into the taboo database.') parser.add_argument('--verified', dest='verified', action='store_true', help='include if these words are verified as good quality') parser.add_argument('--source', dest=...
count = count + 1 except Exception as e: print e cur.close() conn.close() print 'Inserted ' + str(count) + ' words'
prohibited_count = prohibited_count + 1 cur.execute("INSERT INTO prohibited_words (wid, word, rank) VALUES(%s, %s, %s)", (wordid, prohibited, prohibited_count))
conditional_block
borrowck-pat-reassign-binding.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } ...
main
identifier_name
borrowck-pat-reassign-binding.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x...
identifier_body
borrowck-pat-reassign-binding.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred.
random_line_split
borrowck-pat-reassign-binding.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
{ // Note: on this branch, no borrow has occurred. x = Some(0); }
conditional_block
config.js
var INSTALLED={ "keys":["G/Town Roads","Caribbean","Guyana","World","Iceland","Greenland"], "Caribbean":{ "path":"./static/ggmc/data/caribbean/", "bbox":[-90.,-2.,-53.,30.], "center":[-71.5,14.5], "color":"rgba(255,255,0,0)", "fill":"rgba(0,100,40,0)", "width":2, "polygon_sources":[ {"filename":"cari...
"gpx_sources":[] }, "World":{ "path":"./static/ggmc/data/world/", "bbox":[-160,-60,100,60], "center":[0,20], "color":"rgba(255,0,0,0)", "fill":"rgba(0,100,0,0.1)", "width":0, "polygon_sources":[ {"filename":"world_borders.geojson","color":"rgba(0,255,0,1)","fi...
"polygon_sources":[], "point_sources":[], "line_sources":[],
random_line_split
lexical-scope-in-while.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// debugger:finish // debugger:print x // check:$13 = 2 // debugger:continue fn main() { let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope...
// check:$12 = 102 // debugger:continue
random_line_split
lexical-scope-in-while.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); ...
main
identifier_name
lexical-scope-in-while.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
sentinel(); let x = -987; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
{ let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz();
identifier_body
watchdog_of_wxgzh.py
#!/usr/bin/env python # coding:utf-8 # environ: python3.6 32bit # code by shuichon ''' V3.2,优化了执行流程和操作的简易性,修补了几个bug ''' from urllib import request, parse from bs4 import BeautifulSoup import re, json, sys def get_warn(soup): ''' 频繁访问时,搜狗会需要二次验证,判断是否需要二次验证 ''' warn = soup.find_all('p', class_='ip...
字的公众号,默认返回第一个 | | -gnum : 可选参数,从结果中取gnum个公众号,默认1 | | -key : 可选参数,搜索1个公众号,返回近10篇文章中,包含key的文章URL | | -kws : 内容识别关键字,查找包含kws的公众号文章, | | -gnum : 可选参数,在结果中取gnum个公众号,默认1 | ============================================================...
print(version) elif option == 'h': print(''' ================================================================= | 使用说明: | | 参数说明: | | -v : 当前版本 | ...
identifier_body
watchdog_of_wxgzh.py
#!/usr/bin/env python # coding:utf-8 # environ: python3.6 32bit # code by shuichon ''' V3.2,优化了执行流程和操作的简易性,修补了几个bug ''' from urllib import request, parse from bs4 import BeautifulSoup import re, json, sys def get_warn(soup): ''' 频繁访问时,搜狗会需要二次验证,判断是否需要二次验证 ''' warn = soup.find_all('p', class_='ip...
conditional_block
watchdog_of_wxgzh.py
#!/usr/bin/env python # coding:utf-8 # environ: python3.6 32bit # code by shuichon ''' V3.2,优化了执行流程和操作的简易性,修补了几个bug ''' from urllib import request, parse from bs4 import BeautifulSoup import re, json, sys def get_warn(soup): ''' 频繁访问时,搜狗会需要二次验证,判断
''' warn = soup.find_all('p', class_='ip-time-p') return len(warn) def get_gzh_lists(keys, gzh_num=1): """ 根据关键字keys,搜索公众号,未登录搜狗情况下,最多搜索10页,共计100个公众号。 gzh_num为从搜索结果中提取多少个公众号,数组gzh_list,内容为公众号列表 """ gzh_lists = [] m = 1 while gzh_num > 0: pages_url = "http://weixin.sogou.com/weixin?query="...
是否需要二次验证
identifier_name
watchdog_of_wxgzh.py
#!/usr/bin/env python # coding:utf-8 # environ: python3.6 32bit # code by shuichon ''' V3.2,优化了执行流程和操作的简易性,修补了几个bug ''' from urllib import request, parse from bs4 import BeautifulSoup import re, json, sys def get_warn(soup): ''' 频繁访问时,搜狗会需要二次验证,判断是否需要二次验证 ''' warn = soup.find_all('p', class_='ip...
please input '-h' behind the script.''') else: print('''Unknown option ! please input '-h' behind the script.''') else: print('Nothing done!')
random_line_split
test_spilling.py
# Copyright (c) 2014 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
@pytest.mark.execute_serially @CustomClusterTestSuite.with_args( impalad_args="--read_size=200000", catalogd_args="--load_catalog_in_background=false") def test_spilling(self, vector): new_vector = deepcopy(vector) # remove this. the test cases set this explicitly. del new_vector.get_value...
# Reduce the IO read size. This reduces the memory required to trigger spilling.
random_line_split
test_spilling.py
# Copyright (c) 2014 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
@classmethod def setup_class(cls): cls._start_impala_cluster(['--impalad_args=--"read_size=270000"', 'catalogd_args="--load_catalog_in_background=false"']) super(CustomClusterTestSuite, cls).setup_class() def setup_method(self, method): # We don't need CustomClusterTestSuite.setup_method() ...
return 'targeted-stress'
identifier_body
test_spilling.py
# Copyright (c) 2014 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
(CustomClusterTestSuite): @classmethod def get_workload(self): return 'targeted-stress' @classmethod def setup_class(cls): cls._start_impala_cluster(['--impalad_args=--"read_size=270000"', 'catalogd_args="--load_catalog_in_background=false"']) super(CustomClusterTestSuite, cls).setup_class(...
TestSpillStress
identifier_name
test_spilling.py
# Copyright (c) 2014 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
class TestSpilling(CustomClusterTestSuite): @classmethod def get_workload(self): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestSpilling, cls).add_test_dimensions() cls.TestMatrix.clear_constraints() cls.TestMatrix.add_dimension(create_parquet_dimension('tpch')...
self.run_test_case('agg_stress', vector)
conditional_block
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod s...
{ MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) { state_machine.add_state(MainMenuStateID as isize, Box::new(main_men...
State
identifier_name
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod s...
state_machine.add_state(MainMenuStateID as isize, Box::new(main_menu::MainMenu::new(loader, ctx))); state_machine.set_default_state(MainMenuStateID as isize); state_machine.add_state(SlotSelectStateID as isize, Box::new(slot_select_menu::SlotSelectMenu::new(loader, ctx))); state_machine.add_state(Game...
random_line_split
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod s...
pub enum State { MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) { state_machine.add_state(MainMenuStateID as isize, B...
{ let obelix_font = graphics::Font::new_from_file("res/font/AlegreyaSansSC-Light.ttf").unwrap(); loader.add_resource("MenuFont".to_string(), Resource::Font(obelix_font)); }
identifier_body
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import * as moment from 'moment'; import { AlertService } from '../core/local-services/alert.service'; import { AccountsTotalizationsReportService } from '../services/accounts-totalizations-report.service'; import { AccountsTotalizationsReport } from '../model/accounts...
(totals: AccountsTotalizationsReport): any[] { let data = []; for(let t of totals.accountsTotalizations) { if(t.accountLevel == this.level) { let item = { "name": t.accountDescription, "series": [ {"name": "1st Period", "value": t.total}, {"name": "2n...
wrap
identifier_name
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import * as moment from 'moment'; import { AlertService } from '../core/local-services/alert.service'; import { AccountsTotalizationsReportService } from '../services/accounts-totalizations-report.service'; import { AccountsTotalizationsReport } from '../model/accounts...
} return data; } }
{ let item = { "name": t.accountDescription, "series": [ {"name": "1st Period", "value": t.total}, {"name": "2nd Period", "value": t.total} //TODO ] } data.push(item); }
conditional_block
dashboard.component.ts
import { AlertService } from '../core/local-services/alert.service'; import { AccountsTotalizationsReportService } from '../services/accounts-totalizations-report.service'; import { AccountsTotalizationsReport } from '../model/accounts-totalizations-report.model'; import {NgxChartsModule} from '@swimlane/ngx-charts'; i...
import { Component, OnInit } from '@angular/core'; import * as moment from 'moment';
random_line_split
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import * as moment from 'moment'; import { AlertService } from '../core/local-services/alert.service'; import { AccountsTotalizationsReportService } from '../services/accounts-totalizations-report.service'; import { AccountsTotalizationsReport } from '../model/accounts...
ngOnInit() { let filters = new AccountsTotalizationsReport(); filters.filterInitialDate = this.period1ini; filters.filterFinalDate = this.period1end; this.service.generateReport(filters).subscribe(totals => { if(totals.response.hasException) { this.alertService.error(totals.response.ex...
{ }
identifier_body
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); } loop { for c in &CHANNELS { match capture.capture(*c) { Ok(snapshot) => { iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); } E...
let tim2 = TIM2.access(prio, thr);
random_line_split
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
// IDLE LOOP fn idle(ref prio: P0, ref thr: T0) -> ! { const CHANNELS: [Channel; 4] = [Channel::_1, Channel::_2, Channel::_3, Channel::_4]; let itm = ITM.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c);...
{ let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); }
identifier_body
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); } // IDLE LOOP fn idle(ref prio: P0, ref thr: ...
init
identifier_name
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(e)) => panic!("{:?}", e), } } } } // TASKS tasks!(stm32f103xx, {});
{ iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); }
conditional_block
Export_Count_Station_Location.py
''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Fou...
''' import inro.modeller as _m import csv import traceback as _traceback from contextlib import contextmanager from contextlib import nested _mm = _m.Modeller() net =_mm.scenario.get_network() _util = _mm.module('tmg.common.utilities') _tmgTPB = _mm.module('tmg.common.TMG_tool_page_builder') class ExportCou...
0.0.1 Created 0.1.1 Created on 2015-03-13 by David King
random_line_split
Export_Count_Station_Location.py
''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Fou...
def _Execute(self): with _m.logbook_trace(name="{classname} v{version}".format(classname=(self.__class__.__name__), version=self.version), attributes=self._GetAtts()): lines =[] for link in net.links(): ...
self.tool_run_msg = "" self.TRACKER.reset() try: self._Execute() except Exception as e: self.tool_run_msg = _m.PageBuilder.format_exception( e, _traceback.format_exc()) raise self.tool_run_msg = _m.PageBuilder.format_i...
identifier_body
Export_Count_Station_Location.py
''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Fou...
with open(self.CordonExportFile, 'w') as writer: writer.write("Countpost ID ,Link (i-node j-node)") for line in lines: line = [str(c) for c in line] writer.write("\n" + ','.join(line)) ...
lines.append((link['@stn1'],link.id))
conditional_block
Export_Count_Station_Location.py
''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Fou...
(self, Scen, TruthTable): self.tool_run_msg = "" self.TRACKER.reset() self.Scenario = Scen self.CordonTruthTable = TruthTable try: self._Execute() except Exception as e: self.tool_run_msg = _m.PageBuilder.format_exception( ...
__call__
identifier_name
list-question.client.js
'use strict'; angular.module('applicant-test').controller('ApplicantTestController', ['$scope', '$stateParams', '$location', 'Authentication', 'Questions', '$http', function($scope, $stateParams, $location, Authentication, Questions, $http ) { $scope.authentication =Authentication; $sco...
// $scope.findOne = function() { // var url = '/test/' + $stateParams.testId; // console.log('Getting stateParams'); // console.log($stateParams); // $http.get(url).success(function(response) { // $scope.questions = response; // c...
};
random_line_split
RaidEmulator.ts
import { UnreachableCode } from '../../../../resources/not_reached'; import { RaidbossOptions } from '../../raidboss_options'; import EventBus from '../EventBus'; import RaidEmulatorPopupText from '../overrides/RaidEmulatorPopupText'; import AnalyzedEncounter from './AnalyzedEncounter'; import Encounter from './Encoun...
(timeOffset: number): Promise<void> { if (!this.currentEncounter || !this.currentEncounter.encounter) throw new UnreachableCode(); const seekTimestamp = this.currentEncounter.encounter.startTimestamp + timeOffset; await this.seekTo(seekTimestamp); } async seekTo(seekTimestamp: number): Promise<v...
seek
identifier_name
RaidEmulator.ts
import { UnreachableCode } from '../../../../resources/not_reached'; import { RaidbossOptions } from '../../raidboss_options'; import EventBus from '../EventBus'; import RaidEmulatorPopupText from '../overrides/RaidEmulatorPopupText'; import AnalyzedEncounter from './AnalyzedEncounter'; import Encounter from './Encoun...
addEncounter(encounter: Encounter): void { this.encounters.push(encounter); } private setCurrent(enc: Encounter): void { // If language was autodetected from the encounter, set the current ParserLanguage // appropriately if (enc.language) this.options.ParserLanguage = enc.language; t...
{ super(); this.options = options; this.encounters = []; }
identifier_body
RaidEmulator.ts
import { UnreachableCode } from '../../../../resources/not_reached'; import { RaidbossOptions } from '../../raidboss_options'; import EventBus from '../EventBus'; import RaidEmulatorPopupText from '../overrides/RaidEmulatorPopupText'; import AnalyzedEncounter from './AnalyzedEncounter'; import Encounter from './Encoun...
await this.dispatch('postSeek', seekTimestamp); await this.dispatch('tick', this.currentLogTime, this.lastLogLineTime); if (playing) this.play(); } async tick(): Promise<void> { if ( this.currentLogLineIndex === undefined || !this.currentEncounter || this.lastTickTime === undefine...
await this.dispatch('emitLogs', { logs: logs }); await this.dispatch('midSeek', logs.pop()); }
random_line_split
test_voxel.py
sticks = _check_directions(angles) ref_vec1 = (np.sin(np.pi*the1/180) * np.cos(np.pi*phi1/180), np.sin(np.pi*the1/180) * np.sin(np.pi*phi1/180), np.cos(np.pi*the1/180)) ref_vec2 = (np.sin(np.pi*the2/180) * np.cos(np.pi*phi2/180), np.sin(np.pi*the2/180) * np.sin(n...
def test_sticks_and_ball(): d = 0.0015 S, sticks = sticks_and_ball(gtab, d=d, S0=1, angles=[(0, 0), ], fractions=[100], snr=None) assert_array_equal(sticks, [[0, 0, 1]]) S_st = SingleTensor(gtab, 1, evals=[d, 0, 0], evecs=[[0, 0, 0], ...
np.cos(np.pi*the2/180)) assert_array_almost_equal(sticks, [ref_vec1, ref_vec2])
random_line_split
test_voxel.py
sticks = _check_directions(angles) ref_vec1 = (np.sin(np.pi*the1/180) * np.cos(np.pi*phi1/180), np.sin(np.pi*the1/180) * np.sin(np.pi*phi1/180), np.cos(np.pi*the1/180)) ref_vec2 = (np.sin(np.pi*the2/180) * np.cos(np.pi*phi2/180), np.sin(np.pi*the2/180) * np.sin(n...
# compute global DT D = np.zeros((3, 3)) for i in range(len(frac)): D = D + frac[i]*mD[i] # compute voxel's MD MD = (D[0][0] + D[1][1] + D[2][2]) / 3 # Reference dictionary with the 15 independent elements. # Note: The multiplication of the indexes (i+1) * (j+1) * (k+1) * (l+1) ...
R = all_tensor_evecs(sticks[i]) mD[i] = np.dot(np.dot(R, np.diag(mevals[i])), R.T)
conditional_block
test_voxel.py
: kurtosis_element(mD, frac, 0, 0, 0, 0), 16: kurtosis_element(mD, frac, 1, 1, 1, 1), 81: kurtosis_element(mD, frac, 2, 2, 2, 2), 2: kurtosis_element(mD, frac, 0, 0, 0, 1), 3: kurtosis_element(mD, frac, 0, 0, 0, 2), 8: kurtosis_element(mD, frac, 0, 1...
""" Testing DKI simulations of a crossing fiber """ # two fiber not aligned to planes x = 0, y = 0, or z = 0 mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087], [0.00099, 0, 0], [0.00226, 0.00087, 0.00087]]) angles = [(80, 10), (80, 10), (20, 30), (20, 30)] fie = ...
identifier_body
test_voxel.py
(): # Testing spherical angles for two principal coordinate axis angles = [(0, 0)] # axis z sticks = _check_directions(angles) assert_array_almost_equal(sticks, [[0, 0, 1]]) angles = [(0, 90)] # axis z again (phi can be anything it theta is zero) sticks = _check_directions(angles) assert_a...
test_check_directions
identifier_name
schema.rs
diesel::table! { comments (id) { id -> Int4,
body -> Text, created_at -> Timestamp, updated_at -> Timestamp, } } diesel::table! { posts (id) { id -> Int4, user_id -> Int4, title -> Text, body -> Text, created_at -> Timestamp, updated_at -> Timestamp, published_at -> Nullable<...
user_id -> Int4, post_id -> Int4,
random_line_split
ddsmoothmenu.js
forums/showthread.php?t=39177&highlight=smooth //** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items. //** May 1st, 09" (v1.3): //** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v' //** 2) In IE6, shadows are now al...
buildmenu:function($, setting){ var smoothmenu=ddsmoothmenu var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL $mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu" var $headers=$mainmenu.find("ul").parent() $headers.hover( function(e){ $(this).children('a:eq(0)').addCla...
random_line_split
ddsmoothmenu.js
forums/showthread.php?t=39177&highlight=smooth //** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items. //** May 1st, 09" (v1.3): //** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v' //** 2) In IE6, shadows are now al...
this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'}) //insert shadow DIV and set it to parent node for the next shadow div } $curobj.hover( function(e){ var $targetul=$su...
{ var $parentLi=$curobj.parents("li:eq(0)") $parentshadow=$parentLi.get(0).$shadow }
conditional_block
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] funct...
}
{ let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) }
identifier_body
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] funct...
A: AsyncWrite + Unpin + ?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) } }
impl<A> Future for Flush<'_, A> where
random_line_split
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] funct...
<A>(a: &mut A) -> Flush<'_, A> where A: AsyncWrite + Unpin + ?Sized, { Flush { a, _pin: PhantomPinned, } } impl<A> Future for Flush<'_, A> where A: AsyncWrite + Unpin + ?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Out...
flush
identifier_name
D1.py
#!/usr/bin/python # # Problem: Endless Knight # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out # Comments: OK for large, but may time out on small. from itertools import * MOD = 10007 # Precompute factorial table mod MOD fact = [1] * MOD for i in xrange(1, MOD): fact[i]...
return total for i in range(input()): print "Case #%d: %d" % (i+1, compute())
points = [[0,0]] + [rocks[j] for j in perm] + [[h,w]] # number of paths going through all points prod = 1 for j in range(1, len(points)): dh = points[j][0] - points[j-1][0] dw = points[j][1] - points[j-1][1] pro...
conditional_block
D1.py
#!/usr/bin/python # # Problem: Endless Knight # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out # Comments: OK for large, but may time out on small. from itertools import * MOD = 10007 # Precompute factorial table mod MOD fact = [1] * MOD for i in xrange(1, MOD): fact[i]...
total = 0 for num in range(r+1): for perm in permutations(range(r), num): # verify increasing property of permutation inc = True for i in range(num): if rocks[perm[i]] == None: inc = False break ...
h, w, r = map(int, raw_input().split()) rocks = [map(int, raw_input().split()) for i in range(r)] if (h+w-2)%3 != 0: return 0 # normalize rock coordinates h, w = h-1-(h+w-2)/3, w-1-(h+w-2)/3 for i in range(r): row, col = rocks[i] if (row+col-2)%3 != 0: rock...
identifier_body
D1.py
#!/usr/bin/python # # Problem: Endless Knight # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out # Comments: OK for large, but may time out on small. from itertools import * MOD = 10007 # Precompute factorial table mod MOD fact = [1] * MOD for i in xrange(1, MOD): fact[i]...
prod %= MOD n /= MOD k /= MOD return prod def compute(): h, w, r = map(int, raw_input().split()) rocks = [map(int, raw_input().split()) for i in range(r)] if (h+w-2)%3 != 0: return 0 # normalize rock coordinates h, w = h-1-(h+w-2)/3, w-1-(h...
while n > 0: prod *= choose(n%MOD, k%MOD)
random_line_split