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
asm.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn get_clobbers() -> String { "~{dirflag},~{fpsr},~{flags}".to_string() }
{ "".to_string() }
identifier_body
SortSelect.tsx
import { Select, Flex, SelectProps } from "@artsy/palette" import React from "react" import { Media } from "v2/Utils/Responsive" import { useAuctionResultsFilterContext } from "../AuctionResultsFilterContext" // TODO: move this to sortOptions? const SORTS = [ { value: "DATE_DESC", text: "Sale Date (Most rece...
export const SortSelect = () => { const filterContext = useAuctionResultsFilterContext() const props: SelectProps = { width: "auto", variant: "inline", options: SORTS, selected: filterContext?.filters?.sort, onSelect: sort => { filterContext.setFilter("sort", sort) }, } return ( ...
value: "PRICE_AND_DATE_DESC", text: "Sale price", }, ]
random_line_split
communicate.rs
//! Defines the messages passed between client and server. use cgmath::{Aabb3, Vector2, Vector3, Point3}; use std::default::Default; use std::ops::Add; use block_position::BlockPosition; use entity::EntityId; use lod::LODIndex; use serialize::{Copyable, Flatten, MemStream, EOF}; use terrain_block::TerrainBlock; #[de...
(self, rhs: u32) -> ClientId { let ClientId(i) = self; ClientId(i + rhs) } } #[derive(Debug, Clone)] /// TerrainBlock plus identifying info, e.g. for transmission between server and client. pub struct TerrainBlockSend { #[allow(missing_docs)] pub position: Copyable<BlockPosition>, #[allow(missing_docs)...
add
identifier_name
communicate.rs
//! Defines the messages passed between client and server. use cgmath::{Aabb3, Vector2, Vector3, Point3}; use std::default::Default; use std::ops::Add; use block_position::BlockPosition; use entity::EntityId; use lod::LODIndex; use serialize::{Copyable, Flatten, MemStream, EOF}; use terrain_block::TerrainBlock; #[de...
UpdatePlayer(Copyable<EntityId>, Copyable<Aabb3<f32>>), /// Update the client's view of a mob with a given mesh. UpdateMob(Copyable<EntityId>, Copyable<Aabb3<f32>>), /// The sun as a [0, 1) portion of its cycle. UpdateSun(Copyable<f32>), /// Provide a block of terrain to a client. UpdateBlock(TerrainBl...
random_line_split
ccuclkcr.rs
#[doc = "Register `CCUCLKCR` reader"] pub struct R(crate::R<CCUCLKCR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CCUCLKCR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CCUCLKCR_SPEC>> for R { #[inline(always)] fn from(reader: ...
} } impl R { #[doc = "Bit 0 - CCU Clock Divider Enable"] #[inline(always)] pub fn ccudiv(&self) -> CCUDIV_R { CCUDIV_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0 - CCU Clock Divider Enable"] #[inline(always)] pub fn ccudiv(&mut self) -> CCUDIV_W { CCUDIV_W ...
#[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w
random_line_split
ccuclkcr.rs
#[doc = "Register `CCUCLKCR` reader"] pub struct R(crate::R<CCUCLKCR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CCUCLKCR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CCUCLKCR_SPEC>> for R { #[inline(always)] fn from(reader: ...
(crate::W<CCUCLKCR_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CCUCLKCR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } i...
W
identifier_name
ccuclkcr.rs
#[doc = "Register `CCUCLKCR` reader"] pub struct R(crate::R<CCUCLKCR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CCUCLKCR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CCUCLKCR_SPEC>> for R { #[inline(always)] fn from(reader: ...
} impl R { #[doc = "Bit 0 - CCU Clock Divider Enable"] #[inline(always)] pub fn ccudiv(&self) -> CCUDIV_R { CCUDIV_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0 - CCU Clock Divider Enable"] #[inline(always)] pub fn ccudiv(&mut self) -> CCUDIV_W { CCUDIV_W { w: ...
{ self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w }
identifier_body
LanguageList.js
/* * Popular Repositories * Copyright (c) 2014 Alberto Congiu (@4lbertoC) * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var React = require('react'); /** * Like Array.map(), but on an object's own properties. ...
/** * A component that displays a GitHub repo's languages. * * @prop {GitHubRepoLanguages} gitHubRepoLanguages. */ var LanguageList = React.createClass({ propTypes: { gitHubRepoLanguages: React.PropTypes.object.isRequired }, render() { var gitHubRepoLanguages = this.props.gitHubRepoLanguages; ...
{ var results = []; if (obj) { for(var key in obj) { if (obj.hasOwnProperty(key)) { results.push(func(obj[key], key)); } } } return results; }
identifier_body
LanguageList.js
/* * Popular Repositories * Copyright (c) 2014 Alberto Congiu (@4lbertoC) * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var React = require('react'); /** * Like Array.map(), but on an object's own properties. ...
() { var gitHubRepoLanguages = this.props.gitHubRepoLanguages; /* jshint ignore:start */ return ( <div className="text-center language-list"> {mapObject(gitHubRepoLanguages, (percentage, languageName) => { return ( <div className="language" key={languageName}> ...
render
identifier_name
LanguageList.js
/* * Popular Repositories * Copyright (c) 2014 Alberto Congiu (@4lbertoC) * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var React = require('react'); /** * Like Array.map(), but on an object's own properties. ...
}); module.exports = LanguageList;
random_line_split
LanguageList.js
/* * Popular Repositories * Copyright (c) 2014 Alberto Congiu (@4lbertoC) * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var React = require('react'); /** * Like Array.map(), but on an object's own properties. ...
} } return results; } /** * A component that displays a GitHub repo's languages. * * @prop {GitHubRepoLanguages} gitHubRepoLanguages. */ var LanguageList = React.createClass({ propTypes: { gitHubRepoLanguages: React.PropTypes.object.isRequired }, render() { var gitHubRepoLanguages = this.p...
{ results.push(func(obj[key], key)); }
conditional_block
development.py
from .base import BASE_DIR, INSTALLED_APPS, MIDDLEWARE_CLASSES, REST_FRAMEWORK DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] SECRET_KEY = 'secret' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'holonet', 'USER': 'holonet', 'PASSWORD': '', ...
BROKER_URL = 'redis://127.0.0.1' ELASTICSEARCH = { 'default': { 'hosts': [ '127.0.0.1:9200' ] } } REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] += ['rest_framework.renderers.BrowsableAPIRenderer'] INSTALLED_APPS += ('debug_toolbar', ) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware....
EMAIL_BACKEND = 'django.utils.mail.backends.console.EmailBackend'
random_line_split
polygons_to_edges.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
(): bpy.utils.unregister_class(Pols2EdgsNode) if __name__ == '__main__': register()
unregister
identifier_name
polygons_to_edges.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
def polstoedgs(self, pols): out = [] for obj in pols: object = [] for pols in obj: edgs = [] for i, ind in enumerate(pols): #print('p2e',str(i%2), str(ind)) this = [ind, pols[i-1]] t...
out = [] for faces in obj: out_edges = [] #set() #[] for face in faces: for edge in zip(face, face[1:]+[face[0]]): #out_edges.add(tuple(sorted(edge))) out_edges.append(list(edge)) out.append(out_edges) return out
identifier_body
polygons_to_edges.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
X_ = SvGetSocketAnyType(self, self.inputs['pols']) X = dataCorrect(X_) #print('p2e-X',str(X)) result = self.pols_edges(X) #result = self.polstoedgs(X) SvSetSocketAnyType(self, 'edgs', result) def pols_edges(self, obj): ...
def process(self): if 'edgs' in self.outputs and len(self.outputs['edgs'].links) > 0: if 'pols' in self.inputs and len(self.inputs['pols'].links) > 0:
random_line_split
polygons_to_edges.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
register()
conditional_block
strutil.rs
// miscelaneous string utilities // returns the string slice following the target, if any pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> { if let Some(idx) = s.find(target) { Some(&s[(idx+target.len())..]) } else { None } }
// like after, but subsequently finds a word following... pub fn word_after(txt: &str, target: &str) -> Option<String> { if let Some(txt) = after(txt,target) { // maybe skip some space, and end with whitespace or semicolon let start = txt.find(|c:char| c.is_alphanumeric()).unwrap(); let end ...
random_line_split
strutil.rs
// miscelaneous string utilities // returns the string slice following the target, if any pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> { if let Some(idx) = s.find(target) { Some(&s[(idx+target.len())..]) } else { None } } // like after, but subsequently finds a word fo...
// split into two at a delimiter pub fn split(txt: &str, delim: char) -> (&str,&str) { if let Some(idx) = txt.find(delim) { (&txt[0..idx], &txt[idx+1..]) } else { (txt,"") } }
{ (iter.next().unwrap(), iter.next().unwrap()) }
identifier_body
strutil.rs
// miscelaneous string utilities // returns the string slice following the target, if any pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> { if let Some(idx) = s.find(target) { Some(&s[(idx+target.len())..]) } else { None } } // like after, but subsequently finds a word fo...
(txt: &str, delim: char) -> (&str,&str) { if let Some(idx) = txt.find(delim) { (&txt[0..idx], &txt[idx+1..]) } else { (txt,"") } }
split
identifier_name
strutil.rs
// miscelaneous string utilities // returns the string slice following the target, if any pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> { if let Some(idx) = s.find(target)
else { None } } // like after, but subsequently finds a word following... pub fn word_after(txt: &str, target: &str) -> Option<String> { if let Some(txt) = after(txt,target) { // maybe skip some space, and end with whitespace or semicolon let start = txt.find(|c:char| c.is_alphanumeric...
{ Some(&s[(idx+target.len())..]) }
conditional_block
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys class MyTest(TestCommand): def run_tests(self): tests = unittest.TestLoader().discover('tests', pattern='test_*.py') unittes...
packages=find_packages(include=['flask_restapi']), install_requires=[ 'peewee', 'flask', 'wtforms', 'flask_bcrypt', 'flask-script', 'peewee-rest-query' ], test_suite='nose.collector', tests_require=['nose'], classifiers=[ 'Programming Langu...
description=u'A simple rest query framework by flask, peewee, rest_query', author='dracarysX', author_email='huiquanxiong@gmail.com', url='https://github.com/dracarysX/flask_restapi',
random_line_split
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys class MyTest(TestCommand): def run_tests(self):
setup( name='flask_restapi', version='0.2.0', license='MIT', description=u'A simple rest query framework by flask, peewee, rest_query', author='dracarysX', author_email='huiquanxiong@gmail.com', url='https://github.com/dracarysX/flask_restapi', packages=find_packages(include=['flask_r...
tests = unittest.TestLoader().discover('tests', pattern='test_*.py') unittest.TextTestRunner(verbosity=1).run(tests)
identifier_body
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys class
(TestCommand): def run_tests(self): tests = unittest.TestLoader().discover('tests', pattern='test_*.py') unittest.TextTestRunner(verbosity=1).run(tests) setup( name='flask_restapi', version='0.2.0', license='MIT', description=u'A simple rest query framework by flask, peewee, rest_q...
MyTest
identifier_name
searcher.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 ...
if i == "" { dirs_to_search.push(Path::new("/usr/share/terminfo")); } else { dirs_to_search.push(Path::new(i)); } }, // Found nothing in TERMINFO_DIRS, use the default paths: ...
{ if term.len() == 0 { return None; } let homedir = os::homedir(); let mut dirs_to_search = Vec::new(); let first_char = term.char_at(0); // Find search directory match getenv("TERMINFO") { Some(dir) => dirs_to_search.push(Path::new(dir)), None => { if ...
identifier_body
searcher.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 ...
(term: &str) -> Result<File, String> { match get_dbpath_for_term(term) { Some(x) => { match File::open(&*x) { Ok(file) => Ok(file), Err(e) => Err(format!("error opening file: {:?}", e)), } } None => { Err(format!("could not ...
open
identifier_name
searcher.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 ...
#[test] #[ignore(reason = "see test_get_dbpath_for_term")] fn test_open() { open("screen").unwrap(); let t = open("nonexistent terminal that hopefully does not exist"); assert!(t.is_err()); }
}
random_line_split
deriving-meta.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}
a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness
random_line_split
deriving-meta.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }
{}
identifier_body
deriving-meta.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<T: Hash>(_t: &T) {} pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }
hash
identifier_name
constantsourcenode.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::audioparam::AudioParam; use crate::dom::audioscheduledsourcenode::AudioScheduledSourceNode; use c...
#[allow(unrooted_must_root)] pub fn new( window: &Window, context: &BaseAudioContext, options: &ConstantSourceOptions, ) -> Fallible<DomRoot<ConstantSourceNode>> { let node = ConstantSourceNode::new_inherited(window, context, options)?; Ok(reflect_dom_object( ...
}
random_line_split
constantsourcenode.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::audioparam::AudioParam; use crate::dom::audioscheduledsourcenode::AudioScheduledSourceNode; use c...
(&self) -> DomRoot<AudioParam> { DomRoot::from_ref(&self.offset) } } impl<'a> From<&'a ConstantSourceOptions> for ServoMediaConstantSourceOptions { fn from(options: &'a ConstantSourceOptions) -> Self { Self { offset: *options.offset, } } }
Offset
identifier_name
3b0d1321079e_.py
"""Add replies column Revision ID: 3b0d1321079e Revises: 1e2d77a2f0c4 Create Date: 2021-11-03 23:32:15.720557 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "3b0d1321079e" down_revision = "1e2d7...
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("comment", "replies") # ### end Alembic commands ###
op.add_column( "comment", sa.Column( "replies", postgresql.JSONB(astext_type=sa.Text()), nullable=True ), ) # ### end Alembic commands ###
identifier_body
3b0d1321079e_.py
"""Add replies column Revision ID: 3b0d1321079e Revises: 1e2d77a2f0c4 Create Date: 2021-11-03 23:32:15.720557 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "3b0d1321079e" down_revision = "1e2d7...
(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "comment", sa.Column( "replies", postgresql.JSONB(astext_type=sa.Text()), nullable=True ), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic...
upgrade
identifier_name
3b0d1321079e_.py
"""Add replies column Revision ID: 3b0d1321079e Revises: 1e2d77a2f0c4 Create Date: 2021-11-03 23:32:15.720557 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "3b0d1321079e"
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "comment", sa.Column( "replies", postgresql.JSONB(astext_type=sa.Text()), nullable=True ), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated...
down_revision = "1e2d77a2f0c4" branch_labels = None depends_on = None
random_line_split
pivots.action.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
* along with this program. If not, see <http://www.gnu.org/licenses/>. */ import {Action} from '@ngrx/store'; import {Pivot, PivotConfig} from './pivot'; export enum PivotsActionType { ADD_PIVOT = '[Pivot] Add pivot', REMOVE_PIVOT = '[Pivot] Remove pivot', SET_CONFIG = '[Pivot] Set config', CLEAR = '[Piv...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License
random_line_split
pivots.action.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
implements Action { public readonly type = PivotsActionType.SET_CONFIG; public constructor(public payload: {pivotId: string; config: PivotConfig}) {} } export class Clear implements Action { public readonly type = PivotsActionType.CLEAR; } export type All = AddPivot | RemovePivot | SetConfig | C...
SetConfig
identifier_name
try_init.rs
use { serde_json, string }; use dispatch::{ add_node, connect_nodes, get }; use error::*; use action::{ AddNode, ConnectNodes }; use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP }; use libflo_std::LIBFLO; pub unsafe fn
() -> Result<()> { if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? { let action_mapper = ACTION_MAPPER.read()?; let libflo = LIBFLO.read()?; let module_mapper = libflo.get_module_mapper(); // Set up parser let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(a...
try_init
identifier_name
try_init.rs
use { serde_json, string }; use dispatch::{ add_node, connect_nodes, get }; use error::*; use action::{ AddNode, ConnectNodes }; use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP }; use libflo_std::LIBFLO;
// Set up parser let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg)); let connect_nodes_parser = parse_fn(|arg| serde_json::from_str::<ConnectNodes>(arg)); let get_parser = parse_fn(|arg| serde_json::from_str::<BasicAction>(arg)); let parser = ParseMap::n...
pub unsafe fn try_init() -> Result<()> { if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? { let action_mapper = ACTION_MAPPER.read()?; let libflo = LIBFLO.read()?; let module_mapper = libflo.get_module_mapper();
random_line_split
try_init.rs
use { serde_json, string }; use dispatch::{ add_node, connect_nodes, get }; use error::*; use action::{ AddNode, ConnectNodes }; use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP }; use libflo_std::LIBFLO; pub unsafe fn try_init() -> Result<()> {...
PARSE_MAP.set(parser)?; // Set up dispatch map let add_node_dispatch = dispatch_fn(|arg| add_node(arg)); let connect_nodes_dispatch = dispatch_fn(|arg| connect_nodes(arg)); let get_dispatch = dispatch_fn(|_: &BasicAction| get()); let dispatch_map = DispatchMap::new( ...
{ let action_mapper = ACTION_MAPPER.read()?; let libflo = LIBFLO.read()?; let module_mapper = libflo.get_module_mapper(); // Set up parser let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg)); let connect_nodes_parser = parse_fn(|arg| serde_json::fr...
conditional_block
try_init.rs
use { serde_json, string }; use dispatch::{ add_node, connect_nodes, get }; use error::*; use action::{ AddNode, ConnectNodes }; use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP }; use libflo_std::LIBFLO; pub unsafe fn try_init() -> Result<()>
PARSE_MAP.set(parser)?; // Set up dispatch map let add_node_dispatch = dispatch_fn(|arg| add_node(arg)); let connect_nodes_dispatch = dispatch_fn(|arg| connect_nodes(arg)); let get_dispatch = dispatch_fn(|_: &BasicAction| get()); let dispatch_map = DispatchMap::new( ...
{ if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? { let action_mapper = ACTION_MAPPER.read()?; let libflo = LIBFLO.read()?; let module_mapper = libflo.get_module_mapper(); // Set up parser let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg)); let...
identifier_body
index.js
'use strict'; const {URL} = require('url'); const {Agent: HttpAgent} = require('http'); const {Agent: HttpsAgent} = require('https'); const got = require('got'); const registryUrl = require('registry-url'); const registryAuthToken = require('registry-auth-token'); const semver = require('semver'); // These agent optio...
} const packageJson = async (packageName, options) => { options = { version: 'latest', ...options }; const scope = packageName.split('/')[0]; const registryUrl_ = options.registryUrl || registryUrl(scope); const packageUrl = new URL(encodeURIComponent(packageName).replace(/^%40/, '@'), registryUrl_); const...
{ super(`Version \`${version}\` for package \`${packageName}\` could not be found`); this.name = 'VersionNotFoundError'; }
identifier_body
index.js
'use strict'; const {URL} = require('url'); const {Agent: HttpAgent} = require('http'); const {Agent: HttpsAgent} = require('https'); const got = require('got'); const registryUrl = require('registry-url'); const registryAuthToken = require('registry-auth-token'); const semver = require('semver'); // These agent optio...
(packageName) { super(`Package \`${packageName}\` could not be found`); this.name = 'PackageNotFoundError'; } } class VersionNotFoundError extends Error { constructor(packageName, version) { super(`Version \`${version}\` for package \`${packageName}\` could not be found`); this.name = 'VersionNotFoundError';...
constructor
identifier_name
index.js
'use strict'; const {URL} = require('url'); const {Agent: HttpAgent} = require('http'); const {Agent: HttpsAgent} = require('https'); const got = require('got'); const registryUrl = require('registry-url'); const registryAuthToken = require('registry-auth-token'); const semver = require('semver'); // These agent optio...
data = data.versions[version]; if (!data) { throw versionError; } } return data; }; module.exports = packageJson; // TODO: remove this in the next major version module.exports.default = packageJson; module.exports.PackageNotFoundError = PackageNotFoundError; module.exports.VersionNotFoundError = Version...
{ const versions = Object.keys(data.versions); version = semver.maxSatisfying(versions, version); if (!version) { throw versionError; } }
conditional_block
index.js
'use strict'; const {URL} = require('url'); const {Agent: HttpAgent} = require('http'); const {Agent: HttpsAgent} = require('https'); const got = require('got'); const registryUrl = require('registry-url'); const registryAuthToken = require('registry-auth-token'); const semver = require('semver'); // These agent optio...
throw new PackageNotFoundError(packageName); } throw error; } let data = response.body; if (options.allVersions) { return data; } let {version} = options; const versionError = new VersionNotFoundError(packageName, version); if (data['dist-tags'][version]) { data = data.versions[data['dist-tags'][...
try { response = await got(packageUrl, gotOptions); } catch (error) { if (error.statusCode === 404) {
random_line_split
gnu.py
if the match is at the start of the string elif m.start() == 0: return ('gfortran', m.group(1)) else: # Output probably from --version, try harder: m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: retur...
opt.append(runtime_lib) if sys.platform == 'darwin': opt.append('cc_dynamic') return opt def get_flags_debug(self): return ['-g'] def get_flags_opt(self): v = self.get_version() if v and v <= '3.3.3': # With this compiler version...
opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d, f)): g2c = self.g2c else: g2c = self.g2c if g2...
identifier_body
gnu.py
else: _EXTRAFLAGS = [] class GnuFCompiler(FCompiler): compiler_type = 'gnu' compiler_aliases = ('g77',) description = 'GNU Fortran 77 compiler' def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" # Strip warning(s) that may be ...
_EXTRAFLAGS = []
conditional_block
gnu.py
# if the match is at the start of the string elif m.start() == 0: return ('gfortran', m.group(1)) else: # Output probably from --version, try harder: m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: ret...
return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v) # If still nothing, raise an error to make the problem easy to find. err = 'A...
random_line_split
gnu.py
(FCompiler): compiler_type = 'gnu' compiler_aliases = ('g77',) description = 'GNU Fortran 77 compiler' def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" # Strip warning(s) that may be emitted by gfortran while version_strin...
GnuFCompiler
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from os import chmod from spack import * class Tbl2asn(Package): """Tbl2asn is a command-line program that automate...
def url_for_version(self, ver): return "https://ftp.ncbi.nih.gov/toolbox/ncbi_tools/converters/by_program/tbl2asn/linux.tbl2asn.gz" def install(self, spec, prefix): mkdirp(prefix.bin) install('../linux.tbl2asn', prefix.bin.tbl2asn) chmod(prefix.bin.tbl2asn, 0o775)
random_line_split
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from os import chmod from spack import * class Tbl2asn(Package): """Tbl2asn is a command-line program that automate...
def install(self, spec, prefix): mkdirp(prefix.bin) install('../linux.tbl2asn', prefix.bin.tbl2asn) chmod(prefix.bin.tbl2asn, 0o775)
return "https://ftp.ncbi.nih.gov/toolbox/ncbi_tools/converters/by_program/tbl2asn/linux.tbl2asn.gz"
identifier_body
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from os import chmod from spack import * class Tbl2asn(Package): """Tbl2asn is a command-line program that automate...
(self, spec, prefix): mkdirp(prefix.bin) install('../linux.tbl2asn', prefix.bin.tbl2asn) chmod(prefix.bin.tbl2asn, 0o775)
install
identifier_name
cmd_inlinepush.js
/* * Command to inline push ( Push to channel remotely) */ var inlinePushPassword = Ape.config("inlinepush.conf", "password"); var inlinePushAllowedIps = Ape.config("inlinepush.conf", "ips"); Ape.registerCmd("inlinepush", false, function(params, info) { if( inlinePushAllowedIps !== "" && inlinePushAllowedIps.i...
return ["400", "BAD_PASSWORD"]; } });
chan.sendEvent(params.raw, params.data); return {"name":"pushed","data":{"value":"ok"}}; } else {
random_line_split
comment.js
<<<<<<< HEAD /* global postboxes:true, commentL10n:true */ ======= /* global postboxes, commentL10n */ >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 jQuery(document).ready( function($) { postboxes.add_postbox_toggles('comment'); <<<<<<< HEAD var stamp = $('#timestamp').html(); $('.edit-timestamp').click(functio...
event.preventDefault(); }); $timestampdiv.find('.cancel-timestamp').click( function( event ) { // Move focus back to the Edit link. $edittimestamp.show().focus(); $timestampdiv.slideUp( 'fast' ); >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 $('#mm').val($('#hidden_mm').val()); $('#jj').val($('#hidde...
{ $timestampdiv.slideDown( 'fast', function() { $( 'input, select', $timestampwrap ).first().focus(); } ); $(this).hide(); }
conditional_block
comment.js
<<<<<<< HEAD /* global postboxes:true, commentL10n:true */ ======= /* global postboxes, commentL10n */ >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 jQuery(document).ready( function($) { postboxes.add_postbox_toggles('comment'); <<<<<<< HEAD var stamp = $('#timestamp').html(); $('.edit-timestamp').click(functio...
} $timestamp.html( commentL10n.submittedOn + ' <b>' + commentL10n.dateFormat .replace( '%1$s', $( 'option[value="' + mm + '"]', '#mm' ).attr( 'data-text' ) ) .replace( '%2$s', parseInt( jj, 10 ) ) .replace( '%3$s', aa ) .replace( '%4$s', ( '00' + hh ).slice( -2 ) ) .replace( '%5$s', ( '00...
return; } else { $timestampwrap.removeClass( 'form-invalid' );
random_line_split
browser-sync.js
var gulp = require('gulp'), browserSync = require('browser-sync'), config = require('../config'), chalk = require('chalk'), PushBullet = require('pushbullet'); var connection = {}; /** * Run the build task and start a server with BrowserSync */ gulp.task('browsersync', function() { // Serve file...
for(var i=0; i<config.pushbullet.user.length; i++){ pusher.link(config.pushbullet.user[i].email, 'Web Starter Kit', connection.external+':'+connection.port, function(error, response) { if(err){ console.log(chalk.red('✘ Error pushing to devices! '+ err)); } else{ ...
if(config.pushbullet.enabled){ var pusher = new PushBullet('rBXwIUuQRJkcgOZ1OkWgPAqBKTWMFEHu');
random_line_split
browser-sync.js
var gulp = require('gulp'), browserSync = require('browser-sync'), config = require('../config'), chalk = require('chalk'), PushBullet = require('pushbullet'); var connection = {}; /** * Run the build task and start a server with BrowserSync */ gulp.task('browsersync', function() { // Serve file...
} else{ console.log(chalk.green('Pushbullet disabled!')); } }); });
pusher.link(config.pushbullet.user[i].email, 'Web Starter Kit', connection.external+':'+connection.port, function(error, response) { if(err){ console.log(chalk.red('✘ Error pushing to devices! '+ err)); } else{ console.log(chalk.green('Successful pushing to...
conditional_block
classify_all.py
import math import numpy as np from collections import defaultdict import json from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassi...
#print final_indices index = 0 for i in final_indices: final_dict[i] = predicted[index] index += 1 index = 0 for i in final_labeled_indices: final_dict[i] = provided_labels[index] index += 1 # out_json = {} # out_json.update(predicted_values=final_dict) #...
final_labeled_indices = [map_tid_to_index[i] for i in tids_labeled] final_dict = {}
random_line_split
classify_all.py
import math import numpy as np from collections import defaultdict import json from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassi...
(dataset, classifier_name, labeled_data): t = 1 # seed value labeled_data_dict = {} classifier_args = '' for label in labeled_data: labeled_data_dict[label["tid"]] = label["label_value"] file_name, point_file_name = trajectory_manager.get_file_name(dataset) # all_data_dict = trajecto...
run_classification
identifier_name
classify_all.py
import math import numpy as np from collections import defaultdict import json from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassi...
map_tid_to_index = {} index = 0 for tid_key in all_data_tids: data_line = [] map_tid_to_index[index] = tid_key if tid_key in labeled_data_dict: tids_labeled.append(index) # for feature in all_data_dict[tid_key]: # data_line.append(all_data_dict...
t = 1 # seed value labeled_data_dict = {} classifier_args = '' for label in labeled_data: labeled_data_dict[label["tid"]] = label["label_value"] file_name, point_file_name = trajectory_manager.get_file_name(dataset) # all_data_dict = trajectory_manager.load_line_data(file_name) all_d...
identifier_body
classify_all.py
import math import numpy as np from collections import defaultdict import json from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassi...
# for feature in all_data_dict[tid_key]['properties']: # data_line.append(all_data_dict[tid_key]['properties'][feature]) for feature in all_data_traj_feats[tid_key]: data_line.append(all_data_traj_feats[tid_key][feature]) data_to_train_array.append(data_line) i...
tids_not_labeled.append(index)
conditional_block
recurrent.py
# time series prediction of stock data # using recurrent neural network with LSTM layer from pybrain.datasets import SequentialDataSet from itertools import cycle from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import LSTMLayer from pybrain.supervised import RPropMinusTrainer from pybrai...
(): # load dataframe from csv file df = pi.load_data_frame('../../data/NABIL.csv') # column name to match with indicator calculating modules # TODO: resolve issue with column name df.columns = [ 'Transactions', 'Traded_Shares', 'Traded_Amount', 'High', 'Low', ...
rnn
identifier_name
recurrent.py
# time series prediction of stock data # using recurrent neural network with LSTM layer from pybrain.datasets import SequentialDataSet from itertools import cycle from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import LSTMLayer from pybrain.supervised import RPropMinusTrainer from pybrai...
# prepate sequential dataset for pyBrain rnn network ds = SequentialDataSet(1, 1) for sample, next_sample in zip(data, cycle(data[1:])): ds.addSample(sample, next_sample) # build rnn network with LSTM layer # if saved network is available if(os.path.isfile('random.xml')): ...
df = pi.load_data_frame('../../data/NABIL.csv') # column name to match with indicator calculating modules # TODO: resolve issue with column name df.columns = [ 'Transactions', 'Traded_Shares', 'Traded_Amount', 'High', 'Low', 'Close'] data = df.Close....
identifier_body
recurrent.py
# time series prediction of stock data # using recurrent neural network with LSTM layer from pybrain.datasets import SequentialDataSet from itertools import cycle from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import LSTMLayer from pybrain.supervised import RPropMinusTrainer from pybrai...
# save the network NetworkWriter.writeToFile(net,'network.xml') print() print("final error =", train_errors[-1]) predicted = [] for dat in data: predicted.append(net.activate(dat)[0]) # data = min_max_scaler.inverse_transform(data) # predicted = min_max_scaler.inv...
trainer.trainEpochs(EPOCHS_PER_CYCLE) train_errors.append(trainer.testOnData()) epoch = (i+1) * EPOCHS_PER_CYCLE print("\r epoch {}/{}".format(epoch, EPOCHS), end="") sys.stdout.flush()
conditional_block
recurrent.py
# time series prediction of stock data # using recurrent neural network with LSTM layer
from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import LSTMLayer from pybrain.supervised import RPropMinusTrainer from pybrain.tools.customxml.networkwriter import NetworkWriter from pybrain.tools.customxml.networkreader import NetworkReader import matplotlib.pyplot as plt import os.path...
from pybrain.datasets import SequentialDataSet from itertools import cycle
random_line_split
Enthusiasm.test.tsx
import * as React from 'react'; import * as enzyme from 'enzyme';
import Enthusiasm from '../src/module/redux/component/Enthusiasm'; it('renders the correct text when no enthusiasm level is given', () => { const enthusiasm = enzyme.shallow(<Enthusiasm name="Daniel" />); expect(enthusiasm.find('.greeting').text()).toEqual('Enthusiasm Daniel!'); }); it('renders the correct text w...
random_line_split
eightball.py
# Copyright the Karmabot authors and contributors. # All rights reserved. See AUTHORS. # # This file is part of 'karmabot' and is distributed under the BSD license. # See LICENSE for more details. from karmabot.core.facets import Facet from karmabot.core.commands import CommandSet, thing import random predictions = ...
"Outlook good", "Signs point to yes", "Without a doubt", "Yes", "Yes - definitely", "You may rely on it", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "O...
random_line_split
eightball.py
# Copyright the Karmabot authors and contributors. # All rights reserved. See AUTHORS. # # This file is part of 'karmabot' and is distributed under the BSD license. # See LICENSE for more details. from karmabot.core.facets import Facet from karmabot.core.commands import CommandSet, thing import random predictions = ...
(Facet): name = "eightball" commands = thing.add_child(CommandSet(name)) @classmethod def does_attach(cls, thing): return thing.name == "eightball" @commands.add("shake {thing}", help="shake the magic eightball") def shake(self, thing, context): context.reply(random.choic...
EightBallFacet
identifier_name
eightball.py
# Copyright the Karmabot authors and contributors. # All rights reserved. See AUTHORS. # # This file is part of 'karmabot' and is distributed under the BSD license. # See LICENSE for more details. from karmabot.core.facets import Facet from karmabot.core.commands import CommandSet, thing import random predictions = ...
context.reply(random.choice(predictions) + ".")
identifier_body
plain.rs
use text::style::{Style, StyleCommand, Color, PaletteColor}; use std::fmt::{self, Display}; use std::str::FromStr; use serde::de::{Deserializer, Deserialize, Error, Visitor}; use serde::{Serializer, Serialize}; use std::iter::Peekable; use std::slice; // [PlainBuf] Overhead: 48 bytes for collections, 4 bytes per descr...
} let (part, rest) = self.head.split_at(len); self.head = rest; Some((part, style)) } else { None } } } pub struct FormatReader { target: PlainBuf, marker: char, expect_code: bool, style: Style, current_len: usize } impl FormatReader { pub fn new() -> Self { Self::with_marker('§') ...
len += next_len as usize; self.descriptors.next();
random_line_split
plain.rs
use text::style::{Style, StyleCommand, Color, PaletteColor}; use std::fmt::{self, Display}; use std::str::FromStr; use serde::de::{Deserializer, Deserialize, Error, Visitor}; use serde::{Serializer, Serialize}; use std::iter::Peekable; use std::slice; // [PlainBuf] Overhead: 48 bytes for collections, 4 bytes per descr...
pub fn with_marker(marker: char) -> Self { FormatReader { target: PlainBuf::new(), marker: marker, expect_code: false, style: Style::new(), current_len: 0 } } pub fn extend(target: PlainBuf, marker: char) -> Self { FormatReader { target: target, marker: marker, expect_code: false, ...
{ Self::with_marker('§') }
identifier_body
plain.rs
use text::style::{Style, StyleCommand, Color, PaletteColor}; use std::fmt::{self, Display}; use std::str::FromStr; use serde::de::{Deserializer, Deserialize, Error, Visitor}; use serde::{Serializer, Serialize}; use std::iter::Peekable; use std::slice; // [PlainBuf] Overhead: 48 bytes for collections, 4 bytes per descr...
&mut self, string: &str) { let mut start = 0; for (index, char) in string.char_indices() { if self.expect_code { self.target.string.push_str(&string[start..start+self.current_len]); self.flush(); self.style.process(&StyleCommand::from_code(char).unwrap_or(StyleCommand::Color(PaletteColor::Whi...
ppend(
identifier_name
Gamepad.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
setMapping(mapping: Array<Mapping>, id?: string) { if (typeof id !== 'undefined') { this._mappings.set(id, mapping); } const states = new Map<Target, boolean>(); const targets: Array<Target> = []; for (const m of mapping) { if (targets.indexOf(m.ta...
{ return this._gamepadCount; }
identifier_body
Gamepad.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
this.probeGamepads(); window.addEventListener('gamepadconnected', this._onGamepadConnect); window.addEventListener('gamepaddisconnected', this._onGamepadDisconnect); } deinit(): void { this.unbind(); window.removeEventListener('gamepadconnected', this._onGamepadConnec...
{ throw new Error(`gamepad API not available`); }
conditional_block
Gamepad.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
swtch.beforeRead.removeHandler(GamepadDriver._onBeforeSwitchRead, this) ); this._shadows = null; this._auxSwitches = {}; this._joysticks = []; this._bound = false; } getGamepadCount(): number { return this._gamepadCount; } setMapping(mappin...
} this._controlledSwitches().forEach(swtch =>
random_line_split
Gamepad.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
(): void { if (!navigator.getGamepads) { throw new Error(`gamepad API not available`); } this.probeGamepads(); window.addEventListener('gamepadconnected', this._onGamepadConnect); window.addEventListener('gamepaddisconnected', this._onGamepadDisconnect); } d...
init
identifier_name
copyBookmark.ts
import webExtension from 'webextension-polyfill' import { BOOKMARK_TYPES } from '../../../constants' import { getBookmarkInfo, getBookmarkTree } from './getBookmark' export async function recursiveCopyBookmarks( id: string, destination: { parentId: string index: number }, ): Promise<void> { const book...
if (bookmarkInfo.type === BOOKMARK_TYPES.FOLDER) { const bookmarkTree = await getBookmarkTree(id) for (const [index, child] of bookmarkTree.children.entries()) { await recursiveCopyBookmarks(child.id, { parentId: createdBookmarkNode.id, index, }) } } }
? { url: bookmarkInfo.url } : null), })
random_line_split
copyBookmark.ts
import webExtension from 'webextension-polyfill' import { BOOKMARK_TYPES } from '../../../constants' import { getBookmarkInfo, getBookmarkTree } from './getBookmark' export async function recursiveCopyBookmarks( id: string, destination: { parentId: string index: number }, ): Promise<void>
} } }
{ const bookmarkInfo = await getBookmarkInfo(id) const createdBookmarkNode = await webExtension.bookmarks.create({ ...destination, title: bookmarkInfo.title, // @TODO: directly use { url: bookmarkInfo.url } ...(bookmarkInfo.type !== BOOKMARK_TYPES.FOLDER ? { url: bookmarkInfo.url } : nu...
identifier_body
copyBookmark.ts
import webExtension from 'webextension-polyfill' import { BOOKMARK_TYPES } from '../../../constants' import { getBookmarkInfo, getBookmarkTree } from './getBookmark' export async function recursiveCopyBookmarks( id: string, destination: { parentId: string index: number }, ): Promise<void> { const book...
}
{ const bookmarkTree = await getBookmarkTree(id) for (const [index, child] of bookmarkTree.children.entries()) { await recursiveCopyBookmarks(child.id, { parentId: createdBookmarkNode.id, index, }) } }
conditional_block
copyBookmark.ts
import webExtension from 'webextension-polyfill' import { BOOKMARK_TYPES } from '../../../constants' import { getBookmarkInfo, getBookmarkTree } from './getBookmark' export async function
( id: string, destination: { parentId: string index: number }, ): Promise<void> { const bookmarkInfo = await getBookmarkInfo(id) const createdBookmarkNode = await webExtension.bookmarks.create({ ...destination, title: bookmarkInfo.title, // @TODO: directly use { url: bookmarkInfo.url } ...
recursiveCopyBookmarks
identifier_name
pRunoff.py
from numpy import zeros from gwlfe.Memoization import memoize from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f from gwlfe.Output.Loading.PConc import PConc from gwlfe.Output.Loading.PConc import PConc_f @memoize def pRunoff(NYrs, DaysMonth, I...
return result @memoize def pRunoff_f(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas, FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2): p_conc = PConc_f(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstMa...
result[Y][i][l] = 0.1 * p_conc[i][l] * rur_q_runoff[Y][l][i] * Area[l]
conditional_block
pRunoff.py
from numpy import zeros from gwlfe.Memoization import memoize from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f from gwlfe.Output.Loading.PConc import PConc from gwlfe.Output.Loading.PConc import PConc_f @memoize def pRunoff(NYrs, DaysMonth, I...
(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas, FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2): p_conc = PConc_f(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMont...
pRunoff_f
identifier_name
pRunoff.py
from numpy import zeros from gwlfe.Memoization import memoize from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f from gwlfe.Output.Loading.PConc import PConc from gwlfe.Output.Loading.PConc import PConc_f @memoize def pRunoff(NYrs, DaysMonth, I...
FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2): p_conc = PConc_f(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMonth2, LastManureMonth2)[:, :NRur] rur_q_runoff = RurQRunoff_f(NYrs, DaysMonth, InitSn...
@memoize def pRunoff_f(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas,
random_line_split
pRunoff.py
from numpy import zeros from gwlfe.Memoization import memoize from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f from gwlfe.Output.Loading.PConc import PConc from gwlfe.Output.Loading.PConc import PConc_f @memoize def pRunoff(NYrs, DaysMonth, I...
@memoize def pRunoff_f(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas, FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2): p_conc = PConc_f(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastMan...
result = zeros((NYrs, 12, 10)) rur_q_runoff = RurQRunoff(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0) p_conc = PConc(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMonth2, LastManureMonth2) for Y in range(NYrs): ...
identifier_body
google-maps.js
* angular-google-maps * https://github.com/nlaplante/angular-google-maps * * @author Nicolas Laplante https://plus.google.com/108189012221374960701 */ (function () { "use strict"; /* * Utility functions */ /** * Check if 2 floating point numbers are equal * * @see http://stackoverf...
* THE SOFTWARE. *
random_line_split
google-maps.js
functions */ /** * Check if 2 floating point numbers are equal * * @see http://stackoverflow.com/a/588014 */ function floatEqual (f1, f2) { return (Math.abs(f1 - f2) < 0.000001); } /* * Create the model in a self-contained class where map-specific logic is * done. This model w...
if (_instance == null) { // Create a new map instance _instance = new google.maps.Map(that.selector, angular.extend(that.options, { center: that.center, zoom: that.zoom, draggable: that.draggable, mapTypeId : goo...
{ // TODO log error return; }
conditional_block
google-maps.js
functions */ /** * Check if 2 floating point numbers are equal * * @see http://stackoverflow.com/a/588014 */ function floatEqual (f1, f2) { return (Math.abs(f1 - f2) < 0.000001); } /* * Create the model in a self-contained class where map-specific logic is * done. This model w...
(opts) { var _instance = null, _markers = [], // caches the instances of google.maps.Marker _handlers = [], // event handlers _windows = [], // InfoWindow objects o = angular.extend({}, _defaults, opts), that = this, currentInfoWindow = null; t...
PrivateMapModel
identifier_name
google-maps.js
functions */ /** * Check if 2 floating point numbers are equal * * @see http://stackoverflow.com/a/588014 */ function floatEqual (f1, f2) { return (Math.abs(f1 - f2) < 0.000001); } /* * Create the model in a self-contained class where map-specific logic is * done. This model w...
if (that.center == null) { // TODO log error return; } if (_instance == null) { // Create a new map instance _instance = new google.maps.Map(that.selector, angular.extend(that.options, { center: that.center, ...
{ var _instance = null, _markers = [], // caches the instances of google.maps.Marker _handlers = [], // event handlers _windows = [], // InfoWindow objects o = angular.extend({}, _defaults, opts), that = this, currentInfoWindow = null; this.cen...
identifier_body
match-on-borrowed.rs
// Test that a (partially) mutably borrowed place can be matched on, so long as // we don't have to read any values that are mutably borrowed to determine // which arm to take. // // Test that we don't allow mutating the value being matched on in a way that // changes which patterns it matches, until we have chosen an ...
() {}
main
identifier_name
match-on-borrowed.rs
// Test that a (partially) mutably borrowed place can be matched on, so long as // we don't have to read any values that are mutably borrowed to determine // which arm to take. // // Test that we don't allow mutating the value being matched on in a way that // changes which patterns it matches, until we have chosen an ...
let x = &mut b.0; match *b { // OK, no access of borrowed data _ if false => (), A(_, r) => (), } x; } fn underscore_example(mut c: i32) { let r = &mut c; match c { // OK, no access of borrowed data (or any data at all) _ if false => (), _ => (), } r; } ...
fn indirect_struct_example(mut b: &mut A) {
random_line_split
match-on-borrowed.rs
// Test that a (partially) mutably borrowed place can be matched on, so long as // we don't have to read any values that are mutably borrowed to determine // which arm to take. // // Test that we don't allow mutating the value being matched on in a way that // changes which patterns it matches, until we have chosen an ...
enum Never {} fn never_init() { let n: Never; match n {} //~ ERROR } fn main() {}
{ let x = &mut t; match t { true => (), //~ ERROR false => (), } x; }
identifier_body
DepthLimitedBlurShader.js
/** * TODO */ THREE.DepthLimitedBlurShader = { defines: { "KERNEL_RADIUS": 4, "DEPTH_PACKING": 1, "PERSPECTIVE_CAMERA": 1 }, uniforms: { "tDiffuse": { value: null }, "size": { value: new THREE.Vector2( 512, 512 ) }, "sampleUvOffsets": { value: [ new THREE.Vector2( 0, 0 ) ] }, "sampleWeights": { valu...
" vec2 sampleUv = vUv + sampleUvOffset;", " float viewZ = -getViewZ( getDepth( sampleUv ) );", " if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true;", " if( ! rBreak ) {", " diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;", " weightSum += sampleWeight;", " }", " samp...
" float sampleWeight = sampleWeights[i];", " vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize;",
random_line_split
DepthLimitedBlurShader.js
/** * TODO */ THREE.DepthLimitedBlurShader = { defines: { "KERNEL_RADIUS": 4, "DEPTH_PACKING": 1, "PERSPECTIVE_CAMERA": 1 }, uniforms: { "tDiffuse": { value: null }, "size": { value: new THREE.Vector2( 512, 512 ) }, "sampleUvOffsets": { value: [ new THREE.Vector2( 0, 0 ) ] }, "sampleWeights": { valu...
return offsets; }, configure: function ( material, kernelRadius, stdDev, uvIncrement ) { material.defines[ "KERNEL_RADIUS" ] = kernelRadius; material.uniforms[ "sampleUvOffsets" ].value = THREE.BlurShaderUtils.createSampleOffsets( kernelRadius, uvIncrement ); material.uniforms[ "sampleWeights" ].value = ...
{ offsets.push( uvIncrement.clone().multiplyScalar( i ) ); }
conditional_block
transform.js
/** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ import Stream from '../Stream' import Map from '../fusion/Map' import Pipe from '../sink/Pipe' /** * Transform each value in the stream by applying f to each * @param {function(*):*}...
* @param {Stream} stream stream to tap * @returns {Stream} new stream containing the same items as this stream */ export function tap (f, stream) { return new Stream(new Tap(f, stream.source)) } function Tap (f, source) { this.source = source this.f = f } Tap.prototype.run = function (sink, scheduler) { retur...
* @param {function(x:*):*} f side effect to execute for each item. The * return value will be discarded.
random_line_split
transform.js
/** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ import Stream from '../Stream' import Map from '../fusion/Map' import Pipe from '../sink/Pipe' /** * Transform each value in the stream by applying f to each * @param {function(*):*}...
(f, stream) { return new Stream(Map.create(f, stream.source)) } /** * Replace each value in the stream with x * @param {*} x * @param {Stream} stream * @returns {Stream} stream containing items replaced with x */ export function constant (x, stream) { return map(function () { return x }, stream) } /** * Pe...
map
identifier_name
transform.js
/** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ import Stream from '../Stream' import Map from '../fusion/Map' import Pipe from '../sink/Pipe' /** * Transform each value in the stream by applying f to each * @param {function(*):*}...
Tap.prototype.run = function (sink, scheduler) { return this.source.run(new TapSink(this.f, sink), scheduler) } function TapSink (f, sink) { this.sink = sink this.f = f } TapSink.prototype.end = Pipe.prototype.end TapSink.prototype.error = Pipe.prototype.error TapSink.prototype.event = function (t, x) { va...
{ this.source = source this.f = f }
identifier_body
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ast::*; use std::collections::hashmap::HashMap; use servo_util::namespace::Namespace; use errors::l...
} } pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) { let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } ...
impl NamespaceMap { pub fn new() -> NamespaceMap { NamespaceMap { default: None, prefix_map: HashMap::new() }
random_line_split
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ast::*; use std::collections::hashmap::HashMap; use servo_util::namespace::Namespace; use errors::l...
} pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) { let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } let ...
{ NamespaceMap { default: None, prefix_map: HashMap::new() } }
identifier_body
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ast::*; use std::collections::hashmap::HashMap; use servo_util::namespace::Namespace; use errors::l...
}, (None, Some(ns)) => { if namespaces.default.is_some() { log_css_error(location, "Duplicate @namespace rule"); } namespaces.default = Some(ns); }, _ => syntax_error!() } }
{ log_css_error(location, "Duplicate @namespace rule"); }
conditional_block
namespaces.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ast::*; use std::collections::hashmap::HashMap; use servo_util::namespace::Namespace; use errors::l...
(rule: AtRule, namespaces: &mut NamespaceMap) { let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } let mut prefix: Option<String> = Non...
parse_namespace_rule
identifier_name
htmlobjectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } } impl Validatable for HTMLObjectElement {} impl VirtualMethods for HTMLObjectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, ...
GetForm
identifier_name