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 |
|---|---|---|---|---|
__init__.py | from tehbot.plugins import *
import tehbot.plugins as plugins
import wolframalpha
import prettytable
class WolframAlphaPlugin(StandardPlugin):
def __init__(self):
StandardPlugin.__init__(self)
self.parser.add_argument("query", nargs="+")
def initialize(self, dbconn):
StandardPlugin.ini... |
def execute(self, connection, event, extra, dbconn):
try:
pargs = self.parser.parse_args(extra["args"])
if self.parser.help_requested:
return self.parser.format_help().strip()
except Exception as e:
return u"Error: %s" % str(e)
txt = "\x... | table = [[y.strip() for y in x.strip().split("|")] for x in s.splitlines()]
nr_cols = max(map(len, table))
table = [[x[i] if i < len(x) else "" for i in range(nr_cols)] for x in table]
table = WolframAlphaPlugin.remove_empty_columns(table, nr_cols)
if len(table) < 2:
s2 = " ... | identifier_body |
__init__.py | from tehbot.plugins import *
import tehbot.plugins as plugins
import wolframalpha
import prettytable
class WolframAlphaPlugin(StandardPlugin):
def __init__(self):
StandardPlugin.__init__(self)
self.parser.add_argument("query", nargs="+")
def initialize(self, dbconn):
StandardPlugin.ini... |
elif p.id == "Result" and p.text:
res = self.format_table(p.text)
elif p.title and p.text:
misc.append("%s\n%s" % (p.title, self.format_table(p.text)))
txt += inp + "\n"
if res:
txt += res + "\n"
... | inp = " | ".join(p.text.splitlines()) | conditional_block |
__init__.py | from tehbot.plugins import *
import tehbot.plugins as plugins
import wolframalpha
import prettytable
class WolframAlphaPlugin(StandardPlugin):
def __init__(self):
StandardPlugin.__init__(self)
self.parser.add_argument("query", nargs="+")
def initialize(self, dbconn):
StandardPlugin.ini... | if p.id == "Input":
inp = " | ".join(p.text.splitlines())
elif p.id == "Result" and p.text:
res = self.format_table(p.text)
elif p.title and p.text:
misc.append("%s\n%s" % (p.title, self.format_table(p.text)))
... | for p in self.client.query(" ".join(pargs.query)).pods: | random_line_split |
setup_config_screen.py | # -*- coding: utf-8 -*-
import wx
from wx.lib.newevent import NewCommandEvent
from ...common.i18n import N_
from ...common.path import default_root_folder
from ..base_view import BaseView
from ..form import BaseForm
from ..validator import BaseValidator
from ..validator import ConfirmPasswordValidator, MinLengthValid... | main() | conditional_block | |
setup_config_screen.py | # -*- coding: utf-8 -*-
import wx
from wx.lib.newevent import NewCommandEvent
from ...common.i18n import N_
from ...common.path import default_root_folder
from ..base_view import BaseView
from ..form import BaseForm
from ..validator import BaseValidator
from ..validator import ConfirmPasswordValidator, MinLengthValid... | ], flag=wx.EXPAND, sizer=bajoo_folder_sizer)
bajoo_folder_sizer.GetItem(folder_picker,
recursive=True).Proportion = 1
btn_sizer = wx.StdDialogButtonSizer()
btn_sizer.AddButton(validate_btn)
btn_sizer.Realize()
sizer = self.make_sizer(w... | wx.VERTICAL)
self.make_sizer(wx.VERTICAL, [
root_folder_error, [bajoo_folder_label, folder_picker] | random_line_split |
setup_config_screen.py | # -*- coding: utf-8 -*-
import wx
from wx.lib.newevent import NewCommandEvent
from ...common.i18n import N_
from ...common.path import default_root_folder
from ..base_view import BaseView
from ..form import BaseForm
from ..validator import BaseValidator
from ..validator import ConfirmPasswordValidator, MinLengthValid... |
def _reset_validators(self, key_setting, folder_setting):
# Reset validators
self.validators = []
if key_setting:
self.validators.append(self.FindWindow('gpg_error'))
self.validators.append(self.FindWindow('passphrase_validator'))
self.validators.append... | root_folder_error_txt = self.FindWindow('root_folder_error')
if root_folder_error:
root_folder_error_txt.set_msg(root_folder_error)
self.FindWindow('bajoo_folder_section').Show(folder_setting)
self.apply_field_constraints()
gpg_error_txt = self.FindWindow('gpg_error')
... | identifier_body |
setup_config_screen.py | # -*- coding: utf-8 -*-
import wx
from wx.lib.newevent import NewCommandEvent
from ...common.i18n import N_
from ...common.path import default_root_folder
from ..base_view import BaseView
from ..form import BaseForm
from ..validator import BaseValidator
from ..validator import ConfirmPasswordValidator, MinLengthValid... | (self, _event=None):
use_passphrase = not self.FindWindow('no_passphrase').IsChecked()
self.FindWindow('passphrase').Enable(use_passphrase)
self.FindWindow('confirmation').Enable(use_passphrase)
self.FindWindow('passphrase_validator').reset()
self.FindWindow('confirmation_validat... | apply_field_constraints | identifier_name |
126 Word Ladder II.py | '''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
word... | return done or bfs(next_level, end_level, is_forward, word_set, path_dic)
def add_path(word, new_word, is_forward, path_dic):
if is_forward:
path_dic[word] = path_dic.get(word, []) + [new_word]
else:
path_dic[new_word] = path_dic.get(ne... | if len(front_level) == 0:
return False
if len(front_level) > len(end_level):
return bfs(end_level, front_level, not is_forward, word_set, path_dic)
for word in (front_level | end_level):
word_set.discard(word)
next_level = set()
... | identifier_body |
126 Word Ladder II.py | '''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
word... | class Solution(object):
def findLadders(self, beginWord, endWord, wordlist):
"""
:type beginWord: str
:type endWord: str
:type wordlist: Set[str]
:rtype: List[List[int]]
"""
def bfs(front_level, end_level, is_forward, word_set, path_dic):
... | '''
| random_line_split |
126 Word Ladder II.py | '''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
word... | (front_level, end_level, is_forward, word_set, path_dic):
if len(front_level) == 0:
return False
if len(front_level) > len(end_level):
return bfs(end_level, front_level, not is_forward, word_set, path_dic)
for word in (front_level | end_level):
... | bfs | identifier_name |
126 Word Ladder II.py | '''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
word... | assert Solution().findLadders("hit", "cog", {"hot", "dot", "dog", "lot", "log"}) == [
["hit", "hot", "dot", "dog", "cog"],
["hit", "hot", "lot", "log", "cog"]
] | conditional_block | |
test_DVS.js | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this f... | /* Compute client secret for key escrow less scheme z.CS */
res = ctx.MPIN.GET_G1_MULTIPLE(null, 0, Z1, TOKEN, TOKEN);
expect(res).to.be.equal(0);
/* Client extracts PIN from secret to create Token */
var pin = 1234;
res = ctx.MPIN.EXTRACT_PIN(sha... | /* Client and Server are issued secrets by DTA */
ctx.MPIN.GET_SERVER_SECRET(S, SST);
ctx.MPIN.GET_CLIENT_SECRET(S, HCID, TOKEN);
| random_line_split |
mod.rs |
extern crate rand;
extern crate std;
use self::rand::Rng;
use std::fmt;
#[derive(Clone,Debug)]
pub struct Vector2D
{
pub x: f64,
pub y: f64
}
impl Vector2D
{
pub fn len(&self) -> f64
{
f64::sqrt(self.x*self.x + self.y*self.y)
}
pub fn normal(&self) -> Vector2D
{
Vector... | <R: Rng>(rng: &mut R) -> Vector2D
{
Vector2D{ x: rng.gen::<f64>(), y: rng.gen::<f64>() }
}
}
impl std::fmt::Display for Vector2D
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
| rand | identifier_name |
mod.rs | extern crate rand;
extern crate std;
use self::rand::Rng;
use std::fmt;
#[derive(Clone,Debug)]
pub struct Vector2D
{
pub x: f64,
pub y: f64
}
impl Vector2D
{
pub fn len(&self) -> f64
{
f64::sqrt(self.x*self.x + self.y*self.y)
}
pub fn normal(&self) -> Vector2D
{ | }
pub fn normalized(&self) -> Vector2D
{
let mut v = self.clone();
v.normalize();
v
}
pub fn normalize(&mut self)
{
let l = self.len();
self.x /= l;
self.y /= l;
}
pub fn scale(&mut self, s: f64)
{
self.x *= s;
self.... | Vector2D { x:-self.y, y:self.x } | random_line_split |
AutoSuggestField.js | import React, { PureComponent } from 'react'
import { AutoSuggestField, Button } from 'react-ui-core/src'
import { action } from '@storybook/addon-actions'
const ClearButton = props => (<Button {...props}>X</Button>)
const SubmitButton = props => (<Button {...props}>Submit</Button>)
class Example extends PureComponen... | else {
const suggestions = commonWords.filter(word => word.slice(0, length) === value)
this.setState({ suggestions })
}
}
render() {
return (
<AutoSuggestField
onInput={value => this.generateList(value)}
onAfterClear={action('after reset')}
onSubmit={action('On su... | {
this.setState({ suggestions: [] })
} | conditional_block |
AutoSuggestField.js | import React, { PureComponent } from 'react'
import { AutoSuggestField, Button } from 'react-ui-core/src'
import { action } from '@storybook/addon-actions'
const ClearButton = props => (<Button {...props}>X</Button>)
const SubmitButton = props => (<Button {...props}>Submit</Button>)
class Example extends PureComponen... | }
}
render() {
return (
<AutoSuggestField
onInput={value => this.generateList(value)}
onAfterClear={action('after reset')}
onSubmit={action('On submit')}
suggestions={this.state.suggestions}
anchorField={{ placeholder: 'type a common letter or two...' }}
... | {
const length = value.length
const commonWords = [
'the', 'of', 'and', 'a', 'to', 'in', 'is', 'you', 'that', 'it', 'he', 'was',
'for', 'on', 'are', 'as', 'with', 'his', 'they', 'I', 'at', 'be', 'this',
'have', 'from', 'or', 'one', 'had', 'by', 'word', 'but', 'not', 'what',
'all', 'were'... | identifier_body |
AutoSuggestField.js | import React, { PureComponent } from 'react'
import { AutoSuggestField, Button } from 'react-ui-core/src'
import { action } from '@storybook/addon-actions'
const ClearButton = props => (<Button {...props}>X</Button>)
const SubmitButton = props => (<Button {...props}>Submit</Button>)
class Example extends PureComponen... | render() {
return (
<AutoSuggestField
onInput={value => this.generateList(value)}
onAfterClear={action('after reset')}
onSubmit={action('On submit')}
suggestions={this.state.suggestions}
anchorField={{ placeholder: 'type a common letter or two...' }}
highlight... | this.setState({ suggestions })
}
}
| random_line_split |
AutoSuggestField.js | import React, { PureComponent } from 'react'
import { AutoSuggestField, Button } from 'react-ui-core/src'
import { action } from '@storybook/addon-actions'
const ClearButton = props => (<Button {...props}>X</Button>)
const SubmitButton = props => (<Button {...props}>Submit</Button>)
class Example extends PureComponen... | (props) {
super(props)
this.state = { suggestions: [] }
this.generateList = this.generateList.bind(this)
}
generateList(value) {
const length = value.length
const commonWords = [
'the', 'of', 'and', 'a', 'to', 'in', 'is', 'you', 'that', 'it', 'he', 'was',
'for', 'on', 'are', 'as', '... | constructor | identifier_name |
graph-input-interactions.module.ts | // Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | ],
})
export class GraphInputInteractionModule { } | random_line_split | |
graph-input-interactions.module.ts | // Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | { }
| GraphInputInteractionModule | identifier_name |
kraken_taxonomy_report.py | of list for generating trees, due to e.g.
# root (root) -> cellular organisms (no rank) -> bacteria (superkingdom)
RANK_NAME_TO_INTS = dict( [ (y, x) for (x, y) in enumerate( RANK_NAMES ) ] )
RANK_NAMES_INTS = range( len( RANK_NAMES ) )
NO_RANK_INT = RANK_NAMES.index( NO_RANK_NAME )
NO_RANK_CODE = 'n'
PRIMARY_RANK_... | ( db_path, sanitize_names=False ):
child_lists = {}
name_map = {}
rank_map = {}
names = {} # Store names here to look for duplicates (id, True/False name fixed)
with open( os.path.join( db_path, "taxonomy/names.dmp" ) ) as fh:
for line in fh:
line = line.rstrip( "\n\r" )
... | load_taxonomy | identifier_name |
kraken_taxonomy_report.py | . Cannot recover at this time.' % new_name
if not names[name][1]:
orig_new_name = "%s_%s" % ( name, names[name][0] )
print( 'Transforming node "%s" named "%s" to "%s".' % ( names[name][0], name, orig_new_name ), file=sys.stderr )
... | dfs_summation( '1', clade_counts, child_lists ) | conditional_block | |
kraken_taxonomy_report.py | of list for generating trees, due to e.g.
# root (root) -> cellular organisms (no rank) -> bacteria (superkingdom)
RANK_NAME_TO_INTS = dict( [ (y, x) for (x, y) in enumerate( RANK_NAMES ) ] )
RANK_NAMES_INTS = range( len( RANK_NAMES ) )
NO_RANK_INT = RANK_NAMES.index( NO_RANK_NAME )
NO_RANK_CODE = 'n'
PRIMARY_RANK_... | if child_id not in nodes:
nodes[child_id] = BaseTree.Clade(name=_get_name( child_id ), branch_length=branch_length)
nodes[parent_id].clades.append(nodes[child_id])
recurse_children( child_id )
recurse_children( root_node_id )
tree = BaseTree.Tr... | import Bio.Phylo
from Bio.Phylo import BaseTree
def _get_name( node_id ):
if options.name_id:
return node_id
return name_map[node_id]
nodes = {}
root_node_id = child_lists["0"][0]
nodes[root_node_id] = BaseTree.Clade( name=_get_name( root_node_id), branch_length=branch_l... | identifier_body |
kraken_taxonomy_report.py | of list for generating trees, due to e.g.
# root (root) -> cellular organisms (no rank) -> bacteria (superkingdom)
RANK_NAME_TO_INTS = dict( [ (y, x) for (x, y) in enumerate( RANK_NAMES ) ] )
RANK_NAMES_INTS = range( len( RANK_NAMES ) )
NO_RANK_INT = RANK_NAMES.index( NO_RANK_NAME )
NO_RANK_CODE = 'n'
PRIMARY_RANK_... | children = child_lists.get( node )
if children:
for child in children:
dfs_report( child, file_data, hit_taxa, rank_map, name_map, child_lists, output_lines, options, name=name, tax=tax )
def write_tree( child_lists, name_map, rank_map, options, branch_length=1 ):
# Uses Biopython, onl... | if options.taxonomy:
output = "%s\t%s" % ( output, tax )
output_lines[ rank_int ].append( output ) | random_line_split |
payloads.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from xml.etree import ElementTree as et
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.datatype impo... |
if isinstance(text, basestring):
text = int(text) if text.isdigit() else str(text)
elif isinstance(text, list):
count = 0
for _ in text:
text[count] = int(_) if _.isdigit() else str(_)
count += 1
if len(text) == 1 and tag not in ("clause", "where"):
... | text = text.split(',') | conditional_block |
payloads.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from xml.etree import ElementTree as et
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.datatype impo... | (text, tag):
if tag in ("clause", "where"):
text = text.split(',')
if isinstance(text, basestring):
text = int(text) if text.isdigit() else str(text)
elif isinstance(text, list):
count = 0
for _ in text:
text[count] = int(_) if _.isdigit() else str(_)
... | cleanupVals | identifier_name |
payloads.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from xml.etree import ElementTree as et
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.datatype impo... | payloadFiles = os.listdir(paths.SQLMAP_XML_PAYLOADS_PATH)
payloadFiles.sort()
for payloadFile in payloadFiles:
payloadFilePath = os.path.join(paths.SQLMAP_XML_PAYLOADS_PATH, payloadFile)
#logger.debug("Parsing payloads from file '%s'" % payloadFile)
try:
doc = et.parse(pay... | identifier_body | |
payloads.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from xml.etree import ElementTree as et
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.datatype impo... | payloadFilePath = os.path.join(paths.SQLMAP_XML_PAYLOADS_PATH, payloadFile)
#logger.debug("Parsing payloads from file '%s'" % payloadFile)
try:
doc = et.parse(payloadFilePath)
except Exception, ex:
errMsg = "something seems to be wrong with "
errMsg ... |
for payloadFile in payloadFiles: | random_line_split |
client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Client module for connecting to and interacting with SmartyStreets API
"""
import json
import numbers
import requests
from .data import Address, AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
def validate_args(f):
"""
Ensures that... |
if isinstance(v, numbers.Number):
if k == "zipcode":
# If values are presented as integers then leading digits may be cut off,
# and these are significant for the zipcode. Add them back.
return str(v).zfill(5)
return str(v)
return ... | return int(v) | conditional_block |
client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Client module for connecting to and interacting with SmartyStreets API
"""
import json
import numbers
import requests
from .data import Address, AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
def | (f):
"""
Ensures that *args consist of a consistent type
:param f: any client method with *args parameter
:return: function f
"""
def wrapper(self, args):
arg_types = set([type(arg) for arg in args])
if len(arg_types) > 1:
raise TypeError("Mixed input types are not a... | validate_args | identifier_name |
client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Client module for connecting to and interacting with SmartyStreets API
"""
import json
import numbers
import requests | def validate_args(f):
"""
Ensures that *args consist of a consistent type
:param f: any client method with *args parameter
:return: function f
"""
def wrapper(self, args):
arg_types = set([type(arg) for arg in args])
if len(arg_types) > 1:
raise TypeError("Mixed inpu... |
from .data import Address, AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
| random_line_split |
client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Client module for connecting to and interacting with SmartyStreets API
"""
import json
import numbers
import requests
from .data import Address, AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
def validate_args(f):
"""
Ensures that... |
return wrapper
def truncate_args(f):
"""
Ensures that *args do not exceed a set limit or are truncated to meet that limit
:param f: any Client method with *args parameter
:return: function f
"""
def wrapper(self, args):
if len(args) > 100:
if self.truncate_addresses:
... | arg_types = set([type(arg) for arg in args])
if len(arg_types) > 1:
raise TypeError("Mixed input types are not allowed")
elif list(arg_types)[0] not in (dict, str):
raise TypeError("Only dict and str types accepted")
return f(self, args) | identifier_body |
generic-impl-less-params-with-defaults.rs | // Copyright 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-MIT or ... | {
Foo::<int>::new();
//~^ ERROR the impl referenced by this path needs at least 2 type parameters,
// but 1 was supplied
//~^^^ ERROR not enough type parameters provided: expected at least 2, found 1
} | identifier_body | |
generic-impl-less-params-with-defaults.rs | // Copyright 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-MIT or ... | <A, B, C = (A, B)>;
impl<A, B, C = (A, B)> Foo<A, B, C> {
fn new() -> Foo<A, B, C> {Foo}
}
fn main() {
Foo::<int>::new();
//~^ ERROR the impl referenced by this path needs at least 2 type parameters,
// but 1 was supplied
//~^^^ ERROR not enough type parameters provided: expected at least ... | Foo | identifier_name |
generic-impl-less-params-with-defaults.rs | // Copyright 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-MIT or ... | struct Foo<A, B, C = (A, B)>;
impl<A, B, C = (A, B)> Foo<A, B, C> {
fn new() -> Foo<A, B, C> {Foo}
}
fn main() {
Foo::<int>::new();
//~^ ERROR the impl referenced by this path needs at least 2 type parameters,
// but 1 was supplied
//~^^^ ERROR not enough type parameters provided: expected... | // except according to those terms.
#![feature(default_type_params)]
| random_line_split |
search-tasks.component.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 ... | () {
this.page$.next(0);
}
public ngOnDestroy() {
this.subscriptions.unsubscribe();
}
}
| resetPage | identifier_name |
search-tasks.component.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 ... |
return this.store$.pipe(select(selectCurrentView));
})
);
this.searchId$ = this.overrideView$.pipe(
mergeMap(view => {
if (view) {
return of(view.code);
}
return this.store$.pipe(select(selectSearchId));
})
);
this.collections$ = combineLates... | {
return of(view);
} | conditional_block |
search-tasks.component.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 ... |
}
| {
this.subscriptions.unsubscribe();
} | identifier_body |
search-tasks.component.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 ... | public perspectiveConfiguration: SearchPerspectiveConfiguration = defaultSearchPerspectiveConfiguration;
@Input()
public compactEmptyPages: boolean;
@Input()
public scrollContainer: string;
public constraintData$: Observable<ConstraintData>;
public documentsConfig$: Observable<SearchDocumentsConfig>;
... |
@Input() | random_line_split |
date-range.component.spec.ts | import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DateTimePickerModule } from '@ampath-kenya/ngx-openmrs-formentry';
import { NgxMyDatePickerModule } from 'ngx-mydatepicker';
import { DateRangeComponent } from './date-range.component';
describe('Date-range component Tests', () => {
let co... | }); | }); | random_line_split |
split-prepaid-card-handler.ts | import { BigInt } from '@graphprotocol/graph-ts';
import { SplitPrepaidCard as SplitPrepaidCardEvent } from '../../generated/Splits/SplitPrepaidCardHandler';
import { PrepaidCardSplit } from '../../generated/schema';
import { makeEOATransaction, makePrepaidCardPayment, makeTransaction, toChecksumAddress } from '../util... | }
makePrepaidCardPayment(
event,
prepaidCard,
null,
toChecksumAddress(event.params.issuingToken),
issuingTokenAmount,
null
);
let splitEntity = new PrepaidCardSplit(txnHash);
splitEntity.timestamp = event.block.timestamp;
splitEntity.blockNumber = event.block.number;
splitEntity.t... | let issuingTokenAmount = new BigInt(0);
let tokenAmounts = event.params.issuingTokenAmounts;
for (let i = 0; i < tokenAmounts.length; i++) {
// @ts-ignore this is legit AssemblyScript that tsc doesn't understand
issuingTokenAmount += tokenAmounts[i]; | random_line_split |
split-prepaid-card-handler.ts | import { BigInt } from '@graphprotocol/graph-ts';
import { SplitPrepaidCard as SplitPrepaidCardEvent } from '../../generated/Splits/SplitPrepaidCardHandler';
import { PrepaidCardSplit } from '../../generated/schema';
import { makeEOATransaction, makePrepaidCardPayment, makeTransaction, toChecksumAddress } from '../util... |
makePrepaidCardPayment(
event,
prepaidCard,
null,
toChecksumAddress(event.params.issuingToken),
issuingTokenAmount,
null
);
let splitEntity = new PrepaidCardSplit(txnHash);
splitEntity.timestamp = event.block.timestamp;
splitEntity.blockNumber = event.block.number;
splitEntity.tran... | {
// @ts-ignore this is legit AssemblyScript that tsc doesn't understand
issuingTokenAmount += tokenAmounts[i];
} | conditional_block |
split-prepaid-card-handler.ts | import { BigInt } from '@graphprotocol/graph-ts';
import { SplitPrepaidCard as SplitPrepaidCardEvent } from '../../generated/Splits/SplitPrepaidCardHandler';
import { PrepaidCardSplit } from '../../generated/schema';
import { makeEOATransaction, makePrepaidCardPayment, makeTransaction, toChecksumAddress } from '../util... | (event: SplitPrepaidCardEvent): void {
makeTransaction(event);
let prepaidCard = toChecksumAddress(event.params.prepaidCard);
let issuer = toChecksumAddress(event.params.issuer);
let txnHash = event.transaction.hash.toHex();
makeEOATransaction(event, issuer);
let issuingTokenAmount = new BigInt(0);
let... | handlePrepaidCardSplit | identifier_name |
split-prepaid-card-handler.ts | import { BigInt } from '@graphprotocol/graph-ts';
import { SplitPrepaidCard as SplitPrepaidCardEvent } from '../../generated/Splits/SplitPrepaidCardHandler';
import { PrepaidCardSplit } from '../../generated/schema';
import { makeEOATransaction, makePrepaidCardPayment, makeTransaction, toChecksumAddress } from '../util... | issuingTokenAmount,
null
);
let splitEntity = new PrepaidCardSplit(txnHash);
splitEntity.timestamp = event.block.timestamp;
splitEntity.blockNumber = event.block.number;
splitEntity.transaction = txnHash;
splitEntity.prepaidCard = prepaidCard;
splitEntity.issuer = issuer;
splitEntity.faceValues... | {
makeTransaction(event);
let prepaidCard = toChecksumAddress(event.params.prepaidCard);
let issuer = toChecksumAddress(event.params.issuer);
let txnHash = event.transaction.hash.toHex();
makeEOATransaction(event, issuer);
let issuingTokenAmount = new BigInt(0);
let tokenAmounts = event.params.issuingT... | identifier_body |
marionette.stateregion.js | // Marionette.StateRegion
// --------------------
// v0.1.0 | // Copyright (c) 2014 Mattias Rydengren <mattias.rydengren@coderesque.com>
// Distributed under MIT license
Marionette.StateRegion = (function (Marionette, Backbone, _) {
'use strict';
function ensure(obj, message) {
if (!obj) {
throw new Error(message);
}
return obj;
... | // | random_line_split |
marionette.stateregion.js | // Marionette.StateRegion
// --------------------
// v0.1.0
//
// Copyright (c) 2014 Mattias Rydengren <mattias.rydengren@coderesque.com>
// Distributed under MIT license
Marionette.StateRegion = (function (Marionette, Backbone, _) {
'use strict';
function ensure(obj, message) {
if (!obj) |
return obj;
}
return Marionette.Region.extend({
initialize: function() {
ensure(this.initialView, 'Missing `initialState`');
ensure(this.views, 'Missing `states`');
},
createView: function(ViewType) {
return new ViewType({ model: this.model... | {
throw new Error(message);
} | conditional_block |
marionette.stateregion.js | // Marionette.StateRegion
// --------------------
// v0.1.0
//
// Copyright (c) 2014 Mattias Rydengren <mattias.rydengren@coderesque.com>
// Distributed under MIT license
Marionette.StateRegion = (function (Marionette, Backbone, _) {
'use strict';
function | (obj, message) {
if (!obj) {
throw new Error(message);
}
return obj;
}
return Marionette.Region.extend({
initialize: function() {
ensure(this.initialView, 'Missing `initialState`');
ensure(this.views, 'Missing `states`');
},
... | ensure | identifier_name |
marionette.stateregion.js | // Marionette.StateRegion
// --------------------
// v0.1.0
//
// Copyright (c) 2014 Mattias Rydengren <mattias.rydengren@coderesque.com>
// Distributed under MIT license
Marionette.StateRegion = (function (Marionette, Backbone, _) {
'use strict';
function ensure(obj, message) |
return Marionette.Region.extend({
initialize: function() {
ensure(this.initialView, 'Missing `initialState`');
ensure(this.views, 'Missing `states`');
},
createView: function(ViewType) {
return new ViewType({ model: this.model, collection: this.collecti... | {
if (!obj) {
throw new Error(message);
}
return obj;
} | identifier_body |
base.py | # coding=utf-8
import abc
import logging
import tempfile
from bireus.client.download_service import AbstractDownloadService
from bireus.client.notification_service import NotificationService
from bireus.shared import *
from bireus.shared.diff_head import DiffHead
from bireus.shared.diff_item import DiffItem
from bireu... | if diff_head.protocol != self.get_version():
logger.error(".bireus protocol version %s doesn't match patcher task version %s", diff_head.protocol,
self.get_version())
self._notification_service.error(".bireus protocol version %s doesn't match patcher task version... | _patch_tasks = None
def __init__(self, notification_service: NotificationService, download_service: AbstractDownloadService,
repository_url: str, repo_path: Path, patch_file: Path):
self._notification_service = notification_service
self._download_service = download_service
... | identifier_body |
base.py | # coding=utf-8
import abc
import logging
import tempfile
from bireus.client.download_service import AbstractDownloadService
from bireus.client.notification_service import NotificationService
from bireus.shared import *
from bireus.shared.diff_head import DiffHead
from bireus.shared.diff_item import DiffItem
from bireu... | for patch_task_version in PatchTask.__subclasses__():
cls._patch_tasks[patch_task_version.get_version()] = patch_task_version.create
if protocol in cls._patch_tasks:
return cls._patch_tasks[protocol]
else:
raise ProtocolException("Protocol version `%s... | cls._patch_tasks = dict() | random_line_split |
base.py | # coding=utf-8
import abc
import logging
import tempfile
from bireus.client.download_service import AbstractDownloadService
from bireus.client.notification_service import NotificationService
from bireus.shared import *
from bireus.shared.diff_head import DiffHead
from bireus.shared.diff_item import DiffItem
from bireu... |
if protocol in cls._patch_tasks:
return cls._patch_tasks[protocol]
else:
raise ProtocolException("Protocol version `%s` is not supported in this client version", protocol)
@abc.abstractclassmethod
def get_version(cls) -> int:
pass
@abc.abstractclassmethod
... | cls._patch_tasks[patch_task_version.get_version()] = patch_task_version.create | conditional_block |
base.py | # coding=utf-8
import abc
import logging
import tempfile
from bireus.client.download_service import AbstractDownloadService
from bireus.client.notification_service import NotificationService
from bireus.shared import *
from bireus.shared.diff_head import DiffHead
from bireus.shared.diff_item import DiffItem
from bireu... | (cls) -> int:
pass
@abc.abstractclassmethod
def create(cls, notification_service: NotificationService, download_service: AbstractDownloadService, repository_url: str, repo_path: Path,
patch_file: Path) -> 'PatchTask':
"""
Abstract factory function for dynamic patcher init... | get_version | identifier_name |
land_stack.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::BTreeMap;
use std::io::Write;
use anyhow::{anyhow, bail, Error, Result};
use clap::{App, AppSettings, Arg, ArgMatche... | let bookmark: String = matches.value_of(ARG_NAME).expect("name is required").into();
let service_identity = get_service_id(matches).map(String::from);
let pushvars = get_pushvars(&matches)?;
let (head, base) = match ids.as_slice() {
[head_id, base_id] => (head_id.clone(), base_id.clone()),
... | let commit_ids = get_commit_ids(matches)?;
if commit_ids.len() != 2 {
bail!("expected 2 commit_ids (got {})", commit_ids.len())
}
let ids = resolve_commit_ids(&connection, &repo, &commit_ids).await?; | random_line_split |
land_stack.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::BTreeMap;
use std::io::Write;
use anyhow::{anyhow, bail, Error, Result};
use clap::{App, AppSettings, Arg, ArgMatche... |
}
pub(super) async fn run(matches: &ArgMatches<'_>, connection: Connection) -> Result<RenderStream> {
let repo = get_repo_specifier(matches).expect("repository is required");
let commit_ids = get_commit_ids(matches)?;
if commit_ids.len() != 2 {
bail!("expected 2 commit_ids (got {})", commit_ids.le... | {
Ok(serde_json::to_writer(w, self)?)
} | identifier_body |
land_stack.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::BTreeMap;
use std::io::Write;
use anyhow::{anyhow, bail, Error, Result};
use clap::{App, AppSettings, Arg, ArgMatche... | (&self, _matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> {
Ok(serde_json::to_writer(w, self)?)
}
}
pub(super) async fn run(matches: &ArgMatches<'_>, connection: Connection) -> Result<RenderStream> {
let repo = get_repo_specifier(matches).expect("repository is required");
let commit_id... | render_json | identifier_name |
AppleAuthentication.d.ts | import { Subscription } from 'expo-modules-core';
import { AppleAuthenticationCredential, AppleAuthenticationCredentialState, AppleAuthenticationRefreshOptions, AppleAuthenticationSignInOptions, AppleAuthenticationSignOutOptions } from './AppleAuthentication.types';
/**
* Determine if the current device's operating sy... | export declare function signInAsync(options?: AppleAuthenticationSignInOptions): Promise<AppleAuthenticationCredential>;
/**
* An operation that refreshes the logged-in user’s credentials.
* Calling this method will show the sign in modal before actually refreshing the user credentials.
*
* @param options An [`Appl... | * object after a successful authentication, and rejects with `ERR_CANCELED` if the user cancels the
* sign-in operation.
*/ | random_line_split |
prepare.py | '''Data preparation / preprocessing algorithms.'''
import numpy as np
def scale(x, new_range=(0., 1.), eps=1e-9):
'''Changes the scale of an array
Parameters
----------
x : ndarray
1D array to change the scale (remains unchanged)
new_range : tuple (float, float)
Desired range of ... | Previous data range, allowing a rescale to the old range
'''
assert new_range[1] >= new_range[0]
range_ = (x.min(), x.max())
if (range_[1] - range_[0]) < eps:
mean = (new_range[0] + new_range[1]) / 2.0
xp = np.full(x.shape, mean)
else:
xp = (x - range_[0])
xp... | -------
ndarray
Scaled array
tuple (float, float) | random_line_split |
prepare.py | '''Data preparation / preprocessing algorithms.'''
import numpy as np
def scale(x, new_range=(0., 1.), eps=1e-9):
'''Changes the scale of an array
Parameters
----------
x : ndarray
1D array to change the scale (remains unchanged)
new_range : tuple (float, float)
Desired range of ... |
else:
xp = (x - range_[0])
xp *= (new_range[1] - new_range[0]) / (range_[1] - range_[0])
xp += new_range[0]
return xp, range_
| mean = (new_range[0] + new_range[1]) / 2.0
xp = np.full(x.shape, mean) | conditional_block |
prepare.py | '''Data preparation / preprocessing algorithms.'''
import numpy as np
def | (x, new_range=(0., 1.), eps=1e-9):
'''Changes the scale of an array
Parameters
----------
x : ndarray
1D array to change the scale (remains unchanged)
new_range : tuple (float, float)
Desired range of the array
eps: float
Numerical precision, to detect degenerate cases (... | scale | identifier_name |
prepare.py | '''Data preparation / preprocessing algorithms.'''
import numpy as np
def scale(x, new_range=(0., 1.), eps=1e-9):
| range_ = (x.min(), x.max())
if (range_[1] - range_[0]) < eps:
mean = (new_range[0] + new_range[1]) / 2.0
xp = np.full(x.shape, mean)
else:
xp = (x - range_[0])
xp *= (new_range[1] - new_range[0]) / (range_[1] - range_[0])
xp += new_range[0]
return xp, range_
| '''Changes the scale of an array
Parameters
----------
x : ndarray
1D array to change the scale (remains unchanged)
new_range : tuple (float, float)
Desired range of the array
eps: float
Numerical precision, to detect degenerate cases (for example, when
every value o... | identifier_body |
e2e.ts | import { testPopover } from '../test.utils';
import { newE2EPage } from '@stencil/core/testing';
const DIRECTORY = 'basic';
const getActiveElementText = async (page) => {
const activeElement = await page.evaluateHandle(() => document.activeElement);
return await page.evaluate(el => el && el.textContent, activeEle... | test('popover:rtl: custom class', async () => {
await testPopover(DIRECTORY, '#custom-class-popover', true);
}); | random_line_split | |
_activate.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... | (private http: Http) {}
get(key: string): Observable<any> {
const params: URLSearchParams = new URLSearchParams();
params.set('key', key);
return this.http.get(SERVER_API_URL + '<%- apiUaaPath %>api/activate', {
search: params
}).map((res: Response) => res);
}
}
| constructor | identifier_name |
_activate.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... | import { SERVER_API_URL } from '../../app.constants';
@Injectable()
export class ActivateService {
constructor(private http: Http) {}
get(key: string): Observable<any> {
const params: URLSearchParams = new URLSearchParams();
params.set('key', key);
return this.http.get(SERVER_API_URL... | import { Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable'; | random_line_split |
test_feature_version.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
ms.minorVersion = 2449
ms.put()
updateAppAsset(update_app_asset_response, logError, app_user, request=request)
| def testSendNews(self):
self.set_datastore_hr_probability(1)
scale_x = 1
request = UpdateAppAssetRequestTO(u"kind", u"url", scale_x)
app_user = users.User('geert@example.com')
user_profile = create_user_profile(app_user, 'geert', language='en')
mobile = users.get_curre... | identifier_body |
test_feature_version.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import mc_unittest
from rogerthat.bizz.profil... | # Unless required by applicable law or agreed to in writing, software | random_line_split |
test_feature_version.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | (mc_unittest.TestCase):
def testSendNews(self):
self.set_datastore_hr_probability(1)
scale_x = 1
request = UpdateAppAssetRequestTO(u"kind", u"url", scale_x)
app_user = users.User('geert@example.com')
user_profile = create_user_profile(app_user, 'geert', language='en')
... | Test | identifier_name |
text-setting.test.tsx | import { render } from '@testing-library/react';
import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { globalBeforeEach } from '../../../../__jest__/before-each';
import { reduxStateForTest } from '../../../../__jest__/redux-state-for-test';
import { wi... | it('should render label text', async () => {
const { getByLabelText } = render(textSetting, container);
expect(getByLabelText(label)).toBeInTheDocument();
});
it('should render placeholder text', async () => {
const { getByPlaceholderText } = render(textSetting, container);
expect(getByPlaceholde... | const store = mockStore(await reduxStateForTest());
container = { wrapper: withReduxStore(store) };
});
| random_line_split |
autostart.py | # user.py is the autostart code for a ulnoiot node.
# Configure your devices, sensors and local interaction here.
# Always start with this to make everything from ulnoiot available.
# Therefore, do not delete the following line.
from ulnoiot import *
# The following is just example code, adjust to your needs accordin... |
## Add some other devices
# Add a button with a slightly higher debounce rate, which will report
# in the topic myroom/test1/button1.
button("b1", d6, pullup=False, threshold=2)
# Count rising signals on d2=Pin(4) and
# report number counted at myroom/test1/shock1.
# trigger("shock1",Pin(4))
## Start to transmit eve... |
blue.high() # make sure it's off (it's reversed) | random_line_split |
mod.rs | //! Module defining gist hosts.
//!
//! A host is an external (web) service that hosts gists, and allows users to paste snippets
//! of code to share with others. gist.github.com is a prime example; others are the various
//! "pastebins", including the pastebin.com namesake.
mod common;
mod github;
mod bpaste;
mod co... | () {
for (&id, host) in &*HOSTS {
assert_eq!(id, host.id());
}
}
#[test]
fn default_host_id() {
assert!(HOSTS.contains_key(DEFAULT_HOST_ID),
"Default host ID `{}` doesn't occur among known gist hosts", DEFAULT_HOST_ID);
}
#[test]
fn inmemory_host... | consistent_hosts | identifier_name |
mod.rs | //! Module defining gist hosts.
//!
//! A host is an external (web) service that hosts gists, and allows users to paste snippets
//! of code to share with others. gist.github.com is a prime example; others are the various
//! "pastebins", including the pastebin.com namesake.
mod common;
mod github;
mod bpaste;
mod co... |
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()> {
(&**self).fetch_gist(gist, mode)
}
fn gist_url(&self, gist: &Gist) -> io::Result<String> {
(&**self).gist_url(gist)
}
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
(&**self).gist_i... | { (&**self).name() } | identifier_body |
mod.rs | //! Module defining gist hosts.
//!
//! A host is an external (web) service that hosts gists, and allows users to paste snippets
//! of code to share with others. gist.github.com is a prime example; others are the various
//! "pastebins", including the pastebin.com namesake.
mod common;
mod github;
mod bpaste;
mod co... | mozilla::ID => Arc::new(mozilla::create()) as Arc<Host>,
paste_rs::ID => Arc::new(paste_rs::create()) as Arc<Host>,
hastebin::ID => Arc::new(hastebin::Hastebin::new()) as Arc<Host>,
mibpaste::ID => Arc::new(mibpaste::create()) as Arc<Host>,
sprunge::ID => Arc::new(sprunge::Sprung... | heypasteit::ID => Arc::new(heypasteit::create()) as Arc<Host>,
bpaste::ID => Arc::new(bpaste::create()) as Arc<Host>, | random_line_split |
ospec.js | ("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n",
cStyle("red"), ""
)
only.push(predicate)
o(subject, predicate)
}
o.spy = function(fn) {
var spy = function() {
spy.this = this
spy.args = [].slice.call(arguments)
spy.calls.push({this: this, args: s... |
} catch (e) {
if (task.err != null) finalizeAsync(e)
// The errors of internal tasks (which don't have an Err) are ospec bugs and must be rethrown.
else throw e
}
}
globalTimeout = noTimeoutRightNow
}
}
}
function unique(subject) {
if (hasOwn.call(ctx, subject)) {
consol... | {
nextTickish(next)
} | conditional_block |
ospec.js | ("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n",
cStyle("red"), ""
)
only.push(predicate)
o(subject, predicate)
}
o.spy = function(fn) {
var spy = function() {
spy.this = this
spy.args = [].slice.call(arguments)
spy.calls.push({this: this, args: s... |
function setDelay (t) {
if (typeof t !== "number") throw new Error("timeout() and o.timeout() expect a number as argument.")
delay = t
}
if (fn.length > 0) {
var body = fn.toString()
arg = (body.match(/^(.+?)(?:\s|\/\*[\s\S]*?\*\/|\/\/.*?\n)*=>/) || body.match(/\((?:\s|\/\*[\s\S]*?\*\/|... | {
timeout = setTimeout(function() {
timeout = undefined
finalizeAsync("async test timed out after " + delay + "ms")
}, Math.min(delay, 2147483647))
} | identifier_body |
ospec.js | light("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n",
cStyle("red"), ""
)
only.push(predicate)
o(subject, predicate)
}
o.spy = function(fn) {
var spy = function() {
spy.this = this
spy.args = [].slice.call(arguments)
spy.calls.push({this: this, ar... | (err) {
if (err == null) {
if (task.err != null) succeed(new Assert)
} else {
if (err instanceof Error) fail(new Assert, err.message, err)
else fail(new Assert, String(err), null)
}
if (timeout !== undefined) timeout = clearTimeout(timeout)
if (current === cursor) next()
}... | finalizeAsync | identifier_name |
ospec.js | light("/!\\ WARNING /!\\ o.only() mode") + "\n" + o.cleanStackTrace(ensureStackTrace(new Error)) + "\n",
cStyle("red"), ""
)
only.push(predicate)
o(subject, predicate)
}
o.spy = function(fn) {
var spy = function() {
spy.this = this
spy.args = [].slice.call(arguments)
spy.calls.push({this: this, ar... | return stack[i]
}
o.timeout = function(n) {
globalTimeout(n)
}
o.run = function(reporter) {
results = []
start = new Date
test(spec, [], [], new Task(function() {
setTimeout(function () {
timeoutStackName = getStackName({stack: o.cleanStackTrace(ensureStackTrace(new Error))}, /([\w \.]+?:\d+:\d+)/)... | // now we're in user code (or past the stack end) | random_line_split |
shallow-extend.js | /* ==========================================================================
Shallow Extends
Copyright (c) 2014 Alexey Maslennikov
========================================================================== */
'use strict';
/**
* @param {object} JavaScript object.
* @returns {boolean} True if object is plai... | // Expose public methods.
module.exports = { extend: extend }; | random_line_split | |
shallow-extend.js | /* ==========================================================================
Shallow Extends
Copyright (c) 2014 Alexey Maslennikov
========================================================================== */
'use strict';
/**
* @param {object} JavaScript object.
* @returns {boolean} True if object is plai... |
/**
* Copies properties of all sources to the destination object overriding its own
* existing properties. When extending from multiple sources, fields of every
* next source will override same named fields of previous sources.
*
* @param {object} destination object.
* @returns {bbject} extended destination object.
*... | {
return toString.call( object ) === '[object Object]';
} | identifier_body |
shallow-extend.js | /* ==========================================================================
Shallow Extends
Copyright (c) 2014 Alexey Maslennikov
========================================================================== */
'use strict';
/**
* @param {object} JavaScript object.
* @returns {boolean} True if object is plai... | else {
destination[key] = source[key];
}
}
}
}
return destination;
}
// Expose public methods.
module.exports = { extend: extend };
| {
extend( destination[key] = {}, value );
} | conditional_block |
shallow-extend.js | /* ==========================================================================
Shallow Extends
Copyright (c) 2014 Alexey Maslennikov
========================================================================== */
'use strict';
/**
* @param {object} JavaScript object.
* @returns {boolean} True if object is plai... | ( destination ) {
destination = destination || {};
for ( var i = 1; i < arguments.length; i++ ) {
var source = arguments[i] || {};
for ( var key in source ) {
if ( source.hasOwnProperty( key ) ) {
var value = source[key];
if ( _isPlainObject( value ) ) {
extend( destination[... | extend | identifier_name |
rotation_construction.rs | use num::{One, Zero};
use simba::scalar::{ClosedAdd, ClosedMul};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, MatrixN, Scalar};
use crate::geometry::Rotation;
impl<N, D: DimName> Rotation<N, D>
where
N: Scalar + Zero + One,
DefaultAllocator:... | () -> Self {
Self::identity()
}
}
| one | identifier_name |
rotation_construction.rs | use num::{One, Zero};
use simba::scalar::{ClosedAdd, ClosedMul};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, MatrixN, Scalar};
|
impl<N, D: DimName> Rotation<N, D>
where
N: Scalar + Zero + One,
DefaultAllocator: Allocator<N, D, D>,
{
/// Creates a new square identity rotation of the given `dimension`.
///
/// # Example
/// ```
/// # use nalgebra::Quaternion;
/// let rot1 = Quaternion::identity();
/// let rot2... | use crate::geometry::Rotation; | random_line_split |
rotation_construction.rs | use num::{One, Zero};
use simba::scalar::{ClosedAdd, ClosedMul};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, MatrixN, Scalar};
use crate::geometry::Rotation;
impl<N, D: DimName> Rotation<N, D>
where
N: Scalar + Zero + One,
DefaultAllocator:... |
}
| {
Self::identity()
} | identifier_body |
eGauge.py | # Copyright (c) 2013 eGauge Systems LLC
# 4730 Walnut St, Suite 110
# Boulder, CO 80301
# voice: 720-545-9767
# email: davidm@egauge.net
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... |
if ts == None:
raise error, ('<data> element is missing time_stamp attribute')
if delta == None:
raise error, ('<data> element is missing time_delta attribute')
for el in data:
if el.tag == 'r':
row = []
... | self.epoch = int (data.attrib['epoch'], 0) | conditional_block |
eGauge.py | # Copyright (c) 2013 eGauge Systems LLC
# 4730 Walnut St, Suite 110
# Boulder, CO 80301
# voice: 720-545-9767
# email: davidm@egauge.net
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | for el in data:
if el.tag == 'r':
row = []
for c in el:
row.append (long (c.text))
self.ts.append (ts)
self.row.append (row)
ts -= delta
elif el.tag == ... | raise error, ('<data> element is missing time_delta attribute')
| random_line_split |
eGauge.py | # Copyright (c) 2013 eGauge Systems LLC
# 4730 Walnut St, Suite 110
# Boulder, CO 80301
# voice: 720-545-9767
# email: davidm@egauge.net
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | },
"F": {
"doc" : "Frequency",
"units" : ["Hz", "Hzs"],
"scale" : 1e-3,
},
"THD": {
"doc" : "Total Harmonic Distortion",
"units" : ["%", "%s"],
"scale" : 1e-3,
},
"T": {
"doc"... | _tdesc = {
"P": {
"doc" : "Power",
"units" : ["W", "Ws"],
"scale" : 1,
},
"S": {
"doc" : "Apparent power",
"units" : ["VA", "VAs"],
"scale" : 1,
},
"V": {
"doc" : "Voltage",
"... | identifier_body |
eGauge.py | # Copyright (c) 2013 eGauge Systems LLC
# 4730 Walnut St, Suite 110
# Boulder, CO 80301
# voice: 720-545-9767
# email: davidm@egauge.net
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | (self, xml_string):
self.config_serial_number = None
self.num_registers = 0
self.regname = []
self.regtype = []
self.ts = []
self.row = []
xml = etree.fromstring (xml_string)
if xml.tag != 'group':
raise error, ('Expected <group> as the top e... | __init__ | identifier_name |
json2mod.rs | use std::fs::File;
use std::io::BufWriter;
use std::io::BufReader;
use anyhow::{Context, Result, anyhow};
// Command line
use docopt::Docopt;
// JSON
use serde::Deserialize;
// ProTracker and ThePlayer
use modfile::ptmf;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
static USAGE: &'static str = "
json2mod... | -h, --help Show this text.
<source> Input file.
<destination> Output file.
";
#[derive(Debug, Deserialize)]
struct Args {
arg_source: String,
arg_destination: String,
flag_help: bool,
flag_version: bool,
}
fn main() -> Result<()> {
let args: Args = Docopt:... | Options:
-V, --version Show version info. | random_line_split |
json2mod.rs | use std::fs::File;
use std::io::BufWriter;
use std::io::BufReader;
use anyhow::{Context, Result, anyhow};
// Command line
use docopt::Docopt;
// JSON
use serde::Deserialize;
// ProTracker and ThePlayer
use modfile::ptmf;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
static USAGE: &'static str = "
json2mod... | {
arg_source: String,
arg_destination: String,
flag_help: bool,
flag_version: bool,
}
fn main() -> Result<()> {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if args.flag_version {
println... | Args | identifier_name |
mod.rs | extern crate std;
use std::sync::{ Arc, Future, Mutex };
use std::rc::Rc;
use threaded_executer::CommandsThread;
use std::string::String;
#[allow(dead_code)]
mod libglfw3;
mod window;
pub struct GLContext {
window: Mutex<window::Window>
}
impl GLContext {
pub fn new(width: uint, height: uint, title: &str) -> GLCo... |
pub fn exec<T:Send>(&self, f: proc(): Send -> T) -> Future<T> {
let mut lock = self.window.lock();
lock.exec(f)
}
pub fn swap_buffers(&self) {
let mut lock = self.window.lock();
lock.swap_buffers()
}
} | lock.recv()
} | random_line_split |
mod.rs | extern crate std;
use std::sync::{ Arc, Future, Mutex };
use std::rc::Rc;
use threaded_executer::CommandsThread;
use std::string::String;
#[allow(dead_code)]
mod libglfw3;
mod window;
pub struct GLContext {
window: Mutex<window::Window>
}
impl GLContext {
pub fn new(width: uint, height: uint, title: &str) -> GLCo... |
pub fn exec<T:Send>(&self, f: proc(): Send -> T) -> Future<T> {
let mut lock = self.window.lock();
lock.exec(f)
}
pub fn swap_buffers(&self) {
let mut lock = self.window.lock();
lock.swap_buffers()
}
}
| {
let mut lock = self.window.lock();
lock.recv()
} | identifier_body |
mod.rs | extern crate std;
use std::sync::{ Arc, Future, Mutex };
use std::rc::Rc;
use threaded_executer::CommandsThread;
use std::string::String;
#[allow(dead_code)]
mod libglfw3;
mod window;
pub struct GLContext {
window: Mutex<window::Window>
}
impl GLContext {
pub fn new(width: uint, height: uint, title: &str) -> GLCo... | (&self) {
let mut lock = self.window.lock();
lock.swap_buffers()
}
}
| swap_buffers | identifier_name |
Empty Values.js | /**
*
* Empty Values
*
* @author: Corey Hart <http://www.codenothing.com>
* @description: Removes properties that don't have values
*
* @before:
* .example {
* color: red;
* font-size:;
* }
*
*
* @after:
* .example {
* color: red;
* }
*
*/
var CSSCompress... | callback: function( branch, compressor ) {
if ( ! branch.rules || ! branch.rules.length ) {
return;
}
for ( var i = -1, rule; ++i < branch.rules.length; ) {
rule = branch.rules[ i ];
if ( ! rule.parts.length || rule.parts.join( '' ).trim().length < 1 ) {
compressor.log(
"Removing empty value ... | random_line_split | |
Empty Values.js | /**
*
* Empty Values
*
* @author: Corey Hart <http://www.codenothing.com>
* @description: Removes properties that don't have values
*
* @before:
* .example {
* color: red;
* font-size:;
* }
*
*
* @after:
* .example {
* color: red;
* }
*
*/
var CSSCompress... |
}
});
| {
rule = branch.rules[ i ];
if ( ! rule.parts.length || rule.parts.join( '' ).trim().length < 1 ) {
compressor.log(
"Removing empty value with property key '" + rule.property + "'",
[ rule.position ]
);
CSSCompressor.removeItem( branch.rules, rule );
i--;
}
} | conditional_block |
indexes-skiplist.js | /*jshint globalstrict:false, strict:false, unused : false */
/*global assertEqual, assertFalse, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief tests for dump/reload
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
//... | c = db._collection("UnitTestsRecovery3");
idx = c.getIndexes()[1];
assertFalse(idx.unique);
assertFalse(idx.sparse);
assertEqual([ "a", "b" ], idx.fields);
assertEqual(250, c.byExampleSkiplist(idx.id, { a: 1, b: 1 }).toArray().length);
assertEqual(250, c.byExampleSkiplist(idx.i... | assertEqual(1, c.byExampleSkiplist(idx.id, { "a.value" : i }).toArray().length);
}
| random_line_split |
indexes-skiplist.js | /*jshint globalstrict:false, strict:false, unused : false */
/*global assertEqual, assertFalse, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief tests for dump/reload
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
//... |
c = db._collection("UnitTestsRecovery2");
idx = c.getIndexes()[1];
assertTrue(idx.unique);
assertFalse(idx.sparse);
assertEqual([ "a.value" ], idx.fields);
for (i = 0; i < 1000; ++i) {
assertEqual(1, c.byExampleSkiplist(idx.id, { "a.value" : i }).toArray().length);
}
... | {
assertEqual(1, c.byExampleSkiplist(idx.id, { value: i }).toArray().length);
} | conditional_block |
indexes-skiplist.js | /*jshint globalstrict:false, strict:false, unused : false */
/*global assertEqual, assertFalse, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief tests for dump/reload
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
//... | (argv) {
'use strict';
if (argv[1] === "setup") {
runSetup();
return 0;
}
else {
jsunity.run(recoverySuite);
return jsunity.done().status ? 0 : 1;
}
}
| main | identifier_name |
indexes-skiplist.js | /*jshint globalstrict:false, strict:false, unused : false */
/*global assertEqual, assertFalse, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief tests for dump/reload
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
//... | db._drop("UnitTestsRecovery3");
c = db._create("UnitTestsRecovery3");
c.ensureSkiplist("a", "b");
for (i = 0; i < 500; ++i) {
c.save({ a: (i % 2) + 1, b: 1 });
c.save({ a: (i % 2) + 1, b: 2 });
}
db._drop("test");
c = db._create("test");
c.save({ _key: "crashme" }, true);
internal.debugSegf... | {
'use strict';
internal.debugClearFailAt();
db._drop("UnitTestsRecovery1");
var c = db._create("UnitTestsRecovery1"), i;
c.ensureSkiplist("value");
for (i = 0; i < 1000; ++i) {
c.save({ value: i });
}
db._drop("UnitTestsRecovery2");
c = db._create("UnitTestsRecovery2");
c.ensureUniqueSkipl... | identifier_body |
parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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; e... | if isinstance(tree, six.text_type):
tree = StringElem(tree)
if not parse_funcs:
return tree
parse_func = parse_funcs[0]
for leaf in tree.flatten():
#FIXME: we might rather want to test for editability, but for now this
# works better
if not leaf.istranslatable:
... | """Parse placeables from the given string or sub-tree by using the
parsing functions provided.
The output of this function is **heavily** dependent on the order of the
parsing functions. This is because of the algorithm used.
An over-simplification of the algorithm: the leaves in the ``StringElem``
... | identifier_body |
parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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; e... | (tree, parse_funcs):
"""Parse placeables from the given string or sub-tree by using the
parsing functions provided.
The output of this function is **heavily** dependent on the order of the
parsing functions. This is because of the algorithm used.
An over-simplification of the algorithm: the leaves... | parse | identifier_name |
parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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; e... |
parse(leaf, parse_funcs[1:])
if isinstance(leaf, StringElem):
leaf.prune()
return tree
| leaf.sub = subleaves | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.