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 |
|---|---|---|---|---|
seeds_threshold.py | # This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License
from load import load_dataset
import numpy as np
from threshold import learn_model, apply_model, accura... |
error /= 10.0
print('Ten fold cross-validated error was {0:.1%}.'.format(error))
| training = np.ones(len(features), bool)
# numpy magic to make an array with 10% of 0s starting at fold
training[fold::10] = 0
# whatever is not training is for testing
testing = ~training
model = learn_model(features[training], labels[training])
test_error = accuracy(features[testing], labels... | conditional_block |
seeds_threshold.py | # This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License
|
features, labels = load_dataset('seeds')
# Turn the labels into a binary array
labels = (labels == 'Canadian')
error = 0.0
for fold in range(10):
training = np.ones(len(features), bool)
# numpy magic to make an array with 10% of 0s starting at fold
training[fold::10] = 0
# whatever is not training ... | from load import load_dataset
import numpy as np
from threshold import learn_model, apply_model, accuracy | random_line_split |
WebGLLights.d.ts | export class WebGLLights {
constructor( gl: WebGLRenderingContext, properties: any, info: any );
state: {
version: number;
hash: {
directionalLength: number;
pointLength: number;
spotLength: number;
rectAreaLength: number;
hemiLength: number;
numDirectionalShadows: number;
numPointShadows... | hemi: Array<any>;
};
get( light: any ): any;
setup( lights: any, shadows: any, camera: any ): void;
} | random_line_split | |
WebGLLights.d.ts | export class | {
constructor( gl: WebGLRenderingContext, properties: any, info: any );
state: {
version: number;
hash: {
directionalLength: number;
pointLength: number;
spotLength: number;
rectAreaLength: number;
hemiLength: number;
numDirectionalShadows: number;
numPointShadows: number;
numSpotShad... | WebGLLights | identifier_name |
view_container_ref.ts | import {ListWrapper, List} from 'angular2/src/core/facade/collection';
import {ResolvedBinding} from 'angular2/di';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import * as avmModule from './view_manager';
import * as viewModule from './view';
import {ElementRef} from './element_ref';
import {Tem... |
/**
* Return a {@link ViewRef} at specific index.
*/
get(index: number): ViewRef { return this._getViews()[index].ref; }
/**
* Returns number of {@link ViewRef}s currently attached at this location.
*/
get length(): number { return this._getViews().length; }
/**
* Create and insert a {@link... | {
for (var i = this.length - 1; i >= 0; i--) {
this.remove(i);
}
} | identifier_body |
view_container_ref.ts | import {ListWrapper, List} from 'angular2/src/core/facade/collection';
import {ResolvedBinding} from 'angular2/di';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import * as avmModule from './view_manager';
import * as viewModule from './view';
import {ElementRef} from './element_ref';
import {Tem... | (): List<viewModule.AppView> {
var vc = internalView(this.element.parentView).viewContainers[this.element.boundElementIndex];
return isPresent(vc) ? vc.views : [];
}
/**
* Remove all {@link ViewRef}s at current location.
*/
clear(): void {
for (var i = this.length - 1; i >= 0; i--) {
this... | _getViews | identifier_name |
view_container_ref.ts | import {ListWrapper, List} from 'angular2/src/core/facade/collection';
import {ResolvedBinding} from 'angular2/di';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import * as avmModule from './view_manager';
import * as viewModule from './view';
import {ElementRef} from './element_ref';
import {Tem... | if (atIndex == -1) atIndex = this.length - 1;
return this.viewManager.detachViewInContainer(this.element, atIndex);
}
} | detach(atIndex: number = -1): ViewRef { | random_line_split |
ethernet.py | #===============================================================================
# Copyright 2012 NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published ... | __author__ = "Jorge Mora (%s)" % c.NFSTEST_AUTHOR_EMAIL
__copyright__ = "Copyright (C) 2012 NetApp, Inc."
__license__ = "GPL v2"
__version__ = "1.1"
_ETHERNET_map = {
0x0800: 'IPv4',
0x86dd: 'IPv6',
0x0806: 'ARP',
0x8035: 'RARP',
}
class ETHERNET(BaseObj):
"""Ethernet object
Usage:
... | random_line_split | |
ethernet.py | #===============================================================================
# Copyright 2012 NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published ... | (self):
"""String representation of object
The representation depends on the verbose level set by debug_repr().
If set to 0 the generic object representation is returned.
If set to 1 the representation of the object is condensed:
'00:0c:29:54:09:ef -> 60:33:4b:29... | __str__ | identifier_name |
ethernet.py | #===============================================================================
# Copyright 2012 NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published ... | """Constructor
Initialize object's private data.
pktt:
Packet trace object (packet.pktt.Pktt) so this layer has
access to the parent layers.
"""
unpack = pktt.unpack
ulist = unpack.unpack(14, "!6s6sH")
self.dst = MacAddr(ulis... | """Ethernet object
Usage:
from packet.link.ethernet import ETHERNET
x = ETHERNET(pktt)
Object definition:
ETHERNET(
dst = MacAddr(), # destination MAC address
src = MacAddr(), # source MAC address
type = int, # payload type
... | identifier_body |
ethernet.py | #===============================================================================
# Copyright 2012 NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published ... |
elif self.type == 0x8035:
# Decode RARP packet
RARP(pktt)
else:
self.data = unpack.getbytes()
def __str__(self):
"""String representation of object
The representation depends on the verbose level set by debug_repr().
If set to 0 th... | ARP(pktt) | conditional_block |
common.py | # -*- coding: utf-8 -*-
"""
Django settings for LittleSportsBiscuit project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import,... | 'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
# Your stuff: custom template context processors go here
],
},
},
]
# See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-p... | 'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static', | random_line_split |
legend.py | (self, other):
return not self.__eq__(other)
# If we define __eq__ we also need __hash__ otherwise the object
# becomes unhashable. All this does is hash the frozenset of the
# keys. (You can only hash immutables.)
def __hash__(self):
return hash(frozenset(self.__dict__.keys()))
de... | __ne__ | identifier_name | |
legend.py |
for k, v in kwargs.items() or params.items():
k = k.lower().replace(' ', '_')
if k in ['colour', 'color']:
k = 'colour'
if not v:
v = '#eeeeee'
try:
v = v.lower()
except AttributeError:
... | params = p | conditional_block | |
legend.py |
def __ne__(self, other):
return not self.__eq__(other)
# If we define __eq__ we also need __hash__ otherwise the object
# becomes unhashable. All this does is hash the frozenset of the
# keys. (You can only hash immutables.)
def __hash__(self):
return hash(frozenset(self.__dict__.... | if not isinstance(other, self.__class__):
return False
# Weed out empty elements
s = {k: v for k, v in self.__dict__.items() if v}
o = {k: v for k, v in other.__dict__.items() if v}
# Compare
if s == o:
return True
else:
return False | identifier_body | |
legend.py | except AttributeError:
v = v.__repr__()
tr += r.format(v=v, stl=style)
th += h.format(k=k)
return th, tr
@property
def colour(self):
return self._colour
@colour.setter
def colour(self, c):
numbers = r'([\.0-9]+), ?([\.0-9]+), ?([\.... | a plot colour.
Args:
list_of_Decors (list): The decors to collect into a legend. In
general, you will want to leave legend building to the constructor
class methods, `Legend.default()`, and
`Legend.from_csv(text=string)`. We can add others over time, such
... |
class Legend(object):
"""
A look-up table to assist in the conversion of Components to | random_line_split |
monitor_device.rs | extern crate portmidi as pm;
use std::thread::sleep_ms;
use pm::{PortMidiDeviceId, PortMidiResult};
use pm::PortMidiError::InvalidDeviceId;
pub mod common;
fn | () {
// get the device number from the command line, or die()
let device_id = match common::get_arg(1) {
Some(id) => id,
None => { common::die(); return; }
};
// run the monitor, print an error if it returns one
if let Err(e) = monitor(device_id) {
println!("Error: {:?}", e)... | main | identifier_name |
monitor_device.rs | extern crate portmidi as pm;
use std::thread::sleep_ms;
use pm::{PortMidiDeviceId, PortMidiResult};
use pm::PortMidiError::InvalidDeviceId;
pub mod common;
fn main() {
// get the device number from the command line, or die()
let device_id = match common::get_arg(1) {
Some(id) => id,
None => ... | // no more data? wait a little before trying again
sleep_ms(50);
}
// close the input and terminate portmidi
try!(input.close());
pm::terminate()
} | }
| random_line_split |
monitor_device.rs | extern crate portmidi as pm;
use std::thread::sleep_ms;
use pm::{PortMidiDeviceId, PortMidiResult};
use pm::PortMidiError::InvalidDeviceId;
pub mod common;
fn main() {
// get the device number from the command line, or die()
let device_id = match common::get_arg(1) {
Some(id) => id,
None => ... | println!("{} {:?}", event.timestamp, event.message);
}
}
// no more data? wait a little before trying again
sleep_ms(50);
}
// close the input and terminate portmidi
try!(input.close());
pm::terminate()
}
| {
// initialize portmidi
try!(pm::initialize());
// get the device and check it exists
let device = try!(pm::get_device_info(device_id).ok_or(InvalidDeviceId));
println!("Opening: {}", device.name);
// open the input
let mut input = pm::InputPort::new(device_id, 1024);
try!(input.open(... | identifier_body |
editor-base-controller.js | {
return self.get('isDirty') ? self.unloadDirtyMessage() : null;
};
},
/**
* By default, a post will not change its publish state.
* Only with a user-set value (via setSaveType action)
* can the post's status change.
*/
willPublish: boundOneWay('isPublished'),
... | published: {
published: '已更新。',
draft: '已保存。'
},
draft: {
published: '已发布!',
draft: '已保存。'
}
}
}
},
showSaveNotification: function (prevStatus, sta... |
success: {
post: { | random_line_split |
editor-base-controller.js | {
return self.get('isDirty') ? self.unloadDirtyMessage() : null;
};
},
/**
* By default, a post will not change its publish state.
* Only with a user-set value (via setSaveType action)
* can the post's status change.
*/
willPublish: boundOneWay('isPublished'),
... | lers.post-tags-input').send('addNewTag');
// Set the properties that are indirected
// set markdown equal to what's in the editor, minus the image markers.
this.set('markdown', this.getMarkdown().withoutMarkers);
this.set('status', status);
// Set a default ... | osePassive();
// ensure an incomplete tag is finalised before save
this.get('control | conditional_block |
mod.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // 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.
/*!
* Collection types.
*/
#![experimental]
pub use core_collections::{Collection, M... | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
timer.rs | // Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
//
// 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. All files in the project carrying such notice may not... |
}
pub struct Timer;
impl Timer {
pub fn from_chan(duration: Duration, tx: mpsc::Sender<Request>) {
thread::spawn(move || {
while let Ok(_) = tx.send(Request::Timer(TimerEvent(duration))) {
thread::sleep(duration);
}
});
}
}
| {
TimerEvent(Duration::from_millis(ms))
} | identifier_body |
timer.rs | // Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
//
// 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. All files in the project carrying such notice may not... | ;
impl Timer {
pub fn from_chan(duration: Duration, tx: mpsc::Sender<Request>) {
thread::spawn(move || {
while let Ok(_) = tx.send(Request::Timer(TimerEvent(duration))) {
thread::sleep(duration);
}
});
}
}
| Timer | identifier_name |
timer.rs | // Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
//
// 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. All files in the project carrying such notice may not... | } | });
} | random_line_split |
test_auto_Level1Design.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..model import Level1Design
def test_Level1Design_inputs():
input_map = dict(bases=dict(mandatory=True,
),
contrasts=dict(),
ignore_exception=dict(nohash=True,
usedefault=True,
),
interscan_i... | fsf_files=dict(),
)
outputs = Level1Design.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value | random_line_split | |
test_auto_Level1Design.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..model import Level1Design
def test_Level1Design_inputs():
input_map = dict(bases=dict(mandatory=True,
),
contrasts=dict(),
ignore_exception=dict(nohash=True,
usedefault=True,
),
interscan_i... | ():
output_map = dict(ev_files=dict(),
fsf_files=dict(),
)
outputs = Level1Design.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| test_Level1Design_outputs | identifier_name |
test_auto_Level1Design.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..model import Level1Design
def test_Level1Design_inputs():
|
def test_Level1Design_outputs():
output_map = dict(ev_files=dict(),
fsf_files=dict(),
)
outputs = Level1Design.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| input_map = dict(bases=dict(mandatory=True,
),
contrasts=dict(),
ignore_exception=dict(nohash=True,
usedefault=True,
),
interscan_interval=dict(mandatory=True,
),
model_serial_correlations=dict(mandatory=True,
),
orthogonalization=dict(),
session_info=dict(mandatory=True,
... | identifier_body |
test_auto_Level1Design.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..model import Level1Design
def test_Level1Design_inputs():
input_map = dict(bases=dict(mandatory=True,
),
contrasts=dict(),
ignore_exception=dict(nohash=True,
usedefault=True,
),
interscan_i... | assert getattr(outputs.traits()[key], metakey) == value | conditional_block | |
tests.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | pub gas: U256,
pub sender_address: Option<Address>,
pub receive_address: Option<Address>,
pub value: Option<U256>,
pub data: Bytes,
pub code_address: Option<Address>,
}
/// Fake externalities test structure.
///
/// Can't do recursive calls.
#[derive(Default)]
pub struct FakeExt {
pub store: HashMap<H256, H256>... |
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct FakeCall {
pub call_type: FakeCallType, | random_line_split |
tests.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
fn ret(self, _gas: &U256, _data: &ReturnData, _apply_state: bool) -> Result<U256> {
unimplemented!();
}
fn suicide(&mut self, refund_address: &Address) -> Result<()> {
self.suicides.insert(refund_address.clone());
Ok(())
}
fn schedule(&self) -> &Schedule {
&self.schedule
}
fn env_info(&self) -> &Env... | {
self.logs.push(FakeLogEntry {
topics: topics,
data: data.to_vec()
});
Ok(())
} | identifier_body |
tests.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&mut self, topics: Vec<H256>, data: &[u8]) -> Result<()> {
self.logs.push(FakeLogEntry {
topics: topics,
data: data.to_vec()
});
Ok(())
}
fn ret(self, _gas: &U256, _data: &ReturnData, _apply_state: bool) -> Result<U256> {
unimplemented!();
}
fn suicide(&mut self, refund_address: &Address) -> Result... | log | identifier_name |
makefile.py | from tagsetbench import ShellPath
class Makefile:
def __init__(self, path=None, recipes=None):
self.path = path # TODO: všechny budou ve working_dir, stačí 'name'
# TODO: self.declarations? (pomocí slovníku, aby na ně šlo odkazovat)
# split_corpora=' \\\n\t'.join(self.split_corpora)... | self.dependencies = dependencies or []
self.commands = commands or []
self.delete_on_error = delete_on_error
def lines(self):
"""
Solution to building multiple targets only once was inspired by
https://www.cmcrossroads.com/article/rules-multiple-outputs-gnu-make
... | delete_on_error=True):
self.targets = targets or [] | random_line_split |
makefile.py | from tagsetbench import ShellPath
class Makefile:
def __init__(self, path=None, recipes=None):
self.path = path # TODO: všechny budou ve working_dir, stačí 'name'
# TODO: self.declarations? (pomocí slovníku, aby na ně šlo odkazovat)
# split_corpora=' \\\n\t'.join(self.split_corpora)... | ethod
def _pretty_print_command(cls, command):
tokens = iter(command)
executable = cls._format_token(next(tokens))
param_and_values, next_token = cls._consume_parameter_and_values(
tokens)
if param_and_values:
indentation = ' ' * len(executable)
elif... | Solution to building multiple targets only once was inspired by
https://www.cmcrossroads.com/article/rules-multiple-outputs-gnu-make
"""
# TODO: 'make' moc nezvládá mezery, ale můžu ještě jednou prubnout ' '
if len(self.targets) > 1:
for target, next_target in zip(self.t... | identifier_body |
makefile.py | from tagsetbench import ShellPath
class Makefile:
def __init__(self, path=None, recipes=None):
self.path = path # TODO: všechny budou ve working_dir, stačí 'name'
# TODO: self.declarations? (pomocí slovníku, aby na ně šlo odkazovat)
# split_corpora=' \\\n\t'.join(self.split_corpora)... | (obj, 'path'):
return obj.path.name
elif hasattr(obj, 'name'):
return obj.name
else:
return str(obj)
# TODO: tohle vypadá trochu jako duplikát toho nahoře (_get_filename)
@staticmethod
def _format_token(token):
# NOTE: řídit se podle přípony u spu... | if hasattr | identifier_name |
makefile.py | from tagsetbench import ShellPath
class Makefile:
def __init__(self, path=None, recipes=None):
self.path = path # TODO: všechny budou ve working_dir, stačí 'name'
# TODO: self.declarations? (pomocí slovníku, aby na ně šlo odkazovat)
# split_corpora=' \\\n\t'.join(self.split_corpora)... | urn ([parameter] if parameter else []) + values, token
# TODO: asi sloučit s tím dole (budu potřebovat speciální zacházení
# s ShellPath, protože právě tak dávám do command programy)
@staticmethod
def _get_filename(obj):
if hasattr(obj, 'path'):
return obj.path.name
el... | (token, str) and token.startswith('-'):
if parameter is None: # rename to "argument"?
parameter = token
token = None
else:
break # the next parameter encountered
else:
if parameter is None:
... | conditional_block |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may n... |
// NOTE: this macro has to be defined before any modules. See:
// https://danielkeep.github.io/quick-intro-to-macros.html#some-more-gotchas
/// Assert that an expression returning a `Result` is a success. If it is,
/// return the value contained in the result, i.e. `expr.unwrap()`.
#[cfg(test)]
macro_rules! assert_su... | extern crate threadpool;
#[macro_use]
extern crate log; | random_line_split |
panics.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | <S>(&self, child: &S)
where S: MayPanic,
{
let p = self.clone();
child.on_panic(move |t| p.notify_all(t));
}
}
impl<F> OnPanicListener for F
where F: FnMut(String) + Send + Sync + 'static,
{
fn call(&mut self, arg: &str) {
self(arg.to_owned())
}
}
#[test]
#[ignore] // panic forwarding doesnt work on t... | forward_from | identifier_name |
panics.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
}
/// Structure that allows to catch panics and notify listeners
pub struct PanicHandler {
listeners: Mutex<Vec<Box<OnPanicListener>>>,
}
impl Default for PanicHandler {
fn default() -> Self {
PanicHandler::new()
}
}
impl PanicHandler {
/// Creates new `PanicHandler` wrapped in `Arc`
pub fn new_in_arc() -... | {
self.handler.notify_all("Panic!".to_owned());
} | conditional_block |
panics.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | // when
p.catch_panic(|| panic!("Panic: {}", 1)).unwrap_err();
// then
assert!(invocations.read().unwrap()[0] == "Panic: 1");
}
#[test]
fn should_notify_listeners_about_panic_in_other_thread() {
use std::thread;
use std::sync::RwLock;
// given
let invocations = Arc::new(RwLock::new(vec![]));
let i = invocat... | random_line_split | |
panics.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
fn notify_all(&self, r: String) {
let mut listeners = self.listeners.lock().unwrap();
for listener in listeners.deref_mut() {
listener.call(&r);
}
}
}
impl MayPanic for PanicHandler {
fn on_panic<F>(&self, closure: F)
where F: OnPanicListener,
{
self.listeners.lock().unwrap().push(Box::new(closure))... | {
let _guard = PanicGuard { handler: self };
let result = g();
Ok(result)
} | identifier_body |
DbPBS.py | from __future__ import print_function
import os
import abc
import shelve
from pprint import pprint
from cloudmesh_base.tables import dict_printer
from cloudmesh_base.Shell import Shell
from cloudmesh_base.util import banner
from cloudmesh_base.util import path_expand
from cloudmesh_pbs.OpenPBS import OpenPBS
class... | (self, id, value):
"""set the objet with the id to value"""
def set_filename(self, filename):
"""set the objet with the id to value"""
self.filename = filename
def remove(self):
try:
os.remove(self.filename)
except:
pass
@abc.abstractmethod
... | set | identifier_name |
DbPBS.py | from __future__ import print_function
import os
import abc
import shelve
from pprint import pprint
from cloudmesh_base.tables import dict_printer
from cloudmesh_base.Shell import Shell
from cloudmesh_base.util import banner
from cloudmesh_base.util import path_expand
from cloudmesh_pbs.OpenPBS import OpenPBS
class... |
# prepare the dict
d = {}
for jobid in self.db:
content = {}
for attribute in columns:
try:
content[attribute] = self.db[jobid][attribute]
except:
content[attribute] = "None"
d[jobid] = ... | columns = ["cm_jobid", "cm_host", "cm_user", "Job_Name", "job_state", "exit_status"] | conditional_block |
DbPBS.py | from __future__ import print_function
import os
import abc
import shelve
from pprint import pprint
from cloudmesh_base.tables import dict_printer
from cloudmesh_base.Shell import Shell
from cloudmesh_base.util import banner
from cloudmesh_base.util import path_expand
from cloudmesh_pbs.OpenPBS import OpenPBS
class... |
if __name__ == "__main__":
qsub = False
db = DbPBS()
db.clear()
db.info()
db.update(host="india", user=False)
print(db.list(output="table"))
print(db.list(output="csv"))
print(db.list(output="dict"))
print(db.list(output="yaml"))
banner("user")
db.clear()
db.update(... | r = self.pbs.qsub(name, host, script, template=template, kind=kind)
pprint(r)
return dict(r) | identifier_body |
DbPBS.py | from __future__ import print_function
import os
import abc
import shelve
from pprint import pprint
from cloudmesh_base.tables import dict_printer
from cloudmesh_base.Shell import Shell
from cloudmesh_base.util import banner |
class pbs_db_interface(object):
__metaclass__ = abc.ABCMeta
db = None
def data(self):
return dict(self.db)
def __getitem__(self, index):
return self.db[index]
def __setitem__(self, index, value):
self.db[index] = value
@abc.abstractmethod
def load(self, filename... | from cloudmesh_base.util import path_expand
from cloudmesh_pbs.OpenPBS import OpenPBS
| random_line_split |
utils.py | from __future__ import absolute_import
import six
import logging
from collections import namedtuple
from symsynd.macho.arch import get_cpu_name
from symsynd.utils import parse_addr
from sentry.interfaces.contexts import DeviceContextType
logger = logging.getLogger(__name__)
APPLE_SDK_MAPPING = {
'iPhone OS':... |
system_version = tuple(int(x) for x in (
info['system_version'] + '.0' * 3).split('.')[:3])
except (ValueError, LookupError):
return None
return {
'dsym_type': 'macho',
'sdk_name': sdk_name,
'version_major': system_version[0],
'version_minor': system... | sdk_name = APPLE_SDK_MAPPING[info['system_name']] | conditional_block |
utils.py | from __future__ import absolute_import
import six
import logging
from collections import namedtuple
from symsynd.macho.arch import get_cpu_name
from symsynd.utils import parse_addr
from sentry.interfaces.contexts import DeviceContextType
logger = logging.getLogger(__name__)
APPLE_SDK_MAPPING = {
'iPhone OS':... |
def cpu_name_from_data(data):
"""Returns the CPU name from the given data if it exists."""
device = DeviceContextType.primary_value_for_data(data)
if device:
arch = device.get('arch')
if isinstance(arch, six.string_types):
return arch
# TODO: kill this here. we want to n... | if not info:
return None
try:
# Support newer mapping in old format.
if info['system_name'] in KNOWN_DSYM_TYPES:
sdk_name = info['system_name']
else:
sdk_name = APPLE_SDK_MAPPING[info['system_name']]
system_version = tuple(int(x) for x in (
... | identifier_body |
utils.py | from __future__ import absolute_import
import six
import logging
from collections import namedtuple
from symsynd.macho.arch import get_cpu_name
from symsynd.utils import parse_addr
from sentry.interfaces.contexts import DeviceContextType
logger = logging.getLogger(__name__)
APPLE_SDK_MAPPING = {
'iPhone OS':... |
AppInfo = namedtuple('AppInfo', ['id', 'version', 'build', 'name'])
def find_apple_crash_report_referenced_images(binary_images, threads):
"""Given some binary images from an apple crash report and a thread
list this returns a list of image UUIDs to load.
"""
image_map = {}
for image in binary_im... | 'macOS': 'macho',
'watchOS': 'macho',
} | random_line_split |
utils.py | from __future__ import absolute_import
import six
import logging
from collections import namedtuple
from symsynd.macho.arch import get_cpu_name
from symsynd.utils import parse_addr
from sentry.interfaces.contexts import DeviceContextType
logger = logging.getLogger(__name__)
APPLE_SDK_MAPPING = {
'iPhone OS':... | (info):
if not info:
return None
try:
# Support newer mapping in old format.
if info['system_name'] in KNOWN_DSYM_TYPES:
sdk_name = info['system_name']
else:
sdk_name = APPLE_SDK_MAPPING[info['system_name']]
system_version = tuple(int(x) for x in (... | get_sdk_from_apple_system_info | identifier_name |
log.py | from logging import CRITICAL, getLevelName
from functools import wraps
from django.utils.decorators import available_attrs
from celery import states
from celery.utils.log import get_task_logger
from api.decorators import catch_exception
from api.task.utils import task_log
logger = get_task_logger(__name__)
class De... |
if success:
task_status = states.SUCCESS
else:
task_status = states.FAILURE
task_log(self.task_id, self.msg, obj=self.obj, task_status=task_status, task_result=True,
detail=self.get_detail(), dc_id=self.dc_id, update_user_tasks=False)
def save_task_l... | return | conditional_block |
log.py | from logging import CRITICAL, getLevelName |
from api.decorators import catch_exception
from api.task.utils import task_log
logger = get_task_logger(__name__)
class DetailLog(list):
"""
List-like object for collecting log lines for task log detail.
"""
def __init__(self, task_id, msg, obj=None):
super(DetailLog, self).__init__()
... | from functools import wraps
from django.utils.decorators import available_attrs
from celery import states
from celery.utils.log import get_task_logger | random_line_split |
log.py | from logging import CRITICAL, getLevelName
from functools import wraps
from django.utils.decorators import available_attrs
from celery import states
from celery.utils.log import get_task_logger
from api.decorators import catch_exception
from api.task.utils import task_log
logger = get_task_logger(__name__)
class De... | (task_id, sender, **kwargs):
logger.info('Primary task %s issued a secondary mgmt monitoring task %s', sender, task_id)
status = None
# Every monitoring task should collect logs
# NOTE: However, the monitoring task is responsible for setting up the object related to the l... | inner | identifier_name |
log.py | from logging import CRITICAL, getLevelName
from functools import wraps
from django.utils.decorators import available_attrs
from celery import states
from celery.utils.log import get_task_logger
from api.decorators import catch_exception
from api.task.utils import task_log
logger = get_task_logger(__name__)
class De... | detail=self.get_detail(), dc_id=self.dc_id, update_user_tasks=False)
def save_task_log(msg):
"""
Decorator used by monitoring tasks. It creates a unique list-like object for collecting monitoring logs and is
responsible for creating a task log entry after the monitoring task is finished.... | """Save task log entry if result is not None"""
if hasattr(status, '__iter__'):
status = [i for i in status if i is not None] # remove None from result
if status:
success = all(status)
else:
success = None
else:
success = ... | identifier_body |
espacioFisico.ts | import { Document, Model, model, Schema } from 'mongoose';
import * as edificioSchema from '../../../core/tm/schemas/edificio';
import * as nombreSchema from '../../../core/tm/schemas/nombre';
import { ISnomedConcept, SnomedConcept } from './../../rup/schemas/snomed-concept';
export interface IEspacioFisico extends Do... |
export const EspacioFisicoSchema = new Schema({
nombre: String,
detalle: String,
descripcion: String,
organizacion: { type: nombreSchema },
edificio: { type: edificioSchema },
sector: { type: nombreSchema },
servicio: { type: nombreSchema },
equipamiento: [SnomedConcept],
activo: Bo... | estado: {
type: String;
enum: ['disponible', 'mantenimiento', 'clausurado', 'baja permanente'];
};
} | random_line_split |
plugin_disablesshpasswdauth_test.py | #!/usr/bin/python
#
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | self.assertEquals(file(self.sshdConfigFile).read(),
self.SshdConfigContents.replace(
'\nPasswordAuthentication yes',
'\nPasswordAuthentication no').replace(
'# PasswordAuthentication yes',
'# # PasswordAuthentication yes')
... | identifier_body | |
plugin_disablesshpasswdauth_test.py | #!/usr/bin/python
#
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
def setUpExtra(self):
sshdConfigDir = self.mkdirs("etc/ssh")
sshdConfig = self.sshdConfigFile = os.path.join(
sshdConfigDir, "sshd_config")
file(sshdConfig, "w").write(self.SshdConfigContents)
def testFiles(self):
self.assertEquals(file(self.sshdConfigFile).read(),
... | PasswordAuthentication yes
# PasswordAuthentication yes
Dummy line 3
""" | random_line_split |
plugin_disablesshpasswdauth_test.py | #!/usr/bin/python
#
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | (self):
self.assertEquals(file(self.sshdConfigFile).read(),
self.SshdConfigContents.replace(
'\nPasswordAuthentication yes',
'\nPasswordAuthentication no').replace(
'# PasswordAuthentication yes',
'# # PasswordAuthen... | testFiles | identifier_name |
radio.js | /* eslint-env mocha */
const mockBot = require('../mockBot')
const assert = require('assert')
const mockery = require('mockery')
const sinon = require('sinon')
const json = JSON.stringify({
state: 'normal',
nowTitle: 'Midnight News',
nowInfo: '20/03/2019',
nextStart: '2019-03-20T00:30:00Z',
nextTitle: 'Book ... | before(function () {
// mockery mocks the entire require()
mockery.enable()
mockery.registerMock('request-promise', {
get: () => Promise.resolve(json)
})
// sinon stubs individual functions
sandbox = sinon.sandbox.create()
mockBot.loadModule('radio')
})
it('should parse the AP... | })
describe('radio module', function () {
let sandbox
| random_line_split |
averageflags.py | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
flags = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").split_rows('country').set_index('country').drop_duplicates(subset='flag', keep='first')
def flag_image(c):
return Image.from_url_w... |
average = ImageColor.from_linear(sum(ImageColor.to_linear(np.array(img.resize(size))) * w for img,w in zip(imgs, weights)) / sum(weights))
return Image.fromarray(np.uint8(average))
def average_flag(df, size, weights=None):
if callable(weights): weights = weights(df)
flags = [flag_image(i) for i in df.... | weights = [1 for _ in imgs] | conditional_block |
averageflags.py | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
flags = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").split_rows('country').set_index('country').drop_duplicates(subset='flag', keep='first')
def flag_image(c):
return Image.from_url_w... | (imgs, size, weights=None):
if weights is None: weights = [1 for _ in imgs]
average = ImageColor.from_linear(sum(ImageColor.to_linear(np.array(img.resize(size))) * w for img,w in zip(imgs, weights)) / sum(weights))
return Image.fromarray(np.uint8(average))
def average_flag(df, size, weights=None):
if c... | average_image | identifier_name |
averageflags.py | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
flags = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").split_rows('country').set_index('country').drop_duplicates(subset='flag', keep='first')
def flag_image(c):
return Image.from_url_w... | df = pd.read_html("https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_area")[0]
df = df.rename(columns=df.iloc[0])[1:].fillna("0")
df = df.assign_rows(country=lambda d: d[next(c for c in df.columns if "state" in c)].split(" (")[0].split(" !")[-1].strip(" \xa0"),
area=lambda d: d[nex... | # quick and dirty scrape of some area data: will add to the country dataset at some point
| random_line_split |
averageflags.py | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
flags = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").split_rows('country').set_index('country').drop_duplicates(subset='flag', keep='first')
def flag_image(c):
|
def average_image(imgs, size, weights=None):
if weights is None: weights = [1 for _ in imgs]
average = ImageColor.from_linear(sum(ImageColor.to_linear(np.array(img.resize(size))) * w for img,w in zip(imgs, weights)) / sum(weights))
return Image.fromarray(np.uint8(average))
def average_flag(df, size, ... | return Image.from_url_with_cache(flags['flag'][c]).convert("RGBA").remove_transparency("white").convert("RGB") | identifier_body |
signUp.js | $ = $.noConflict();
$(document).ready(function() {
$("#signupForm").submit(function(event) {
event.preventDefault();
});
// hide the span elements which show errors (initially)
$("#invEmail").hide();
$("#existEmail").hide();
$("#succSignUp").hide();
$("#btnSignUp").click(function() {... | $("#existEmail").show().fadeOut(4000);
console.log("Email Id already exists.")
console.log(error);
}
});
}
// Unusually long email entered
else {
$("#invEmail").show().fadeOut(4000);
c... | // Entered email id already exists | random_line_split |
signUp.js | $ = $.noConflict();
$(document).ready(function() {
$("#signupForm").submit(function(event) {
event.preventDefault();
});
// hide the span elements which show errors (initially)
$("#invEmail").hide();
$("#existEmail").hide();
$("#succSignUp").hide();
$("#btnSignUp").click(function() {... |
});
});
| {
$("#invEmail").show().fadeOut(4000);
console.log("Email Id is too long!")
} | conditional_block |
E0597.rs | // Copyright 2017 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 ... | }
| { } | identifier_body |
E0597.rs | // Copyright 2017 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 ... | x.x = Some(&y);
//~^ `y` does not live long enough [E0597]
}
impl<'a> Drop for Foo<'a> { fn drop(&mut self) { } } |
fn main() {
let mut x = Foo { x: None };
let y = 0; | random_line_split |
E0597.rs | // Copyright 2017 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 ... | <'a> {
x: Option<&'a u32>,
}
fn main() {
let mut x = Foo { x: None };
let y = 0;
x.x = Some(&y);
//~^ `y` does not live long enough [E0597]
}
impl<'a> Drop for Foo<'a> { fn drop(&mut self) { } }
| Foo | identifier_name |
ChartQueryParameters.js | /* COPYRIGHT 2012 SUPERMAP
* 本程序只能在有效的授权许可下使用。
* 未经许可,不得以任何手段擅自使用或传播。*/
/**
* @requires SuperMap/Util.js
* @requires SuperMap/REST.js
*/
/**
* Class: SuperMap.REST.ChartQueryParameters
* 海图查询参数类,该类用于设置海图查询时的相关参数,海图查询分为海图属性
* 查询和海图范围查询两类,通过属性queryMode指定查询模式。必设属性有:
* queryMode、chartLayerNames、chart... | me.chartLayerNames = null;
me.chartQueryFilterParameters = null;
me.returnContent = true;
me.startRecord = 0;
me.expectCount = null;
},
/**
* Method: getVariablesJson
* 将属性信息转换成能够被服务识别的JSON格式字符串。
*/
getVariablesJson:function () {
var json="";
... | random_line_split | |
ChartQueryParameters.js | /* COPYRIGHT 2012 SUPERMAP
* 本程序只能在有效的授权许可下使用。
* 未经许可,不得以任何手段擅自使用或传播。*/
/**
* @requires SuperMap/Util.js
* @requires SuperMap/REST.js
*/
/**
* Class: SuperMap.REST.ChartQueryParameters
* 海图查询参数类,该类用于设置海图查询时的相关参数,海图查询分为海图属性
* 查询和海图范围查询两类,通过属性queryMode指定查询模式。必设属性有:
* queryMode、chartLayerNames、chart... | conditional_block | ||
api_v2.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# 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
#... | (self):
session = db.get_session()
return session.query(ryu_models_v2.TunnelKey).all()
def set_port_status(session, port_id, status):
try:
port = session.query(models_v2.Port).filter_by(id=port_id).one()
port['status'] = status
session.merge(port)
session.flush()
... | all_list | identifier_name |
api_v2.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# 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
#... |
def _last_key(self, session):
try:
return session.query(ryu_models_v2.TunnelKeyLast).one()
except orm_exc.MultipleResultsFound:
max_key = session.query(
func.max(ryu_models_v2.TunnelKeyLast.last_key))
if max_key > self.key_max:
ma... | self.key_min = key_min
self.key_max = key_max
if (key_min < self._KEY_MIN_HARD or key_max > self._KEY_MAX_HARD or
key_min > key_max):
raise ValueError(_('Invalid tunnel key options '
'tunnel_key_min: %(key_min)d '
... | identifier_body |
api_v2.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# 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
#... |
port = port_and_sgs[0][0]
plugin = manager.NeutronManager.get_plugin()
port_dict = plugin._make_port_dict(port)
port_dict[ext_sg.SECURITYGROUPS] = [
sg_id for port_, sg_id in port_and_sgs if sg_id]
port_dict['security_group_rules'] = []
port_dict['security_group_source_groups'] = []
... | return None | conditional_block |
api_v2.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# 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
#... | session.query(ryu_models_v2.TunnelKeyLast).delete()
last_key = ryu_models_v2.TunnelKeyLast(last_key=max_key)
except orm_exc.NoResultFound:
last_key = ryu_models_v2.TunnelKeyLast(last_key=self.key_min)
session.add(last_key)
session.flush()
return sessi... | random_line_split | |
unary_expr.rs | ///! fff-lang
///!
///! syntax/unary_expr
///! unary_expr = { unary_operator } postfix_expr
use std::fmt;
use crate::source::Span;
use crate::lexical::Token;
use crate::lexical::Seperator;
use crate::lexical::SeperatorCategory;
use super::Expr;
use super::PostfixExpr;
use super::super::Formatter;
use supe... | fn unary_expr_parse() {
use crate::lexical::LitValue;
use super::LitExpr;
use super::super::WithTestInput;
assert_eq!{ make_node!("1"),
Expr::Lit(LitExpr::new(LitValue::from(1), Span::new(0, 0)))
}
assert_eq!{ make_node!("!~!1"),
Expr::Unary(UnaryExpr::new(
... | #[cfg(test)] #[test]
| random_line_split |
unary_expr.rs | ///! fff-lang
///!
///! syntax/unary_expr
///! unary_expr = { unary_operator } postfix_expr
use std::fmt;
use crate::source::Span;
use crate::lexical::Token;
use crate::lexical::Seperator;
use crate::lexical::SeperatorCategory;
use super::Expr;
use super::PostfixExpr;
use super::super::Formatter;
use supe... | (&self, f: Formatter) -> String {
f.indent().header_text_or("unary-expr").space().span(self.all_span).endl()
.indent1().lit("\"").debug(&self.operator).lit("\"").space().span(self.operator_span).endl()
.apply1(self.base.as_ref())
.finish()
}
}
impl fmt::Debug for U... | format | identifier_name |
unary_expr.rs | ///! fff-lang
///!
///! syntax/unary_expr
///! unary_expr = { unary_operator } postfix_expr
use std::fmt;
use crate::source::Span;
use crate::lexical::Token;
use crate::lexical::Seperator;
use crate::lexical::SeperatorCategory;
use super::Expr;
use super::PostfixExpr;
use super::super::Formatter;
use supe... | }
} | {
use crate::lexical::LitValue;
use super::LitExpr;
use super::super::WithTestInput;
assert_eq!{ make_node!("1"),
Expr::Lit(LitExpr::new(LitValue::from(1), Span::new(0, 0)))
}
assert_eq!{ make_node!("!~!1"),
Expr::Unary(UnaryExpr::new(
Seperator::Lo... | identifier_body |
trait-inheritance-overloading-xc-exe.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 (a, b, c) = f(x, y);
assert_eq!(a, mi(8));
assert_eq!(b, mi(-2));
assert_eq!(c, mi(15)); | random_line_split |
trait-inheritance-overloading-xc-exe.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... |
fn mi(v: isize) -> MyInt { MyInt { val: v } }
pub fn main() {
let (x, y) = (mi(3), mi(5));
let (a, b, c) = f(x, y);
assert_eq!(a, mi(8));
assert_eq!(b, mi(-2));
assert_eq!(c, mi(15));
}
| {
return (x.clone() + y.clone(), x.clone() - y.clone(), x * y);
} | identifier_body |
trait-inheritance-overloading-xc-exe.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... | (v: isize) -> MyInt { MyInt { val: v } }
pub fn main() {
let (x, y) = (mi(3), mi(5));
let (a, b, c) = f(x, y);
assert_eq!(a, mi(8));
assert_eq!(b, mi(-2));
assert_eq!(c, mi(15));
}
| mi | identifier_name |
wsgi.py | """
WSGI config for Texas LAN Web project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICAT... | # application = HelloWorldApplication(application) | random_line_split | |
gnome.py | This module provides helper functions for Gnome/GLib related
functionality such as gobject-introspection and gresources.'''
import build
import os, sys
import subprocess
from coredata import MesonException
import mlog
class GnomeModule:
def compile_resources(self, state, args, kwargs):
cmd = ['glib-compi... |
if not 'src_dir' in kwargs:
raise MesonException('Keyword argument src_dir missing.')
main_file = kwargs.get('main_sgml', '')
if not isinstance(main_file, str):
raise MesonException('Main sgml keyword argument must be a string.')
main_xml = kwargs.get('main_xml',... | raise MesonException('Gtkdoc arg must be string.') | conditional_block |
gnome.py | = args[0]
while hasattr(girtarget, 'held_object'):
girtarget = girtarget.held_object
if not isinstance(girtarget, (build.Executable, build.SharedLibrary)):
raise MesonException('Gir target must be an executable or shared library')
pkgstr = subprocess.check_output(['pkg-c... | super().__init__(name, subdir, kwargs) | identifier_body | |
gnome.py | This module provides helper functions for Gnome/GLib related
functionality such as gobject-introspection and gresources.'''
import build
import os, sys
import subprocess
from coredata import MesonException
import mlog
class GnomeModule:
def compile_resources(self, state, args, kwargs):
cmd = ['glib-compi... | # lib/x86_64-linux-gnu but the girepo dir is always under lib.
kwargs['install_dir'] = 'lib/girepository-1.0'
typelib_target = TypelibTarget(typelib_output, state.subdir, kwargs)
return [scan_target, typelib_target]
def compile_schemas(self, state, args, kwargs):
if len(args... | typelib_cmd += ["--includedir=%s" % girdir]
kwargs['output'] = typelib_output
kwargs['command'] = typelib_cmd
# Note that this can't be libdir, because e.g. on Debian it points to | random_line_split |
gnome.py | 1:
raise MesonException('Gir takes one argument')
girtarget = args[0]
while hasattr(girtarget, 'held_object'):
girtarget = girtarget.held_object
if not isinstance(girtarget, (build.Executable, build.SharedLibrary)):
raise MesonException('Gir target must be an ... | __init__ | identifier_name | |
PLSVM.py | from __future__ import division
__author__ = 'wenqihe'
import sys
import random
import math
class PLSVM:
def __init__(self, feature_size, label_size, type_hierarchy, lambda_reg=0.1, max_iter=5000, threshold=0.5, batch_size=100):
self._feature_size = feature_size
self._label_size = label_size
... | (self, x):
labels = set()
parent_mapping = self._type_hierarchy._type_hierarchy
scores = []
max_index = 0
max_value = self.inner_prod(self._weight[0], x)
scores.append(max_value)
for i in xrange(1, self._label_size):
temp = self.inner_prod(self._weight... | predict | identifier_name |
PLSVM.py | from __future__ import division
__author__ = 'wenqihe'
import sys
import random
import math
class PLSVM:
def __init__(self, feature_size, label_size, type_hierarchy, lambda_reg=0.1, max_iter=5000, threshold=0.5, batch_size=100):
self._feature_size = feature_size
self._label_size = label_size
... | yi = self.find_max(y, x)
nyi = self.find_max(ny, x)
for feature in x:
self._weight[yi][feature] = self._weight[yi][feature]*(1-eta_t*self._lambda_reg) + eta_t
self._weight[nyi][feature] = self._weight[nyi][feature]*(1-eta_t*self._la... | ny = [k for k in range(self._label_size) if k not in y] | random_line_split |
PLSVM.py | from __future__ import division
__author__ = 'wenqihe'
import sys
import random
import math
class PLSVM:
def __init__(self, feature_size, label_size, type_hierarchy, lambda_reg=0.1, max_iter=5000, threshold=0.5, batch_size=100):
self._feature_size = feature_size
self._label_size = label_size
... |
# self.update_weight(dW, eta_t, 1)
sys.stdout.write('{0} iteration done.\r'.format(t))
sys.stdout.flush()
def predict(self, x):
labels = set()
parent_mapping = self._type_hierarchy._type_hierarchy
scores = []
max_index = 0
... | self._weight[yi][feature] = self._weight[yi][feature]*(1-eta_t*self._lambda_reg) + eta_t
self._weight[nyi][feature] = self._weight[nyi][feature]*(1-eta_t*self._lambda_reg) - eta_t | conditional_block |
PLSVM.py | from __future__ import division
__author__ = 'wenqihe'
import sys
import random
import math
class PLSVM:
def __init__(self, feature_size, label_size, type_hierarchy, lambda_reg=0.1, max_iter=5000, threshold=0.5, batch_size=100):
self._feature_size = feature_size
self._label_size = label_size
... | i1 = 0
i2 = 0
result = 0
while i1<len(x1) and i2<len(x2):
if x1[i1] == x2[i2]:
result += 1
i1 += 1
i2 += 1
elif x1[i1] < x2[i2]:
i1 += 1
else:
i2 += 1
return result | identifier_body | |
dompoint.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{
DOMPointInit, DOMPointMethods, Wrap,
};
use c... | (&self, value: f64) {
self.point.SetY(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn Z(&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.poin... | SetY | identifier_name |
dompoint.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{
DOMPointInit, DOMPointMethods, Wrap,
};
use c... | }
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn SetX(&self, value: f64) {
self.point.SetX(value);
... | }
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> {
DOMPoint::new(global, p.x, p.y, p.z, p.w) | random_line_split |
dompoint.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{
DOMPointInit, DOMPointMethods, Wrap,
};
use c... |
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn SetX(&self, value: f64) {
self.point.SetX(value);
}
... | {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
} | identifier_body |
provideSignatureHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp);
| {
const supports = SignatureHelpProviderRegistry.ordered(model);
let result: SignatureHelp;
return sequence(supports.map(support => () => {
if (result) {
// stop when there is a result
return undefined;
}
return asWinJsPromise(token => support.provideSignatureHelp(model, position, token)).then(thisRe... | identifier_body |
provideSignatureHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return asWinJsPromise(token => support.provideSignatureHelp(model, position, token)).then(thisResult => {
result = thisResult;
}, onUnexpectedExternalError);
})).then(() => result);
}
registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp);
| {
// stop when there is a result
return undefined;
} | conditional_block |
provideSignatureHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp); | }
| random_line_split |
provideSignatureHelp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (model: IReadOnlyModel, position: Position): TPromise<SignatureHelp> {
const supports = SignatureHelpProviderRegistry.ordered(model);
let result: SignatureHelp;
return sequence(supports.map(support => () => {
if (result) {
// stop when there is a result
return undefined;
}
return asWinJsPromise(token... | provideSignatureHelp | identifier_name |
Const.ts | // *Astronomical unit in kilometres*
// const ASTRONOMICAL_UNIT = 149597870.0;
// *Julian day number (JDN) of Gregorian epoch: 0000-01-01*
const J0000 = 1721424.5;
// *Julian day number (JDN) at Unix epoch: 1970-01-01*
const J1970 = 2440587.5;
// *Epoch of Modified Julian day number (JDN) system*
const JMJD = 240000... | const JULIAN_CENTURY = 36525;
// *Days in Julian millennium*
// const JULIAN_MILLENIUM = 365250;
| random_line_split | |
rx-stream-pacing.py | #!/usr/bin/env python3
'''
Make a stream emit at the pace of a slower stream
Pros:
Introduce a delay between events in an otherwise rapid stream (like range)
Cons:
When the stream being delayed runs out of events to push, the zipped stream
will keep pushing events, defined with the lambda fn ... | # => Value published to observer 1: 5
# => Value published to observer 2: 5
# => Value published to observer 1: 6
# => Value published to observer 2: 6
# => Value published to observer 2: 7
# => Value published to observer 1: 7
# => Value published to observer 2: 8
# => Value published to observer 1: 8 | sleep(5)
sub1.dispose()
sub2.dispose()
| random_line_split |
run.py | from flask import Flask, request, redirect, session
import twilio.twiml
import navigation
SECRET_KEY = 'donuts'
logging = True
app = Flask(__name__)
app.config.from_object(__name__)
def log(mesagge=""):
if logging:
print mesagge
@app.route("/", methods=['GET', 'POST'])
def main_reply():
# Log value... | app.run(debug=True) | conditional_block | |
run.py | from flask import Flask, request, redirect, session
import twilio.twiml
import navigation
SECRET_KEY = 'donuts'
logging = True
app = Flask(__name__)
app.config.from_object(__name__)
def log(mesagge=""):
if logging:
print mesagge
@app.route("/", methods=['GET', 'POST'])
def | ():
# Log values from request
from_number = request.values.get('From', None)
log(from_number)
recieved_message = request.values.get('Body')
log(recieved_message)
# pick reply to message
reply = navigation.choose_script(bodyText=recieved_message)
# trim the length of the reply to one text... | main_reply | identifier_name |
run.py | from flask import Flask, request, redirect, session
import twilio.twiml
import navigation
SECRET_KEY = 'donuts'
logging = True
app = Flask(__name__)
app.config.from_object(__name__)
def log(mesagge=""):
if logging:
print mesagge
@app.route("/", methods=['GET', 'POST'])
def main_reply():
# Log value... | recieved_message = request.values.get('Body')
log(recieved_message)
# pick reply to message
reply = navigation.choose_script(bodyText=recieved_message)
# trim the length of the reply to one text
if len(reply) > 160:
reply = reply[0:159]
if reply == "":
reply = "Error."
#... | log(from_number) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.