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 |
|---|---|---|---|---|
test_ivim.py | 0., 160., 180., 200., 300.,
400., 500., 600., 700., 800., 900.,
1000.])
bvecs_with_multiple_b0 = generate_bvecs(N)
gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0,
bvecs_with_m... |
def test_mask():
"""
Test whether setting incorrect mask raises and error
"""
mask_correct = data_multi[..., 0] > 0.2
mask_not_correct = np.array([[False, True, False], [True, False]],
dtype=np.bool)
ivim_fit = ivim_model_trr.fit(data_multi, mask_correct)
... | """
Test if errors raised in the module are working correctly.
Scipy introduced bounded least squares fitting in the version 0.17
and is not supported by the older versions. Initializing an IvimModel
with bounds for older Scipy versions should raise an error.
"""
ivim_model_trr = IvimModel(gtab... | identifier_body |
test_ivim.py | 0., 160., 180., 200., 300.,
400., 500., 600., 700., 800., 900.,
1000.])
bvecs_with_multiple_b0 = generate_bvecs(N)
gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0,
bvecs_with_m... | ():
"""
Test the implementation of the fitting for a single voxel.
Here, we will use the multi_tensor function to generate a
bi-exponential signal. The multi_tensor generates a multi
tensor signal and expects eigenvalues of each tensor in mevals.
Our basic test requires a scalar signal isotropi... | test_single_voxel_fit | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describi... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
}
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(... | fmt | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describi... |
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(response) {
Ok(json) => {
match json.find_path(&["error", "message"]) {
Some(message_json) => match message_json.as_string() {
Some(message) => {
if m... | {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
} | identifier_body |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describi... | }
/// Constructs a new `FleetError` from a `hyper::client::Response`. Not intended for public
/// use.
pub fn from_hyper_response(response: &mut Response) -> FleetError {
FleetError {
code: Some(response.status.to_u16()),
message: extract_message(response),
}
... | code: None,
message: Some(error.description().to_string()),
} | random_line_split |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
... | (self):
return self.items[:] # copy of items
| get_seq | identifier_name |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
|
import types
class seq_with_cursor (object):
__slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals | random_line_split |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
... |
def set_index (self, initial_index):
if initial_index is None:
self.index = len (self.items) / 2
elif initial_index >= 0 and initial_index < len (self.items):
self.index = initial_index
else:
raise ValueError
def set_index_by_value(self, v):
... | assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value is not None:
self.set_index_by_value(initial_value) | identifier_body |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
... |
elif initial_index >= 0 and initial_index < len (self.items):
self.index = initial_index
else:
raise ValueError
def set_index_by_value(self, v):
"""
Set index to the smallest value such that items[index] >= v.
If there is no such item, set index to t... | self.index = len (self.items) / 2 | conditional_block |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equ... | """ the (E)MST solution to a list of two points (i.e. [a, b]) is a list
containing a tuple of points (i.e. [(a, b)]) """
one, two = Point(3, 1), Point(1, 3)
actual = solve([one, two])
compare_solutions(actual, [(one, two)])
def test_triangle():
""" Given a list of points L:
L = [Point... | assert solve([Point(0, 0)]) == [], __doc__
def test_list_of_two(): | random_line_split |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equ... | ():
""" Given a list of points L:
L = [Point(0, 0), Point(3, 0), Point(0, 6)]
The solution is:
[(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]
"""
graph = [Point(0, 0), Point(3, 0), Point(6, 0)]
actual = solve(graph)
compare_solutions(actual, [(Point(0, 0), Point(3,... | test_triangle | identifier_name |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equ... |
def test_list_of_one():
""" the (E)MST solution to a list of one is an empty list """
assert solve([Point(0, 0)]) == [], __doc__
def test_list_of_two():
""" the (E)MST solution to a list of two points (i.e. [a, b]) is a list
containing a tuple of points (i.e. [(a, b)]) """
one, two = Point(3, 1),... | """ this function should reject non-lists (invalid inputs) by raising
a TypeError """
with pytest.raises(TypeError):
solve(True) | identifier_body |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equ... | assert right == Point(0, 0) or right == Point(6, 0), \
"expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0)) | conditional_block | |
calc.py | # Copyright 2017 Battelle Energy Alliance, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform) | random_line_split | |
calc.py | # Copyright 2017 Battelle Energy Alliance, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform) | conditional_block | |
calc.py | # Copyright 2017 Battelle Energy Alliance, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | (self, Input):
number_of_steps = 16
self.time = numpy.zeros(number_of_steps)
uniform = Input["uniform"]
self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform)
| run | identifier_name |
calc.py | # Copyright 2017 Battelle Energy Alliance, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | number_of_steps = 16
self.time = numpy.zeros(number_of_steps)
uniform = Input["uniform"]
self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform) | identifier_body | |
Modal.d.ts | import * as React from 'react';
import { Sizes, TransitionCallbacks } from 'react-bootstrap';
import * as ModalBody from './ModalBody';
import * as ModalHeader from './ModalHeader';
import * as ModalTitle from './ModalTitle';
import * as ModalDialog from './ModalDialog';
import * as ModalFooter from './ModalFooter';
d... | }
export = Modal; | static Footer: typeof ModalFooter;
static Dialog: typeof ModalDialog; | random_line_split |
Modal.d.ts | import * as React from 'react';
import { Sizes, TransitionCallbacks } from 'react-bootstrap';
import * as ModalBody from './ModalBody';
import * as ModalHeader from './ModalHeader';
import * as ModalTitle from './ModalTitle';
import * as ModalDialog from './ModalDialog';
import * as ModalFooter from './ModalFooter';
d... | extends React.Component<Modal.ModalProps> {
static Body: typeof ModalBody;
static Header: typeof ModalHeader;
static Title: typeof ModalTitle;
static Footer: typeof ModalFooter;
static Dialog: typeof ModalDialog;
}
export = Modal;
| Modal | identifier_name |
main.js | var knwl = new Knwl();
var demo = {};
demo.resultBoxes = {};
demo.input = null;
demo.resultsDiv = null;
demo.setup = function() {
var resultsDiv = document.getElementById('results');
demo.resultsDiv = resultsDiv;
for (var el in demo.resultBoxes) {
if (demo.resultsDiv.contains(demo.resultBoxes[el])) {
demo.resu... | if (key !== 'preview') {
p.innerHTML = key + ': <span class = "val">' + data[ii][key] + '</span>';
} else {
p.innerHTML = data[ii][key];
p.setAttribute('class', 'preview');
}
resultDiv.appendChild(p);
}
}
demo.resultBoxes[parser].appendChild(resultDiv);
}
if (data.len... | var p = document.createElement('p'); | random_line_split |
main.js | var knwl = new Knwl();
var demo = {};
demo.resultBoxes = {};
demo.input = null;
demo.resultsDiv = null;
demo.setup = function() {
var resultsDiv = document.getElementById('results');
demo.resultsDiv = resultsDiv;
for (var el in demo.resultBoxes) {
if (demo.resultsDiv.contains(demo.resultBoxes[el])) {
demo.resu... |
resultDiv.appendChild(p);
}
}
demo.resultBoxes[parser].appendChild(resultDiv);
}
if (data.length === 0) {
demo.resultsDiv.removeChild(demo.resultBoxes[parser]);
}
}
};
window.onload = function() {
demo.setup();
if (localStorage.getItem('knwlDemoText') !== '')
demo.input.value = local... | {
p.innerHTML = data[ii][key];
p.setAttribute('class', 'preview');
} | conditional_block |
workbench.ts | vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class W... |
readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel(), getPixelRatio()));
}
private store | {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(storedFontInfo)) {
restoreFontInfo(storedFontInfo);
}
} catch (err) {
/* ignore */
}
} | conditional_block |
workbench.ts | 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class... | // Services
const instantiationService = this.initServices(this.serviceCollection);
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
const storageService = accessor.get(IStorageService);
const configurationService = accessor.get(IConfigura... |
// Configure emitter leak warning threshold
setGlobalLeakWarningThreshold(175);
| random_line_split |
workbench.ts | 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class... | }
private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void {
const storedFontInfoRaw = storageService.get('editorFontInfo', StorageScope.GLOBAL);
if (storedFontInfoRaw) {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(s... | {
if (!isMacintosh) {
return; // macOS only
}
const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing');
if (this.fontAliasing === aliasing) {
return;
}
this.fontAliasing = aliasing;
// Remove all
const fontAliasingValues: (typeof alia... | identifier_body |
workbench.ts | /workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class Wor... | storeFontInfo | identifier_name | |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... | os.makedirs(dirname)
fp = open(settings_filepath, 'w')
import base64
output = open(template_filename).read()
output = output % {
'default_key': base64.b64encode(os.urandom(KEY_LENGTH)),
}
fp.write(output)
fp.close()
def parse_args(args):
"""Parses the given argum... | """
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname): | random_line_split |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... |
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the u... | """Parses the given arguments.
:param args: List of command-line arguments as got from sys.argv.
:return: 3-element tuple: (args, command, command_args)
"""
index = None
for i, arg in enumerate(args):
if not arg.startswith('-'):
index = i
break
if index is None:... | identifier_body |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... | (args):
"""Parses the given arguments.
:param args: List of command-line arguments as got from sys.argv.
:return: 3-element tuple: (args, command, command_args)
"""
index = None
for i, arg in enumerate(args):
if not arg.startswith('-'):
index = i
break
if in... | parse_args | identifier_name |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... |
fp = open(settings_filepath, 'w')
import base64
output = open(template_filename).read()
output = output % {
'default_key': base64.b64encode(os.urandom(KEY_LENGTH)),
}
fp.write(output)
fp.close()
def parse_args(args):
"""Parses the given arguments.
:param args: List... | os.makedirs(dirname) | conditional_block |
MenuList.js | ("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var ... |
}, [autoFocus]);
React.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, theme) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.... | {
listRef.current.focus();
} | conditional_block |
MenuList.js | ("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var ... |
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(ne... | {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
} | identifier_body |
MenuList.js | ("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var ... | (obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasProper... | _interopRequireWildcard | identifier_name |
MenuList.js | ("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var ... |
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItem... | } | random_line_split |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
... | (args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile)
def gmap(args):
"""
%prog gmap... | index | identifier_name |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
... |
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmap... | sys.exit(not p.print_help()) | conditional_block |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
... | try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.snp:
EY... | cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip" | random_line_split |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
... |
def check_index(dbfile):
dbfile = get_abs_path(dbfile)
dbdir, filename = op.split(dbfile)
if not dbdir:
dbdir = "."
dbname = filename.rsplit(".", 1)[0]
safile = op.join(dbdir, "{0}/{0}.genomecomp".format(dbname))
if dbname == filename:
dbname = filename + ".db"
if need_upd... | actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', 'wraps gmap'),
)
p = ActionDispatcher(actions)
p.dispatch(globals()) | identifier_body |
middleware.rs | use std::default::Default;
use std::sync::Arc;
use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;
use nickel::{Request, Response, Middleware, Continue, MiddlewareResult};
use typemap::Key;
use plugin::{Pluggable, Extensible};
pub struct MysqlMiddleware {
pub pool: Arc<MyPool>,
}... | }
impl Key for MysqlMiddleware { type Value = Arc<MyPool>; }
impl Middleware for MysqlMiddleware {
fn invoke<'res>(&self, request: &mut Request, response: Response<'res>) -> MiddlewareResult<'res> {
request.extensions_mut().insert::<MysqlMiddleware>(self.pool.clone());
Ok(Continue(response))
}... | random_line_split | |
middleware.rs | use std::default::Default;
use std::sync::Arc;
use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;
use nickel::{Request, Response, Middleware, Continue, MiddlewareResult};
use typemap::Key;
use plugin::{Pluggable, Extensible};
pub struct MysqlMiddleware {
pub pool: Arc<MyPool>,
}... | <'res>(&self, request: &mut Request, response: Response<'res>) -> MiddlewareResult<'res> {
request.extensions_mut().insert::<MysqlMiddleware>(self.pool.clone());
Ok(Continue(response))
}
}
pub trait MysqlRequestExtensions {
fn db_connection(&self) -> Arc<MyPool>;
}
impl<'a, 'b, 'c> Mys... | invoke | identifier_name |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relai... |
pub fn set(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>, num: u64) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.set(num)?,
false => relais.clear(num)?,
}
Ok(())
}
| {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
} | identifier_body |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relai... | (button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.test_random()?,
false => relais.reset()?,
}
Ok(())}
pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<S... | random | identifier_name |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relai... | let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
}
pub f... | pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> { | random_line_split |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn normalise(a: &Array) -> Array |
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims = Dim4::new(&[nx, ny, 1, 1]);
// Pressure field
let mut p = constant::... | {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
} | identifier_body |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn | (a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims =... | normalise | identifier_name |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn normalise(a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Dist... |
// Draw the image.
win.set_colormap(af::ColorMap::BLUE);
win.draw_image(&normalise(&p), None);
it += 1;
}
}
| {
// Location of the source.
let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)];
// Set the pressure there.
p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]));
} | conditional_block |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info(); |
fn normalise(a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
... |
acoustic_wave_simulation();
} | random_line_split |
evictions.component.ts | */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex... |
}
/** Removes currently selected index on closing the panel */
onClose() {
this.scrollToIndex(this.selectedIndex, true);
this.setCurrentLocation(null);
}
/**
* Checks if location is in view, scrolls to it if so
* @param rank Rank of location
*/
onPanelLocationClick(rank: number) {
th... | {
this.setCurrentLocation(this.selectedIndex - 1);
} | conditional_block |
evictions.component.ts | ) {
this.trackLocationSelection(location, 'search');
const searchEvent = {
locationSearchTerm: term, ...this.getSelectedData(location), locationFindingMethod: 'search'
};
this.analytics.trackEvent('searchSelection', searchEvent);
}
private setupPageScroll() {
this.scroll.defaultScrollOffs... | random_line_split | ||
evictions.component.ts | ('d', dataProp.value);
}
/** Update current location, shows toast if data unavailable */
setCurrentLocation(locationIndex: number) {
if (this.selectedIndex === locationIndex) { return; }
if (this.isLocationInvalid(locationIndex)) {
this.showUnavailableToast();
return;
}
const value = ... | getRegionTweet | identifier_name | |
evictions.component.ts | */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex... |
/** Update the route when the area type changes */
onAreaTypeChange(areaType: { name: string, value: number }) {
if (this.areaType && areaType.value === this.areaType.value) { return; }
this.updateQueryParam('a', areaType.value);
}
/** Update the sort property when the area type changes */
onDataPr... | {
if (newRegion === this.region) { return; }
this.updateQueryParam('r', newRegion);
} | identifier_body |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSou... | expr = sy.exp(-xs)*sy.sin(xs)
def taylor(fx, xs, order, x_range=(0, 1), n=200):
x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
ty = np.zeros_like(x)
ty.fill(float(tx))
... | random_line_split | |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSou... |
else:
ty = sy.lambdify(xs, tx, modules=['numpy'])(x)
return x, fy, ty
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", ... | ty = np.zeros_like(x)
ty.fill(float(tx)) | conditional_block |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSou... |
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source)
p.background_fill_color =... | x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
ty = np.zeros_like(x)
ty.fill(float(tx))
else:
ty = sy.lambdify(xs, tx, modules=['numpy'])(x)
return x, fy, t... | identifier_body |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSou... | ():
try:
expr = sy.sympify(text.value, dict(x=xs))
except Exception as exception:
errbox.text = str(exception)
else:
errbox.text = ""
x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)
p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.va... | update | identifier_name |
test-shift.js |
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
//var e = connection.exchange('node-ack-fanout', {type: 'fanout'});
var e = connection.exchange();
var q = connection.queue('node-123ack-queue');
q.bind(e... | require('./harness'); | random_line_split | |
test-shift.js | require('./harness');
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
//var e = connection.exchange('node-ack-fanout', {type: 'fanout'});
var e = connection.exchange();
var q = connection.queue('node-123ac... | else {
throw new Error('Too many message!');
}
})
.addCallback(function () {
puts("publishing 2 json messages");
e.publish('ackmessage.json1', { name: 'A' });
e.publish('ackmessage.json2', { name: 'B' });
});
});
process.addListener('exit', function () {
assert.equal(2, recvCount);
});... | {
puts('got message 2');
assert.equal('B', json.name);
puts('closing connection');
connection.end();
} | conditional_block |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.co... |
def add_entry(self, fg, commit_info):
fe = fg.add_entry()
fe.title(commit_info['message'])
fe.link(href=commit_info['html_url'])
id_prefix = 'tag:github.com,2008:Grit::Commit/'
entry_id = id_prefix + commit_info['sha']
fe.id(entry_id)
fe.author(commit_info['... | fg = FeedGenerator()
title = 'Recent commits to ' + repo_info['full_name']
fg.title(title)
fg.link(href=repo_info['html_url'])
fg.updated(repo_info['updated_at'])
fg.id(repo_info['html_url'])
fg.author(repo_info['author'])
return fg | identifier_body |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.co... | (self):
s = requests.Session()
s.auth = (self.user, self.passwd)
r = s.get(self.auth_url)
if r.status_code != 200:
print("authentication failed. status_code: " + r.status_code)
return requests.Session()
else:
print("authentication succeed")
... | get_session | identifier_name |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.co... |
rss.gen_atom(fg_repo, '/tmp/test/atom_test.xml')
| rss.add_entry(fg_repo, commit_info) | conditional_block |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.co... | def get_commit_diff(self, s, commit_url):
diff_headers = {'Accept': 'application/vnd.github.diff'}
commit_diff = s.get(commit_url, headers=diff_headers)
if commit_diff.status_code == 200:
commit_diff_txt = commit_diff.text
return commit_diff_txt
else:
... | random_line_split | |
treeitems.py | ._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not conta... | (self, row):
""" Gets the child given its row number
"""
return self.childItems[row]
def childByNodeName(self, nodeName):
""" Gets first (direct) child that has the nodeName.
"""
assert '/' not in nodeName, "nodeName can not contain slashes"
for child in sel... | child | identifier_name |
treeitems.py | Model._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not ... |
@property
def backgroundBrush(self):
""" Returns a brush for drawing the background role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def foregroundBrush(self):
""" Returns a brush for drawing the... | """ Returns a font for displaying this item's text in the tree.
The default implementation returns None (i.e. uses default font).
"""
return None | identifier_body |
treeitems.py | Model._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not ... | """
if position is None:
position = self.nChildren()
assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem)
assert childItem._model is None, "childItem already has a model: {}".format(childItem)
childItem.parentItem = self
... | random_line_split | |
treeitems.py | ._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not conta... |
return _auxGetByPath(nodePath.split('/'), self)
def childNumber(self):
""" Gets the index (nr) of this node in its parent's list of children.
"""
# This is O(n) in time. # TODO: store row number in the items?
if self.parentItem is not None:
return self.parentI... | raise IndexError("Item not found: {!r}".format(nodePath)) | conditional_block |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... |
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method)
| return True | conditional_block |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | (self, become_method):
''' Checks if the current class supports this privilege escalation method '''
if become_method in self.__class__.become_methods:
return True
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method)
| _become_method_supported | identifier_name |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible.errors import AnsibleError
# FIXME: this object should be created upfront and passed through
# the entire chain of calls to here, as there are o... | # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
| random_line_split |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | '''
A base class for connections to contain common code.
'''
has_pipelining = False
become_methods = C.BECOME_METHODS
def __init__(self, connection_info, *args, **kwargs):
self._connection_info = connection_info
self._display = Display(verbosity=connection_info.verbosity)
def... | identifier_body | |
htmltablecaptionelement.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::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindin... |
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document),
document,
... | {
HTMLTableCaptionElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
htmltablecaptionelement.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::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindin... | (local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document),
document,
HTMLTableCaptionElement... | new | identifier_name |
htmltablecaptionelement.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::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindin... | document,
HTMLTableCaptionElementBinding::Wrap)
}
} | pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document), | random_line_split |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function | ($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
... | dimRandomCtrl | identifier_name |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) |
$q.when(dimStoreService.getStores())
.then((stores) => {
const store = _.reduce(stores, (memo, store) => {
if (!memo) {
return store;
}
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store)... | {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return;
}
if (!$window.confirm($translate.instant('Load... | identifier_body |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout =... | } | random_line_split | |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout =... |
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store) {
const classTypeId = ({
titan: 0,
hunter: 1,
warlock: 2
})[store.class];
var checkClassType = function(classType) {
... | {
return store;
} | conditional_block |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/r... |
bgpIntfs = {
'bgpq1-eth0': bgpEth0
}
bgpq1 = self.addHost("bgpq1", cls=Router,
quaggaConfFile='{}/quagga1.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addL... | '10.0.1.1/24',
]
} | random_line_split |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/r... |
class SdnIpTopo(Topo):
def build(self):
zebraConf = '{}/zebra.conf'.format(ZCONFIG_DIR)
s1 = self.addSwitch('s1', dpid='0000000000000001', cls=OVSSwitch, failMode="standalone")
# Quagga 1
bgpEth0 = {
'mac': '00:00:00:00:00:01',
'ipAddrs': [
... | self.cmd("ps ax | egrep 'bgpd%s.pid|zebra%s.pid' | awk '{print $1}' | xargs kill" % (self.name, self.name))
Host.terminate(self) | identifier_body |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/r... | (self, name, ip, route, *args, **kwargs):
Host.__init__(self, name, ip=ip, *args, **kwargs)
self.route = route
def config(self, **kwargs):
Host.config(self, **kwargs)
debug("configuring route %s" % self.route)
self.cmd('ip route add default via %s' % self.route)
class R... | __init__ | identifier_name |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/r... |
# setup address to interfaces
for addr in attrs['ipAddrs']:
self.cmd('ip addr add %s dev %s' % (addr, intf))
self.cmd('zebra -d -f %s -z %s/zebra%s.api -i %s/zebra%s.pid' % (self.zebraConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
self.cmd('bg... | self.cmd('ip link set %s down' % intf)
self.cmd('ip link set %s address %s' % (intf, attrs['mac']))
self.cmd('ip link set %s up ' % intf) | conditional_block |
mapAccumRight.js | import _curry3 from './internal/_curry3.js';
/**
* The `mapAccumRight` function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from right to left, and returning a final value of this
* accumulator together with the new list.
*
... | * ]
*/
var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
var idx = list.length - 1;
var result = [];
var tuple = [acc];
while (idx >= 0) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx -= 1;
}
return [tuple[0], result];
});
export default mapAccumRight; | * f(f(f(a, d)[0], c)[0], b)[1]
* ] | random_line_split |
mapAccumRight.js | import _curry3 from './internal/_curry3.js';
/**
* The `mapAccumRight` function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from right to left, and returning a final value of this
* accumulator together with the new list.
*
... |
return [tuple[0], result];
});
export default mapAccumRight;
| {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx -= 1;
} | conditional_block |
__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislatu... | doc = lxml.html.fromstring(data)
return doc.xpath('//html')[0].text_content() | identifier_body | |
__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislatu... | # Their dump filename changed, probably just a hiccup.
'_scraped_name': '2013',
# '_scraped_name': '2013 Session',
},
'2014': {'display_name': '2014 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2014%20Sess... | 'zip_url': 'http://gencourt.state.nh.us/downloads/2012%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2012 Session',
},
'2013': {'display_name': '2013 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2013%20Session... | random_line_split |
__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislatu... | (doc, data):
doc = lxml.html.fromstring(data)
return doc.xpath('//html')[0].text_content()
| extract_text | identifier_name |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
retur... | ():
lock_operation('acquire')
def release_lock():
lock_operation('release')
def scp_agent_exe():
agents_windows_dir = os.path.dirname(localdir)
agent_exe = os.path.join(agents_windows_dir, 'check_mk_agent-64.exe')
cmd = ['scp', agent_exe, '%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
asse... | acquire_lock | identifier_name |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
retur... |
def rm_rf_testfiles():
cmd = [
'ssh',
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && del /S /F /Q * '
'&& for /d %G in ("*") do rmdir "%~G" /Q')
]
exit_code, stdout, stderr = run_subprocess(cmd)
if stdout:
sys.stdout.write(stdout)
if stderr... | test_files = [
os.path.abspath(t)
for t in glob.glob(os.path.join(localdir, 'test_*')) +
[os.path.join(localdir, 'remote.py')]
]
cmd = ['scp'
] + test_files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd) | identifier_body |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
retur... |
def acquire_lock():
lock_operation('acquire')
def release_lock():
lock_operation('release')
def scp_agent_exe():
agents_windows_dir = os.path.dirname(localdir)
agent_exe = os.path.join(agents_windows_dir, 'check_mk_agent-64.exe')
cmd = ['scp', agent_exe, '%s@%s:%s' % (remoteuser, remote_ip, r... | assert_subprocess(cmd) | conditional_block |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
retur... | scp_agent_exe()
scp_tests()
yield
finally:
release_lock()
rm_rf_testfiles() | random_line_split | |
domquery.ts | "use strict";
import * as typeId from './typeidentifiers';
export type NodeIteratorCallback = (node: Node) => void;
export type ElementIteratorCallback = (element: Element) => void;
/**
* Derive the plain javascript element from a passed element
* @param {string|Node} element - the element to detect
* @returns {... | if (context !== undefined) {
if (matches(context, element)) {
return context;
}
else {
return context.querySelector(element);
}
}
else {
return document.querySelector(element);
}
}
if (ele... | */
export function first(element: Node | string, context?: HTMLElement): Node {
if (typeof element === 'string') { | random_line_split |
domquery.ts | "use strict";
import * as typeId from './typeidentifiers';
export type NodeIteratorCallback = (node: Node) => void;
export type ElementIteratorCallback = (element: Element) => void;
/**
* Derive the plain javascript element from a passed element
* @param {string|Node} element - the element to detect
* @returns {... | lement: Node | string, context?: HTMLElement): Node {
if (typeof element === 'string') {
if (context !== undefined) {
if (matches(context, element)) {
return context;
}
else {
return context.querySelector(element);
}
}
... | rst(e | identifier_name |
domquery.ts | "use strict";
import * as typeId from './typeidentifiers';
export type NodeIteratorCallback = (node: Node) => void;
export type ElementIteratorCallback = (element: Element) => void;
/**
* Derive the plain javascript element from a passed element
* @param {string|Node} element - the element to detect
* @returns {... | for (var i = 0; i < nodes.length; ++i) {
cb(nodes[i]);
}
} | identifier_body | |
cursor.js | GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert"); |
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
sys.puts("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-exampl... |
var Db = require('../lib/mongodb').Db,
Connection = require('../lib/mongodb').Connection,
Server = require('../lib/mongodb').Server; | random_line_split |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionCo... |
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
title="Sluit"
type="button"
size={30}
onClick={onClo... | {
login()
} | identifier_body |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionCo... | () {
login()
}
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
title="Sluit"
type="button"
size={30}
... | handleLogin | identifier_name |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionCo... |
export default DataSelectionDownloadModal | )}
</ModalBody>
</Modal>
)
} | random_line_split |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionCo... |
return Promise.reject()
}, [url, retryCount])
function handleLogin() {
login()
}
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
... | {
return requestDownloadLink(url)
} | conditional_block |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import ... |
downstreamProjects.push(downstreamJob);
}
return downstreamProjects;
}
private getJobApiUrl(jobUrl: string, config: ConfigService) {
if (jobUrl === undefined || jobUrl === null || jobUrl.length === 0) {
return undefined;
}
/** Remove t... | {
continue;
} | conditional_block |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import ... | (jobJson: JSON, job: IJenkinsJob) {
let downstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("downstreamProjects")) {
this.LOGGER.debug("No downstream projects found for:", job);
return downstreamProjects;
}
for (let dow... | getDownstreamProjects | identifier_name |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import ... |
private getDownstreamProjects(jobJson: JSON, job: IJenkinsJob) {
let downstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("downstreamProjects")) {
this.LOGGER.debug("No downstream projects found for:", job);
return downstreamProjec... | {
let upstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("upstreamProjects")) {
this.LOGGER.debug("No upstream projects found for:", job);
return upstreamProjects;
}
for (let upstreamJobJson of (jobJson["upstreamProjects... | identifier_body |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import ... |
job.fromJson(jobJson);
job.upstreamProjects = this.getUpstreamProjects(jobJson, job);
job.downstreamProjects = this.getDownstreamProjects(jobJson, job);
this.LOGGER.debug("Updated details for job:", job.name);
}
... | if (job === undefined) {
this.LOGGER.warn("No job with name", jobJson["name"], "found");
this.allItemsRetrievedSuccessfully = false;
continue;
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.