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 |
|---|---|---|---|---|
configureStore.ts | declare const module: { hot: any };
import * as Raven from "raven-js";
const createRavenMiddleware = require("raven-for-redux");
import thunkMiddleware from "redux-thunk";
import * as createLogger from "redux-logger";
import { createStore, applyMiddleware } from "redux";
import rootReducer from "reducers";
import { ... | if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept("reducers", () => {
const nextRootReducer = require("reducers");
store.replaceReducer(nextRootReducer);
});
}
if (config.SCREEN === 'primary') {
store.subscribe(... | )(createStore);
export default function configureStore(initialState: any = {}) {
const store = createStoreWithMiddleware(rootReducer, initialState);
| random_line_split |
term.js | document.write('<div id="terminal" class="terminal-content"></div>');
var session = {};
// return a parameter value from the current URL
function getParam(sname) {
var params = location.search.substr(location.search.indexOf("?") + 1);
var sval = "";
params = params.split("&");
// split param and value... | (term) {
var snapUrl = null;
$.ajax({type: 'POST', async: false, url: '/snap', data: 'id=' + session.clientId})
.done(function (data) {
snapUrl = getBaseURL() + '?snap=' + data.snap;
}).fail(function (xhr, textStatus, errorThrown) {
restartSession(term)
});
return sn... | makeSnap | identifier_name |
term.js | document.write('<div id="terminal" class="terminal-content"></div>');
var session = {};
// return a parameter value from the current URL
function getParam(sname) {
var params = location.search.substr(location.search.indexOf("?") + 1);
var sval = "";
params = params.split("&");
// split param and value... |
function handleTerminalMessage(log, term) {
if (log.type != "CONTROL") {
var style = log.type == "ERROR" ? "terminal-message-error" : "terminal-message-success";
term.echo(log.message, messageStyle(style))
return log.type == "ERROR";
}
return false;
}
$(document).ready(function (... | {
if (log.type == "CONTROL") {
switch (log.message) {
case "CLEAR_SCREEN":
term.clear();
term.echo(session.welcomeMessage);
term.echo(' ');
break;
}
return true;
}
return false;
} | identifier_body |
term.js | document.write('<div id="terminal" class="terminal-content"></div>');
var session = {};
// return a parameter value from the current URL
function getParam(sname) {
var params = location.search.substr(location.search.indexOf("?") + 1);
var sval = "";
params = params.split("&");
// split param and value... | var completionResult = [];
$.ajax({
type: 'GET',
async: false,
cache: false,
url: '/completions',
data: {id: session.clientId, expression: term.get_command()}
... |
keydown: function (event, term) {
if (event.keyCode == 9) //Tab
{
| random_line_split |
term.js | document.write('<div id="terminal" class="terminal-content"></div>');
var session = {};
// return a parameter value from the current URL
function getParam(sname) {
var params = location.search.substr(location.search.indexOf("?") + 1);
var sval = "";
params = params.split("&");
// split param and value... |
if (!hadError) {
_gaq.push(["_trackEvent", "console", "evaluation", "success"]);
} else {
_gaq.push(["_trackEvent", "console", "evaluation", "error"]);
}
session.requesting = false;
... | {
var log = data.logs[i];
if (!handleTerminalCommand(log, term)) {
hadError = handleTerminalMessage(log, term) || hadError;
}
} | conditional_block |
gen_graph.py | ) ]
length = [ random.expovariate(1.0) for x in xrange(edges) ]
return { 'nodes': nodes,
'edges': edges,
'n1': n1,
'n2': n2,
'length': length }
def compute_subgraphs(n, p):
return [(x*(n/p) + min(x, n%p), ((x+1)*(n/p)-1) + min(x + 1, n%p)) for x in xrange... | ():
n1 = random.randint(0, nodes - 1)
if random.randint(1, 100) <= cluster_factor:
s = find_subgraph(n1, subgraphs)
n2 = random.randint(*s)
else:
n2 = random.randint(min(n1, nodes-1), nodes-1)
return (n1, n2)
n1, n2 = zip(*(make_edge() for x in xr... | make_edge | identifier_name |
gen_graph.py | (edges) ]
length = [ random.expovariate(1.0) for x in xrange(edges) ]
return { 'nodes': nodes,
'edges': edges,
'n1': n1,
'n2': n2,
'length': length }
def compute_subgraphs(n, p):
return [(x*(n/p) + min(x, n%p), ((x+1)*(n/p)-1) + min(x + 1, n%p)) for x in ... | if random.randint(0, 1) == 0:
s2 = subgraphs[((ix+1)%blocks) + iy*blocks]
else:
s2 = subgraphs[ix + ((iy+1)%blocks)*blocks]
n2 = random.randint(*s2)
return (n1, n2)
n1, n2 = zip(*(make_edge() for x in xrange(edges)))
length = [xlen + r... | if verbose: print('Creating clustered geometric graph with {} nodes and {} edges...'.format(nodes, edges))
blocks = int(math.sqrt(nsubgraphs))
assert blocks**2 == nsubgraphs
bounds = [((1.0*(i%blocks)/blocks, 1.0*(i%blocks + 1)/blocks),
(1.0*(i/blocks)/blocks, 1.0*(i/blocks + 1)/blocks))
... | identifier_body |
gen_graph.py | ) ]
length = [ random.expovariate(1.0) for x in xrange(edges) ]
return { 'nodes': nodes,
'edges': edges,
'n1': n1,
'n2': n2,
'length': length }
def compute_subgraphs(n, p):
return [(x*(n/p) + min(x, n%p), ((x+1)*(n/p)-1) + min(x + 1, n%p)) for x in xrange... |
mapping = dict(zip(sorted(xrange(g['edges']), key = lambda x: (g['n1'][x], g['n2'][x])), range(g['edges'])))
g['n1'] = [g['n1'][mapping[x]] for x in xrange(g['edges'])]
g['n2'] = [g['n2'][mapping[x]] for x in xrange(g['edges'])]
g['length'] = [g['length'][mapping[x]] for x in xrange(g['edges'])]
def s... | print('Sorting graph...') | conditional_block |
gen_graph.py | ) ]
length = [ random.expovariate(1.0) for x in xrange(edges) ]
return { 'nodes': nodes,
'edges': edges,
'n1': n1,
'n2': n2,
'length': length }
def compute_subgraphs(n, p):
return [(x*(n/p) + min(x, n%p), ((x+1)*(n/p)-1) + min(x + 1, n%p)) for x in xrange... |
return dist
def write_graph(g, problems, outdir, verbose):
if verbose: print('Writing graph...')
with open(os.path.join(outdir, 'edges.dat'), 'wb') as f:
array.array('i', g['n1']).tofile(f)
array.array('i', g['n2']).tofile(f)
array.array('f', g['length']).tofile(f)
with open(o... | # print('{:3d} {:3d} {:5.3f}'.format(i, n[0], n[1])) | random_line_split |
options.d.ts | import { Vue, CreateElement, CombinedVueInstance } from "./vue";
import { VNode, VNodeData, VNodeDirective } from "./vnode";
type Constructor = {
new (...args: any[]): any;
}
// we don't support infer props in async component
export type Component<Data=DefaultData<Vue>, Methods=DefaultMethods<Vue>, Computed=Default... |
/**
* This type should be used when an array of strings is used for a component's `props` value.
*/
export type ThisTypedComponentOptionsWithArrayProps<V extends Vue, Data, Methods, Computed, PropNames extends string> =
object &
ComponentOptions<V, Data | ((this: Readonly<Record<PropNames, any>> & V) => Data), M... | [K in keyof T]: (() => T[K]) | ComputedOptions<T[K]>
} | random_line_split |
webpack.d.ts | info?: boolean;
/** If set, export the bundle as library. output.library is the name. */
library?: boolean;
/**
* Which format to export the library:
* <ul>
* <li>"var" - Export by setting a variable: var Library = xxx (default)</li>
... | OccurenceOrderPlugin: optimize.OccurenceOrderPluginStatic;
/**
* Minimize all JavaScript output of chunks. Loaders are switched into minimizing mode. | random_line_split | |
tmtheme.js | .function": "entity.name.function",
"entity.name": "entity.name",
"entity.name.tag": "entity.name.tag",
"markup.heading": "markup.heading",
"markup.heading.1": "markup.heading.1",
"markup.heading.2": "markup.heading.2",
"markup.heading.3": "markup.heading.3",
"markup.heading.4": "markup.heading.4"... | {
console.log("Converting " + name);
var tmTheme = fs.readFileSync(__dirname + "/tmthemes/" + themes[name] + ".tmTheme", "utf8");
parseTheme(tmTheme, function(theme) {
var styles = extractStyles(theme);
styles.cssClass = "ace-" + hyphenate(name);
styles.uuid = theme.uuid;
va... | identifier_body | |
tmtheme.js | string.regexp",
"comment": "comment",
"comment.documentation": "comment.doc",
"comment.documentation.tag": "comment.doc.tag",
"variable": "variable",
"variable.language": "variable.language",
"variable.parameter": "variable.parameter",
"meta": "meta",
"meta.tag.sgml.doctype": "xml-pe",
"me... |
colors.gutterBg = colors.background
colors.gutterFg = mix(colors.foreground, colors.background, 0.5)
if (!colors.selected_word_highlight)
colors.selected_word_highlight = "border: 1px solid " + colors.selection + ";";
colors.isDark = (luma(colors.background) < 0.5) + "";
return... | {
var foldSource = colors["entity.name.function"] || colors.keyword;
if (foldSource) {
colors.fold = foldSource.match(/\:([^;]+)/)[1];
}
} | conditional_block |
tmtheme.js | string.regexp",
"comment": "comment",
"comment.documentation": "comment.doc",
"comment.documentation.tag": "comment.doc.tag",
"variable": "variable",
"variable.language": "variable.language",
"variable.parameter": "variable.parameter",
"meta": "meta",
"meta.tag.sgml.doctype": "xml-pe",
"me... | return str.replace(/([A-Z])/g, "-$1").replace(/_/g, "-").toLowerCase();
}
function quoteString(str) {
return '"' + str.replace(/\\/, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\\n") + '"';
}
var cssTemplate = fs.readFileSync(__dirname + "/templates/theme.css", "utf8");
var jsTemplate = fs.readFileSync(__di... | return replacements[m] || "";
});
}
function hyphenate(str) { | random_line_split |
tmtheme.js | (themeXml, callback) {
parseString(themeXml, function(_, theme) {
callback(theme[0])
});
}
var unsupportedScopes = { };
var supportedScopes = {
"keyword": "keyword",
"keyword.operator": "keyword.operator",
"keyword.other.unit": "keyword.other.unit",
"constant": "constant",
"constant.la... | parseTheme | identifier_name | |
compose_actions.js | _classes).hide();
$("#compose").css({visibility: "visible"});
// When changing this, edit the 42px in _maybe_autoscroll
$(".new_message_textarea").css("min-height", "3em");
set_focus(msg_type, opts);
}
export function clear_textarea() {
$("#compose").find("input[type=text], textarea").val("");
}
... | (msg_type, opts) {
// This is sort of a kitchen sink function, and it's called only
// by compose.start() for now. Having this as a separate function
// makes testing a bit easier.
maybe_scroll_up_selected_message();
compose_fade.start_compose(msg_type);
stream_bar.decorate(opts.stream, $("#st... | complete_starting_tasks | identifier_name |
compose_actions.js | );
}
compose_state.set_message_type(msg_type);
// Show either stream/topic fields or "You and" field.
show_box(msg_type, opts);
// Show a warning if topic is resolved
compose_validate.warn_if_topic_resolved();
// Reset the `max-height` property of `compose-textarea` so that the
// co... | message.raw_content = data.raw_content;
replace_content(message);
},
| identifier_body | |
compose_actions.js | // When changing this, edit the 42px in _maybe_autoscroll
$(".new_message_textarea").css("min-height", "3em");
set_focus(msg_type, opts);
}
export function clear_textarea() {
$("#compose").find("input[type=text], textarea").val("");
}
function clear_box() {
compose.clear_invites();
// TODO: ... | $("#stream_toggle").removeClass("active");
$("#private_message_toggle").addClass("active");
}
$("#compose-send-status").removeClass(common.status_classes).hide();
$("#compose").css({visibility: "visible"}); | random_line_split | |
compose_actions.js | _classes).hide();
$("#compose").css({visibility: "visible"});
// When changing this, edit the 42px in _maybe_autoscroll
$(".new_message_textarea").css("min-height", "3em");
set_focus(msg_type, opts);
}
export function clear_textarea() {
$("#compose").find("input[type=text], textarea").val("");
}
... |
const selected_row = message_lists.current.selected_row();
if (selected_row.height() > message_viewport.height() - 100) {
// For very tall messages whose height is close to the entire
// height of the viewport, don't auto-scroll the viewport to
// the end of the message (since that mak... | {
// If there's no selected message, there's no need to
// scroll the compose box to avoid it.
return;
} | conditional_block |
konami.js | // a key map of allowed keys
| 69: 'e',
83: 's',
66: 'b',
73: 'i',
84: 't'
};
// the 'official' Konami Code sequence
var konamiCode = ['e', 'e', 'c', 's', 'b', 'i', 't'];
// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition = 0;
// add keydown event listener
document.addEventListener... | var allowedKeys = {
67: 'c',
| random_line_split |
konami.js | // a key map of allowed keys
var allowedKeys = {
67: 'c',
69: 'e',
83: 's',
66: 'b',
73: 'i',
84: 't'
};
// the 'official' Konami Code sequence
var konamiCode = ['e', 'e', 'c', 's', 'b', 'i', 't'];
// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition =... | () {
document.body.style.backgroundImage = "url('images/james.jpg')";
var audio = new Audio('audio/barbie.mp3');
audio.play();
alert("Throughout this project, Paul and James have constantly made jokes and bits. Here's a picture of James stripping in EECS - Vikram");
} | activateCheats | identifier_name |
konami.js | // a key map of allowed keys
var allowedKeys = {
67: 'c',
69: 'e',
83: 's',
66: 'b',
73: 'i',
84: 't'
};
// the 'official' Konami Code sequence
var konamiCode = ['e', 'e', 'c', 's', 'b', 'i', 't'];
// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition =... | else
konamiCodePosition = 0;
});
function activateCheats() {
document.body.style.backgroundImage = "url('images/james.jpg')";
var audio = new Audio('audio/barbie.mp3');
audio.play();
alert("Throughout this project, Paul and James have constantly made jokes and bits. Here's a picture of James s... | {
// move to the next key in the konami code sequence
konamiCodePosition++;
// if the last key is reached, activate cheats
if (konamiCodePosition == konamiCode.length)
activateCheats();
} | conditional_block |
konami.js | // a key map of allowed keys
var allowedKeys = {
67: 'c',
69: 'e',
83: 's',
66: 'b',
73: 'i',
84: 't'
};
// the 'official' Konami Code sequence
var konamiCode = ['e', 'e', 'c', 's', 'b', 'i', 't'];
// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition =... | {
document.body.style.backgroundImage = "url('images/james.jpg')";
var audio = new Audio('audio/barbie.mp3');
audio.play();
alert("Throughout this project, Paul and James have constantly made jokes and bits. Here's a picture of James stripping in EECS - Vikram");
} | identifier_body | |
setup.py | from setuptools import setup
with open("README.rst") as readme_file:
long_description = readme_file.read()
setup(name="Presser",
version="0.1.8",
packages=["presser",],
license="GNU GPL v3.0",
description="Extracts data from vine, in lieu of an API",
author="Gemma Hentsch",
author_email="... | "mock",
"coverage",
"nose",
"PyExecJS",
"responses"
],
long_description=long_description,
test_suite="nose.collector",
url="https://github.com/ladyrassilon/presser",
keywords = ['scraping','vine'],
download_url="https://github.com/ladyrassilon/presser/arch... | tests_require=[
"beautifulsoup4",
"requests", | random_line_split |
einstein.py | from pyeda.inter import *
'''
The Englishman lives in the red house.
The Swede keeps dogs.
The Dane drinks tea.
The green house is just to the left of the white one.
The owner of the green house drinks coffee.
The Pall Mall smoker keeps birds.
The owner of the yellow house smokes Dunhills.
The man in the center house ... | The German smokes Prince.
The Norwegian lives next to the blue house.
The Blend smoker has a neighbor who drinks water.
'''
X = exprvars('x', (1,6), (1,6), (1,6))
class Solve:
def __init__(self):
X = exprvars('x', (1,6), (1,6), (1,6))
self.DIGITS = "123456789"
self.F = And (*[ And (*[ OneHo... | The Norwegian lives in the first house.
The Blend smoker has a neighbor who keeps cats.
The man who smokes Blue Masters drinks beer.
The man who keeps horses lives next to the Dunhill smoker. | random_line_split |
einstein.py | from pyeda.inter import *
'''
The Englishman lives in the red house.
The Swede keeps dogs.
The Dane drinks tea.
The green house is just to the left of the white one.
The owner of the green house drinks coffee.
The Pall Mall smoker keeps birds.
The owner of the yellow house smokes Dunhills.
The man in the center house ... |
if __name__ == "__main__":
gridStr = (
".73...8.."
"..413..5."
".85..631."
"5...9..3."
"..8.1.5.."
".1..6...7"
".516..28."
".4..529.."
"..2...64.")
s = Solve()
print (s.solve())
#s.displayOne(s.solve(gridStr))
| for r in range(1,6):
line = ""
for c in range(1,6):
for v in range(1,6):
if solution[X[r, c, v]]:
line = line + ("%d " % v)
print ("%s" % line) | identifier_body |
einstein.py | from pyeda.inter import *
'''
The Englishman lives in the red house.
The Swede keeps dogs.
The Dane drinks tea.
The green house is just to the left of the white one.
The owner of the green house drinks coffee.
The Pall Mall smoker keeps birds.
The owner of the yellow house smokes Dunhills.
The man in the center house ... |
r = r + (c == 8)
c = (c + 1) % 9
return grid
def display(self, solutions):
for s in solutions:
self.display(s)
print ("\n\n")
def displayOne(self, solution):
for r in range(1,6):
line = ""
for c in range(1,6):
... | grid = And (grid, X[r+1, c+1, int(ch)]) | conditional_block |
einstein.py | from pyeda.inter import *
'''
The Englishman lives in the red house.
The Swede keeps dogs.
The Dane drinks tea.
The green house is just to the left of the white one.
The owner of the green house drinks coffee.
The Pall Mall smoker keeps birds.
The owner of the yellow house smokes Dunhills.
The man in the center house ... | (self, solution):
for r in range(1,6):
line = ""
for c in range(1,6):
for v in range(1,6):
if solution[X[r, c, v]]:
line = line + ("%d " % v)
print ("%s" % line)
if __name__ == "__main__":
gridStr = (
".73...8..... | displayOne | identifier_name |
set.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (self):
super().__init__()
self.output = Endpoint(unsigned(32))
self.value = self.output.payload
self.new_en = Signal()
self.new_value = Signal(32)
def elab(self, m):
with m.If(self.output.is_transferring()):
m.d.sync += self.output.valid.eq(0)
w... | __init__ | identifier_name |
set.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | The value held by the register.
new_en: Signal(1), in
Indicates to register that a new value is being presented on new_value
new_value: unsigned(32), in
New value for the register. Read when "set" is asserted.
"""
def __init__(self):
super().__init__()
self.output = ... | output: Endpoint(unsigned(32))
An output stream of values. A new value onto the stream whenever
the register is set.
value: unsigned(32), out | random_line_split |
set.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
with m.Else():
m.d.sync += self.done.eq(0)
| with m.Case(i):
m.d.comb += register.new_en.eq(1)
m.d.comb += register.new_value.eq(self.in0)
m.d.comb += self.write_strobes[i].eq(1) | conditional_block |
set.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Constants.REG_INPUT_NUM_WORDS,
Constants.REG_INPUT_OFFSET,
Constants.REG_SET_FILTER,
Constants.REG_SET_INPUT,
Constants.REG_OUTPUT_OFFSET,
Constants.REG_OUTPUT_MIN,
Constants.REG_OUTPUT_MAX,
Constants.REG_FILTER_INPUT_NEXT,
Constants.REG_VERIFY,
... | """An instruction used to set values into a register of the CFU.
Sets a configuration register from in0.
Attributes
----------
output_streams: dict[id, Endpoint[unsigned(32)]], out
Value output for each register.
values: dict[id, unsigned(32)], out
Values as set into registers.
... | identifier_body |
file_loader.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 resource_task::{ProgressMsg, Metadata, Payload, Done, LoaderTask, start_sending};
use std::io;
use std::io::F... | (reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>)
-> Result<(), ()> {
loop {
let mut buf = ~[];
match reader.push_exact(&mut buf, READ_SIZE) {
Ok(_) => progress_chan.send(Payload(buf)),
Err(e) => match e.kind {
io::EndOfFile => return Ok((... | read_all | identifier_name |
file_loader.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 resource_task::{ProgressMsg, Metadata, Payload, Done, LoaderTask, start_sending};
use std::io;
use std::io::F... | }
};
});
};
f
} | let res = read_all(reader as &mut io::Stream, &progress_chan);
progress_chan.send(Done(res));
}
Err(_) => {
progress_chan.send(Done(Err(()))); | random_line_split |
file_loader.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 resource_task::{ProgressMsg, Metadata, Payload, Done, LoaderTask, start_sending};
use std::io;
use std::io::F... |
pub fn factory() -> LoaderTask {
let f: LoaderTask = proc(url, start_chan) {
assert!("file" == url.scheme);
let progress_chan = start_sending(start_chan, Metadata::default(url.clone()));
spawn_named("file_loader", proc() {
match File::open_mode(&Path::new(url.path), io::Open, i... | {
loop {
let mut buf = ~[];
match reader.push_exact(&mut buf, READ_SIZE) {
Ok(_) => progress_chan.send(Payload(buf)),
Err(e) => match e.kind {
io::EndOfFile => return Ok(()),
_ => return Err(()),
}
}
}
} | identifier_body |
NestedView.ts | /// <reference path="../../_references.ts" />
module Views.Nested {
export class NestedView extends Orange.Controls.KnockoutViewBase {
static dependencies = () => [Views.Nested.NestedViewModel];
constructor(viewModel: NestedViewModel) {
// call Orange.Controls.ViewBase constructor with
// (namespace1... | * this class.
*
* NOTE: None of the below methods have to be overridden, they are there to supply
* hookcs in to the layout engine att given stepps in the layout process.
*/
// onElementSet will be called directly after the view has been assigned a HTMLElement to
// this.Element. onElementSet is i... | * The following protected methods will be called in the order they are defined in | random_line_split |
NestedView.ts | /// <reference path="../../_references.ts" />
module Views.Nested {
export class NestedView extends Orange.Controls.KnockoutViewBase {
static dependencies = () => [Views.Nested.NestedViewModel];
constructor(viewModel: NestedViewModel) |
/*
* The following protected methods will be called in the order they are defined in
* this class.
*
* NOTE: None of the below methods have to be overridden, they are there to supply
* hookcs in to the layout engine att given stepps in the layout process.
*/
// onElementSet will be called dir... | {
// call Orange.Controls.ViewBase constructor with
// (namespace1-namespace2-viewClass [, viewmodel])
super("Views-Nested-NestedView", viewModel);
} | identifier_body |
NestedView.ts | /// <reference path="../../_references.ts" />
module Views.Nested {
export class NestedView extends Orange.Controls.KnockoutViewBase {
static dependencies = () => [Views.Nested.NestedViewModel];
constructor(viewModel: NestedViewModel) {
// call Orange.Controls.ViewBase constructor with
// (namespace1... | (): void {
super.onApplyTemplate();
}
// onApplyBindings will be called when any bindings (e.g. knockout bindings when using
// knockout) has been applied.
protected onApplyBindings(): void {
super.onApplyBindings();
}
}
}
| onApplyTemplate | identifier_name |
evalrational.js | Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in... |
fpath = resolve( __dirname, '..', 'lib', 'r | {
var fpath;
var opts;
var str;
opts = {
'encoding': 'utf8'
};
fpath = resolve( __dirname, '..', 'lib', 'rational_p1q1.js' );
str = header + compile( P1, Q1 );
writeFileSync( fpath, str, opts );
fpath = resolve( __dirname, '..', 'lib', 'rational_p2q2.js' );
str = header + compile( P2, Q2 );
writeFileSyn... | identifier_body |
evalrational.js | Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in... |
var Q1 = [
3.0737873921079286084e+14,
4.1272286200406461981e+12,
2.7800352738690585613e+10,
1.2250435122182963220e+08,
3.8136470753052572164e+05,
8.2079908168393867438e+02,
1.0
];
var P2 = [
1.1514276357909013326e+19,
-5.6808094574724204577e+18,
-2.3638408497043134724e+16,
4.0686275289804744814e+15,
-5.95... | -3.1714424660046133456e+02
]; | random_line_split |
evalrational.js | Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in... | () {
var fpath;
var opts;
var str;
opts = {
'encoding': 'utf8'
};
fpath = resolve( __dirname, '..', 'lib', 'rational_p1q1.js' );
str = header + compile( P1, Q1 );
writeFileSync( fpath, str, opts );
fpath = resolve( __dirname, '..', 'lib', 'rational_p2q2.js' );
str = header + compile( P2, Q2 );
writeFile... | main | identifier_name |
build.rs | extern crate protoc;
extern crate protoc_rust;
use std::env;
use std::fs;
fn main() {
if env::var("CARGO_FEATURE_PROTOCOLS").is_ok() {
generate_protocols();
}
}
fn generate_protocols() |
fn protocol_files() -> Vec<String> {
let mut files = vec![];
for entry in fs::read_dir("protocols").unwrap() {
let file = entry.unwrap();
// skip vim temp files
if file.file_name().to_str().unwrap().starts_with(".") {
continue;
}
if file.metadata().unwrap().... | {
let protocols = protocol_files();
protoc_rust::run(protoc_rust::Args {
out_dir: "src/generated",
input: protocols
.iter()
.map(AsRef::as_ref)
.collect::<Vec<&str>>()
.as_slice(),
includes: &["protocols"],
}).expect("protoc");
} | identifier_body |
build.rs | extern crate protoc;
extern crate protoc_rust;
use std::env;
use std::fs;
fn | () {
if env::var("CARGO_FEATURE_PROTOCOLS").is_ok() {
generate_protocols();
}
}
fn generate_protocols() {
let protocols = protocol_files();
protoc_rust::run(protoc_rust::Args {
out_dir: "src/generated",
input: protocols
.iter()
.map(AsRef::as_ref)
... | main | identifier_name |
build.rs | extern crate protoc;
extern crate protoc_rust;
use std::env;
use std::fs;
fn main() {
if env::var("CARGO_FEATURE_PROTOCOLS").is_ok() |
}
fn generate_protocols() {
let protocols = protocol_files();
protoc_rust::run(protoc_rust::Args {
out_dir: "src/generated",
input: protocols
.iter()
.map(AsRef::as_ref)
.collect::<Vec<&str>>()
.as_slice(),
includes: &["protocols"],
}... | {
generate_protocols();
} | conditional_block |
build.rs | extern crate protoc;
extern crate protoc_rust;
use std::env;
use std::fs;
fn main() {
if env::var("CARGO_FEATURE_PROTOCOLS").is_ok() {
generate_protocols();
}
}
fn generate_protocols() {
let protocols = protocol_files();
protoc_rust::run(protoc_rust::Args {
out_dir: "src/generated",
... | fn protocol_files() -> Vec<String> {
let mut files = vec![];
for entry in fs::read_dir("protocols").unwrap() {
let file = entry.unwrap();
// skip vim temp files
if file.file_name().to_str().unwrap().starts_with(".") {
continue;
}
if file.metadata().unwrap().is... | }).expect("protoc");
}
| random_line_split |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... |
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
/// The compartment for reporting exceptions.
/// As a RootedObject, this must be the first field in order to
/// determine the... | {
rval.set(p.reflector().get_jsobject().get());
assert!(!rval.get().is_null());
unsafe {
if !JS_WrapObject(cx, rval) {
rval.set(ptr::null_mut());
}
}
} | identifier_body |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... | () -> CallbackFunction {
CallbackFunction {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut J... | new | identifier_name |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... |
unsafe {
JS_EndRequest(self.cx);
}
}
}
| {
unsafe {
let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr);
let saved = JS_SaveFrameChain(self.cx);
{
let _ac = JSAutoCompartment::new(self.cx, old_global.ptr);
JS_ReportPendingException(self.... | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::glob... | }
}
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
/// The compartment for reporting exceptions.
/// As a RootedObject, this must be the first field in order to
/// determ... | if !JS_WrapObject(cx, rval) {
rval.set(ptr::null_mut());
} | random_line_split |
res_company.py | # Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
| from odoo import fields, models
SORTING_CRITERIA = [
("name", "By name"),
("product_id.name", "By product name"),
("product_id.default_code", "By product reference"),
("date_planned", "By date planned"),
("price_unit", "By price"),
("product_qty", "By quantity"),
]
SORTING_DIRECTION = [
("... | random_line_split | |
res_company.py | # Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
from odoo import fields, models
SORTING_CRITERIA = [
("name", "By name"),
("product_id.name", "By product name"),
("product_id.default_code", "By product reference"),
("... | (models.Model):
_inherit = "res.company"
default_po_line_order = fields.Selection(
selection=SORTING_CRITERIA,
string="Line Order",
help="Select a sorting criteria for purchase order lines.",
)
default_po_line_direction = fields.Selection(
selection=SORTING_DIRECTION,
... | ResCompany | identifier_name |
res_company.py | # Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
from odoo import fields, models
SORTING_CRITERIA = [
("name", "By name"),
("product_id.name", "By product name"),
("product_id.default_code", "By product reference"),
("... | _inherit = "res.company"
default_po_line_order = fields.Selection(
selection=SORTING_CRITERIA,
string="Line Order",
help="Select a sorting criteria for purchase order lines.",
)
default_po_line_direction = fields.Selection(
selection=SORTING_DIRECTION,
string="Sort D... | identifier_body | |
Key.js | var Key = require('bindings')('KeyModule').Key;
var CommonKey = require('./common/Key');
var bignum = require('bignum');
var Point = require('./Point');
var coinUtil = require('../util');
for (var i in CommonKey) { |
Key.sign = function(hash, priv, k) {
if (k)
throw new Error('Deterministic k not supported in node');
var key = new Key();
key.private = priv.toBuffer({size: 32});
var sig = key.signSync(hash);
var parsed = Key.parseDERsig(sig);
return {r: parsed.r, s: parsed.s};
};
Key.signCompressed = function(ha... | if (CommonKey.hasOwnProperty(i))
Key[i] = CommonKey[i];
} | random_line_split |
exception.py | # Copyright 2013 - Red Hat, 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 in writi... |
class ObjectNotFound(SolumException):
msg_fmt = _("The %(name)s %(id)s could not be found.")
class ObjectNotUnique(SolumException):
msg_fmt = _("The %(name)s already exists.")
class ResourceNotFound(ObjectNotFound):
msg_fmt = _("The %(name)s resource %(id)s could not be found.")
code = 404
class ... | return self.message
| random_line_split |
exception.py | # Copyright 2013 - Red Hat, 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 in writi... | (f):
def wrapped(self, context, *args, **kw):
# Don't store self or context in the payload, it now seems to
# contain confidential information.
try:
return f(self, context, *args, **kw)
except Exception as e:
with excutils.save_and_... | inner | identifier_name |
exception.py | # Copyright 2013 - Red Hat, 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 in writi... |
return wrapped
class SolumException(Exception):
"""Base Solum Exception
To correctly use this class, inherit from it and define
a 'msg_fmt' property. That msg_fmt will get printf'd
with the keyword arguments provided to the constructor.
"""
message = _("An unknown exception occurred.")
... | try:
return func(*args, **kw)
except keystone_exceptions.AuthorizationFailure:
raise AuthorizationFailure(
client=func.__name__, message="reason: %s" % sys.exc_info()[1])
except keystone_exceptions.ClientException:
raise AuthorizationFailure(
... | identifier_body |
exception.py | # Copyright 2013 - Red Hat, 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 in writi... |
notifier.notify(context, publisher_id, temp_type,
temp_level, payload)
return functools.wraps(f)(wrapped)
return inner
def wrap_controller_exception(func):
"""This decorator wraps controllers method to manage wsme exceptions:
a wsm... | temp_type = f.__name__ | conditional_block |
user.server.model.test.js | 'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User');
/**
* Globals
*/
var user, user2;
/**
* Unit tests
*/
describe.skip('User Model Unit Tests:', function() {
before(function(done) {
user = new User({
firstName: 'Ful... | password: 'password',
provider: 'local'
});
done();
});
describe('Method Save', function() {
it('should begin with no users', function(done) {
User.find({}, function(err, users) {
users.should.have.length(0);
done();
});
});
it('should be able to save without problems', function(done)... | random_line_split | |
regs.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from miasm2.expression.expression import ExprId
from miasm2.core.cpu import gen_reg, gen_regs
gen_reg('PC', globals())
gen_reg('PC_FETCH', globals())
| gen_reg('R_LO', globals())
gen_reg('R_HI', globals())
exception_flags = ExprId('exception_flags', 32)
PC_init = ExprId("PC_init")
PC_FETCH_init = ExprId("PC_FETCH_init")
regs32_str = ["ZERO", 'AT', 'V0', 'V1'] +\
['A%d'%i for i in xrange(4)] +\
['T%d'%i for i in xrange(8)] +\
['S%d'%i for i in xrange(8)]... | random_line_split | |
regs.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from miasm2.expression.expression import ExprId
from miasm2.core.cpu import gen_reg, gen_regs
gen_reg('PC', globals())
gen_reg('PC_FETCH', globals())
gen_reg('R_LO', globals())
gen_reg('R_HI', globals())
exception_flags = ExprId('exception_flags', 32)
PC_init = ExprId("... | regs_init[r] = all_regs_ids_init[i] | conditional_block | |
club.form.component.ts | import { Component, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FirebaseService } from '../../shared/services/firebase.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'my-club-form',
templateUrl: './club.form.component.html',
styleUrls: ['./club-list.compo... |
onSubmit(){
let club = {
name: this.name,
description: this.description
};
this.firebaseService.addData(club);
this.submitted = true;
this.name = '';
this.description = '';
}
onChange(event){
event = event;
let imageV... | {
} | identifier_body |
club.form.component.ts | import { Component, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FirebaseService } from '../../shared/services/firebase.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'my-club-form',
templateUrl: './club.form.component.html',
styleUrls: ['./club-list.compo... | },
'description': {
'required': 'Description is required.',
'minlength': 'Description must be from 30 to 500 characters long',
'maxlength': 'Description cannot be more than 500 characters long.'
}
};
} | 'minlength': 'Name must be at least 4 characters long.',
'maxlength': 'Name cannot be more than 24 characters long.' | random_line_split |
club.form.component.ts | import { Component, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FirebaseService } from '../../shared/services/firebase.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'my-club-form',
templateUrl: './club.form.component.html',
styleUrls: ['./club-list.compo... |
this.myForm = this.currentForm;
if (this.myForm) {
this.myForm.valueChanges
.subscribe(data => this.onValueChanged(data));
}
}
onValueChanged(data?: any) {
data = data;
if (!this.myForm) { return; }
const form = this.myForm.form;
for... | { return; } | conditional_block |
club.form.component.ts | import { Component, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { FirebaseService } from '../../shared/services/firebase.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'my-club-form',
templateUrl: './club.form.component.html',
styleUrls: ['./club-list.compo... | implements OnInit, AfterViewChecked {
submitted: boolean;
active: boolean;
myForm: NgForm;
event: any;
changed: boolean;
@ViewChild('myForm') currentForm: NgForm;
private name: string;
private description: string;
public image: any;
constructor(private firebaseService: Firebase... | ClubFormComponent | identifier_name |
serverRound.ts | import { EventEmitter } from "events";
import { SECONDS_ROUND_COUNTDOWN } from "../../shared/const";
import { loadLevel } from "../../shared/level/level";
import { RoomManualStartMessage } from "../../shared/room/roomMessages";
import { RoomOptions } from "../../shared/room/roomOptions";
import { Round } from "../../sh... | (winnerPlayer: ServerPlayer): void {
// TODO: Handle in Client?
this.players.send(new RoundWrapupMessage(winnerPlayer.id));
this.wrappingUp = true;
}
start(): void {
this.countDown = true;
}
set countDown(enabled: boolean) {
if (this._countDown === enabled) {
... | wrapUp | identifier_name |
serverRound.ts | import { EventEmitter } from "events";
import { SECONDS_ROUND_COUNTDOWN } from "../../shared/const";
import { loadLevel } from "../../shared/level/level";
import { RoomManualStartMessage } from "../../shared/room/roomMessages";
import { RoomOptions } from "../../shared/room/roomOptions";
import { Round } from "../../sh... |
wrapUp(winnerPlayer: ServerPlayer): void {
// TODO: Handle in Client?
this.players.send(new RoundWrapupMessage(winnerPlayer.id));
this.wrappingUp = true;
}
start(): void {
this.countDown = true;
}
set countDown(enabled: boolean) {
if (this._countDown === e... | {
this.unbindEvents();
this.level = await loadLevel(this.LevelClass, serverImageLoader);
this.game = new ServerGame(this.roomEmitter, this.level, this.players);
this.players.send(new RoundStartMessage());
} | identifier_body |
serverRound.ts | import { EventEmitter } from "events";
import { SECONDS_ROUND_COUNTDOWN } from "../../shared/const";
import { loadLevel } from "../../shared/level/level";
import { RoomManualStartMessage } from "../../shared/room/roomMessages";
import { RoomOptions } from "../../shared/room/roomOptions";
import { Round } from "../../sh... |
unbindEvents(): void {
this.roomEmitter.off(SERVER_EVENT.PLAYER_DISCONNECT, this.onPlayerDisconnect);
this.roomEmitter.removeAllListeners(RoomManualStartMessage.id);
}
async startRound(): Promise<void> {
this.unbindEvents();
this.level = await loadLevel(this.LevelClass, ser... | this.level?.destruct();
delete this.level;
} | random_line_split |
serverRound.ts | import { EventEmitter } from "events";
import { SECONDS_ROUND_COUNTDOWN } from "../../shared/const";
import { loadLevel } from "../../shared/level/level";
import { RoomManualStartMessage } from "../../shared/room/roomMessages";
import { RoomOptions } from "../../shared/room/roomOptions";
import { Round } from "../../sh... |
}
}
| {
this.countdownTimer = setTimeout(async () => {
await this.startRound();
}, SECONDS_ROUND_COUNTDOWN * 1000);
} | conditional_block |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
modu... | ;
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
} | {
this.heroes = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time
// return the http search o... | identifier_body |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
| selector: 'hero-search',
templateUrl: 'hero-search.component.html',
styleUrls: [ 'hero-search.component.css' ],
providers: [
HeroSearchService
]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms = new Subject<string>();
const... | import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
moduleId: module.id, | random_line_split |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
modu... | (term: string): void {
this.searchTerms.next(term);
};
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term =>... | search | identifier_name |
mainbuttons.test.ts | import * as ko from "knockout";
import { debugSettings } from "../../js/debugsettings";
import { ActionBlock } from "../../js/table/actionBlock";
import { GameActionsQueue } from "../../js/table/gameactionsqueue";
import {
TableView,
} from "../../js/table/tableview";
import { drainQueue, getTable, getTestTableView... |
};
beforeEach(function () {
GameActionsQueue.waitDisabled = true;
logEnabled = false;
debugSettings.tableView.trace = false;
global.messages = {
};
});
afterEach(function () {
GameActionsQueue.waitDisabled = true;
});
describe("initial status", ... | {
console.log(message);
} | conditional_block |
mainbuttons.test.ts | import * as ko from "knockout";
import { debugSettings } from "../../js/debugsettings";
import { ActionBlock } from "../../js/table/actionBlock";
import { GameActionsQueue } from "../../js/table/gameactionsqueue";
import { | describe("main buttons", function () {
let logEnabled = false;
const log = function (message: string, ...params: any[]) {
if (logEnabled) {
console.log(message);
}
};
beforeEach(function () {
GameActionsQueue.waitDisabled = true;
logEnabled = false;
d... | TableView,
} from "../../js/table/tableview";
import { drainQueue, getTable, getTestTableView, printTableView, simpleInitialization } from "../table/helper";
| random_line_split |
tests.py | """Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... |
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create albums for testing."""
class Meta(object):
"""Meta."""
model = Album
title = factory.Sequence(lambda n: "album{}".format(n))
class ApiTests(APITestCase):
"""Tests for the Api."""
def setUp(self):
"""Set ... | """Create photos for testing."""
class Meta(object):
"""Meta."""
model = Photo
title = factory.Sequence(lambda n: "photo{}".format(n))
image = SimpleUploadedFile(
name="testing.png",
content=open(MEDIA_ROOT + '/test/testing.png', 'rb').read(),
content_type="image/pn... | identifier_body |
tests.py | """Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... |
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create photos for testing."""
class Meta(object):
"""Meta."""
model = Photo
title = factory.Sequence(lambda n: "photo{}".format(n))
image = SimpleUploadedFile(
name="testing.png",
content=open(MEDIA_ROOT + '/te... | email = factory.Sequence(
lambda n: "user{}@example.com".format(n)
) | random_line_split |
tests.py | """Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... | (APITestCase):
"""Tests for the Api."""
def setUp(self):
"""Set up for testing."""
user = UserFactory.create()
user.set_password('caaarlos')
user.save()
self.user = user
photos = [PhotoFactory.create(profile=user.profile) for i in range(20)]
album = Album... | ApiTests | identifier_name |
tests.py | """Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... |
album.cover_photo = photos[0]
album.save()
def tearDown(self):
"""Teardown when tests complete."""
to_delete = os.path.join(MEDIA_ROOT, 'photos', 'testing*.png')
os.system('rm -rf ' + to_delete)
def test_get_route_status_200(self):
"""Status 200."""
res... | album.photos.add(photo) | conditional_block |
main.rs | extern crate liner;
extern crate termion;
use std::mem::replace;
use std::env::{args, current_dir};
use std::io;
use liner::{Context, CursorPosition, Event, EventKind, FilenameCompleter};
fn main() | // Figure out of we are completing a command (the first word) or a filename.
let filename = match pos {
CursorPosition::InWord(i) => i > 0,
CursorPosition::InSpace(Some(_), _) => true,
CursorPosition::InSpace(None, _) => false,
... | {
let mut con = Context::new();
let history_file = args().nth(1);
match history_file {
Some(ref file_name) => println!("History file: {}", file_name),
None => println!("No history file"),
}
con.history.set_file_name(history_file);
if con.history.file_name().is_some() {
... | identifier_body |
main.rs | extern crate liner;
extern crate termion;
use std::mem::replace;
use std::env::{args, current_dir};
use std::io;
use liner::{Context, CursorPosition, Event, EventKind, FilenameCompleter};
fn | () {
let mut con = Context::new();
let history_file = args().nth(1);
match history_file {
Some(ref file_name) => println!("History file: {}", file_name),
None => println!("No history file"),
}
con.history.set_file_name(history_file);
if con.history.file_name().is_some() {
... | main | identifier_name |
main.rs | extern crate liner;
extern crate termion;
use std::mem::replace;
use std::env::{args, current_dir};
use std::io;
use liner::{Context, CursorPosition, Event, EventKind, FilenameCompleter};
fn main() {
let mut con = Context::new();
let history_file = args().nth(1);
match history_file {
Some(ref fi... | // ctrl-d pressed
io::ErrorKind::UnexpectedEof => {
println!("exiting...");
break;
}
_ => {
// Ensure that all writes to the history file
// are... | match e.kind() {
// ctrl-c pressed
io::ErrorKind::Interrupted => {} | random_line_split |
tokenSelectionSupport.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
let actualStr = actual.map(r => new Range(r.range.startLineNumber, r.range.startColumn, r.range.endLineNumber, r.range.endColumn).toString());
let desiredStr = ranges.map(r => String(r));
assert.deepEqual(actualStr, desiredStr);
modelService.destroyModel(uri);
}
test('getRangesToPosition #1', () => {
a... | random_line_split | |
tokenSelectionSupport.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (text: string[], lineNumber: number, column: number, ranges: Range[]): void {
let uri = URI.file('test.js');
modelService.createModel(text.join('\n'), mode, uri);
let actual = tokenSelectionSupport.getRangesToPositionSync(uri, new Position(lineNumber, column));
let actualStr = actual.map(r => new Range(r.rang... | assertGetRangesToPosition | identifier_name |
tokenSelectionSupport.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
suite('TokenSelectionSupport', () => {
let modelService: ModelServiceImpl | null = null;
let tokenSelectionSupport: TokenSelectionSupport;
let mode: MockJSMode | null = null;
setup(() => {
modelService = new ModelServiceImpl(null, new TestConfigurationService());
tokenSelectionSupport = new TokenSelection... | {
super(MockJSMode._id);
this._register(LanguageConfigurationRegistry.register(this.getLanguageIdentifier(), {
brackets: [
['(', ')'],
['{', '}'],
['[', ']']
],
onEnterRules: javascriptOnEnterRules
}));
} | identifier_body |
progressbarsample.component.ts | import { Component, NgModule } from "@angular/core";
import { IgxProgressBarModule } from "../../../src/main";
@Component({
selector: "progressbar-sample",
template: `
<h3>Progress Bars</h3>
<div class="button-container">
<button igxButton="fab" igxRipple="" (click)="generateNewProg... | (min:number,max:number)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
f(evt) {
console.log(evt);
}
change(evt) {
console.log(evt);
}
} | randomIntFromInterval | identifier_name |
progressbarsample.component.ts | import { Component, NgModule } from "@angular/core";
import { IgxProgressBarModule } from "../../../src/main";
@Component({
selector: "progressbar-sample",
template: `
<h3>Progress Bars</h3>
<div class="button-container">
<button igxButton="fab" igxRipple="" (click)="generateNewProg... |
} | {
console.log(evt);
} | identifier_body |
progressbarsample.component.ts | import { Component, NgModule } from "@angular/core";
import { IgxProgressBarModule } from "../../../src/main";
@Component({
selector: "progressbar-sample",
template: `
<h3>Progress Bars</h3>
<div class="button-container">
<button igxButton="fab" igxRipple="" (click)="generateNewProg... | <igx-linear-bar [striped]="false" [value]="currentValue" [max]="200">
</igx-linear-bar>
</div>
<div class="progress-container-linear">
<igx-linear-bar type="danger" [striped]="false" [value]="currentValue">
</igx-linear-bar>
</div>
<div cla... | </button>
</div>
<div class="progress-container-linear"> | random_line_split |
textFileServices.ts | import ipc = require('ipc');
const Dialog = remote.require('dialog');
export class TextFileService extends AbstractTextFileService {
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IInstantiationService instantiationService: IInstantiationService,
@IFileService private fileSe... | }
});
return this.doSaveAll(filesToSave, untitledToSave);
}
private doSaveAll(fileResources: URI[], untitledResources: URI[]): TPromise<ITextFileOperationResult> {
// Preflight for untitled to handle cancellation from the dialog
let targetsForUntitled: URI[] = [];
for (let i = 0; i < untitledResource... | {
// get all dirty
let toSave: URI[] = [];
if (Array.isArray(arg1)) {
(<URI[]>arg1).forEach((r) => {
toSave.push(...this.getDirty(r));
});
} else {
toSave = this.getDirty();
}
// split up between files and untitled
let filesToSave: URI[] = [];
let untitledToSave: URI[] = [];
toSave.forE... | identifier_body |
textFileServices.ts | this.untitledEditorService.getAll(resources);
untitledInputs.forEach((input) => {
if (input) {
input.dispose();
r.results.push({
source: input.getResource(),
success: true
});
}
});
return r;
});
}
public getDirty(resource?: URI): URI[] {
// Collect files
let dir... | getSaveDialogOptions | identifier_name | |
textFileServices.ts | import ipc = require('ipc');
const Dialog = remote.require('dialog');
export class TextFileService extends AbstractTextFileService {
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IInstantiationService instantiationService: IInstantiationService,
@IFileService private fileSe... |
let opts: remote.IMessageBoxOptions = {
title: this.contextService.getConfiguration().env.appName,
message: message.join('\n'),
type: 'warning',
detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them."),
buttons: buttons.map(b => b.label),
noLink: true,
canc... | {
buttons.push(cancel, dontSave);
} | conditional_block |
textFileServices.ts | import ipc = require('ipc');
const Dialog = remote.require('dialog');
export class TextFileService extends AbstractTextFileService {
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IInstantiationService instantiationService: IInstantiationService,
@IFileService private fileSe... | filesToSave.push(s);
} else if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === 'untitled') {
untitledToSave.push(s);
}
});
return this.doSaveAll(filesToSave, untitledToSave);
}
private doSaveAll(fileResources: URI[], untitledResources: URI[]): TPromise<ITextFileOperat... | let untitledToSave: URI[] = [];
toSave.forEach((s) => {
if (s.scheme === 'file') { | random_line_split |
lib.rs | .build()
//! .send();
//! }
//! }
//! }
//! ```
//!
//! Configuration
//! -------------
//!
//! ### project_key & project_id
//!
//! You **must** set both `project_id` & `project_key`.
//!
//! To find your `project_id` and `project_key` navigate to your project's _General
//! Settings_ and ... | configure | identifier_name | |
lib.rs | to test Airbrake Rust with your
//! project:
//!
//! ```
//! use std::num::ParseIntError;
//!
//! fn double_number(number_str: &str) -> Result<i32, ParseIntError> {
//! number_str.parse::<i32>().map(|n| 2 * n)
//! }
//!
//! fn main() {
//! let mut airbrake = airbrake::configure(|config| {
//! config.pro... | //!
//!
//! The Notice module contains the various structs that make up an Airbrake
//! Notice. A Notice primarily contains NoticeErrors, which represents the error
//! itself. Other parts of the of Notice are Context, Environment, Session and
//! Parameters.
//!
//! Typically you won't need to work with the NoticeErro... | //!
//! | random_line_split |
lib.rs | `project_id` and `project_key` navigate to your project's _General
//! Settings_ and copy the values from the right sidebar.
//!
//! ![][project-idkey]
//!
//! ```
//! let mut airbrake = airbrake::configure(|config| {
//! config.project_id("113743");
//! config.project_key("81bbff95d52f8856c770bb39e827f3f6");
... | {
AirbrakeClient::builder()
.configure(builder_callback)
.build()
.expect("Airbrake configuration failed")
} | identifier_body | |
edges.ts | /**
* @module modifiers/snapEdges
*
* @description
* WOW> This module allows snapping of the edges of targets during resize
* interactions.
*
* ```js
* interact(target).resizable({
* snapEdges: {
* targets: [interact.snappers.grid({ x: 100, y: 50 })],
* },
* })
*
* interact(target).resizable({
* ... | (arg: ModifierArg<SnapState>) {
const { edges } = arg
if (!edges) {
return null
}
arg.state.targetFields = arg.state.targetFields || [
[edges.left ? 'left' : 'right', edges.top ? 'top' : 'bottom'],
]
return snapSize.start(arg)
}
const snapEdges: ModifierModule<SnapEdgesOptions, SnapState, Retur... | start | identifier_name |
edges.ts | /**
* @module modifiers/snapEdges
*
* @description
* WOW> This module allows snapping of the edges of targets during resize
* interactions.
*
* ```js
* interact(target).resizable({
* snapEdges: {
* targets: [interact.snappers.grid({ x: 100, y: 50 })],
* },
* })
*
* interact(target).resizable({
* ... | start,
set: snapSize.set,
defaults: extend(clone(snapSize.defaults), {
targets: null,
range: null,
offset: { x: 0, y: 0 },
} as const),
}
export default makeModifier(snapEdges, 'snapEdges')
export { snapEdges } | const snapEdges: ModifierModule<SnapEdgesOptions, SnapState, ReturnType<typeof snapSize.set>> = { | random_line_split |
edges.ts | /**
* @module modifiers/snapEdges
*
* @description
* WOW> This module allows snapping of the edges of targets during resize
* interactions.
*
* ```js
* interact(target).resizable({
* snapEdges: {
* targets: [interact.snappers.grid({ x: 100, y: 50 })],
* },
* })
*
* interact(target).resizable({
* ... |
arg.state.targetFields = arg.state.targetFields || [
[edges.left ? 'left' : 'right', edges.top ? 'top' : 'bottom'],
]
return snapSize.start(arg)
}
const snapEdges: ModifierModule<SnapEdgesOptions, SnapState, ReturnType<typeof snapSize.set>> = {
start,
set: snapSize.set,
defaults: extend(clone(snapSi... | {
return null
} | conditional_block |
edges.ts | /**
* @module modifiers/snapEdges
*
* @description
* WOW> This module allows snapping of the edges of targets during resize
* interactions.
*
* ```js
* interact(target).resizable({
* snapEdges: {
* targets: [interact.snappers.grid({ x: 100, y: 50 })],
* },
* })
*
* interact(target).resizable({
* ... |
const snapEdges: ModifierModule<SnapEdgesOptions, SnapState, ReturnType<typeof snapSize.set>> = {
start,
set: snapSize.set,
defaults: extend(clone(snapSize.defaults), {
targets: null,
range: null,
offset: { x: 0, y: 0 },
} as const),
}
export default makeModifier(snapEdges, 'snapEdges')
export { ... | {
const { edges } = arg
if (!edges) {
return null
}
arg.state.targetFields = arg.state.targetFields || [
[edges.left ? 'left' : 'right', edges.top ? 'top' : 'bottom'],
]
return snapSize.start(arg)
} | identifier_body |
mysql.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use clap::Args;
/// Command line arguments for controlling MySql
// Defaults are derived from `sql_ext::facebook::mysql`
// https://fburl.... | /// MySql connection pool per key limit
#[clap(long, default_value = "100")]
pub mysql_pool_per_key_limit: u64,
/// Number of threads in MySql connection pool (number of real pools)
#[clap(long, default_value = "10")]
pub mysql_pool_threads_num: i32,
/// Mysql connection pool age timeout i... |
/// Size of the MySql connection pool
#[clap(long, default_value = "10000")]
pub mysql_pool_limit: usize,
| random_line_split |
mysql.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use clap::Args;
/// Command line arguments for controlling MySql
// Defaults are derived from `sql_ext::facebook::mysql`
// https://fburl.... | {
/// Connect to MySql master only.
#[clap(long)]
pub mysql_master_only: bool,
/// Size of the MySql connection pool
#[clap(long, default_value = "10000")]
pub mysql_pool_limit: usize,
/// MySql connection pool per key limit
#[clap(long, default_value = "100")]
pub mysql_pool_per_... | MysqlArgs | identifier_name |
ratings.rs | use super::*;
use crate::{core::util, infrastructure::flows::prelude as flows};
#[post("/ratings", format = "application/json", data = "<data>")]
pub fn post_rating(
connections: sqlite::Connections,
mut search_engine: tantivy::SearchEngine,
data: Json<usecases::NewPlaceRating>,
) -> Result<()> {
let ... | json::Rating {
id: r.id.into(),
created: r.created_at.into_seconds(),
title: r.title,
value: r.value.into(),
context: r.context.into(),
source: r.source.unwrap_or_default(),
comments,
... | {
// TODO: RESTful API
// - Only lookup and return a single entity
// - Add a new action and method for getting multiple ids at once
let ids = util::split_ids(&ids);
if ids.is_empty() {
return Ok(Json(vec![]));
}
let ratings_with_comments = usecases::load_ratings_with_comments(&*... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.