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
secrets.ts
import * as _ from 'lodash'; import * as AWS from 'aws-sdk'; import * as config from './config'; export interface Secrets { REDDIT_CLIENT_ID: string; REDDIT_CLIENT_TOKEN: string; REDDIT_USERNAME: string; REDDIT_PASSWORD: string; STEAM_API_KEY: string; } export async function
(): Promise<Secrets> { if (config.isLocalDev() && !process.env.USE_SECRETS) { console.info('Getting secrets from ENV instead of encrypted bundle.'); return _.pick(process.env, [ 'REDDIT_CLIENT_ID', 'REDDIT_CLIENT_TOKEN', 'REDDIT_PASSWORD', 'STEAM_API_KEY', ]) as any; } const k...
resolve
identifier_name
secrets.ts
import * as _ from 'lodash'; import * as AWS from 'aws-sdk'; import * as config from './config'; export interface Secrets { REDDIT_CLIENT_ID: string; REDDIT_CLIENT_TOKEN: string; REDDIT_USERNAME: string; REDDIT_PASSWORD: string; STEAM_API_KEY: string; } export async function resolve(): Promise<Secrets> { ...
}).promise(); return JSON.parse(secrets.Plaintext.toString()); }
random_line_split
secrets.ts
import * as _ from 'lodash'; import * as AWS from 'aws-sdk'; import * as config from './config'; export interface Secrets { REDDIT_CLIENT_ID: string; REDDIT_CLIENT_TOKEN: string; REDDIT_USERNAME: string; REDDIT_PASSWORD: string; STEAM_API_KEY: string; } export async function resolve(): Promise<Secrets>
}
{ if (config.isLocalDev() && !process.env.USE_SECRETS) { console.info('Getting secrets from ENV instead of encrypted bundle.'); return _.pick(process.env, [ 'REDDIT_CLIENT_ID', 'REDDIT_CLIENT_TOKEN', 'REDDIT_PASSWORD', 'STEAM_API_KEY', ]) as any; } const kms = new AWS.KMS({ ...
identifier_body
web-server.tsx
import * as express from "express"; import {WebServerConfig} from "./web-server-config"; import * as http from "http"; import * as Rx from "rx"; import * as endpoints from "../api/endpoints"; import {ServerSession, ClientSession} from "./../sessions/session-model"; import * as headers from "./header-and-cookie-names"; ...
private configure() { this.app.disable('x-powered-by'); this.app.enable('trust proxy'); this.configureMiddleware(); this.addJsonServices(); } protected addJsonServices() { this.jsonServiceHandlers().forEach(s => { this.jsonServiceContainer().addServiceHandler(s); }); } protec...
{ if (this.stopping) return; this.stopping = true; this.lifecycleSubject.onNext(Lifecycle.STOPPING); handler((e) => { if (e != null) return this.lifecycleSubject.onError(e); this.lifecycleSubject.onNext(Lifecycle.STOPPED); this.lifecycleSubject.onCompleted(); }); }
identifier_body
web-server.tsx
import * as express from "express"; import {WebServerConfig} from "./web-server-config"; import * as http from "http"; import * as Rx from "rx"; import * as endpoints from "../api/endpoints"; import {ServerSession, ClientSession} from "./../sessions/session-model"; import * as headers from "./header-and-cookie-names"; ...
protected getMcdsService = cached( () => new GetMcdsService(this.evernoteClient(), this.scheduleStorage(), this.syncService(), this.timeProvider())) protected putMcdsService = cached(() => new PutMcdsService(this.evernoteClient(), this.scheduleStorage())); protected fetchScheduleService = cached( () => ne...
random_line_split
web-server.tsx
import * as express from "express"; import {WebServerConfig} from "./web-server-config"; import * as http from "http"; import * as Rx from "rx"; import * as endpoints from "../api/endpoints"; import {ServerSession, ClientSession} from "./../sessions/session-model"; import * as headers from "./header-and-cookie-names"; ...
() { this.app.get(endpoints.Login.path, this.login().loginEvernote); this.app.get(endpoints.Logout.path, this.login().logout); this.app.use(endpoints.Api.path, this.jsonServiceContainer().services); this.app.get(endpoints.Home.path, this.staticAssets().homePageCatchAll); } private configureMiddlewa...
configureEndpoints
identifier_name
wordlist.rs
extern crate regex; extern crate rustc_serialize; extern crate strsim; use std::collections::HashMap; use std::io::{self, Read, Write}; use dopt::Docopt; use parse::{Atom, Parser}; // cheat until we get syntax extensions back :-( macro_rules! regex( ($s:expr) => (::regex::Regex::new($s).unwrap()); ); macro_rule...
given usage (provided on stdin). Example use: your-command --help | docopt-wordlist This command also supports completing positional arguments when given a list of choices. The choices are included in the word list if and only if the argument name appears in the usage string. For example: your-command --help | ...
const USAGE: &'static str = " Usage: docopt-wordlist [(<name> <possibles>)] ... docopt-wordlist prints a list of available flags and commands arguments for the
random_line_split
wordlist.rs
extern crate regex; extern crate rustc_serialize; extern crate strsim; use std::collections::HashMap; use std::io::{self, Read, Write}; use dopt::Docopt; use parse::{Atom, Parser}; // cheat until we get syntax extensions back :-( macro_rules! regex( ($s:expr) => (::regex::Regex::new($s).unwrap()); ); macro_rule...
fn run(args: Args) -> Result<(), String> { let mut usage = String::new(); try!(io::stdin().read_to_string(&mut usage).map_err(|e| e.to_string())); let parsed = try!(Parser::new(&usage).map_err(|e| e.to_string())); let arg_possibles: HashMap<String, Vec<String>> = args.arg_name.iter() ...
{ let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); match run(args) { Ok(_) => {}, Err(err) => { write!(&mut io::stderr(), "{}", err).unwrap(); ::std::process::exit(1) ...
identifier_body
wordlist.rs
extern crate regex; extern crate rustc_serialize; extern crate strsim; use std::collections::HashMap; use std::io::{self, Read, Write}; use dopt::Docopt; use parse::{Atom, Parser}; // cheat until we get syntax extensions back :-( macro_rules! regex( ($s:expr) => (::regex::Regex::new($s).unwrap()); ); macro_rule...
} } fn run(args: Args) -> Result<(), String> { let mut usage = String::new(); try!(io::stdin().read_to_string(&mut usage).map_err(|e| e.to_string())); let parsed = try!(Parser::new(&usage).map_err(|e| e.to_string())); let arg_possibles: HashMap<String, Vec<String>> = args.arg_name.iter() ...
{ write!(&mut io::stderr(), "{}", err).unwrap(); ::std::process::exit(1) }
conditional_block
wordlist.rs
extern crate regex; extern crate rustc_serialize; extern crate strsim; use std::collections::HashMap; use std::io::{self, Read, Write}; use dopt::Docopt; use parse::{Atom, Parser}; // cheat until we get syntax extensions back :-( macro_rules! regex( ($s:expr) => (::regex::Regex::new($s).unwrap()); ); macro_rule...
{ arg_name: Vec<String>, arg_possibles: Vec<String>, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); match run(args) { Ok(_) => {}, Err(err) => { write!(&mut i...
Args
identifier_name
ClientCssHelper.js
var logger = require('../logging').getLogger(__LOGGER__); var {PAGE_CSS_NODE_ID} = require('../constants'); var Q = require('q'); var PageUtil = require('./PageUtil') var loadedCss = {}; module.exports = { registerPageLoad: function registerPageLoad() { if (SERVER_SIDE) { throw new Error("ClientCssHelper.regi...
{ // Step 1: make the url protocol less first. This helps recognizing http://0.0.0.0:3001/common.css // and //0.0.0.0:3001/common.css as the same file. // Step 2: The browser will give us a full URL even if we only put a // path in on the server. So, if we're comparing against just // a path here we need to stri...
identifier_body
ClientCssHelper.js
var logger = require('../logging').getLogger(__LOGGER__); var {PAGE_CSS_NODE_ID} = require('../constants'); var Q = require('q'); var PageUtil = require('./PageUtil') var loadedCss = {}; module.exports = { registerPageLoad: function registerPageLoad() { if (SERVER_SIDE) { throw new Error("ClientCssHelper.regis...
// next add the style URLs that weren't already loaded. return Q.all(Object.keys(newCssByKey).map(newCssKey => { var retval; if (!loadedCss[newCssKey]) { // this means that the CSS is not currently present in the // document, so we need to add it. logger.debug("Adding stylesheet: " + newCss...
delete loadedCss[loadedCssKey]; } });
random_line_split
ClientCssHelper.js
var logger = require('../logging').getLogger(__LOGGER__); var {PAGE_CSS_NODE_ID} = require('../constants'); var Q = require('q'); var PageUtil = require('./PageUtil') var loadedCss = {}; module.exports = { registerPageLoad: function registerPageLoad() { if (SERVER_SIDE) { throw new Error("ClientCssHelper.regi...
(url) { // Step 1: make the url protocol less first. This helps recognizing http://0.0.0.0:3001/common.css // and //0.0.0.0:3001/common.css as the same file. // Step 2: The browser will give us a full URL even if we only put a // path in on the server. So, if we're comparing against just // a path here we need t...
normalizeLocalUrl
identifier_name
ClientCssHelper.js
var logger = require('../logging').getLogger(__LOGGER__); var {PAGE_CSS_NODE_ID} = require('../constants'); var Q = require('q'); var PageUtil = require('./PageUtil') var loadedCss = {}; module.exports = { registerPageLoad: function registerPageLoad() { if (SERVER_SIDE) { throw new Error("ClientCssHelper.regi...
else { key = styleNode.innerHTML; } loadedCss[key] = styleNode; } }, ensureCss: function ensureCss(routeName, pageObject) { if (SERVER_SIDE) { throw new Error("ClientCssHelper.registerPageLoad can't be called server-side"); } return Q.all(PageUtil.standardizeStyles(pageObject.getHeadStylesheet...
{ key = normalizeLocalUrl(styleNode.href); }
conditional_block
cuda_af_app.rs
use arrayfire::{af_print, dim4, info, set_device, Array}; use rustacuda::prelude::*; fn main()
}; let mut in_x = DeviceBuffer::from_slice(&[1.0f32; 10]).unwrap(); let mut in_y = DeviceBuffer::from_slice(&[2.0f32; 10]).unwrap(); // wait for any prior kernels to finish before passing // the device pointers to ArrayFire match stream.synchronize() { Ok(()) => {} Err(e) => pa...
{ // MAKE SURE to do all rustacuda initilization before arrayfire API's // first call. It seems like some CUDA context state is getting messed up // if we mix CUDA context init(device, context, module, stream) with ArrayFire API match rustacuda::init(CudaFlags::empty()) { Ok(()) => {} Er...
identifier_body
cuda_af_app.rs
use arrayfire::{af_print, dim4, info, set_device, Array}; use rustacuda::prelude::*; fn
() { // MAKE SURE to do all rustacuda initilization before arrayfire API's // first call. It seems like some CUDA context state is getting messed up // if we mix CUDA context init(device, context, module, stream) with ArrayFire API match rustacuda::init(CudaFlags::empty()) { Ok(()) => {} ...
main
identifier_name
cuda_af_app.rs
use arrayfire::{af_print, dim4, info, set_device, Array}; use rustacuda::prelude::*; fn main() { // MAKE SURE to do all rustacuda initilization before arrayfire API's // first call. It seems like some CUDA context state is getting messed up // if we mix CUDA context init(device, context, module, stream) wi...
x.lock(); y.lock(); af_print!("x", x); af_print!("y", y); let o = x + y; af_print!("out", o); let _o_dptr = unsafe { o.device_ptr() }; // Calls an implicit lock // User has to call unlock if they want to relenquish control to ArrayFire // Once the non-arrayfire operations are do...
// Lock so that ArrayFire doesn't free pointers from RustaCUDA // But we have to make sure these pointers stay in valid scope // as long as the associated ArrayFire Array objects are valid
random_line_split
System.js
System = { _cycle: null, _startCycle: function() { this._cycle = setInterval("System.Queue.walk()",1); }, _stopCycle: function() { clearInterval(this._cycle); }, _initialize: function() { // start the cycle this._startCycle(); // set the document monitor ...
System.handleException(e,arguments); } }, register: function(scr) { try { // set prototype of new object to System eval(scr + ".prototype = System"); // add new object to System collection eval("this." + scr + " = new " + scr + "()"); ...
} catch(e) {
random_line_split
System.js
System = { _cycle: null, _startCycle: function() { this._cycle = setInterval("System.Queue.walk()",1); }, _stopCycle: function() { clearInterval(this._cycle); }, _initialize: function() { // start the cycle this._startCycle(); // set the document monitor ...
} } };
{ // create the Microsoft handle var prefixes = ["MSXML4","MSXML3","MSXML2","MSXML","Microsoft"]; for (var i = 0; i < prefixes.length; i++) { try { http = new ActiveXObject(prefixes[i] + ".XmlH...
conditional_block
server.js
var http = require('http'); var fs = require('fs'); var url = require('url'); http.createServer( function (req, res) { var pathname = url.parse(req.url).pathname; if (pathname == '/data' && req.method == "POST") { req.setEncoding('utf8'); var t = new Date(); var body = ''; ...
}); } }).listen(80);
{ res.writeHead(200, {'Content-Type':mimetype}); res.write(data); res.end(); }
conditional_block
server.js
var http = require('http'); var fs = require('fs'); var url = require('url'); http.createServer( function (req, res) { var pathname = url.parse(req.url).pathname; if (pathname == '/data' && req.method == "POST") { req.setEncoding('utf8'); var t = new Date(); var body = ''; ...
}); res.writeHead(200); res.end(); } else { var fn = pathname.substr(1); var extn = pathname.slice (pathname.lastIndexOf('.')); var mimetype = 'none'; switch(pathname.slice( pathname.lastIndexOf('.'))) { case ".js": mimetype = "applicati...
var entry = { ts: t, d: body }; fs.appendFile('data.json', JSON.stringify(entry)); console.log("Recorded entry to data.json: " + JSON.stringify(entry));
random_line_split
set-user-multi-sort.js
var primaryCol = this.orderBy.column; var primaryAsc = this.orderBy.ascending; if (!this.userMultiSorting[primaryCol]) this.$set(this.userMultiSorting, primaryCol, []); var multi = this.userMultiSorting[primaryCol]; if (primaryCol === secondaryCol) { if (!multi.length || primaryAsc) { // primary is...
"use strict"; module.exports = function (secondaryCol) {
random_line_split
set-user-multi-sort.js
"use strict"; module.exports = function (secondaryCol) { var primaryCol = this.orderBy.column; var primaryAsc = this.orderBy.ascending; if (!this.userMultiSorting[primaryCol]) this.$set(this.userMultiSorting, primaryCol, []); var multi = this.userMultiSorting[primaryCol]; if (primaryCol === secondaryCol) { ...
;
{ var cols = [JSON.parse(JSON.stringify(main))]; cols = cols.concat(secondary[main.column]); return cols; }
identifier_body
set-user-multi-sort.js
"use strict"; module.exports = function (secondaryCol) { var primaryCol = this.orderBy.column; var primaryAsc = this.orderBy.ascending; if (!this.userMultiSorting[primaryCol]) this.$set(this.userMultiSorting, primaryCol, []); var multi = this.userMultiSorting[primaryCol]; if (primaryCol === secondaryCol) { ...
(main, secondary) { var cols = [JSON.parse(JSON.stringify(main))]; cols = cols.concat(secondary[main.column]); return cols; } ;
getMultiSortData
identifier_name
set-user-multi-sort.js
"use strict"; module.exports = function (secondaryCol) { var primaryCol = this.orderBy.column; var primaryAsc = this.orderBy.ascending; if (!this.userMultiSorting[primaryCol]) this.$set(this.userMultiSorting, primaryCol, []); var multi = this.userMultiSorting[primaryCol]; if (primaryCol === secondaryCol) { ...
} // force re-compilation of the filteredData computed property this.time = Date.now(); this.dispatch('sorted', getMultiSortData(this.orderBy, this.userMultiSorting)); }; function getMultiSortData(main, secondary) { var cols = [JSON.parse(JSON.stringify(main))]; cols = cols.concat(secondary[main.column]);...
{ // add sort multi.push({ column: secondaryCol, ascending: true }); }
conditional_block
derive_form.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use rocket::request::{FromForm, FromFormValue, FormItems}; use rocket::http::RawStr; #[derive(Debug, PartialEq, FromForm)] struct TodoTask { description: String, completed: bool } // TODO: Make deriving `FromForm` for this en...
() { // Same number of arguments: simple case. let task: Option<TodoTask> = strict("description=Hello&completed=on"); assert_eq!(task, Some(TodoTask { description: "Hello".to_string(), completed: true })); // Argument in string but not in form. let task: Option<TodoTask> = stric...
main
identifier_name
derive_form.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use rocket::request::{FromForm, FromFormValue, FormItems}; use rocket::http::RawStr; #[derive(Debug, PartialEq, FromForm)] struct TodoTask { description: String, completed: bool } // TODO: Make deriving `FromForm` for this en...
} #[derive(Debug, PartialEq, FromForm)] struct UnpresentCheckbox { checkbox: bool } #[derive(Debug, PartialEq, FromForm)] struct UnpresentCheckboxTwo<'r> { checkbox: bool, something: &'r RawStr } #[derive(Debug, PartialEq, FromForm)] struct FieldNamedV<'r> { v: &'r RawStr, } fn parse<'f, T: FromForm...
#[derive(Debug, PartialEq, FromForm)] struct ManualMethod<'r> { _method: Option<&'r RawStr>, done: bool
random_line_split
yahoo.py
ERROR: type should be large_string, got "https://www.yahoo.com/movies/v/true-story-trailer-173000497.html',\n 'md5': '989396ae73d20c6f057746fb226aa215',\n 'info_dict': {\n 'id': '071c4013-ce30-3a93-a5b2-e0413cd4a9d1',\n 'ext': 'mp4',\n 'title': '\\'True Story\\' Trailer',\n 'description': 'True Story',\n 'duration': 150,\n },\n }, {\n 'url': 'https://gma.yahoo.com/pizza-delivery-man-surprised-huge-tip-college-kids-195200785.html',\n 'only_matching': True,\n }, {\n 'note': 'NBC Sports embeds',\n 'url': 'http://sports.yahoo.com/blogs/ncaab-the-dagger/tyler-kalinoski-s-buzzer-beater-caps-davidson-s-comeback-win-185609842.html?guid=nbc_cbk_davidsonbuzzerbeater_150313',\n 'info_dict': {\n 'id': '9CsDKds0kvHI',\n 'ext': 'flv',\n 'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',\n 'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',\n }\n }, {\n 'url': 'https://tw.news.yahoo.com/-100120367.html',\n 'only_matching': True,\n }, {\n # Query result is embedded in webpage, but explicit request to video API fails with geo restriction\n 'url': 'https://screen.yahoo.com/community/communitary-community-episode-1-ladders-154501237.html',\n 'md5': '4fbafb9c9b6f07aa8f870629f6671b35',\n 'info_dict': {\n 'id': '1f32853c-a271-3eef-8cb6-f6d6872cb504',\n 'ext': 'mp4',\n 'title': 'Communitary - Community Episode 1: Ladders',\n 'description': 'md5:8fc39608213295748e1e289807838c97',\n 'duration': 1646,\n },\n }\n ]\n\n def _real_extract(self, url):\n mobj = re.match(self._VALID_URL, url)\n display_id = mobj.group('display_id') or self._match_id(url)\n page_id = mobj.group('id')\n url = mobj.group('url')\n host = mobj.group('host')\n webpage = self._download_webpage(url, display_id)\n\n # Look for iframed media first\n iframe_m = re.search(r'<iframe[^>]+src=\"(/video/.+?-\\d+\\.html\\?format=embed.*?)\"', webpage)\n if iframe_m:\n iframepage = self._download_webpage(\n host + iframe_m.group(1), display_id, 'Downloading iframe webpage')\n items_json = self._search_regex(\n r'mediaItems: (\\[.+?\\])$', iframepage, 'items', flags=re.MULTILINE, default=None)\n if items_json:\n items = json.loads(items_json)\n video_id = items[0]['id']\n return self._get_info(video_id, display_id, webpage)\n # Look for NBCSports iframes\n nbc_sports_url = NBCSportsVPlayerIE._extract_url(webpage)\n if nbc_sports_url:\n return self.url_result(nbc_sports_url, 'NBCSportsVPlayer')\n\n # Query result is often embedded in webpage as JSON. Sometimes explicit requests\n # to video API results in a failure with geo restriction reason therefore using\n # embedded query result when present sounds reasonable.\n config_json = self._search_regex(\n r'window\\.Af\\.bootstrap\\[[^\\]]+\\]\\s*=\\s*({.*?\"applet_type\"\\s*:\\s*\"td-applet-videoplayer\".*?});(?:</script>|$)',\n webpage, 'videoplayer applet', default=None)\n if config_json:\n config = self._parse_json(config_json, display_id, fatal=False)\n if config:\n sapi = config.get('models', {}).get('applet_model', {}).get('data', {}).get('sapi')\n if sapi:\n return self._extract_info(display_id, sapi, webpage)\n\n items_json = self._search_regex(\n r'mediaItems: ({.*?})$', webpage, 'items', flags=re.MULTILINE,\n default=None)\n if items_json is None:\n CONTENT_ID_REGEXES = [\n r'YUI\\.namespace\\(\"Media\"\\)\\.CONTENT_ID\\s*=\\s*\"([^\"]+)\"',\n r'root\\.App\\.Cache\\.context\\.videoCache\\.curVideo = \\{\"([^\"]+)\"',\n r'\"first_videoid\"\\s*:\\s*\"([^\"]+)\"',\n r'%s[^}]*\"ccm_id\"\\s*:\\s*\"([^\"]+)\"' % re.escape(page_id),\n ]\n video_id = self._search_regex(CONTENT_ID_REGEXES, webpage, 'content ID')\n else:\n items = json.loads(items_json)\n info = items['mediaItems']['query']['results']['mediaObj'][0]\n # The 'meta' field is not always in the video webpage, we request it\n # from another page\n video_id = info['id']\n return self._get_info(video_id, display_id, webpage)\n\n def _extract_info(self, display_id, query, webpage):\n info = query['query']['results']['mediaObj'][0]\n meta = info.get('meta')\n video_id = info.get('id')\n\n if not meta:\n msg = info['status'].get('msg')\n if msg:\n raise ExtractorError(\n '%s returned error: %s' % (self.IE_NAME, msg), expected=True)\n raise ExtractorError('Unable to extract media object meta')\n\n formats = []\n for s in info['streams']:\n format_info = {\n 'width': int_or_none(s.get('width')),\n 'height': int_or_none(s.get('height')),\n 'tbr': int_or_none(s.get('bitrate')),\n }\n\n host = s['host']\n path = s['path']\n if host.startswith('rtmp'):\n format_info.update({\n 'url': host,\n 'play_path': path,\n 'ext': 'flv',\n })\n else:\n if s.get('format') == 'm3u8_playlist':\n format_info['protocol'] = 'm3u8_native'\n format_info['ext'] = 'mp4'\n format_url = compat_urlparse.urljoin(host, path)\n format_info['url'] = format_url\n formats.append(format_info)\n\n self._sort_formats(formats)\n\n closed_captions = self._html_search_regex(\n r'\"closedcaptions\":(\\[[^\\]]+\\])', webpage, 'closed captions',\n default='[]')\n\n cc_json = self._parse_json(closed_captions, video_id, fatal=False)\n subtitles = {}\n if cc_json:\n for closed_caption in cc_json:\n lang = closed_caption['lang']\n if lang not in subtitles:\n subtitles[lang] = []\n subtitles[lang].append({\n 'url': closed_caption['url'],\n 'ext': mimetype2ext(closed_caption['content_type']),\n })\n\n return {\n 'id': video_id,\n 'display_id': display_id,\n 'title': unescapeHTML(meta['title']),\n 'formats': formats,\n 'description': clean_html(meta['description']),\n 'thumbnail': meta['thumbnail'] if meta.get('thumbnail') else self._og_search_thumbnail(webpage),\n 'duration': int_or_none(meta.get('duration')),\n 'subtitles': subtitles,\n }\n\n def _get_info(self, video_id, display_id, webpage):\n region = self._search_regex(\n r'\\\\?\"region\\\\?\"\\s*:\\s*\\\\?\"([^\"]+?)\\\\?\"',\n webpage, 'region', fatal=False, default='US')\n data = compat_urllib_parse.urlencode({\n 'protocol': 'http',\n 'region': region,\n })\n query_url = (\n 'https://video.media.yql.yahoo.com/v1/video/sapi/streams/'\n '{id}?{data}'.format(id=video_id, data=data))\n query_result = self._download_json(\n query_url, display_id, 'Downloading video info')\n return self._extract_info(display_id, query_result, webpage)\n\n\nclass YahooSearchIE(SearchInfoExtractor):\n IE_DESC = 'Yahoo screen search'\n _MAX_RESULTS = 1000\n IE_NAME = 'screen.yahoo:search'\n _SEARCH_KEY = 'yvsearch'\n\n def _get_n_results(self, query, n):\n \"\"\"Get a specified number of results for a query\"\"\"\n "
entries
identifier_name
yahoo.py
/tyler-kalinoski-s-buzzer-beater-caps-davidson-s-comeback-win-185609842.html?guid=nbc_cbk_davidsonbuzzerbeater_150313', 'info_dict': { 'id': '9CsDKds0kvHI', 'ext': 'flv', 'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d', 'title': 'Tyler Ka...
_SEARCH_KEY = 'yvsearch' def _get_n_results(self, query, n): """Get a specified number of results for a query""" entries = [] for pagenum in itertools.count(0): result_url = 'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus...
identifier_body
yahoo.py
'id': '2d25e626-2378-391f-ada0-ddaf1417e588', 'ext': 'mp4', 'title': 'Julian Smith & Travis Legg Watch Julian Smith', 'description': 'Julian and Travis watch Julian Smith', 'duration': 6863, }, }, { '...
_TESTS = [ { 'url': 'http://screen.yahoo.com/julian-smith-travis-legg-watch-214727115.html', 'info_dict': {
random_line_split
yahoo.py
97, } }, { 'url': 'https://ca.sports.yahoo.com/video/program-makes-hockey-more-affordable-013127711.html', 'md5': '57e06440778b1828a6079d2f744212c4', 'info_dict': { 'id': 'c9fa2a36-0d4d-3937-b8f6-cc0fb1881e73', 'ext': 'mp4',...
iaObj'][0] # The 'meta' field is not always in the video webpage, we request it # from another page video_id = info['id'] return self._get_info(video_id, display_id, webpage) def _extract_info(self, dis
conditional_block
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool { let i = limbs.i...
limbs[i].wrapping_neg_assign(); let j = i + 1; if j != len { limbs_not_in_place(&mut limbs[j..]); } false } pub fn limbs_twos_complement_in_place_alt_2(limbs: &mut [Limb]) -> bool { let carry = limbs_sub_limb_in_place(limbs, 1); limbs_not_in_place(limbs); carry }
{ return true; }
conditional_block
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool { let i = limbs.i...
}
random_line_split
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn
(limbs: &mut [Limb]) -> bool { let i = limbs.iter().cloned().take_while(|&x| x == 0).count(); let len = limbs.len(); if i == len { return true; } limbs[i].wrapping_neg_assign(); let j = i + 1; if j != len { limbs_not_in_place(&mut limbs[j..]); } false } pub fn limbs_...
limbs_twos_complement_in_place_alt_1
identifier_name
to_twos_complement_limbs.rs
use malachite_base::num::arithmetic::traits::WrappingNegAssign; use malachite_nz::natural::arithmetic::sub::limbs_sub_limb_in_place; use malachite_nz::natural::logic::not::limbs_not_in_place; use malachite_nz::platform::Limb; pub fn limbs_twos_complement_in_place_alt_1(limbs: &mut [Limb]) -> bool { let i = limbs.i...
{ let carry = limbs_sub_limb_in_place(limbs, 1); limbs_not_in_place(limbs); carry }
identifier_body
app.js
const bodyParser = require("body-parser"); const compression = require("compression"); const cors = require("cors"); const express = require("express"); const Joi = require("@hapi/joi"); const { HttpError, ObjectNotExistError } = require("./libs/errors"); const expressMongoDb = require("./middlewares/express_mongo_db")...
next(err); }); // development error handler // will print stacktrace if (app.get("env") === "development") { // eslint-disable-next-line app.use((err, req, res, next) => { if (err instanceof HttpError) { winston.warn(req.originalUrl, { ip: req.ip, ips: re...
random_line_split
app.js
const bodyParser = require("body-parser"); const compression = require("compression"); const cors = require("cors"); const express = require("express"); const Joi = require("@hapi/joi"); const { HttpError, ObjectNotExistError } = require("./libs/errors"); const expressMongoDb = require("./middlewares/express_mongo_db")...
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(expressMongoDb()); app.use(expressRedisDb(REDIS_URL)); app.use((req, res, next) => { req.manager = new ModelManager(req.db); next(); }); if (CORS_ANY === "TRUE") { app.use(cors()); } else { app.use( cors({...
{ app.use(logger("dev")); }
conditional_block
packed-struct-layout.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { unsafe { let s4 = S4 { a: 1, b: [2,3,4] }; let transd : [u8; 4] = mem::transmute(s4); assert_eq!(transd, [1, 2, 3, 4]); let s5 = S5 { a: 1, b: 0xff_00_00_ff }; let transd : [u8; 5] = mem::transmute(s5); // Don't worry about endianness, the u32 is pal...
a: u8, b: u32 }
random_line_split
packed-struct-layout.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { unsafe { let s4 = S4 { a: 1, b: [2,3,4] }; let transd : [u8; 4] = mem::transmute(s4); assert_eq!(transd, [1, 2, 3, 4]); let s5 = S5 { a: 1, b: 0xff_00_00_ff }; let transd : [u8; 5] = mem::transmute(s5); // Don't worry about endianness, the u32 is palindromic. ...
main
identifier_name
light.rs
use ::types::Vec3f; use ::types::Color; pub trait Light { /// Light direction /// v: Point to illuminate /// Returns the direction of light rays pointing from v fn direction(&self, v: Vec3f) -> Vec3f; /// Light illumincation /// v: Point to illuminate /// Returns the color of the ligh...
} pub struct PointLight { position: Vec3f, color: Color, } impl PointLight { pub fn new(position: Vec3f, color: Color) -> Self { Self { position, color } } pub fn set_position(&mut self, position: Vec3f) { self.position = position; } fn pos...
/// Line index of the closest shadow ray intesection /// Where the point is in shadow fn shadow(&self, t: f64) -> bool;
random_line_split
light.rs
use ::types::Vec3f; use ::types::Color; pub trait Light { /// Light direction /// v: Point to illuminate /// Returns the direction of light rays pointing from v fn direction(&self, v: Vec3f) -> Vec3f; /// Light illumincation /// v: Point to illuminate /// Returns the color of the ligh...
(&self, t: f64) -> bool { t < 1.0 } }
shadow
identifier_name
light.rs
use ::types::Vec3f; use ::types::Color; pub trait Light { /// Light direction /// v: Point to illuminate /// Returns the direction of light rays pointing from v fn direction(&self, v: Vec3f) -> Vec3f; /// Light illumincation /// v: Point to illuminate /// Returns the color of the ligh...
fn position(&self) -> &Vec3f { &self.position } } impl Light for PointLight { fn direction(&self, v: Vec3f) -> Vec3f { self.position - v } fn illumination(&self, v: Vec3f) -> Color { self.color } fn shadow(&self, t: f64) -> bool { t < 1.0 } }
{ self.position = position; }
identifier_body
test-helper.js
import {identity} from 'ladda-fp'; export const createApiFunction = (fn, config = {}) => { const fnCopy = fn.bind(null); fnCopy.operation = config.operation || 'NO_OPERATION'; fnCopy.invalidates = config.invalidates || []; fnCopy.idFrom = config.idFrom || 'ENTITY'; fnCopy.byId = config.byId || false; fnCop...
}; export const createSampleConfig = () => { return [ createEntityConfig({ name: 'user', api: { getUsers: createApiFunction(identity, {operation: 'READ'}), getUsers2: createApiFunction(identity, {operation: 'READ'}), deleteUser: createApiFunction(identity, {operation: 'DELETE'...
invalidatesOn: ['CREATE', 'UPDATE', 'DELETE'], ...config };
random_line_split
encoding.rs
// Copyright 2013-2014 Simon Sapin. // // 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 accordi...
.and_then(encoding_from_whatwg_label) .map(EncodingOverride::from_encoding) } pub fn is_utf8(&self) -> bool { self.encoding.is_none() } pub fn decode(&self, input: &[u8]) -> String { match self.encoding { Some(encoding) => encoding.decode(input, DecoderTrap:...
random_line_split
encoding.rs
// Copyright 2013-2014 Simon Sapin. // // 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 accordi...
; #[cfg(not(feature = "query_encoding"))] impl EncodingOverride { pub fn utf8() -> EncodingOverride { EncodingOverride } pub fn lookup(_label: &[u8]) -> Option<EncodingOverride> { None } pub fn is_utf8(&self) -> bool { true } pub fn decode(&self, input: &[u8]) -> ...
EncodingOverride
identifier_name
cli.js
#! /usr/bin/env node /* * This is the Command Line Implementation of the `emptydir` module * * Command Line Argument Processing * emptydir dirA dirB - empties the directories * emptydir --version - show version * emptydir --help - show this help message * emptydir -v - be verbose in empty...
}); args = new_args; if (args.length == 0) { process.stdout.write(missing_operand); return missing_operand; } // Invalid option? args_string = args.toString(); if (args_string.match(/^-/) || args_string.match(/,-/)) { process...
{ new_args.push(arg); }
conditional_block
cli.js
#! /usr/bin/env node /* * This is the Command Line Implementation of the `emptydir` module * * Command Line Argument Processing * emptydir dirA dirB - empties the directories * emptydir --version - show version * emptydir --help - show this help message * emptydir -v - be verbose in empty...
'\n' ] // Commandline runner function run(args, options){ args = args || []; if (!options) options = {}; missing_operand = options['missing_operand'] || ''; help_info = options['help_info'] || ''; version_info = options['version_info'] || ''; invalid_option = options['invalid_option'] || ''...
random_line_split
cli.js
#! /usr/bin/env node /* * This is the Command Line Implementation of the `emptydir` module * * Command Line Argument Processing * emptydir dirA dirB - empties the directories * emptydir --version - show version * emptydir --help - show this help message * emptydir -v - be verbose in empty...
return help_info; } else if (args[0] == '--help') { process.stdout.write(help_info); return help_info; } } // Are we verbose? var verbose = false; var new_args = []; args.forEach(function (arg) { ...
{ args = args || []; if (!options) options = {}; missing_operand = options['missing_operand'] || ''; help_info = options['help_info'] || ''; version_info = options['version_info'] || ''; invalid_option = options['invalid_option'] || ''; // Shift twice to remove the node executable and filen...
identifier_body
cli.js
#! /usr/bin/env node /* * This is the Command Line Implementation of the `emptydir` module * * Command Line Argument Processing * emptydir dirA dirB - empties the directories * emptydir --version - show version * emptydir --help - show this help message * emptydir -v - be verbose in empty...
(path, error) { if (error) { process.stdout.write('FAIL\t' + path + '\t->' + error.code + '\n'); return; } process.stdout.write('OKAY\t' + path + '\n'); } // Missing operand var missing_operand = [ 'emptydir: missing operand', 'Try \'emptydir --help\' for more information', '\n'...
print
identifier_name
0202-layers-overlays-simple-example.js
'use strict'; describe('Loading 0202-layers-overlays-simple-example.html', function() { beforeEach(function() { browser.get('0202-layers-overlays-simple-example.html'); browser.wait(function() { return element(by.css('img.leaflet-tile-loaded')).isPresent(); }, 5000); }); it('should change the...
}, 5000); expect(element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent()).toBe(true); var overlayButton = element(by.xpath('//input[@type=\'checkbox\'][1]')); overlayButton.click(); browser.driver.sleep(300); expect(element(by.xpath('//img[contains(...
expect(element(by.xpath('//img[contains(@src, "http://c.tile.openstreetmap.org/")]')).isPresent()).toBe(true); browser.actions().mouseMove(element(by.xpath('//a[contains(@class, "leaflet-control-layers-toggle")][1]'))).perform(); browser.wait(function() { return element(by.xpath('//img[contains(@src,...
random_line_split
fsGraphFactoryTest.ts
import { script } from 'lab'; import { expect } from 'chai'; import fsGraphFactory from '../src/lib/fsGraphFactory'; export const lab = script(); const { describe, it } = lab; export function isStrict(declaration)
describe('fsGraphFactory', () => { it('builds a strict graph from the files described in the globs', done => { fsGraphFactory({ globs: [ 'test/fsGraphFixture/**/*{Task,Factory}.ts' ], deriveKey: func => func.name.replace(/Fixture((Task)|(Factory))$/, '') }) .then(graph => { ...
{ const { dependencies, provider } = declaration; return (!dependencies || dependencies instanceof Array) && provider instanceof Function; }
identifier_body
fsGraphFactoryTest.ts
import { script } from 'lab'; import { expect } from 'chai'; import fsGraphFactory from '../src/lib/fsGraphFactory'; export const lab = script(); const { describe, it } = lab; export function isStrict(declaration) { const { dependencies, provider } = declaration; return (!dependencies || dependencies inst...
} expect(keys.sort()).to.eql(['a', 'b']); expect(allStrict).to.be.ok; done(); }); }); });
{ allStrict = false; break; }
conditional_block
fsGraphFactoryTest.ts
import { script } from 'lab'; import { expect } from 'chai'; import fsGraphFactory from '../src/lib/fsGraphFactory'; export const lab = script(); const { describe, it } = lab; export function isStrict(declaration) { const { dependencies, provider } = declaration; return (!dependencies || dependencies inst...
for (const key of keys) { if (!isStrict(graph[key])) { allStrict = false; break; } } expect(keys.sort()).to.eql(['a', 'b']); expect(allStrict).to.be.ok; done(); }); }); });
const keys = Object.keys(graph); let allStrict = true;
random_line_split
fsGraphFactoryTest.ts
import { script } from 'lab'; import { expect } from 'chai'; import fsGraphFactory from '../src/lib/fsGraphFactory'; export const lab = script(); const { describe, it } = lab; export function
(declaration) { const { dependencies, provider } = declaration; return (!dependencies || dependencies instanceof Array) && provider instanceof Function; } describe('fsGraphFactory', () => { it('builds a strict graph from the files described in the globs', done => { fsGraphFactory({ globs: [ ...
isStrict
identifier_name
ripgrepFileSearch.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
args.push('--quiet'); } args.push('--no-config'); if (config.disregardGlobalIgnoreFiles) { args.push('--no-ignore-global'); } return { args, siblingClauses }; } function anchor(glob: string) { return startsWith(glob, '**') || startsWith(glob, '/') ? glob : `/${glob}`; }
} if (config.exists) {
random_line_split
ripgrepFileSearch.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
args.push('-g', exclusion); if (isMac) { const normalized = normalizeNFD(exclusion); if (normalized !== exclusion) { args.push('-g', normalized); } } }); siblingClauses = rgGlobs.siblingClauses; if (folderQuery.disregardIgnoreFiles !== false) { // Don't use .gitignore or .ignore args.push('--...
{ const args = ['--files', '--hidden', '--case-sensitive']; // includePattern can't have siblingClauses foldersToIncludeGlobs([folderQuery], includePattern, false).forEach(globArg => { const inclusion = anchor(globArg); args.push('-g', inclusion); if (isMac) { const normalized = normalizeNFD(inclusion); ...
identifier_body
ripgrepFileSearch.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return { args, siblingClauses }; } function anchor(glob: string) { return startsWith(glob, '**') || startsWith(glob, '/') ? glob : `/${glob}`; }
{ args.push('--no-ignore-global'); }
conditional_block
ripgrepFileSearch.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(config: IRawSearch, folderQuery: IFolderSearch, includePattern: glob.IExpression, excludePattern: glob.IExpression) { const rgArgs = getRgArgs(config, folderQuery, includePattern, excludePattern); const cwd = folderQuery.folder; return { cmd: cp.spawn(rgDiskPath, rgArgs.args, { cwd }), siblingClauses: rgArgs.si...
spawnRipgrepCmd
identifier_name
fullscreen.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::io; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cfg(feature = ...
() { // enumerating monitors let monitor = { for (num, monitor) in glutin::get_available_monitors().enumerate() { println!("Monitor #{}: {:?}", num, monitor.get_name()); } print!("Please write the number of the monitor to use: "); let mut num = String::new(); ...
main
identifier_name
fullscreen.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::io; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main()
#[cfg(feature = "window")] fn main() { // enumerating monitors let monitor = { for (num, monitor) in glutin::get_available_monitors().enumerate() { println!("Monitor #{}: {:?}", num, monitor.get_name()); } print!("Please write the number of the monitor to use: "); ...
{ println!("This example requires glutin to be compiled with the `window` feature"); }
identifier_body
fullscreen.rs
#[cfg(target_os = "android")] #[macro_use]
extern crate glutin; use std::io; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cfg(feature = "window")] fn main() { // enumerating monitors let monitor = { ...
extern crate android_glue;
random_line_split
datatype-date-parse-coverage.js
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if ...
} }); // Add Parsers shortcut _yuitest_coverline("build/datatype-date-parse/datatype-date-parse.js", 29); Y.namespace("Parsers").date = Y.Date.parse; _yuitest_coverline("build/datatype-date-parse/datatype-date-parse.js", 31); Y.namespace("DataType"); _yuitest_coverline("build/datatype-date-parse/datatype-date-pa...
{ _yuitest_coverline("build/datatype-date-parse/datatype-date-parse.js", 23); return null; }
conditional_block
datatype-date-parse-coverage.js
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if ...
_yuitest_coverline("build/datatype-date-parse/datatype-date-parse.js", 10); Y.mix(Y.namespace("Date"), { /** * Converts data to type Date. * * @method parse * @param data {Date|Number|String} date object, timestamp (string or number), or string parsable by Date.parse * @return {Date} a Date...
* @module datatype-date * @submodule datatype-date-parse * @for Date */ _yuitest_coverfunc("build/datatype-date-parse/datatype-date-parse.js", "(anonymous 1)", 1);
random_line_split
pulse_generator.ts
// Interface for PulseGenerator driver // (c) Koheron interface PulseStatus { width: number; period: number; } class PulseGenerator { private driver: Driver; private id: number; private cmds: HashTable<ICommand>; private adc0: number[][]; // Volts private adc1: number[][]; // Volts ...
constructor (private client: Client) { this.driver = this.client.getDriver('Pulse'); this.id = this.driver.id; this.cmds = this.driver.getCmds(); this.adc0 = new Array(this.n_pts); this.adc1 = new Array(this.n_pts); for (var i: number = 0, len: number = this.adc0.le...
random_line_split
pulse_generator.ts
// Interface for PulseGenerator driver // (c) Koheron interface PulseStatus { width: number; period: number; } class PulseGenerator { private driver: Driver; private id: number; private cmds: HashTable<ICommand>; private adc0: number[][]; // Volts private adc1: number[][]; // Volts ...
} trigPulse(): void { this.client.send(Command(this.id, this.cmds['trig_pulse'])); } getStatus(cb: (status: PulseStatus) => void): void { this.client.readTuple(Command(this.id, this.cmds['get_status']), 'II', (tup: number[]) => { let status: PulseStatus = <PulseStatus>{}; ...
{ this.adc0[i] = [i, 0]; this.adc1[i] = [i, 0]; }
conditional_block
pulse_generator.ts
// Interface for PulseGenerator driver // (c) Koheron interface PulseStatus { width: number; period: number; } class PulseGenerator { private driver: Driver; private id: number; private cmds: HashTable<ICommand>; private adc0: number[][]; // Volts private adc1: number[][]; // Volts ...
setPulseWidth(width: number) { this.client.send(Command(this.id, this.cmds['set_pulse_width'], width)); } setPulsePeriod(period: number) { this.client.send(Command(this.id, this.cmds['set_pulse_period'], period)); } setDacData(data: Uint32Array): void { this.client.send(C...
{ this.client.readTuple(Command(this.id, this.cmds['get_status']), 'II', (tup: number[]) => { let status: PulseStatus = <PulseStatus>{}; status.width = tup[0]; status.period = tup[1]; cb(status); }); }
identifier_body
pulse_generator.ts
// Interface for PulseGenerator driver // (c) Koheron interface PulseStatus { width: number; period: number; } class PulseGenerator { private driver: Driver; private id: number; private cmds: HashTable<ICommand>; private adc0: number[][]; // Volts private adc1: number[][]; // Volts ...
(cb: (adc0: Array<Array<number>>, adc1: Array<Array<number>>) => void): void { this.client.readUint32Array(Command(this.id, this.cmds['get_fifo_buffer']), (data_rcv: Uint32Array) => { for (var i: number = 0, len: number = data_rcv.length; i < len; i++) { this.adc0[i] = [i, (((data_rc...
getFifoBuffer
identifier_name
global-state.ts
import { findIndexOf, removeElement } from './helper'; import { ComponentOrFactoryMetadata } from './tsdi'; export type ComponentListener = ( metadataOrExternal: ComponentOrFactoryMetadata | Function ) => void; let listeners: ComponentListener[] = []; const knownComponents: ComponentOrFactoryMetadata[] = []; const ...
export function addListener(listener: ComponentListener): void { listeners.push(listener); knownComponents.forEach((metadata) => listener(metadata)); knownExternals.forEach((external) => listener(external)); } export function removeListener(listener: ComponentListener): void { listeners = removeElement(listen...
} export function isKnownExternal(external: Function): boolean { return findIndexOf(knownExternals, (fn) => fn === external) !== -1; }
random_line_split
global-state.ts
import { findIndexOf, removeElement } from './helper'; import { ComponentOrFactoryMetadata } from './tsdi'; export type ComponentListener = ( metadataOrExternal: ComponentOrFactoryMetadata | Function ) => void; let listeners: ComponentListener[] = []; const knownComponents: ComponentOrFactoryMetadata[] = []; const ...
(external: Function): void { if (!isKnownExternal(external)) { knownExternals.push(external); listeners.forEach((listener) => listener(external)); } } export function isKnownExternal(external: Function): boolean { return findIndexOf(knownExternals, (fn) => fn === external) !== -1; } export function addL...
addKnownExternal
identifier_name
global-state.ts
import { findIndexOf, removeElement } from './helper'; import { ComponentOrFactoryMetadata } from './tsdi'; export type ComponentListener = ( metadataOrExternal: ComponentOrFactoryMetadata | Function ) => void; let listeners: ComponentListener[] = []; const knownComponents: ComponentOrFactoryMetadata[] = []; const ...
export function isKnownExternal(external: Function): boolean { return findIndexOf(knownExternals, (fn) => fn === external) !== -1; } export function addListener(listener: ComponentListener): void { listeners.push(listener); knownComponents.forEach((metadata) => listener(metadata)); knownExternals.forEach((ex...
{ if (!isKnownExternal(external)) { knownExternals.push(external); listeners.forEach((listener) => listener(external)); } }
identifier_body
global-state.ts
import { findIndexOf, removeElement } from './helper'; import { ComponentOrFactoryMetadata } from './tsdi'; export type ComponentListener = ( metadataOrExternal: ComponentOrFactoryMetadata | Function ) => void; let listeners: ComponentListener[] = []; const knownComponents: ComponentOrFactoryMetadata[] = []; const ...
} export function isKnownExternal(external: Function): boolean { return findIndexOf(knownExternals, (fn) => fn === external) !== -1; } export function addListener(listener: ComponentListener): void { listeners.push(listener); knownComponents.forEach((metadata) => listener(metadata)); knownExternals.forEach((...
{ knownExternals.push(external); listeners.forEach((listener) => listener(external)); }
conditional_block
crypto.py
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. import sys from OpenSSL.crypto import TYPE_DSA, Error, PKey, X509 class Checker_X509_get_pubkey(object):
""" Call the method repeatedly such that it will return a PKey object. """ small = xrange(3) for i in xrange(self.iterations): key = PKey() key.generate_key(TYPE_DSA, 256) for i in small: cert = X509() cert.set_p...
""" Leak checks for L{X509.get_pubkey}. """ def __init__(self, iterations): self.iterations = iterations def check_exception(self): """ Call the method repeatedly such that it will raise an exception. """ for i in xrange(self.iterations): cert = X509...
identifier_body
crypto.py
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. import sys from OpenSSL.crypto import TYPE_DSA, Error, PKey, X509 class Checker_X509_get_pubkey(object): """ Leak checks for L{X509.get_pubkey}. """ def __init__(self, iterations): self.iterations = iterations def check_exce...
if __name__ == '__main__': main(*sys.argv[1:])
if klass.startswith('Checker_'): klass = globals()[klass] print klass checker = klass(iterations) for meth in dir(checker): if meth.startswith('check_'): print '\t', meth, vmsize(), '...', getattr(checker, meth)() ...
conditional_block
crypto.py
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. import sys from OpenSSL.crypto import TYPE_DSA, Error, PKey, X509 class Checker_X509_get_pubkey(object): """ Leak checks for L{X509.get_pubkey}. """ def __init__(self, iterations): self.iterations = iterations def check_exce...
def main(iterations='1000'): iterations = int(iterations) for klass in globals(): if klass.startswith('Checker_'): klass = globals()[klass] print klass checker = klass(iterations) for meth in dir(checker): if meth.startswith('check_'): ...
random_line_split
crypto.py
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. import sys from OpenSSL.crypto import TYPE_DSA, Error, PKey, X509 class Checker_X509_get_pubkey(object): """ Leak checks for L{X509.get_pubkey}. """ def __init__(self, iterations): self.iterations = iterations def check_exce...
(iterations='1000'): iterations = int(iterations) for klass in globals(): if klass.startswith('Checker_'): klass = globals()[klass] print klass checker = klass(iterations) for meth in dir(checker): if meth.startswith('check_'): ...
main
identifier_name
MysqlHelper.py
#encoding=utf-8 import pymysql import json class MysqlHelper: """mysql 帮助类""" @staticmethod def insert
asymbol,esymbol,explain,cizu,liju,xiangguancihui,aspoken,espoken): db=pymysql.connect(host="192.168.180.187",user="root",password="123456",db="lytest",charset="utf8") cursor=db.cursor() print(word.encode("utf8")) print("--------------------------------insert into mysql db") curso...
(word,
identifier_name
MysqlHelper.py
#encoding=utf-8 import pymysql import json class MysqlHelper:
"""mysql 帮助类""" @staticmethod def insert(word,asymbol,esymbol,explain,cizu,liju,xiangguancihui,aspoken,espoken): db=pymysql.connect(host="192.168.180.187",user="root",password="123456",db="lytest",charset="utf8") cursor=db.cursor() print(word.encode("utf8")) print("------------...
identifier_body
MysqlHelper.py
#encoding=utf-8 import pymysql import json class MysqlHelper:
"""mysql 帮助类""" @staticmethod def insert(word,asymbol,esymbol,explain,cizu,liju,xiangguancihui,aspoken,espoken): db=pymysql.connect(host="192.168.180.187",user="root",password="123456",db="lytest",charset="utf8") cursor=db.cursor() print(word.encode("utf8")) print("--------...
random_line_split
findRegressions-simple.py
#!/usr/bin/env python import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def parse(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' ...
elif math.isnan(d_old[t][x]) and not math.isnan(d_new[t][x]): passes[x] += t + "\n" elif not math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]): regressions[x] += t + ": NaN%\n" if d_new[t][x] > d_old[t][x] and d_old[t][x] > 0.0 and \ (d_new[t][x] - d_old[t...
continue
conditional_block
findRegressions-simple.py
#!/usr/bin/env python import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def parse(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' ...
if d_old[t][x] == 'PASS': if d_new[t][x] != 'PASS': regressions[x] += t + "\n" else: if d_new[t][x] == 'PASS': passes[x] += t + "\n" else : regressions[x] += t + "\n" if x == 'compile state' or x == 'exec...
regressions = {} passes = {} removed = '' for x in ['compile state', 'compile time', 'exec state', 'exec time']: regressions[x] = '' passes[x] = '' for t in sorted(d_old.keys()) : if d_new.has_key(t): # Check if the test passed or failed. for x in ['compile state', 'compile time', 'ex...
identifier_body
findRegressions-simple.py
#!/usr/bin/env python import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def
(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' for t in r: if DEBUG: print t if t[0] == 'PASS' or t[0] == 'FAIL' : tmp = t[2].split('llvm-te...
parse
identifier_name
findRegressions-simple.py
#!/usr/bin/env python import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def parse(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' ...
# print "ERROR!" sys.exit(1) except: continue return test # Diff results and look for regressions. def diffResults(d_old, d_new): regressions = {} passes = {} removed = '' for x in ['compile state', 'compile time', 'exec state', 'exec time']: regressions[x] = '' ...
random_line_split
base.py
import sys, os, shutil import markdown from pyquery import PyQuery as pq j = os.path.join md = markdown.Markdown(extensions=['toc', 'codehilite']) up = lambda p: j(*os.path.split(p)[:-1]) dirname = lambda p: os.path.basename(os.path.abspath(p)) extensions = ['md', 'mdown', 'markdown'] INDEX_PRE = u'''\ <!DOCTYPE htm...
(title, header, footer, source, destination, page_type, toc=None): with open(source) as f: data = _read(f) fallback_title = _get_fallback_title(source) if page_type == 'content': page_title = _find_title(data) or fallback_title title_tag = page_title + ' / ' + title else: ...
_render
identifier_name
base.py
import sys, os, shutil import markdown from pyquery import PyQuery as pq j = os.path.join md = markdown.Markdown(extensions=['toc', 'codehilite']) up = lambda p: j(*os.path.split(p)[:-1]) dirname = lambda p: os.path.basename(os.path.abspath(p)) extensions = ['md', 'mdown', 'markdown'] INDEX_PRE = u'''\ <!DOCTYPE htm...
def _get_project_title(source): if os.path.isfile(j(source, 'title')): with open(j(source, 'title')) as f: return _read(f).strip() else: current = dirname(source).lower() if current not in ['doc', 'docs', 'documentation']: return current else: ...
parts = filename.split('-', 1) if len(parts) > 1 and all(c in '0123456789' for c in parts[0]): filename = parts[1] return j(destination, filename.rsplit('.', 1)[0])
identifier_body
base.py
import sys, os, shutil import markdown from pyquery import PyQuery as pq j = os.path.join md = markdown.Markdown(extensions=['toc', 'codehilite']) up = lambda p: j(*os.path.split(p)[:-1]) dirname = lambda p: os.path.basename(os.path.abspath(p)) extensions = ['md', 'mdown', 'markdown'] INDEX_PRE = u'''\ <!DOCTYPE htm...
def _write(f, content): return f.write(content.encode('utf-8')) def _get_target_url(path, destination): return os.path.split(_get_target(path, destination))[-1] def _get_target(filename, destination): parts = filename.split('-', 1) if len(parts) > 1 and all(c in '0123456789' for c in parts[0]): ...
def _read(f): return f.read().decode('utf-8')
random_line_split
base.py
import sys, os, shutil import markdown from pyquery import PyQuery as pq j = os.path.join md = markdown.Markdown(extensions=['toc', 'codehilite']) up = lambda p: j(*os.path.split(p)[:-1]) dirname = lambda p: os.path.basename(os.path.abspath(p)) extensions = ['md', 'mdown', 'markdown'] INDEX_PRE = u'''\ <!DOCTYPE htm...
def _get_footer(source): for ext in extensions: filename = 'footer.' + ext target = j(source, filename); if os.path.isfile(target): with open(target) as f: return md.convert(_read(f)) return '' def _get_toc(chapters, destination): toc = '<h2>Table of...
name, ext = os.path.splitext(filename) if ext[1:] in extensions: if name not in ['footer', 'index']: yield filename
conditional_block
hist_bench.py
curr_state in proliferants: prolif_pes.append(pes[i]) prolif_st.append(curr_state) return(prolif_st, prolif_pes) # From a matched pair of numpy arrays containing countries and their pursuit # scores, make a new array of the scores for the subset of countries that # actually chose to pursue...
score = np.nan elif (n_tot == step0): score = 0 elif (n_tot <= stepA): score = 2
random_line_split
hist_bench.py
China"] = 9 t2acq["Egypt"] = -50 t2acq["France"] = 6 t2acq["India"] = 10 t2acq["Iran"] = -30 t2acq["Iraq"] = -32 t2acq["Israel"] = 9 t2acq["Libya"] = -45 t2acq["N-Korea"] = 26 t2acq["S-Korea"] = -45 t2acq["Pakist"] = 15 t2acq["S-Afric"] = 5 t2acq["Syria"] = -15 t2acq[...
score = 6
conditional_block
hist_bench.py
_data['Weapon_Status_1'], raw_data['Conflict_Relation_1'], raw_data['Weapon_Status_2'], raw_data['Conflict_Relation_2'], raw_data['Weapon_Status_3'], raw_data['Conflict_Relation_3'], raw_d...
relations2conflict_score
identifier_name
hist_bench.py
score = np.nan elif (gpi_val < stepA): score = 2 elif (gpi_val < stepB): score = 4 elif (gpi_val < stepC): score = 6 elif (gpi_val < stepD): score = 8 else: score = 10 all_scores[i] = score ...
score_matrix = { "ally_0_0": 2, "neut_0_0": 2, "enemy_0_0": 6, "ally_0_2": 3, "neut_0_2": 4, "enemy_0_2": 8, "ally_0_3": 1, "neut_0_3": 4, "enemy_0_3": 6, "ally_2_2": 3, "neut_2_2": 4, "enemy_2_2": 9, "ally_2_3": 3, ...
identifier_body
PropertiesShaderPlane.ts
/// <reference path="../typed/rx.d.ts"/> /// <reference path="./ShaderPlane.ts"/> /// <reference path="./UniformsManager.ts"/> class PropertiesShaderPlane { private _shaderSubject: Rx.Subject<ShaderText>; private _meshSubject: Rx.Subject<THREE.Mesh>; private _uniformsManager: UniformsManager; MeshObservable: R...
(shader: ShaderText) { /* Calculate the uniforms after it's subscribed to*/ this._shaderSubject.onNext(shader); this._uniformsManager.calculateUniforms(); } }
onShaderText
identifier_name
PropertiesShaderPlane.ts
/// <reference path="../typed/rx.d.ts"/> /// <reference path="./ShaderPlane.ts"/>
private _uniformsManager: UniformsManager; MeshObservable: Rx.Observable<THREE.Mesh>; constructor(glProperties: Array<UniformProvider<any>>) { this._shaderSubject = new Rx.Subject<ShaderText>(); this._meshSubject = new Rx.Subject<THREE.Mesh>(); this.MeshObservable = this._meshSubject.asObservable(); ...
/// <reference path="./UniformsManager.ts"/> class PropertiesShaderPlane { private _shaderSubject: Rx.Subject<ShaderText>; private _meshSubject: Rx.Subject<THREE.Mesh>;
random_line_split
validation-parser.ts
/** * @file Validation Parser * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private */ import { Debug, Log, ParserRegistry } from '../globals' import XmlParser, { XmlParserParameters } from './xml-parser' import Validation from '../structure/validation' import Streamer from '../streamer/streamer'; cla...
get isXml () { return true } _parse () { super._parse() if (Debug) Log.time('ValidationParser._parse ' + this.name) this.validation.fromXml(this.xml.data) if (Debug) Log.timeEnd('ValidationParser._parse ' + this.name) } } ParserRegistry.add('validation', ValidationParser) export default Val...
{ return 'validation' }
identifier_body
validation-parser.ts
/** * @file Validation Parser * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private */ import { Debug, Log, ParserRegistry } from '../globals' import XmlParser, { XmlParserParameters } from './xml-parser' import Validation from '../structure/validation' import Streamer from '../streamer/streamer'; cla...
() { super._parse() if (Debug) Log.time('ValidationParser._parse ' + this.name) this.validation.fromXml(this.xml.data) if (Debug) Log.timeEnd('ValidationParser._parse ' + this.name) } } ParserRegistry.add('validation', ValidationParser) export default ValidationParser
_parse
identifier_name
validation-parser.ts
/** * @file Validation Parser * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private */ import { Debug, Log, ParserRegistry } from '../globals' import XmlParser, { XmlParserParameters } from './xml-parser' import Validation from '../structure/validation' import Streamer from '../streamer/streamer';
this.useDomParser = true this.validation = new Validation(this.name, this.path) } get __objName () { return 'validation' } get isXml () { return true } _parse () { super._parse() if (Debug) Log.time('ValidationParser._parse ' + this.name) this.validation.fromXml(this.xml.data) if (...
class ValidationParser extends XmlParser { constructor (streamer: Streamer, params?: Partial<XmlParserParameters>) { const p = params || {} super(streamer, p)
random_line_split
videotest.js
video is currently paused or has ended (via the Media API's paused and ended attributes); if so, it uses the play() method to playback the video. Otherwise the video must be playing, so it is paused using the pause() method. */ //Stop stop.addEventListener('click', function(e) { video.pause(); vid...
/* Coming back to the video.duration problem mentioned above, when the timeupdate event is raised, in most mobile browsers the video's duration attribute should now have the correct value. This can be taken advantage of to set the progress element's max attribute if it is currently not set: */ video.addEv...
random_line_split
securitygroup.py
""" -*- coding: utf-8 -*- """ from python2awscli import bin_aws from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate from python2awscli import must class BaseSecurityGroup(object): def __init__(self, name, region, vpc, description, inbound=None, outbound=None): """ :param name: S...
""" Delete myself by my own id. As of 20170114 no other methods call me. You must do `foo._delete()` :return: """ command = ['ec2', 'delete-security-group', '--region', self.region, # '--dry-run', '--group-id', self.id ] ...
identifier_body
securitygroup.py
""" -*- coding: utf-8 -*- """ from python2awscli import bin_aws from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate from python2awscli import must class BaseSecurityGroup(object): def
(self, name, region, vpc, description, inbound=None, outbound=None): """ :param name: String, name of SG :param region: String, AWS region :param vpc: String, IP of the VPC this SG belongs to :param description: String :param inbound: List of dicts, IP Permissions that sh...
__init__
identifier_name
securitygroup.py
""" -*- coding: utf-8 -*- """ from python2awscli import bin_aws from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate from python2awscli import must class BaseSecurityGroup(object): def __init__(self, name, region, vpc, description, inbound=None, outbound=None): """ :param name: S...
def _rm_rule(self, ip_permissions, egress): """ :param ip_permissions: Dict of IP Permissions :param egress: Bool :return: Bool """ direction = 'revoke-security-group-ingress' if egress: direction = 'revoke-security-group-egress' command = ...
return True
random_line_split
securitygroup.py
""" -*- coding: utf-8 -*- """ from python2awscli import bin_aws from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate from python2awscli import must class BaseSecurityGroup(object): def __init__(self, name, region, vpc, description, inbound=None, outbound=None): """ :param name: S...
for rule in requested: if rule not in active: self._add_rule(rule, egress) for active_rule in active: if active_rule not in requested: self._rm_rule(active_rule, egress) return True def _add_rule(self, ip_permissions, egress): ...
raise ParseError( 'SecurityGroup {0}, need a list of dicts, instead got "{1}"'.format(self.name, requested))
conditional_block