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 |
|---|---|---|---|---|
literals.rs | fn main() { | // 试一试 ^ 尝试将 `1i32` 改为 `1u32`,体会为什么类型声明这么重要
// 短路的布尔类型的逻辑运算
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
// 位运算符
println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
println!("0011 OR 0101 is {:0... | // 整数相加
println!("1 + 2 = {}", 1u32 + 2);
// 整数相减
println!("1 - 2 = {}", 1i32 - 2); | random_line_split |
literals.rs | fn main() | // 使用下划线改善数字的可读性!
println!("One million is written as {}", 1_000_000u32);
}
| {
// 整数相加
println!("1 + 2 = {}", 1u32 + 2);
// 整数相减
println!("1 - 2 = {}", 1i32 - 2);
// 试一试 ^ 尝试将 `1i32` 改为 `1u32`,体会为什么类型声明这么重要
// 短路的布尔类型的逻辑运算
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
... | identifier_body |
feature-gate-cfg-target-vendor.rs | // Copyright 2015 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 ... | (u64, u64);
#[cfg(not(any(all(target_vendor = "x"))))] //~ ERROR `cfg(target_vendor)` is experimental
fn foo() {}
fn main() {
cfg!(target_vendor = "x");
//~^ ERROR `cfg(target_vendor)` is experimental and subject to change
}
| Foo | identifier_name |
feature-gate-cfg-target-vendor.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
config_manager.py | , Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARR... |
else:
self.modify_repo()
def modify_repo(self):
""" process --set-enabled, --set-disabled and --setopt options """
sbc = self.base.conf
modify = []
if hasattr(self.cli, 'main_setopts') and self.cli.main_setopts:
modify = self.cli.main_setopts.items
... | self.add_repo() | conditional_block |
config_manager.py | , Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARR... | url = RE_SLASH.sub("_", url)
url = RE_BEGIN.sub("", url)
url = RE_FINAL.sub("", url)
# limit length of url
if len(url) > 250:
parts = url[:185].split('_')
lastindex = 185-len(parts[-1])
csum = dnf.yum.misc.Checksums([' | """Return a filename suitable for the filesystem
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
try:
if RE_SCHEME.match(url):
if dnf.pycomp.PY3:
url = url.encode('idna').decode('utf-8')
else:
... | identifier_body |
config_manager.py | Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY ... | self.modify_repo()
def modify_repo(self):
""" process --set-enabled, --set-disabled and --setopt options """
sbc = self.base.conf
modify = []
if hasattr(self.cli, 'main_setopts') and self.cli.main_setopts:
modify = self.cli.main_setopts.items
if not ... | else: | random_line_split |
config_manager.py | , Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARR... | (self, base, cli):
super(ConfigManager, self).__init__(base, cli)
self.base = base
self.cli = cli
if self.cli is not None:
self.cli.register_command(ConfigManagerCommand)
class ConfigManagerCommand(dnf.cli.Command):
aliases = ['config-manager']
summary = _('manage ... | __init__ | identifier_name |
test_quotation.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class | (unittest.TestCase):
def test_make_sales_order(self):
from erpnext.selling.doctype.quotation.quotation import make_sales_order
quotation = frappe.copy_doc(test_records[0])
quotation.insert()
self.assertRaises(frappe.ValidationError, make_sales_order, quotation.name)
quotation.submit()
sales_order = mak... | TestQuotation | identifier_name |
test_quotation.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
| sales_order.transaction_date = "2013-05-12"
sales_order.insert()
def test_create_quotation_with_margin(self):
from erpnext.selling.doctype.quotation.quotation import make_sales_order
from erpnext.selling.doctype.sales_order.sales_order \
import make_delivery_note, make_sales_invoice
rate_with_margin = f... | def test_make_sales_order(self):
from erpnext.selling.doctype.quotation.quotation import make_sales_order
quotation = frappe.copy_doc(test_records[0])
quotation.insert()
self.assertRaises(frappe.ValidationError, make_sales_order, quotation.name)
quotation.submit()
sales_order = make_sales_order(quotatio... | identifier_body |
test_quotation.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
def test_ma... |
if not item_code:
item_code = '_Test Item'
return {
'doctype': 'Quotation',
'customer': customer,
'items': [
{
'item_code': item_code,
'qty': 1,
'rate': 100
}
]
}
| customer = '_Test Customer' | conditional_block |
test_quotation.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
def test_ma... | sales_order.transaction_date = "2016-01-01"
sales_order.delivery_date = "2016-01-02"
sales_order.insert()
self.assertEquals(quotation.get("items")[0].rate, rate_with_margin)
sales_order.submit()
dn = make_delivery_note(sales_order.name)
self.assertEquals(quotation.get("items")[0].rate, rate_with_margi... | self.assertRaises(frappe.ValidationError, make_sales_order, quotation.name)
quotation.submit()
sales_order = make_sales_order(quotation.name)
sales_order.naming_series = "_T-Quotation-" | random_line_split |
issue-19135.rs | // Copyright 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-MIT or ... | <F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) {
f(LifetimeStruct(PhantomData));
}
| takes_hrtb_closure | identifier_name |
issue-19135.rs | // Copyright 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-MIT or ... | f(LifetimeStruct(PhantomData));
} | }
fn takes_hrtb_closure<F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) { | random_line_split |
issue-19135.rs | // Copyright 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-MIT or ... | {
f(LifetimeStruct(PhantomData));
} | identifier_body | |
node.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency between layout and
//! style.
use le... | use smallvec::VecLike;
use selectors::matching::DeclarationBlock;
pub use selectors::tree::{TNode, TElement};
use string_cache::{Atom, Namespace};
pub trait TElementAttributes {
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: VecLike<DeclarationBlock<Vec<PropertyDeclara... | use properties::PropertyDeclaration; | random_line_split |
unifont.rs | use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
fn main() {
let mut input = File::open("unifont.hex").unwrap();
let mut output = File::create("unifont.font").unwrap();
let mut count = 0;
for line_res in BufReader::new(input).lines() {
let line = line_res.unwrap();
let mut ... | count += 1;
}
} |
output.write(&data).unwrap();
| random_line_split |
unifont.rs | use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
fn | () {
let mut input = File::open("unifont.hex").unwrap();
let mut output = File::create("unifont.font").unwrap();
let mut count = 0;
for line_res in BufReader::new(input).lines() {
let line = line_res.unwrap();
let mut parts = line.split(":");
let num = u32::from_str_radix(parts.next().... | main | identifier_name |
unifont.rs | use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
fn main() | count += 1;
}
}
| {
let mut input = File::open("unifont.hex").unwrap();
let mut output = File::create("unifont.font").unwrap();
let mut count = 0;
for line_res in BufReader::new(input).lines() {
let line = line_res.unwrap();
let mut parts = line.split(":");
let num = u32::from_str_radix(parts.next().unw... | identifier_body |
closest-pair.rs | // Implements http://rosettacode.org/wiki/Closest-pair_problem
// We interpret complex numbers as points in the Cartesian plane, here.
// We also use the sweepline/plane sweep closest pairs algorithm
// (http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html) instead
// of the divide-and-conquer algorithm, sinc... | {
point: Point
}
impl PartialOrd for YSortedPoint {
fn partial_cmp(&self, other: &YSortedPoint) -> Option<Ordering> {
(self.point.im, self.point.re).partial_cmp(&(other.point.im, other.point.re))
}
}
impl Ord for YSortedPoint {
fn cmp(&self, other: &YSortedPoint) -> Ordering {
self.pa... | YSortedPoint | identifier_name |
closest-pair.rs | // Implements http://rosettacode.org/wiki/Closest-pair_problem
// We interpret complex numbers as points in the Cartesian plane, here.
// We also use the sweepline/plane sweep closest pairs algorithm
// (http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html) instead
// of the divide-and-conquer algorithm, sinc... | closest_distance_sqr = dist_sqr;
closest_distance = dist_sqr.sqrt();
}
}
}
// Insert point into strip
strip.insert(YSortedPoint { point: point.clone() });
}
Some(closest_pair)
}
#[cfg(not(test))]
pub fn main() {
l... | closest_pair = (point2, *point); | random_line_split |
directives.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive} from '@angular/core';
import {_MatMenuContentBase, _MatMenuTriggerBase, MAT_MENU_CONTENT} from '@a... | providers: [{provide: MAT_MENU_CONTENT, useExisting: MatMenuContent}],
})
export class MatMenuContent extends _MatMenuContentBase {} | export class MatMenuTrigger extends _MatMenuTriggerBase {}
/** Menu content that will be rendered lazily once the menu is opened. */
@Directive({
selector: 'ng-template[matMenuContent]', | random_line_split |
directives.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive} from '@angular/core';
import {_MatMenuContentBase, _MatMenuTriggerBase, MAT_MENU_CONTENT} from '@a... | extends _MatMenuContentBase {}
| MatMenuContent | identifier_name |
rhn_channel.py | #!/usr/bin/python
# Copyright: (c) Vincent Van de Kussen
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['pr... |
def unsubscribe_channels(channelname, client, session, sysname, sys_id):
channels = base_channels(client, session, sys_id)
channels.remove(channelname)
return client.system.setChildChannels(session, sys_id, channels)
def base_channels(client, session, sys_id):
basechan = client.channel.software.lis... | channels = base_channels(client, session, sys_id)
channels.append(channelname)
return client.system.setChildChannels(session, sys_id, channels) | identifier_body |
rhn_channel.py | #!/usr/bin/python
# Copyright: (c) Vincent Van de Kussen
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['pr... | (channelname, client, session, sysname, sys_id):
channels = base_channels(client, session, sys_id)
channels.append(channelname)
return client.system.setChildChannels(session, sys_id, channels)
def unsubscribe_channels(channelname, client, session, sysname, sys_id):
channels = base_channels(client, ses... | subscribe_channels | identifier_name |
rhn_channel.py | #!/usr/bin/python
# Copyright: (c) Vincent Van de Kussen
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['pr... | def get_systemid(client, session, sysname):
systems = client.system.listUserSystems(session)
for system in systems:
if system.get('name') == sysname:
idres = system.get('id')
idd = int(idres)
return idd
def subscribe_channels(channelname, client, session, sysname, s... | from ansible.module_utils.six.moves import xmlrpc_client
| random_line_split |
rhn_channel.py | #!/usr/bin/python
# Copyright: (c) Vincent Van de Kussen
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['pr... |
else:
subscribe_channels(channelname, client, session, systname, sys_id)
module.exit_json(changed=True, msg="Channel %s added" % channelname)
if state == 'absent':
if channelname not in chans:
module.exit_json(changed=False, msg="Not subs... | module.exit_json(changed=False, msg="Channel %s already exists" % channelname) | conditional_block |
box-of-array-of-drop-2.rs | // Copyright 2015 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that we ... | random_line_split | |
box-of-array-of-drop-2.rs | // Copyright 2015 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 ... | () -> D { panic!("Oh no"); }
let g = thread::spawn(|| {
let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]);
let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]);
let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]);
let _b4: Box<[D; 4]> = Box::new([D(13),... | die | identifier_name |
box-of-array-of-drop-2.rs | // Copyright 2015 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 g = thread::spawn(|| {
let _b1: Box<[D; 4]> = Box::new([D( 1), D( 2), D( 3), D( 4)]);
let _b2: Box<[D; 4]> = Box::new([D( 5), D( 6), D( 7), D( 8)]);
let _b3: Box<[D; 4]> = Box::new([D( 9), D(10), die(), D(12)]);
let _b4: Box<[D; 4]> = Box::new([D(13), D(14), D(15), D(16)]);
... | { panic!("Oh no"); } | identifier_body |
dfu.py | #!/usr/bin/env python
#
# dfu.py: Access USB DFU class devices
# Copyright (C) 2009 Black Sphere Technologies
# Copyright (C) 2012 Transition Robotics Inc.
# Written by Gareth McMullin <gareth@blacksphere.co.nz>
# Modified by Piotr Esden-Tempski <piotr@esden.net>
#
# This program is free software: you can redistribut... |
else:
print("Found %i devices." % len(devs))
for dfu in devs:
handle = dfu[0].open()
try:
man = handle.getString(dfu[0].iManufacturer, 30)
product = handle.getString(dfu[0].iProduct, 30)
serial = handle.getString(dfu[0].iSerialNumber, 40)
exc... | print("No devices found!")
exit(-1) | conditional_block |
dfu.py | #!/usr/bin/env python
#
# dfu.py: Access USB DFU class devices
# Copyright (C) 2009 Black Sphere Technologies
# Copyright (C) 2012 Transition Robotics Inc.
# Written by Gareth McMullin <gareth@blacksphere.co.nz>
# Modified by Piotr Esden-Tempski <piotr@esden.net>
#
# This program is free software: you can redistribut... | usb.RECIP_INTERFACE, DFU_DETACH,
None, value=wTimeout, index=self.index)
def download(self, wBlockNum, data):
self.handle.controlMsg(usb.ENDPOINT_OUT | usb.TYPE_CLASS |
usb.RECIP_INTERFACE, DFU_DNLOAD,
... | random_line_split | |
dfu.py | #!/usr/bin/env python
#
# dfu.py: Access USB DFU class devices
# Copyright (C) 2009 Black Sphere Technologies
# Copyright (C) 2012 Transition Robotics Inc.
# Written by Gareth McMullin <gareth@blacksphere.co.nz>
# Modified by Piotr Esden-Tempski <piotr@esden.net>
#
# This program is free software: you can redistribut... |
if __name__ == "__main__":
devs = finddevs()
if not devs:
print("No devices found!")
exit(-1)
else:
print("Found %i devices." % len(devs))
for dfu in devs:
handle = dfu[0].open()
try:
man = handle.getString(dfu[0].iManufacturer, 30)
pro... | devs = []
for bus in usb.busses():
for dev in bus.devices:
for conf in dev.configurations:
for ifaces in conf.interfaces:
for iface in ifaces:
if ((iface.interfaceClass == 0xFE) and
(iface.interfaceSubClass =... | identifier_body |
dfu.py | #!/usr/bin/env python
#
# dfu.py: Access USB DFU class devices
# Copyright (C) 2009 Black Sphere Technologies
# Copyright (C) 2012 Transition Robotics Inc.
# Written by Gareth McMullin <gareth@blacksphere.co.nz>
# Modified by Piotr Esden-Tempski <piotr@esden.net>
#
# This program is free software: you can redistribut... | (self, buf):
self.bStatus = buf[0]
self.bwPollTimeout = buf[1] + (buf[2]<<8) + (buf[3]<<16)
self.bState = buf[4]
self.iString = buf[5]
class dfu_device(object):
def __init__(self, dev, conf, iface):
self.dev = dev
self.conf = conf
self.iface = iface
... | __init__ | identifier_name |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... |
/// Construct a TimeSpan that started at `start` and ends at `end`.
pub fn from_start_and_end_systemtime(
start: &std::time::SystemTime,
end: &std::time::SystemTime,
) -> TimeSpan {
let start = Self::since_epoch(start);
let end = Self::since_epoch(end);
let duration = match end.checked_sub(s... | {
let start = Self::since_epoch(start);
let duration = Self::since_epoch(&std::time::SystemTime::now()) - start;
TimeSpan {
start: start.into(),
duration: duration.into(),
}
} | identifier_body |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | {
/// Duration since the UNIX_EPOCH
pub start: Duration,
/// Duration since `start`
pub duration: Duration,
}
impl TimeSpan {
fn since_epoch(time: &std::time::SystemTime) -> std::time::Duration {
time
.duration_since(std::time::UNIX_EPOCH)
.expect("Surely you're not before the unix epoch?")
... | TimeSpan | identifier_name |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | }
}
/// A timespan
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
pub struct TimeSpan {
/// Duration since the UNIX_EPOCH
pub start: Duration,
/// Duration since `start`
pub duration: Duration,
}
impl TimeSpan {
fn since_epoch(time: &std::time::SystemTime) -> std::time::Duration {
time
... |
impl From<Duration> for std::time::Duration {
fn from(duration: Duration) -> std::time::Duration {
std::time::Duration::new(duration.secs, duration.nanos) | random_line_split |
helpers.py | check if a previous building object in the db exists
if buildings.exists():
bldg = buildings[0]
print "Already had: %s" % bldg.address
else:
#if not,
#CREATE A NEW BUILDING OBJECT HERE
#c... | make_row | identifier_name | |
helpers.py | unit, make=True)
"""
full_city = '%s, IN, USA' % city.name
match = False
#find an address to use
for geo_source in location.sources:
if not match:
source_list = location.get_source(geo_source)
if len(source_list) and source_list[0]['place'] and source_list[0]['place'... |
if no_units:
bldg.number_of_units = no_units
if sqft:
bldg.sqft = sqft
bldg.save()
print "Created new building: %s" % bldg.address
return bldg
else:
... | bldg.type = bldg_type | conditional_block |
helpers.py | m = rg.search(text)
if m:
csv1=m.group(1)
print "PO BOX MATCH: ("+csv1+")"+"\n"
print text
parts = text.split(csv1)
#name = m.group(0)
name = parts[0]
#IndexError: no such group
#address = m.group(1) + m.group(2)
address = m.group... | po_box='( P\\.O\\. | P O | PO )'
rg = re.compile(po_box,re.IGNORECASE|re.DOTALL) | random_line_split | |
helpers.py | # out.write(location.make_row())
print match_tallies
exit()
class Location(object):
"""
hold geolocation data associated with a specific address
making an object to help with processing results consistently
"""
def __init__(self, dictionary={}, sources=None):
"""
h... | self.google = geocoders.GoogleV3()
#doesn't look like yahoo supports free api any longer:
#http://developer.yahoo.com/forum/General-Discussion-at-YDN/Yahoo-GeoCode-404-Not-Found/1362061375511-7faa66ba-191d-4593-ba63-0bb8f5d43c06
#yahoo = geocoders.Yahoo('PCqXY9bV34G8P7jzm_9JeuOfIviv37mvfyTvA62Ro... | identifier_body | |
10-api-mock.test.ts | /**
* @jest-environment jsdom
*/
import { loadIcons, iconExists } from '../../dist';
import { mockAPIData } from '@iconify/core/lib/api/modules/mock';
import { provider, nextPrefix } from './load';
describe('Testing fake API', () => {
test('using fake API to load icon', (done) => {
const prefix = nextPrefix();
... | provider,
prefix,
name,
},
]);
expect(missing).toMatchObject([]);
expect(pending).toMatchObject([]);
done();
});
});
}); | loadIcons([iconName], (loaded, missing, pending) => {
expect(loaded).toMatchObject([
{ | random_line_split |
solutions.py |
__problem_title__ = "Comfortable distance"
__problem_url___ = "https://projecteuler.net/problem=364"
__problem_description__ = "There are seats in a row. people come after each other to fill the " \
"seats according to the following rules: We can verify that T(10) = " \
... | s = Solution()
print(s.solution1())
s.time_solutions() | conditional_block | |
solutions.py |
__problem_title__ = "Comfortable distance"
__problem_url___ = "https://projecteuler.net/problem=364"
__problem_description__ = "There are seats in a row. people come after each other to fill the " \
"seats according to the following rules: We can verify that T(10) = " \
... | ():
pass
@staticmethod
def time_solutions():
setup = 'from __main__ import Solution'
print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1))
if __name__ == '__main__':
s = Solution()
print(s.solution1())
s.time_solutions()
| solution1 | identifier_name |
solutions.py |
__problem_title__ = "Comfortable distance"
__problem_url___ = "https://projecteuler.net/problem=364"
__problem_description__ = "There are seats in a row. people come after each other to fill the " \
"seats according to the following rules: We can verify that T(10) = " \
... |
if __name__ == '__main__':
s = Solution()
print(s.solution1())
s.time_solutions()
| @staticmethod
def solution1():
pass
@staticmethod
def time_solutions():
setup = 'from __main__ import Solution'
print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1)) | identifier_body |
solutions.py | __problem_title__ = "Comfortable distance"
__problem_url___ = "https://projecteuler.net/problem=364"
__problem_description__ = "There are seats in a row. people come after each other to fill the " \
"seats according to the following rules: We can verify that T(10) = " \
... | class Solution():
@staticmethod
def solution1():
pass
@staticmethod
def time_solutions():
setup = 'from __main__ import Solution'
print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1))
if __name__ == '__main__':
s = Solution()
print(s.solut... |
import timeit
| random_line_split |
mock_compiler_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {MockDirectory, setup} from '../aot/test_util';
import {compile, expectEmit} from './mock_compile';
describ... | const files = {
app: {
'hello.component.ts': `
import {Component, Input} from '@angular/core';
@Component({template: 'Hello {{name}}! Your name as {{name.length}} characters'})
export class HelloComponent {
@Input() name: string = 'world';
... | });
});
describe('expecting emitted output', () => {
it('should be able to find a simple expression in the output', () => { | random_line_split |
eio.rs | // Eio Rust bindings for EFL.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library 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 the License, or (at... | () -> int {
unsafe { eio_shutdown() as int }
}
/// List contents of a directory without locking your app.
pub fn file_ls<T>(dir: &str, filter_cb: EioFilterCb<T>,
main_cb: EioMainCb<T>, done_cb: EioDoneCb<T>,
error_cb: EioErrorCb<T>, data: &T) -> Box<EioFile> {
dir.with_c_str... | shutdown | identifier_name |
eio.rs | // Eio Rust bindings for EFL.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library 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 the License, or (at... | type _CEioProgressCb = fn (*c_void, *EioFile, *EioProgress);
#[link(name = "eio")]
extern "C" {
fn eio_init() -> c_int;
fn eio_shutdown() -> c_int;
fn eio_file_ls(dir: *c_char, filter_cb: _CEioFilterCb,
main_cb: _CEioMainCb, done_cb: _CEioDoneCb,
error_cb: _CEioErrorCb... | pub type EioErrorCb<T> = fn (&mut T, &EioFile, int);
type _CEioErrorCb = fn (*c_void, *EioFile, c_int);
pub type EioProgressCb<T> = fn (&mut T, &EioFile, &EioProgress); | random_line_split |
BreachedServers.tsx | import React, {useEffect, useState} from 'react';
import ReactTable from 'react-table';
import {renderArray, renderIpAddresses} from '../common/RenderArrays';
import LoadingIcon from '../../ui-components/LoadingIcon';
import IslandHttpClient from '../../IslandHttpClient';
const columns = [
{
Header: 'Breached S... |
let defaultPageSize = exploitations.length > pageSize ? pageSize : exploitations.length;
let showPagination = exploitations.length > pageSize;
return (
<>
<div className="data-table-container">
<ReactTable
columns={columns}
data={exploitations}
showPagination={sho... | {
return <LoadingIcon />
} | conditional_block |
BreachedServers.tsx | import React, {useEffect, useState} from 'react';
import ReactTable from 'react-table';
import {renderArray, renderIpAddresses} from '../common/RenderArrays';
import LoadingIcon from '../../ui-components/LoadingIcon';
import IslandHttpClient from '../../IslandHttpClient';
| {Header: 'Machine', accessor: 'label'},
{
Header: 'IP Addresses', id: 'ip_addresses',
accessor: x => renderIpAddresses(x)
},
{Header: 'Exploits', id: 'exploits', accessor: x => renderArray(x.exploits)}
]
}
];
const pageSize = 10;
function BreachedServersComponent() {
c... | const columns = [
{
Header: 'Breached Servers',
columns: [ | random_line_split |
Bootstrap.js | import React from 'react';
import IconBase from '@suitejs/icon-base';
function | (props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 37.358V10.642A4.642 4.642 0 0 1 10.642 6h26.716A4.642 4.642 0 0 1 42 10.642v26.716A4.642 4.642 0 0 1 37.358 42H10.642A4.642 4.642 0 0 1 6 37.358zm10.136-24.256v21.796h10.562c.977 0 1.929-.122 2.855-.366a7.633 7.633 0 0 0 2.472-1.13 5.5... | DvBootstrap | identifier_name |
Bootstrap.js | import React from 'react';
import IconBase from '@suitejs/icon-base';
function DvBootstrap(props) |
export default DvBootstrap;
| {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 37.358V10.642A4.642 4.642 0 0 1 10.642 6h26.716A4.642 4.642 0 0 1 42 10.642v26.716A4.642 4.642 0 0 1 37.358 42H10.642A4.642 4.642 0 0 1 6 37.358zm10.136-24.256v21.796h10.562c.977 0 1.929-.122 2.855-.366a7.633 7.633 0 0 0 2.472-1.13 5.563 5.563... | identifier_body |
Bootstrap.js | import React from 'react'; | return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 37.358V10.642A4.642 4.642 0 0 1 10.642 6h26.716A4.642 4.642 0 0 1 42 10.642v26.716A4.642 4.642 0 0 1 37.358 42H10.642A4.642 4.642 0 0 1 6 37.358zm10.136-24.256v21.796h10.562c.977 0 1.929-.122 2.855-.366a7.633 7.633 0 0 0 2.472-1.13 5.563 5.563 0... | import IconBase from '@suitejs/icon-base';
function DvBootstrap(props) { | random_line_split |
blob.js | /**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Wrappers for the HTML5 File API. These wrappers closely mirror
* the underlying APIs, but use Closure-style events and Deferred return values.
* Their existence also makes it possible to mock the... |
if (opt_endings) {
properties['endings'] = opt_endings;
}
return new Blob(parts, properties);
} else {
throw new Error('This browser doesn\'t seem to support creating Blobs');
}
};
| {
properties['type'] = opt_type;
} | conditional_block |
blob.js | /**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Wrappers for the HTML5 File API. These wrappers closely mirror
* the underlying APIs, but use Closure-style events and Deferred return values.
* Their existence also makes it possible to mock the... | var properties = {};
if (opt_type) {
properties['type'] = opt_type;
}
if (opt_endings) {
properties['endings'] = opt_endings;
}
return new Blob(parts, properties);
} else {
throw new Error('This browser doesn\'t seem to support creating Blobs');
}
}; | random_line_split | |
webpack.development.ts | import * as common from './webpack.common'
import * as webpack from 'webpack'
import merge from 'webpack-merge'
const config: webpack.Configuration = {
mode: 'development',
devtool: 'source-map',
}
const mainConfig = merge({}, common.main, config)
const askPassConfig = merge({}, common.askPass, config)
const cli... |
return result
}
return 3000
}
const port = getPortOrDefault()
const webpackHotModuleReloadUrl = `webpack-hot-middleware/client?path=http://localhost:${port}/__webpack_hmr`
const publicPath = `http://localhost:${port}/build/`
const rendererConfig = merge({}, common.renderer, config, {
entry: {
renderer... | {
throw new Error(`Unable to parse '${port}' into valid number`)
} | conditional_block |
webpack.development.ts | import * as common from './webpack.common'
import * as webpack from 'webpack'
import merge from 'webpack-merge'
const config: webpack.Configuration = {
mode: 'development',
devtool: 'source-map',
}
const mainConfig = merge({}, common.main, config)
const askPassConfig = merge({}, common.askPass, config)
const cli... | rendererConfig,
askPassConfig,
crashConfig,
cliConfig,
highlighterConfig,
] | })
// eslint-disable-next-line no-restricted-syntax
export default [
mainConfig, | random_line_split |
3_10_exercise_oop_wave.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-10: OOP Wave
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
wave0: Wave,
wave1: Wave,
}
struct Wave {
x_spacing: f32, // How far apart should each horizontal positio... | y_values,
}
}
fn calculate(&mut self) {
// Increment theta (try different values for 'angular velocity' here
self.theta += 0.02;
// For every x values, calculate a y value with sine function
let mut x = self.theta;
for i in 0..self.y_values.len() {
... | dx, | random_line_split |
3_10_exercise_oop_wave.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Exercise 3-10: OOP Wave
use nannou::prelude::*;
fn | () {
nannou::app(model).update(update).run();
}
struct Model {
wave0: Wave,
wave1: Wave,
}
struct Wave {
x_spacing: f32, // How far apart should each horizontal position be spaced
_w: f32, // Width of entire wave
origin: Point2, // Where does the wave's first point start
... | main | identifier_name |
components.py | """
Simple entity system: any renderable Object can have
a number of Components attached.
"""
import math
import algebra
class Object:
"""
This is a generic object: the player, a monster, an item, the stairs...
It's always represented by a character on screen.
"""
def __init__(self, pos, char, nam... |
class Equipment(Component):
"""
An object that can be equipped, yielding bonuses.
Requires an Item component.
"""
def __init__(self, slot, power_bonus=0, defense_bonus=0, max_hp_bonus=0):
self.power_bonus = power_bonus
self.defense_bonus = defense_bonus
self.max_hp_bonus =... | """
An item that can be picked up and used.
"""
def __init__(self, description=None, count=1, use_function=None):
self.description = description
self.use_function = use_function
self.count = count
def can_combine(self, other):
"""
Returns true if other can stack ... | identifier_body |
components.py | """
Simple entity system: any renderable Object can have
a number of Components attached.
"""
import math
import algebra
class Object:
"""
This is a generic object: the player, a monster, an item, the stairs...
It's always represented by a character on screen.
"""
def __init__(self, pos, char, nam... | (obj):
"""
Returns a list of all equipped items.
"""
if hasattr(obj, 'inventory'):
equipped_list = []
for item in obj.inventory:
if item.equipment and item.equipment.is_equipped:
equipped_list.append(item.equipment)
return equipped_list
else:
... | _get_all_equipped | identifier_name |
components.py | """
Simple entity system: any renderable Object can have
a number of Components attached.
"""
import math
import algebra
class Object:
"""
This is a generic object: the player, a monster, an item, the stairs...
It's always represented by a character on screen.
"""
def __init__(self, pos, char, nam... | self.is_equipped = False
def set_owner(self, entity):
Component.set_owner(self, entity)
# There must be an Item component for the Equipment
# component to work properly.
if entity.item is None:
entity.item = Item()
entity.item.set_owner(entity)
cla... | self.power_bonus = power_bonus
self.defense_bonus = defense_bonus
self.max_hp_bonus = max_hp_bonus
self.slot = slot | random_line_split |
components.py | """
Simple entity system: any renderable Object can have
a number of Components attached.
"""
import math
import algebra
class Object:
"""
This is a generic object: the player, a monster, an item, the stairs...
It's always represented by a character on screen.
"""
def __init__(self, pos, char, nam... |
else:
return []
| equipped_list = []
for item in obj.inventory:
if item.equipment and item.equipment.is_equipped:
equipped_list.append(item.equipment)
return equipped_list | conditional_block |
question_boolean.ts | import { QuestionFactory } from "./questionfactory";
import { property, Serializer } from "./jsonobject";
import { Question } from "./question";
import { LocalizableString } from "./localizablestring";
import { surveyLocalization } from "./surveyStrings";
/**
* A Model for a boolean question.
*/
export class Questio... | (): any {
return this.getLocalizableStringText("labelTrue");
}
public set labelTrue(val: any) {
this.setLocalizableStringText("labelTrue", val);
}
get locLabelTrue(): LocalizableString {
return this.getLocalizableString("labelTrue");
}
/**
* Set this property, if you want to have a different... | labelTrue | identifier_name |
question_boolean.ts | import { QuestionFactory } from "./questionfactory";
import { property, Serializer } from "./jsonobject";
import { Question } from "./question";
import { LocalizableString } from "./localizablestring";
import { surveyLocalization } from "./surveyStrings";
/**
* A Model for a boolean question.
*/
export class Questio... |
public set defaultValue(val: any) {
if (val === true) val = "true";
if (val === false) val = "false";
this.setPropertyValue("defaultValue", val);
this.updateValueWithDefaults();
}
public getDefaultValue(): any {
if (this.defaultValue == "indeterminate") return null;
if (this.defaultValue ... | {
return this.getPropertyValue("defaultValue");
} | identifier_body |
question_boolean.ts | import { QuestionFactory } from "./questionfactory";
import { property, Serializer } from "./jsonobject";
import { Question } from "./question";
import { LocalizableString } from "./localizablestring";
import { surveyLocalization } from "./surveyStrings";
/**
* A Model for a boolean question.
*/
export class Questio... | */
public get labelTrue(): any {
return this.getLocalizableStringText("labelTrue");
}
public set labelTrue(val: any) {
this.setLocalizableStringText("labelTrue", val);
}
get locLabelTrue(): LocalizableString {
return this.getLocalizableString("labelTrue");
}
/**
* Set this property, if ... | }
/**
* Set this property, if you want to have a different label for state when check is set. | random_line_split |
settings.py | """
Django settings for simplemooc project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pat... |
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'... | 'django.contrib.messages',
'django.contrib.staticfiles',
'simplemooc.core',
'simplemooc.courses'
) | random_line_split |
create-notebook.component.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... | k-select';
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// View초기화
private initViewPage() {
... | folderId;
}
this.step = 'create-noteboo | conditional_block |
create-notebook.component.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... |
// Init
}
// Destory
public ngOnDestroy() {
// Destory
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public init(workspaceId: string, folderId?: string) {
console.log('init', workspaceI... | random_line_split | |
create-notebook.component.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... | rvice: PopupService,
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
... | ate popupSe | identifier_name |
create-notebook.component.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... | -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public init(workspaceId: string, folderId?: string) {
console.log('init', workspaceId, folderId);
this.workspaceId = workspaceId;
// this.workbook = new Workbook();
this.notebook = new Not... | y
super.ngOnDestroy();
}
/*-=-=-=-=-= | identifier_body |
EncounterOptions.ts | import { Match } from './Match';
/**
* Options that can be passed to an Encounter.
*/
export interface EncounterOptions {
/**
* If partial matching is being performed.
*/
partial?: boolean;
/**
* If fuzzy matching is being performed.
*/
fuzzy?: boolean;
/**
* Only match if all tokens have been consu... | */
supportsFuzzy?: boolean;
/**
* Method used to determine if two matches are equal.
*/
matchIsEqual?: (options: EncounterOptions) => (a: any, b: any) => boolean;
/**
* Function called when a match is found.
*/
onMatch?: (match: Match<any>) => void;
} | random_line_split | |
user.js | import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/user'
import * as usersService from '../services/users'
import { pageModel } from './common'
import { config } from 'utils'
const { query } = usersService
const { prefix } = config
export default modelExtend(pageModel, {
... | ,
},
})
| {
localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
return { ...state, isMotion: !state.isMotion }
} | identifier_body |
user.js | import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/user'
import * as usersService from '../services/users'
import { pageModel } from './common'
import { config } from 'utils'
const { query } = usersService
const { prefix } = config
export default modelExtend(pageModel, {
... | ({ dispatch, history }) {
history.listen(location => {
if (location.pathname === '/user') {
dispatch({
type: 'query',
payload: location.query,
})
}
})
},
},
effects: {
*query ({ payload = {} }, { call, put }) {
const data = yie... | setup | identifier_name |
user.js | import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/user'
import * as usersService from '../services/users'
import { pageModel } from './common'
import { config } from 'utils'
const { query } = usersService
const { prefix } = config
export default modelExtend(pageModel, {
... | *update ({ payload }, { select, call, put }) {
const id = yield select(({ user }) => user.currentItem.id)
const newUser = { ...payload, id }
const data = yield call(update, newUser)
if (data.success) {
yield put({ type: 'hideModal' })
yield put({ type: 'query' })
} else... | random_line_split | |
user.js | import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/user'
import * as usersService from '../services/users'
import { pageModel } from './common'
import { config } from 'utils'
const { query } = usersService
const { prefix } = config
export default modelExtend(pageModel, {
... |
},
*'multiDelete' ({ payload }, { call, put }) {
const data = yield call(usersService.remove, payload)
if (data.success) {
yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
yield put({ type: 'query' })
} else {
throw data
}
},
*create... | {
throw data
} | conditional_block |
subscription.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... | {
push_uri: String,
public_key: String,
auth: Option<String>
}
impl Subscription {
pub fn new(push_uri: &str, public_key: &str, auth: &str) -> Self {
Subscription {
push_uri: push_uri.to_owned(),
public_key: public_key.to_owned(),
auth: Some(auth.to_owned())... | Subscription | identifier_name |
subscription.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... |
}
pub struct Subscription {
push_uri: String,
public_key: String,
auth: Option<String>
}
impl Subscription {
pub fn new(push_uri: &str, public_key: &str, auth: &str) -> Self {
Subscription {
push_uri: push_uri.to_owned(),
public_key: public_key.to_owned(),
... | {
sub.post(&self.crypto, &self.gcm_api_key, message)
} | identifier_body |
subscription.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... | ;
// TODO: Add a retry mechanism if 429 Too Many Requests returned by push service
Ok(try!(req.send()))
}
}
| {
req.header(ContentEncoding(vec![Encoding::EncodingExt(String::from("aesgcm128"))]))
.header(EncryptionKey(format!("keyid=p256dh;dh={}", public_key)))
} | conditional_block |
subscription.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use crypto::CryptoContext;
use error::{WebPushError, WebPushResult};
use hyper::header::{ContentEncoding, Encoding, A... | use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::cmp::max;
// Place these headers inside a sub module to prevent them from getting
// exported by the crate, as the macro declares them pub.
mod hidden {
header! { (CryptoKey, "Crypto-Key") => [String] }
header! { (Encryption, "Encr... | use hyper::client::response::Response; | random_line_split |
app.module.ts | import { ErrorHandler, NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { BlocksPage, HomePage, PagesModule } from '../pages';
import { ApiProvider } fr... | ],
bootstrap: [IonicApp],
entryComponents: [InsightApp, HomePage, BlocksPage],
providers: [
{ provide: ErrorHandler, useClass: IonicErrorHandler },
ApiProvider,
CurrencyProvider,
BlocksProvider,
TxsProvider,
DefaultProvider,
PriceProvider
]
})
export class AppModule { } | PagesModule,
IonicModule.forRoot(InsightApp) | random_line_split |
app.module.ts | import { ErrorHandler, NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { BlocksPage, HomePage, PagesModule } from '../pages';
import { ApiProvider } fr... | { }
| AppModule | identifier_name |
previewbrowser.py | SizePolicy,
QStyleOption, QStylePainter
)
from PyQt4.QtSvg import QSvgWidget
from PyQt4.QtCore import (
Qt, QSize, QByteArray, QModelIndex, QEvent
)
from PyQt4.QtCore import pyqtSignal as Signal
from ..utils import check_type
from ..gui.dropshadow import DropShadowFrame
from . import previewmodel
NO_PREVI... |
def elideMode(self):
return self.__elideMode
def setAlignment(self, align):
"""Set text alignment (`Qt.Alignment`).
"""
if self.__alignment != align:
self.__alignment = align
self.__update()
def sizeHint(self):
if self.__sizeHint is None:
... | """Set elide mode (`Qt.TextElideMode`)
"""
if self.__textElideMode != mode:
self.__textElideMode = mode
self.__update() | identifier_body |
previewbrowser.py | SizePolicy,
QStyleOption, QStylePainter
)
from PyQt4.QtSvg import QSvgWidget
from PyQt4.QtCore import (
Qt, QSize, QByteArray, QModelIndex, QEvent
)
from PyQt4.QtCore import pyqtSignal as Signal
from ..utils import check_type
from ..gui.dropshadow import DropShadowFrame
from . import previewmodel
NO_PREVI... | (QWidget):
"""A Preview Browser for recent/premade scheme selection.
"""
# Emitted when the current previewed item changes
currentIndexChanged = Signal(int)
# Emitted when an item is double clicked in the preview list.
activated = Signal(int)
def __init__(self, *args):
QWidget.__in... | PreviewBrowser | identifier_name |
previewbrowser.py | SizePolicy,
QStyleOption, QStylePainter
)
from PyQt4.QtSvg import QSvgWidget
from PyQt4.QtCore import (
Qt, QSize, QByteArray, QModelIndex, QEvent
)
from PyQt4.QtCore import pyqtSignal as Signal
from ..utils import check_type
from ..gui.dropshadow import DropShadowFrame
from . import previewmodel
NO_PREVI... | if self.__currentIndex <= topleft.row() and \
self.__currentIndex >= bottomRight.row():
self.__update()
def __onDoubleClicked(self, index):
"""Double click on an item in the preview item list.
"""
self.activated.emit(index.row())
def __update(self):
... | range.
""" | random_line_split |
previewbrowser.py | SizePolicy,
QStyleOption, QStylePainter
)
from PyQt4.QtSvg import QSvgWidget
from PyQt4.QtCore import (
Qt, QSize, QByteArray, QModelIndex, QEvent
)
from PyQt4.QtCore import pyqtSignal as Signal
from ..utils import check_type
from ..gui.dropshadow import DropShadowFrame
from . import previewmodel
NO_PREVI... |
if not index.isValid():
description = ""
name = ""
path = ""
svg = NO_PREVIEW_SVG
else:
description = str(index.data(Qt.WhatsThisRole))
if not description:
description = "No description."
description =... | index = QModelIndex() | conditional_block |
scrolling.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A timer thread that gives the painting task a little time to catch up when the user scrolls.
use compositor_t... | impl ScrollingTimer {
pub fn run(&mut self) {
while let Ok(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) = self.receiver.recv() {
let target = timestamp + TIMEOUT;
let delta_ns = target - time::precise_time_ns();
thread::sleep(duration_from_nanoseconds(delta_ns... | pub fn shutdown(&mut self) {
self.sender.send(ToScrollingTimerMsg::ExitMsg).unwrap()
}
}
| random_line_split |
scrolling.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A timer thread that gives the painting task a little time to catch up when the user scrolls.
use compositor_t... | (&mut self, timestamp: u64) {
self.sender.send(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)).unwrap()
}
pub fn shutdown(&mut self) {
self.sender.send(ToScrollingTimerMsg::ExitMsg).unwrap()
}
}
impl ScrollingTimer {
pub fn run(&mut self) {
while let Ok(ToScrollingTime... | scroll_event_processed | identifier_name |
report_financial.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... |
data['form']['used_context'].update(
account_financial_report_horizontal_side=side)
return super(report_account_common_horizontal, self).get_lines(
data)
def get_left_lines(self, data):
return self.get_lines(data, side='left')
def get_right_lines(self, data):
... | data['form']['used_context'] = {} | conditional_block |
report_financial.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | class ReportFinancial(models.AbstractModel):
_inherit = 'report.account.report_financial'
_wrapped_report_class = report_account_common_horizontal | def get_right_lines(self, data):
return self.get_lines(data, side='right')
| random_line_split |
report_financial.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | (report_account_common):
def __init__(self, cr, uid, name, context=None):
super(report_account_common_horizontal, self).__init__(
cr, uid, name, context=context)
self.localcontext.update({
'get_left_lines': self.get_left_lines,
'get_right_lines': self.get_right_li... | report_account_common_horizontal | identifier_name |
report_financial.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... |
def get_left_lines(self, data):
return self.get_lines(data, side='left')
def get_right_lines(self, data):
return self.get_lines(data, side='right')
class ReportFinancial(models.AbstractModel):
_inherit = 'report.account.report_financial'
_wrapped_report_class = report_account_common... | data = copy.deepcopy(data)
if data['form']['used_context'] is None:
data['form']['used_context'] = {}
data['form']['used_context'].update(
account_financial_report_horizontal_side=side)
return super(report_account_common_horizontal, self).get_lines(
data) | identifier_body |
totalstatistics.py | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
def add_test(self, test):
self.stats.all.add_test(test)
if test.critical:
self.stats.critical.add_test(test)
def visit_test(self, test):
self.add_test(test)
def visit_keyword(self, kw):
pass
| suite.visit(self) | conditional_block |
totalstatistics.py | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | pass | identifier_body | |
totalstatistics.py | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | (self, visitor):
visitor.visit_total_statistics(self)
def __iter__(self):
return iter([self.critical, self.all])
@property
def message(self):
"""String representation of the statistics.
For example::
2 critical tests, 1 passed, 1 failed
2 tests tot... | visit | identifier_name |
totalstatistics.py | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
def _get_counts(self, stat):
ending = 's' if stat.total != 1 else ''
return stat.total, ending, stat.passed, stat.failed
class TotalStatisticsBuilder(SuiteVisitor):
def __init__(self, suite=None):
self.stats = TotalStatistics()
if suite:
suite.visit(self)
def... | % (ctotal, cend, cpass, cfail, atotal, aend, apass, afail)) | random_line_split |
zmq_server.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 00:01:09 2021
@author: roman
"""
import zmq
import time
import sys
#import random
import os;
sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore
#sys.path.append(r'C:\Github\xrt') # analysis:ignore
import numpy as np
#import matplotlib
#matplotlib.use... |
CustomSource = rs.SourceFromField(targetOpenCL='CPU')
port = "15560"
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.connect("tcp://localhost:%s" % port)
while True:
# message = socket.recv_pyobj() # Python 3 only
message = recv_zipped_pickle(socket)
reply = CustomSource.ucl.run_parallel(... | """inverse of send_zipped_pickle"""
z = socket.recv(flags)
# p = zlib.decompress(z)
return pickle.loads(z) | identifier_body |
zmq_server.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 00:01:09 2021
@author: roman
"""
import zmq
import time
import sys
#import random
import os;
sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore
#sys.path.append(r'C:\Github\xrt') # analysis:ignore
import numpy as np
#import matplotlib
#matplotlib.use... | (socket, obj, flags=0, protocol=2):
"""pickle an object, and zip the pickle before sending it"""
p = pickle.dumps(obj, protocol)
# z = zlib.compress(p, 8)
return socket.send(p, flags=flags)
def recv_zipped_pickle(socket, flags=0, protocol=2):
"""inverse of send_zipped_pickle"""
z = socket.recv(f... | send_zipped_pickle | identifier_name |
zmq_server.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 00:01:09 2021
@author: roman
"""
import zmq
import time
import sys
#import random
import os;
sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore
#sys.path.append(r'C:\Github\xrt') # analysis:ignore
import numpy as np
#import matplotlib
#matplotlib.use... | message = recv_zipped_pickle(socket)
reply = CustomSource.ucl.run_parallel(**message)
print("calculations complete. sending back results")
send_zipped_pickle(socket, reply, protocol=2) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.