file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
typedParser.ts | import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
export class | <V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstructor<T>
parser: IParser<any>
constructor(ctor: TypedConstructor<T>, parser: IParser<any>) {
this.ctor = ctor
this.parser = parser
}
parse(input: string): ParseResult<T> {
const result = this.parser.parse(input)
if (result i... | TypedParser | identifier_name |
typedParser.ts | import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
export class TypedParser<V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstruct... |
}
}
export function typed<V, T extends TypedValue>(ctor: TypedConstructor<T>, parser: IParser<any>) {
return new TypedParser<V, T>(ctor, parser)
}
| {
return result
} | conditional_block |
typedParser.ts | import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
| export class TypedParser<V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstructor<T>
parser: IParser<any>
constructor(ctor: TypedConstructor<T>, parser: IParser<any>) {
this.ctor = ctor
this.parser = parser
}
parse(input: string): ParseResult<T> {
const result = this.parser.parse(... | export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
| random_line_split |
completions_dev.py | import sys
import sublime_plugin
if sys.version_info < (3,):
from sublime_lib.path import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Co... | (sublime_plugin.WindowCommand):
def run(self):
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.set_syntax_file(COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
| NewCompletionsCommand | identifier_name |
completions_dev.py | import sys
import sublime_plugin
if sys.version_info < (3,):
from sublime_lib.path import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Co... | v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.set_syntax_file(COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User')) | identifier_body | |
completions_dev.py | import sys
import sublime_plugin
if sys.version_info < (3,):
|
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL = """{
"scope": "source.${1:off}",
"completions": [
... | from sublime_lib.path import root_at_packages, get_package_name | conditional_block |
completions_dev.py | from sublime_lib.path import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL... | import sys
import sublime_plugin
if sys.version_info < (3,):
| random_line_split | |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflect... |
}
| {
self.stylerule.read().to_css_string().into()
} | identifier_body |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public |
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sy... | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflect... | (&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString {
self.stylerule.read().to_css_string().into()
}
}
| ty | identifier_name |
completionListInvalidMemberNames3.ts | /// <reference path='fourslash.ts' />
// @allowjs: true
// @Filename: test.js
////interface Symbol {
//// /** Returns a string representation of an object. */
//// toString(): string;
//// /** Returns the primitive value of the specified object. */
//// valueOf(): Object;
////}
////interfac... | //// (description?: string | number): symbol;
//// /**
//// * Returns a Symbol object from the global symbol registry matching the given key if found.
//// * Otherwise, returns a new symbol with this key.
//// * @param key key to search for.
//// */
//// for(key: string): symbol;
... | //// * Returns a new unique Symbol value.
//// * @param description Description of the new Symbol object.
//// */
| random_line_split |
index.js | /** PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES
*
* EXAMPLE:
* const fn = promisify( (callback) => callback(null, "Hello world!") );
* fn((err, str) => console.log(str));
* fn().then((str) => console.log(str));
* //Both functions, will log 'Hello world!'
*
* Note: The function you pass, may have any arguments yo... | {
this["promisify"] = module.exports;
} | conditional_block | |
index.js | /** PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES
*
* EXAMPLE:
* const fn = promisify( (callback) => callback(null, "Hello world!") );
* fn((err, str) => console.log(str));
* fn().then((str) => console.log(str));
* //Both functions, will log 'Hello world!'
*
* Note: The function you pass, may have any arguments yo... | if (typeof module === "undefined") module = {}; // Browserify this module
module.exports = function (methods, options) {
options = options || {};
var type = Object.prototype.toString.call(methods);
if (type === "[object Object]" || type === "[object Array]") {
var obj = options.replace ? methods :... | };
};
| random_line_split |
validations.ts | import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2; | glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Validation[];
next?: Validation;
loadError: boolean;
}
enum ActionType {
REFILL_CACHE = 'REFILL_VALIDATIONS_CACHE',
NEXT_VALIDATION = 'NEXT_VALIDATION',
}
interface RefillCacheAction extend... |
export namespace Validations {
export interface Validation { | random_line_split |
validations.ts | import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
export namespace Validations {
export interface Validation {
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Vali... |
} catch (err) {
if (err instanceof XMLHttpRequest) {
dispatch({ type: ActionType.REFILL_CACHE });
} else {
throw err;
}
}
},
vote: (isValid: boolean) => async (
dispatch: Dispatch<NewValidationAction | RefillCacheAction>,
getState: () => Stat... | {
const clip = await api.getRandomClip();
dispatch({
type: ActionType.REFILL_CACHE,
validation: {
glob: clip.glob,
sentence: decodeURIComponent(clip.text),
audioSrc: clip.sound,
},
});
await new Promise... | conditional_block |
validations.ts | import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
export namespace Validations {
export interface Validation {
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Vali... | (
state: State = {
cache: [],
next: null,
loadError: false,
},
action: Action
): State {
switch (action.type) {
case ActionType.REFILL_CACHE: {
const { validation } = action;
const cache = validation ? state.cache.concat(validation) : state.cache;
const ... | reducer | identifier_name |
validations.ts | import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
export namespace Validations {
export interface Validation {
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Vali... |
}
| {
switch (action.type) {
case ActionType.REFILL_CACHE: {
const { validation } = action;
const cache = validation ? state.cache.concat(validation) : state.cache;
const next = state.next || cache.shift();
return {
...state,
cache,
loadError: !next,
... | identifier_body |
message.rs | //! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
p... |
pub fn make_response(result: Option<Value>, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result, error: None, id }) }
}
pub fn version(&self) -> &str {
self.jsonrpc.as_str()
}
pub fn is_request(&self) -> bool {
matches!(sel... | {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result: None, error: Some(error), id }) }
} | identifier_body |
message.rs | //! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
p... |
pub fn is_response(&self) -> bool {
matches!(self.type_, Type::Response(_))
}
pub fn request(self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self... | random_line_split | |
message.rs | //! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
p... | (self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self.type_ {
Type::Response(resp) => Some(resp),
_ => None,
}
}
}
#[derive(Serial... | request | identifier_name |
bootstrap.v3.datetimepicker-tests.ts | import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
... | {
let undef: undefined;
let parser: BootstrapV3DatetimePicker.InputParser;
$("#picker").datetimepicker();
$("#picker").datetimepicker({
parseInputDate: inputParser
});
undef = dp.parseInputDate() as undefined;
parser = dp.parseInputDate() as BootstrapV3DatetimePicker.InputParser;
... | identifier_body | |
bootstrap.v3.datetimepicker-tests.ts | import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
... | $("#date-start-display").text($("#date-start").data("date"));
}
})
.on("dp.error", ev => {
console.log(`Error: ${ev.date.format("YYYY-MM-DD")}`);
})
.on("dp.update", ev => {
console.log(`Change: ${ev.change}, ${ev.viewDate.format("YYYY-... | } else {
$("#alert").hide();
startDate = ev.date; | random_line_split |
bootstrap.v3.datetimepicker-tests.ts | import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
... | (inputDate: string | Date | moment.Moment) {
const relativeDatePattern = /[0-9]+\s+(days ago)/;
if (moment.isMoment(inputDate) || inputDate instanceof Date) {
return moment(inputDate);
} else {
const relativeDate = inputDate.match(relativeDatePattern);
if (relativeDate !== null) {
... | inputParser | identifier_name |
bootstrap.v3.datetimepicker-tests.ts | import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
... |
}
function test_parseInputDate() {
let undef: undefined;
let parser: BootstrapV3DatetimePicker.InputParser;
$("#picker").datetimepicker();
$("#picker").datetimepicker({
parseInputDate: inputParser
});
undef = dp.parseInputDate() as undefined;
parser = dp.parseInputDate() as Boot... | {
const relativeDate = inputDate.match(relativeDatePattern);
if (relativeDate !== null) {
const subDays = +relativeDate[0].replace("days ago", "").trim();
return moment().subtract(subDays, "day");
} else {
return moment();
}
} | conditional_block |
app.py | from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
... | }
vals = []
for i in range(0, num):
vals.append(random.randint(1, size))
data = {
'response_type': 'ephemeral' if flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join([str(v)... | flag = match.group(3)
if flag is not None and flag not in HIDDEN:
return {
'response_type': 'ephemeral',
'text': 'ERROR: unrecognized modifier `%s`' % flag | random_line_split |
app.py | from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
... |
if __name__ == "__main__":
app.run(debug=True)
| try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify({
'response_type': 'ephemeral',
'text': USAGE
}) | identifier_body |
app.py | from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
... | ():
try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify({
'response_type': 'ephemeral',
'text': USAGE
})
if __name__ == "__ma... | roll | identifier_name |
app.py | from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
... |
vals = []
for i in range(0, num):
vals.append(random.randint(1, size))
data = {
'response_type': 'ephemeral' if flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join([str(v) for v in... | return {
'response_type': 'ephemeral',
'text': 'ERROR: unrecognized modifier `%s`' % flag
} | conditional_block |
Layout.js | // @flow
/* eslint-disable react/no-danger */
// $FlowMeteor
import { find, propEq } from "ramda";
import { Link } from "react-router";
import Split, {
Left,
Right,
} from "../../../components/@primitives/layout/split";
import Meta from "../../../components/shared/meta";
import AddToCart from "../../../components/... | <div className="constrain-copy soft-double@lap-and-up">
<div className="soft soft-double-bottom soft-double-top@lap-and-up">
<AddToCart accounts={[account]} donate />
</div>
</div>
</div>
</Left>
</div>
);
export default Layout; | <div dangerouslySetInnerHTML={{ __html: account.description }} />
</div>
</div>
<div className="background--light-secondary"> | random_line_split |
forms.py | from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, l... |
class FormDataGroupForm(forms.ModelForm):
"""Form for basic form group data"""
display_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_... | file = forms.FileField() | identifier_body |
forms.py | from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, l... | model = FormDataGroup
fields = ("display_name", "view_name") | FormDataGroup.objects.filter(view_name=view_name).count() > 0:
raise forms.ValidationError("Sorry, view name %s is already in use! Please pick a new one." % view_name)
return self.cleaned_data["view_name"]
class Meta: | random_line_split |
forms.py | from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, l... |
return self.cleaned_data["view_name"]
class Meta:
model = FormDataGroup
fields = ("display_name", "view_name")
| if FormDataGroup.objects.get(id=self.instance.id).view_name != view_name and \
FormDataGroup.objects.filter(view_name=view_name).count() > 0:
raise forms.ValidationError("Sorry, view name %s is already in use! Please pick a new one." % view_name) | conditional_block |
forms.py | from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class | (forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, label=u'Form Display Name')
class SubmitDataForm(forms.Form):
file = forms.FileField()
class FormDataGroupForm(forms.ModelForm):
"""Form for basic form group data"""
display_name = forms.CharField(wid... | RegisterXForm | identifier_name |
android.py | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class | (Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", ... | GCMError | identifier_name |
android.py | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send... |
return True
| raise GCMError(repr(body)) | conditional_block |
android.py | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send... | hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
ht... | random_line_split | |
android.py | # -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
|
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
... | pass | identifier_body |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> ! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
}
| oom | identifier_name |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
} | identifier_body | |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
/// Common out-of-memory routine
#[cold]
#[inline(never)]
#[unstable(feature = "oom", reason = "not a scrutinized interface")]
pub fn oom() -> ! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// ... | pub mod rc;
pub mod raw_vec; | random_line_split |
res_config.py | # -*- coding: utf-8 -*-
from openerp.osv import fields, osv
class AccountPaymentConfig(osv.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'module_payment_transfer': fields.boolean(
'Wire Transfer',
help='-This installs the module payment_transfer.'),
... | _defaults = {
'module_payment_transfer': True
} | 'module_payment_sips': fields.boolean(
'Sips',
help='-This installs the module payment_sips.'),
}
| random_line_split |
res_config.py | # -*- coding: utf-8 -*-
from openerp.osv import fields, osv
class | (osv.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'module_payment_transfer': fields.boolean(
'Wire Transfer',
help='-This installs the module payment_transfer.'),
'module_payment_paypal': fields.boolean(
'Paypal',
help='-This... | AccountPaymentConfig | identifier_name |
res_config.py | # -*- coding: utf-8 -*-
from openerp.osv import fields, osv
class AccountPaymentConfig(osv.TransientModel):
| _inherit = 'account.config.settings'
_columns = {
'module_payment_transfer': fields.boolean(
'Wire Transfer',
help='-This installs the module payment_transfer.'),
'module_payment_paypal': fields.boolean(
'Paypal',
help='-This installs the module payme... | identifier_body | |
lib.rs | #![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use ... | (direction: T) -> Self{
let (y, x) = direction.sin_cos();
Vector2(x, y)
}
/// Normalises the vector
pub fn normalise(self) -> Self{
self / self.length()
}
/// Returns the magnitude/length of the vector
pub fn length(self) -> T{
// This is apparently faster than us... | unit_vector | identifier_name |
lib.rs | #![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use ... | Vector2(self.0/rhs, self.1/rhs)
}
}
impl<T: Neg> Neg for Vector2<T>{
type Output = Vector2<T::Output>;
fn neg(self) -> Self::Output{
Vector2(-self.0, -self.1)
}
}
impl<T> Into<[T; 2]> for Vector2<T>{
#[inline]
fn into(self) -> [T; 2]{
[self.0, self.1]
}
}
impl<T: ... | random_line_split | |
lib.rs | #![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use ... |
/// Returns direction the vector is pointing
pub fn direction(self) -> T{
self.1.atan2(self.0)
}
/// Returns direction towards another vector
pub fn direction_to(self, other: Self) -> T{
(other-self).direction()
}
/// Returns the distance betweens two vectors
pub fn dist... | {
self.0.powi(2) + self.1.powi(2)
} | identifier_body |
mongodbUpgrade.js | // This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are ... | process.exit(1);
}
// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => {
if(err){
console.log('Couldn\'t connect to the Mongo database');
console.log(err);
process.exit(1);
}
console.log('Connected to: ' + config.sett... |
// check for DB config
if(!config.settings.database.connection_string){
console.log('No MongoDB configured. Please see README.md for help'); | random_line_split |
mongodbUpgrade.js | // This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are ... |
});
});
});
};
| {
console.log('All users successfully inserted');
console.log('');
callback(null, 'All users successfully inserted');
} | conditional_block |
mongodbUpgrade.js | // This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are ... | ;
function insertUsers(db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
proce... | {
const collection = db.collection('kb');
console.log(path.join(__dirname, 'kb.db'));
ndb = new Nedb(path.join(__dirname, 'kb.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
... | identifier_body |
mongodbUpgrade.js | // This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are ... | (db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
... | insertUsers | identifier_name |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header()... | <T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T,
len: u32,
pos: u32)
... | chain | identifier_name |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header()... | {
let mut chained = chain_nf(parent);
for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
... | identifier_body | |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header()... | .transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} else {
chained
}
} | for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>() | random_line_split |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header()... | else {
chained
}
}
| {
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} | conditional_block |
toc.rs | // Copyright 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-MIT or ... | }
/// Collapse the chain until the first heading more important than
/// `level` (i.e., lower level)
///
/// Example:
///
/// ```text
/// ## A
/// # B
/// # C
/// ## D
/// ## E
/// ### F
/// #### G
/// ### H
/// ```
///
/// If we are considering H... | random_line_split | |
toc.rs | // Copyright 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-MIT or ... | (&mut self, level: u32) {
let mut this = None;
loop {
match self.chain.pop() {
Some(mut next) => {
this.map(|e| next.children.entries.push(e));
if next.level < level {
// this is the parent we want, so return it ... | fold_until | identifier_name |
customizer-preview.js | /**
* The Customizer-specific functionality of the plugin.
* Handles the selective refresh logic for widgets in the Customizer.
*
* @since 1.1.5
* @author Weston Ruter <weston@xwp.co>
*/
( function( $ ) {
if ( 'undefined' === typeof wp || ! wp.customize || ! wp.customize.selectiveRefresh || ! wp.customize.wid... |
// Check the value of the attribute after partial content has been rendered.
wp.customize.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
// Abort if the partial is not for a widget.
if ( ! placement.partial.extended( wp.customize.widgetsPreview.WidgetPartial ) ) {
return;
}
... | {
return;
} | conditional_block |
pilha.py | import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
e... |
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
pilha.empilhar('A')
self.assertFalse(pilha.v... | if (self.lista):
return self.lista.pop(-1)
else:
raise PilhaVaziaErro | identifier_body |
pilha.py | import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
e... | pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())... | self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha() | random_line_split |
pilha.py | import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
e... | letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada) | conditional_block | |
pilha.py | import unittest
class | (Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
except IndexError:
raise P... | PilhaVaziaErro | identifier_name |
manifest.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | : &str, n: usize) -> Result<()> {
if !s.chars().take(n).all(|c| c == ' ') {
return Err(format!("leading {:?} chars aren't all spaces: {:?}", n, s).into())
}
Ok(())
}
fn extract_block(s: &str) -> Result<String> {
/*
On every line:
- update nesting lev... | leading_spaces(s | identifier_name |
manifest.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | fn extract_block(s: &str) -> Result<String> {
/*
On every line:
- update nesting level and detect end-of-comment
- if margin is None:
- if there appears to be a margin, set margin.
- strip off margin marker
- update the leading space counter
- str... | if !s.chars().take(n).all(|c| c == ' ') {
return Err(format!("leading {:?} chars aren't all spaces: {:?}", n, s).into())
}
Ok(())
}
| identifier_body |
manifest.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | /**
Returns a slice of the input string with the leading hashbang, if there is one, omitted.
*/
fn strip_hashbang(s: &str) -> &str {
match RE_HASHBANG.find(s) {
Some((_, end)) => &s[end..],
None => s
}
}
#[test]
fn test_strip_hashbang() {
assert_eq!(strip_hashbang("\
#!/usr/bin/env run-carg... | );
}
| random_line_split |
application.rs | //! This module contains the base elements of an OrbTk application (Application, WindowBuilder and Window).
use std::sync::mpsc;
use dces::prelude::Entity;
use crate::{
core::{application::WindowAdapter, localization::*, *},
shell::{Shell, ShellRequest},
};
/// The `Application` represents the entry point o... |
/// Create a new application with the given name.
pub fn from_name(name: impl Into<Box<str>>) -> Self {
let (sender, receiver) = mpsc::channel();
Application {
request_sender: sender,
name: name.into(),
shell: Shell::new(receiver),
theme: Rc::ne... | {
self.localization = Some(Rc::new(RefCell::new(Box::new(localization))));
self
} | identifier_body |
application.rs | //! This module contains the base elements of an OrbTk application (Application, WindowBuilder and Window).
use std::sync::mpsc;
use dces::prelude::Entity;
use crate::{
core::{application::WindowAdapter, localization::*, *},
shell::{Shell, ShellRequest},
};
/// The `Application` represents the entry point o... | localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
}
impl Default for Application {
fn default() -> Self {
Application::from_name("orbtk_application")
}
}
impl Application {
/// Creates a new application.
pub fn new() -> Self {
Self::default()
}
/// Sets the default... | random_line_split | |
application.rs | //! This module contains the base elements of an OrbTk application (Application, WindowBuilder and Window).
use std::sync::mpsc;
use dces::prelude::Entity;
use crate::{
core::{application::WindowAdapter, localization::*, *},
shell::{Shell, ShellRequest},
};
/// The `Application` represents the entry point o... | (mut self) {
self.shell.run();
}
}
| run | identifier_name |
SineWavePointOptimizer.py | from neurotune.controllers import SineWaveController
import sys
from neurotune import evaluators
from neurotune import optimizers
from neurotune import utils
if __name__ == "__main__":
showPlots = not ("-nogui" in sys.argv)
verbose = not ("-silent" in sys.argv)
sim_vars = {"amp": 65, "period": 250, "of... | utils.plot_generation_evolution(sim_vars.keys(), sim_vars) | conditional_block | |
SineWavePointOptimizer.py | from neurotune.controllers import SineWaveController
import sys
from neurotune import evaluators
from neurotune import optimizers
from neurotune import utils
if __name__ == "__main__":
showPlots = not ("-nogui" in sys.argv)
verbose = not ("-silent" in sys.argv)
sim_vars = {"amp": 65, "period": 250, "of... | population_size = 20
max_evaluations = 300
num_selected = 10
num_offspring = 5
mutation_rate = 0.5
num_elites = 1
# make an optimizer
my_optimizer = optimizers.CustomOptimizerA(
max_constraints,
min_constraints,
my_evaluator,
population_size=population_si... | )
| random_line_split |
profile-editor.component.1.ts | // #docplaster
// #docregion formgroup, nested-formgroup
import { Component } from '@angular/core';
// #docregion imports
import { FormGroup, FormControl } from '@angular/forms';
// #enddocregion imports
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./p... | () {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street'
}
});
}
// #enddocregion patch-value
// #docregion formgroup, nested-formgroup
}
// #enddocregion formgroup
| updateProfile | identifier_name |
profile-editor.component.1.ts | // #docplaster
// #docregion formgroup, nested-formgroup
import { Component } from '@angular/core';
// #docregion imports
import { FormGroup, FormControl } from '@angular/forms';
// #enddocregion imports | templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// #docregion formgroup-compare
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
// #enddocregion formgroup
address: new Fo... |
@Component({
selector: 'app-profile-editor', | random_line_split |
np.common.js | (function () {
'use strict';
var module = angular.module('np.common', []);
module.factory('np.common.requestFactory', [
'$log', '$q', '$http',
function (console, Q, http) {
return function (config) {
return function (method, path, data, params) {
... |
//if (config.authorization) {
// req.headers.Authorization = 'Bearer ' + SHA1(key + secret + nonce) + nonce
//}
return http(req).then(function (res) {
console.log('***request ', req.method, req.url, 'ok:', res... | {
req.headers['Content-Type'] = 'application/json;charset=utf8';
req.data = data;
req.params = params;
} | conditional_block |
np.common.js | (function () {
'use strict';
var module = angular.module('np.common', []);
module.factory('np.common.requestFactory', [
'$log', '$q', '$http', | method: method,
url: config.endpoint + path,
headers: {Accept: 'application/json'}
//withCredentials: true
};
if (method == 'GET' || method == 'DELETE') {
req.... | function (console, Q, http) {
return function (config) {
return function (method, path, data, params) {
var req = { | random_line_split |
directory.d.ts | /**
* TypeScript definitions for objects returned by the Application Directory.
*
* These structures are defined by the App-Directory FDC3 working group. The definitions here are based on the 1.0.0
* specification which can be found [here](https://fdc3.finos.org/appd-spec).
*
* @module Directory
*/
/**
* Type a... | displayName?: string | undefined;
/**
* The context types that this intent supports. A context type is a namespaced name;
* examples are given [here](https://fdc3.finos.org/docs/1.0/context-spec).
*/
contexts?: string[] | undefined;
/**
* Custom configuration for the intent. Currentl... | */ | random_line_split |
run.py | import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
... |
args[name] = value
script = ['{0}(**{1})'.format(cab['binary'], args)]
def log2term(result):
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. ... | continue | conditional_block |
run.py | import os
import sys | import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = {}
for... | import drivecasa
import logging
import shlex
import shutil
import subprocess | random_line_split |
run.py | import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
... |
try:
result = casa.run_script(script, raise_on_severe=False)
log2term(result)
finally:
for item in junk:
for dest in [OUTPUT, MSDIR]: # these are the only writable volumes in the container
items = glob.glob("{dest}/{item}".format(**locals()))
for f in items:
... | if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See error message above')
sys.stdout.write('WARNING:: SEVERE messages from CASA run') | identifier_body |
run.py | import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
... | (result):
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See error message above')
sys.stdout.write('WARNING:: SEVERE messages from CASA run'... | log2term | identifier_name |
index.js | var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.... |
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {... | {
sendPOST(hc, '/', callback);
} | identifier_body |
index.js | var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.... | (hc, callback) {
sendPOST(hc, '/', callback);
}
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncodin... | sendHealthcheck | identifier_name |
index.js | var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.... |
else {
var json = JSON.parse(data);
logger.debug('Got response: ' + data);
var newInterval = json.Interval * 1000;
if (newInterval != timeout) {
logger.debug('Changing d... | {
logger.error(err);
} | conditional_block |
index.js | var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.... | healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
if (err) throw err;
logger.debug('Healthcheck: ' + JSON.stringify(res));
logger.debug('Sending data to API...');
sendHealthcheck(res, function (err, data) {
... | var machineContainer = JSON.parse(res);
(function gatherHealthCheck(timeout) {
logger.debug('Getting healthcheck...')
| random_line_split |
mobile_v2_message.js | /**
* zepto插件:向左滑动删除动效
* 使用方法:$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
* 参数:itemDelete 删除按钮的样式名
*/
(function($) {
$.fn.touchWipe = function(option) {
var isMove = 0;
var defaults = {
itemDelete: '.item-delete', //删除元素
};
var isMoveAdd = function(){
isMove += ... | return isMove
}
/* var num = abc();
if(num>0){
var zero = function(){
isMoveZero();
}
zero();
}else{
} */
if (objX > -delWidth / 2) {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + 0 + "px)";... | //event.preventDefault();
var obj = this;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
var abc = function(){ | random_line_split |
mobile_v2_message.js | /**
* zepto插件:向左滑动删除动效
* 使用方法:$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
* 参数:itemDelete 删除按钮的样式名
*/
(function($) {
$.fn.touchWipe = function(option) {
var isMove = 0;
var defaults = {
itemDelete: '.item-delete', //删除元素
};
var isMoveAdd = function(){
isMove +=... | );
$('.content-detail').hide();
$('.detail').hide();
})
$('.list-li').on('click',function(event) {
var content = $(this).attr('_val');
$('.content-detail').html(content);
$('.content-detail').show();
$('.detail').show();
//alert()
})
$('.item-delete').on('click'... | 31:8090",
host1 = "localhost:4567";
$loading.style.display = "block";
$.ajax({
type: "DELETE",
url: "http://" + host + "/mobile/v2/message",
data: {id: rawID},
success: function(response, status, xhr) {
$('.'+id).remove();
$loading.style.display = ... | identifier_body |
mobile_v2_message.js | /**
* zepto插件:向左滑动删除动效
* 使用方法:$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
* 参数:itemDelete 删除按钮的样式名
*/
(function($) {
$.fn.touchWipe = function(option) {
var isMove = 0;
var defaults = {
itemDelete: '.item-delete', //删除元素
};
var isMoveAdd = function(){
isMove +=... | .91.131:8090",
host1 = "localhost:4567";
$loading.style.display = "block";
$.ajax({
type: "DELETE",
url: "http://" + host + "/mobile/v2/message",
data: {id: rawID},
success: function(response, status, xhr) {
$('.'+id).remove();
$loading.style.displ... | ost = "123.56 | identifier_name |
modal.component.ts | import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ModalService } from 'service/modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.co... | state('in', style({ 'background-color': 'rgba(30, 30, 30, 0.4)' })),
transition('void => *', [
style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }), animate(200)
]),
transition('* => void', [
animate(200, style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }))
])
]),
... | trigger('bgInOut', [ | random_line_split |
modal.component.ts | import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ModalService } from 'service/modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.co... | {
@ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;
constructor(
public modalService: ModalService) { }
clickBackground(event: MouseEvent) {
if (event.target === event.currentTarget) this.resolve();
}
resolve() {
this.modalService.resolve(null);
}
... | ModalComponent | identifier_name |
modal.component.ts | import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ModalService } from 'service/modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.co... |
clickBackground(event: MouseEvent) {
if (event.target === event.currentTarget) this.resolve();
}
resolve() {
this.modalService.resolve(null);
}
reject() {
this.modalService.reject();
}
}
| { } | identifier_body |
DsReplicaObjMetaData2Ctr.py | # encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def | (self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
array = property(lambda self: object(), lam... | __init__ | identifier_name |
DsReplicaObjMetaData2Ctr.py | # encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc |
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, ... | import talloc as __talloc | random_line_split |
DsReplicaObjMetaData2Ctr.py | # encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def __init__(self, *args, **kwar... |
array = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
enumeration_context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
| """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass | identifier_body |
main.rs |
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last... |
fn has_two_doubles(&self) -> bool {
let mut double_count = 0;
let mut pos = 0;
while pos < (self.len() - 1) {
if self[pos] == self[pos + 1] {
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;... | {
let i = ('i' as u8) - ('a' as u8);
let o = ('o' as u8) - ('a' as u8);
let l = ('l' as u8) - ('a' as u8);
!(self.contains(&i) || self.contains(&o) || self.contains(&l))
} | identifier_body |
main.rs |
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last... | (&self) -> bool {
let mut double_count = 0;
let mut pos = 0;
while pos < (self.len() - 1) {
if self[pos] == self[pos + 1] {
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;
}
... | has_two_doubles | identifier_name |
main.rs |
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last... |
pos += 1;
}
false
}
}
fn main() {
let mut a = args();
a.next(); // The first argument is the binary name/path
let start = a.next().unwrap(); // The puzzle input
let mut char_to_num = HashMap::new();
let mut num_to_char = HashMap::new();
for i in 0..26 {... | {
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;
}
} | conditional_block |
main.rs | use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last_... | }
if !passwd_vec.no_forbidden_chars() {
continue;
}
if !passwd_vec.has_two_doubles() {
continue;
}
break;
}
let readable_passwd = passwd_vec.iter().map(|ch_num| num_to_char[ch_num]).collect::<String>();
println!("The next password ... | random_line_split | |
main.rs | use std::thread;
use std::time::Duration;
use std::collections::HashMap;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
struct Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std... | (&mut self, arg: K) -> V {
let closure = &self.calculation;
let v = self.value
.entry(arg.clone())
.or_insert_with(|| (closure)(arg));
(*v).clone()
}
}
fn generate_workout(intensity: i32, random_number: i32) {
let mut expensive_result = Cacher::new(|num| {
... | value | identifier_name |
main.rs | use std::thread;
use std::time::Duration;
use std::collections::HashMap;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
struct Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std... |
}
fn generate_workout(intensity: i32, random_number: i32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
... | {
let closure = &self.calculation;
let v = self.value
.entry(arg.clone())
.or_insert_with(|| (closure)(arg));
(*v).clone()
} | identifier_body |
main.rs | use std::thread;
use std::time::Duration;
use std::collections::HashMap;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
struct Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std... | fn generate_workout(intensity: i32, random_number: i32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
... | }
}
| random_line_split |
controls.ts | // Copyright 2016 David Li, Michael Mauer, Andy Jiang
// This file is part of Tell Me to Survive.
// Tell Me to Survive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the Licens... |
text = "Over Memory Limit: " + overLimit;
}
buttons.push(m(<any> ("button" + cssClass), {
onclick: function() {
if (!args.valid) {
if (args.onruninvalid) {
args.onruninvalid();
... | {
overLimit = "main";
} | conditional_block |
controls.ts | // Copyright 2016 David Li, Michael Mauer, Andy Jiang
// This file is part of Tell Me to Survive.
// Tell Me to Survive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the Licens... | args.onreset();
}
},
}, "Reset"));
}
else if (!args.executing()) {
let cssClass = args.valid ? ".run" : ".runInvalid";
let text = args.valid ? "Run" : "Invalid Code";
if (args.memoryUsage !== null... | if (args.onreset) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.