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 |
|---|---|---|---|---|
diagnostic_led.py | import machine
import time
DIAGNOSTIC_LED = None
try:
with open('config/diagnostic_led.pin', 'r') as fp:
invert = False
value = int(fp.read())
if value < 0:
value = -value
invert = True
DIAGNOSTIC_LED = machine.Signal(value, machine.Pin.OUT, invert=invert)
... |
time.sleep_ms(half_period)
if DIAGNOSTIC_LED is not None:
DIAGNOSTIC_LED.off()
time.sleep_ms(half_period)
| DIAGNOSTIC_LED.on() | conditional_block |
diagnostic_led.py | import machine
import time
DIAGNOSTIC_LED = None
try:
with open('config/diagnostic_led.pin', 'r') as fp:
invert = False
value = int(fp.read())
if value < 0:
value = -value
invert = True
DIAGNOSTIC_LED = machine.Signal(value, machine.Pin.OUT, invert=invert)
... | half_period = cycle_period_ms // 2
if DIAGNOSTIC_LED is not None:
DIAGNOSTIC_LED.on()
time.sleep_ms(half_period)
if DIAGNOSTIC_LED is not None:
DIAGNOSTIC_LED.off()
time.sleep_ms(half_period) | identifier_body | |
diagnostic_led.py | import machine
import time
DIAGNOSTIC_LED = None
try:
with open('config/diagnostic_led.pin', 'r') as fp:
invert = False
value = int(fp.read())
if value < 0:
value = -value
invert = True
DIAGNOSTIC_LED = machine.Signal(value, machine.Pin.OUT, invert=invert)
... | blink_once(cycle_period_ms)
def blink_n(cycle_period_ms, count):
i = 0
while i < count:
blink_once(cycle_period_ms)
i += 1
def blink_once(cycle_period_ms):
half_period = cycle_period_ms // 2
if DIAGNOSTIC_LED is not None:
DIAGNOSTIC_LED.on()
time.sleep_ms(half_pe... |
def blink_forever(cycle_period_ms):
while True: | random_line_split |
diagnostic_led.py | import machine
import time
DIAGNOSTIC_LED = None
try:
with open('config/diagnostic_led.pin', 'r') as fp:
invert = False
value = int(fp.read())
if value < 0:
value = -value
invert = True
DIAGNOSTIC_LED = machine.Signal(value, machine.Pin.OUT, invert=invert)
... | (cycle_period_ms, count):
i = 0
while i < count:
blink_once(cycle_period_ms)
i += 1
def blink_once(cycle_period_ms):
half_period = cycle_period_ms // 2
if DIAGNOSTIC_LED is not None:
DIAGNOSTIC_LED.on()
time.sleep_ms(half_period)
if DIAGNOSTIC_LED is not None:
... | blink_n | identifier_name |
kcp_server.rs | extern crate futures;
extern crate tokio_core;
extern crate tokio_kcp;
extern crate tokio_io;
extern crate env_logger;
use std::env;
use std::net::SocketAddr;
use futures::future::Future;
use futures::stream::Stream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use tokio_io::io::copy;
use tokio_kcp::KcpLis... | });
core.run(echo).unwrap();
} | Ok(()) | random_line_split |
kcp_server.rs | extern crate futures;
extern crate tokio_core;
extern crate tokio_kcp;
extern crate tokio_io;
extern crate env_logger;
use std::env;
use std::net::SocketAddr;
use futures::future::Future;
use futures::stream::Stream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use tokio_io::io::copy;
use tokio_kcp::KcpLis... | () {
// let socket = UdpSocket::bind("127.0.0.1:1234").expect("couldn't bind to address");
//
// let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap();
//
// for _ in 0..20 {
// socket.send_to("123123".as_bytes(), addr).expect("sendto failed");
// }
//
// let mut vec = vec![];
//
// printl... | main | identifier_name |
kcp_server.rs | extern crate futures;
extern crate tokio_core;
extern crate tokio_kcp;
extern crate tokio_io;
extern crate env_logger;
use std::env;
use std::net::SocketAddr;
use futures::future::Future;
use futures::stream::Stream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use tokio_io::io::copy;
use tokio_kcp::KcpLis... | let addr = env::args()
.nth(1)
.unwrap_or_else(|| "192.168.12.82:1234".to_string());
let addr = addr.parse::<SocketAddr>().unwrap();
let mut core = Core::new().unwrap();
let handle = core.handle();
let listener = KcpListener::bind(&addr, &handle).unwrap();
println!("listening on... | {
// let socket = UdpSocket::bind("127.0.0.1:1234").expect("couldn't bind to address");
//
// let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap();
//
// for _ in 0..20 {
// socket.send_to("123123".as_bytes(), addr).expect("sendto failed");
// }
//
// let mut vec = vec![];
//
// println!(... | identifier_body |
browsershot.py | #!/usr/bin/python
# browsershots.org - Test your web design in different browsers
# Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org>
#
# Browsershots 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 Foundatio... | metavar="<seconds>", default=5,
help="wait before taking screenshots (default 5)")
(options, args) = parser.parse_args()
config = {'width': 1024, 'bpp': 32}
system = platform.system()
if system == 'Linux':
from shotfactory04.gui import linux
g... | parser.add_option("-w", dest="wait", action="store", type="int", | random_line_split |
browsershot.py | #!/usr/bin/python
# browsershots.org - Test your web design in different browsers
# Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org>
#
# Browsershots 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 Foundatio... | ():
from optparse import OptionParser
version = '%prog ' + __revision__.strip('$').replace('Rev: ', 'r')
parser = OptionParser(version=version)
parser.add_option("-d", dest="display", action="store", type="string",
metavar="<name>", default=":0",
help="run on ... | _main | identifier_name |
browsershot.py | #!/usr/bin/python
# browsershots.org - Test your web design in different browsers
# Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org>
#
# Browsershots 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 Foundatio... | % options.wait
time.sleep(options.wait)
gui.browsershot()
if __name__ == '__main__':
_main()
| from optparse import OptionParser
version = '%prog ' + __revision__.strip('$').replace('Rev: ', 'r')
parser = OptionParser(version=version)
parser.add_option("-d", dest="display", action="store", type="string",
metavar="<name>", default=":0",
help="run on a differ... | identifier_body |
browsershot.py | #!/usr/bin/python
# browsershots.org - Test your web design in different browsers
# Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org>
#
# Browsershots 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 Foundatio... |
print "Waiting %d seconds, please activate your browser window..." \
% options.wait
time.sleep(options.wait)
gui.browsershot()
if __name__ == '__main__':
_main()
| raise NotImplemented(system) | conditional_block |
core.js | qr_threadid")) return r.t.value;
return null;
}
/**
* @param {object} $ - jQuery object
* @param {object} _ - underscore object
* @param {object} bootbox - bootbox object
* @param {object} console - console object
* @param {undefined} undefined - safe reference to undefined
*/
(function ($, _, SHURSCRIPT, boot... | $log.append(message + "<br>");
},
/**
* Compone el string para este modulo + usuario + key
*
* @param {string} key - nombre de la llave
* @param {boolean} [withId] - bool para incluir o no el ID del usuario en la llave. Default: false
*/
_getShurKey: function (key, withId) {
var id = (withId ==... | $(document.body).append('<div id="shurscript_log" style="display:none;"></div>');
$log = $('#shurscript_log');
}
| conditional_block |
core.js |
/**
* @param {object} $ - jQuery object
* @param {object} _ - underscore object
* @param {object} bootbox - bootbox object
* @param {object} console - console object
* @param {undefined} undefined - safe reference to undefined
*/
(function ($, _, SHURSCRIPT, bootbox, console, undefined) {
'use strict';
var c... | {
var r;
if (r = unsafeWindow.threadid) return r;
if (r = decodeURIComponent((new RegExp('[?|&]t=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1])) return r;// from URL parameter
if (r = document.getElementById("qr_threadid")) return r.t.value;
return null;
} | identifier_body | |
core.js | qr_threadid")) return r.t.value;
return null;
}
/**
* @param {object} $ - jQuery object
* @param {object} _ - underscore object
* @param {object} bootbox - bootbox object
* @param {object} console - console object
* @param {undefined} undefined - safe reference to undefined
*/
(function ($, _, SHURSCRIPT, boot... | * @param defaultValue
*/
getValue: function (key, defaultValue) {
return GM.getValue(this._getShurKey(key, false), defaultValue);
},
/**
* Elimina un valor del servidor
*
* @param key
* @param {function} callback - funcion a ejecutar despues de la operacion
*/
deleteValue: function (key... | },
/**
* Devuelve un valor del servidor, o el defaultValue si no encuentra la clave
* @param key | random_line_split |
core.js | () {
var r;
if (r = unsafeWindow.threadid) return r;
if (r = decodeURIComponent((new RegExp('[?|&]t=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1])) return r;// from URL parameter
if (r = document.getElementById("qr_threadid")) return r.t.value;
return null;
}
/**
* @param {object} $ - jQuery ob... | getCurrentThread | identifier_name | |
tree-differ.ts | /// <reference path="../typings/node/node.d.ts" />
import fs = require('fs');
import path = require('path');
function tryStatSync(path) {
try {
return fs.statSync(path);
} catch (e) {
if (e.code === "ENOENT") return null;
throw e;
}
}
export class TreeDiffer {
private fingerprints: {[key: strin... | {
public filesChecked: number = 0;
public directoriesChecked: number = 0;
public changedPaths: string[] = [];
public removedPaths: string[] = [];
public startTime: number = Date.now();
public endTime: number = null;
constructor(public name: string) {}
toString() {
return `${pad(this.name, 40)}, d... | DirtyCheckingDiffResult | identifier_name |
tree-differ.ts | /// <reference path="../typings/node/node.d.ts" />
import fs = require('fs');
import path = require('path');
function tryStatSync(path) {
try {
return fs.statSync(path);
} catch (e) {
if (e.code === "ENOENT") return null;
throw e;
}
}
export class TreeDiffer {
private fingerprints: {[key: strin... |
}
function pad(value, length) {
value = '' + value;
let whitespaceLength = (value.length < length) ? length - value.length : 0;
whitespaceLength = whitespaceLength + 1;
return new Array(whitespaceLength).join(' ') + value;
}
| {
let prefixedPaths =
this.changedPaths.map((p) => `* ${p}`).concat(this.removedPaths.map((p) => `- ${p}`));
console.log(`Tree diff: ${this}` + ((verbose && prefixedPaths.length) ?
` [\n ${prefixedPaths.join('\n ')}\n]` :
... | identifier_body |
tree-differ.ts | /// <reference path="../typings/node/node.d.ts" />
import fs = require('fs'); | return fs.statSync(path);
} catch (e) {
if (e.code === "ENOENT") return null;
throw e;
}
}
export class TreeDiffer {
private fingerprints: {[key: string]: string} = Object.create(null);
private nextFingerprints: {[key: string]: string} = Object.create(null);
private rootDirName: string;
privat... | import path = require('path');
function tryStatSync(path) {
try { | random_line_split |
create.ts | import color from '@heroku-cli/color'
import {Command, flags} from '@heroku-cli/command'
import {StageCompletion} from '@heroku-cli/command/lib/completions'
import cli from 'cli-ux'
import {prompt} from 'inquirer'
import {createCoupling, createPipeline, getAccountInfo, getTeam} from '../../api'
import infer from '../.... | team: flags.team({
description: 'the team which will own the apps',
}),
}
static args = [{
name: 'name',
description: 'name of pipeline (defaults to basename of the app)',
required: false,
}]
async run() {
const {args, flags} = this.parse(Create)
let name
let stage
l... | description: 'stage of first app in pipeline',
completion: StageCompletion,
}), | random_line_split |
create.ts | import color from '@heroku-cli/color'
import {Command, flags} from '@heroku-cli/command'
import {StageCompletion} from '@heroku-cli/command/lib/completions'
import cli from 'cli-ux'
import {prompt} from 'inquirer'
import {createCoupling, createPipeline, getAccountInfo, getTeam} from '../../api'
import infer from '../.... | else {
questions.push({
type: 'list',
name: 'stage',
message: `Stage of ${app}`,
choices: stages,
default: guesses[1],
})
}
const teamName = flags.team
const ownerType = teamName ? 'team' : 'user'
// If team or org is not specified, we assign owners... | {
stage = flags.stage
} | conditional_block |
create.ts | import color from '@heroku-cli/color'
import {Command, flags} from '@heroku-cli/command'
import {StageCompletion} from '@heroku-cli/command/lib/completions'
import cli from 'cli-ux'
import {prompt} from 'inquirer'
import {createCoupling, createPipeline, getAccountInfo, getTeam} from '../../api'
import infer from '../.... | extends Command {
static description = `create a new pipeline
An existing app must be specified as the first app in the pipeline.
The pipeline name will be inferred from the app name if not specified.
The stage of the app will be guessed based on its name if not specified.
The pipeline owner will be the user... | Create | identifier_name |
index.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
accordionDetailsClasses: true
}; | return _AccordionDetails.default;
}
});
Object.defineProperty(exports, "accordionDetailsClasses", {
enumerable: true,
get: function () {
return _accordionDetailsClasses.default;
}
});
var _AccordionDetails = _interopRequireDefault(require("./AccordionDetails"));
var _accordionDetailsClasses = _interop... | Object.defineProperty(exports, "default", {
enumerable: true,
get: function () { | random_line_split |
clientos.py | """
Based on http://vaig.be/2009/03/getting-client-os-in-django.html
"""
import re
def | (user_agent):
'''
Context processor for Django that provides operating system
information base on HTTP user agent.
A user agent looks like (line break added):
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) \
Gecko/2009020409 Iceweasel/3.0.6 (Debian-3.0.6-1)"
'''
# Mozilla/5.0
... | client_os | identifier_name |
clientos.py | """
Based on http://vaig.be/2009/03/getting-client-os-in-django.html
"""
import re
def client_os(user_agent):
'''
Context processor for Django that provides operating system
information base on HTTP user agent.
A user agent looks like (line break added):
"Mozilla/5.0 (X11; U; Linux i686; en-US; r... |
else:
full_platform = None
platform = None
return {
'full_platform': full_platform,
'platform': platform,
}
| full_platform = "Windows"
platform = 'Windows' | conditional_block |
clientos.py | """
Based on http://vaig.be/2009/03/getting-client-os-in-django.html
"""
import re
def client_os(user_agent):
| regex += '; .*'
result = re.match(regex, user_agent)
if result:
result_dict = result.groupdict()
full_platform = result_dict['platform_token']
platform_values = full_platform.split(' ')
if platform_values[0] in ('Windows', 'Linux', 'Mac'):
platform = platform_val... | '''
Context processor for Django that provides operating system
information base on HTTP user agent.
A user agent looks like (line break added):
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) \
Gecko/2009020409 Iceweasel/3.0.6 (Debian-3.0.6-1)"
'''
# Mozilla/5.0
regex = '(?P<appli... | identifier_body |
clientos.py | """
Based on http://vaig.be/2009/03/getting-client-os-in-django.html
"""
import re
def client_os(user_agent):
'''
Context processor for Django that provides operating system
information base on HTTP user agent.
A user agent looks like (line break added):
"Mozilla/5.0 (X11; U; Linux i686; en-US; r... | full_platform = None
platform = None
return {
'full_platform': full_platform,
'platform': platform,
} | random_line_split | |
knn.py | from ..dataset.arff import ArffFile
from scipy.spatial import kdtree, distance
from ..representations.intervalsProbability import IntervalsProbability
import numpy as np
from math import exp
class IPKNN(object):
"""IPKNN implements a K-nearest neighbour method using lower previsions.
If data are all preci... | (self,testdataset,knn_beta=1.5,knn_epsilon=0.99,knn_nb_neigh=3):
"""evaluate the instances and return a list of probability intervals
:param testdataset: list of input features of instances to evaluate
:type dataset: list
:param knn_beta: value of beta parameter used in evaluati... | evaluate | identifier_name |
knn.py | from ..dataset.arff import ArffFile
from scipy.spatial import kdtree, distance
from ..representations.intervalsProbability import IntervalsProbability
import numpy as np
from math import exp
class IPKNN(object):
"""IPKNN implements a K-nearest neighbour method using lower previsions.
If data are all preci... | .. note::
* Assumes that the class attribute is the last one in samples in the learning method
* If too many data, average distance approximated by sampling
.. todo::
* Make it possible for the class to be in any column (retrieve index)
"""
def __ini... | :param classes: list of class names
| random_line_split |
knn.py | from ..dataset.arff import ArffFile
from scipy.spatial import kdtree, distance
from ..representations.intervalsProbability import IntervalsProbability
import numpy as np
from math import exp
class IPKNN(object):
"""IPKNN implements a K-nearest neighbour method using lower previsions.
If data are all preci... |
for k in range(len(query[0])):
#retrieve class index of kth neighbour
neigh_class=self.classes.index(self.truelabels[query[1][k]])
#compute the linear vacuous model of this neighbour
#the higher discount, the most original info is kept
... | query=list(query)
query[0]=[query[0]]
query[1]=[query[1]] | conditional_block |
knn.py | from ..dataset.arff import ArffFile
from scipy.spatial import kdtree, distance
from ..representations.intervalsProbability import IntervalsProbability
import numpy as np
from math import exp
class IPKNN(object):
"""IPKNN implements a K-nearest neighbour method using lower previsions.
If data are all preci... |
def learn(self,learndataset):
"""learn the KNN structure required to evaluate new instances
:param learndataset: learning instances
:type learndataset: :class:`~classifip.dataset.arff.ArffFile`
"""
self.__init__()
self.classes=learndataset.attribute... | """Build an empty IPKNN structure
"""
self.tree=None
self.truelabels=[]
self.beta=1.5
self.epsilon=0.99
self.classes=[]
self.av_dist=[] | identifier_body |
qthelpers.py | # Here is an example of how to do it:
# (self.listwidget is widget *a* and self is widget *b*)
# self.connect(self.listwidget, SIGNAL('option_changed'),
# lambda *args: self.emit(SIGNAL('option_changed'), *args))
def qapplication(translate=True):
"""Return QApplication instance
Crea... | target, actions, insert_before=None):
"""Add actions to a menu"""
previous_action = None
target_actions = list(target.actions())
if target_actions:
previous_action = target_actions[-1]
if previous_action.isSeparator():
previous_action = None
for action in actions:... | dd_actions( | identifier_name |
qthelpers.py | # Here is an example of how to do it:
# (self.listwidget is widget *a* and self is widget *b*)
# self.connect(self.listwidget, SIGNAL('option_changed'),
# lambda *args: self.emit(SIGNAL('option_changed'), *args))
def qapplication(translate=True):
"""Return QApplication instance
Crea... |
button.setAutoRaise(autoraise)
if triggered is not None:
QObject.connect(button, SIGNAL('clicked()'), triggered)
if toggled is not None:
QObject.connect(button, SIGNAL("toggled(bool)"), toggled)
button.setCheckable(True)
if shortcut is not None:
button.setShortcut... | utton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
| conditional_block |
qthelpers.py | # Here is an example of how to do it:
# (self.listwidget is widget *a* and self is widget *b*)
# self.connect(self.listwidget, SIGNAL('option_changed'),
# lambda *args: self.emit(SIGNAL('option_changed'), *args))
def qapplication(translate=True):
"""Return QApplication instance
Crea... | if text is not None:
button.setText(text)
if icon is not None:
if isinstance(icon, (str, unicode)):
icon = get_icon(icon)
button.setIcon(icon)
if text is not None or tip is not None:
button.setToolTip(text if tip is None else tip)
if text_beside_icon:
... | button = QToolButton(parent)
| random_line_split |
qthelpers.py | # Here is an example of how to do it:
# (self.listwidget is widget *a* and self is widget *b*)
# self.connect(self.listwidget, SIGNAL('option_changed'),
# lambda *args: self.emit(SIGNAL('option_changed'), *args))
def qapplication(translate=True):
"""Return QApplication instance
Crea... |
def mimedata2url(source, extlist=None):
"""
Extract url list from MIME data
extlist: for example ('.py', '.pyw')
"""
pathlist = []
if source.hasUrls():
for url in source.urls():
path = _process_mime_path(unicode(url.toString()), extlist)
if path is n... | f path.startswith(r"file://"):
if os.name == 'nt':
# On Windows platforms, a local path reads: file:///c:/...
# and a UNC based path reads like: file://server/share
if path.startswith(r"file:///"): # this is a local path
path=path[8:]
else: #... | identifier_body |
test_peakdf.py | import numpy as np
import numpy.testing as npt
from dipy.reconst.peaks import default_sphere, peaks_from_model
def test_PeaksAndMetricsDirectionGetter():
class SillyModel(object):
def fit(self, data, mask=None):
return SillyFit(self)
class SillyFit(object):
def __init__(self, m... |
def get_direction(dg, point, dir):
newdir = dir.copy()
state = dg.get_direction(point, newdir)
return (state, np.array(newdir))
data = np.random.random((3, 4, 5, 2))
peaks = peaks_from_model(SillyModel(), data, default_sphere,
relative_peak_threshold=.... | odf = np.zeros(sphere.theta.shape)
r = np.random.randint(0, len(odf))
odf[r] = 1
return odf | identifier_body |
test_peakdf.py | import numpy as np
import numpy.testing as npt
from dipy.reconst.peaks import default_sphere, peaks_from_model
def test_PeaksAndMetricsDirectionGetter():
class SillyModel(object):
def fit(self, data, mask=None):
return SillyFit(self)
class SillyFit(object):
def __init__(self, m... | state, nd = get_direction(peaks, point, up)
npt.assert_equal(state, 0)
# Check that points are rounded to get initial direction
point -= .5
id = peaks.initial_direction(point)
# id should be a (1, 3) array
n... | for k in range(5-1):
point = np.array([i, j, k], dtype=float)
# Test that the angle threshold rejects points
peaks.ang_thr = 0.
state, nd = get_direction(peaks, point, up)
npt.assert_equal(state, 1)
# Here we leverage the ... | conditional_block |
test_peakdf.py | import numpy as np
import numpy.testing as npt
from dipy.reconst.peaks import default_sphere, peaks_from_model
def test_PeaksAndMetricsDirectionGetter():
class SillyModel(object):
def fit(self, data, mask=None):
return SillyFit(self)
class SillyFit(object):
def | (self, model):
self.model = model
def odf(self, sphere):
odf = np.zeros(sphere.theta.shape)
r = np.random.randint(0, len(odf))
odf[r] = 1
return odf
def get_direction(dg, point, dir):
newdir = dir.copy()
state = dg.get_direction(p... | __init__ | identifier_name |
test_peakdf.py | import numpy as np
import numpy.testing as npt
from dipy.reconst.peaks import default_sphere, peaks_from_model
def test_PeaksAndMetricsDirectionGetter():
class SillyModel(object):
def fit(self, data, mask=None):
return SillyFit(self)
class SillyFit(object):
def __init__(self, m... | odf = np.zeros(sphere.theta.shape)
r = np.random.randint(0, len(odf))
odf[r] = 1
return odf
def get_direction(dg, point, dir):
newdir = dir.copy()
state = dg.get_direction(point, newdir)
return (state, np.array(newdir))
data = np.random.r... | random_line_split | |
area_square_miles_to_metric.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from decimal ... | (square_miles, precision=1):
"""
Converts from square miles to square m or to hectares
:param acres: Square miles value in string
:return: square m or to hectares value in string, and the symbol
"""
sqm_to_ha_rate = Decimal(258.999)
symbol = HECTARE_SYMBOL
square_miles_list = square_mile... | convert | identifier_name |
area_square_miles_to_metric.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from decimal ... |
name = 'square_mile_to_metric'
label = 'Area square miles to metric'
callback = square_mile_to_metric
access_type = 'frontend'
action_type = 'interactive'
group = 'area' | return unit_base.do_conversion(item, convert, unit_base.format_output, regex, match_index=0, value_index=1) | random_line_split |
area_square_miles_to_metric.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from decimal ... |
else:
square_meter_list = [unit_base.format_converted(s, precision=precision) for s in square_meter_list]
return '-'.join(square_meter_list), symbol
def square_mile_to_metric(item, **kwargs):
"""Converts from square miles to metric"""
regex = r'(\d+-?,?\.?\d*)((\s*)|(-))((sq\.?\s*-?mi)|([sS... | square_meter_list = [unit_base.format_converted((s / Decimal(100)), precision=1) for s in square_meter_list]
symbol = SQUARE_KILOMETER_SYMBOL | conditional_block |
area_square_miles_to_metric.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from decimal ... |
name = 'square_mile_to_metric'
label = 'Area square miles to metric'
callback = square_mile_to_metric
access_type = 'frontend'
action_type = 'interactive'
group = 'area'
| """Converts from square miles to metric"""
regex = r'(\d+-?,?\.?\d*)((\s*)|(-))((sq\.?\s*-?mi)|([sS]quare\s*-?[mM]iles?)|([sS]quare\s*-?mi))\b'
return unit_base.do_conversion(item, convert, unit_base.format_output, regex, match_index=0, value_index=1) | identifier_body |
osx_say.py | import os
import re
import subprocess
from utils import whereis_exe
class osx_voice():
def __init__(self, voice_line):
mess = voice_line.split(' ')
cleaned = [ part for part in mess if len(part)>0 ]
self.name = cleaned[0]
self.locality = cleaned[1]
self.desc = cleaned[2].... | subprocess.call(["say", text, "-v", voice, "-r", rate]) | conditional_block | |
osx_say.py | import os
import re
import subprocess
from utils import whereis_exe
class osx_voice():
def __init__(self, voice_line):
mess = voice_line.split(' ')
cleaned = [ part for part in mess if len(part)>0 ]
self.name = cleaned[0]
self.locality = cleaned[1]
self.desc = cleaned[2].... | (self):
return self.name + ' ' + self.locality + ' ' + self.desc
def fetch_voices():
osx_voices = []
if whereis_exe("say"):
voices_raw = os.popen("say -v ?").read()
voice_lines = voices_raw.split('\n')
for line in voice_lines:
try:
osx_voices.append(... | __str__ | identifier_name |
osx_say.py | import os
import re
import subprocess
from utils import whereis_exe
class osx_voice():
|
def fetch_voices():
osx_voices = []
if whereis_exe("say"):
voices_raw = os.popen("say -v ?").read()
voice_lines = voices_raw.split('\n')
for line in voice_lines:
try:
osx_voices.append(osx_voice(line))
except IndexError:
pass
... | def __init__(self, voice_line):
mess = voice_line.split(' ')
cleaned = [ part for part in mess if len(part)>0 ]
self.name = cleaned[0]
self.locality = cleaned[1]
self.desc = cleaned[2].replace('# ', '')
def __str__(self):
return self.name + ' ' + self.locality + ' '... | identifier_body |
osx_say.py | import os
import re
import subprocess
from utils import whereis_exe
class osx_voice():
def __init__(self, voice_line):
mess = voice_line.split(' ')
cleaned = [ part for part in mess if len(part)>0 ]
self.name = cleaned[0]
self.locality = cleaned[1]
self.desc = cleaned[2].... | def fetch_voices():
osx_voices = []
if whereis_exe("say"):
voices_raw = os.popen("say -v ?").read()
voice_lines = voices_raw.split('\n')
for line in voice_lines:
try:
osx_voices.append(osx_voice(line))
except IndexError:
pass
re... | random_line_split | |
testNavigateFTP.js | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
Cu.import("resource://gre/modules/Services.jsm");
const TEST_DATA = "ftp://ftp.mozqa.com/";
var setupModule = function(aModule) {
aModule.controller = mozmill.getBrowserController();
}
var testNavigateFTP = function () {
// opens the ... | /* 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 | random_line_split | |
client.js | "use strict";
var React = require("react");
var MainView = require("../views/MainView");
var MainElement = document.getElementById("main");
var socket = require("socket.io-client")();
var Store = require("../views/Store");
var omit = require("lodash/object/omit");
socket.on("initialize", function (data) {
Store.lea... |
var franchises = data.league.franchises.franchise;
total = franchises.length;
i = 0;
for (; i < total; ++i) {
Store.franchises[franchises[i].id] = omit(franchises[i], ["_id", "id"]);
}
var handleClick = function handleClick(event, callback) {
console.log("deeper click");
var typeStr = event.tar... | {
Store.players[players[i].id] = omit(players[i], ["_id", "id"]);
} | conditional_block |
client.js | "use strict";
var React = require("react");
var MainView = require("../views/MainView"); | var omit = require("lodash/object/omit");
socket.on("initialize", function (data) {
Store.league = data.league;
Store.adp = data.adp;
var i = 0,
players = data.players,
total = players.length;
for (; i < total; ++i) {
Store.players[players[i].id] = omit(players[i], ["_id", "id"]);
}
var fra... | var MainElement = document.getElementById("main");
var socket = require("socket.io-client")();
var Store = require("../views/Store"); | random_line_split |
twice.js | var test = require('tap').test;
var sliceFile = require('../');
var through = require('through2');
var fs = require('fs');
var wordFile = __dirname + '/data/words';
test('slice twice on the same instance', function (t) {
t.plan(2);
var xs = sliceFile(wordFile);
var first = [];
var second = [];
... | xs.slice(-10, -5).pipe(through(
function (line, _, next) {
second.push(line.toString('utf8'));
next();
},
function () {
t.deepEqual(second, [
"élan's\n",
... | random_line_split | |
pull.py | import csv
import numpy
import pandas
import pymongo
import requests
from datetime import datetime
from io import StringIO
mongo_client = pymongo.MongoClient("localhost", 27017)
financial_db = mongo_client.financial_data
financial_collection = financial_db.data
| def __call__(self, source, tickers, start_date, end_date):
if source=='Google':
results = self.google_call(tickers, start_date, end_date)
return results
elif source=='Database':
results = self.database_call(tickers, start_date, end_date)
return results... | class Pull:
| random_line_split |
pull.py | import csv
import numpy
import pandas
import pymongo
import requests
from datetime import datetime
from io import StringIO
mongo_client = pymongo.MongoClient("localhost", 27017)
financial_db = mongo_client.financial_data
financial_collection = financial_db.data
class Pull:
def __call__(self, source, tickers, ... |
elif source=='Database':
results = self.database_call(tickers, start_date, end_date)
return results
def google_call(self, tickers, start_date, end_date):
"""
google_call makes a call to the google finance api for historical data
Args:
None (uses ... | results = self.google_call(tickers, start_date, end_date)
return results | conditional_block |
pull.py | import csv
import numpy
import pandas
import pymongo
import requests
from datetime import datetime
from io import StringIO
mongo_client = pymongo.MongoClient("localhost", 27017)
financial_db = mongo_client.financial_data
financial_collection = financial_db.data
class Pull:
def __call__(self, source, tickers, ... |
def google_call(self, tickers, start_date, end_date):
"""
google_call makes a call to the google finance api for historical data
Args:
None (uses the class variables)
Returns:
None (sets self.results)
"""
results = {}
for ticker in ti... | if source=='Google':
results = self.google_call(tickers, start_date, end_date)
return results
elif source=='Database':
results = self.database_call(tickers, start_date, end_date)
return results | identifier_body |
pull.py | import csv
import numpy
import pandas
import pymongo
import requests
from datetime import datetime
from io import StringIO
mongo_client = pymongo.MongoClient("localhost", 27017)
financial_db = mongo_client.financial_data
financial_collection = financial_db.data
class Pull:
def | (self, source, tickers, start_date, end_date):
if source=='Google':
results = self.google_call(tickers, start_date, end_date)
return results
elif source=='Database':
results = self.database_call(tickers, start_date, end_date)
return results
def google... | __call__ | identifier_name |
extensionsFileTemplate.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | export const ExtensionsConfigurationSchema: IJSONSchema = {
id: ExtensionsConfigurationSchemaId,
allowComments: true,
type: 'object',
title: localize('app.extensions.json.title', "Extensions"),
properties: {
recommendations: {
type: 'array',
description: localize('app.extensions.json.recommendations', "Lis... | import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { EXTENSION_IDENTIFIER_PATTERN } from 'vs/platform/extensionManagement/common/extensionManagement';
export const ExtensionsConfigurationSchemaId = 'vscode://schemas/extensions'; | random_line_split |
test_features.py | """Testing code for the tupa.features package, unit-testing only."""
import os
from collections import OrderedDict
import pytest
from ucca import textutil
from tupa.action import Actions
from tupa.features.dense_features import DenseFeatureExtractor
from tupa.features.sparse_features import SparseFeatureExtractor
fro... | self.id = vocab == "-"
self.wordvectors = wordvectors
self.omit = omit
def __str__(self):
return "-".join([self.name] + [attr for attr in ("indexed", "annotated", "vocab", "id", "wordvectors", "omit")
if getattr(self, attr)])
def __call__(... | self.annotated = annotated
self.vocab = vocab | random_line_split |
test_features.py | """Testing code for the tupa.features package, unit-testing only."""
import os
from collections import OrderedDict
import pytest
from ucca import textutil
from tupa.action import Actions
from tupa.features.dense_features import DenseFeatureExtractor
from tupa.features.sparse_features import SparseFeatureExtractor
fro... |
def feature_extractors(*args, **kwargs):
return [FeatureExtractorCreator(SPARSE, *args, **kwargs), FeatureExtractorCreator(DENSE, *args, **kwargs),
FeatureExtractorCreator(DENSE, *args, indexed=True, **kwargs)]
def extract_features(feature_extractor, state, features):
values = feature_extractor... | def __init__(self, name, indexed=False, annotated=False, vocab=None, wordvectors=None, omit=None):
self.name = name
self.indexed = indexed
self.annotated = annotated
self.vocab = vocab
self.id = vocab == "-"
self.wordvectors = wordvectors
self.omit = omit
def... | identifier_body |
test_features.py | """Testing code for the tupa.features package, unit-testing only."""
import os
from collections import OrderedDict
import pytest
from ucca import textutil
from tupa.action import Actions
from tupa.features.dense_features import DenseFeatureExtractor
from tupa.features.sparse_features import SparseFeatureExtractor
fro... |
features = [feature_extractor.init_features(state)]
while True:
extract_features(feature_extractor, state, features)
action = min(oracle.get_actions(state, actions).values(), key=str)
state.transition(action)
if state.need_label:
extract_features(feature_extractor, s... | param.dropout = 0
feature_extractor.init_param(key) | conditional_block |
test_features.py | """Testing code for the tupa.features package, unit-testing only."""
import os
from collections import OrderedDict
import pytest
from ucca import textutil
from tupa.action import Actions
from tupa.features.dense_features import DenseFeatureExtractor
from tupa.features.sparse_features import SparseFeatureExtractor
fro... | (config, feature_extractor_creator, filename, write_features):
_test_features(config, feature_extractor_creator, filename, write_features)
@pytest.mark.parametrize("feature_extractor_creator",
[f for v in ("-", VOCAB) for w in (None, WORD_VECTORS) for o in (None, OMITTED)
... | test_features | identifier_name |
toggleButtonClasses.d.ts | export interface ToggleButtonClasses {
/** Styles applied to the root element. */
root: string;
/** State class applied to the root element if `disabled={true}`. */
disabled: string;
/** State class applied to the root element if `selected={true}`. */
selected: string;
/** State class... | sizeMedium: string;
/** Styles applied to the root element if `size="large"`. */
sizeLarge: string;
}
export declare type ToggleButtonClassKey = keyof ToggleButtonClasses;
export declare function getToggleButtonUtilityClass(slot: string): string;
declare const toggleButtonClasses: ToggleButtonClasses;... | /** State class applied to the root element if `color="secondary"`. */
secondary: string;
/** Styles applied to the root element if `size="small"`. */
sizeSmall: string;
/** Styles applied to the root element if `size="medium"`. */
| random_line_split |
search.tsx | import { Link } from "gatsby";
import React, { useEffect, useState } from "react";
const Search = () => {
const [query, setQuery] = useState("");
const [results, setResults] = useState<LunrResult[]>([]);
useEffect(() => {
if (!query || !window.__LUNR__) {
setResults([]);
return;
}
const lunrIndex = win... | </form>
);
};
export default Search; | </li>
);
})}
</ul> | random_line_split |
search.tsx | import { Link } from "gatsby";
import React, { useEffect, useState } from "react";
const Search = () => {
const [query, setQuery] = useState("");
const [results, setResults] = useState<LunrResult[]>([]);
useEffect(() => {
if (!query || !window.__LUNR__) |
const lunrIndex = window.__LUNR__["en"];
const searchResults = lunrIndex.index.search(query);
setResults(searchResults.map(({ ref }) => lunrIndex.store[ref]));
}, [query]);
return (
<form
onSubmit={(e) => e.preventDefault()}
role="search"
area-label="All Articles"
>
<label htmlFor="search">Sea... | {
setResults([]);
return;
} | conditional_block |
actions.js | /**
* External dependencies
*/
import Dispatcher from 'dispatcher';
const wpcom = require( 'lib/wp' ).undocumented();
/**
* Internal dependencies
*/
import { actionTypes } from './constants';
import { toApi } from './common';
export function cancelImport( importerId ) {
Dispatcher.handleViewAction( {
type: act... |
failUpload( importerId, error.message );
},
onprogress: event => {
setUploadProgress( importerId, {
uploadLoaded: event.loaded,
uploadTotal: event.total
} );
},
onabort: () => cancelImport( importerId )
} );
}
| {
return finishUpload( importerId, data );
} | conditional_block |
actions.js | /**
* External dependencies
*/
import Dispatcher from 'dispatcher';
const wpcom = require( 'lib/wp' ).undocumented();
/**
* Internal dependencies
*/
import { actionTypes } from './constants';
import { toApi } from './common';
export function cancelImport( importerId ) {
Dispatcher.handleViewAction( {
type: act... |
export function startImport( importerType ) {
// Dev-only: this will come from an API call
let importerId = `${ Math.round( Math.random() * 10000 ) }`;
Dispatcher.handleViewAction( {
type: actionTypes.START_IMPORT,
importerId,
importerType
} );
}
export function startImporting( importerStatus ) {
const {... | {
Dispatcher.handleViewAction( {
type: actionTypes.SET_UPLOAD_PROGRESS,
uploadLoaded: data.uploadLoaded,
uploadTotal: data.uploadTotal,
importerId
} );
} | identifier_body |
actions.js | /**
* External dependencies
*/
import Dispatcher from 'dispatcher';
const wpcom = require( 'lib/wp' ).undocumented();
/**
* Internal dependencies
*/
import { actionTypes } from './constants';
import { toApi } from './common';
export function cancelImport( importerId ) {
Dispatcher.handleViewAction( {
type: act... | Dispatcher.handleViewAction( {
type: actionTypes.FAIL_UPLOAD,
importerId,
error
} );
}
export function finishUpload( importerId, importerStatus ) {
Dispatcher.handleViewAction( {
type: actionTypes.FINISH_UPLOAD,
importerId, importerStatus
} );
}
export function mapAuthor( importerId, sourceAuthor, targe... | }
export function failUpload( importerId, error ) { | random_line_split |
actions.js | /**
* External dependencies
*/
import Dispatcher from 'dispatcher';
const wpcom = require( 'lib/wp' ).undocumented();
/**
* Internal dependencies
*/
import { actionTypes } from './constants';
import { toApi } from './common';
export function cancelImport( importerId ) {
Dispatcher.handleViewAction( {
type: act... | ( importerId, sourceAuthor, targetAuthor ) {
Dispatcher.handleViewAction( {
type: actionTypes.MAP_AUTHORS,
importerId,
sourceAuthor,
targetAuthor
} );
}
export function resetImport( importerId ) {
Dispatcher.handleViewAction( {
type: actionTypes.RESET_IMPORT,
importerId
} );
}
// Use when developing t... | mapAuthor | identifier_name |
theme.init.js | $(function (){
$('#formorm_description, textarea[name=description]').sceditorBBCodePlugin({
toolbar: "bold,italic,underline,strike|left,center,right,justify|" +
"bulletlist,orderedlist|link,unlink|source",
resizeEnabled: "true"});
$('.tips').popover();
$("select").chosen... | if(!$('input').hasClass('form-control') &&
$('input').attr('type') != 'checkbox') {$('input').addClass('form-control');}
});
});
_debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
... | $('#from_email').parent().parent().css('display','none');
});
$('input').each(function(){ | random_line_split |
theme.init.js | $(function (){
$('#formorm_description, textarea[name=description]').sceditorBBCodePlugin({
toolbar: "bold,italic,underline,strike|left,center,right,justify|" +
"bulletlist,orderedlist|link,unlink|source",
resizeEnabled: "true"});
$('.tips').popover();
$("select").chosen... |
else{
$('#cf_values_input').attr('type','hidden');
$('#cf_values_input').parent().parent().css('display','none'); // parent of a parent. dont show whole block
}
}).change();
// custom field edit, show/hide values field
$('#cf_values_input').parent().parent()... | {
$('#cf_values_input').attr('type','text');
$('#cf_values_input').parent().parent().css('display','block'); // parent of a parent. display whole block
} | conditional_block |
theme.init.js | $(function (){
$('#formorm_description, textarea[name=description]').sceditorBBCodePlugin({
toolbar: "bold,italic,underline,strike|left,center,right,justify|" +
"bulletlist,orderedlist|link,unlink|source",
resizeEnabled: "true"});
$('.tips').popover();
$("select").chosen... | (c_name,value,exdays)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays==null) ? "" : ";path=/; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// $(window).load(function(){
// $('input,select,textarea').addClass('form-control');... | setCookie | identifier_name |
theme.init.js | $(function (){
$('#formorm_description, textarea[name=description]').sceditorBBCodePlugin({
toolbar: "bold,italic,underline,strike|left,center,right,justify|" +
"bulletlist,orderedlist|link,unlink|source",
resizeEnabled: "true"});
$('.tips').popover();
$("select").chosen... |
// $(window).load(function(){
// $('input,select,textarea').addClass('form-control');
// $('label').next().addClass('col-sm-4');
// $('textarea').parent().removeClass('col-sm-4').addClass('col-sm-6');
// $('.control-label').addClass('col-sm-3');
// $('.form-group').removeClass('form-group').addCla... | {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays==null) ? "" : ";path=/; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
} | identifier_body |
long_tests_client.rs | use grpc::ClientStubExt;
use long_tests::long_tests_pb::*;
use long_tests::long_tests_pb_grpc::*;
use futures::executor;
use std::env;
fn single_num_arg_or(cmd_args: &[String], or: u64) -> u64 {
if cmd_args.len() == 0 {
or
} else if cmd_args.len() == 1 {
cmd_args[0].parse().expect("failed to p... | else {
panic!("unknown command: {}", cmd);
}
}
| {
run_echo(client, cmd_args);
} | conditional_block |
long_tests_client.rs | use grpc::ClientStubExt;
use long_tests::long_tests_pb::*;
use long_tests::long_tests_pb_grpc::*;
use futures::executor;
use std::env;
fn single_num_arg_or(cmd_args: &[String], or: u64) -> u64 |
fn run_echo(client: LongTestsClient, cmd_args: &[String]) {
let count = single_num_arg_or(cmd_args, 1);
println!("running {} iterations of echo", count);
for i in 0..count {
let payload = format!("payload {}", i);
let mut req = EchoRequest::new();
req.set_payload(payload.clone()... | {
if cmd_args.len() == 0 {
or
} else if cmd_args.len() == 1 {
cmd_args[0].parse().expect("failed to parse as u64")
} else {
panic!("too many args");
}
} | identifier_body |
long_tests_client.rs | use grpc::ClientStubExt;
use long_tests::long_tests_pb::*;
use long_tests::long_tests_pb_grpc::*;
use futures::executor;
use std::env;
fn single_num_arg_or(cmd_args: &[String], or: u64) -> u64 {
if cmd_args.len() == 0 {
or
} else if cmd_args.len() == 1 {
cmd_args[0].parse().expect("failed to p... | }
fn main() {
env_logger::init();
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
panic!("too few args")
}
let client = LongTestsClient::new_plain("localhost", 23432, Default::default()).expect("init");
let cmd = &args[1];
let cmd_args = &args[2..];
if cmd ... |
assert!(payload == r.get_payload());
}
println!("done"); | random_line_split |
long_tests_client.rs | use grpc::ClientStubExt;
use long_tests::long_tests_pb::*;
use long_tests::long_tests_pb_grpc::*;
use futures::executor;
use std::env;
fn | (cmd_args: &[String], or: u64) -> u64 {
if cmd_args.len() == 0 {
or
} else if cmd_args.len() == 1 {
cmd_args[0].parse().expect("failed to parse as u64")
} else {
panic!("too many args");
}
}
fn run_echo(client: LongTestsClient, cmd_args: &[String]) {
let count = single_num_a... | single_num_arg_or | identifier_name |
knowledgebase.service.ts |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class KnowledgebaseService
{
public category_id: number;
... | (kb_id: number, value: any): Observable<Object>
{
return this.http.put(environment.API_ENDPOINT + `/api/kb/update/${kb_id}`, value, { headers: this.authHeader })
}
deleteknowledgebaseItem(kb_id: number): Observable<Object>
{
return this.http.delete(environment.API_ENDPOINT + `/api/kb/de... | updateKnowledgebaseItem | identifier_name |
knowledgebase.service.ts |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class KnowledgebaseService
{
public category_id: number;
... |
deleteknowledgebaseItem(kb_id: number): Observable<Object>
{
return this.http.delete(environment.API_ENDPOINT + `/api/kb/delete/${kb_id}`, { headers: this.authHeader })
}
}
| {
return this.http.put(environment.API_ENDPOINT + `/api/kb/update/${kb_id}`, value, { headers: this.authHeader })
} | identifier_body |
knowledgebase.service.ts | import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class KnowledgebaseService
{
public category_id: number;
... | }
deleteknowledgebaseItem(kb_id: number): Observable<Object>
{
return this.http.delete(environment.API_ENDPOINT + `/api/kb/delete/${kb_id}`, { headers: this.authHeader })
}
} | random_line_split | |
sampler.py |
__all__ = ["GaussianPrior",
"TophatPrior",
"ParticleProposal",
"KNNParticleProposal",
"OLCMParticleProposal",
"Sampler",
"PoolSpec",
"weighted_cov",
"weighted_avg_and_std"
]
class GaussianPrior(object):
"""
... | (self, theta=None):
if theta is None:
return self._random.multivariate_normal(self.mu, self.sigma)
else:
return stats.multivariate_normal.pdf(theta, self.mu, self.sigma)
class TophatPrior(object):
"""
Tophat prior
:param min: scalar or array of min values
:... | __call__ | identifier_name |
sampler.py | spatial
__all__ = ["GaussianPrior",
"TophatPrior",
"ParticleProposal",
"KNNParticleProposal",
"OLCMParticleProposal",
"Sampler",
"PoolSpec",
"weighted_cov",
"weighted_avg_and_std"
]
class GaussianPrior(object):
... | :param prior: instance of a prior definition (or an other callable) see :py:class:`sampler.GaussianPrior`
:param eps_proposal: an instance of a threshold proposal (or an other callable) see :py:class:`sampler.ConstEps`
:param pool: (optional) a PoolSpec instance,if not None the initial rejectio... | Launches the sampling process. Yields the intermediate results per iteration.
| random_line_split |
sampler.py |
__all__ = ["GaussianPrior",
"TophatPrior",
"ParticleProposal",
"KNNParticleProposal",
"OLCMParticleProposal",
"Sampler",
"PoolSpec",
"weighted_cov",
"weighted_avg_and_std"
]
class GaussianPrior(object):
"""
... |
class TophatPrior(object):
"""
Tophat prior
:param min: scalar or array of min values
:param max: scalar or array of max values
"""
def __init__(self, min, max):
self.min = np.atleast_1d(min)
self.max = np.atleast_1d(max)
self._random = np.random.mtrand.Rando... | return stats.multivariate_normal.pdf(theta, self.mu, self.sigma) | conditional_block |
sampler.py | 2 * weighted_cov(pool.thetas, pool.ws)
def __call__(self, i):
# setting seed to prevent problem with multiprocessing
self._random.seed(i)
cnt = 1
while True:
idx = self._random.choice(range(self.N), 1, p= self.pool.ws/np.sum(self.pool.ws))[0]
theta = self... | """
Return the weighted avg and standard deviation.
:param values: Array with the values
:param weights: Array with the same shape as values containing the weights
:param axis: (optional) the axis to be used for the computation
:returns avg, sigma: weighted average and standard deviation
... | identifier_body | |
main.py | XDG_CONFIG_HOME")
if path is None:
path = os.getenv("HOME")
if path is None:
return config
path = os.path.join(path, ".config")
path = os.path.join(path, _PROG)
config_file = os.path.join(path, "config.py")
# Check if config file exists.
if not os.path.exists(con... | capture_file = None
code_to_inject = None
file_to_inject = None
while len(args):
if args[0] == "--capture":
args.pop(0)
capture_file = args.pop(0)
elif args[0] == "--inject-code":
args.pop(0)
code_to_inject = bytes(args.pop(0).replace("\\n", "... | identifier_body | |
main.py | directory.
with open(config_file) as f:
config_data = f.read()
prev_cwd = os.getcwd()
os.chdir(path)
exec(config_data, config.__dict__)
os.chdir(prev_cwd)
return config
def prepare_command_expansions(config):
global _command_expansions
_command_expansions = {}
for comma... | console_out_write | identifier_name | |
main.py | )
config_file = os.path.join(path, "config.py")
# Check if config file exists.
if not os.path.exists(config_file):
return config
# Exec the config file in its directory.
with open(config_file) as f:
config_data = f.read()
prev_cwd = os.getcwd()
os.chdir(path)
exec(confi... | print("Use Ctrl-J to inject", code_to_inject) | conditional_block | |
main.py | This program provides a set of utilities to interact with and automate a
MicroPython device over a serial connection. Commands supported are:
mpremote -- auto-detect, connect and enter REPL
mpremote <device-shortcut> -- connect to given device
mpremote connect <device> ... | random_line_split | ||
test_autoestimator_keras.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | resources_per_trial={"cpu": 2},
name="test_fit")
data, validation_data = get_train_val_data()
def pyrmsle(y_true, y_pred):
y_pred[y_pred < -1] = -1 + 1e-6
elements = np.power(np.log1p(y_true... | random_line_split | |
test_autoestimator_keras.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | (self):
auto_est = AutoEstimator.from_keras(model_creator=model_creator,
logs_dir="/tmp/zoo_automl_logs",
resources_per_trial={"cpu": 2},
name="test_fit")
data, validation... | test_fit_multiple_times | identifier_name |
test_autoestimator_keras.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | metric="mse")
assert auto_est.get_best_model()
best_config = auto_est.get_best_config()
assert "hidden_size" in best_config
assert all(k in best_config.keys() for k in create_linear_search_space().keys())
def test_fit_multiple_times(self):
auto_est = Aut... | def setUp(self) -> None:
from zoo.orca import init_orca_context
init_orca_context(cores=4, init_ray_on_spark=True)
def tearDown(self) -> None:
from zoo.orca import stop_orca_context
stop_orca_context()
def test_fit(self):
auto_est = AutoEstimator.from_keras(model_creato... | identifier_body |
test_autoestimator_keras.py | #
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | pytest.main([__file__]) | conditional_block | |
error.rs | //! A Status encapsulates the result of an operation.
//!
//! It may indicate success,
//! or it may indicate an error with an associated error message.
//!
//! Multiple threads can invoke const methods on a Status without
//! external synchronization, but if any of the threads may call a
//! non-const method, all thre... | (&self) -> Severity {
unsafe { mem::transmute(ll::rocks_status_severity(self.raw())) }
}
/// string indicating the message of the Status
pub fn state(&self) -> &str {
unsafe {
let ptr = ll::rocks_status_get_state(self.raw());
ptr.as_ref().and_then(|s| CStr::from_ptr(... | severity | identifier_name |
error.rs | //! A Status encapsulates the result of an operation.
//! | //! non-const method, all threads accessing the same Status must use
//! external synchronization.
use std::ffi::CStr;
use std::fmt;
use std::mem;
use std::str;
use rocks_sys as ll;
use crate::to_raw::{FromRaw, ToRaw};
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Code {
_Ok = 0, // wil... | //! It may indicate success,
//! or it may indicate an error with an associated error message.
//!
//! Multiple threads can invoke const methods on a Status without
//! external synchronization, but if any of the threads may call a | random_line_split |
error.rs | //! A Status encapsulates the result of an operation.
//!
//! It may indicate success,
//! or it may indicate an error with an associated error message.
//!
//! Multiple threads can invoke const methods on a Status without
//! external synchronization, but if any of the threads may call a
//! non-const method, all thre... | else {
Err(Error::LowLevel(raw))
}
}
}
impl Drop for Error {
fn drop(&mut self) {
if !self.raw().is_null() {
unsafe { ll::rocks_status_destroy(self.raw()) }
}
}
}
impl Error {
pub fn is_not_found(&self) -> bool {
self.code() == Code::NotFound
... | {
Ok(())
} | conditional_block |
credentials.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | /// build a [`ChannelCredentials`].
pub struct ChannelCredentials {
creds: *mut grpc_channel_credentials,
}
impl ChannelCredentials {
pub fn as_mut_ptr(&mut self) -> *mut grpc_channel_credentials {
self.creds
}
/// Try to build a [`ChannelCredentials`] to authenticate with Google OAuth credent... | /// Use [`ChannelCredentialsBuilder`] or [`ChannelCredentials::google_default_credentials`] to | random_line_split |
credentials.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (mut self) -> ServerCredentials {
let root_cert = self
.root
.take()
.map_or_else(ptr::null_mut, CString::into_raw);
let cert_chains = self.cert_chains.as_mut_ptr();
let private_keys = self.private_keys.as_mut_ptr();
let force_auth = if self.force_clie... | build | identifier_name |
credentials.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | ;
let credentials = unsafe {
grpc_sys::grpcwrap_ssl_server_credentials_create(
root_cert,
cert_chains as _,
private_keys as _,
self.cert_chains.len(),
force_auth,
)
};
if !root_cert.is_null(... | { 0 } | conditional_block |
defaults-unsound-62211-1.rs | //! Regression test for https://github.com/rust-lang/rust/issues/62211
//!
//! The old implementation of defaults did not check whether the provided
//! default actually fulfills all bounds on the assoc. type, leading to
//! unsoundness, demonstrated here as a use-after-free.
//!
//! Note that the underlying cause of t... |
fn main() {
bug(String::from("hello!"));
}
| {
let origin = T::make_origin(origin);
let mut copy = T::unchecked_copy(&origin);
// assert we indeed have 2 strings pointing to the same buffer.
assert_eq!(origin.as_ptr(), copy.as_ptr());
// Drop the origin. Any use of `copy` is UB.
drop(origin);
copy += "This is invalid!";
println!... | identifier_body |
defaults-unsound-62211-1.rs | //! Regression test for https://github.com/rust-lang/rust/issues/62211
//!
//! The old implementation of defaults did not check whether the provided
//! default actually fulfills all bounds on the assoc. type, leading to
//! unsoundness, demonstrated here as a use-after-free.
//!
//! Note that the underlying cause of t... | (other: &Self::Output) -> Self::Output {
(*other)
}
fn make_origin(s: Self) -> Self::Output {
s.into()
}
}
impl<T> UncheckedCopy for T {}
fn bug<T: UncheckedCopy>(origin: T) {
let origin = T::make_origin(origin);
let mut copy = T::unchecked_copy(&origin);
// assert we indeed ... | unchecked_copy | identifier_name |
defaults-unsound-62211-1.rs | //! Regression test for https://github.com/rust-lang/rust/issues/62211
//!
//! The old implementation of defaults did not check whether the provided
//! default actually fulfills all bounds on the assoc. type, leading to
//! unsoundness, demonstrated here as a use-after-free.
//! | //! Note that the underlying cause of this is still not yet fixed.
//! See: https://github.com/rust-lang/rust/issues/33017
#![feature(associated_type_defaults)]
use std::{
fmt::Display,
ops::{AddAssign, Deref},
};
trait UncheckedCopy: Sized {
// This Output is said to be Copy. Yet we default to Self
... | random_line_split | |
colors.py | import jobs
import config
from utils.various import bound
from utils.colors import mix_colors
from notifiers import notifier
from db.models import StatusColor
class ColorNotifier(notifier.Notifier):
def _check(self):
current = self.job.status
if current.error:
self.set_color(config.ERR... | (self, status):
bound_response = bound(
float(status.value),
self.job.min_time,
self.job.max_time
)
self.set_color(mix_colors(
config.RESPONSE_FAST_COLOR,
config.RESPONSE_SLOW_COLOR,
(bound_response - self.job.min_time) / s... | assign_color | identifier_name |
colors.py | import jobs
import config
from utils.various import bound
from utils.colors import mix_colors
from notifiers import notifier
from db.models import StatusColor
class ColorNotifier(notifier.Notifier):
def _check(self):
current = self.job.status
if current.error:
self.set_color(config.ERR... | float(status.value),
self.job.min_time,
self.job.max_time
)
self.set_color(mix_colors(
config.RESPONSE_FAST_COLOR,
config.RESPONSE_SLOW_COLOR,
(bound_response - self.job.min_time) / self.job.max_time
))
class CIColorNotif... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.