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
index.js
import axios from 'axios'; import token from './Token'; let API_ROOT = process.env.WEB_URL + process.env.API_ROOT; let AUTH_ROOT = 'auth/auth/refreshtoken'; token.setAccessToken(window.localStorage.getItem('access_token')); token.setRefreshToken(window.localStorage.getItem('refresh_token')); const getHeaderConfig = ...
token.setRefreshToken(responseBody.data.refresh_token); token.setUser(responseBody.data.user); originalRequest.headers['Authorization'] = 'Bearer ' + responseBody.data.access_token; return axios(originalRequest); })); } return Promise.reject(error); }); const requests = { ...
window.localStorage.setItem('refresh_token', responseBody.data.refresh_token); window.localStorage.setItem('vyaguta_user', JSON.stringify(responseBody.data.user)); token.setAccessToken(responseBody.data.access_token);
random_line_split
index.js
import axios from 'axios'; import token from './Token'; let API_ROOT = process.env.WEB_URL + process.env.API_ROOT; let AUTH_ROOT = 'auth/auth/refreshtoken'; token.setAccessToken(window.localStorage.getItem('access_token')); token.setRefreshToken(window.localStorage.getItem('refresh_token')); const getHeaderConfig = ...
return Promise.reject(error); }); const requests = { get: url => axios.get(`${API_ROOT}${url}`, getHeaderConfig()), post: (url, body) => axios.post(`${API_ROOT}${url}`, body, getHeaderConfig()), put: (url, body) => axios.put(`${API_ROOT}${url}`, body, getHeaderConfig()), del: (url) => axios...
{ originalRequest._retry = true; const refreshToken = token.getRefreshToken(); return (axios.post(`${API_ROOT}${AUTH_ROOT}`, {refresh_token: refreshToken}) .then(responseBody => { window.localStorage.setItem('access_token', responseBody.data.access_token); window.localStorage.setItem(...
conditional_block
welcome.component.ts
import {Component} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {OnInit} from '@angular/core'; import {OnDestroy} from '@angular/core'; import {Subscription} from 'rxjs/Subscription'; import {User} from './../../cla...
import {UserService} from './../../services/user.service'; import {WebsocketUserService} from './../../services/websocket.user.service'; @Component({ moduleId : module.id, selector : 'welcome', templateUrl: 'welcome.component.html' }) export class WelcomeComponent extends ComponentBase...
random_line_split
welcome.component.ts
import {Component} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {OnInit} from '@angular/core'; import {OnDestroy} from '@angular/core'; import {Subscription} from 'rxjs/Subscription'; import {User} from './../../cla...
public ngOnDestroy() : void { this.userSubscription.unsubscribe(); } }
{ this.userObservable = this.userService.getObservableUser(); this.userSubscription = this.userObservable.subscribe( value => { this.userName = value.name; }); this.sendLocation("welcome"); }
identifier_body
welcome.component.ts
import {Component} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {OnInit} from '@angular/core'; import {OnDestroy} from '@angular/core'; import {Subscription} from 'rxjs/Subscription'; import {User} from './../../cla...
( private _websocketUserService : WebsocketUserService, private userService : UserService ) { super(_websocketUserService); } public ngOnInit() : void { this.userObservable = this.userService.getObservableUser(); this.userSubscription = this...
constructor
identifier_name
scale_resource.py
import sys import os from scale_model import StartupDataModel, VCModel from flask.ext.restful import Resource, reqparse from flask import Flask, jsonify, request, make_response import os from database import db from flask.ext.security import current_user from json import dumps class Scale_DAO(object): def __init_...
except: jsonify(msg="Error adding your data.")
return jsonify(status=200,msg="Data added successfully!")
random_line_split
scale_resource.py
import sys import os from scale_model import StartupDataModel, VCModel from flask.ext.restful import Resource, reqparse from flask import Flask, jsonify, request, make_response import os from database import db from flask.ext.security import current_user from json import dumps class Scale_DAO(object): def __init_...
class Scale_resource(Resource): def get(self, **kwargs): """ TODO: get old data to render in form as default """ #check= request.args.get('check') if current_user.is_anonymous(): return jsonify(status=400) scale = Scale_DAO() if scale.user_scale...
print 'making scale DAO' self.user_scale = StartupDataModel.query.filter_by(username=current_user.email).order_by(StartupDataModel.date.desc()).first() print self.user_scale
identifier_body
scale_resource.py
import sys import os from scale_model import StartupDataModel, VCModel from flask.ext.restful import Resource, reqparse from flask import Flask, jsonify, request, make_response import os from database import db from flask.ext.security import current_user from json import dumps class
(object): def __init__(self): print 'making scale DAO' self.user_scale = StartupDataModel.query.filter_by(username=current_user.email).order_by(StartupDataModel.date.desc()).first() print self.user_scale class Scale_resource(Resource): def get(self, **kwargs): """ TODO: get o...
Scale_DAO
identifier_name
scale_resource.py
import sys import os from scale_model import StartupDataModel, VCModel from flask.ext.restful import Resource, reqparse from flask import Flask, jsonify, request, make_response import os from database import db from flask.ext.security import current_user from json import dumps class Scale_DAO(object): def __init_...
else: return jsonify(scale_authed=False) def post(self): """ TODO: add update instead of just creating whole new record """ if current_user.is_anonymous(): return jsonify(msg="You are no longer logged in",status=400) try: data = ...
return make_response(dumps(scale.user_scale.as_dict()))
conditional_block
compositor_thread.rs
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/. */ //! Communication with the compositor thread. use SendableFrameTree; use compositor::CompositingReason; use euclid::point::Point2D; use euclid::size::S...
(&mut self) -> Option<Msg> { self.try_recv().ok() } fn recv_compositor_msg(&mut self) -> Msg { self.recv().unwrap() } } pub trait RenderListener { fn recomposite(&mut self, reason: CompositingReason); } impl RenderListener for Box<CompositorProxy + 'static> { fn recomposite(&mut se...
try_recv_compositor_msg
identifier_name
compositor_thread.rs
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/. */ //! Communication with the compositor thread. use SendableFrameTree; use compositor::CompositingReason; use euclid::point::Point2D; use euclid::size::S...
CreatePng(IpcSender<Option<Image>>), /// Alerts the compositor that the viewport has been constrained in some manner ViewportConstrained(PipelineId, ViewportConstraints), /// A reply to the compositor asking if the output image is stable. IsReadyToSaveImageReply(bool), /// A favicon was detected...
random_line_split
RS_ChangeWindowTextColorSafely.js
//================================================================ // RS_ChangeWindowTextColorSafely.js // --------------------------------------------------------------- // The MIT License // Copyright (c) 2017 biud436 // --------------------------------------------------------------- // Free for commercial and non co...
const CLASS_NAME = window[clsName]; const FUNC_NAME = funcName.slice(0); const COLOR_NAME = color.slice(0); if (typeof CLASS_NAME === "function") { const prototypeName = CLASS_NAME.prototype[FUNC_NAME]; if (typeof ...
done = true; } if (done) {
random_line_split
RS_ChangeWindowTextColorSafely.js
//================================================================ // RS_ChangeWindowTextColorSafely.js // --------------------------------------------------------------- // The MIT License // Copyright (c) 2017 biud436 // --------------------------------------------------------------- // Free for commercial and non co...
ction") { CLASS_NAME.prototype[funcName] = function () { return COLOR_NAME; }; } } } }); }; Utils.changeWindowTextColorSafely(defaultWindowClasses); })();
if (typeof CLASS_NAME === "function") { const prototypeName = CLASS_NAME.prototype[FUNC_NAME]; if (typeof prototypeName === "fun
conditional_block
index.d.ts
// Type definitions for React (react-dom) 16.9 // Project: http://facebook.github.io/react/ // Definitions by: Asana <https://asana.com> // AssureSign <http://www.assuresign.com> // Microsoft <https://microsoft.com> // MartynasZilinskas <https://github.com/MartynasZilinsk...
( element: SFCElement<any> | Array<SFCElement<any>>, container: Element | null, callback?: () => void ): void; <P, T extends Component<P, ComponentState>>( element: CElement<P, T>, container: Element | null, callback?: () => void ): T; ( ele...
( element: Array<DOMElement<DOMAttributes<any>, any>>, container: Element | null, callback?: () => void ): Element;
random_line_split
report.py
import time import csv def report(ob): #Create log file
log_report.write("\nScan frames: %s" % ob.scan) if ob.frameSET: log_report.write("\nManual framerate: %s" % ob.frame_rate) log_report.write("\nSet ROI: %s" % ob.ROI_include) log_report.write("\nArea counter?: %s" % ob.set_areacounter) log_report.write("\n...
log_file_report = ob.file_destination + "/" + "Parameters_Results.log" log_report = file(log_file_report, 'a' ) #Print parameters #Batch or single file log_report.write("\nRun type: %s" % ob.runtype) if ob.runtype in ["file","pictures"]: log_report.write("\nInput...
identifier_body
report.py
import time import csv def
(ob): #Create log file log_file_report = ob.file_destination + "/" + "Parameters_Results.log" log_report = file(log_file_report, 'a' ) #Print parameters #Batch or single file log_report.write("\nRun type: %s" % ob.runtype) if ob.runtype in ["file","pictures"]: ...
report
identifier_name
report.py
import time import csv def report(ob): #Create log file log_file_report = ob.file_destination + "/" + "Parameters_Results.log" log_report = file(log_file_report, 'a' ) #Print parameters #Batch or single file log_report.write("\nRun type: %s" % ob.runtype) if ob....
log_report.write("\nOutput dir: %s" % ob.fileD) log_report.write("\nAdapt accAvg? %s" % ob.adapt) if ob.adapt: log_report.write("\nExpected hitrate: %s" % ob.frameHIT) log_report.write("\nMinimum accAvg: %s" % ob.floorvalue) log_report.write("\nT...
log_report.write("\nInput file path: %s" % ob.batchpool)
conditional_block
report.py
import time import csv def report(ob): #Create log file log_file_report = ob.file_destination + "/" + "Parameters_Results.log" log_report = file(log_file_report, 'a' ) #Print parameters #Batch or single file log_report.write("\nRun type: %s" % ob.runtype) if ob....
else: log_report.write("\nInput file path: %s" % ob.batchpool) log_report.write("\nOutput dir: %s" % ob.fileD) log_report.write("\nAdapt accAvg? %s" % ob.adapt) if ob.adapt: log_report.write("\nExpected hitrate: %s" % ob.frameHIT)...
log_report.write("\nInput file path: %s" % ob.inDEST)
random_line_split
url.helper.ts
export class UrlGenerator { private queries: { [name: string]: number | string | boolean } = {}; private sections: Array<number | string | boolean> = []; constructor(private rootpath: string) { } public section(value: string | number | boolean | Array<string | number | boolean>) { if (value i...
} public toString() { const queries: string[] = []; Object.keys(this.queries).forEach(name => { if (this.queries[name] !== null && this.queries[name] !== undefined) { queries.push(`${name}=${this.queries[name]}`); } }); return `${this.root...
this.queries[name] = value; return this;
random_line_split
url.helper.ts
export class UrlGenerator { private queries: { [name: string]: number | string | boolean } = {}; private sections: Array<number | string | boolean> = []; constructor(private rootpath: string) { } public
(value: string | number | boolean | Array<string | number | boolean>) { if (value instanceof Array) { this.sections.push(...value); } else { this.sections.push(value); } return this; } public query(name: string, value: number | string | boolean) { ...
section
identifier_name
url.helper.ts
export class UrlGenerator { private queries: { [name: string]: number | string | boolean } = {}; private sections: Array<number | string | boolean> = []; constructor(private rootpath: string) { } public section(value: string | number | boolean | Array<string | number | boolean>) { if (value ...
}); return `${this.rootpath}${this.sections.length > 0 ? '/' : ''}${this.sections.join('/')}${queries.length > 0 ? '?' : ''}${queries.join('&')}`; } }
{ queries.push(`${name}=${this.queries[name]}`); }
conditional_block
url.helper.ts
export class UrlGenerator { private queries: { [name: string]: number | string | boolean } = {}; private sections: Array<number | string | boolean> = []; constructor(private rootpath: string) { } public section(value: string | number | boolean | Array<string | number | boolean>) { if (value ...
public toString() { const queries: string[] = []; Object.keys(this.queries).forEach(name => { if (this.queries[name] !== null && this.queries[name] !== undefined) { queries.push(`${name}=${this.queries[name]}`); } }); return `${this.rootpath}...
{ this.queries[name] = value; return this; }
identifier_body
vec-res-add.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 ...
{ i:int } fn r(i:int) -> r { r { i: i } } impl Drop for r { fn drop(&mut self) {} } fn main() { // This can't make sense as it would copy the classes let i = vec!(r(0)); let j = vec!(r(1)); let k = i + j; //~^ ERROR not implemented println!("{}", j); //~^ ERROR not implemented }
r
identifier_name
vec-res-add.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 ...
}
random_line_split
vec-res-add.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 ...
{ // This can't make sense as it would copy the classes let i = vec!(r(0)); let j = vec!(r(1)); let k = i + j; //~^ ERROR not implemented println!("{}", j); //~^ ERROR not implemented }
identifier_body
routes.js
/** * Module dependencies. */ var api = require('lib/db-api'); var config = require('lib/config'); var express = require('express'); var jwt = require('lib/jwt'); var passport = require('passport'); var log = require('debug')('democracyos:auth:facebook:routes'); var User = require('lib/models').User; var fbSignedPar...
(userFacebookId) { log('Deauthorizing user with facebook id "%s".', userFacebookId); var profile = { id: userFacebookId, provider: 'facebook' }; User.findByProvider(profile, function (err, user) { if (err) { return log('Error looking for user with facebook id "%s".', userFacebookId); } ...
deauthorizeUser
identifier_name
routes.js
/** * Module dependencies. */ var api = require('lib/db-api'); var config = require('lib/config'); var express = require('express'); var jwt = require('lib/jwt'); var passport = require('passport'); var log = require('debug')('democracyos:auth:facebook:routes'); var User = require('lib/models').User; var fbSignedPar...
id: userFacebookId, provider: 'facebook' }; User.findByProvider(profile, function (err, user) { if (err) { return log('Error looking for user with facebook id "%s".', userFacebookId); } if (!user) { return log('User with facebook id "%s" not found.', userFacebookId); } use...
var profile = {
random_line_split
routes.js
/** * Module dependencies. */ var api = require('lib/db-api'); var config = require('lib/config'); var express = require('express'); var jwt = require('lib/jwt'); var passport = require('passport'); var log = require('debug')('democracyos:auth:facebook:routes'); var User = require('lib/models').User; var fbSignedPar...
if (err) return log(err); log('Facebook login for user "%s" deauthorized.', user.id); }); }); }
{ log('Deauthorizing user with facebook id "%s".', userFacebookId); var profile = { id: userFacebookId, provider: 'facebook' }; User.findByProvider(profile, function (err, user) { if (err) { return log('Error looking for user with facebook id "%s".', userFacebookId); } if (!user) { ...
identifier_body
routes.js
/** * Module dependencies. */ var api = require('lib/db-api'); var config = require('lib/config'); var express = require('express'); var jwt = require('lib/jwt'); var passport = require('passport'); var log = require('debug')('democracyos:auth:facebook:routes'); var User = require('lib/models').User; var fbSignedPar...
if (!user) { return log('User with facebook id "%s" not found.', userFacebookId); } user.set('profiles.facebook.deauthorized', true); return user.save(function(err){ if (err) return log(err); log('Facebook login for user "%s" deauthorized.', user.id); }); }); }
{ return log('Error looking for user with facebook id "%s".', userFacebookId); }
conditional_block
cue_parser.py
import re from enum import Enum, auto from fractions import Fraction from io import BufferedIOBase from numbers import Number from typing import Iterable import chardet class CueCmd(Enum):
def _unquote(s: str): return s[1 + s.index('"'):s.rindex('"')] _whitespace_pattern = re.compile(r'\s+') _rem_tag_pattern = re.compile(r'([A-Z_]+) (.+)') def parse_cd_time(offset: str) -> Number: """parse time in CD-DA (75fps) format to seconds, exactly MM:SS:FF""" m, s, f = map(int, offset.split(...
PERFORMER = auto() TITLE = auto() FILE = auto() TRACK = auto() INDEX = auto() REM = auto() EOF = auto()
identifier_body
cue_parser.py
import re from enum import Enum, auto from fractions import Fraction from io import BufferedIOBase from numbers import Number from typing import Iterable import chardet class CueCmd(Enum): PERFORMER = auto() TITLE = auto() FILE = auto() TRACK = auto() INDEX = auto() REM = auto() EOF = aut...
return None def read_cue_from_file(in_path: str) -> str: with open(in_path, 'rb') as f: assert isinstance(f, BufferedIOBase) content = f.read() encoding = chardet.detect(content)['encoding'] return content.decode(encoding) def parse_cue_str(content: str, offset_in_seconds: bool = T...
tag_name, tag_value = _rem_tag_pattern.fullmatch(args).groups() return CueCmd.REM, tag_name, tag_value
conditional_block
cue_parser.py
import re from enum import Enum, auto from fractions import Fraction from io import BufferedIOBase from numbers import Number from typing import Iterable import chardet class CueCmd(Enum): PERFORMER = auto() TITLE = auto() FILE = auto() TRACK = auto() INDEX = auto() REM = auto() EOF = aut...
(offset: str) -> Number: """parse time in CD-DA (75fps) format to seconds, exactly MM:SS:FF""" m, s, f = map(int, offset.split(':')) return m * 60 + s + Fraction(f, 75) def _parse_cue_cmd(line: str, offset_in_seconds: bool = True): line = line.strip() cmd, args = _whitespace_pattern.split(line...
parse_cd_time
identifier_name
cue_parser.py
import re from enum import Enum, auto from fractions import Fraction from io import BufferedIOBase from numbers import Number from typing import Iterable import chardet class CueCmd(Enum): PERFORMER = auto() TITLE = auto() FILE = auto() TRACK = auto() INDEX = auto() REM = auto() EOF = aut...
def read_cue_from_file(in_path: str) -> str: with open(in_path, 'rb') as f: assert isinstance(f, BufferedIOBase) content = f.read() encoding = chardet.detect(content)['encoding'] return content.decode(encoding) def parse_cue_str(content: str, offset_in_seconds: bool = True) -> Iterable[tu...
return None
random_line_split
__init__.py
""" unittests for xmodule Run like this: rake test_common/lib/xmodule """ import json import os import unittest import fs import fs.osfs import numpy from mock import Mock from path import path import calc from xblock.field_data import DictFieldData from xmodule.x_module import ModuleSystem, XModuleDescriptor...
def test_load_class(self): vc = XModuleDescriptor.load_class('video') vc_str = "<class 'xmodule.video_module.VideoDescriptor'>" self.assertEqual(str(vc), vc_str) class PostData(object): """Class which emulate postdata.""" def __init__(self, dict_data): self.dict_data = dic...
pass
identifier_body
__init__.py
""" unittests for xmodule Run like this: rake test_common/lib/xmodule """ import json import os import unittest import fs import fs.osfs import numpy from mock import Mock from path import path import calc from xblock.field_data import DictFieldData from xmodule.x_module import ModuleSystem, XModuleDescriptor...
: """Empty object.""" url_name = '' category = 'test' self.system = get_test_system() self.descriptor = EmptyClass() self.xmodule_class = self.descriptor_class.module_class self.xmodule = self.xmodule_class( self.descriptor, self.system, ...
EmptyClass
identifier_name
__init__.py
""" unittests for xmodule Run like this: rake test_common/lib/xmodule """ import json import os import unittest import fs import fs.osfs import numpy from mock import Mock
from path import path import calc from xblock.field_data import DictFieldData from xmodule.x_module import ModuleSystem, XModuleDescriptor, DescriptorSystem from xmodule.modulestore.inheritance import InheritanceMixin from xmodule.mako_module import MakoDescriptorSystem # Location of common test DATA directory # '.....
random_line_split
function-arg-initialization.rs
// === GDB TESTS =================================================================================== // gdb-command:run // IMMEDIATE ARGS // gdb-command:print a // gdb-check:$1 = 1 // gdb-command:print b // gdb-check:$2 = true // gdb-command:print c // gdb-check:$3 = 2.5 // gdb-command:continue // NON IMMEDIATE ARGS...
// lldb-command:print b // lldb-check:[...]$9 = 23 // lldb-command:print c // lldb-check:[...]$10 = 24.5 // lldb-command:continue // FUNCTION CALL // lldb-command:print x // lldb-check:[...]$11 = 25 // lldb-command:print y // lldb-check:[...]$12 = 26 // lldb-command:print z // lldb-check:[...]$13 = 27.5 // lldb-comman...
// lldb-command:print a // lldb-check:[...]$8 = 22
random_line_split
function-arg-initialization.rs
GDB TESTS =================================================================================== // gdb-command:run // IMMEDIATE ARGS // gdb-command:print a // gdb-check:$1 = 1 // gdb-command:print b // gdb-check:$2 = true // gdb-command:print c // gdb-check:$3 = 2.5 // gdb-command:continue // NON IMMEDIATE ARGS // gd...
(a: int, b: bool, c: f64) { ::std::old_io::print("") // #break } struct BigStruct { a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, g: u64, h: u64 } fn non_immediate_args(a: BigStruct, b: BigStruct) { ::std::old_io::print("") // #break } fn binding(a: i64, b: u64, c: f64) { ...
immediate_args
identifier_name
function-arg-initialization.rs
print x // gdb-check:$12 = 25 // gdb-command:print y // gdb-check:$13 = 26 // gdb-command:print z // gdb-check:$14 = 27.5 // gdb-command:continue // EXPR // gdb-command:print x // gdb-check:$15 = 28 // gdb-command:print y // gdb-check:$16 = 29 // gdb-command:print z // gdb-check:$17 = 30.5 // gdb-command:continue // ...
{ immediate_args(1, true, 2.5); non_immediate_args( BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }, BigStruct { a: 11, b: 12, c: 13, ...
identifier_body
function-arg-initialization.rs
5, d = 6, e = 7, f = 8, g = 9, h = 10} // gdb-command:print b // gdb-check:$5 = {a = 11, b = 12, c = 13, d = 14, e = 15, f = 16, g = 17, h = 18} // gdb-command:continue // BINDING // gdb-command:print a // gdb-check:$6 = 19 // gdb-command:print b // gdb-check:$7 = 20 // gdb-command:print c // gdb-check:$8 = 21.5 // g...
{ y }
conditional_block
Widgets.py
# This file is part of Pooky. # Copyright (C) 2013 Fcrh <coquelicot1117@gmail.com> # # Pooky is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ver...
def __init__(self, *args): super().__init__(*args) mainlayout = QtGui.QVBoxLayout() mainlayout.addWidget(self.initContent(), True) mainlayout.addLayout(self.initButtonLayout(), True) self.setLayout(mainlayout) self.setWindowTitle('About Pooky') self.adjustSi...
self.setWindowTitle('Preference') class About(SingletonWidget):
random_line_split
Widgets.py
# This file is part of Pooky. # Copyright (C) 2013 Fcrh <coquelicot1117@gmail.com> # # Pooky is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ver...
(SingletonWidget): def __init__(self, *args): super().__init__(*args) class Preference(SingletonWidget): def __init__(self, *args): super().__init__(*args) QtGui.QLabel('Almost Empty XD.', self) self.resize(640, 480) self.setWindowTitle('Preference') class About(Sing...
Palette
identifier_name
Widgets.py
# This file is part of Pooky. # Copyright (C) 2013 Fcrh <coquelicot1117@gmail.com> # # Pooky is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ver...
else: self.__class__.__instance = self class Palette(SingletonWidget): def __init__(self, *args): super().__init__(*args) class Preference(SingletonWidget): def __init__(self, *args): super().__init__(*args) QtGui.QLabel('Almost Empty XD.', self) self.re...
raise RuntimeError("Singleton check failed.")
conditional_block
Widgets.py
# This file is part of Pooky. # Copyright (C) 2013 Fcrh <coquelicot1117@gmail.com> # # Pooky is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ver...
class Palette(SingletonWidget): def __init__(self, *args): super().__init__(*args) class Preference(SingletonWidget): def __init__(self, *args): super().__init__(*args) QtGui.QLabel('Almost Empty XD.', self) self.resize(640, 480) self.setWindowTitle('Preference') c...
__instance = None def __init__(self, *args): super().__init__(*args) if self.__class__.__instance is not None: raise RuntimeError("Singleton check failed.") else: self.__class__.__instance = self
identifier_body
lib.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate rusqlite; pub mod weblog; use regex::Regex; use weblog::Weblog; use rusqlite::Connection; // Take an unprocessed string representing a single line of an Apache log, // attempt to match the various components of the string, and generate a Weblog ...
\"(.+)\" ").expect("Unable to compile Regex"); } // This used to print to stdout before returning None, but the calling // program should do the printing. let cap = match RE.captures(line) { Some(x) => x, None => { return None; } }; le...
\"(\\S+)\"\\s
random_line_split
lib.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate rusqlite; pub mod weblog; use regex::Regex; use weblog::Weblog; use rusqlite::Connection; // Take an unprocessed string representing a single line of an Apache log, // attempt to match the various components of the string, and generate a Weblog ...
return None; } }; let logline = Weblog::new( cap[1].to_string(), cap[4].to_string(), cap[5].to_string(), cap[6].parse::<i32>().unwrap_or(0), cap[7].parse::<i32>().unwrap_or(0), cap[8].to_string(), cap[9].to_string() ); Some(logl...
{ lazy_static! { static ref RE: Regex = Regex::new("(?x) (\\S+)\\s (\\S+)\\s (\\S+)\\s \\[(\\d{2}/\\w+/\\d{4}:\\d{2}:\\d{2}:\\d{2}\\s+.+?)\\]\\s \"(\\w+\\s\\S+\\s\\w+/\\d+\\.\\d+)\"\\s (\\d+)\\s (\\d+)\\s \"(\\S+...
identifier_body
lib.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate rusqlite; pub mod weblog; use regex::Regex; use weblog::Weblog; use rusqlite::Connection; // Take an unprocessed string representing a single line of an Apache log, // attempt to match the various components of the string, and generate a Weblog ...
(count: i32) -> Vec<Weblog> { let conn = Connection::open("test.db").expect("Cannot open database?"); let mut stmt = conn.prepare("SELECT * FROM weblogs LIMIT (?)") .expect("Unable to prepare SELECT statement"); let log_iter = stmt.query_map(&[&count], |row| { Weblog { ip: row.ge...
fetch
identifier_name
compile.rs
// 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 according to those terms. // Enable this to squash warnings due to exporting pieces of the representation // for ...
Rep(x, ZeroMore, g) => { let j1 = self.insts.len(); let split = self.empty_split(); let j2 = self.insts.len(); self.compile(*x); let jmp = self.empty_jump(); let j3 = self.insts.len(); self.set_...
{ let split = self.empty_split(); let j1 = self.insts.len(); self.compile(*x); let j2 = self.insts.len(); if g.is_greedy() { self.set_split(split, j1, j2); } else { self.set_split(spl...
conditional_block
compile.rs
// 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 according to those terms. // Enable this to squash warnings due to exporting pieces of the representation // for ...
EmptyEnd(Flags), // Matches a word boundary (\w on one side and \W \A or \z on the other), // and consumes no character. // The flags indicate whether this matches a word boundary or something // that isn't a word boundary. EmptyWordBoundary(Flags), // Saves the current position in the inp...
EmptyBegin(Flags), // Matches the end of the string, consumes no characters. // The flags indicate whether it matches if the proceeding character // is a new line.
random_line_split
compile.rs
// 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 according to those terms. // Enable this to squash warnings due to exporting pieces of the representation // for ...
/// Appends an *empty* `Jump` instruction to the program and returns the /// index of that instruction. #[inline] fn empty_jump(&mut self) -> Inst
{ let split = self.insts.get_mut(i); match *split { Split(_, _) => *split = Split(pc1, pc2), _ => fail!("BUG: Invalid split index."), } }
identifier_body
compile.rs
// 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 according to those terms. // Enable this to squash warnings due to exporting pieces of the representation // for ...
(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) { let split = self.insts.get_mut(i); match *split { Split(_, _) => *split = Split(pc1, pc2), _ => fail!("BUG: Invalid split index."), } } /// Appends an *empty* `Jump` instruction to the program and returns the ...
set_split
identifier_name
ring_buffer.rs
signifies where a consumer should read from. head: usize, /// Tail, signifies where a producer should write. tail: usize, /// Size of the ring buffer. size: usize, /// Used for computing circular things. mask: usize, /// Things for shm. bottom_map: *mut c_void, top_map: *mut c_v...
/// Produce an immutable slice at an offset. The nice thing about our implementation is that we can produce slices /// despite using a circular ring buffer. #[inline] fn slice_at_offset(&self, offset: usize, len: usize) -> &[u8] { if len >= self.size { panic!("slice beyond buffer l...
{ unsafe { RingBuffer::allocate(pages) } }
identifier_body
ring_buffer.rs
rust buffer. buf: *mut u8, } unsafe impl Send for RingBuffer {} impl Drop for RingBuffer { fn drop(&mut self) { unsafe { munmap(self.bottom_map, self.size); munmap(self.top_map, self.size); } } } #[cfg_attr(feature = "dev", allow(len_without_is_empty))] impl RingB...
random_line_split
ring_buffer.rs
_without_is_empty))] impl RingBuffer { unsafe fn allocate(pages: usize) -> Result<RingBuffer> { if pages & (pages - 1) != 0 { // We need pages to be a power of 2. return Err(ErrorKind::InvalidRingSize(pages).into()); } let bytes = pages << 12; let alloc_bytes ...
seek_tail
identifier_name
ring_buffer.rs
signifies where a consumer should read from. head: usize, /// Tail, signifies where a producer should write. tail: usize, /// Size of the ring buffer. size: usize, /// Used for computing circular things. mask: usize, /// Things for shm. bottom_map: *mut c_void, top_map: *mut c_v...
// First get a big enough chunk of virtual memory. Fortunately for us this does not actually commit any physical // pages. We allocate twice as much memory so as to mirror the ring buffer. let address = mmap(ptr::null_mut(), alloc_bytes, li...
{ libc::close(fd); shm_unlink(name.as_ptr()); return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure); }
conditional_block
ShareBar.tsx
import { Email, Facebook, Linkedin, Print, Twitter } from '@amsterdam/asc-assets' import { ShareButton, themeSpacing } from '@amsterdam/asc-ui' import type { FunctionComponent } from 'react' import { useCallback } from 'react' import styled, { css } from 'styled-components' import getShareUrl from '../../utils/shareUrl...
}, []) return ( <ShareBarContainer {...otherProps} data-testid="sharebar"> <ShareButton // @ts-ignore type="button" onClick={() => handlePageShare('facebook')} hoverColor="#3b5999" iconSize={30} title="Deel op Facebook" > <Facebook /> <...
{ window.open(link.url, link.target) }
conditional_block
ShareBar.tsx
import { Email, Facebook, Linkedin, Print, Twitter } from '@amsterdam/asc-assets' import { ShareButton, themeSpacing } from '@amsterdam/asc-ui' import type { FunctionComponent } from 'react' import { useCallback } from 'react' import styled, { css } from 'styled-components' import getShareUrl from '../../utils/shareUrl...
title="Deel op Facebook" > <Facebook /> </ShareButton> <ShareButton // @ts-ignore type="button" onClick={() => handlePageShare('twitter')} hoverColor="#55acee" title="Deel op Twitter" > <Twitter /> </ShareButton> <ShareB...
hoverColor="#3b5999" iconSize={30}
random_line_split
PreviewModal.test.js
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas is distribut...
import React from 'react' import {render, fireEvent} from '@testing-library/react' import PreviewModal from '../PreviewModal' import {mockShare} from 'jsx/content_shares/__tests__/test-utils' describe('content_shares/PreviewModal', () => { it('renders an iframe with the appropriate src', () => { window.ENV = {CO...
*/
random_line_split
round.ts
// Arithmetic Expression Operators: https://docs.mongodb.com/manual/reference/operator/aggregation/#arithmetic-expression-operators import { computeValue, Options } from "../../../core"; import { AnyVal, RawArray, RawObject } from "../../../types"; import { assert, isNil, isNumber } from "../../../util"; import { trun...
{ const args = computeValue(obj, expr, null, options) as RawArray; const num = args[0] as number; const place = args[1] as number; if (isNil(num) || isNaN(num) || Math.abs(num) === Infinity) return num; assert(isNumber(num), "$round expression must resolve to a number."); return truncate(num, place, true);...
identifier_body
round.ts
// Arithmetic Expression Operators: https://docs.mongodb.com/manual/reference/operator/aggregation/#arithmetic-expression-operators import { computeValue, Options } from "../../../core"; import { AnyVal, RawArray, RawObject } from "../../../types"; import { assert, isNil, isNumber } from "../../../util"; import { trun...
( obj: RawObject, expr: AnyVal, options?: Options ): number | null { const args = computeValue(obj, expr, null, options) as RawArray; const num = args[0] as number; const place = args[1] as number; if (isNil(num) || isNaN(num) || Math.abs(num) === Infinity) return num; assert(isNumber(num), "$round expr...
$round
identifier_name
round.ts
// Arithmetic Expression Operators: https://docs.mongodb.com/manual/reference/operator/aggregation/#arithmetic-expression-operators import { computeValue, Options } from "../../../core"; import { AnyVal, RawArray, RawObject } from "../../../types"; import { assert, isNil, isNumber } from "../../../util";
* @param {*} obj * @param {*} expr */ export function $round( obj: RawObject, expr: AnyVal, options?: Options ): number | null { const args = computeValue(obj, expr, null, options) as RawArray; const num = args[0] as number; const place = args[1] as number; if (isNil(num) || isNaN(num) || Math.abs(num)...
import { truncate } from "./_internal"; /** * Rounds a number to to a whole integer or to a specified decimal place.
random_line_split
setup.py
from setuptools import setup, find_packages from helga_github_meta import __version__ as version setup( name='helga-github-meta', version=version, description=('Provide information for github related metadata'), classifiers=[
'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat :: Internet Relay Chat'], keywords='irc bot github-meta urbandictionary urban dictionary ud', author='Jon Robison', author_email='narfman0@gmail.com', url='https://github.com/narfman0/helga-g...
'Development Status :: 4 - Beta', 'Topic :: Communications :: Chat :: Internet Relay Chat', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python',
random_line_split
start.ts
import { navigator, window } from 'global'; import addons, { DecorateStoryFunction, Channel } from '@storybook/addons'; import createChannel from '@storybook/channel-postmessage'; import { ClientApi, ConfigApi, StoryStore } from '@storybook/client-api'; import Events from '@storybook/core-events'; import { getSelecti...
try { channel = addons.getChannel(); } catch (e) { channel = createChannel({ page: 'preview' }); addons.setChannel(channel); } } return channel; } function getClientApi(decorateStory: DecorateStoryFunction, channel?: Channel) { let storyStore: StoryStore; let clientApi: ClientApi...
!(navigator.userAgent.indexOf('jsdom') > -1); function getOrCreateChannel() { let channel = null; if (isBrowser) {
random_line_split
start.ts
import { navigator, window } from 'global'; import addons, { DecorateStoryFunction, Channel } from '@storybook/addons'; import createChannel from '@storybook/channel-postmessage'; import { ClientApi, ConfigApi, StoryStore } from '@storybook/client-api'; import Events from '@storybook/core-events'; import { getSelecti...
(event: Event) { const target = event.target as Element; return /input|textarea/i.test(target.tagName) || target.getAttribute('contenteditable') !== null; } // todo improve typings export default function start( render: RenderStoryFunction, { decorateStory }: { decorateStory?: DecorateStoryFunction } = {} ) { ...
focusInInput
identifier_name
start.ts
import { navigator, window } from 'global'; import addons, { DecorateStoryFunction, Channel } from '@storybook/addons'; import createChannel from '@storybook/channel-postmessage'; import { ClientApi, ConfigApi, StoryStore } from '@storybook/client-api'; import Events from '@storybook/core-events'; import { getSelecti...
else { storyStore = new StoryStore({ channel }); clientApi = new ClientApi({ storyStore, decorateStory }); } return { clientApi, storyStore }; } function focusInInput(event: Event) { const target = event.target as Element; return /input|textarea/i.test(target.tagName) || target.getAttribute('contented...
{ clientApi = window.__STORYBOOK_CLIENT_API__; storyStore = window.__STORYBOOK_STORY_STORE__; }
conditional_block
start.ts
import { navigator, window } from 'global'; import addons, { DecorateStoryFunction, Channel } from '@storybook/addons'; import createChannel from '@storybook/channel-postmessage'; import { ClientApi, ConfigApi, StoryStore } from '@storybook/client-api'; import Events from '@storybook/core-events'; import { getSelecti...
function getClientApi(decorateStory: DecorateStoryFunction, channel?: Channel) { let storyStore: StoryStore; let clientApi: ClientApi; if ( typeof window !== 'undefined' && window.__STORYBOOK_CLIENT_API__ && window.__STORYBOOK_STORY_STORE__ ) { clientApi = window.__STORYBOOK_CLIENT_API__; ...
{ let channel = null; if (isBrowser) { try { channel = addons.getChannel(); } catch (e) { channel = createChannel({ page: 'preview' }); addons.setChannel(channel); } } return channel; }
identifier_body
fileref.rs
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Genera...
(&mut self) { VPE::cur().files().remove(self.fd); } } impl Deref for FileRef { type Target = FileHandle; fn deref(&self) -> &FileHandle { &self.file } } impl Read for FileRef { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> { self.file.borrow_mut().read(buf) ...
drop
identifier_name
fileref.rs
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Genera...
} impl Map for FileRef { fn map(&self, pager: &Pager, virt: goff, off: usize, len: usize, prot: kif::Perm) -> Result<(), Error> { self.file.borrow().map(pager, virt, off, len, prot) } } impl fmt::Debug for FileRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FileRef...
{ self.file.borrow_mut().seek(off, whence) }
identifier_body
fileref.rs
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Genera...
self.file.borrow().map(pager, virt, off, len, prot) } } impl fmt::Debug for FileRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FileRef[fd={}, file={:?}]", self.fd, self.file.borrow()) } }
impl Map for FileRef { fn map(&self, pager: &Pager, virt: goff, off: usize, len: usize, prot: kif::Perm) -> Result<(), Error> {
random_line_split
factor.rs
#![crate_name = "uu_factor"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com> * 20150223 added Pollard rho method implementation * (c) kwantam <kwantam@gmail.com> * 20150429 sped up trial division ...
(mut num: u64, factors: &mut Vec<u64>) { if num < 2 { return; } while num % 2 == 0 { num /= 2; factors.push(2); } if num == 1 { return; } if is_prime(num) { factors.push(num); return; } for &(prime, inv, ceil) in P_INVS_U64 { if...
table_division
identifier_name
factor.rs
#![crate_name = "uu_factor"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com> * 20150223 added Pollard rho method implementation * (c) kwantam <kwantam@gmail.com> * 20150429 sped up trial division ...
else { big_add(big_mul(a, big_mul(x, x, num), num), b, num) } } fn gcd(mut a: u64, mut b: u64) -> u64 { while b > 0 { a %= b; swap(&mut a, &mut b); } a } fn rho_pollard_find_divisor(num: u64) -> u64 { let range = Range::new(1, num); let mut rng = rand::weak_rng(); ...
{ (sm_mul(a, sm_mul(x, x, num), num) + b) % num }
conditional_block
factor.rs
#![crate_name = "uu_factor"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com> * 20150223 added Pollard rho method implementation * (c) kwantam <kwantam@gmail.com> * 20150429 sped up trial division ...
// inv = prime^-1 mod 2^64 // ceil = floor((2^64-1) / prime) // if (num * inv) mod 2^64 <= ceil, then prime divides num // See http://math.stackexchange.com/questions/1251327/ // for a nice explanation. loop { let Wrapping(x) = Wrapping(num) * Wrapping(inv); ...
{ if num < 2 { return; } while num % 2 == 0 { num /= 2; factors.push(2); } if num == 1 { return; } if is_prime(num) { factors.push(num); return; } for &(prime, inv, ceil) in P_INVS_U64 { if num == 1 { break; ...
identifier_body
factor.rs
#![crate_name = "uu_factor"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com> * 20150223 added Pollard rho method implementation * (c) kwantam <kwantam@gmail.com> * 20150429 sped up trial division ...
} } } else { for num_str in &matches.free { print_factors_str(num_str); } } 0 }
for line in BufReader::new(stdin()).lines() { for number in line.unwrap().split_whitespace() { print_factors_str(number);
random_line_split
archivo.py
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionar...
def main(): cast() if __name__=="__main__": main()
print e
random_line_split
archivo.py
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionar...
contador = 0 while contador <=10: print contador contador +=1 EXCEPTION(): def getWeb(): try: web=urllib2.urlopen("http://itjiquilpan.edu.mx/") print web.read() web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as...
print"Es mayor de edad" else: print"Es menor de edad"
conditional_block
archivo.py
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def
(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionario: print "%s %s" % (k,v) class Estudiante(object): def __init__(self, nombre, edad): ...
areatriangulo
identifier_name
archivo.py
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast():
class Estudiante(object): def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exceptio...
lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionario: print "%s %s" % (k,v)
identifier_body
__init__.py
Server import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler import cgi import SocketServer import ssl import re import setproctitle import others.dict2xml as dict2xml import sober.config import sober.settings import sober.rule __version__ = 'Sober HTTP/1.0' __service__ = 'sober' class WSHandler(S...
def load_whitelist(self): return {'item': self.value} def load_settings(self): return self.settings.get() def return_error(self): return 'error' def do_POST(self): self.do_GET() def do_GET(self): try: path = self.path.strip().split('/') ...
return self.settings.get_blacklist()
identifier_body
__init__.py
HTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler import cgi import SocketServer import ssl import re import setproctitle import others.dict2xml as dict2xml import sober.config import sober.settings import sober.rule __version__ = 'Sober HTTP/1.0' __service__ = 'sober' class WSHandl...
elif len(cond[rtype]) == 1: x = 0 for item in cond[rtype]: items['item'+ str(x)] = item x = x + 1 conditions[rtype] = items else: op = cond[rtype][0] ...
x = 0 for item in cond[rtype]: items['item'+ str(x)] = item x = x + 1 conditions[rtype] = items
conditional_block
__init__.py
Server import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler import cgi import SocketServer import ssl import re import setproctitle import others.dict2xml as dict2xml import sober.config import sober.settings import sober.rule __version__ = 'Sober HTTP/1.0' __service__ = 'sober' class WSHandler(S...
(self): return 'error' def do_POST(self): self.do_GET() def do_GET(self): try: path = self.path.strip().split('/') if len(path) > 5 and self.command == 'GET': self.value = path[5] self.object_type = path[2] r...
return_error
identifier_name
__init__.py
HTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler import cgi import SocketServer import ssl import re import setproctitle
import others.dict2xml as dict2xml import sober.config import sober.settings import sober.rule __version__ = 'Sober HTTP/1.0' __service__ = 'sober' class WSHandler(SimpleHTTPRequestHandler): value = None def load_blacklist(self): return self.settings.get_blacklist() def load_whitelist(self): ...
random_line_split
CheckerNode.js
import { TempNode } from '../core/TempNode.js'; import { FunctionNode } from '../core/FunctionNode.js'; import { UVNode } from '../accessors/UVNode.js'; class CheckerNode extends TempNode { constructor( uv ) { super( 'f' ); this.uv = uv || new UVNode(); } generate( builder, output ) { const snoise = bui...
( source ) { super.copy( source ); this.uv = source.uv; return this; } toJSON( meta ) { let data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); data.uv = this.uv.toJSON( meta ).uuid; } return data; } } CheckerNode.Nodes = ( function () { // https:/...
copy
identifier_name
CheckerNode.js
import { TempNode } from '../core/TempNode.js'; import { FunctionNode } from '../core/FunctionNode.js'; import { UVNode } from '../accessors/UVNode.js'; class CheckerNode extends TempNode { constructor( uv ) { super( 'f' ); this.uv = uv || new UVNode(); } generate( builder, output ) { const snoise = bui...
return data; } } CheckerNode.Nodes = ( function () { // https://github.com/mattdesl/glsl-checker/blob/master/index.glsl const checker = new FunctionNode( /* glsl */` float checker( vec2 uv ) { float cx = floor( uv.x ); float cy = floor( uv.y ); float result = mod( cx + cy, 2.0 ); return sign...
{ data = this.createJSONNode( meta ); data.uv = this.uv.toJSON( meta ).uuid; }
conditional_block
CheckerNode.js
import { FunctionNode } from '../core/FunctionNode.js'; import { UVNode } from '../accessors/UVNode.js'; class CheckerNode extends TempNode { constructor( uv ) { super( 'f' ); this.uv = uv || new UVNode(); } generate( builder, output ) { const snoise = builder.include( CheckerNode.Nodes.checker ); re...
import { TempNode } from '../core/TempNode.js';
random_line_split
CheckerNode.js
import { TempNode } from '../core/TempNode.js'; import { FunctionNode } from '../core/FunctionNode.js'; import { UVNode } from '../accessors/UVNode.js'; class CheckerNode extends TempNode { constructor( uv )
generate( builder, output ) { const snoise = builder.include( CheckerNode.Nodes.checker ); return builder.format( snoise + '( ' + this.uv.build( builder, 'v2' ) + ' )', this.getType( builder ), output ); } copy( source ) { super.copy( source ); this.uv = source.uv; return this; } toJSON( meta ...
{ super( 'f' ); this.uv = uv || new UVNode(); }
identifier_body
Servo.py
import Adafruit_BBIO.PWM as PWM class Servo: def __init__(self, pin): self.servo_pin = pin self.duty_min = 3 self.duty_max = 14.5 self.duty_span = self.duty_max - self.duty_min def StartServo(self): print("Starting servo") print(self.servo_pin) PWM.start(self.servo_pin, (100 - self.duty_min), 60.0...
(self, angle): angle_f = float(angle) duty = 100 - ((angle_f / 180) * self.duty_span + self.duty_min) PWM.set_duty_cycle(self.servo_pin, duty) def IncreaseAngle(self, angle): self.current_angle += angle self.SetAngle(self.current_angle) def DecreaseAngle(self, angle): self.current_angle -= angle self...
SetAngle
identifier_name
Servo.py
import Adafruit_BBIO.PWM as PWM class Servo: def __init__(self, pin): self.servo_pin = pin self.duty_min = 3 self.duty_max = 14.5 self.duty_span = self.duty_max - self.duty_min def StartServo(self): print("Starting servo") print(self.servo_pin) PWM.start(self.servo_pin, (100 - self.duty_min), 60.0...
def StopServo(self): PWM.stop(self.servo_pin)
self.current_angle -= angle self.SetAngle(self.current_angle)
identifier_body
Servo.py
import Adafruit_BBIO.PWM as PWM class Servo: def __init__(self, pin): self.servo_pin = pin self.duty_min = 3 self.duty_max = 14.5 self.duty_span = self.duty_max - self.duty_min def StartServo(self): print("Starting servo") print(self.servo_pin) PWM.start(self.servo_pin, (100 - self.duty_min), 60.0...
def IncreaseAngle(self, angle): self.current_angle += angle self.SetAngle(self.current_angle) def DecreaseAngle(self, angle): self.current_angle -= angle self.SetAngle(self.current_angle) def StopServo(self): PWM.stop(self.servo_pin)
def SetAngle(self, angle): angle_f = float(angle) duty = 100 - ((angle_f / 180) * self.duty_span + self.duty_min) PWM.set_duty_cycle(self.servo_pin, duty)
random_line_split
transcript.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs/Rx'; import { JhiEventManager, JhiParseLinks, JhiPaginationUtil, JhiLanguageService, JhiAlertService } from 'ng-jhipster'; import { Transcript } from './transcript....
} private onError(error) { this.alertService.error(error.message, null, null); } }
{ this.transcripts.push(data[i]); }
conditional_block
transcript.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs/Rx'; import { JhiEventManager, JhiParseLinks, JhiPaginationUtil, JhiLanguageService, JhiAlertService } from 'ng-jhipster'; import { Transcript } from './transcript....
(data, headers) { this.links = this.parseLinks.parse(headers.get('link')); this.totalItems = headers.get('X-Total-Count'); for (let i = 0; i < data.length; i++) { this.transcripts.push(data[i]); } } private onError(error) { this.alertService.error(error.messa...
onSuccess
identifier_name
transcript.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs/Rx'; import { JhiEventManager, JhiParseLinks, JhiPaginationUtil, JhiLanguageService, JhiAlertService } from 'ng-jhipster'; import { Transcript } from './transcript....
trackId(index: number, item: Transcript) { return item.id; } registerChangeInTranscripts() { this.eventSubscriber = this.eventManager.subscribe('transcriptListModification', (response) => this.reset()); } sort() { const result = [this.predicate + ',' + (this.reverse ? 'asc'...
ngOnDestroy() { this.eventManager.destroy(this.eventSubscriber); }
random_line_split
url_abuse_async.py
for url in get_urls(meta_redir_url, depth): yield url def url_list(url): cached = _cache_get(url, 'list') if cached is not None: return cached list_urls = [] for u in get_urls(url): if u is None or u in list_urls: continue list_urls.append(u) _cache...
_deserialize_cached
identifier_name
url_abuse_async.py
().isoformat() else: day = day.isoformat() key = date.today().isoformat() + '_mails' return r_cache.sadd(key, url) def is_valid_url(url): cached = _cache_get(url, 'valid') key = date.today().isoformat() + '_submissions' r_cache.zincrby(key, url) if cached is not Non...
to_return = list(set(emails)) for mail in reversed(to_return): for ignorelist_entry in ignorelist: if re.search(ignorelist_entry, mail, re.I): if mail in to_return: to_return.remove(mail) for k, v in list(replacelist.items()): if re.search(...
identifier_body
url_abuse_async.py
day = date.today().isoformat() else: day = day.isoformat() key = date.today().isoformat() + '_mails' return r_cache.sismember(key, url) def set_mail_sent(url, day=None): _cache_init() if enable_cache: if day is None: day = date.today().isofor...
response = urlquery.search(query) except: return None if response['_response_']['status'] == 'ok': if response.get('reports') is not None: total_alert_count = 0 for r in response['reports']: total_alert_count += r['urlquery_alert_count'] ...
urlquery.url = url urlquery.key = key
random_line_split
url_abuse_async.py
def _cache_set(key, value, field=None): _cache_init() if enable_cache: if field is None: r_cache.setex(key, json.dumps(value), 3600) else: r_cache.hset(key, field, json.dumps(value)) r_cache.expire(key, 3600) def _cache_get(key, field=None): _cache_in...
r_cache = redis.Redis(host, port, db=db)
conditional_block
lowercase_pipe_spec.ts
import {LowerCasePipe} from '@angular/common'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; export function
() { describe('LowerCasePipe', () => { var upper: any /** TODO #9100 */; var lower: any /** TODO #9100 */; var pipe: any /** TODO #9100 */; beforeEach(() => { lower = 'something'; upper = 'SOMETHING'; pipe = new LowerCasePipe(); }); describe('transform', () => { it('s...
main
identifier_name
lowercase_pipe_spec.ts
import {LowerCasePipe} from '@angular/common'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; export function main() { describe('LowerCasePipe', () => { var upper: any /** TODO #9100 */; var lower: any /** TODO #9100 */; var pipe: ...
}); describe('transform', () => { it('should return lowercase', () => { var val = pipe.transform(upper); expect(val).toEqual(lower); }); it('should lowercase when there is a new value', () => { var val = pipe.transform(upper); expect(val).toEqual(lower); ...
random_line_split
lowercase_pipe_spec.ts
import {LowerCasePipe} from '@angular/common'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; export function main()
expect(val).toEqual(lower); var val2 = pipe.transform('WAT'); expect(val2).toEqual('wat'); }); it('should not support other objects', () => { expect(() => pipe.transform(new Object())).toThrowError(); }); }); }); }
{ describe('LowerCasePipe', () => { var upper: any /** TODO #9100 */; var lower: any /** TODO #9100 */; var pipe: any /** TODO #9100 */; beforeEach(() => { lower = 'something'; upper = 'SOMETHING'; pipe = new LowerCasePipe(); }); describe('transform', () => { it('shou...
identifier_body
StreetMetaWidthMenu.test.js
/* eslint-env jest */ import React from 'react' import { fireEvent, cleanup } from '@testing-library/react' import { renderWithIntl } from '../../../../test/helpers/render' import StreetMetaWidthMenu from '../StreetMetaWidthMenu' describe('StreetMetaWidthMenu', () => { afterEach(cleanup) it('renders (metric units...
) expect(wrapper.asFragment()).toMatchSnapshot() }) it('renders (imperial units, default width selected)', () => { const wrapper = renderWithIntl( <StreetMetaWidthMenu street={{ units: 1, width: 60, occupiedWidth: 10 }} onChange={jest.fn()} ...
occupiedWidth: 10 }} onChange={jest.fn()} />
random_line_split
commands.py
in irc.state.channels: state.error('I\'m not even in %s.' % state.channel, Raise=True) if not irc.state.channels[state.channel].isOp(irc.nick): state.error('I need to be opped to %s.' % action, Raise=True) def validChannel(irc, msg, args, state): if irc.isChannel(args[0]): state.args.a...
getEmail
identifier_name