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 |
|---|---|---|---|---|
file_path_generator.py | # Copyright 2018-present Facebook, 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... | (
self,
package_key,
root,
depth,
sizes_by_depth,
component_generator,
extension=None,
):
assert depth >= 1
parent_path, parent_dir = self._generate_parent(
package_key, root, depth - 1, sizes_by_depth, component_generator
)... | _generate_path | identifier_name |
file_path_generator.py | # Copyright 2018-present Facebook, 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... |
def _split_path_into_components(self, path):
components = []
while path:
path, component = os.path.split(path)
components.append(component)
return components[::-1]
def _generate_path(
self,
package_key,
root,
depth,
sizes... | directory = self._root
existed = True
for component in self._split_path_into_components(path):
if component not in directory:
directory[component] = {}
existed = False
directory = directory[component]
if directory is None:
... | identifier_body |
_text.js | /* global Fae, SimpleMDE, toolbarBuiltInButtons */
/**
* Fae form text
* @namespace form.text
* @memberof form
*/
Fae.form.text = {
init: function() {
this.overrideMarkdownDefaults();
this.initMarkdown();
},
/**
* Override SimpleMDE's preference for font-awesome icons and use a modal for the gui... | var editor = new SimpleMDE({
element: this,
autoDownloadFontAwesome: false,
status: false,
spellChecker: false,
hideIcons: ['image', 'side-by-side', 'fullscreen', 'preview']
});
// Disable tabbing within editor
editor.codemirror.options.extraKeys['Tab'] =... | var $this = $(this);
| random_line_split |
print_progressbar.py | # -*- coding: utf-8 -*-
import sys
def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
... | sys.stdout.flush() | s.stdout.write('\n')
| conditional_block |
print_progressbar.py | # -*- coding: utf-8 -*-
import sys
def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
| sys.stdout.flush() | """
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optiona... | identifier_body |
print_progressbar.py | # -*- coding: utf-8 -*-
import sys
def | (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
... | print_progress | identifier_name |
print_progressbar.py | # -*- coding: utf-8 -*-
import sys
def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
... | With slight adjustment so that it allows just one iteration (total = 0)
"""
formatStr = "{0:." + str(decimals) + "f}"
percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100)
filledLength = int(round(barLength * iteration / float(total))) if not ... | barLength - Optional : character length of bar (Int)
copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console | random_line_split |
chart_of_accounts.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe, os, json
from frappe.utils import cstr
from unidecode import unidecode
from six import iteritems
def create_charts(company, chart_template=None, existing_company=None):
chart... | "is_group": is_group,
"root_type": root_type,
"report_type": report_type,
"account_number": account_number,
"account_type": child.get("account_type"),
"account_currency": frappe.db.get_value("Company", company, "default_currency"),
"tax_rate": child.get("tax_rate")
})
... | for account_name, child in iteritems(children):
if root_account:
root_type = child.get("root_type")
if account_name not in ["account_number", "account_type",
"root_type", "is_group", "tax_rate"]:
account_number = cstr(child.get("account_number")).strip()
account_name, account_name_in_db = ... | identifier_body |
chart_of_accounts.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe, os, json
from frappe.utils import cstr
from unidecode import unidecode
from six import iteritems
def create_charts(company, chart_template=None, existing_company=None):
chart... | else:
is_group = 0
return is_group
def get_chart(chart_template, existing_company=None):
chart = {}
if existing_company:
return get_account_tree_from_existing_company(existing_company)
elif chart_template == "Standard":
from erpnext.accounts.doctype.account.chart_of_accounts.verified import standard_chart... | elif len(set(child.keys()) - set(["account_type", "root_type", "is_group", "tax_rate", "account_number"])):
is_group = 1 | random_line_split |
chart_of_accounts.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe, os, json
from frappe.utils import cstr
from unidecode import unidecode
from six import iteritems
def create_charts(company, chart_template=None, existing_company=None):
chart... | (existing_company):
all_accounts = frappe.get_all('Account',
filters={'company': existing_company},
fields = ["name", "account_name", "parent_account", "account_type",
"is_group", "root_type", "tax_rate", "account_number"],
order_by="lft, rgt")
account_tree = {}
# fill in tree starting with root accounts ... | get_account_tree_from_existing_company | identifier_name |
chart_of_accounts.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe, os, json
from frappe.utils import cstr
from unidecode import unidecode
from six import iteritems
def create_charts(company, chart_template=None, existing_company=None):
chart... |
# call recursively to build a subtree for current account
build_account_tree(tree[child.account_name], child, all_accounts)
@frappe.whitelist()
def validate_bank_account(coa, bank_account):
accounts = []
chart = get_chart(coa)
if chart:
def _get_account_names(account_master):
for account_name, child in ... | tree[child.account_name]["root_type"] = child.root_type | conditional_block |
borrowed-c-style-enum.rs | // compile-flags:-g
// min-lldb-version: 310
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *the_a_ref
// gdbg-check:$1 = TheA
// gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA
// gdb-command:print *the_b_ref
// gdbg-che... | () {
let the_a = ABC::TheA;
let the_a_ref: &ABC = &the_a;
let the_b = ABC::TheB;
let the_b_ref: &ABC = &the_b;
let the_c = ABC::TheC;
let the_c_ref: &ABC = &the_c;
zzz(); // #break
}
fn zzz() {()}
| main | identifier_name |
borrowed-c-style-enum.rs | // compile-flags:-g
// min-lldb-version: 310
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *the_a_ref
// gdbg-check:$1 = TheA
// gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA
// gdb-command:print *the_b_ref
// gdbg-che... | {()} | identifier_body | |
borrowed-c-style-enum.rs | // compile-flags:-g
// min-lldb-version: 310
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *the_a_ref | // gdbr-check:$2 = borrowed_c_style_enum::ABC::TheB
// gdb-command:print *the_c_ref
// gdbg-check:$3 = TheC
// gdbr-check:$3 = borrowed_c_style_enum::ABC::TheC
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *the_a_ref
/... | // gdbg-check:$1 = TheA
// gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA
// gdb-command:print *the_b_ref
// gdbg-check:$2 = TheB | random_line_split |
ext.rs | use std::io;
use std::mem;
use std::net::SocketAddr;
use std::os::unix::io::RawFd;
use libc;
use sys::unix::err::cvt;
#[inline]
#[allow(dead_code)]
pub fn pipe() -> io::Result<(RawFd, RawFd)> {
let mut fds = [0 as libc::c_int; 2];
cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK)... |
#[inline]
pub fn socket_v6() -> io::Result<RawFd> {
let res = unsafe {
libc::socket(
libc::AF_INET6,
libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
0,
)
};
cvt(res)
}
#[inline]
pub fn accept(listener_fd: RawFd) -> io::Result<(RawFd, Socke... | {
let res = unsafe {
libc::socket(
libc::AF_INET,
libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
0,
)
};
cvt(res)
} | identifier_body |
ext.rs | use std::io;
use std::mem;
use std::net::SocketAddr;
use std::os::unix::io::RawFd;
use libc;
use sys::unix::err::cvt;
#[inline]
#[allow(dead_code)]
pub fn pipe() -> io::Result<(RawFd, RawFd)> {
let mut fds = [0 as libc::c_int; 2];
cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK)... | () -> io::Result<RawFd> {
let res = unsafe {
libc::socket(
libc::AF_INET,
libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
0,
)
};
cvt(res)
}
#[inline]
pub fn socket_v6() -> io::Result<RawFd> {
let res = unsafe {
libc::socket(
... | socket_v4 | identifier_name |
ext.rs | use std::net::SocketAddr;
use std::os::unix::io::RawFd;
use libc;
use sys::unix::err::cvt;
#[inline]
#[allow(dead_code)]
pub fn pipe() -> io::Result<(RawFd, RawFd)> {
let mut fds = [0 as libc::c_int; 2];
cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) })?;
Ok((fds[0], fds[1... | use std::io;
use std::mem; | random_line_split | |
datestring_convert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
def | (s):
"""Convert datetime string which appears in subversion commit log.
"""
assert type(s) == str, "Argument must be string"
dt = s.split()
year, month, day = map(int, dt[0].split("-"))
hour, minute, second = map(int, dt[1].split(":"))
return datetime.datetime(year, month, day, hour, minute,... | datestring_convert | identifier_name |
datestring_convert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
def datestring_convert(s):
"""Convert datetime string which appears in subversion commit log.
"""
assert type(s) == str, "Argument must be string"
dt = s.split()
year, month, day = map(int, dt[0].split("-"))
hour, minute, second = ... |
# vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
| TEST_1 = "2012-01-14 07:56:02"
TEST_2 = "2012-01-14 04:46:30 +0900"
d1 = datestring_convert(TEST_1)
d2 = datestring_convert(TEST_2)
diff = d1 - d2
print("{} ==> {}".format(TEST_1, TEST_2))
print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds)) | conditional_block |
datestring_convert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
| """Convert datetime string which appears in subversion commit log.
"""
assert type(s) == str, "Argument must be string"
dt = s.split()
year, month, day = map(int, dt[0].split("-"))
hour, minute, second = map(int, dt[1].split(":"))
return datetime.datetime(year, month, day, hour, minute, seco... | def datestring_convert(s): | random_line_split |
datestring_convert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
def datestring_convert(s):
|
if __name__ == '__main__':
TEST_1 = "2012-01-14 07:56:02"
TEST_2 = "2012-01-14 04:46:30 +0900"
d1 = datestring_convert(TEST_1)
d2 = datestring_convert(TEST_2)
diff = d1 - d2
print("{} ==> {}".format(TEST_1, TEST_2))
print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds))
# vim... | """Convert datetime string which appears in subversion commit log.
"""
assert type(s) == str, "Argument must be string"
dt = s.split()
year, month, day = map(int, dt[0].split("-"))
hour, minute, second = map(int, dt[1].split(":"))
return datetime.datetime(year, month, day, hour, minute, second) | identifier_body |
progressbar.js | !function ($) {
var ProgressBar = function (element, options) {
this.element = $(element);
this.position = 0; | this.percent = 0;
var hasOptions = typeof options == 'object';
this.dangerMarker = $.fn.progressbar.defaults.dangerMarker;
if (hasOptions && typeof options.dangerMarker == 'number') {
this.setDangerMarker(options.dangerMarker);
}
this.warningMarker = $.fn.progressbar.defaults.warningMarker;
if (hasO... | random_line_split | |
logging.js | /**
* Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
* @version 1.1
* @author Sky_, TCSASSEMBLER
* changes in 1.1:
* 1. change handleError. Return sql error with unique constrains as Bad Request.
* 2. close db when request ends.
* 3. don't create transactions for GET requests
*/
"use strict";
var _ = r... |
winston.info("EXIT %s %j", signature, paramsToLog, {});
if (!customHandled) {
res.json(apiResult);
}
disposeDB();
}
], function (error) {
if (canRollback && transaction) {
transaction.rol... | {
paramsToLog.response = apiResult;
} | conditional_block |
logging.js | /**
* Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
* @version 1.1
* @author Sky_, TCSASSEMBLER
* changes in 1.1:
* 1. change handleError. Return sql error with unique constrains as Bad Request.
* 2. close db when request ends.
* 3. don't create transactions for GET requests
*/
"use strict";
var _ = r... | baseError = apiCodes.notFound;
} else if (error.code === 'ER_DUP_ENTRY') {
baseError = apiCodes.badRequest;
if (error.message.indexOf("UC_c_sort") !== -1) {
error.message += ". Pair of the columns 'sort' and 'tab' must be unique.";
}
}
errdetail = _.clone(baseErro... | baseError = apiCodes.badRequest;
} else if (error instanceof NotFoundError) { | random_line_split |
logging.js | /**
* Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
* @version 1.1
* @author Sky_, TCSASSEMBLER
* changes in 1.1:
* 1. change handleError. Return sql error with unique constrains as Bad Request.
* 2. close db when request ends.
* 3. don't create transactions for GET requests
*/
"use strict";
var _ = r... |
/**
* This function create a delegate for the express action.
* Input and output logging is performed.
* Errors are handled also and proper http status code is set.
* Wrapped method must always call the callback function, first param is error, second param is object to return.
* @param {String} signature the si... | {
var errdetail, baseError = apiCodes.serverError;
if (error.isValidationError ||
error instanceof IllegalArgumentError ||
error instanceof BadRequestError) {
baseError = apiCodes.badRequest;
} else if (error instanceof NotFoundError) {
baseError = apiCodes.notFound;
... | identifier_body |
logging.js | /**
* Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
* @version 1.1
* @author Sky_, TCSASSEMBLER
* changes in 1.1:
* 1. change handleError. Return sql error with unique constrains as Bad Request.
* 2. close db when request ends.
* 3. don't create transactions for GET requests
*/
"use strict";
var _ = r... | (signature, fn, customHandled) {
if (!_.isString(signature)) {
throw new Error("signature should be a string");
}
if (!_.isFunction(fn)) {
throw new Error("fn should be a function");
}
return function (req, res, next) {
var paramsToLog, db, transaction, apiResult, canRollback... | wrapExpress | identifier_name |
asha-workers-details.service_20170227130424.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerP... | (ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{
let body = JSON.stringify(ashaWorkerPaymentRulesModel);
console.log("body = "+ body);
return this.http.post(this.updateURL,body)
.toPromise()
.then(response => response... | updateAshaWorkerPaymentRules | identifier_name |
asha-workers-details.service_20170227130424.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerP... |
getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{
//return Promise.resolve(AshaWorkersList);
return this.http.get(this.url)
.toPromise()
.then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[]) ... | {} | identifier_body |
asha-workers-details.service_20170227130424.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerP... | export class AshaWorkersDetailsService{
private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details";
private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity"
constructor(private http: Http){}
... |
@Injectable() | random_line_split |
donate.ts | let dialog: HTMLDivElement = null
export function getDialog (title: string, content: string, qrcodes: {src: string, desc: string}[]) | qrcode.className = 'donate-qrcode-img'
qrcode.src = i.src
const qrcodeDesc = document.createElement('div')
qrcodeDesc.className = 'donate-qrcode-desc'
qrcodeDesc.innerText = i.desc
qrcodeBox.appendChild(qrcode)
qrcodeBox.appendChild(qrcodeDesc)
qrcodeEl.appendChild(qrcodeBox)
}... | {
if (dialog) {
return dialog
}
dialog = document.createElement('div')
dialog.className = 'donate-dialog'
const wrap = document.createElement('div')
wrap.className = 'donate-wrap'
const titleEl = document.createElement('h3')
titleEl.className = 'donate-title'
titleEl.innerText = title
... | identifier_body |
donate.ts | let dialog: HTMLDivElement = null
export function getDialog (title: string, content: string, qrcodes: {src: string, desc: string}[]) {
if (dialog) {
return dialog
}
dialog = document.createElement('div')
dialog.className = 'donate-dialog'
const wrap = document.createElement('div')
wrap.className... | } | wrap.appendChild(closeEl)
dialog.appendChild(wrap)
dialog.style.display = 'none'
return dialog
| random_line_split |
donate.ts | let dialog: HTMLDivElement = null
export function | (title: string, content: string, qrcodes: {src: string, desc: string}[]) {
if (dialog) {
return dialog
}
dialog = document.createElement('div')
dialog.className = 'donate-dialog'
const wrap = document.createElement('div')
wrap.className = 'donate-wrap'
const titleEl = document.createElement('... | getDialog | identifier_name |
donate.ts | let dialog: HTMLDivElement = null
export function getDialog (title: string, content: string, qrcodes: {src: string, desc: string}[]) {
if (dialog) |
dialog = document.createElement('div')
dialog.className = 'donate-dialog'
const wrap = document.createElement('div')
wrap.className = 'donate-wrap'
const titleEl = document.createElement('h3')
titleEl.className = 'donate-title'
titleEl.innerText = title
const contentEl = document.createElement(... | {
return dialog
} | conditional_block |
place.js | define([
'jquery',
'jquery-ui',
'dialogForm'
], function($, jqueryUi, DialogForm) {
return function(id, writer) {
var w = writer;
var html = ''+
'<div id="'+id+'Dialog" class="annotationDialog">'+ | id: id,
type: 'place',
title: 'Tag Place',
height: 150,
width: 450,
html: html
});
dialog.$el.on('beforeShow', function(e, config, dialog) {
var cwrcInfo = dialog.currentData.cwrcInfo;
if (cwrcInfo !== undefined) {
$('#'+id+'_ref')... | '<input type="hidden" id="'+id+'_ref" data-type="hidden" data-mapping="REF"/>'+
'</div>';
var dialog = new DialogForm({
writer: w, | random_line_split |
place.js | define([
'jquery',
'jquery-ui',
'dialogForm'
], function($, jqueryUi, DialogForm) {
return function(id, writer) {
var w = writer;
var html = ''+
'<div id="'+id+'Dialog" class="annotationDialog">'+
'<input type="hidden" id="'+id+'_ref" data-type="hidden" data-mapping="REF"/>'+
... |
});
return {
show: function(config) {
dialog.show(config);
}
};
};
}); | {
$('#'+id+'_ref').val(cwrcInfo.id);
} | conditional_block |
datemath.ts | ///<reference path="../../headers/common.d.ts" />
import _ from 'lodash';
import moment from 'moment';
var units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
export function parse(text, roundUp?) {
if (!text) { return undefined; }
if (moment.isMoment(text)) { return text; }
if (_.isDate(text)) { return moment(text);... | } else if (type === 1) {
dateTime.add(num, unit);
} else if (type === 2) {
dateTime.subtract(num, unit);
}
}
}
return dateTime;
} | dateTime.startOf(unit);
} | random_line_split |
datemath.ts | ///<reference path="../../headers/common.d.ts" />
import _ from 'lodash';
import moment from 'moment';
var units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
export function parse(text, roundUp?) {
if (!text) { return undefined; }
if (moment.isMoment(text)) { return text; }
if (_.isDate(text)) { return moment(text);... | (mathString, time, roundUp?) {
var dateTime = time;
var i = 0;
var len = mathString.length;
while (i < len) {
var c = mathString.charAt(i++);
var type;
var num;
var unit;
if (c === '/') {
type = 0;
} else if (c === '+') {
type = 1;
} else if (c === '-') {
type = 2... | parseDateMath | identifier_name |
datemath.ts | ///<reference path="../../headers/common.d.ts" />
import _ from 'lodash';
import moment from 'moment';
var units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
export function parse(text, roundUp?) | mathString = text.substring(index + 2);
}
// We're going to just require ISO8601 timestamps, k?
time = moment(parseString, moment.ISO_8601);
}
if (!mathString.length) {
return time;
}
return parseDateMath(mathString, time, roundUp);
}
export function isValid(text) {
var date = parse(... | {
if (!text) { return undefined; }
if (moment.isMoment(text)) { return text; }
if (_.isDate(text)) { return moment(text); }
var time;
var mathString = '';
var index;
var parseString;
if (text.substring(0, 3) === 'now') {
time = moment();
mathString = text.substring('now'.length);
} else {
... | identifier_body |
normalize_projection_ty.rs | use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::TraitEngineExt as _;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
use rustc_trait_selection::infer::InferCtxtBuilderExt;
use rustc_trait_selection::trai... |
fn normalize_projection_ty<'tcx>(
tcx: TyCtxt<'tcx>,
goal: CanonicalProjectionGoal<'tcx>,
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> {
debug!("normalize_provider(goal={:#?})", goal);
tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering:... | {
*p = Providers { normalize_projection_ty, ..*p };
} | identifier_body |
normalize_projection_ty.rs | use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::TraitEngineExt as _;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
use rustc_trait_selection::infer::InferCtxtBuilderExt;
use rustc_trait_selection::trai... | <'tcx>(
tcx: TyCtxt<'tcx>,
goal: CanonicalProjectionGoal<'tcx>,
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> {
debug!("normalize_provider(goal={:#?})", goal);
tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed);
tcx.infer_ctx... | normalize_projection_ty | identifier_name |
normalize_projection_ty.rs | use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::TraitEngineExt as _;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
use rustc_trait_selection::infer::InferCtxtBuilderExt;
use rustc_trait_selection::trai... | );
fulfill_cx.register_predicate_obligations(infcx, obligations);
Ok(NormalizationResult { normalized_ty: answer })
},
)
} | goal,
cause,
0,
&mut obligations, | random_line_split |
test_process_mode_boot.py | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | exit_message = subprocess.check_output(args, env=self.env).decode("utf-8")
self.assertIn("No control endpoint provided.", exit_message)
def test_set_working_directory(self):
JProcessPythonEnvironmentManager = \
get_gateway().jvm.org.apache.flink.python.env.beam.ProcessPythonEnvi... | "--logging_endpoint", "localhost:0000",
"--provision_endpoint", "localhost:%d" % self.provision_port] | random_line_split |
test_process_mode_boot.py | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... |
def test_set_working_directory(self):
JProcessPythonEnvironmentManager = \
get_gateway().jvm.org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager
output_file = os.path.join(self.tmp_dir, "output.txt")
pyflink_dir = os.path.join(self.tmp_dir, "pyflink")
os.m... | args = [self.runner_path]
exit_message = subprocess.check_output(args, env=self.env).decode("utf-8")
self.assertIn("No id provided.", exit_message)
args = [self.runner_path, "--id", "1"]
exit_message = subprocess.check_output(args, env=self.env).decode("utf-8")
self.assertIn("No... | identifier_body |
test_process_mode_boot.py | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... |
self.assertEqual(os.path.realpath(self.tmp_dir),
process_cwd,
"setting working directory variable is not work!")
def tearDown(self):
self.provision_server.stop(0)
try:
if self.tmp_dir is not None:
shutil.rmtree(... | with open(output_file, 'r') as f:
process_cwd = f.read() | conditional_block |
test_process_mode_boot.py | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | ():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
add_ProvisionServiceServicer_to_server(ProvisionService(), server)
port = get_unused_port()
server.add_insecure_port('[::]:' + str(port))
server.start()
return server, port
... | start_test_provision_server | identifier_name |
platform-credentials-modal.component.spec.ts | import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {AuthService} from "../../../auth/auth.service";
import {SystemService} from "../../../platform-providers/system.service";
import {AutoCompleteComponent} from "../../../ui/auto... | });
it("should create", () => {
expect(component).toBeTruthy();
});
}); | component = fixture.componentInstance;
fixture.detectChanges(); | random_line_split |
x86_64_linux_android.rs | // https://developer.android.com/ndk/guides/abis.html#86-64
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string());
// don't use probe-stack=inline-asm unt... | use crate::spec::{LinkerFlavor, StackProbeType, Target};
pub fn target() -> Target {
let mut base = super::android_base::opts();
base.cpu = "x86-64".to_string(); | random_line_split | |
x86_64_linux_android.rs | use crate::spec::{LinkerFlavor, StackProbeType, Target};
pub fn | () -> Target {
let mut base = super::android_base::opts();
base.cpu = "x86-64".to_string();
// https://developer.android.com/ndk/guides/abis.html#86-64
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.entry(L... | target | identifier_name |
x86_64_linux_android.rs | use crate::spec::{LinkerFlavor, StackProbeType, Target};
pub fn target() -> Target | {
let mut base = super::android_base::opts();
base.cpu = "x86-64".to_string();
// https://developer.android.com/ndk/guides/abis.html#86-64
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string();
base.max_atomic_width = Some(64);
base.pre_link_args.entry(LinkerFlavor::... | identifier_body | |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from aiohttp.log import... |
class ImproperlyConfigured(BaseException):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
class BaseSettings(object):
"""
Common logic for settings whether set by a module or by the user.
"""
def __setattr__(self, name, value):
... |
from . import global_settings
ENVIRONMENT_VARIABLE = "AIOWEB_SETTINGS_MODULE"
| random_line_split |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from aiohttp.log import... | (BaseSettings):
"""
Holder for user configured settings.
"""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are ... | UserSettingsHolder | identifier_name |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from aiohttp.log import... |
def __delattr__(self, name):
self._deleted.add(name)
if hasattr(self, name):
super(UserSettingsHolder, self).__delattr__(name)
def __dir__(self):
return sorted(
s for s in list(self.__dict__) + dir(self.default_settings)
if s not in self._deleted
... | self._deleted.discard(name)
super(UserSettingsHolder, self).__setattr__(name, value) | identifier_body |
__init__.py | """
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from aiohttp.log import... |
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
if self.SETTINGS_MODULE:
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
tuple_settings = (
"APPS",
)
... | if setting.isupper():
setattr(self, setting, getattr(global_settings, setting)) | conditional_block |
munging.js | var d3 = require('d3');
function true_index(arr, config) {
// Series.ix[start, end].true().index;
if (!config) { config = {}; }
if (!config.length) { config.length = arr.length }
config.start = config.start ? config.start : 0;
config.end = config.end ? config.end : config.length;
var valid = new Array(co... |
}
return data;
}
module.exports.true_index = true_index;
module.exports.where = where;
mask = [true, true, false, false, true, false]
series = d3.range(mask.length);
res = true_index(mask, {});
res = true_index(mask, {'start':1});
res = where(series, mask);
| {
data[i] = null;
} | conditional_block |
munging.js | var d3 = require('d3');
function true_index(arr, config) {
// Series.ix[start, end].true().index;
if (!config) { config = {}; }
if (!config.length) { config.length = arr.length }
config.start = config.start ? config.start : 0;
config.end = config.end ? config.end : config.length;
var valid = new Array(co... | }
valid = valid.slice(0, j);
return valid;
}
function where(arr, mask) {
var data = arr.slice(0);
for (var i=0; i < data.length; i++) {
if (!mask[i]) {
data[i] = null;
}
}
return data;
}
module.exports.true_index = true_index;
module.exports.where = where;
mask = [true, true, false, false... | if (arr[i]) {
valid[j] = i;
j++;
} | random_line_split |
munging.js | var d3 = require('d3');
function true_index(arr, config) |
function where(arr, mask) {
var data = arr.slice(0);
for (var i=0; i < data.length; i++) {
if (!mask[i]) {
data[i] = null;
}
}
return data;
}
module.exports.true_index = true_index;
module.exports.where = where;
mask = [true, true, false, false, true, false]
series = d3.range(mask.length);
re... | {
// Series.ix[start, end].true().index;
if (!config) { config = {}; }
if (!config.length) { config.length = arr.length }
config.start = config.start ? config.start : 0;
config.end = config.end ? config.end : config.length;
var valid = new Array(config.length);
var j = 0;
for (var i=config.start; i <=... | identifier_body |
munging.js | var d3 = require('d3');
function | (arr, config) {
// Series.ix[start, end].true().index;
if (!config) { config = {}; }
if (!config.length) { config.length = arr.length }
config.start = config.start ? config.start : 0;
config.end = config.end ? config.end : config.length;
var valid = new Array(config.length);
var j = 0;
for (var i=conf... | true_index | identifier_name |
sync.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | /// Network information
pub network: PeerNetworkInfo,
/// Protocols information
pub protocols: PeerProtocolsInfo,
}
/// Peer network information
#[derive(Default, Debug, Serialize)]
pub struct PeerNetworkInfo {
/// Remote endpoint address
#[serde(rename="remoteAddress")]
pub remote_address: String,
/// Local e... | /// Node client ID
pub name: String,
/// Capabilities
pub caps: Vec<String>, | random_line_split |
sync.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
#[test]
fn test_serialize_peers() {
let t = Peers::default();
let serialized = serde_json::to_string(&t).unwrap();
assert_eq!(serialized, r#"{"active":0,"connected":0,"max":0,"peers":[]}"#);
}
#[test]
fn test_serialize_sync_status() {
let t = SyncStatus::None;
let serialized = serde_json::to_string(&t... | {
let t = SyncInfo::default();
let serialized = serde_json::to_string(&t).unwrap();
assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#);
} | identifier_body |
sync.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | {
/// Public node id
pub id: Option<String>,
/// Node client ID
pub name: String,
/// Capabilities
pub caps: Vec<String>,
/// Network information
pub network: PeerNetworkInfo,
/// Protocols information
pub protocols: PeerProtocolsInfo,
}
/// Peer network information
#[derive(Default, Debug, Serialize)]
pub... | PeerInfo | identifier_name |
timeline.js | var events = {};
function showEvent(e) {
eid = e.getAttribute('data-event-id');
fid = e.getAttribute('data-frame-id');
var url = '?view=event&eid='+eid+'&fid='+fid;
url += filterQuery;
window.location.href = url;
//video element is blocking video elements elsewhere in chrome possible interaction with mous... | (zm_event, frame) {
var eventHtml = new Element('div');
if ( zm_event.Archived > 0 ) {
eventHtml.addClass('archived');
}
new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name);
new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):''));
... | createEventHtml | identifier_name |
timeline.js | var events = {};
function showEvent(e) {
eid = e.getAttribute('data-event-id');
fid = e.getAttribute('data-frame-id');
var url = '?view=event&eid='+eid+'&fid='+fid;
url += filterQuery;
window.location.href = url;
//video element is blocking video elements elsewhere in chrome possible interaction with mous... |
function previewEvent(slot) {
eventId = slot.getAttribute('data-event-id');
frameId = slot.getAttribute('data-frame-id');
if ( events[eventId] ) {
showEventData(eventId, frameId);
} else {
requestFrameData(eventId, frameId);
}
}
function loadEventImage( imagePath, eid, fid, width, height, fps, vide... | {
if ( !events[eventId] ) {
eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId;
eventQuery.send();
} else {
frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId;
frameQuery.send();
}
} | identifier_body |
timeline.js | var events = {};
function showEvent(e) {
eid = e.getAttribute('data-event-id');
fid = e.getAttribute('data-frame-id');
var url = '?view=event&eid='+eid+'&fid='+fid;
url += filterQuery;
window.location.href = url;
//video element is blocking video elements elsewhere in chrome possible interaction with mous... |
}
function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) {
var vid = $('preview');
var imageSrc = $('imageSrc');
if ( videoName && vid ) {
vid.show();
imageSrc.hide();
var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName;
... | {
requestFrameData(eventId, frameId);
} | conditional_block |
timeline.js | var events = {};
function showEvent(e) {
eid = e.getAttribute('data-event-id');
fid = e.getAttribute('data-frame-id');
var url = '?view=event&eid='+eid+'&fid='+fid;
url += filterQuery;
window.location.href = url;
//video element is blocking video elements elsewhere in chrome possible interaction with mous... | eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId;
eventQuery.send();
} else {
frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId;
frameQuery.send();
}
}
function previewEvent(slot) {
event... | function requestFrameData( eventId, frameId ) {
if ( !events[eventId] ) { | random_line_split |
graphviz.py | """Generate directed and non-directed graphs using Graphviz."""
import asyncio
import io
import os
import subprocess
import threading
import dot_parser
from dot_parser import graph_definition
from pyparsing import ParseException
from plumeria.command import commands, CommandError
from plumeria.message import Respons... | (s):
with lock:
dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad
parser = graph_definition()
parser.parseWithTabs()
tokens = parser.parseString(s)
return list(tokens)
def render_dot(graph, format="png"):
program = 'dot'
if os.na... | parse_dot_data | identifier_name |
graphviz.py | """Generate directed and non-directed graphs using Graphviz."""
import asyncio
import io
import os
import subprocess
import threading
import dot_parser
from dot_parser import graph_definition
from pyparsing import ParseException
from plumeria.command import commands, CommandError
from plumeria.message import Respons... | tokens = parser.parseString(s)
return list(tokens)
def render_dot(graph, format="png"):
program = 'dot'
if os.name == 'nt' and not program.endswith('.exe'):
program += '.exe'
p = subprocess.Popen(
[program, '-T' + format],
env={'SERVER_NAME': 'plumeria',
... | def parse_dot_data(s):
with lock:
dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad
parser = graph_definition()
parser.parseWithTabs() | random_line_split |
graphviz.py | """Generate directed and non-directed graphs using Graphviz."""
import asyncio
import io
import os
import subprocess
import threading
import dot_parser
from dot_parser import graph_definition
from pyparsing import ParseException
from plumeria.command import commands, CommandError
from plumeria.message import Respons... |
@commands.create("digraph", category="Graphing")
@rate_limit()
async def digraph(message):
"""
Generates a directed graph using DOT syntax and drawn using Graphviz.
Example::
/digraph
a -> b
b -> c
c -> a
"""
return await handle_request(message, "digraph")
def... | """
Generates a non-directed graph using DOT syntax and drawn using Graphviz.
Example::
/graph
a -- b
b -- c
c -- a
"""
return await handle_request(message, "graph") | identifier_body |
graphviz.py | """Generate directed and non-directed graphs using Graphviz."""
import asyncio
import io
import os
import subprocess
import threading
import dot_parser
from dot_parser import graph_definition
from pyparsing import ParseException
from plumeria.command import commands, CommandError
from plumeria.message import Respons... |
return stdout
async def handle_request(message, type):
content = strip_markdown_code(message.content.strip())
def execute():
# Use parser as a rudimentary validator
graph = parse_dot_data(type + " G {\n" + content + "\n}")[0]
buf = io.BytesIO()
buf.write(render_dot(graph... | raise Exception("Received non-zero return code from grapviz\n\nError: {}".format(stderr.decode('utf-8'))) | conditional_block |
glnoise.js | (0.309016994374947451)) )
var x0 = v - i + dot(i, C.xxxx)
var i0 = vec4()
var isX = step( x0.yzw, x0.xxx )
var isYZ = step( x0.zww, x0.yyz )
i0.x = isX.x + isX.y + isX.z
i0.yzw = 1.0 - isX
i0.y += isYZ.x + isYZ.y
i0.zw += 1.0 - isYZ.xy
i0.z += isYZ.z
i0.w += 1.0 - isYZ.z
var i3 = clamp( i0, 0.0, 1... | var Pfz = Pf.z + vec3(1.0, 0.0, -1.0)
var p = permute3(Pi.x + vec3(-1.0, 0.0, 1.0))
var p1 = permute3(p + Pi.y - 1.0)
var p2 = permute3(p + Pi.y) | random_line_split | |
error.rs | extern crate backtrace;
extern crate libc;
use std::fmt;
use std::ops::Deref;
use std::io;
use std::string::FromUtf8Error;
use self::backtrace::Backtrace;
use self::backtrace::BacktraceFrame;
#[derive(Debug)]
pub struct RError<E> {
e: E,
bt: Option<Backtrace>,
}
pub fn is_enoent(e: &io::Error) -> bool {
... |
pub fn from(e: E) -> RError<E> {
let mut bt = Backtrace::new();
let mut i: usize = 0;
let mut chop: usize = 0;
for f in bt.frames() {
if let Some(sym) = f.symbols().first() {
if let Some(p) = sym.filename() {
if p.file_name().unwrap()... | {
RError {
e: e,
bt: Default::default(),
}
} | identifier_body |
error.rs | extern crate backtrace;
extern crate libc;
use std::fmt;
use std::ops::Deref;
use std::io;
use std::string::FromUtf8Error;
use self::backtrace::Backtrace;
use self::backtrace::BacktraceFrame;
#[derive(Debug)]
pub struct RError<E> {
e: E,
bt: Option<Backtrace>,
}
pub fn is_enoent(e: &io::Error) -> bool {
... | else {
return libc::EIO;
}
}
impl<E> RError<E> {
pub fn propagate(e: E) -> RError<E> {
RError {
e: e,
bt: Default::default(),
}
}
pub fn from(e: E) -> RError<E> {
let mut bt = Backtrace::new();
let mut i: usize = 0;
let mut chop... | {
return e.e.raw_os_error().unwrap();
} | conditional_block |
error.rs | extern crate backtrace;
extern crate libc;
use std::fmt;
use std::ops::Deref;
use std::io;
use std::string::FromUtf8Error;
use self::backtrace::Backtrace;
use self::backtrace::BacktraceFrame;
#[derive(Debug)]
pub struct RError<E> {
e: E,
bt: Option<Backtrace>,
}
pub fn is_enoent(e: &io::Error) -> bool {
... | <T>(e: io::Error) -> Result<T> {
return Err(RError::propagate(e));
}
pub fn errno(e: &RError<io::Error>) -> libc::c_int {
if RError::expected(e) {
return e.e.raw_os_error().unwrap();
} else {
return libc::EIO;
}
}
impl<E> RError<E> {
pub fn propagate(e: E) -> RError<E> {
R... | propagate | identifier_name |
error.rs | extern crate backtrace;
extern crate libc;
use std::fmt;
use std::ops::Deref;
use std::io;
use std::string::FromUtf8Error;
use self::backtrace::Backtrace;
use self::backtrace::BacktraceFrame; | pub struct RError<E> {
e: E,
bt: Option<Backtrace>,
}
pub fn is_enoent(e: &io::Error) -> bool {
return e.kind() == io::ErrorKind::NotFound;
}
pub fn try_enoent(e: io::Error) -> Result<bool> {
if is_enoent(&e) {
return Ok(true);
} else {
return Err(RError::from(e));
}
}
pub fn ... |
#[derive(Debug)] | random_line_split |
taskReducer.js | import Immutable from "immutable"
import moment from "moment"
import {airtableDateFormat} from "api/airtableAPI"
const initialState = Immutable.Map({
list: Immutable.List(),
tasks: Immutable.List(),
habits: Immutable.List(),
bucketlist: Immutable.List(),
tags: Immutable.List(),
contexts: Immutable.List(),
... | .set('formId', action.id)
case "RESET_FORM":
return state
.set('form', initialState.get('form'))
.set('formId', null)
case "CHANGE_FILTER":
return state.setIn(['filters', action.field], action.newVal)
case "REMOVE_FILTER":
return state.setIn(['filters', action.field... | {
switch (action.type) {
case "REPLACE_TASKS":
let tasks = action.tasks.filter(task => !task.fields.Type || task.fields.Type == "task")
let habits = action.tasks.filter(task => task.fields.Type == "habit")
let bucketlist = action.tasks.filter(task => task.fields.Type == "bucketlist")
retur... | identifier_body |
taskReducer.js | import Immutable from "immutable"
import moment from "moment"
import {airtableDateFormat} from "api/airtableAPI"
const initialState = Immutable.Map({
list: Immutable.List(),
tasks: Immutable.List(),
habits: Immutable.List(),
bucketlist: Immutable.List(),
tags: Immutable.List(),
contexts: Immutable.List(),
... | let habits = action.tasks.filter(task => task.fields.Type == "habit")
let bucketlist = action.tasks.filter(task => task.fields.Type == "bucketlist")
return state
.set('list', action.tasks)
.set('tasks', tasks)
.set('habits', habits)
.set('bucketlist', bucketlist)
ca... | random_line_split | |
taskReducer.js | import Immutable from "immutable"
import moment from "moment"
import {airtableDateFormat} from "api/airtableAPI"
const initialState = Immutable.Map({
list: Immutable.List(),
tasks: Immutable.List(),
habits: Immutable.List(),
bucketlist: Immutable.List(),
tags: Immutable.List(),
contexts: Immutable.List(),
... | (state = initialState, action) {
switch (action.type) {
case "REPLACE_TASKS":
let tasks = action.tasks.filter(task => !task.fields.Type || task.fields.Type == "task")
let habits = action.tasks.filter(task => task.fields.Type == "habit")
let bucketlist = action.tasks.filter(task => task.fields.Ty... | tasks | identifier_name |
main.rs | use std::net::SocketAddr;
use std::sync::Arc;
use hyper::server::Server;
use hyper::service::{make_service_fn, service_fn};
use log::{error, info};
use crate::runtime;
use crate::server::github_handler::GithubHandlerState;
use crate::server::octobot_service::OctobotService;
use crate::server::sessions::Sessions;
use ... | Ok(s) => Arc::new(s),
Err(e) => panic!("Error initiating github session: {}", e),
};
}
let jira: Option<Arc<dyn jira::api::Session>>;
if let Some(ref jira_config) = config.jira {
jira = match JiraSession::new(jira_config, Some(metrics.clone())).await {
Ok... | .await
{ | random_line_split |
main.rs | use std::net::SocketAddr;
use std::sync::Arc;
use hyper::server::Server;
use hyper::service::{make_service_fn, service_fn};
use log::{error, info};
use crate::runtime;
use crate::server::github_handler::GithubHandlerState;
use crate::server::octobot_service::OctobotService;
use crate::server::sessions::Sessions;
use ... | (config: Config) {
let num_http_threads = config.main.num_http_threads.unwrap_or(20);
let metrics = metrics::Metrics::new();
runtime::run(num_http_threads, metrics.clone(), async move {
run_server(config, metrics).await
});
}
async fn run_server(config: Config, metrics: Arc<metrics::Metrics>) ... | start | identifier_name |
main.rs | use std::net::SocketAddr;
use std::sync::Arc;
use hyper::server::Server;
use hyper::service::{make_service_fn, service_fn};
use log::{error, info};
use crate::runtime;
use crate::server::github_handler::GithubHandlerState;
use crate::server::octobot_service::OctobotService;
use crate::server::sessions::Sessions;
use ... | config
.github
.api_token
.as_ref()
.expect("expected an api_token"),
Some(metrics.clone()),
)
.await
{
Ok(s) => Arc::new(s),
Err(e) => panic!("Error initiating github session: {}", e)... | {
let config = Arc::new(config);
let github: Arc<dyn github::api::GithubSessionFactory>;
if config.github.app_id.is_some() {
github = match github::api::GithubApp::new(
&config.github.host,
config.github.app_id.expect("expected an app_id"),
&config.github.app_ke... | identifier_body |
dashboard-controller.js | function DashboardController($scope, $state, $stateParams, dashboardFactory) {
var dc = this;
dc.playerStats = {};
dc.itemForAuction = {};
dc.auctionStarted = false;
// Called on page load to retrieve player data
dashboardFactory.getData(dashboardFactory.getName()).then(function(response) {
... |
}
module.exports = DashboardController;
| {
playerData.coins = playerData.coins - newData.value;
angular.forEach(playerData.inventoryItems, function(item) {
if (item.name === newData.itemName) {
item.quantity = item.quantity - newData.qty;
}
});
} | identifier_body |
dashboard-controller.js | function | ($scope, $state, $stateParams, dashboardFactory) {
var dc = this;
dc.playerStats = {};
dc.itemForAuction = {};
dc.auctionStarted = false;
// Called on page load to retrieve player data
dashboardFactory.getData(dashboardFactory.getName()).then(function(response) {
dc.playerStats = respo... | DashboardController | identifier_name |
dashboard-controller.js | function DashboardController($scope, $state, $stateParams, dashboardFactory) {
var dc = this;
dc.playerStats = {};
dc.itemForAuction = {};
dc.auctionStarted = false;
// Called on page load to retrieve player data
dashboardFactory.getData(dashboardFactory.getName()).then(function(response) {
... |
});
}
}
module.exports = DashboardController;
| {
item.quantity = item.quantity - newData.qty;
} | conditional_block |
dashboard-controller.js | function DashboardController($scope, $state, $stateParams, dashboardFactory) {
var dc = this;
dc.playerStats = {};
dc.itemForAuction = {};
dc.auctionStarted = false;
// Called on page load to retrieve player data
dashboardFactory.getData(dashboardFactory.getName()).then(function(response) {
... |
});
});
// Clear events
$scope.$on('$destroy', function() {
unbindLogout();
unbindStart();
unbindClose();
});
/**
* @desc function that updates player dashboard in real-time
* @param {Object} playerData - logged in player's data
* @param {Object} newD... | });
} | random_line_split |
Main.js | Ext.define('TrackApp.view.main.Main', {
extend: 'Ext.panel.Panel',
requires: [
'Ext.resizer.Splitter'
],
xtype: 'app-main',
controller: 'main',
viewModel: {
type: 'main'
},
title: 'Oslo-Bergen til fots',
header: {
titlePosition: 0,
defaults: {
xtype: 'button',
toggleGroup: 'men... | reference: 'positions',
xtype: 'positions'
}]
}]
}); | items: [{
reference: 'profile',
xtype: 'profile'
},{ | random_line_split |
local_ptr.rs | /// pointer is returned.
pub struct Borrowed<T> {
val: *(),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: ~T = cast::transmute(... |
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline(never)] // see comments above
pub unsafe fn unsafe_take<T>() -> ~T {
cast::transmute(RT_TLS_P... | {
let ptr: ~T = cast::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = cast::transmute(0);
Some(ptr)
} | conditional_block |
local_ptr.rs | /// pointer is returned.
pub struct Borrowed<T> {
val: *(),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: ~T = cast::transmute(... | <T>() -> ~T {
cast::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
#[inline(never)] // see comments above
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
#[inline(never)] // see comments above
pub uns... | unsafe_take | identifier_name |
local_ptr.rs | null borrowed object!");
}
let val: ~T = cast::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Deref<T> for Borrowed<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*(self.val as *T) }
}
}
impl<T> DerefMut<T> for Borr... | {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: ~T = cast::transmute(void_ptr);
tls::set(key, ptr::mut_null());
... | identifier_body | |
local_ptr.rs | >(&'a self) -> &'a T {
unsafe { &*(self.val as *T) }
}
}
impl<T> DerefMut<T> for Borrowed<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *(self.val as *mut T) }
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not avai... | pub unsafe fn unsafe_take<T>() -> ~T { | random_line_split | |
__init__.py | import os
from twisted.trial import unittest
from scrapy.contrib.djangoitem import DjangoItem, Field
from scrapy import optional_features
os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings'
if 'django' in optional_features:
from .models import Person, IdentifiedPerson
class BasePe... | self.assertEqual(person.name, 'Robot') | person = i.save(commit=False) | random_line_split |
__init__.py | import os
from twisted.trial import unittest
from scrapy.contrib.djangoitem import DjangoItem, Field
from scrapy import optional_features
os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings'
if 'django' in optional_features:
from .models import Person, IdentifiedPerson
class BasePe... |
def test_base(self):
i = BasePersonItem()
self.assertEqual(i.fields.keys(), ['age', 'name'])
def test_new_fields(self):
i = NewFieldPersonItem()
self.assertEqual(i.fields.keys(), ['age', 'other', 'name'])
def test_override_field(self):
i = OverrideFieldPersonItem(... | raise unittest.SkipTest("Django is not available") | conditional_block |
__init__.py | import os
from twisted.trial import unittest
from scrapy.contrib.djangoitem import DjangoItem, Field
from scrapy import optional_features
os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings'
if 'django' in optional_features:
from .models import Person, IdentifiedPerson
class BasePe... | (BasePersonItem):
age = Field()
class IdentifiedPersonItem(DjangoItem):
django_model = IdentifiedPerson
class DjangoItemTest(unittest.TestCase):
def setUp(self):
if 'django' not in optional_features:
raise unittest.SkipTest("Django is not available")
def test_base(se... | OverrideFieldPersonItem | identifier_name |
__init__.py | import os
from twisted.trial import unittest
from scrapy.contrib.djangoitem import DjangoItem, Field
from scrapy import optional_features
os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings'
if 'django' in optional_features:
from .models import Person, IdentifiedPerson
class BasePe... |
def test_override_field(self):
i = OverrideFieldPersonItem()
self.assertEqual(i.fields.keys(), ['age', 'name'])
def test_custom_primary_key_field(self):
"""
Test that if a custom primary key exists, it is
in the field list.
"""
i = IdentifiedPersonItem(... | i = NewFieldPersonItem()
self.assertEqual(i.fields.keys(), ['age', 'other', 'name']) | identifier_body |
mod.rs | mod arrays;
mod strings;
use self::strings::unescape;
pub use self::{arrays::ArrayMethod, strings::StringMethod};
use super::Expander;
use crate::{parser::lexers::ArgumentSplitter, types};
use thiserror::Error;
#[derive(Debug, PartialEq, Clone)]
pub enum Pattern<'a> {
StringPattern(&'a str),
Whitespace,
}
#... | ///
/// Ex: `$join($scalar)` (can't join a scala) or `$unknown(@variable)` (unknown method)
#[derive(Debug, Clone, Error)]
pub enum MethodError {
/// Unknown array method
#[error("'{0}' is an unknown array method")]
InvalidArrayMethod(String),
/// Unknown scalar method
#[error("'{0}' is an unknown s... | expand: &'b mut E,
}
/// Error during method expansion | random_line_split |
mod.rs | mod arrays;
mod strings;
use self::strings::unescape;
pub use self::{arrays::ArrayMethod, strings::StringMethod};
use super::Expander;
use crate::{parser::lexers::ArgumentSplitter, types};
use thiserror::Error;
#[derive(Debug, PartialEq, Clone)]
pub enum Pattern<'a> {
StringPattern(&'a str),
Whitespace,
}
#... |
}
| {
MethodArgs { args, expand }
} | identifier_body |
mod.rs | mod arrays;
mod strings;
use self::strings::unescape;
pub use self::{arrays::ArrayMethod, strings::StringMethod};
use super::Expander;
use crate::{parser::lexers::ArgumentSplitter, types};
use thiserror::Error;
#[derive(Debug, PartialEq, Clone)]
pub enum Pattern<'a> {
StringPattern(&'a str),
Whitespace,
}
#... | (self, pattern: &str) -> super::Result<types::Str, E::Error> {
Ok(unescape(&self.expand.expand_string(self.args)?.join(pattern)))
}
pub fn new(args: &'a str, expand: &'b mut E) -> MethodArgs<'a, 'b, E> {
MethodArgs { args, expand }
}
}
| join | identifier_name |
bitcast_op_test.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def testSmaller(self):
x = np.random.rand(3, 2)
datatype = tf.int8
shape = [3, 2, 8]
self._testBitcast(x, datatype, shape)
def testLarger(self):
x = np.arange(16, dtype=np.int8).reshape([4, 4])
datatype = tf.int32
shape = [4]
self._testBitcast(x, datatype, shape)
def testSameDt... | with self.test_session():
tf_ans = tf.bitcast(x, datatype)
out = tf_ans.eval()
buff_after = memoryview(out).tobytes()
buff_before = memoryview(x).tobytes()
self.assertEqual(buff_before, buff_after)
self.assertEqual(tf_ans.get_shape(), shape)
self.assertEqual(tf_ans.dtype, datat... | identifier_body |
bitcast_op_test.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
class BitcastTest(tf.test.TestCase):
def _testBitcast(self, x, datatype, shape):
with self.test_session():
tf_ans = tf.bitcast(x, datatype)
out = tf_ans.eval()
buff_after = memoryview(out).tobytes()
buff_before = memoryview(x).tobytes()
self.assertEqual(buff_before, buff_after)
... |
import numpy as np
import tensorflow as tf
| random_line_split |
bitcast_op_test.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | tf.test.main() | conditional_block | |
bitcast_op_test.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (self, x, datatype, shape):
with self.test_session():
tf_ans = tf.bitcast(x, datatype)
out = tf_ans.eval()
buff_after = memoryview(out).tobytes()
buff_before = memoryview(x).tobytes()
self.assertEqual(buff_before, buff_after)
self.assertEqual(tf_ans.get_shape(), shape)
self... | _testBitcast | identifier_name |
main.rs | #![allow(unused_variables)]
fn | () {
// Rust let bindings are immutable by default.
let z = 3;
// This will raise a compiler error:
// z += 2; //~ ERROR cannot assign twice to immutable variable `z`
// You must declare a variable mutable explicitly:
let mut x = 3;
// Similarly, references are immutable by default e.g.
... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.