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 |
|---|---|---|---|---|
create.js | var middleware = require('../../middleware')
;
function handler (req, res, next) {
var profile = { };
res.send(200, res.profile);
next( );
return;
}
var endpoint = {
path: '/users/:user/create'
, method: 'get'
, handler: handler
};
module.exports = function configure (opts, server) {
function mount ... | var mandatory = middleware.mandatory(opts, server);
endpoint.middleware = mandatory.concat(userInfo);
function updateUser (req, res, next) {
var profile = { };
var name = req.params.user;
var update = req.params;
server.updateUser(name, update, {save:false, create:true}, function (result) {
... | server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler);
}
var userInfo = middleware.minUser(opts, server); | random_line_split |
create.js | var middleware = require('../../middleware')
;
function handler (req, res, next) {
var profile = { };
res.send(200, res.profile);
next( );
return;
}
var endpoint = {
path: '/users/:user/create'
, method: 'get'
, handler: handler
};
module.exports = function configure (opts, server) {
function mount ... |
endpoint.mount = mount;
return endpoint;
};
module.exports.endpoint = endpoint;
| {
var profile = { };
var name = req.params.user;
var update = req.params;
server.updateUser(name, update, {save:false, create:true}, function (result) {
server.log.debug('UPDATED user', arguments);
res.profile = result;
next( );
});
} | identifier_body |
create.js | var middleware = require('../../middleware')
;
function handler (req, res, next) {
var profile = { };
res.send(200, res.profile);
next( );
return;
}
var endpoint = {
path: '/users/:user/create'
, method: 'get'
, handler: handler
};
module.exports = function configure (opts, server) {
function | (server) {
server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler);
}
var userInfo = middleware.minUser(opts, server);
var mandatory = middleware.mandatory(opts, server);
endpoint.middleware = mandatory.concat(userInfo);
function updateUser (req, res, next) {
var profile = { };
... | mount | identifier_name |
api.ts | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the proj... | <T extends TApiMethodName>(
apiPath: T,
requestId: string,
...requestData: Parameters<TApiMethod[T]>
) {
const splitPath = apiPath.split("/");
const moduleId = splitPath[0] as TModuleApi;
const methodId = splitPath[1] as TMethodApi;
return put(apiActions.request.build(requestId, moduleId, me... | apiSaga | identifier_name |
api.ts | // Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the project repository.
// ==LICENSE-END==
import { TApiMethod, TApiMethodName } from "readium-desktop/common/api/api.type";
import { TMethodApi } from "readium-desktop/common/api/metho... | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements. | random_line_split | |
api.ts | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the proj... | {
const splitPath = apiPath.split("/");
const moduleId = splitPath[0] as TModuleApi;
const methodId = splitPath[1] as TMethodApi;
return put(apiActions.request.build(requestId, moduleId, methodId, requestData));
} | identifier_body | |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
r... | Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream ... |
// echo incoming bytes back
match stream.write(&mut buf) { | random_line_split |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() |
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
... | {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}... | identifier_body |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
r... | (mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buf... | handle_client | identifier_name |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
r... |
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
} | conditional_block |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used i... | q = Question(question=question,
location=GeoPt(latitude, longitude),
user=user)
q.update_location()
q.put()
# return stock JSON with the Question object details
return _json_response(question=q.to_json(), user=user.to_json())
@validate_session()
@validate_request... | # to the authenticated user | random_line_split |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used i... |
def _json_unauthorized_response(**kwargs):
"""
Helper method to build an HTTPResponse with a stock JSON object
that represents unauthorized access to an API method.
NOTE: Always returns success=false and msg="Unauthorized"
@kwargs: any number of key/value pairs to be sent with the JSON object
... | """
Helper method to build an HTTPResponse with a stock
JSON object.
@param success=True: indicates success or failure of the API method
@param msg: string with details on success or failure
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# build up the response... | identifier_body |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used i... |
# Pull the User from the datastore
user = users.get()
# Build a new session object and store the user
session = Session()
session["user"] = user
# return stock JSON with user details
return _json_response(user=user.to_json())
# Utility method for generating random questions around a
# ... | return _json_response(details=None,
success=False,
msg="Internal security error. Contact an administrator") | conditional_block |
api.py | ##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used i... | (method, *params):
"""
Decorator for validating the required request method for an API call as
well as enforcing any required parameters in the request. If either the
method or parameter checks fail a stock failure JSON object is returned
with the exact issue in the msg field. If all checks pass the... | validate_request | identifier_name |
testText.ts | import {delay} from './delay'
import { Laya } from 'Laya';
import { Text } from 'laya/display/Text';
import { TextRender } from 'laya/webgl/text/TextRender';
export class Main {
constructor() |
/**
* 某张文字贴图的一部分被释放后,应该能正确恢复。
* 有cacheas normal的情况
*/
async test1(){
// 先创建两个文字贴图,由于字体较大,4个字就占一张图。
var t1 = new Text();
t1.fontSize = 120;
t1.text = 'abcd'; // 1是 abcd
t1.color='red';
t1.cacheAs='normal';
Laya.stage.addChild(t1)... | {
Laya.init(800,600);
//Laya.stage.scaleMode = 'fixedwidth';
Laya.stage.screenMode = 'none';
//Laya.Stat.show();
this.test1();
} | identifier_body |
testText.ts | import {delay} from './delay'
import { Laya } from 'Laya';
import { Text } from 'laya/display/Text';
import { TextRender } from 'laya/webgl/text/TextRender';
export class Main {
| () {
Laya.init(800,600);
//Laya.stage.scaleMode = 'fixedwidth';
Laya.stage.screenMode = 'none';
//Laya.Stat.show();
this.test1();
}
/**
* 某张文字贴图的一部分被释放后,应该能正确恢复。
* 有cacheas normal的情况
*/
async test1(){
// 先创建两个文字贴图,由于字体较大,4个字就占一张图。
var t1 = new... | constructor | identifier_name |
testText.ts | import {delay} from './delay'
import { Laya } from 'Laya';
import { Text } from 'laya/display/Text';
import { TextRender } from 'laya/webgl/text/TextRender';
export class Main { | //Laya.stage.scaleMode = 'fixedwidth';
Laya.stage.screenMode = 'none';
//Laya.Stat.show();
this.test1();
}
/**
* 某张文字贴图的一部分被释放后,应该能正确恢复。
* 有cacheas normal的情况
*/
async test1(){
// 先创建两个文字贴图,由于字体较大,4个字就占一张图。
var t1 = new Text();
t1.fontSize = 12... | constructor() {
Laya.init(800,600); | random_line_split |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.rea... | (text, color='red'):
color_dict = {
'red': '\033[31m',
}
print color_dict[color]+text+'\033[0m',
def fetch_result():
while 1:
try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')... | colorful_print | identifier_name |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.rea... |
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() != 'status':
#login()
submit_code()
fetch_result()
if __name__ == '__main__':
main()
| while 1:
try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')[7:13]:
flag = 0
for td in tr('td'):
if user in td.text:
flag = 1
break
elif ... | identifier_body |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.rea... |
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() != 'status':
#login()
submit_code()
fetch_result()
if __name__ == '__main__':
main()
| try:
r = s.get('http://acm.timus.ru/status.aspx?space=1')
soup = BeautifulSoup(r.text)
os.system('cls')
time.sleep(0.2)
for tr in soup('tr')[7:13]:
flag = 0
for td in tr('td'):
if user in td.text:
flag = 1
break
elif 'BoardHome' i... | conditional_block |
submit.py | #!/usr/bin/env python2
"""
submit.py
~~~~~~~~~
submit code to poj
usage:
./submit.py file_name
file_name format: probmenId_xxx.c/cpp
"""
import requests
import sys
import os
import time
from bs4 import BeautifulSoup
s = requests.Session()
try:
with open('./user') as fi:
user = fi.rea... | if flag == 2:
continue
for td in tr('td'):
if flag:
colorful_print(td.text)
else:
print td.text,
print
print '-' * 100
time.sleep(1)
except KeyboardInterrupt:
exit(0)
def main():
if len(sys.argv) > 1 and sys.argv[1].l... | random_line_split | |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn | (input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we w... | encryption_oracle | identifier_name |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
... | {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91... | identifier_body | |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
... | else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b... | {
input.push('A' as u8);
} | conditional_block |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
... | let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_blo... |
let out = encryption_oracle(&input, &unknown, &key);
| random_line_split |
general_tests.rs |
#[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug... | {
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestCompon... | identifier_body | |
general_tests.rs | #[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug,... | )
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn process(&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl E... | hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
) | random_line_split |
general_tests.rs |
#[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug... | (&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut Data... | process | identifier_name |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive sh... | if (visSlopeStart < visSlopeEnd) { return; }
for (let i = row; i <= radius; i++) {
let dx = -i - 1;
let dy = -i;
let blocked = false;
let newStart = 0;
//'Row' could be column, names here assume octant 0 and would be flipped for half the octants
while (dx <= 0) {
dx += 1;
//Translate fro... | identifier_body | |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive sh... |
//Block has ended
blocked = false;
visSlopeStart = newStart;
}
}
if (blocked) { break; }
}
}
}
| newStart = slopeEnd;
continue;
}
| conditional_block |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive sh... | : number, y: number, R: number, dir: number, callback: VisibilityCallback) {
//You can always see your own tile
callback(x, y, 0, 1);
let previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees
this._renderOctant(x, y, OCTANTS[dir], R, callback);
this._renderOcta... | mpute90(x | identifier_name |
recursive-shadowcasting.ts | import FOV, { VisibilityCallback } from "./fov.js";
/** Octants used for translating recursive shadowcasting offsets */
const OCTANTS = [
[-1, 0, 0, 1],
[ 0, -1, 1, 0],
[ 0, -1, -1, 0],
[-1, 0, 0, -1],
[ 1, 0, 0, -1],
[ 0, 1, -1, 0],
[ 0, 1, 1, 0],
[ 1, 0, 0, 1]
];
/**
* @class Recursive sh... | * Render one octant (45-degree arc) of the viewshed
* @param {int} x
* @param {int} y
* @param {int} octant Octant to be rendered
* @param {int} R Maximum visibility radius
* @param {function} callback
*/
_renderOctant(x: number, y: number, octant: number[], R: number, callback: VisibilityCallback) {
/... | }
/** | random_line_split |
htmltabledatacellelement.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::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::H... |
}
impl HTMLTableDataCellElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement... | {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementType... | identifier_body |
htmltabledatacellelement.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::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::H... | }
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
... | fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
... | random_line_split |
htmltabledatacellelement.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::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::H... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
... | new | identifier_name |
constants.py | SEFARIA_API_NODE = "https://www.sefaria.org/api/texts/"
CACHE_MONITOR_LOOP_DELAY_IN_SECONDS = 86400
CACHE_LIFETIME_SECONDS = 604800
category_colors = {
"Commentary": "#4871bf",
"Tanakh": "#004e5f",
"Midrash": "#5d956f",
"Mishnah": "#5a99b7",
"Talmud": "#c... | "Responsa": "#cb6158",
"Apocrypha": "#c7a7b4",
"Other": "#073570",
"Quoting Commentary": "#cb6158",
"Sheets": "#7c406f",
"Community": "#7c406f",
"Targum": "#7f85a9",
"Modern Works": "#7c406f",
"Modern Commentary": "#7c406f",
}
pl... | "Chasidut": "#97b386",
"Musar": "#7c406f", | random_line_split |
main.ts | import { ComponentDoc, Documentation } from './Documentation'
import { DocGenOptions, parseFile, ParseOptions, parseSource as parseSourceLocal } from './parse'
export { ScriptHandler, TemplateHandler } from './parse'
export { ComponentDoc, DocGenOptions, ParseOptions, Documentation }
export function parse(
filePath:... | {
const doc = new Documentation()
const options: ParseOptions = isOptionsObject(opts)
? { ...opts, filePath }
: { filePath, alias: opts }
createDoc(doc, options)
return doc.toObject()
} | identifier_body | |
main.ts | import { ComponentDoc, Documentation } from './Documentation'
import { DocGenOptions, parseFile, ParseOptions, parseSource as parseSourceLocal } from './parse'
export { ScriptHandler, TemplateHandler } from './parse'
export { ComponentDoc, DocGenOptions, ParseOptions, Documentation }
export function parse(
filePath:... | (opts: any): opts is DocGenOptions {
return !!opts && !!opts.alias
}
function parsePrimitive(
createDoc: (doc: Documentation, opts: ParseOptions) => void,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
const doc = new Documentation()
const options: ParseOptions = is... | isOptionsObject | identifier_name |
main.ts | import { ComponentDoc, Documentation } from './Documentation'
import { DocGenOptions, parseFile, ParseOptions, parseSource as parseSourceLocal } from './parse'
export { ScriptHandler, TemplateHandler } from './parse'
export { ComponentDoc, DocGenOptions, ParseOptions, Documentation }
export function parse(
filePath:... | function isOptionsObject(opts: any): opts is DocGenOptions {
return !!opts && !!opts.alias
}
function parsePrimitive(
createDoc: (doc: Documentation, opts: ParseOptions) => void,
filePath: string,
opts?: DocGenOptions | { [alias: string]: string },
): ComponentDoc {
const doc = new Documentation()
const op... | random_line_split | |
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenge... | let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
} | random_line_split | |
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenge... | () -> String {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
}
| execute | identifier_name |
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenge... | {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
} | identifier_body | |
import.rs | // Copyright 2012-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-MI... | //~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn bar() { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() {
zed::foo(); //~ ERROR `foo` is private
bar();
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432] | random_line_split |
import.rs | // Copyright 2012-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-MI... | {
zed::foo(); //~ ERROR `foo` is private
bar();
} | identifier_body | |
import.rs | // Copyright 2012-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-MI... | () { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() {
zed::foo(); //~ ERROR `foo` is private
bar();
}
| bar | identifier_name |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
} | use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window c... | random_line_split | |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn | () {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const ... | test_headless | identifier_name |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() | {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);... | identifier_body | |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() {
let width: i32 = 256;
let height: i32 = 256;
le... |
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.Re... | {
panic!("Error while creating the framebuffer");
} | conditional_block |
ConfigVariable-extensions.py |
def __str__(self):
return self.getStringValue()
def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self):
|
def __int__(self):
return int(self.getValue())
def __long__(self):
return long(self.getValue())
def __float__(self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValue())
def __oct__(self):
return oct(self.getValue())
def... | from pandac.Notify import Notify
self.write(Notify.out()) | identifier_body |
ConfigVariable-extensions.py |
def __str__(self):
return self.getStringValue()
def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self):
from pandac.Notify import Notify
self.write(Notify.out())
def __int__(self):
return int(self.getValue())
def __lon... |
return self.getWord(n)
def __setitem__(self, n, value):
if n < 0 or n > self.getNumWords():
raise IndexError
self.setWord(n, value)
| raise IndexError | conditional_block |
ConfigVariable-extensions.py | def __str__(self):
return self.getStringValue()
| from pandac.Notify import Notify
self.write(Notify.out())
def __int__(self):
return int(self.getValue())
def __long__(self):
return long(self.getValue())
def __float__(self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValu... | def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self): | random_line_split |
ConfigVariable-extensions.py |
def __str__(self):
return self.getStringValue()
def __hash__(self):
raise AttributeError, "ConfigVariables are not immutable."
def ls(self):
from pandac.Notify import Notify
self.write(Notify.out())
def __int__(self):
return int(self.getValue())
def __lon... | (self):
return float(self.getValue())
def __nonzero__(self):
return bool(self.getValue())
def __oct__(self):
return oct(self.getValue())
def __hex__(self):
return hex(self.getValue())
def __cmp__(self, other):
return self.getValue().__cmp__(other)
def __n... | __float__ | identifier_name |
forms.py | #
# Copyright (C) 2014 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | (forms.Form):
"""Form for searching for ip-devices and interfaces"""
query = forms.CharField(
label='',
widget=forms.TextInput(
attrs={'placeholder': 'Search for ip device or interface'}))
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwa... | SearchForm | identifier_name |
forms.py | #
# Copyright (C) 2014 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | """Form for searching for ip-devices and interfaces"""
query = forms.CharField(
label='',
widget=forms.TextInput(
attrs={'placeholder': 'Search for ip device or interface'}))
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.... | identifier_body | |
forms.py | #
# Copyright (C) 2014 Uninett AS
# | # NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABIL... | # This file is part of Network Administration Visualized (NAV).
# | random_line_split |
test_mnistplus.py | """
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_... | """
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, test sets.
Tests that a topological batch has 4 dimensions.
Tests that it work well with selected type of augmentation.
"""
skip_if_no_data()
for subset in ['train', 'valid', 'test']:
ids = MNISTPl... | identifier_body | |
test_mnistplus.py | """
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_... |
train_y = MNISTPlus(which_set='train', label_type='label')
assert 0.99 <= train_y.X.max() <= 1.0
assert 0.0 <= train_y.X.min() <= 0.01
assert train_y.y.max() == 9
assert train_y.y.min() == 0
assert train_y.y.shape == (train_y.X.shape[0], 1)
train_y = MNISTPlus(which_set='train', label_typ... | ids = MNISTPlus(which_set=subset)
assert 0.01 >= ids.X.min() >= 0.0
assert 0.99 <= ids.X.max() <= 1.0
topo = ids.get_batch_topo(1)
assert topo.ndim == 4
del ids | conditional_block |
test_mnistplus.py | """ | views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_if_no_data
import numpy as np
def test_MNISTPlus():
"""
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, ... | This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological | random_line_split |
test_mnistplus.py | """
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_... | ():
"""
Test the MNISTPlus warper.
Tests the scale of data, the splitting of train, valid, test sets.
Tests that a topological batch has 4 dimensions.
Tests that it work well with selected type of augmentation.
"""
skip_if_no_data()
for subset in ['train', 'valid', 'test']:
ids =... | test_MNISTPlus | identifier_name |
when.ts | import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { ArrayObserver, splice } from 'observe-js';
import { ChangeNotification, Model, TypedChangeNotification } from './model';
import * as isFunction from 'lodash.isfunction';
import * as isObject from 'lodash.isobject';... |
const defaultResultPredicate = (v: any) => Array.isArray(v) ? !!v.length : !!v;
export function getResultAfterChange<T extends Model, TProp>(
target: T,
selector: (value: T) => TProp,
predicate: (value: TProp, index: number) => boolean = defaultResultPredicate,
numberOfChanges: number = 1)
: Promise<TProp> {
... | {
const propChain = functionToPropertyChain(accessor);
return fetchValueForPropertyChain(target, propChain);
} | identifier_body |
when.ts | import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { ArrayObserver, splice } from 'observe-js';
import { ChangeNotification, Model, TypedChangeNotification } from './model';
import * as isFunction from 'lodash.isfunction';
import * as isObject from 'lodash.isobject';... | (name = '') {
let ret = proxyCache.get(name);
if (ret) return ret;
ret = new Proxy(EMPTY_FN, new SelfDescribingProxyHandler(name));
proxyCache.set(name, ret);
return ret;
}
}
export function functionToPropertyChain(chain: Function): Array<string> {
let input = SelfDescribingProxyHandler.create... | create | identifier_name |
when.ts | import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { ArrayObserver, splice } from 'observe-js';
import { ChangeNotification, Model, TypedChangeNotification } from './model';
import * as isFunction from 'lodash.isfunction';
import * as isObject from 'lodash.isobject';... | export function whenProperty<TSource, TProp1, TProp2, TRet>(
target: TSource,
prop1: PropSelector<TSource, TProp1>,
prop2: PropSelector<TSource, TProp2>,
sel: ((p1: TypedChangeNotification<TSource, TProp1>, p2: TypedChangeNotification<TSource, TProp2>) => TRet)):
Observable<TypedChangeNotification<TSo... | prop: PropSelector<TSource, TRet>):
Observable<TypedChangeNotification<TSource, TRet>>;
| random_line_split |
settestpath.py | # yum-rhn-plugin - RHN support for yum
#
# Copyright (C) 2006 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public Licens... | # (at your option) any later version.
# | random_line_split |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct | {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
}
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv",... | StressedPacket | identifier_name |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct StressedPacket {
writer : i32,
n : i32,
}
fn writer(out : S... |
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
... | {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
} | identifier_body |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct StressedPacket {
writer : i32,
n : i32,
}
fn writer(out : S... | }
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &in... | _ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => () | random_line_split |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
... |
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, ... | {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
} | identifier_body |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
... | var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, ... |
// CANCEL BUTTON | random_line_split |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
... | () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
}
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $inp... | showEditorForm | identifier_name |
editor.js | (function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
... |
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blo... | {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
} | conditional_block |
Users.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) {
... | if (user.image) {
avatar = <img className="avatar" alt="avatar" src={user.image.data} />;
} else {
avatar = <UserIcon className="avatar" />;
}
return (
<Link className={classNames.join(' ')} to={`/users/${user._id}`}>
<div className="item">
<span className="box--row box--static">
... | }
let avatar; | random_line_split |
Users.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) {
... | extends List {}
Users.defaultProps = {
...List.defaultProps,
category: 'users',
adminable: false,
Item,
path: '/users',
sort: '-modified name email',
title: 'People',
};
| Users | identifier_name |
Users.js | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) |
let avatar;
if (user.image) {
avatar = <img className="avatar" alt="avatar" src={user.image.data} />;
} else {
avatar = <UserIcon className="avatar" />;
}
return (
<Link className={classNames.join(' ')} to={`/users/${user._id}`}>
<div className="item">
<span className="box--row box-... | {
classNames.push(className);
} | conditional_block |
methodelement.ts | import {defineClass} from './decorator.js'
import {Method, method} from './mixin.js'
@defineClass('method-ts')
export default class MethodElement extends method(HTMLElement) {
state:object = {}
constructor() {
super()
} | selector(select:HTMLSelectElement, json:any){
const data:Method[] = json.data
data.forEach((v)=>{
const option = document.createElement('option')
option.value = v.id
option.innerText = v.description
select.appendChild(option)
})
}
connectedCallback() {
const root = this.a... | random_line_split | |
methodelement.ts | import {defineClass} from './decorator.js'
import {Method, method} from './mixin.js'
@defineClass('method-ts')
export default class MethodElement extends method(HTMLElement) {
state:object = {}
constructor() {
super()
}
selector(select:HTMLSelectElement, json:any){
const data:Method[] = json.data
... |
}
| { } | identifier_body |
methodelement.ts | import {defineClass} from './decorator.js'
import {Method, method} from './mixin.js'
@defineClass('method-ts')
export default class MethodElement extends method(HTMLElement) {
state:object = {}
constructor() {
super()
}
selector(select:HTMLSelectElement, json:any){
const data:Method[] = json.data
... | () {
const root = this.attachShadow({mode: 'open'});
root.innerHTML = `<slot name="input"></slot>`
const select = this.querySelector('select')
this.method()
.then(json => this.selector(select!, json))
.catch(err => console.log(err))
}
disconnectedCallback() { }
attributeChangedCallba... | connectedCallback | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~Scro... | window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext); | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &g... | {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
} | identifier_body |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | (&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
stru... | call | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| { println("Cursor left window."); } | conditional_block |
definition_spec.ts | import "../spec_helper";
describe("Definition#buildModel", function () {
class LocalType extends Factory.Model {
public id: number;
}
const getDef = (cb: Function): Factory.Definition => Factory.define("test", cb);
it("must build model without given attributes", function () {
const de... | });
it("must define field using this notation", function () {
const definition = getDef(function () {
this.id = 234;
});
expect(function () {
definition.buildModel({id: 1})
}).not.toThrowError("Unexpected data: [\"id\"]");
});
it("must define fie... | const definition: Factory.Definition = getDef(() => {});
expect(function () {
definition.buildModel({id: 1})
}).toThrowError("Unexpected data: [\"id\"]"); | random_line_split |
definition_spec.ts | import "../spec_helper";
describe("Definition#buildModel", function () {
class | extends Factory.Model {
public id: number;
}
const getDef = (cb: Function): Factory.Definition => Factory.define("test", cb);
it("must build model without given attributes", function () {
const definition: Factory.Definition = getDef(function () { });
expect(definition.buildModel<... | LocalType | identifier_name |
TestMNITagPoints.py | #!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Test label reading from an MNI tag file
#
# The current directory must be writeable.
#
try:
fname = "mni-tagtest.tag"
channel = open(fname, "wb")
... | xform.RotateWXYZ(20, 1, 0, 0)
xformFilter = vtk.vtkTransformFilter()
xformFilter.SetTransform(xform)
xformFilter.SetInputConnection(sphere1.GetOutputPort())
labels = vtk.vtkStringArray()
labels.InsertNextValue("0")
labels.InsertNextValue("1")
labels.InsertNextValue("2")
l... |
xform = vtk.vtkTransform()
| random_line_split |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
... |
if coordinate.name == exclude.name:
return True
return False
| return True | conditional_block |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
... | (self, other):
return not self == other
def __repr__(self):
return 'ClasspathEntry(path={!r}, directory_digest={!r})'.format(
self.path,
self.directory_digest,
)
@classmethod
def is_artifact_classpath_entry(cls, classpath_entry):
"""
:API: public
"""
return isinstance(cla... | __ne__ | identifier_name |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
... |
def _matches_exclude(coordinate, exclude):
if not coordinate.org == exclude.org:
return False
if not exclude.name:
return True
if coordinate.name == exclude.name:
return True
return False
| return (
'ArtifactClasspathEntry(path={!r}, coordinate={!r}, cache_path={!r}, directory_digest={!r})'
.format(self.path, self.coordinate, self.cache_path, self.directory_digest)
) | identifier_body |
classpath_entry.py | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
class ClasspathEntry(object):
"""Represents a java classpath entry.
:API: public
... | self._directory_digest = directory_digest
@property
def path(self):
"""Returns the pants internal path of this classpath entry.
Suitable for use in constructing classpaths for pants executions and pants generated artifacts.
:API: public
:rtype: string
"""
return self._path
@proper... | def __init__(self, path, directory_digest=None):
self._path = path | random_line_split |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db... |
else:
sql = """
SELECT {select} FROM {table};
""".format(select='*', table=args.table)
print sql
cursor.execute(sql)
colnames = [desc[0] for desc in cursor.description]
data = pd.DataFrame(cursor.fetchall(), columns=colnames)
# Set args.data, so we can pass only args to funct... | with open(args.query, 'r') as infile:
sql = ''.join(list(infile)) | conditional_block |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db... | plt.title("N = {}".format(data.shape[0]))
def plot_distribution(args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtu... | plt.xlabel(args.hist2d[0])
plt.ylabel(args.hist2d[1])
set_plot_limits(plt, args) | random_line_split |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db... | (args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtus]
print 'after filtering size =', data.shape[0]
if args.... | plot_distribution | identifier_name |
plot_distribution.py | """
Plots a scatter plot of 2 metrics provided.
Data could be given from postgres or a csv file.
"""
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from common import add_db... |
def plot_distribution(args):
if args.csv is not None:
data = pd.read_csv(args.csv)
print ' '.join(list(data.columns.values))
if args.filter_num_rtus:
print 'before filtering size =', data.shape[0]
data = data[data['num_rtus'] == args.filter_num_rtus]
print 'after filtering size =', da... | data = data[data[args.hist2d[0]].notnull()][data[args.hist2d[1]].notnull()]
if data.shape[0] < 1000:
sys.exit(1)
df = data.replace([np.inf, -np.inf], np.nan).dropna(subset=args.hist2d)
plt.hist2d(df[args.hist2d[0]].astype(float),
df[args.hist2d[1]].astype(float),
bins=args.histogram_... | identifier_body |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieP... | rs.loadDirectory("./eg/brain", function() {
rs.sortReplies();
onReady();
});
// This is a function for delivering the message to a user. Its actual
// implementation could vary; for example if you were writing an IRC chatbot
// this message could deliver a private message to a target username... |
// Load the replies and process them. | random_line_split |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieP... | else {
username = "guest" + guest++;
console.log(username);
res.cookie('username', username, { maxAge: 100000 * 60 });
}
/*
if (username == undefined) {
username = "guest" + guest++;
};
*/
console.log(username);
// Make sure username and message are included.
if (typeo... | {
username = req.cookies.username;
} | conditional_block |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieP... | ;
// All other routes shows the usage to test the /reply route.
function showUsage(req, res) {
var egPayload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso"
}
};
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Usage: curl -i \\\n");
res.write(" -H \"Conte... | {
// Get data from the JSON post.
var message = req.body.message;
var vars = req.body.vars;
var username = req.body.username;
if (req.cookies.username) {
username = req.cookies.username;
} else {
username = "guest" + guest++;
console.log(username);
res.cookie('username', username, { ... | identifier_body |
server.js | // Run this with: `node server.js` or npm start
"use strict";
var readline = require("readline");
var colors = require('colors');
var rs = require("./rs");
// This would just be require("rivescript") if not for running this
// example from within the RiveScript project.
var express = require("express"),
cookieP... | (res, message) {
res.json({
"status": "error",
"message": message
});
}
| error | identifier_name |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function gameObj(eventId, name, image, rules, scoreType) {
this.eventId = eventId;
this.name = name; // str
thi... | this.showHeader = true;
this.title = 'Games';
this.addingGame = ko.observable(false);
this.imgSrc = function() {
var randomNum1 = Math.round((Math.random()*100+300)/10)*10;
var randomNum2 = Math.round((Math.random()*100+200)/10)*10;
return "http://pla... | random_line_split | |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function gameObj(eventId, name, image, rules, scoreType) |
self.games = ko.observableArray([]);
function getGames() {
// http.get(app.url+'event/78f9075c-f81c-42fe-9d50-63e666b5450d/games').then(function(response) {
// for(var i = 0; i < response.items.length; i++) {
// self.games.push(new gameObj("NAME", respon... | {
this.eventId = eventId;
this.name = name; // str
this.image = image; // url
this.rules = rules; // str
this.scoreType = scoreType; // str
} | identifier_body |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function | (eventId, name, image, rules, scoreType) {
this.eventId = eventId;
this.name = name; // str
this.image = image; // url
this.rules = rules; // str
this.scoreType = scoreType; // str
}
self.games = ko.observableArray([]);
function getGam... | gameObj | identifier_name |
games.js | define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) {
var ctor = function () {
var self = this;
function gameObj(eventId, name, image, rules, scoreType) {
this.eventId = eventId;
this.name = name; // str
thi... |
});
};
getGames();
};
return ctor;
}); | {
console.dir(result);
//http.post(app.url+'event/'+app.event.id+'/games/', JSON.stringify(result)).then(function(response) {
self.games.unshift(new gameObj(result.eventId, result.name, "", result.rules, result.scoreType));
//});
... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.