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 |
|---|---|---|---|---|
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a no... |
}
#[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description... | {
unsafe { czmq_sys::zsys_interrupted == 1 }
} | identifier_body |
actions.js | /*
* Minio Cloud Storage (C) 2018 Minio, 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... | export const SET = "alert/SET"
export const CLEAR = "alert/CLEAR"
export let alertId = 0
export const set = alert => {
const id = alertId++
return (dispatch, getState) => {
if (alert.type !== "danger" || alert.autoClear) {
setTimeout(() => {
dispatch({
type: CLEAR,
alert: {
... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
| random_line_split |
actions.js | /*
* Minio Cloud Storage (C) 2018 Minio, 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... |
dispatch({
type: SET,
alert: Object.assign({}, alert, {
id
})
})
}
}
export const clear = () => {
return { type: CLEAR }
}
| {
setTimeout(() => {
dispatch({
type: CLEAR,
alert: {
id
}
})
}, 5000)
} | conditional_block |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object t... | if (webpackProperties) {
if (action === "init") {
return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} else if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.O... | utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
| identifier_body |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object t... | ) {
utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
if (webpackProperties) {
if (action === "init") {
return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} else if (action... | eateNodeProperty(p | identifier_name |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object t... | lse if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.ObjectExpression)
.filter(p => utils.pushObjectKeys(j, p, webpackProperties, "node"));
} else {
return nodeTransform(j, ast, webpackProperties, "init");
}... | return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} e | conditional_block |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object t... | if (action === "init") {
return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} else if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.ObjectExpression)
.fi... | function createNodeProperty(p) {
utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
if (webpackProperties) { | random_line_split |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as... | public async cancel(key: string): Promise<void> {
// Validate key
if (!this.taskList.has(key)) {
return
}
// Removed the serialized copy.
await this.redundancyService.remove(key)
// Fetch local copy.
const job: NodeSchedule.Job | undefined = this... | * @param key The key that identifies the task that is to be cancelled.
*/ | random_line_split |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as... | (): number {
return this.taskList.size
}
/**
* Schedule a given task.
*
* @param task The task that is being scheduled.
*/
public async schedule(task: ITask): Promise<ITask> {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < ... | getPendingCount | identifier_name |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as... |
/**
* Schedule a given task.
*
* @param task The task that is being scheduled.
*/
public async schedule(task: ITask): Promise<ITask> {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
throw new Error(Errors.SCH... | {
return this.taskList.size
} | identifier_body |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as... |
return task
}
/**
* Cancel a pending task by key.
*
* @param key The key that identifies the task that is to be cancelled.
*/
public async cancel(key: string): Promise<void> {
// Validate key
if (!this.taskList.has(key)) {
return
}
... | {
// Create job with the key in the jobItem and with the data being
// the data from the JobItem.
await this.redundancyService.commit(task)
} | conditional_block |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implemen... | {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", ha... | identifier_body | |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implemen... | () {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}",... | main | identifier_name |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
|
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn main() {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
... | // This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library. | random_line_split |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
se... |
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_geom, "checkin", point.dateTime, point.... | return "'" + s + "'" | identifier_body |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
se... | if happened_at is None:
happened_at = ''
if message is None:
message = ''
def quote(s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
... | print resp
def _craft_insert(self, the_geom, event_type, happened_at, message): | random_line_split |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
se... | (s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_ge... | quote | identifier_name |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
se... |
if message is None:
message = ''
def quote(s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(poi... | happened_at = '' | conditional_block |
LogPage.js | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2012 the ConQAT Project |
| |
| Licensed u... | else {
subtitle = "All log messages generated during ConQAT run.";
}
var subtitleElement = goog.dom.getElement("caption-subtitle");
goog.dom.setTextContent(subtitleElement, subtitle);
};
| {
var processor = new conqat.config.UnitEditPart(this.processorFilter);
subtitle = "Log messages for processor " + processor.getName();
} | conditional_block |
LogPage.js | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2012 the ConQAT Project |
| |
| Licensed u... | conqat.config.TemplateUtils.clearParametersTable();
if (this.processorFilter) {
var processor = new conqat.config.UnitEditPart(this.processorFilter);
conqat.config.TemplateUtils.renderParametersTable(this.processorFilter);
}
};
/**
* Updates the page subtitle after settings have changed.
*
* @private
*/
co... | * @private
*/
conqat.config.LogPage.prototype.updateParametersTable = function() {
var logTable = conqat.config.LogPage.getLogTable();
| random_line_split |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
... | {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics... | identifier_body |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(... | expand_deriving_from_primitive | identifier_name |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
... | methods: vec!( | random_line_split |
sync.rs | , even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
Blocked... | {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.... | identifier_body | |
sync.rs | : uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_... | match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(), | random_line_split | |
sync.rs | *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current... | {
Vec::new()
} | conditional_block | |
sync.rs | because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads ... | drop_port | identifier_name | |
angular.js | regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/... | each: each, | random_line_split | |
angular.js | , [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
... |
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this funct... | {
callback.call(null, i, obj[i]);
} | conditional_block |
angular.js | , [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
... |
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable... | {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
} | identifier_body |
angular.js | , [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
... | (value) {
return supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]... | isErrorEvent | identifier_name |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):... |
else:
def is_string(x):
return isinstance(x, basestring)
def to_string(x):
if is_string(x):
return x
else:
return str(x)
def print_exc():
if traceback:
traceback.print_exc()
if IS_PY3K:
def quote_smart(s, safe='/'):
return quote(s, safe)
else:
def quot... |
if IS_PY3K:
def is_string(x):
return isinstance(x, str) | random_line_split |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):... | (s, safe='/'):
if isinstance(s, unicode):
s = s.encode('utf-8')
return quote(s, safe)
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
... | quote_smart | identifier_name |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):... |
filters_cache.append(new_filters)
return filters_cache[-1]
def is_ignored_by_filter(filename, filename_to_ignored_by_filters_cache={}):
try:
return filename_to_ignored_by_filters_cache[filename]
except:
import fnmatch
for stepping_filter in _get_stepping_filters():
... | new_filters.append(new_filter) | conditional_block |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):... | filename_to_not_in_scope_cache[original_filename] = True
# at this point it must be loaded.
return filename_to_not_in_scope_cache[original_filename]
def is_filter_enabled():
return os.getenv('PYDEVD_FILTERS') is not None
def is_filter_libraries():
is_filter = os.getenv(... | try:
return filename_to_not_in_scope_cache[filename]
except:
project_roots = _get_project_roots()
original_filename = filename
if not os.path.isabs(filename) and not filename.startswith('<'):
filename = os.path.abspath(filename)
filename = os.path.normcase(filenam... | identifier_body |
SiteConfig.ts | export class SiteConfig {
constructor() {
$("#smtpAuthType").on("change", this.rebuildVisibility.bind(this));
$("#emailTransport").on("change", this.rebuildVisibility.bind(this)).trigger("change");
}
private | () {
let transport = $("[name=\"mailService[transport]\"]").val(),
auth = $("[name=\"mailService[smtpAuthType]\"]").val();
$('.emailOption').hide();
if (transport == 'sendmail') {
// Nothing to do
} else if (transport == 'mandrill') {
$('.emailOption.... | rebuildVisibility | identifier_name |
SiteConfig.ts | export class SiteConfig {
constructor() {
$("#smtpAuthType").on("change", this.rebuildVisibility.bind(this));
$("#emailTransport").on("change", this.rebuildVisibility.bind(this)).trigger("change");
}
private rebuildVisibility() {
let transport = $("[name=\"mailService[transport]\"]"... | }
}
}
} | $('.emailOption.smtpTls').show();
$('.emailOption.smtpAuthType').show();
if (auth != 'none') {
$('.emailOption.smtpUsername').show();
$('.emailOption.smtpPassword').show(); | random_line_split |
SiteConfig.ts | export class SiteConfig {
constructor() |
private rebuildVisibility() {
let transport = $("[name=\"mailService[transport]\"]").val(),
auth = $("[name=\"mailService[smtpAuthType]\"]").val();
$('.emailOption').hide();
if (transport == 'sendmail') {
// Nothing to do
} else if (transport == 'mandrill')... | {
$("#smtpAuthType").on("change", this.rebuildVisibility.bind(this));
$("#emailTransport").on("change", this.rebuildVisibility.bind(this)).trigger("change");
} | identifier_body |
sentex_ML_demo7.py | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
... | plt.show()
'''
http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html
''' | plt.ylabel('ys')
plt.title("plot mx+b using linear regression fit") | random_line_split |
sentex_ML_demo7.py | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
... | (xs, ys):
m = (mean(xs) * mean(ys) - mean(xs*ys)) / ( mean(xs)*mean(xs) - mean(xs*xs) )
b = mean(ys) - m * mean(xs)
return m, b
m,b = best_fit_slope_and_intercept(xs, ys)
#regression_line = xs*m+b
regression_line = [m*x+b for x in xs]
print ( "m={}".format(m), ", b={}".format(b) )
predict_x = 8
predict_y ... | best_fit_slope_and_intercept | identifier_name |
sentex_ML_demo7.py | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
... |
m,b = best_fit_slope_and_intercept(xs, ys)
#regression_line = xs*m+b
regression_line = [m*x+b for x in xs]
print ( "m={}".format(m), ", b={}".format(b) )
predict_x = 8
predict_y = (m*predict_x) + b
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color = 'g', marker='s', s=50)
#plt.plot(xs, xs*m+b)
plt.plot(xs... | m = (mean(xs) * mean(ys) - mean(xs*ys)) / ( mean(xs)*mean(xs) - mean(xs*xs) )
b = mean(ys) - m * mean(xs)
return m, b | identifier_body |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "... |
});
}
list(query: string, coordinate: CoordinateModel) {
const path = this._config.apiUrl + '/places?query={query}&coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{query}', q... | {
return [];
} | conditional_block |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "... | }
listTheFavorites(){
const path = this._config.apiUrl + '/places?query=sport&favorites=true';
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
} | .delete(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
}); | random_line_split |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "... |
addToFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.post(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
... | {
const path = this._config.apiUrl + '/places/{id}?coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{id}', id);
return this._http
.get(path, { headers: this._config.apiHead... | identifier_body |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "... | (query: string){
let url = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=cb3856e77ccf23b9db42c77ad5c70d96&tags=${query}&per_page=1&format=json&nojsoncallback=1`;
return this._http
.get(url)
.map(res => res.json())
.map((val) => {
... | getFlickr | identifier_name |
shootout-nbody.rs | Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/... | shift_mut_ref | identifier_name | |
shootout-nbody.rs | :
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other m... |
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &... | {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
... | identifier_body |
shootout-nbody.rs | met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or oth... | vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64... | Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR, | random_line_split |
shootout-nbody.rs | permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIB... | { return None } | conditional_block | |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(... | (self):
return self.message
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available data providers.',
511: 'Data provider is not currently supported.',
512: 'Source type is not currently supported.',
513: 'Error while parsing the payload of the... | get_message | identifier_name |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(... | # Data processing
550: "Error processing data",
} | random_line_split | |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
|
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
def get_message(self):
return self.message
def get_status_code(self):
return self.status_code
erro... | self.status_code = status_code | conditional_block |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(... |
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available data providers.',
511: 'Data provider is not currently supported.',
512: 'Source type is not currently supported.',
513: 'Error while parsing the payload of the request.',
# geoserver
520... | return self.message | identifier_body |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = ... | except twitter.TwitterError as e:
context["error"] = e.message[0]["message"]
return context
return context
class OptOutHandleView(TemplateView):
template_name = "main/opt-out.html"
title = "Opt-out"
methods = ["GET", "POST"]
def get_context_data(self... | if image is not None:
image.mode = "rb"
try:
status = api.PostUpdate(tweet, image)
context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id) | random_line_split |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = ... |
try:
status = api.PostUpdate(tweet, image)
context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id)
except twitter.TwitterError as e:
context["error"] = e.message[0]["message"]
return context
... | image.mode = "rb" | conditional_block |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = ... | db.session.add(Blacklisted(handle))
db.session.commit()
return context
blueprint.add_url_rule("/", view_func=MainView.as_view("main"))
blueprint.add_url_rule("/opt-out", view_func=OptOutHandleView.as_view("opt-out"))
| context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if not app.config["INDEX_POSTING_ENABLED"]:
context["error"] = "Posting Tweets from the site index is currently disabled."
return context
if ratelimit.r... | identifier_body |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = ... | (TemplateView):
template_name = "main/opt-out.html"
title = "Opt-out"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if not app.config["INDEX_POSTIN... | OptOutHandleView | identifier_name |
index.d.ts | // Type definitions for nouislider v9.0.0
// Project: https://github.com/leongersen/noUiSlider
// Definitions by: Patrick Davies <https://github.com/bleuarg>, Guust Nieuwenhuis <https://github.com/lagaffe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="wnumb"/>
export = noUiSl... | /**
* To create a slider, call noUiSlider.create() with an element and your options.
*/
function create(target: HTMLElement, options: Options): void;
interface Options {
/**
* The start option sets the number of handles and their start positions, relative to range.
*/
start: number |... | random_line_split | |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def | (self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
protos = dict()
for dirpath, dirnames, filenames in os.walk(self.srcdir):
for fname in filenames:
... | __init__ | identifier_name |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
... |
else:
protos[node.spelling].append(node.result_type.get_canonical().spelling)
for c in node.get_arguments():
if (c.type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
... | protos[node.spelling].append("void *") | conditional_block |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
... | self.__clang_find_protos(c, protos) | random_line_split | |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
... | if (node.type.kind == TypeKind.FUNCTIONPROTO): # or node.type.kind == TypeKind.FUNCTIONNOPROTO):
if node.spelling not in protos.keys():
protos[node.spelling] = list()
if len(protos[node.spelling]) == 0:
if (node.result_type.spelling == "Lisp_Object"):
... | identifier_body | |
test_ddg_api_instant_answers.py | """Our instant answers come from a variety of sources, including
Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total.
Our long-term goal is for all of our instant answers to be available through this open API.
Many of these instant answers are open source via our DuckDuckHack platfor... | dg, url_params, logger, expected_ans_type, query, expected_value):
with pytest.allure.step("send request: {!r}".format(query)):
url_params.update(q=query)
r = ddg.get(params=url_params)
r.raise_for_status()
with pytest.allure.step("'AnswerType' in the response is {!r}".format(expected... | st_instant_answer(d | identifier_name |
test_ddg_api_instant_answers.py | """Our instant answers come from a variety of sources, including
Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total.
Our long-term goal is for all of our instant answers to be available through this open API.
Many of these instant answers are open source via our DuckDuckHack platfor... | logger.debug("Raw answer: {!r}".format(data['Answer']))
logger.debug("Processed answer: {!r}".format(answer))
assert answer == expected_value |
with pytest.allure.step("'Answer' in the response is {!r}".format(expected_value)):
answer = data['Answer'] | random_line_split |
test_ddg_api_instant_answers.py | """Our instant answers come from a variety of sources, including
Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total.
Our long-term goal is for all of our instant answers to be available through this open API.
Many of these instant answers are open source via our DuckDuckHack platfor... | th pytest.allure.step("send request: {!r}".format(query)):
url_params.update(q=query)
r = ddg.get(params=url_params)
r.raise_for_status()
with pytest.allure.step("'AnswerType' in the response is {!r}".format(expected_ans_type)):
data = r.json()
ans_type = data['AnswerType'... | identifier_body | |
ServiceAccountsPage.ts | import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Title } from '@angular/platform-browser';
import { Activate... | (
private yamcs: YamcsService,
title: Title,
private route: ActivatedRoute,
private router: Router,
private messageService: MessageService,
) {
title.setTitle('Service accounts');
this.dataSource.filterPredicate = (serviceAccount, filter) => {
return serviceAccount.name.toLowerCase()... | constructor | identifier_name |
ServiceAccountsPage.ts | import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Title } from '@angular/platform-browser';
import { Activate... |
}
}
| {
this.yamcs.yamcsClient.deleteServiceAccount(name)
.then(() => this.refresh())
.catch(err => this.messageService.showError(err));
} | conditional_block |
ServiceAccountsPage.ts | import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Title } from '@angular/platform-browser';
import { Activate... | private route: ActivatedRoute,
private router: Router,
private messageService: MessageService,
) {
title.setTitle('Service accounts');
this.dataSource.filterPredicate = (serviceAccount, filter) => {
return serviceAccount.name.toLowerCase().indexOf(filter) >= 0;
};
}
ngAfterViewInit(... | dataSource = new MatTableDataSource<ServiceAccount>();
constructor(
private yamcs: YamcsService,
title: Title, | random_line_split |
DataDescription.tsx | 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.... | value={this.props.value}
style={{fontSize: 11}}
/>
);
}
}
type DataDescriptionState = {
editing: boolean;
origValue: any;
value: any;
};
export class DataDescription extends PureComponent<
DataDescriptionProps,
DataDescriptionState
> {
constructor(props: DataDescriptionProps, ... | {
const extraProps: any = {};
if (this.props.type === 'number') {
// render as a HTML number input
extraProps.type = 'number';
// step="any" allows any sort of float to be input, otherwise we're limited
// to decimal
extraProps.step = 'any';
}
return (
<Input
... | identifier_body |
DataDescription.tsx | 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.... | export class DataDescription extends PureComponent<
DataDescriptionProps,
DataDescriptionState
> {
constructor(props: DataDescriptionProps, context: Object) {
super(props, context);
this.state = {
editing: false,
origValue: '',
value: '',
};
}
commit = (opts: DescriptionCommitO... | random_line_split | |
DataDescription.tsx | origValue: any;
}> {
onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val =
this.props.type === 'number'
? parseFloat(e.target.value)
: e.target.value;
this.props.commit({
clear: false,
keep: true,
value: val,
set: false,
});
}... | render | identifier_name | |
DataDescription.tsx | 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.... | else {
return;
}
this.props.commit({clear: false, keep: true, value: val, set: true});
};
onChangeLite = ({
rgb: {a, b, g, r},
}: {
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
if (typeof prev !== 'number') {
return;
}
... | {
// compute RRGGBBAA value
val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
const prevClear = ((prev >> 24) & 0xff) === 0;
const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff);
if (!onlyAlphaChan... | conditional_block |
Navigation.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
/// <reference path="../../index.d.ts" />
/// <reference path="./report/index.ts" ... | t view: ibas.IView = null;
switch (id) {
case app.ReportViewerApp.APPLICATION_ID:
view = new m.ReportViewerView();
break;
case app.UserReportPageApp.APPLICATION_ID:
view = new m.UserReportPage... | identifier_body | |
Navigation.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
/// <reference path="../../index.d.ts" />
/// <reference path="./report/index.ts" ... | View {
let view: ibas.IView = null;
switch (id) {
case app.ReportViewerApp.APPLICATION_ID:
view = new m.ReportViewerView();
break;
case app.UserReportPageApp.APPLICATION_ID:
vi... | ibas.I | identifier_name |
Navigation.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
/// <reference path="../../index.d.ts" />
/// <reference path="./report/index.ts" ... | }
}
}
} | break;
default:
break;
}
return view; | random_line_split |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_... |
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
@web.authenticated
def delete(self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
manager.terminate(name, force=True)
s... | entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time})) | conditional_block |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_... | manager = self.settings["tensorboard_manager"]
if name in manager:
manager.terminate(name, force=True)
self.set_status(204)
self.finish()
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name) | identifier_body | |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_... | manager = self.settings["tensorboard_manager"]
if name in manager:
entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
... | @web.authenticated
def get(self, name):
| random_line_split |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_... | (self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.relo... | get | identifier_name |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn new(ip: String, date: String, req: String, code: i32, size: i32, ... |
}
| {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
} | identifier_body |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn | (ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog {
fn eq(&self, other: &Self) -> bool {
s... | new | identifier_name |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn new(ip: String, date: String, req: String, code: i32, size: i32, ... | }
impl fmt::Display for Weblog {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
}
} | fn eq(&self, other: &Self) -> bool {
self.ip == other.ip && self.date == other.date
} | random_line_split |
mir-typeck-normalize-fn-sig.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'x> {
foo: for<'y> fn(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value,
}
fn foo<'y, 'x: 'x>(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value {
*x as f64
}
fn main() {
Providers { foo };
}
| Providers | identifier_name |
mir-typeck-normalize-fn-sig.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
Providers { foo };
} | identifier_body | |
mir-typeck-normalize-fn-sig.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // normalizing the signature afterwards. As a result, we sometimes got
// errors around the `<u32 as Foo<'x>>::Value`, which can be
// normalized to `f64`.
#![allow(dead_code)]
trait Foo<'x> {
type Value;
}
impl<'x> Foo<'x> for u32 {
type Value = f64;
}
struct Providers<'x> {
foo: for<'y> fn(x: &'x u32,... | // which involves extracting its signature, but we were not | random_line_split |
_webcore.ts | // TypeScript declarations for the Dicoogle webcore
import {SearchPatientResult} from 'dicoogle-client';
export type WebPluginType = string;
export type WebcoreEvent = 'load' | 'result' | string;
export interface WebPlugin {
name: string,
slotId: WebPluginType,
caption?: string,
} | [key: string]: any,
}
export interface Webcore {
issueQuery(query, options: IssueQueryOptions, callback: (error: any, result: any) => void);
issueQuery(query, callback: (error: any, result: any) => void);
addEventListener(eventName: WebcoreEvent, fn: (...args: any[]) => void);
addResultListener(fn... |
export interface IssueQueryOptions {
override?: string, | random_line_split |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
... | channels = 1
image_np = np.expand_dims(image_np, 2)
elif len(image_np.shape) == 3:
channels = image_np.shape[2]
else:
raise ValueError(
("Image should have ... | with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
("Image file '{}' no."
... | conditional_block |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
... | target_height: int = 227) -> Callable:
"""Load and prepare image the same way as Caffe scripts."""
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):... |
def imagenet_reader(prefix: str,
target_width: int = 227, | random_line_split |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
... | img_h, img_w = image.shape[:2]
image_padded = np.zeros((pad_h, pad_w, channels))
image_padded[:img_h, :img_w, :] = image
return image_padded | identifier_body | |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
... | (list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
... | load | identifier_name |
__init__.py | import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
'contract... | new_jobs_response_handler | identifier_name | |
__init__.py | that.utils import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
... | response.job_domains.sort(key=lambda item: item.label)
if job_criteria:
response.active = job_criteria.active
response.location = JobCriteriaLocationTO()
response.location.address = job_criteria.address
response.location.geo = JobCriteriaGeoLocationTO()
response.location... | to = JobKeyLabelTO()
to.key = domain
to.label = localize_jobs(user_profile.language, domain)
to.enabled = domain in job_criteria.job_domains if job_criteria else False
response.job_domains.append(to) | random_line_split |
__init__.py | that.utils import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
... |
response.contract_types.sort(key=lambda item: item.label)
for domain in JOB_DOMAINS:
to = JobKeyLabelTO()
to.key = domain
to.label = localize_jobs(user_profile.language, domain)
to.enabled = domain in job_criteria.job_domains if job_criteria else False
response.job_doma... | to = JobKeyLabelTO()
to.key = contract_type
to.label = localize_jobs(user_profile.language, contract_type)
to.enabled = contract_type in job_criteria.contract_types if job_criteria else False
response.contract_types.append(to) | conditional_block |
__init__.py | _from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
'contract_type_005',
'contr... | pass | identifier_body | |
forms.py | Validator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_databas... | instance.save()
else:
return None
create_config_files(instance.site)
if instance.site.category == "php":
reload_php_fpm()
elif | site = forms.ModelChoiceField(queryset=Site.objects.all(), disabled=True)
host = forms.ModelChoiceField(queryset=DatabaseHost.objects.all(), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, user, *args, **kwargs):
super(DatabaseForm, self).__init__(*args, **kwargs)
self.initial[... | identifier_body |
forms.py | Validator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_databas... | (self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.host = SiteHost.objects.first()
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
instance.group.users.clear()
instance.group.users.add(instance.user)
... | save | identifier_name |
forms.py | Validator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_databas... |
elif domain.endswith(settings.PROJECT_DOMAIN):
if not domain[:-len(settings.PROJECT_DOMAIN)].rstrip(".") == self.cleaned_data["name"]:
if not self._user.is_superuser:
raise forms.ValidationError("Your subdomain for {} must match your site name!".f... | raise forms.ValidationError("Only administrators can set up *.tjhsst.edu domains.") | conditional_block |
forms.py | Validator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_databas... |
class Meta:
model = Site
fields = ["name", "domain", "description", "category", "purpose", "users", "custom_nginx"]
class ProcessForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProcessForm, self).__init__(*args, **kwargs)
if not user.is_superuser:
... | create_config_files(instance)
return instance | random_line_split |
SearchContainer.js | import React, { Component } from 'react';
import InfoSection from '../components/InfoSection';
import InfoSectionToggle from '../components/InfoSectionToggle';
class SearchContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
error: '',
showConte... |
}
renderInfoSection() {
return (
<InfoSection
revealContent={this.state.showContent}
content={this.state.content}
title={'Add Skill'}
/>
);
}
render() {
return (
<div>
{this.renderInfoSection()}
<section>
<InfoSectionToggle onPressIn... | {
return (
<li>
<div className="error">
<span className="message">{this.state.error}</span>
<span className="error-icon" onClick={this.onPressError.bind(this)}>
<i className="fa fa-times-circle"></i>
</span>
</div>
</li>
)... | conditional_block |
SearchContainer.js | import React, { Component } from 'react';
import InfoSection from '../components/InfoSection';
import InfoSectionToggle from '../components/InfoSectionToggle';
class SearchContainer extends React.Component {
constructor(props) {
super(props); | showContent: true,
content: `The field below accepts search criteria for those on Odecee bench. Try searching by technologies like: 'node', or 'javascript' and you will see a list of candidates with those skill sets.`
};
}
onPressError() {
this.setState({
error: ''
});
}
onPressI... | this.state = {
message: '',
error: '', | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.