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
_pydev_jy_imports_tipper.py
args, varargs, varkw args = getargs(func.func_code) return 1, [Info(func.func_name, args=args[0], varargs=args[1], kwargs=args[2], doc=func.func_doc)] if isinstance(func, core.PyMethod): #this is something from java itself, and jython just wrapped i...
if len(r) > 0: r += ', ' r += formatArg(a)
conditional_block
_pydev_jy_imports_tipper.py
kw = func_code.co_varnames[nargs] return args, varargs, varkw args = getargs(func.func_code) return 1, [Info(func.func_name, args=args[0], varargs=args[1], kwargs=args[2], doc=func.func_doc)] if isinstance(func, core.PyMethod): #this ...
r = '' for a in (args): if len(r) > 0:
random_line_split
_pydev_jy_imports_tipper.py
f = mod.__file__ else: if len(foundAs) > 0: foundAs = foundAs + '.' foundAs = foundAs + comp old_comp = comp return f, mod, parent, foundAs def formatParamClassName(paramClassName): if paramClassName.startswith('['): if para...
def basicAsStr(self): '''@returns this class information as a string (just basic format) ''' s = 'function:%s args=%s, varargs=%s, kwargs=%s, docs:%s' % \ (str(self.name), str(self.args), str(self.varargs), str(self.kwargs), str(self.doc)) return s ...
self.name = name self.doc = kwargs.get('doc', None) self.args = kwargs.get('args', ()) #tuple of strings self.varargs = kwargs.get('varargs', None) #string self.kwargs = kwargs.get('kwargs', None) #string self.ret = kwargs.get('ret', None) #string
identifier_body
_pydev_jy_imports_tipper.py
f = mod.__file__ else: if len(foundAs) > 0: foundAs = foundAs + '.' foundAs = foundAs + comp old_comp = comp return f, mod, parent, foundAs def formatParamClassName(paramClassName): if paramClassName.startswith('['): if para...
(func): '''this function should return the information gathered on a function @param func: this is the function we want to get info on @return a tuple where: 0 = indicates whether the parameter passed is a method or not 1 = a list of classes 'Info', with the info gathered from the funct...
ismethod
identifier_name
event.rs
#[cfg(not(any(test, rustdoc)))] #[allow(unused_imports)] use alloc::prelude::v1::*; #[cfg(any(test, rustdoc))] #[allow(unused_imports)] use std::prelude::v1::*; use crate::event::Event; use crate::DRIVERS; pub fn driver_event_handler(ev: Event)
pub fn framework_event_handler(ev: Event) { if ev.class != "framework" { return; } // assume subclass is framework name if let Some(driver) = DRIVERS.get().find_framework_by_name(&ev.subclass) { driver.get().handle_event(ev); } }
{ if ev.class != "driver" { return; } // assume the subclass is the driver ID, and convert it to a usize let id = match ev.subclass.parse::<usize>() { Ok(i) => i, _ => return, }; // find driver with given id if let Some(driver) = DRIVERS.get().find_by_id(id) { ...
identifier_body
event.rs
#[cfg(any(test, rustdoc))] #[allow(unused_imports)] use std::prelude::v1::*; use crate::event::Event; use crate::DRIVERS; pub fn driver_event_handler(ev: Event) { if ev.class != "driver" { return; } // assume the subclass is the driver ID, and convert it to a usize let id = match ev.subclass....
#[cfg(not(any(test, rustdoc)))] #[allow(unused_imports)] use alloc::prelude::v1::*;
random_line_split
event.rs
#[cfg(not(any(test, rustdoc)))] #[allow(unused_imports)] use alloc::prelude::v1::*; #[cfg(any(test, rustdoc))] #[allow(unused_imports)] use std::prelude::v1::*; use crate::event::Event; use crate::DRIVERS; pub fn driver_event_handler(ev: Event) { if ev.class != "driver" { return; } // assume the ...
}
{ driver.get().handle_event(ev); }
conditional_block
event.rs
#[cfg(not(any(test, rustdoc)))] #[allow(unused_imports)] use alloc::prelude::v1::*; #[cfg(any(test, rustdoc))] #[allow(unused_imports)] use std::prelude::v1::*; use crate::event::Event; use crate::DRIVERS; pub fn driver_event_handler(ev: Event) { if ev.class != "driver" { return; } // assume the ...
(ev: Event) { if ev.class != "framework" { return; } // assume subclass is framework name if let Some(driver) = DRIVERS.get().find_framework_by_name(&ev.subclass) { driver.get().handle_event(ev); } }
framework_event_handler
identifier_name
utils.js
// Make inheritance bearable: clone one level of properties MM.extend = function(child, parent) { for (var property in parent.prototype) { if (typeof child.prototype[property] == "undefined") { child.prototype[property] = parent.prototype[property]; } } ...
MM.moveElement = function(el, point) { if (MM.transformProperty) { // Optimize for identity transforms, where you don't actually // need to change this element's string. Browsers can optimize for // the .style.left case but not for this CSS case. if (!point.s...
webkit: ('WebKitCSSMatrix' in window), webkit3d: ('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()) }; })(this); // use this for node.js global
random_line_split
settings.py
""" Django settings for untitled project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import o...
'datefmt': '%H:%M:%S', } }, 'filters': { 'ignore_get_current_task': { '()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not (len(r.args) > 2 and r.args[1] == '200' and r.args[0] == 'GET /get_current_task HTTP/1.1'), } }, 'handlers'...
random_line_split
transport.py
9, OpenCensus 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 writing, softwar...
def _transmit(self, envelopes): """ Transmit the data envelopes to the ingestion service. Return a negative value for partial success or non-retryable failure. Return 0 if all envelopes have been successfully ingested. Return the next retry time in seconds for retryable fai...
if self.storage: for blob in self.storage.gets(): # give a few more seconds for blob lease operation # to reduce the chance of race (for perf consideration) if blob.lease(self.options.timeout + 5): envelopes = blob.get() ...
identifier_body
transport.py
19, OpenCensus 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 writing, softwa...
(self): if self.storage: for blob in self.storage.gets(): # give a few more seconds for blob lease operation # to reduce the chance of race (for perf consideration) if blob.lease(self.options.timeout + 5): envelopes = blob.get() ...
_transmit_from_storage
identifier_name
transport.py
19, OpenCensus 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 writing, softwa...
logger.error( 'Error while processing %s: %s %s.', response.status_code, text, ex, ) if self._check_stats_collection(): with _requests_lock: ...
if data: try: resend_envelopes = [] for error in data['errors']: if error['statusCode'] in ( 429, # Too Many Requests 500, # Internal Server Error ...
conditional_block
transport.py
19, OpenCensus 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 writing, softwa...
with _requests_lock: _requests_map['success'] = _requests_map.get('success', 0) + 1 # noqa: E501 return 0 # Status code not 200 counts as failure if self._check_stats_collection(): with _requests_lock: _requests_map['failure'] ...
random_line_split
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2017 Phyks (Lucas Verney) # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 o...
(self): l = list(self.backend.iter_gauges()) assert len(l) == 26 def test_ratp_gauges_filter(self): l = list(self.backend.iter_gauges(pattern="T3A")) assert len(l) == 1 def test_ratp_sensors(self): l = list(self.backend.iter_sensors("ligne_metro_4")) assert len(...
test_ratp_gauges
identifier_name
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2017 Phyks (Lucas Verney) # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 o...
def test_ratp_sensors(self): l = list(self.backend.iter_sensors("ligne_metro_4")) assert len(l) == 1 def test_ratp_status(self): m = self.backend.get_last_measure("ligne_metro_4_sensor") assert m.level <= 0.0
l = list(self.backend.iter_gauges(pattern="T3A")) assert len(l) == 1
identifier_body
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2017 Phyks (Lucas Verney) # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 o...
def test_ratp_gauges(self): l = list(self.backend.iter_gauges()) assert len(l) == 26 def test_ratp_gauges_filter(self): l = list(self.backend.iter_gauges(pattern="T3A")) assert len(l) == 1 def test_ratp_sensors(self): l = list(self.backend.iter_sensors("ligne_metro_...
random_line_split
nvd3-test-tooltip.ts
/// <reference path="../d3/d3.d.ts" /> /// <reference path="nvd3.d.ts" /> module nvd3_test_tooltip { var width = 500, height = 20; var tooltip = nv.models.tooltip(); tooltip.duration(0); d3.select('.tooltip_me') .on('mouseover', function (d, i) { console.log("mouseover", d,...
() { var cos = []; for (var i = 0; i < 5; i++) { cos.push({ x: i, y: Math.round(.5 * Math.cos(i / 10) * 100) / 100 }); } return [{ values: cos, key: "Cosine Wave", color: "#2ca02c" }]; } }
sinAndCos
identifier_name
nvd3-test-tooltip.ts
/// <reference path="../d3/d3.d.ts" /> /// <reference path="nvd3.d.ts" /> module nvd3_test_tooltip { var width = 500, height = 20; var tooltip = nv.models.tooltip(); tooltip.duration(0); d3.select('.tooltip_me') .on('mouseover', function (d, i) { console.log("mouseover", d,...
} }
random_line_split
nvd3-test-tooltip.ts
/// <reference path="../d3/d3.d.ts" /> /// <reference path="nvd3.d.ts" /> module nvd3_test_tooltip { var width = 500, height = 20; var tooltip = nv.models.tooltip(); tooltip.duration(0); d3.select('.tooltip_me') .on('mouseover', function (d, i) { console.log("mouseover", d,...
}
{ var cos = []; for (var i = 0; i < 5; i++) { cos.push({ x: i, y: Math.round(.5 * Math.cos(i / 10) * 100) / 100 }); } return [{ values: cos, key: "Cosine Wave", color: "#2ca02c" }]; }
identifier_body
nvd3-test-tooltip.ts
/// <reference path="../d3/d3.d.ts" /> /// <reference path="nvd3.d.ts" /> module nvd3_test_tooltip { var width = 500, height = 20; var tooltip = nv.models.tooltip(); tooltip.duration(0); d3.select('.tooltip_me') .on('mouseover', function (d, i) { console.log("mouseover", d,...
return [{ values: cos, key: "Cosine Wave", color: "#2ca02c" }]; } }
{ cos.push({ x: i, y: Math.round(.5 * Math.cos(i / 10) * 100) / 100 }); }
conditional_block
rocket.js
class Rocket { constructor( context, canvasWidth, canvasHeight, width, height, orientationDirection, rotationRate, xVector, yVector, x, y, color) { // "this" refers to the instance of Rocket that I'm currently working with // Add properties to "this" when each instance of the class sho...
// Draw a triangle with paths context.strokeStyle = this.color; // Start a new path context.beginPath(); // Now define the path with .moveTo() and .lineTo() methods var triangleOriginX = -width/2; var triangleOriginY = -height/2; context.moveTo(triangleOriginX, triangleOriginY); context.lineTo(tr...
{ this.update(); var context = this.context; var x = this.x; var y = this.y; var width = this.width; var height = this.height; var orientationDirection = this.orientationDirection; context.save(); var centerX = x + width/2; var centerY = y + height/2; context.translate(centerX, centerY); // T...
identifier_body
rocket.js
class Rocket { constructor( context, canvasWidth, canvasHeight, width, height, orientationDirection, rotationRate, xVector, yVector, x, y, color) { // "this" refers to the instance of Rocket that I'm currently working with // Add properties to "this" when each instance of the class sho...
(){ this.xVector = 0; this.yVector = 0; } draw(){ this.update(); var context = this.context; var x = this.x; var y = this.y; var width = this.width; var height = this.height; var orientationDirection = this.orientationDirection; context.save(); var centerX = x + width/2; var centerY = y +...
stopRocket
identifier_name
rocket.js
class Rocket { constructor( context, canvasWidth, canvasHeight, width, height, orientationDirection, rotationRate, xVector, yVector, x, y, color) { // "this" refers to the instance of Rocket that I'm currently working with // Add properties to "this" when each instance of the class sho...
this.orientationDirection = orientationDirection + rotationRate; break; case 40: // down this.movementRate = this.movementRate - 1; break; default: } } update(){ // var x = this.x; // x = 2; // this.x did not get changed to 2. Only the variable x got updated. // To change this.x, I hav...
case 39: // right
random_line_split
create_model.py
import argparse import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.feature_selection import RFECV from sklearn.ensemble import RandomForestClassifier from beveridge.models import ModelStorage import pickle parser = argparse.ArgumentParser(description="Create model from CSV stats data....
data['relFrees'] = data['frees'] / data['oppFrees'] data['relContested'] = data['contested'] / data['oppContested'] data['relUncontested'] = data['uncontested'] / data['oppUncontested'] data['relContestedMarks'] = data['contestedMarks'] / data['oppContestedMarks'] data['relMarksIn50'] = data['marksIn50'] / data['oppMar...
data['relClangers'] = data['clangers'] / data['oppClangers']
random_line_split
i18n.tsx
import type { Options, Value } from '@react-page/editor'; import Editor from '@react-page/editor'; import { demo } from '../../sampleContents/demo'; import React, { useState, useCallback } from 'react'; import { cellPlugins } from '../../plugins/cellPlugins'; import PageLayout from '../../components/PageLayout'; import...
nslate)`; }, []); return ( <PageLayout> <Editor cellPlugins={cellPlugins} value={value} lang={LANGUAGES[0].lang} onChange={setValue} languages={LANGUAGES} uiTranslator={uiTranslator} /> <Button onClick={reset}>Reset</Button> </PageLayout> ...
label]; } return `${label}(to tra
conditional_block
i18n.tsx
import type { Options, Value } from '@react-page/editor'; import Editor from '@react-page/editor'; import { demo } from '../../sampleContents/demo'; import React, { useState, useCallback } from 'react'; import { cellPlugins } from '../../plugins/cellPlugins'; import PageLayout from '../../components/PageLayout'; import...
const TRANSLATIONS: { [key: string]: string } = { 'Edit blocks': '编辑', 'Add blocks': '添加', 'Move blocks': '移动', 'Resize blocks': '调整大小', 'Preview blocks': '预览模式', }; export default function Home() { const [value, setValue] = useState<Value>(demo); const reset = () => setValue(demo); const uiTranslator...
];
random_line_split
i18n.tsx
import type { Options, Value } from '@react-page/editor'; import Editor from '@react-page/editor'; import { demo } from '../../sampleContents/demo'; import React, { useState, useCallback } from 'react'; import { cellPlugins } from '../../plugins/cellPlugins'; import PageLayout from '../../components/PageLayout'; import...
</PageLayout> ); }
= useState<Value>(demo); const reset = () => setValue(demo); const uiTranslator = useCallback((label?: string) => { if (TRANSLATIONS[label] !== undefined) { return TRANSLATIONS[label]; } return `${label}(to translate)`; }, []); return ( <PageLayout> <Editor cellPlugins={cell...
identifier_body
i18n.tsx
import type { Options, Value } from '@react-page/editor'; import Editor from '@react-page/editor'; import { demo } from '../../sampleContents/demo'; import React, { useState, useCallback } from 'react'; import { cellPlugins } from '../../plugins/cellPlugins'; import PageLayout from '../../components/PageLayout'; import...
e] = useState<Value>(demo); const reset = () => setValue(demo); const uiTranslator = useCallback((label?: string) => { if (TRANSLATIONS[label] !== undefined) { return TRANSLATIONS[label]; } return `${label}(to translate)`; }, []); return ( <PageLayout> <Editor cellPlugins={c...
Valu
identifier_name
trait_inheritance_overloading_xc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Eq for MyInt { fn eq(&self, other: &MyInt) -> bool { self.val == other.val } fn ne(&self, other: &MyInt) -> bool { !self.eq(other) } } impl MyNum for MyInt; fn mi(v: int) -> MyInt { MyInt { val: v } }
{ mi(self.val * other.val) }
identifier_body
trait_inheritance_overloading_xc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ val: int } impl Add<MyInt, MyInt> for MyInt { fn add(&self, other: &MyInt) -> MyInt { mi(self.val + other.val) } } impl Sub<MyInt, MyInt> for MyInt { fn sub(&self, other: &MyInt) -> MyInt { mi(self.val - other.val) } } impl Mul<MyInt, MyInt> for MyInt { fn mul(&self, other: &MyInt) -> MyInt { mi(s...
MyInt
identifier_name
trait_inheritance_overloading_xc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
random_line_split
cors.rs
use rocket::{Request, Response}; use rocket::fairing::{Fairing, Info, Kind}; use rocket::http::{Header, ContentType, Method}; use std::io::Cursor; pub struct CORS(); impl Fairing for CORS { fn info(&self) -> Info
fn on_response(&self, request: &Request, response: &mut Response) { if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON) { response.set_header(Header::new("Access-Control-Allow-Origin", "*")); response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, ...
{ Info { name: "Add CORS headers to requests", kind: Kind::Response } }
identifier_body
cors.rs
use rocket::{Request, Response}; use rocket::fairing::{Fairing, Info, Kind}; use rocket::http::{Header, ContentType, Method}; use std::io::Cursor; pub struct CORS(); impl Fairing for CORS { fn info(&self) -> Info { Info { name: "Add CORS headers to requests", kind: Kind::Response } } fn on_response(&sel...
if request.method() == Method::Options { response.set_header(ContentType::Plain); response.set_sized_body(Cursor::new("")); } } }
{ response.set_header(Header::new("Access-Control-Allow-Origin", "*")); response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, OPTIONS")); response.set_header(Header::new("Access-Control-Allow-Headers", "Content-Type")); response.set_header(Header::new("Access-Control-Allow-Credentials"...
conditional_block
cors.rs
use rocket::{Request, Response}; use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::{Header, ContentType, Method}; use std::io::Cursor; pub struct CORS(); impl Fairing for CORS { fn info(&self) -> Info { Info { name: "Add CORS headers to requests", kind: Kind::Response } } fn on_response(&self, request: &Request, response: &mut Response) { if request.method() == Met...
random_line_split
cors.rs
use rocket::{Request, Response}; use rocket::fairing::{Fairing, Info, Kind}; use rocket::http::{Header, ContentType, Method}; use std::io::Cursor; pub struct CORS(); impl Fairing for CORS { fn
(&self) -> Info { Info { name: "Add CORS headers to requests", kind: Kind::Response } } fn on_response(&self, request: &Request, response: &mut Response) { if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON) { response.set_header(Header::new("Access-Control-All...
info
identifier_name
scrollSvc.js
diamondApp.service('scrollSvc', function () { this.scrollTo = function (eID) { // This scrolling function // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance ...
function elmYPosition(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; ...
{ // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7 ...
identifier_body
scrollSvc.js
diamondApp.service('scrollSvc', function () { this.scrollTo = function (eID) { // This scrolling function // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance ...
(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; } return y; ...
elmYPosition
identifier_name
scrollSvc.js
diamondApp.service('scrollSvc', function () { this.scrollTo = function (eID) { // This scrolling function // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance ...
timer++; } function currentYPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return docume...
setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY;
random_line_split
launch_nightly_test.py
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved.
# --test-host <hostname>[:<port>] # (--email <name>@<address>)* # [--title "<Title>"] # [-- <flags for full_test_driver.py>] import sys, subprocess, os, optparse if __name__ != "__main__": raise ImportError("It doesn't make any sense to import this as a module") parser...
# Usage: ./launch_nightly_test.py
random_line_split
launch_nightly_test.py
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. # Usage: ./launch_nightly_test.py # --test-host <hostname>[:<port>] # (--email <name>@<address>)* # [--title "<Title>"] # [-- <flags for full_test_driver.py>] import sys, subprocess, os, optparse i...
tar_proc = subprocess.Popen( ["tar", "--create", "--gzip", "--file=-", "-C", os.path.dirname(__file__), "--"] + ["full_test_driver.py", "remotely.py", "simple_linear_db.py", "renderer"], stdout = subprocess.PIPE ) try: command = "SLURM_CONF=/home/teapot/slurm/slurm.conf ./full_test_driver.py %...
return "'" + arg.replace("'", "'\''") + "'"
identifier_body
launch_nightly_test.py
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. # Usage: ./launch_nightly_test.py # --test-host <hostname>[:<port>] # (--email <name>@<address>)* # [--title "<Title>"] # [-- <flags for full_test_driver.py>] import sys, subprocess, os, optparse i...
subprocess.check_call(curl_cmd_line, stdin = tar_proc.stdout) finally: try: tar_proc.terminate() except IOError: pass
curl_cmd_line += ["-F", "emailee=%s" % emailee]
conditional_block
launch_nightly_test.py
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. # Usage: ./launch_nightly_test.py # --test-host <hostname>[:<port>] # (--email <name>@<address>)* # [--title "<Title>"] # [-- <flags for full_test_driver.py>] import sys, subprocess, os, optparse i...
(arg): return "'" + arg.replace("'", "'\''") + "'" tar_proc = subprocess.Popen( ["tar", "--create", "--gzip", "--file=-", "-C", os.path.dirname(__file__), "--"] + ["full_test_driver.py", "remotely.py", "simple_linear_db.py", "renderer"], stdout = subprocess.PIPE ) try: command = "SLURM_CONF...
escape
identifier_name
dictTest.py
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import str import sys import unittest import re import os dirname = os.path.dirname(__file__) sys.path.insert(0, os.path.join(dirname, '..', '..', '..')) import uuid from SpiffWorkflow.serializer.dict import Dictiona...
elif isinstance(item1, list): msg = "item is not a list (is a " + str(type(item2)) + ")" self.assertIsInstance(item2, list, msg) msg = "list lengths differ: {} vs {}".format( len(item1), len(item2)) self.assertEqual(len(item1), len(item2), msg) ...
self.assertIn(key, item1)
conditional_block
dictTest.py
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import str import sys import unittest import re import os dirname = os.path.dirname(__file__) sys.path.insert(0, os.path.join(dirname, '..', '..', '..')) import uuid from SpiffWorkflow.serializer.dict import Dictiona...
if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite())
return unittest.defaultTestLoader.loadTestsFromTestCase(DictionarySerializerTest)
identifier_body
dictTest.py
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import str import sys import unittest import re import os dirname = os.path.dirname(__file__) sys.path.insert(0, os.path.join(dirname, '..', '..', '..')) import uuid from SpiffWorkflow.serializer.dict import Dictiona...
(): return unittest.defaultTestLoader.loadTestsFromTestCase(DictionarySerializerTest) if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite())
suite
identifier_name
dictTest.py
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import str import sys import unittest import re import os dirname = os.path.dirname(__file__) sys.path.insert(0, os.path.join(dirname, '..', '..', '..')) import uuid from SpiffWorkflow.serializer.dict import Dictiona...
if 'last_task' not in exclude_items: exclude_items.append('last_task') if uuid.UUID not in exclude_items: exclude_items.append(uuid.UUID) if type(item1) in exclude_items: return if isinstance(item1, dict): self.assertIsInst...
exclude_items = exclude_items if exclude_items is not None else [] if exclude_dynamic: if 'last_state_change' not in exclude_items: exclude_items.append('last_state_change')
random_line_split
show.py
# This file is part of VoltDB. # Copyright (C) 2008-2016 VoltDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ver...
@VOLT.Multi_Command( bundles = VOLT.AdminBundle(), description = 'Display information about a live database.', modifiers = VOLT.Modifier('snapshots', show_snapshots, 'Display current snapshot status.') ) def show(runner): runner.go()
response = runner.call_proc('@SnapshotStatus', [], []) print response.table(0).format_table(caption = 'Snapshot Status')
identifier_body
show.py
# This file is part of VoltDB. # Copyright (C) 2008-2016 VoltDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ver...
(runner): runner.go()
show
identifier_name
show.py
# This file is part of VoltDB. # Copyright (C) 2008-2016 VoltDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ver...
@VOLT.Multi_Command( bundles = VOLT.AdminBundle(), description = 'Display information about a live database.', modifiers = VOLT.Modifier('snapshots', show_snapshots, 'Display current snapshot status.') ) def show(runner): runner.go()
print response.table(0).format_table(caption = 'Snapshot Status')
random_line_split
unwind-rec2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn build2() -> Vec<int> { panic!(); } struct Blk { node: Vec<int> , span: Vec<int> } fn main() { let _blk = Blk { node: build1(), span: build2() }; }
{ vec!(0,0,0,0,0,0,0) }
identifier_body
unwind-rec2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> Vec<int> { panic!(); } struct Blk { node: Vec<int> , span: Vec<int> } fn main() { let _blk = Blk { node: build1(), span: build2() }; }
build2
identifier_name
unwind-rec2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
struct Blk { node: Vec<int> , span: Vec<int> } fn main() { let _blk = Blk { node: build1(), span: build2() }; }
fn build2() -> Vec<int> { panic!(); }
random_line_split
servicio.ts
import { Injectable } from '@angular/core'; //import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import {AngularFire, FirebaseListObservable} from 'angularFire2'; /* Generated class for the Servicio provider. See https://angular.io/docs/ts/latest/guide/dependency-injection.html for more info ...
} public guardarUsuario(nombre : string) { localStorage.setItem("Nombre",nombre); } public tomarUsuario = function(){ return localStorage.getItem("Nombre"); } save(Usu:string, respuestaComputador: string, respuestaPersona: string, Resultado: string, fecha: Date) { this.juegos.push({ Usuar...
//console.log('Hello Servicio Provider');
random_line_split
servicio.ts
import { Injectable } from '@angular/core'; //import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import {AngularFire, FirebaseListObservable} from 'angularFire2'; /* Generated class for the Servicio provider. See https://angular.io/docs/ts/latest/guide/dependency-injection.html for more info ...
(nombre : string) { localStorage.setItem("Nombre",nombre); } public tomarUsuario = function(){ return localStorage.getItem("Nombre"); } save(Usu:string, respuestaComputador: string, respuestaPersona: string, Resultado: string, fecha: Date) { this.juegos.push({ Usuario: Usu, ...
guardarUsuario
identifier_name
download.ts
import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController, ToastController } from 'ionic-angular'; import { FilePath, Transfer } from 'ionic-native'; import { File } from '@ionic-native/file'; import { Http, Headers } from '@angular/http'; /* Generated class for the Download pag...
ionViewDidLoad() { console.log('ionViewDidLoad DownloadPage'); } }
{ console.log(file); const fileTransfer = new Transfer(); var uri= encodeURI(this.hostname + 'download/' + file); this.loading = this.loadingCtrl.create({ content: 'Downloading...', }); this.loading.present(); fileTransfer.download(uri, this.file.externalRootDirectory+ '/Download/' + ...
identifier_body
download.ts
import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController, ToastController } from 'ionic-angular';
Generated class for the Download page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-download', templateUrl: 'download.html' }) export class DownloadPage { items: any; hostname: string; filelist: any; loading:...
import { FilePath, Transfer } from 'ionic-native'; import { File } from '@ionic-native/file'; import { Http, Headers } from '@angular/http'; /*
random_line_split
download.ts
import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController, ToastController } from 'ionic-angular'; import { FilePath, Transfer } from 'ionic-native'; import { File } from '@ionic-native/file'; import { Http, Headers } from '@angular/http'; /* Generated class for the Download pag...
(file){ console.log(file); const fileTransfer = new Transfer(); var uri= encodeURI(this.hostname + 'download/' + file); this.loading = this.loadingCtrl.create({ content: 'Downloading...', }); this.loading.present(); fileTransfer.download(uri, this.file.externalRootDirectory+ '/Downloa...
download
identifier_name
regexp.rs
use std::borrow::ToOwned; use std::collections::HashMap; use regex::Regex; use url::percent_encoding; /// A route `Expression` is a regular expression compiled from a /// "template string" in which portions of a URL path are bound to /// named groupings denoted by curly braces. /// /// This expression can then be matc...
#[test] fn test_template_extractor_values() { let template = "/foo/{bar:pat}"; match extract_segments(template) { Ok(meta_segment) => { let (_, ref segment) = meta_segment[0]; assert!("bar:pat" == &segment[..]); }, Err(msg) => { panic!("Error while extracting segments {}", msg); }, } }
{ // tests that a pattern w/ no extractable parameters // can still be matched... let template = Expression::from_template("/foo/bar").unwrap(); assert!(template.is_match("/foo/bar") == true); assert!(template.is_match("/baz/qux") == false); }
identifier_body
regexp.rs
use std::borrow::ToOwned; use std::collections::HashMap; use regex::Regex; use url::percent_encoding; /// A route `Expression` is a regular expression compiled from a /// "template string" in which portions of a URL path are bound to /// named groupings denoted by curly braces. /// /// This expression can then be matc...
, None => { break; }, } } if brace_count == 0 { return Ok(segments); } else { return Err("missing closing brace in route pattern?"); } } // // tests // // test creation of a template #[test] fn test_build_template() { match Expression::from_template("/{foo}/{bar}") { Err(e) => { panic!("{}", e); },...
{ input_buf = &input_buf[1..]; // move slice forward 1 char. match token { '{' => { brace_count += 1; continue; }, '}' => { brace_count -= 1; segments.push((segment_text.to_owned(), param_text.to_owned())); param_text = String::new(); segment_text = Stri...
conditional_block
regexp.rs
use std::borrow::ToOwned; use std::collections::HashMap; use regex::Regex; use url::percent_encoding; /// A route `Expression` is a regular expression compiled from a /// "template string" in which portions of a URL path are bound to /// named groupings denoted by curly braces. /// /// This expression can then be matc...
Some(captures) => { for idx in 0..self.names.len() { if let Some(binding) = captures.at(idx+1) { // TODO: do we really want urlencoding in here? // TODO: decode utf8 lossy? since this is a middleware it's not // clear that there's...
random_line_split
regexp.rs
use std::borrow::ToOwned; use std::collections::HashMap; use regex::Regex; use url::percent_encoding; /// A route `Expression` is a regular expression compiled from a /// "template string" in which portions of a URL path are bound to /// named groupings denoted by curly braces. /// /// This expression can then be matc...
(&self, path: &str) -> HashMap<String, String> { let mut results = HashMap::new(); let captures = self.regex.captures(path); // iterates over our list of named parameters and extracts // the corresponding capture group from the regex. // // the captures are offset by 1 because the first match // is th...
map_path
identifier_name
received_mint.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_address::AccountAddress; use anyhow::Result; use move_core_types::{ identifier::{IdentStr, Identifier}, move_resource::MoveResource, }; use serde::{Deserialize, Serialize}; /// Struct that represents a Recei...
/// Return the address who received the mint pub fn destination_address(&self) -> AccountAddress { self.destination_address } /// Return the code for the currency that was minted pub fn currency_code(&self) -> &IdentStr { &self.currency_code } pub fn try_from_bytes(bytes:...
{ self.amount }
identifier_body
received_mint.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_address::AccountAddress; use anyhow::Result; use move_core_types::{ identifier::{IdentStr, Identifier}, move_resource::MoveResource, }; use serde::{Deserialize, Serialize}; /// Struct that represents a Recei...
/// Return the code for the currency that was minted pub fn currency_code(&self) -> &IdentStr { &self.currency_code } pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> { bcs::from_bytes(bytes).map_err(Into::into) } } impl MoveResource for ReceivedMintEvent { const MODULE_NAM...
pub fn destination_address(&self) -> AccountAddress { self.destination_address }
random_line_split
received_mint.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_address::AccountAddress; use anyhow::Result; use move_core_types::{ identifier::{IdentStr, Identifier}, move_resource::MoveResource, }; use serde::{Deserialize, Serialize}; /// Struct that represents a Recei...
(&self) -> u64 { self.amount } /// Return the address who received the mint pub fn destination_address(&self) -> AccountAddress { self.destination_address } /// Return the code for the currency that was minted pub fn currency_code(&self) -> &IdentStr { &self.currency_co...
amount
identifier_name
gulpfile.js
var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var sass = require('gulp-sass');
// Load all gulp plugins automatically // and attach them to the `plugins` object var plugins = require('gulp-load-plugins')(); // Temporary solution until gulp 4 // https://github.com/gulpjs/gulp/issues/355 var runSequence = require('run-sequence'); var pkg = require('./package.json'); var dirs = pkg['h5bp-configs...
random_line_split
20120209C.py
''' we all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input...
if min > max: got_answer = True print('ERROR! ERROR! ERROR! Master did not answer the questions properly!')
max = guess - 1
conditional_block
20120209C.py
''' we all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input...
if response == '2': got_answer = True if try_count > 1: print('\nHurray! I guessed {} in {} tries!!!'.format(guess, try_count)) else: print('\nHurray! I guessed {} in the first try!!! WOOHOO!'.format(guess, try_count)) elif response == '1': min = guess +...
print('\nIs your number {}'.format(guess)) response = input('> ')
random_line_split
projectownership.py
from __future__ import absolute_import import operator from django.db import models from django.db.models import Q from django.utils import timezone from sentry.db.models import Model, sane_repr from sentry.db.models.fields import FlexibleForeignKey, JSONField from sentry.ownership.grammar import load_schema from f...
__repr__ = sane_repr("project_id", "is_active") @classmethod def get_owners(cls, project_id, data): """ For a given project_id, and event data blob. If Everyone is returned, this means we implicitly are falling through our rules and everyone is responsible. If an...
app_label = "sentry" db_table = "sentry_projectownership"
identifier_body
projectownership.py
from __future__ import absolute_import import operator from django.db import models from django.db.models import Q from django.utils import timezone from sentry.db.models import Model, sane_repr from sentry.db.models.fields import FlexibleForeignKey, JSONField from sentry.ownership.grammar import load_schema from f...
(Model): __core__ = True project = FlexibleForeignKey("sentry.Project", unique=True) raw = models.TextField(null=True) schema = JSONField(null=True) fallthrough = models.BooleanField(default=True) auto_assignment = models.BooleanField(default=False) date_created = models.DateTimeField(defau...
ProjectOwnership
identifier_name
projectownership.py
from __future__ import absolute_import import operator from django.db import models from django.db.models import Q from django.utils import timezone from sentry.db.models import Model, sane_repr from sentry.db.models.fields import FlexibleForeignKey, JSONField from sentry.ownership.grammar import load_schema from f...
# is assigned to the project or has been removed from the org. if not actors: return None return actors[0].resolve() @classmethod def _matching_ownership_rules(cls, ownership, project_id, data): rules = [] if ownership.schema is not None: for rule...
score = candidate owners = rule.owners actors = filter(None, resolve_actors(owners, project_id).values()) # Can happen if the ownership rule references a user/team that no longer
random_line_split
projectownership.py
from __future__ import absolute_import import operator from django.db import models from django.db.models import Q from django.utils import timezone from sentry.db.models import Model, sane_repr from sentry.db.models.fields import FlexibleForeignKey, JSONField from sentry.ownership.grammar import load_schema from f...
score = 0 owners = None # Automatic assignment prefers the owner with the longest # matching pattern as the match is more specific. for rule in rules: candidate = len(rule.matcher.pattern) if candidate > score: score = candidate ...
return None
conditional_block
__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # Account Statement Operation multi-company module for Odoo # Copyright (C) 2015 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # # This program is free so...
'account_view.xml', 'security/rule.xml', ], 'installable': True, }
'summary': 'Fix multi-company issue on Statement Operation Templates', 'author': "Akretion,Odoo Community Association (OCA)", 'website': 'http://www.akretion.com', 'depends': ['account'], 'data': [
random_line_split
p004.rs
fn
(){ println!("Euler Problem #4"); println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers"); println!("Solution: {}", largest_palendrome(100, 999)); } fn largest_palendrome(min : i32, max : i32) -> i32 { let mut solution = 0; for a in std::iter::range_step_inclus...
main
identifier_name
p004.rs
fn main(){ println!("Euler Problem #4"); println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers"); println!("Solution: {}", largest_palendrome(100, 999)); } fn largest_palendrome(min : i32, max : i32) -> i32 { let mut solution = 0;
for b in std::iter::range_step_inclusive(max, a, -1){ let c = a*b; if c <= solution {break} if is_palendrome(c) {solution = c} } } return solution; } fn is_palendrome(a : i32) -> bool{ let mut y = 0i32; let mut x = a; while x > 0 { y = y*...
for a in std::iter::range_step_inclusive(max, min, -1){
random_line_split
p004.rs
fn main(){ println!("Euler Problem #4"); println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers"); println!("Solution: {}", largest_palendrome(100, 999)); } fn largest_palendrome(min : i32, max : i32) -> i32 { let mut solution = 0; for a in std::iter::range_step...
if is_palendrome(c) {solution = c} } } return solution; } fn is_palendrome(a : i32) -> bool{ let mut y = 0i32; let mut x = a; while x > 0 { y = y*10 + x%10; x /= 10; } return a==y }
{break}
conditional_block
p004.rs
fn main()
fn largest_palendrome(min : i32, max : i32) -> i32 { let mut solution = 0; for a in std::iter::range_step_inclusive(max, min, -1){ for b in std::iter::range_step_inclusive(max, a, -1){ let c = a*b; if c <= solution {break} if is_palendrome(c) {solution = c} ...
{ println!("Euler Problem #4"); println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers"); println!("Solution: {}", largest_palendrome(100, 999)); }
identifier_body
index.test.tsx
import { shallow, render } from 'enzyme'; import * as React from 'react'; import Alert from './index'; describe('Alert Component', () => { it('should create an alert with the default classes', () => { const alert = shallow(<Alert>Loading...</Alert>); expect(alert).not.toBeNull(); expect(alert.text())....
expect(alert.hasClass('alert-error white')).toBe(true); }); it('should create an alert with the given id value', () => { const alert = shallow(<Alert id={ 'This id' }>Loading...</Alert>); expect(alert.prop('id')).toEqual('This id'); }); });
const alert = shallow(<Alert status={ 'error' }>Error</Alert>);
random_line_split
36.rs
/* Problem 36: Double-base palindromes * * The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. * * Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. * * (Please note that the palindromic number, in either base, may not include leading zeros....
} impl NumberFormatter for Decimal { fn format(number: u32, buffer: &mut String) { write!(buffer, "{}", number).unwrap(); } } fn main() { let mut b1 = String::with_capacity(50); let mut b2 = String::with_capacity(50); let result: u32 = (1..1_000_000) .filter(|number| is_palindrom...
{ write!(buffer, "{:b}", number).unwrap(); }
identifier_body
36.rs
/* Problem 36: Double-base palindromes * * The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. * * Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. * * (Please note that the palindromic number, in either base, may not include leading zeros....
struct Binary; struct Decimal; impl NumberFormatter for Binary { fn format(number: u32, buffer: &mut String) { write!(buffer, "{:b}", number).unwrap(); } } impl NumberFormatter for Decimal { fn format(number: u32, buffer: &mut String) { write!(buffer, "{}", number).unwrap(); } } fn ma...
random_line_split
36.rs
/* Problem 36: Double-base palindromes * * The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. * * Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. * * (Please note that the palindromic number, in either base, may not include leading zeros....
(number: u32, buffer: &mut String) { write!(buffer, "{}", number).unwrap(); } } fn main() { let mut b1 = String::with_capacity(50); let mut b2 = String::with_capacity(50); let result: u32 = (1..1_000_000) .filter(|number| is_palindrome::<Decimal>(*number, &mut b1)) .filter(|num...
format
identifier_name
Brocfile.js
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); // Configures ember-cli-foundation-sass: // Includes modernizr, fastclick and the full foundation.js with all modules var app = new EmberApp({ 'foundation-sass': { 'modernizr': true, 'fastclick': true, 'foundationJs...
// object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the ...
// output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That
random_line_split
monacoComponent.tsx
import * as React from "react"; import { MonacoManager } from "../tools/monacoManager"; import { GlobalState } from "../globalState"; require("../scss/monaco.scss");
className: string; refObject: React.RefObject<HTMLDivElement>; globalState: GlobalState; } export class MonacoComponent extends React.Component<IMonacoComponentProps> { private _monacoManager: MonacoManager; public constructor(props: IMonacoComponentProps) { super(props); ...
interface IMonacoComponentProps {
random_line_split
monacoComponent.tsx
import * as React from "react"; import { MonacoManager } from "../tools/monacoManager"; import { GlobalState } from "../globalState"; require("../scss/monaco.scss"); interface IMonacoComponentProps { className: string; refObject: React.RefObject<HTMLDivElement>; globalState: GlobalState; } expo...
extends React.Component<IMonacoComponentProps> { private _monacoManager: MonacoManager; public constructor(props: IMonacoComponentProps) { super(props); this._monacoManager = new MonacoManager(this.props.globalState); this.props.globalState.onEditorFullcreenRequiredObservable...
MonacoComponent
identifier_name
monacoComponent.tsx
import * as React from "react"; import { MonacoManager } from "../tools/monacoManager"; import { GlobalState } from "../globalState"; require("../scss/monaco.scss"); interface IMonacoComponentProps { className: string; refObject: React.RefObject<HTMLDivElement>; globalState: GlobalState; } expo...
else if (editorDiv.mozRequestFullScreen) { editorDiv.mozRequestFullScreen(); } else if (editorDiv.webkitRequestFullscreen) { editorDiv.webkitRequestFullscreen(); } }); } componentDidMount() { let hostElement = this.props.refObjec...
{ editorDiv.requestFullscreen(); }
conditional_block
monacoComponent.tsx
import * as React from "react"; import { MonacoManager } from "../tools/monacoManager"; import { GlobalState } from "../globalState"; require("../scss/monaco.scss"); interface IMonacoComponentProps { className: string; refObject: React.RefObject<HTMLDivElement>; globalState: GlobalState; } expo...
componentDidMount() { let hostElement = this.props.refObject.current!; this._monacoManager.setupMonacoAsync(hostElement, true); } public render() { return <div id="monacoHost" ref={this.props.refObject} className={this.props.className}></div>; } }
{ super(props); this._monacoManager = new MonacoManager(this.props.globalState); this.props.globalState.onEditorFullcreenRequiredObservable.add(() => { let editorDiv = this.props.refObject.current! as any; if (editorDiv.requestFullscreen) { edito...
identifier_body
htmllielement.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::HTMLLIElementBinding; use dom::bindings::codegen::InheritTypes::HTMLLIElemen...
}
{ let element = HTMLLIElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLLIElementBinding::Wrap) }
identifier_body
htmllielement.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::HTMLLIElementBinding; use dom::bindings::codegen::InheritTypes::HTMLLIElemen...
HTMLLIElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLLIElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Tempora...
random_line_split
htmllielement.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::HTMLLIElementBinding; use dom::bindings::codegen::InheritTypes::HTMLLIElemen...
(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLIElement))) } } impl HTMLLIElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLLIEle...
is_htmllielement
identifier_name
retinanet_model.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
raise ValueError('build_loss_fn() must be called after build_model().') filter_fn = self.make_filter_trainable_variables_fn() trainable_variables = filter_fn(self._keras_model.trainable_variables) def _total_loss_fn(labels, outputs): cls_loss = self._cls_loss_fn(outputs['cls_outputs'], ...
def build_loss_fn(self): if self._keras_model is None:
random_line_split
retinanet_model.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
return _total_loss_fn def build_model(self, params, mode=None): if self._keras_model is None: with backend.get_graph().as_default(): outputs = self.model_outputs(self._input_layer, mode) model = tf.keras.models.Model( inputs=self._input_layer, outputs=outputs, name='retin...
cls_loss = self._cls_loss_fn(outputs['cls_outputs'], labels['cls_targets'], labels['num_positives']) box_loss = self._box_loss_fn(outputs['box_outputs'], labels['box_targets'], ...
identifier_body
retinanet_model.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
filter_fn = self.make_filter_trainable_variables_fn() trainable_variables = filter_fn(self._keras_model.trainable_variables) def _total_loss_fn(labels, outputs): cls_loss = self._cls_loss_fn(outputs['cls_outputs'], labels['cls_targets'], ...
raise ValueError('build_loss_fn() must be called after build_model().')
conditional_block
retinanet_model.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(self): return eval_factory.evaluator_generator(self._params.eval)
eval_metrics
identifier_name
fields.js
var test = require('tap').test; var CronExpression = require('../lib/expression'); test('Fields are exposed', function(t){ try { var interval = CronExpression.parse('0 1 2 3 * 1-3,5'); t.ok(interval, 'Interval parsed'); CronExpression.map.forEach(function(field) { interval.fields[field] = []; ...
});
t.end();
random_line_split
test_indextable.py
""" A test script for the `indextable` module """ from random import randrange import pytest from HamiltonianPy.indextable import IndexTable class TestIndexTable: def test_init(self): match0 = r"unhashable type" match1 = r"The .* has different type from the previous ones" match2 = r"Th...
def test_query_object(self): num0 = 7 num1 = 3 table = IndexTable((x, y) for x in range(num0) for y in range(num1)) for i in range(5): index = randrange(num0 * num1) assert table.query_object(index) == divmod(index, num1)
key = (randrange(num0), randrange(num1)) assert table(key) == key[0] * num1 + key[1]
conditional_block
test_indextable.py
""" A test script for the `indextable` module """ from random import randrange import pytest from HamiltonianPy.indextable import IndexTable class TestIndexTable: def test_init(self):
def test_object_type(self): table = IndexTable((x, y) for x in range(4) for y in range(4)) assert table.object_type is tuple def test_str_and_iteration(self): separator = "*" * 80 table = IndexTable((x, y) for x in range(2) for y in range(2)) print(table) print...
match0 = r"unhashable type" match1 = r"The .* has different type from the previous ones" match2 = r"The .* object already exists" with pytest.raises(TypeError, match=match0): IndexTable([[0, 1], [2, 3]]) with pytest.raises(TypeError, match=match1): IndexTable([(0,...
identifier_body
test_indextable.py
""" A test script for the `indextable` module """ from random import randrange import pytest from HamiltonianPy.indextable import IndexTable class TestIndexTable: def test_init(self): match0 = r"unhashable type" match1 = r"The .* has different type from the previous ones" match2 = r"Th...
(self): separator = "*" * 80 table = IndexTable((x, y) for x in range(2) for y in range(2)) print(table) print(separator) for index in table.indices(): print(index) print(separator) for item in table.objects(): print(item) print(s...
test_str_and_iteration
identifier_name
test_indextable.py
""" A test script for the `indextable` module """ from random import randrange import pytest from HamiltonianPy.indextable import IndexTable class TestIndexTable: def test_init(self): match0 = r"unhashable type" match1 = r"The .* has different type from the previous ones" match2 = r"Th...
for index in table.indices(): print(index) print(separator) for item in table.objects(): print(item) print(separator) for index, item in table: print(index, item) print(separator) def test_length(self): num0 = 4 ...
table = IndexTable((x, y) for x in range(2) for y in range(2)) print(table) print(separator)
random_line_split
yubi.rs
use yubico::config::{Command, Config, Mode, Slot}; use yubico::configure::DeviceModeConfig; use yubico::hmacmode::HmacKey; use yubico::Yubico; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use hex; use std::ops::Deref; pub fn setup_secret() -> Result<(), String> { let mut yubi = Yubico::new...
} pub fn retrieve_secret(token: [u8; 20]) -> Option<String> { let mut yubi = Yubico::new(); if let Ok(device) = yubi.find_yubikey() { let config = Config::default() .set_vendor_id(device.vendor_id) .set_product_id(device.product_id) .set_variable_size(true) ...
random_line_split
yubi.rs
use yubico::config::{Command, Config, Mode, Slot}; use yubico::configure::DeviceModeConfig; use yubico::hmacmode::HmacKey; use yubico::Yubico; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use hex; use std::ops::Deref; pub fn setup_secret() -> Result<(), String> { let mut yubi = Yubico::new...
}
{ return None; }
conditional_block