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 |
|---|---|---|---|---|
mod.rs | use command_prelude::*;
pub fn | () -> Vec<App> {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
... | builtin | identifier_name |
mod.rs | use command_prelude::*;
pub fn builtin() -> Vec<App> {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_p... | "doc" => doc::exec,
"fetch" => fetch::exec,
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"init" => init::exec,
"install" => install::exec,
"locate-project" => locate_project::exec,
"login" => login::exec,
"m... | "build" => build::exec,
"check" => check::exec,
"clean" => clean::exec, | random_line_split |
mod.rs | use command_prelude::*;
pub fn builtin() -> Vec<App> | read_manifest::cli(),
run::cli(),
rustc::cli(),
rustdoc::cli(),
search::cli(),
test::cli(),
uninstall::cli(),
update::cli(),
verify_project::cli(),
version::cli(),
yank::cli(),
]
}
pub fn builtin_exec(cmd: &str) -> Option<fn(&... | {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
metadata:... | identifier_body |
_build.rs | use std::env;
use std::path::PathBuf;
fn | () {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
... | main | identifier_name |
_build.rs | use std::env;
use std::path::PathBuf;
fn main() | dll_dir.push("64");
} else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.exp... | {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
... | identifier_body |
_build.rs | use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") | lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let fi... | {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
} else {
... | conditional_block |
_build.rs | use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone(... | println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = m... | random_line_split | |
commands.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
import click
from werkzeug.security import generate_password_hash
import newspipe.models
from newspipe.bootstrap import application, db
from newspipe.controller... | ():
"Will create the database from conf parameters."
with application.app_context():
try:
db.create_all()
except Exception as e:
print(e)
@application.cli.command("create_admin")
@click.option("--nickname", default="admin", help="Nickname")
@click.option("--password", d... | db_create | identifier_name |
commands.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
import click
from werkzeug.security import generate_password_hash
import newspipe.models
from newspipe.bootstrap import application, db
from newspipe.controller... | "is_api": True,
"is_active": True,
"nickname": nickname,
"pwdhash": generate_password_hash(password),
}
with application.app_context():
try:
UserController(ignore_context=True).create(**admin)
except Exception as e:
print(e)
@application.... | def create_admin(nickname, password):
"Will create an admin user."
admin = {
"is_admin": True, | random_line_split |
commands.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
import click
from werkzeug.security import generate_password_hash
import newspipe.models
from newspipe.bootstrap import application, db
from newspipe.controller... |
users = UserController().read(**filters).all()
try:
feed_id = int(feed_id)
except:
feed_id = None
loop = asyncio.get_event_loop()
queue = asyncio.Queue(maxsize=3, loop=loop)
producer_coro = default_crawler.retrieve_feed(queue, users, feed_id)
... | filters["id"] = user_id | conditional_block |
commands.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
import click
from werkzeug.security import generate_password_hash
import newspipe.models
from newspipe.bootstrap import application, db
from newspipe.controller... |
@application.cli.command("fetch_asyncio")
@click.option("--user-id", default=None, help="Id of the user")
@click.option("--feed-id", default=None, help="If of the feed")
def fetch_asyncio(user_id=None, feed_id=None):
"Crawl the feeds with asyncio."
import asyncio
with application.app_context():
... | filter = {}
filter["entry_id"] = None
articles = ArticleController().read(**filter).limit(50)
for article in articles:
try:
article.entry_id = str(article.id)
db.session.commit()
except:
db.session.rollback() | identifier_body |
evernote_exporter.py |
def _counter(self, ind, msg):
stdout.write('\r' + '\t%s: %s' % (msg, ind))
stdout.flush()
def _exception(self, msg, file_path, e):
logging.error(e)
while True:
inp = input('Cannot %s: %s\n'
'Error: %s\n'
'Skip & conti... | # fix urls and images
new_c = re.sub(r'\*{2}(\[)|\)\*{2}', self._remove_asterisks, new_c)
# new_c = re.sub(r'!*\[[^\]]*\]\([^\)]*\)', self._image_url_fix, new_c)
new_c = re.sub(r'!*[\\\[]*\[[^\]]*[\\\]]*\([^\)]*[\]\)]*(\([^\)]*\))*', self._image_url_fix, new_c)
return new_c
... | spaces = re.compile(r'^[^\S\n]*\*', re.MULTILINE)
new_c = re.sub(spaces, self._fix_spacing, new_c)
| random_line_split |
evernote_exporter.py |
def _counter(self, ind, msg):
stdout.write('\r' + '\t%s: %s' % (msg, ind))
stdout.flush()
def _exception(self, msg, file_path, e):
logging.error(e)
while True:
inp = input('Cannot %s: %s\n'
'Error: %s\n'
'Skip & conti... |
# todo: image path (remove random dash? -_) i.e t seal img
path = self._remove_chars(path, self.fb_w_trail, trail=True)
path += '?800'
if not url:
return '{{%s|%s}}' % (path, title)
else:
return '[[%s|{{%s|%s}}]]' % (url, path, title)
def _remove_as... | url = ''
string = matchobj.group(0)
# remove escape chars
if '\n' in string:
string = string.replace('\n', ' ')
# this is a url
if '![' not in string:
url, _ = self._get_pt(string)
return '%s' % url
# image contains url
url_p... | identifier_body |
evernote_exporter.py | (object):
def __init__(self, evernote_dir, db_dir='', output_dir=''):
self.forbidden = ["?", "#", "/", "\\", "*", '"', "<", ">", "|", "%", " "]
self.fb_w_trail = self.forbidden
del self.fb_w_trail[2]
self.evernote_dir = evernote_dir
self.db_dir = db_dir
self.output_d... | BackupEvernote | identifier_name | |
evernote_exporter.py |
def _counter(self, ind, msg):
stdout.write('\r' + '\t%s: %s' % (msg, ind))
stdout.flush()
def _exception(self, msg, file_path, e):
logging.error(e)
while True:
inp = input('Cannot %s: %s\n'
'Error: %s\n'
'Skip & conti... | nb_in_stack = self.output_dir + '/%s/%s' % (stack, notebook)
if not os.path.isdir(nb_in_stack):
os.mkdir(nb_in_stack)
s_dir = nb_in_stack
for p, d, files in os.walk(self.evernote_dir):
for f in files:
... | nb_id, notebook, stack = i[0], i[1], i[2]
stack = self._remove_chars(stack, folder_chars)
notebook = self._remove_chars(notebook, folder_chars)
nb_notes = con.execute('SELECT * FROM note_attr WHERE note_attr.notebook_uid = %s;' % nb_id)
notes_set = {i[1] for i in nb_note... | conditional_block |
ADQ14_FWDAQ_streaming_example.py | _timeout = 0.5
# Load ADQAPI
ADQAPI = adqapi_load()
# Create ADQControlUnit
adq_cu = ct.c_void_p(ADQAPI.CreateADQControlUnit())
# Enable error logging from ADQAPI
ADQAPI.ADQControlUnit_EnableErrorTrace(adq_cu, 3, '.')
# Find ADQ devices
ADQAPI.ADQControlUnit_FindDevices(adq_cu)
n_of_ADQ = ADQAP... |
print('Waiting for data...')
# Collect data until all requested records have been recieved
records_completed = [0, 0, 0, 0]
headers_completed = [0, 0, 0, 0]
records_completed_cnt = 0
ltime = time.time()
buffers_filled = ct.c_uint(0)
# Read out data until records_completed for ch A is number_of_records
whi... | ADQAPI.ADQ_SWTrig(adq_cu, adq_num) | conditional_block |
ADQ14_FWDAQ_streaming_example.py | _timeout = 0.5
# Load ADQAPI
ADQAPI = adqapi_load()
# Create ADQControlUnit
adq_cu = ct.c_void_p(ADQAPI.CreateADQControlUnit())
# Enable error logging from ADQAPI
ADQAPI.ADQControlUnit_EnableErrorTrace(adq_cu, 3, '.')
# Find ADQ devices
ADQAPI.ADQControlUnit_FindDevices(adq_cu)
n_of_ADQ = ADQAP... | # Read out data until records_completed for ch A is number_of_records
while (number_of_records > records_completed[0]):
buffers_filled.value = 0
collect_result = 1
poll_time_diff_prev = time.time()
# Wait for next data buffer
while ((buffers_filled.value == 0) and (collect_result)):
collect_result ... | random_line_split | |
Dots.tsx | import * as React from "react";
import * as PropTypes from "prop-types";
import IconButton from "../IconButton";
import Icon from "../Icon";
export interface DotsProps {
count: number;
showControl: boolean;
controlStyle: React.CSSProperties;
controlContentStyle: React.CSSProperties;
iconStyle: React.CSSProp... | {Array(count).fill(0).map((numb, index) => (
<Icon
style={iconStyle}
onClick={() => {
this.setState({ focusSwipeIndex: index });
handleSwipeToIndex(index);
}}
key={`${index}`}
>
... | return (
count > 1 && showControl && (
<div {...classes.controlStyle}>
<div {...classes.controlContentStyle}> | random_line_split |
no_effect.rs | #![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32... | (&mut self) {}
}
struct FooString {
s: String,
}
union Union {
a: u8,
b: f64,
}
fn get_number() -> i32 {
0
}
fn get_struct() -> Struct {
Struct { field: 0 }
}
fn get_drop_struct() -> DropStruct {
DropStruct { field: 0 }
}
unsafe fn unsafe_fn() -> i32 {
0
}
fn main() {
let s = get_stru... | drop | identifier_name |
no_effect.rs | #![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32... |
fn main() {
let s = get_struct();
let s2 = get_struct();
0;
s2;
Unit;
Tuple(0);
Struct { field: 0 };
Struct { ..s };
Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5... | {
0
} | identifier_body |
no_effect.rs | #![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32... | Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5..=6;
[42, 55];
[42, 55][1];
(42, 55).1;
[42; 55];
[42; 55][13];
let mut x = 0;
|| x += 5;
let s: String = "foo".into();... | Struct { ..s }; | random_line_split |
app_settings.py | from __future__ import unicode_literals
from django.conf import settings
from drf_authentication.serializers.drf_auth_login_serializer \
import DrfAuthLoginSerializer
from drf_authentication.serializers.drf_auth_logout_serializer \
import DrfAuthLogoutSerializer
from drf_authentication.serializers.drf_auth_us... | (object):
"""
A settings object, that allows API settings to be accessed as properties.
For example:
from rest_framework.settings import api_settings
print(api_settings.DEFAULT_RENDERER_CLASSES)
Any setting with string import paths will be automatically resolved
and return the clas... | APISettings | identifier_name |
app_settings.py | from __future__ import unicode_literals
from django.conf import settings
from drf_authentication.serializers.drf_auth_login_serializer \
import DrfAuthLoginSerializer
from drf_authentication.serializers.drf_auth_logout_serializer \
import DrfAuthLogoutSerializer
from drf_authentication.serializers.drf_auth_us... |
api_settings = APISettings(USER_SETTINGS, DEFAULTS)
| if attr not in self.defaults.keys():
raise AttributeError("Invalid API setting: '%s'" % attr)
try:
# Check if present in user settings
val = self.user_settings[attr]
except KeyError:
# Fall back to defaults
val = self.defaults[attr]
#... | identifier_body |
app_settings.py | from __future__ import unicode_literals
from django.conf import settings
from drf_authentication.serializers.drf_auth_login_serializer \
import DrfAuthLoginSerializer
from drf_authentication.serializers.drf_auth_logout_serializer \
import DrfAuthLogoutSerializer
from drf_authentication.serializers.drf_auth_us... |
try:
# Check if present in user settings
val = self.user_settings[attr]
except KeyError:
# Fall back to defaults
val = self.defaults[attr]
# Cache the result
setattr(self, attr, val)
return val
api_settings = APISettings(USER_S... | raise AttributeError("Invalid API setting: '%s'" % attr) | conditional_block |
app_settings.py | from __future__ import unicode_literals
from django.conf import settings
from drf_authentication.serializers.drf_auth_login_serializer \
import DrfAuthLoginSerializer
from drf_authentication.serializers.drf_auth_logout_serializer \
import DrfAuthLogoutSerializer
from drf_authentication.serializers.drf_auth_us... | """
def __init__(self, user_settings=None, defaults=None):
self.user_settings = user_settings or {}
self.defaults = defaults or DEFAULTS
def __getattr__(self, attr):
if attr not in self.defaults.keys():
raise AttributeError("Invalid API setting: '%s'" % attr)
t... | Any setting with string import paths will be automatically resolved
and return the class, rather than the string literal. | random_line_split |
ZabbixHelper.py | # -*- coding: utf-8 -*-
'''
Created on 2015/04/17
@author: 2015 AIST
'''
import time
from django.conf import settings
from zbxsend import Metric, send_to_zabbix
import logging
import json
from vt_manager_kvm.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator
class ZabbixHelper():
logg... |
driver = HandlerConfigurator.get_vt_am_driver()
vm_urn = driver.generate_sliver_urn(vm)
timestamp = int(time.time())
itemname = settings.ZBX_ITEM_USERVMSTATUS + '[' + str(vm_urn) + ']'
metric = Metric(vm.name, str(itemname), status, timestamp)
ZabbixHelper.sendZabbix(metric)
return
@staticmethod
def s... | status = 2 # DOWN | conditional_block |
ZabbixHelper.py | # -*- coding: utf-8 -*-
'''
Created on 2015/04/17
@author: 2015 AIST
'''
import time
from django.conf import settings
from zbxsend import Metric, send_to_zabbix
import logging
import json
from vt_manager_kvm.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator
class ZabbixHelper():
logg... |
@staticmethod
def sendVMDiscovery(server, vms):
timestamp = int(time.time())
discoveryList = []
for vm in vms:
discovery = {"{#USERVM.NAME}": vm.name}
discoveryList.append(discovery)
tmpobj = {"data": discoveryList}
discoveryStr = json.dumps(tmpobj)
metric = Metric(server.name, settings.ZBX_ITEM_DI... | random_line_split | |
ZabbixHelper.py | # -*- coding: utf-8 -*-
'''
Created on 2015/04/17
@author: 2015 AIST
'''
import time
from django.conf import settings
from zbxsend import Metric, send_to_zabbix
import logging
import json
from vt_manager_kvm.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator
class ZabbixHelper():
logg... |
@staticmethod
def sendVMStatusDiscovery(vms):
timestamp = int(time.time())
driver = HandlerConfigurator.get_vt_am_driver()
for vm in vms:
discoveryList = []
vm_urn = driver.generate_sliver_urn(vm)
discovery = {"{#USERVM.URN}": vm_urn}
discoveryList.append(discovery)
tmpobj = {"data": discoveryL... | timestamp = int(time.time())
discoveryList = []
for vm in vms:
discovery = {"{#USERVM.NAME}": vm.name}
discoveryList.append(discovery)
tmpobj = {"data": discoveryList}
discoveryStr = json.dumps(tmpobj)
metric = Metric(server.name, settings.ZBX_ITEM_DISCOVERY_USERVM,
str(discoveryStr), timestamp)
... | identifier_body |
ZabbixHelper.py | # -*- coding: utf-8 -*-
'''
Created on 2015/04/17
@author: 2015 AIST
'''
import time
from django.conf import settings
from zbxsend import Metric, send_to_zabbix
import logging
import json
from vt_manager_kvm.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator
class ZabbixHelper():
logg... | (server, vms):
timestamp = int(time.time())
discoveryList = []
for vm in vms:
discovery = {"{#USERVM.NAME}": vm.name}
discoveryList.append(discovery)
tmpobj = {"data": discoveryList}
discoveryStr = json.dumps(tmpobj)
metric = Metric(server.name, settings.ZBX_ITEM_DISCOVERY_USERVM,
str(discoveryS... | sendVMDiscovery | identifier_name |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn | (attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let fn_item = syn::parse_item(&fn_ts.to_string()).unwrap();
let function = function::parse(&fn_item).unwrap();
let lisp_fn_args = match remacs_util::parse_lisp_fn(
&attr_ts.to_string(),
&function.name,
function.fntype.def_mi... | lisp_fn | identifier_name |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(att... | {
syn::Ident::new(format!("{}{}", lhs, rhs))
} | identifier_body | |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(att... |
let tokens = quote! {
#[no_mangle]
pub extern "C" fn #fname(#cargs) -> ::remacs_sys::Lisp_Object {
#body
let ret = #rname(#rargs);
::lisp::LispObject::from(ret).to_raw()
}
lazy_static! {
pub static ref #sname: ::lisp::LispSubrRef = ... | {
windows_header = quote!{
| (::std::mem::size_of::<::remacs_sys::Lisp_Subr>()
/ ::std::mem::size_of::<::remacs_sys::EmacsInt>()) as ::libc::ptrdiff_t
};
} | conditional_block |
lib.rs | #![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(att... |
// we could put #fn_item into the quoted code above, but doing so
// drops all of the line numbers on the floor and causes the
// compiler to attribute any errors in the function to the macro
// invocation instead.
// Note: TokenStream has a FromIterator trait impl that converts
// an iterator ... | ::lisp::ExternalPtr::new(ptr)
}
};
}
}; | random_line_split |
c3.py | # -*- coding: utf-8 -*-
"""The ants module provides basic functions for interfacing with ants functions.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/dat... | itk_transform = traits.Either(traits.Bool, File(), hash_files=False,
desc="Export ITK transform.",
argstr="-oitk %s", position=5)
fsl2ras = traits.Bool(argstr='-fsl2ras', position=4)
class C3dAffineToolOutputSpec(TraitedSpec):
itk_transfo... |
class C3dAffineToolInputSpec(CommandLineInputSpec):
reference_file = File(exists=True, argstr="-ref %s", position=1)
source_file = File(exists=True, argstr='-src %s', position=2)
transform_file = File(exists=True, argstr='%s', position=3) | random_line_split |
c3.py | # -*- coding: utf-8 -*-
"""The ants module provides basic functions for interfacing with ants functions.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/dat... |
class C3dAffineToolOutputSpec(TraitedSpec):
itk_transform = File(exists=True)
class C3dAffineTool(SEMLikeCommandLine):
"""Converts fsl-style Affine registration into ANTS compatible itk format
Example
=======
>>> from nipype.interfaces.c3 import C3dAffineTool
>>> c3 = C3dAffineTool()
... | reference_file = File(exists=True, argstr="-ref %s", position=1)
source_file = File(exists=True, argstr='-src %s', position=2)
transform_file = File(exists=True, argstr='%s', position=3)
itk_transform = traits.Either(traits.Bool, File(), hash_files=False,
desc="Export ITK t... | identifier_body |
c3.py | # -*- coding: utf-8 -*-
"""The ants module provides basic functions for interfacing with ants functions.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/dat... | (TraitedSpec):
itk_transform = File(exists=True)
class C3dAffineTool(SEMLikeCommandLine):
"""Converts fsl-style Affine registration into ANTS compatible itk format
Example
=======
>>> from nipype.interfaces.c3 import C3dAffineTool
>>> c3 = C3dAffineTool()
>>> c3.inputs.source_file = 'cma... | C3dAffineToolOutputSpec | identifier_name |
gen_utils.py | import json
import shutil
import sys
import warnings
from itertools import zip_longest
import s3fs
from smart_open import open
from tqdm import tqdm
def session_type():
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return "python"
from IPython import get_ipyt... |
return child_link_name
def find_descendents(cls):
"""
A generator which yields all descendent classes of the given class
(including the given class)
Args:
cls (Class): the class to find descendents of
"""
yield cls
for sub in cls.__subclasses__():
for c in find_descen... | parent_link_name = child_link_name
child_link_name = '%s.%s' % (r.parent_entity.id,
parent_link_name) | conditional_block |
gen_utils.py | import json
import shutil
import sys
import warnings
from itertools import zip_longest
import s3fs
from smart_open import open
from tqdm import tqdm
def session_type():
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return "python"
from IPython import get_ipyt... | return "kernel"
return "ipython"
def make_tqdm_iterator(**kwargs):
options = {
"file": sys.stdout,
"leave": True
}
options.update(kwargs)
if session_type() == 'kernel':
# from IPython import display
# capture_stderr = StringIO()
# with RedirectStdSt... | if getattr(get_ipython(), 'kernel', None) is not None: | random_line_split |
gen_utils.py | import json
import shutil
import sys
import warnings
from itertools import zip_longest
import s3fs
from smart_open import open
from tqdm import tqdm
def session_type():
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return "python"
from IPython import get_ipyt... | s3 = s3fs.S3FileSystem(anon=True)
if read:
with s3.open(file_path, "r", encoding='utf-8') as f:
features_dict = json.load(f)
return features_dict
else:
with s3.open(file_path, "w") as f:
features = json.dumps(features_dict, ensure_ascii=False)
f.wr... | identifier_body | |
gen_utils.py | import json
import shutil
import sys
import warnings
from itertools import zip_longest
import s3fs
from smart_open import open
from tqdm import tqdm
def session_type():
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return "python"
from IPython import get_ipyt... | (path, features_dict=None, transport_params=None, read=True):
if read:
with open(path, 'r', encoding='utf-8', transport_params=transport_params) as f:
features_dict = json.load(f)
return features_dict
else:
with open(path, "w", transport_params=transport_params) as f:
... | use_smartopen_features | identifier_name |
messageevent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | (&self) -> bool {
self.event.IsTrusted()
}
}
| IsTrusted | identifier_name |
messageevent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event... |
pub fn new(global: GlobalRef, type_: Atom, | random_line_split |
messageevent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... |
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap... | {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
} | identifier_body |
script.py | # Orca
#
# Copyright 2005-2008 Sun Microsystems Inc.
#
# 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 your option) any later version.
#
# This... | import orca.speech as speech
import orca.eventsynthesizer as eventsynthesizer
import pyatspi
from orca.orca_i18n import _ # for gettext support
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2005-2008 Sun Microsystems Inc."
__license__ = "LGPL"
class Sc... | random_line_split | |
script.py | # Orca
#
# Copyright 2005-2008 Sun Microsystems Inc.
#
# 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 your option) any later version.
#
# This... |
# Here we handle the case when the focus is in the headlines table.
# See comment #3 of bug #350233.
# http://bugzilla.gnome.org/show_bug.cgi?id=350233
#
if orca_state.locusOfFocus.getRole() == \
pyatspi.ROLE_TABLE_COLUMN_HEADER:
... | utterances = []
utterances.append(_("Work online / offline"))
# Here we extend the utterances with the speech generator for
# the object with focus (the push button).
#
utterances.extend(speechGen.generateSpeech(event.source))
# Finally we spea... | conditional_block |
script.py | # Orca
#
# Copyright 2005-2008 Sun Microsystems Inc.
#
# 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 your option) any later version.
#
# This... | # Here we handle the case when focus is in the "Work online/offline"
# button near the status bar that has an image without a description.
# We speak and braille "Online/Offline button" here, until the
# developer of the application adds a description to the images
# associate... | """Called when the visual object with focus changes.
Arguments:
- event: if not None, the Event that caused the change
- oldLocusOfFocus: Accessible that is the old locus of focus
- newLocusOfFocus: Accessible that is the new locus of focus
"""
brailleGen = self.braille... | identifier_body |
script.py | # Orca
#
# Copyright 2005-2008 Sun Microsystems Inc.
#
# 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 your option) any later version.
#
# This... | (self, event):
# Since we haven't feed back informationb when the
# "work online/offline" status changes, we speech/braille the
# statusbar content which is the the information that sets the
# work online or work offline mode.
#
if event.source.getRole() != pyatspi.ROL... | onNameChanged | identifier_name |
showcase.tsx | // React
import * as React from 'react';
// Components
import {LightboxComponent} from '../lightbox/lightbox';
import './showcase.scss';
export const ShowcaseComponent = (props) => {
// Props
const { title, elements, emptyStateText } = props;
if ( elements.length === 0 ) | className="ShowcaseComponent">
<h3>{title}</h3>
<p>{emptyStateText}</p>
</div>
)
}
return (
<div id={`${props.id | title}`} className="ShowcaseComponent">
<h3>{title}</h3>
<div className="Thumbnails" style={{
columnCount: props.columnCount || '4'
}}>
... | {
return (
<div id={`${props.id | title}`} | conditional_block |
showcase.tsx | // React
import * as React from 'react';
// Components
import {LightboxComponent} from '../lightbox/lightbox';
import './showcase.scss'; | if ( elements.length === 0 ) {
return (
<div id={`${props.id | title}`} className="ShowcaseComponent">
<h3>{title}</h3>
<p>{emptyStateText}</p>
</div>
)
}
return (
<div id={`${props.id | title}`} className="ShowcaseComponent">
<h3>{title}</h3>
<div className="... |
export const ShowcaseComponent = (props) => {
// Props
const { title, elements, emptyStateText } = props;
| random_line_split |
WaterShader.js | 707, 0.70707, 0 ) },
"eye": { type: "v3", value: new THREE.Vector3() },
"waterColor": { type: "c", value: new THREE.Color( 0x555555 ) }
}
] ),
vertexShader: [
'uniform mat4 textureMatrix;',
'uniform float time;',
'varying vec4 mirrorCoord;',
'varying vec3 worldPosition;',
'void... | {
return x ? x < 0 ? - 1 : 1 : 0;
} | identifier_body | |
WaterShader.js | 0707, 0.70707, 0 ) },
"eye": { type: "v3", value: new THREE.Vector3() },
"waterColor": { type: "c", value: new THREE.Color( 0x555555 ) }
}
] ),
vertexShader: [
'uniform mat4 textureMatrix;',
'uniform float time;',
'varying vec4 mirrorCoord;',
'varying vec3 worldPosition;',
'voi... | ( x ) {
return x ? x < 0 ? - 1 : 1 : 0;
| sign | identifier_name |
WaterShader.js | 0707, 0.70707, 0 ) },
"eye": { type: "v3", value: new THREE.Vector3() },
"waterColor": { type: "c", value: new THREE.Color( 0x555555 ) }
}
] ),
vertexShader: [
'uniform mat4 textureMatrix;',
'uniform float time;',
'varying vec4 mirrorCoord;',
'varying vec3 worldPosition;',
'voi... |
'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor )',
'{',
' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
... | '}', | random_line_split |
mpi_helloworld.py | #!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
# | # limitations under the License.
"""
Parallel Hello World
"""
from mpi4py import MPI
import sys
size = MPI.COMM_WORLD.Get_size()
rank = MPI.COMM_WORLD.Get_rank()
name = MPI.Get_processor_name()
sys.stdout.write(
"Hello, World! I am process %d of %d on %s.\n"
% (rank, size, name)) | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and | random_line_split |
SectionAttributesTestCase.js | /*
* Copyright 2013 Amadeus s.a.s.
* 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 i... | checkClasses : function (args) {
var dom = this.dom;
this.assertTrue(dom.classList.contains("class1"), "The dom should contains the class1");
this.assertTrue(dom.classList.contains("class2"), "The dom should contains the class2");
this.assertEquals(dom.classList.... | random_line_split | |
InputArray.tsx | import React from 'react';
import PropTypes from 'prop-types';
import {Row} from './';
import {cloneDeep} from 'lodash';
export const InputArray: React.StatelessComponent<any> = ({
field,
value,
onChange,
addButtonText,
component,
defaultValue,
readOnly,
errors,
...props
}) => {
... | onChange={onChange}
value={val}
remove={remove.bind(null, index)}
readOnly={readOnly}
errors={errors}
{...props} />
))}
{!readOnly && (
<button
... | {value.map((val, index) => (
<Component
key={index}
field={`${field}[${index}]`} | random_line_split |
form.model.spec.ts | import { FormModel } from './form.model';
describe('FormModel', () => {
let data: any;
let model: FormModel;
| item1: {
type: 'text',
label: 'Item1'
},
item2: {
type: 'text',
label: 'Item2',
groupvalidators: [{name: 'compare', fields: ['item1', 'item2']}]
}
};
model = new FormModel();
model.addInput('... | beforeEach(() => {
data = { | random_line_split |
codeplayer.js | var windowHeight = $(window).height();
var menuBarHeight = $('#codeplayer-menubar').height();
$('.codeplayer-code-container').css('height', (windowHeight - menuBarHeight) + 'px');
$('.codeplayer-toogle').click(function() {
$(this).toggleClass('codeplayer-selected');
var codeContainerDiv = '#codeplayer-' + $(thi... | $('#codeplayer-runbuttondiv').click(function() {
var iframeContent = '<style>' +
$('#codeplayer-cssCode').val() +
'</style>' +
$('#codeplayer-htmlCode').val();
$('#codeplayer-iframe').contents().find('html').html(iframeContent);
document.getElementById('codeplayer-iframe').contentW... |
$('.codeplayer-code-container').css('width', divWidthPercentage + '%');
});
| random_line_split |
run.js | /* 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 strict";
var path = require("path");
var fs = require("fs");
var minify = require("jsonminify");
var js_beaut... | (value) {
return value == "true" || value == true;
}
function getUserHome() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
function parseJSON(file) {
try {
return JSON.parse(minify(fs.readFileSync(file, "utf8")));
} catch (e) {
console.log("Could not parse JSON at: " +... | isTrue | identifier_name |
run.js | /* 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 strict";
var path = require("path");
var fs = require("fs");
var minify = require("jsonminify");
var js_beaut... | function isTrue(value) {
return value == "true" || value == true;
}
function getUserHome() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
function parseJSON(file) {
try {
return JSON.parse(minify(fs.readFileSync(file, "utf8")));
} catch (e) {
console.log("Could not par... | // Some handy utility functions.
| random_line_split |
run.js | /* 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 strict";
var path = require("path");
var fs = require("fs");
var minify = require("jsonminify");
var js_beaut... | {
// If file unsaved, check if first non-whitespace character is NOT <
if (path == "?") {
return !data.match(/^\s*</);
}
return isTypeAllowed("js", path);
} | identifier_body | |
run.js | /* 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 strict";
var path = require("path");
var fs = require("fs");
var minify = require("jsonminify");
var js_beaut... |
return isTypeAllowed("css", path);
}
function isHTML(path, data) {
// If file unsaved, check if first non-whitespace character is <
if (path == "?") {
return data.match(/^\s*</);
}
return isTypeAllowed("html", path);
}
function isJS(path, data) {
// If file unsaved, check if first non-whitespace c... | {
return false;
} | conditional_block |
picturepark.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CONFIG as GLOBAL_CONFIG} from '../../data/config.data';
import { IdentityService } from '../../se... | console.log(request);
return this.http.get(request)
.map(res => <Asset[]>res.json())
.catch(this.handleError);
}
private handleError(error: Response) {
// In the future, we may send the server to some remote logging infrastructure
console.error(error);
... | random_line_split | |
picturepark.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CONFIG as GLOBAL_CONFIG} from '../../data/config.data';
import { IdentityService } from '../../se... | {
// Assumes HTTP_PROVIDERS was added as a provider at a higher level
constructor(private http: Http, private _identityService: IdentityService) { }
public getUrlAssets(assets: string): Observable<Asset[]> {
// This function takes in the JSON response from https://pultegroup.picturepark.com/Websit... | PictureParkService | identifier_name |
eslint-plugin-prettier_vx.x.x.js | // flow-typed signature: f9f4fa8dbf1e89fa445e8deb2a98f812
// flow-typed version: <<STUB>>/eslint-plugin-prettier_v^3.0.0/flow_v0.89.0
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-plugin-prettier'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to s... | declare module 'eslint-plugin-prettier/eslint-plugin-prettier' {
declare module.exports: any;
}
// Filename aliases
declare module 'eslint-plugin-prettier/eslint-plugin-prettier.js' {
declare module.exports: $Exports<'eslint-plugin-prettier/eslint-plugin-prettier'>;
} | random_line_split | |
SectionSelectInput.js | import React from 'react'
import { connect } from 'react-redux'
import ItemSelectInput from './ItemSelectInput'
import sectionsActions from '../../../actions/SectionsActions'
class | extends React.Component {
listSections(query) {
let queryObj = {}
if (query) {
queryObj['q'] = query
}
this.props.listSections(this.props.token, queryObj)
}
render() {
return (
<ItemSelectInput
many={false}
value={this.props.value}
inline={this.props.i... | SectionSelectInputComponent | identifier_name |
SectionSelectInput.js | import React from 'react'
import { connect } from 'react-redux'
import ItemSelectInput from './ItemSelectInput'
import sectionsActions from '../../../actions/SectionsActions'
class SectionSelectInputComponent extends React.Component {
listSections(query) {
let queryObj = {}
if (query) |
this.props.listSections(this.props.token, queryObj)
}
render() {
return (
<ItemSelectInput
many={false}
value={this.props.value}
inline={this.props.inline}
showSortableList={this.props.showSortableList}
results={this.props.sections.ids}
entities={thi... | {
queryObj['q'] = query
} | conditional_block |
SectionSelectInput.js | import React from 'react'
import { connect } from 'react-redux'
import ItemSelectInput from './ItemSelectInput'
import sectionsActions from '../../../actions/SectionsActions'
class SectionSelectInputComponent extends React.Component {
listSections(query) {
let queryObj = {}
if (query) {
queryObj['q... |
const mapStateToProps = (state) => {
return {
sections: state.app.sections.list,
entities: {
sections: state.app.entities.sections
},
token: state.app.auth.token
}
}
const mapDispatchToProps = (dispatch) => {
return {
listSections: (token, query) => {
dispatch(sectionsActions.lis... |
} | random_line_split |
SectionSelectInput.js | import React from 'react'
import { connect } from 'react-redux'
import ItemSelectInput from './ItemSelectInput'
import sectionsActions from '../../../actions/SectionsActions'
class SectionSelectInputComponent extends React.Component {
listSections(query) {
let queryObj = {}
if (query) {
queryObj['q... |
}
const mapStateToProps = (state) => {
return {
sections: state.app.sections.list,
entities: {
sections: state.app.entities.sections
},
token: state.app.auth.token
}
}
const mapDispatchToProps = (dispatch) => {
return {
listSections: (token, query) => {
dispatch(sectionsActions... | {
return (
<ItemSelectInput
many={false}
value={this.props.value}
inline={this.props.inline}
showSortableList={this.props.showSortableList}
results={this.props.sections.ids}
entities={this.props.entities.sections}
onChange={(value) => this.props.update(... | identifier_body |
pad_packed_gpu.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;
const innerDims =
rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;
const componentSetup = [
`${dtype} rc = outputLoc;`, `${coords[rank - 1]} += 1;
if(${cLimit}) {
`,
rank === 1 ? '' : `}
... | random_line_split | |
pad_packed_gpu.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | ${coords[rank - 2]} += 1;
if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {`,
rank === 1 ? '' : ` ${coords[rank - 1]} += 1;
if(${cLimit}) {`
];
const paddingArea = rank === 1 ?
'rc < start || rc >= end' :
'any(lessThan(rc, start)) || any(greaterThanEqual(rc... | {
this.outputShape = paddings.map(
(p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);
const rank = xShape.length;
const dtype = getCoordsDataType(rank);
const start = paddings.map(p => p[0]).join(',');
const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');
const... | identifier_body |
pad_packed_gpu.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | implements GPGPUProgram {
variableNames = ['x'];
packedInputs = true;
packedOutput = true;
outputShape: number[];
userCode: string;
customUniforms = [{name: 'value', type: 'float' as UniformType}];
constructor(
xShape: number[], paddings: Array<[number, number]>,
constantValue: number) {
... | PadPackedProgram | identifier_name |
pad_packed_gpu.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
mainLoop += (rank === 1 ? `} ` : `}}`);
this.userCode = `
const ${dtype} start = ${dtype}(${start});
const ${dtype} end = ${dtype}(${end});
void main() {
${dtype} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${mainLoop}
setOutput(result);
}
... | {
mainLoop += `
${componentSetup[i]}
if (${paddingArea}) {
result[${i}] = float(value);
} else {
${dtype} source = rc - start;
result[${i}] = getChannel(getX(${source.join()}), ${innerDims});
}
`;
} | conditional_block |
timed_out-and-back.py | #!/usr/bin/env python
""" timed_out_and_back.py - Version 1.1 2013-12-20
A basic demo of the using odometry data to move the robot along
and out-and-back trajectory.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2012 Patrick Goebel. All rights reserved.
This program is free software; you ca... |
# Stop the robot before the next leg
move_cmd = Twist()
self.cmd_vel.publish(move_cmd)
rospy.sleep(1)
# Stop the robot
self.cmd_vel.publish(Twist())
def shutdown(self):
# Always stop the robot when shutti... | self.cmd_vel.publish(move_cmd)
r.sleep() | conditional_block |
timed_out-and-back.py | #!/usr/bin/env python
""" timed_out_and_back.py - Version 1.1 2013-12-20
A basic demo of the using odometry data to move the robot along
and out-and-back trajectory.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2012 Patrick Goebel. All rights reserved.
This program is free software; you ca... |
for t in range(ticks):
self.cmd_vel.publish(move_cmd)
r.sleep()
# Stop the robot before the rotation
move_cmd = Twist()
self.cmd_vel.publish(move_cmd)
rospy.sleep(1)
# Now rotat... | move_cmd.linear.x = linear_speed
# Move forward for a time to go the desired distance
ticks = int(linear_duration * rate) | random_line_split |
timed_out-and-back.py | #!/usr/bin/env python
""" timed_out_and_back.py - Version 1.1 2013-12-20
A basic demo of the using odometry data to move the robot along
and out-and-back trajectory.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2012 Patrick Goebel. All rights reserved.
This program is free software; you ca... |
if __name__ == '__main__':
try:
OutAndBack()
except:
rospy.loginfo("Out-and-Back node terminated.")
| rospy.loginfo("Stopping the robot...")
self.cmd_vel.publish(Twist())
rospy.sleep(1) | identifier_body |
timed_out-and-back.py | #!/usr/bin/env python
""" timed_out_and_back.py - Version 1.1 2013-12-20
A basic demo of the using odometry data to move the robot along
and out-and-back trajectory.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2012 Patrick Goebel. All rights reserved.
This program is free software; you ca... | (self):
# Give the node a name
rospy.init_node('out_and_back', anonymous=False)
# Set rospy to execute a shutdown function when exiting
rospy.on_shutdown(self.shutdown)
# Publisher to control the robot's speed
self.cmd_vel = rospy.Publisher('/cmd_vel', Twist)
... | __init__ | identifier_name |
jquery.flot.hiddengraphs.js | /* 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/. */
/*
* Plugin to hide series in flot graphs.
*
* To activate, set legend.hideable to true in the flot options obj... |
plot.hooks.processDatapoints.push(hideDatapointsIfNecessary);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'hiddenGraphs',
version: '1.0'
});
})(jQuery);
| {
if (!plot.getOptions().legend.hideable) {
return;
}
if (!s.points.show && !s.lines.show) {
s.datapoints.format = [ null, null ];
}
} | identifier_body |
jquery.flot.hiddengraphs.js | /* 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/. */
/*
* Plugin to hide series in flot graphs.
*
* To activate, set legend.hideable to true in the flot options obj... | (plot) {
function findPlotSeries(label) {
var plotdata = plot.getData();
for (var i = 0; i < plotdata.length; i++) {
if (plotdata[i].label == label) {
return plotdata[i];
}
}
return null;
}
funct... | init | identifier_name |
jquery.flot.hiddengraphs.js | /* 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/. */
/*
* Plugin to hide series in flot graphs.
*
* To activate, set legend.hideable to true in the flot options obj... | * points: { show: true },
* lines: { show: true }
* },
* legend: {
* hideable: true,
* hidden: ["graph 1", "graph 2"]
* }
* });
*
*/
(function ($) {
var options = { };
var drawnOnce = false;
function init(plot) {
... | random_line_split | |
jquery.flot.hiddengraphs.js | /* 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/. */
/*
* Plugin to hide series in flot graphs.
*
* To activate, set legend.hideable to true in the flot options obj... |
// HACK: Reset the data, triggering recalculation of graph bounds
plot.setData(plot.getData());
plot.setupGrid();
plot.draw();
}
function plotLabelHandlers(plot, options) {
$(".graphlabel").mouseenter(function() { $(this).css("cursor", "poi... | {
var switchedOn = false;
if (!series.points.show && series.points.oldShow) {
series.points.show = true;
series.points.oldShow = false;
switchedOn = true;
}
if (!series.lines.show && series.lines.... | conditional_block |
bvh_base.rs | #![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// indivi... | (&self) -> usize {
0
}
fn acc_bounds<'a, T, F>(&mut self, objects: &mut [T], bounder: &F)
where
F: 'a + Fn(&T) -> &'a [BBox],
{
// TODO: do all of this without the temporary cache
let max_len = objects.iter().map(|obj| bounder(obj).len()).max().unwrap();
self.bo... | root_node_index | identifier_name |
bvh_base.rs | #![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// indivi... | self.bounds_cache[i] |= bounds[i];
}
} else {
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
}
}
... | random_line_split | |
bvh_base.rs | #![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// indivi... |
}
}
fn recursive_build<'a, T, F>(
&mut self,
offset: usize,
depth: usize,
objects_per_leaf: usize,
objects: &mut [T],
bounder: &F,
) -> (usize, (usize, usize))
where
F: 'a + Fn(&T) -> &'a [BBox],
{
let me = self.nodes.len();
... | {
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
} | conditional_block |
deriving-rand.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.
//
// 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... | {
D0,
D1(usize),
D2 { x: (), y: () }
}
pub fn main() {
// check there's no segfaults
for _ in 0..20 {
rand::random::<A>();
rand::random::<B>();
rand::random::<C>();
rand::random::<D>();
}
}
| D | identifier_name |
deriving-rand.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.
//
// 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... | } | } | random_line_split |
update_teams.py | #!/usr/bin/python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
# Don't add the ad unit if the team has all inventory already.
if not Utils.BoolTypeConvert(team['hasAllInventory']):
ad_unit_ids.append(ad_unit_id)
team['adUnitIds'] = ad_unit_ids
# Update teams on the server.
teams = team_service.UpdateTeams(teams)
# Display results.
if teams:
for tea... | ad_unit_ids = team['adUnitIds'] | conditional_block |
update_teams.py | #!/usr/bin/python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
"""This example updates teams by adding an ad unit to the first 5.
To determine which teams exist, run get_all_teams.py. To determine which ad
units exist, run get_all_ad_units.py
Tags: TeamService.getTeamsByStatement, TeamService.updateTeams
"""
__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'
# Locate the clien... | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. | random_line_split |
correlations.py | relation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None):
"""
calculates time correlation. Raises P to power 'times' by diagonalization.
If rdl tuple (R, D, L) is given, it will be used for
further calculation.
"""
if rdl is None:
raise ValueError("no rdl decomposition")
... | time_relaxations_direct | identifier_name | |
correlations.py | Created on 29.11.2013
.. moduleauthor:: marscher, noe
'''
from __future__ import absolute_import
import numpy as np
from .decomposition import rdl_decomposition
from six.moves import range
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None):
"""
calculates time correlation. Ra... |
else:
return corr
def time_correlations_direct(P, pi, obs1, obs2=None, times=[1]):
r"""Compute time-correlations of obs1, or time-cross-correlation with obs2.
The time-correlation at time=k is computed by the matrix-vector expression:
cor(k) = obs1' diag(pi) P^k obs2
Parameters
---... | return corr, (time, P_i_obs) | conditional_block |
correlations.py | '''
Created on 29.11.2013
.. moduleauthor:: marscher, noe
'''
from __future__ import absolute_import
import numpy as np
from .decomposition import rdl_decomposition
from six.moves import range
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None):
"""
calculates time correlation... | start iteration of calculation of matrix power product, with this values.
only useful when calling this function out of a loop over times.
return_P_k_obs : bool
if True, the dot product <P^time, obs2> will be returned for further
calculations.
Returns
-------
cor(k) : fl... | r"""Compute time-correlation of obs1, or time-cross-correlation with obs2.
The time-correlation at time=k is computed by the matrix-vector expression:
cor(k) = obs1' diag(pi) P^k obs2
Parameters
----------
P : ndarray, shape=(n, n) or scipy.sparse matrix
Transition matrix
obs1 : ndarr... | identifier_body |
correlations.py |
'''
Created on 29.11.2013
.. moduleauthor:: marscher, noe
'''
from __future__ import absolute_import
import numpy as np
from .decomposition import rdl_decomposition
from six.moves import range
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None):
"""
calculates time correlatio... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. | random_line_split | |
package.ts | import { resolve, join } from "path";
const { version } = require('../package.json');
const root = resolve(__dirname, '..');
export type PkgEnv = {
name: string;
version: string;
root: string;
buildCtx: {
src: string;
config: string;
output: { [key: string]: any };
entr... | src: join(root, 'src'),
output: { parent: join(root, 'build'), app: join(root, 'build', 'ux') },
config: 'tsconfig.app.json',
target: 'es2015',
entryPoints: {
main: './main.ts',
polyfill: './polyfill.ts'
},
styles: [],
assets: [{
... | version,
buildCtx: { | random_line_split |
el.js | "No shared links" : "Κανένας διαμοιρασμένος σύνδεσμος",
"Files and folders you share by link will show up here" : "Τα αρχεία και οι φάκελοι που διαμοιράζεστε μέσω συνδέσμου θα εμφανιστούνε εδώ",
"Do you want to add the remote share {name} from {owner}@{remote}?" : "Θέλετε να προσθέσουμε τον απομακρυσμένο κο... | random_line_split | ||
cities.service.ts | import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/catch';
import {environment} from '../../environments/environment';
import {City} from '../classes/city';... | (countryId): Observable<City[]> {
return this.http.get(this.countriesUrl + countryId + '/cities/')
.map(res => res.json().data.items as City[]).catch(this.handleError);
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${erro... | getCitiesByCountry | identifier_name |
cities.service.ts | import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/catch';
import {environment} from '../../environments/environment';
import {City} from '../classes/city';... |
citiesUrl = environment.apiUrl + 'cities/';
countriesUrl = environment.apiUrl + 'countries/';
constructor(private http: Http) {
}
getAllCities(): Observable<City[]> {
return this.http.get(this.citiesUrl)
.map(res => res.json().data.items as City[]).catch(this.handleError);
}
getCitiesByCount... |
@Injectable()
export class CitiesService { | random_line_split |
cities.service.ts | import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/catch';
import {environment} from '../../environments/environment';
import {City} from '../classes/city';... |
getCitiesByCountry(countryId): Observable<City[]> {
return this.http.get(this.countriesUrl + countryId + '/cities/')
.map(res => res.json().data.items as City[]).catch(this.handleError);
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${... | {
return this.http.get(this.citiesUrl)
.map(res => res.json().data.items as City[]).catch(this.handleError);
} | identifier_body |
unparser.py | #
# Contain unparsing procedures.
#
import sys
#-------------------------------------------
def unparseToC(vars, annot_body_code, indent, extra_indent):
'''Unparse to C/C++ code'''
if len(vars) == 0:
return annot_body_code
s = '\n'
s += indent + '#pragma disjoint ('
for i, v in enumerat... |
return s
| s += '('
s += ','.join(map(str, dimensions))
s += ')' | conditional_block |
unparser.py | #
# Contain unparsing procedures.
#
import sys
#-------------------------------------------
def | (vars, annot_body_code, indent, extra_indent):
'''Unparse to C/C++ code'''
if len(vars) == 0:
return annot_body_code
s = '\n'
s += indent + '#pragma disjoint ('
for i, v in enumerate(vars):
if i > 0:
s += ', '
s += '*' + __printAddressC(v.var_name, v.dimensions)... | unparseToC | identifier_name |
unparser.py | #
# Contain unparsing procedures.
#
import sys
#-------------------------------------------
def unparseToC(vars, annot_body_code, indent, extra_indent):
'''Unparse to C/C++ code'''
if len(vars) == 0:
return annot_body_code
s = '\n'
s += indent + '#pragma disjoint ('
for i, v in enumerat... | '''Return the starting address location of the given variable (in Fortran)'''
dimensions = dimensions[:]
dimensions.remove(None)
s = str(var_name)
if len(dimensions) > 0:
s += '('
s += ','.join(map(str, dimensions))
s += ')'
return s | identifier_body | |
unparser.py |
import sys
#-------------------------------------------
def unparseToC(vars, annot_body_code, indent, extra_indent):
'''Unparse to C/C++ code'''
if len(vars) == 0:
return annot_body_code
s = '\n'
s += indent + '#pragma disjoint ('
for i, v in enumerate(vars):
if i > 0:
... | #
# Contain unparsing procedures.
# | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.