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 |
|---|---|---|---|---|
test_connect_helpers.py |
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import scipy.stats
import nest
from scipy.stats import truncexpon
try:
from mpi4py import MPI
haveMPI4Py = Tr... |
def bcast_data(data):
"""
Broadcasts data from the root MPI node to all other nodes.
"""
if haveMPI4Py:
data = MPI.COMM_WORLD.bcast(data, root=0)
return data
def is_array(data):
'''
Returns True if data is a list or numpy-array and False otherwise.
'''
return isinstance(... | '''
Gathers data from all mpi processes by collecting all element in a list if
data is a list and summing all elements to one numpy-array if data is one
numpy-array. Returns gathered data if rank of current mpi node is zero and
None otherwise.
'''
if haveMPI4Py:
data_array_list = MPI.CO... | identifier_body |
simple.py | from __future__ import absolute_import
from itertools import cycle
import logging
import random
import six
from six.moves import xrange
from .base import Producer
log = logging.getLogger(__name__)
class SimpleProducer(Producer):
"""A simple, round-robin producer.
See Producer class for Base Arguments
... | (self):
return '<SimpleProducer batch=%s>' % self.async
| __repr__ | identifier_name |
simple.py | from __future__ import absolute_import
from itertools import cycle
import logging
import random
import six
from six.moves import xrange
from .base import Producer
log = logging.getLogger(__name__)
class SimpleProducer(Producer):
"""A simple, round-robin producer.
See Producer class for Base Arguments
... | # Randomize the initial partition that is returned
if self.random_start:
num_partitions = len(self.client.get_partition_ids_for_topic(topic))
for _ in xrange(random.randint(0, num_partitions-1)):
next(self.partition_cycles[topic])
retu... | self.partition_cycles[topic] = cycle(self.client.get_partition_ids_for_topic(topic))
| random_line_split |
simple.py | from __future__ import absolute_import
from itertools import cycle
import logging
import random
import six
from six.moves import xrange
from .base import Producer
log = logging.getLogger(__name__)
class SimpleProducer(Producer):
"""A simple, round-robin producer.
See Producer class for Base Arguments
... |
return next(self.partition_cycles[topic])
def send_messages(self, topic, *msg):
if not isinstance(topic, six.binary_type):
topic = topic.encode('utf-8')
partition = self._next_partition(topic)
return super(SimpleProducer, self).send_messages(
topic, partit... | next(self.partition_cycles[topic]) | conditional_block |
simple.py | from __future__ import absolute_import
from itertools import cycle
import logging
import random
import six
from six.moves import xrange
from .base import Producer
log = logging.getLogger(__name__)
class SimpleProducer(Producer):
"""A simple, round-robin producer.
See Producer class for Base Arguments
... |
def _next_partition(self, topic):
if topic not in self.partition_cycles:
if not self.client.has_metadata_for_topic(topic):
self.client.load_metadata_for_topics(topic)
self.partition_cycles[topic] = cycle(self.client.get_partition_ids_for_topic(topic))
... | self.partition_cycles = {}
self.random_start = kwargs.pop('random_start', True)
super(SimpleProducer, self).__init__(*args, **kwargs) | identifier_body |
scope.py | self.liss_animate_arrow1=None
self.liss_animate_arrow2=None
self.liss_animate_arrow3=None
self.liss_anim1=None
self.liss_anim2=None
self.liss_anim3=None
self.samples=self.I.MAX_SAMPLES/4#self.sample_slider.value()
self.active_channels=1
self.channel_states=np.array([1,0,0,0])
self.channels_in_buffer... | def __init__(self, parent=None,**kwargs):
super(AppWindow, self).__init__(parent)
self.setupUi(self)
self.I=kwargs.get('I',None)
self.math = analyticsClass()
self.setWindowTitle(self.I.generic_name + ' : ' +self.I.H.version_string)
self.plot=pg.PlotWidget()
#cross hair
self.vLine = pg.InfiniteLine(ang... | identifier_body | |
scope.py | self.curveB = pg.PlotDataItem(name='CH2')
self.plot2.addItem(self.curveB)
self.curveB.setPen(color=self.trace_colors[1], width=1)
self.curveFR = pg.PlotDataItem()
self.plot2.addItem(self.curveFR); self.curveFR.setPen(color=(255,255,255), width=1)
self.CH1_ENABLE.setStyleSheet('background-color:rgba'+str(se... | (self):
n=0
while(not self.I.oscilloscope_progress()[0]):
time.sleep(0.1)
print self.timebase,'correction required',n
n+=1
if n>10:
self.timer.singleShot(100,self.start_capture)
return
if(self.channels_in_buffer>=1):self.I.__fetch_channel__(1)
if(self.channels_in_buffer>=2):self.I.__fetch_ch... | update | identifier_name |
scope.py | self.curveB = pg.PlotDataItem(name='CH2')
self.plot2.addItem(self.curveB)
self.curveB.setPen(color=self.trace_colors[1], width=1)
self.curveFR = pg.PlotDataItem()
self.plot2.addItem(self.curveFR); self.curveFR.setPen(color=(255,255,255), width=1)
self.CH1_ENABLE.setStyleSheet('background-color:rgba'+str(s... | self.curve_lis.setData(self.I.achans[self.liss_x].get_yaxis(),self.I.achans[self.liss_y].get_yaxis())
self.liss_ready=True
else:
self.curve_lis.clear()
self.liss_ready=False
self.message_label.setText('Channels for XY display not selected')
#print self.fps,'not available',self.active_channels... | self.liss_x = chans.index(lissx)
self.liss_y = chans.index(lissy)
la=self.I.achans[self.liss_x].get_yaxis()
lb=self.I.achans[self.liss_y].get_yaxis()
if(self.liss_x<self.active_channels and self.liss_y<self.active_channels and len(la)==len(lb)): | random_line_split |
scope.py | self.curveB = pg.PlotDataItem(name='CH2')
self.plot2.addItem(self.curveB)
self.curveB.setPen(color=self.trace_colors[1], width=1)
self.curveFR = pg.PlotDataItem()
self.plot2.addItem(self.curveFR); self.curveFR.setPen(color=(255,255,255), width=1)
self.CH1_ENABLE.setStyleSheet('background-color:rgba'+str(s... |
elif b:
self.active_channels=2
elif a:
self.active_channels=1
else:
self.active_channels=0
self.channels_in_buffer=self.active_channels
self.channel_states[0]=a
self.channel_states[1]=b
self.channel_states[2]=c
self.channel_states[3]=c
if self.active_channels:
self.I.configure_trigger... | self.active_channels=4 | conditional_block |
sqlalchemy.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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... |
@locked_cached_property
def model(self):
"""Return SQLAchemy model."""
if isinstance(self.__model, six.string_types):
return import_string(self.__model)
return self.__model
def save_one(self, json, id=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Sto... | random_line_split | |
sqlalchemy.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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... |
@locked_cached_property
def model(self):
"""Return SQLAchemy model."""
if isinstance(self.__model, six.string_types):
return import_string(self.__model)
return self.__model
def save_one(self, json, id=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Sto... | """Implement database backend for SQLAlchemy model storage."""
# FIXME: This storage engine should use transactions!
def __init__(self, model, **kwards):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.__init__`."""
self.__db = kwards.get('sqlalchemy_backend',
... | identifier_body |
sqlalchemy.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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... |
self.db.session.add_all([self.model(id=id, json=json)
for id, json in zip(ids, jsons)])
self.db.session.commit()
def update_one(self, json, id=None):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.update_one`."""
#FIXME: what if we get o... | ids = map(lambda j: j['_id'], jsons) | conditional_block |
sqlalchemy.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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... | (self):
"""See :meth:`~invenio.modules.jsonalchemy.storage.Storage.create`."""
self.model.__table__.drop(bind=self.db.engine)
| drop | identifier_name |
compiled.py | from dbt.contracts.graph.parsed import (
HasTestMetadata,
ParsedNode,
ParsedAnalysisNode,
ParsedDataTestNode,
ParsedHookNode,
ParsedModelNode,
ParsedResource,
ParsedRPCNode,
ParsedSchemaTestNode,
ParsedSeedNode,
ParsedSnapshotNode,
ParsedSourceDefinition,
SeedConfig,
... |
@dataclass
class CompiledSnapshotNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Snapshot]})
@dataclass
class CompiledDataTestNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]})
config: TestConfig = field(default_factory=TestCo... | resource_type: NodeType = field(metadata={'restrict': [NodeType.Seed]})
config: SeedConfig = field(default_factory=SeedConfig)
@property
def empty(self):
""" Seeds are never empty"""
return False | identifier_body |
compiled.py | from dbt.contracts.graph.parsed import (
HasTestMetadata,
ParsedNode,
ParsedAnalysisNode,
ParsedDataTestNode,
ParsedHookNode,
ParsedModelNode,
ParsedResource,
ParsedRPCNode,
ParsedSchemaTestNode,
ParsedSeedNode,
ParsedSnapshotNode,
ParsedSourceDefinition,
SeedConfig,
... | resource_type: NodeType = field(metadata={'restrict': [NodeType.Model]})
@dataclass
class CompiledRPCNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.RPCCall]})
@dataclass
class CompiledSeedNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [Node... | @dataclass
class CompiledModelNode(CompiledNode): | random_line_split |
compiled.py | from dbt.contracts.graph.parsed import (
HasTestMetadata,
ParsedNode,
ParsedAnalysisNode,
ParsedDataTestNode,
ParsedHookNode,
ParsedModelNode,
ParsedResource,
ParsedRPCNode,
ParsedSchemaTestNode,
ParsedSeedNode,
ParsedSnapshotNode,
ParsedSourceDefinition,
SeedConfig,
... | (sql: str, ctes: List[InjectedCTE]) -> str:
"""
`ctes` is a list of InjectedCTEs like:
[
InjectedCTE(
id="cte_id_1",
sql="__dbt__CTE__ephemeral as (select * from table)",
),
InjectedCTE(
id="cte_id_2",
s... | _inject_ctes_into_sql | identifier_name |
compiled.py | from dbt.contracts.graph.parsed import (
HasTestMetadata,
ParsedNode,
ParsedAnalysisNode,
ParsedDataTestNode,
ParsedHookNode,
ParsedModelNode,
ParsedResource,
ParsedRPCNode,
ParsedSchemaTestNode,
ParsedSeedNode,
ParsedSnapshotNode,
ParsedSourceDefinition,
SeedConfig,
... |
if with_stmt is None:
# no with stmt, add one, and inject CTEs right at the beginning
first_token = parsed.token_first()
with_stmt = sqlparse.sql.Token(sqlparse.tokens.Keyword, 'with')
parsed.insert_before(first_token, with_stmt)
else:
# stmt exists, add a comma (which ... | if token.is_keyword and token.normalized == 'WITH':
with_stmt = token
break | conditional_block |
vision.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things computer vision.
'''
import cv2
from mousetrap.i18n import _
from mousetrap.image import Image
import mousetrap.plugins.interface as interface
import logg... | self._single["center"] = {
"x": (self._single["x"] + self._single["width"]) // 2,
"y": (self._single["y"] + self._single["height"]) // 2,
}
def _extract_image(self):
single = self._single
from_y = single['y']
to_y = single['y'] + single['height']
... | def _calculate_center(self): | random_line_split |
vision.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things computer vision.
'''
import cv2
from mousetrap.i18n import _
from mousetrap.image import Image
import mousetrap.plugins.interface as interface
import logg... | (self, app):
FeatureDetector.clear_all_detection_caches()
class FeatureNotFoundException(Exception):
def __init__(self, message, cause=None):
if cause is not None:
message = message + ', caused by ' + repr(cause)
self.cause = cause
super(FeatureNotFoundException, self).... | run | identifier_name |
vision.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things computer vision.
'''
import cv2
from mousetrap.i18n import _
from mousetrap.image import Image
import mousetrap.plugins.interface as interface
import logg... |
class HaarNameError(Exception):
pass
class FeatureDetector(object):
_INSTANCES = {}
@classmethod
def get_detector(cls, config, name, scale_factor=1.1, min_neighbors=3):
key = (name, scale_factor, min_neighbors)
if key in cls._INSTANCES:
LOGGER.info("Reusing %s detector... | import os
if cache_name in self._haar_cache:
return self._haar_cache[cache_name]
current_dir = os.path.dirname(os.path.realpath(__file__))
haar_file = os.path.join(current_dir, file_)
haar = cv2.CascadeClassifier(haar_file)
if not cache_name is None:
... | identifier_body |
vision.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things computer vision.
'''
import cv2
from mousetrap.i18n import _
from mousetrap.image import Image
import mousetrap.plugins.interface as interface
import logg... |
def _unpack_first(self):
self._single = dict(
zip(['x', 'y', 'width', 'height'],
self._plural[0]))
def _calculate_center(self):
self._single["center"] = {
"x": (self._single["x"] + self._single["width"]) // 2,
"y": (self._single["y"] + s... | self._last_attempt_successful = True
message = _('Feature detected: %s') % (self._name)
LOGGER.info(message) | conditional_block |
test_survey.py | from datetime import date
from django.core.validators import URLValidator
from django.utils.timezone import now
from survey.tests.models import BaseModelTest
class TestSurvey(BaseModelTest):
def test_unicode(self):
"""Unicode generation."""
self.assertIsNotNone(str(self.survey))
def test_qu... |
def test_latest_answer(self):
"""the lastest answer date is returned."""
self.assertIsInstance(self.survey.latest_answer_date(), date)
def test_publish_date(self):
"""the pblish date must be None or datetime date instance."""
self.assertIsInstance(self.survey.publish_date, dat... | """Absoulte url is not None and do not raise error."""
self.assertIsNotNone(self.survey.get_absolute_url()) | identifier_body |
test_survey.py | from datetime import date
from django.core.validators import URLValidator
from django.utils.timezone import now
from survey.tests.models import BaseModelTest
class TestSurvey(BaseModelTest):
def test_unicode(self):
"""Unicode generation."""
self.assertIsNotNone(str(self.survey))
def test_qu... | (self):
"""Absoulte url is not None and do not raise error."""
self.assertIsNotNone(self.survey.get_absolute_url())
def test_latest_answer(self):
"""the lastest answer date is returned."""
self.assertIsInstance(self.survey.latest_answer_date(), date)
def test_publish_date(self)... | test_absolute_url | identifier_name |
test_survey.py | from datetime import date
from django.core.validators import URLValidator |
class TestSurvey(BaseModelTest):
def test_unicode(self):
"""Unicode generation."""
self.assertIsNotNone(str(self.survey))
def test_questions(self):
"""Recovering a list of questions from a survey."""
questions = self.survey.questions.all()
self.assertEqual(len(question... | from django.utils.timezone import now
from survey.tests.models import BaseModelTest | random_line_split |
see-n-say.ts | import fbapi = require("facebook-chat-api");
import winston = require("winston");
import { Utils } from "../utils";
import { IContext, MessageModule } from "./chat-module";
import { groups, userFriendlyName } from "./const";
export class SayModule extends MessageModule {
private pattern: RegExp = new RegExp("^/(sa... | }
}
return ids.join("|");
}
} | const ids: string[] = [];
for (const key in groups) {
if (groups.hasOwnProperty(key)) {
const element = groups[key];
ids.push(element.threadStrId); | random_line_split |
see-n-say.ts | import fbapi = require("facebook-chat-api");
import winston = require("winston");
import { Utils } from "../utils";
import { IContext, MessageModule } from "./chat-module";
import { groups, userFriendlyName } from "./const";
export class SayModule extends MessageModule {
private pattern: RegExp = new RegExp("^/(sa... | (): string {
return `/say [thread-id (optional)] [message] - makes ${userFriendlyName} say something
/title [thread-id (optional)] [title] - set the title`;
}
public processMessage(ctx: IContext<fbapi.MessageEvent>): void {
if (ctx.message.body) {
if (this.pattern.test(ctx.message.b... | getHelpLine | identifier_name |
see-n-say.ts | import fbapi = require("facebook-chat-api");
import winston = require("winston");
import { Utils } from "../utils";
import { IContext, MessageModule } from "./chat-module";
import { groups, userFriendlyName } from "./const";
export class SayModule extends MessageModule {
private pattern: RegExp = new RegExp("^/(sa... | winston.info("Title set", obj);
}
});
break;
}
}
}
}
private getStrIds(): string {
const ids: string[] = [];
for (const key in groups) {
i... | {
if (this.pattern.test(ctx.message.body)) {
const matches = this.pattern.exec(ctx.message.body);
const operation = matches[1];
let thread = matches[2];
const msg = matches[3];
thread = Utils.getThreadIdFromInput(thread, ctx.me... | conditional_block |
net.rs | };
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use std::sync::{Arc, Mutex};
use uany::UncheckedBoxAnyDowncast;
use openssl::ssl::{SslStream, SslContext, Sslv23};
use ope... | <T: 'static>(self) -> bool {
self.get_type_id() == TypeId::of::<T>()
}
#[inline]
fn downcast_ref<T: 'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_co... | is | identifier_name |
net.rs | use std::io::net::ip::{SocketAddr, ToSocketAddr};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use std::sync::{Arc, Mutex};
use uany::UncheckedBoxAnyDowncast;
use openssl::ssl::{SslStream, SslContext, Sslv23};
use openss... |
}
impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoR... | { (**self).read(buf) } | identifier_body |
net.rs | };
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use std::sync::{Arc, Mutex};
use uany::UncheckedBoxAnyDowncast;
use openssl::ssl::{SslStream, SslContext, Sslv23};
use ope... | impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResul... | }
| random_line_split |
main.rs | extern crate rand;
use std::net::{TcpStream, Shutdown};
use std::io::prelude::*;
use rand::distributions::{IndependentSample, Range};
use std::io::BufWriter;
use std::fs::File;
fn main() | fw.write(rand_data.as_bytes())
.ok()
.expect("Failed to write to file.");
// write 10 bytes of the string to the stream
for out_buf in rand_data.into_bytes().chunks(10) {
stream.write(&out_buf)
.ok()
.expect("Failed to write to... | {
let f = File::create("socket_producer_out.txt")
.ok()
.expect("Failed to create file.");
let mut fw = BufWriter::new(f);
// fill array with random bytes
let r = Range::new(0i32, 9);
let mut rng = rand::thread_rng();
let mut rand_data = String::new();
for _ in 0..1... | identifier_body |
main.rs | extern crate rand;
use std::net::{TcpStream, Shutdown};
use std::io::prelude::*;
use rand::distributions::{IndependentSample, Range};
use std::io::BufWriter;
use std::fs::File;
fn | () {
let f = File::create("socket_producer_out.txt")
.ok()
.expect("Failed to create file.");
let mut fw = BufWriter::new(f);
// fill array with random bytes
let r = Range::new(0i32, 9);
let mut rng = rand::thread_rng();
let mut rand_data = String::new();
for _ in 0... | main | identifier_name |
main.rs | extern crate rand;
use std::net::{TcpStream, Shutdown};
use std::io::prelude::*;
use rand::distributions::{IndependentSample, Range};
use std::io::BufWriter;
use std::fs::File;
fn main() {
let f = File::create("socket_producer_out.txt")
.ok()
.expect("Failed to create file.");
let mut ... | }
}
stream.shutdown(Shutdown::Both)
.ok()
.expect("Failed to close streams.");
}
} | .ok()
.expect("Failed to read from stream.");
print!("in={} ", in_buf[0]); | random_line_split |
string-lit.rs | // rustfmt-force_format_strings: true
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa... | identifier_name | ||
string-lit.rs | // rustfmt-force_format_strings: true
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa... | forall x. mult(x, x) = e()");
} | random_line_split | |
string-lit.rs | // rustfmt-force_format_strings: true
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa... | identifier_body | ||
pre_commit_linter.py | ia_tools', 'pylint-1.5.2')
if not os.path.exists(_PYLINT_PATH):
print ''
print 'ERROR Please run start.sh first to install pylint '
print ' and its dependencies.'
sys.exit(1)
_PATHS_TO_INSERT = [
_PYLINT_PATH,
os.getcwd(),
os.path.join(
_PARENT_DIR, 'oppia_tools', 'google... | """This function is used to check if node-jscs dependencies are installed
and pass JSCS binary path
"""
jscsrc_path = os.path.join(os.getcwd(), '.jscsrc')
pylintrc_path = os.path.join(os.getcwd(), '.pylintrc')
config_jscsrc = '--config=%s' % jscsrc_path
config_pylint = '--rcfile=%s' % pylintrc_... | identifier_body | |
pre_commit_linter.py | 'core/templates/dev/head/expressions/evaluatorSpec.js',
'core/templates/dev/head/expressions/typeParserSpec.js')},
' != ': {
'message': 'Please replace != with !== in this file.',
'excluded_files': (
'core/templates/dev/head/expressions/parserSpec.js',
'core/temp... | _pre_commit_linter | identifier_name | |
pre_commit_linter.py | google_appengine_1.9.19',
'google_appengine', 'lib', 'jinja2-2.6'),
os.path.join(
_PARENT_DIR, 'oppia_tools', 'google_appengine_1.9.19',
'google_appengine'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'webtest-1.4.2'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'numpy-1.6.1'),
os.pat... | target=_lint_py_files,
args=(config_pylint, py_files_to_lint, py_result)))
print 'Starting Javascript and Python Linting'
print '----------------------------------------'
for process in linting_processes: | random_line_split | |
pre_commit_linter.py | a list of files in directory and subdirectories without excluded files.
"""
files_in_directory = []
for _dir, _, files in os.walk(dir_path):
for file_name in files:
filename = os.path.relpath(
os.path.join(_dir, file_name), os.getcwd())
if not any([fnmatch.fn... | sys.exit(1) | conditional_block | |
NoteEditorPreview.tsx | import React, {SFC, MouseEvent} from 'react'
import {MarkdownRenderer} from 'src/shared/components/views/MarkdownRenderer'
import {DapperScrollbars} from '@influxdata/clockface'
interface Props {
note: string
scrollTop: number
onScroll: (e: MouseEvent) => void
}
const cloudImageRenderer = (): any =>
"We don'... | >
<div className="note-editor--markdown-container">
<MarkdownRenderer
text={props.note}
className="markdown-format"
cloudRenderers={{
image: cloudImageRenderer,
imageReference: cloudImageRenderer,
}}
/>
... | scrollTop={props.scrollTop}
onScroll={props.onScroll} | random_line_split |
moos_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import pymoos.MOOSCommClient
import morse.core.middleware
import bge
class MOOSClass(morse.core.middleware.MorseMiddlewareClass):
""" Handle communication between Blender and MOOS."""
def __init__(self):
""" Initialize the MOOS app"... | # register for control variables from the database
# tells
self.m.Register("cVelocity")
self.m.Register("cYawRate")
logger.info("========== Registering component =================")
parent_name = component_instance.robot_parent.blender_obj.name
# Extract the inform... |
The name of the topic is composed of the robot and sensor names.
Only useful for sensors.
"""
| random_line_split |
moos_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import pymoos.MOOSCommClient
import morse.core.middleware
import bge
class MOOSClass(morse.core.middleware.MorseMiddlewareClass):
""" Handle communication between Blender and MOOS."""
def __init__(self):
""" Initialize the MOOS app"... | if (message.GetKey()=="cVelocity") and (message.IsDouble()):
component_instance.local_data['v'] =message.GetDouble() # command linear velocity [m/s]
elif (message.GetKey()=="cYawRate") and (message.IsDouble()):
component_instance.local_data['w']=message.GetDouble() # command... | conditional_block | |
moos_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import pymoos.MOOSCommClient
import morse.core.middleware
import bge
class MOOSClass(morse.core.middleware.MorseMiddlewareClass):
""" Handle communication between Blender and MOOS."""
def __init__(self):
""" Initialize the MOOS app"... | """ read a command message from the database and send to the simulator???"""
logger.debug("Read message called.")
current_time = pymoos.MOOSCommClient.MOOSTime()
# get latest mail from the MOOS comm client
messages = self.m.FetchRecentMail()
# look for command messages: ... | identifier_body | |
moos_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import pymoos.MOOSCommClient
import morse.core.middleware
import bge
class MOOSClass(morse.core.middleware.MorseMiddlewareClass):
""" Handle communication between Blender and MOOS."""
def __init__(self):
""" Initialize the MOOS app"... | (self, component_name, component_instance, mw_data):
""" Generate a new topic to publish the data
The name of the topic is composed of the robot and sensor names.
Only useful for sensors.
"""
# register for control variables from the database
# tells
self.m.Register(... | register_component | identifier_name |
AddResourceDropdown.tsx | // Libraries
import React, {PureComponent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import _ from 'lodash'
// Components
import {
IconFont,
ComponentColor,
ComponentSize,
Dropdown,
ComponentStatus,
} from '@influxdata/clockface'
// Actions
import {showOverlay, dismissOverlay} from 's... |
if (selection === this.newOption) {
onSelectNew()
}
if (selection === this.importOption) {
onSelectImport()
}
if (selection == this.templateOption) {
onSelectTemplate()
}
}
}
const mdtp = {
onShowOverlay: showOverlay,
onDismissOverlay: dismissOverlay,
}
const connecto... | {
this.handleLimit()
return
} | conditional_block |
AddResourceDropdown.tsx | // Libraries
import React, {PureComponent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import _ from 'lodash'
// Components
import {
IconFont,
ComponentColor,
ComponentSize,
Dropdown,
ComponentStatus,
} from '@influxdata/clockface'
// Actions
import {showOverlay, dismissOverlay} from 's... | private handleSelect = (selection: string): void => {
const {
onSelectNew,
onSelectImport,
onSelectTemplate,
limitStatus = LimitStatus.OK,
} = this.props
if (CLOUD && limitStatus === LimitStatus.EXCEEDED) {
this.handleLimit()
return
}
if (selection === this.ne... | random_line_split | |
beanbot-client.py | #!/usr/bin/python
import sys, re
from socket import *
serve_addr = ('localhost', 47701)
if __name__ == '__main__':
IRC_BOLD = '\x02'
IRC_ULINE = '\x1f'
IRC_NORMAL = '\x0f'
IRC_RED = '\x034'
IRC_LIME = '\x039'
IRC_BLUE = '\x0312'
repo, branch, author, rev, description = sys.argv[1:6]
match = re.sear... |
data = (
"%(IRC_RED)s%(repo)s"
"%(IRC_NORMAL)s[%(branch)s] "
"%(IRC_NORMAL)s%(IRC_BOLD)s%(author)s "
"%(IRC_NORMAL)s%(IRC_ULINE)s%(rev)s%(IRC_NORMAL)s "
"%(description)s" % locals()
)
if len(data) > 400:
data = data[:400] + "..."
sock = socket(AF_INET, SOCK_DGRAM)
sock.... | author = match.group(1) | conditional_block |
beanbot-client.py | #!/usr/bin/python
import sys, re
from socket import *
serve_addr = ('localhost', 47701)
if __name__ == '__main__':
IRC_BOLD = '\x02'
IRC_ULINE = '\x1f'
IRC_NORMAL = '\x0f'
IRC_RED = '\x034'
IRC_LIME = '\x039'
IRC_BLUE = '\x0312'
repo, branch, author, rev, description = sys.argv[1:6]
match = re.sear... | "%(IRC_RED)s%(repo)s"
"%(IRC_NORMAL)s[%(branch)s] "
"%(IRC_NORMAL)s%(IRC_BOLD)s%(author)s "
"%(IRC_NORMAL)s%(IRC_ULINE)s%(rev)s%(IRC_NORMAL)s "
"%(description)s" % locals()
)
if len(data) > 400:
data = data[:400] + "..."
sock = socket(AF_INET, SOCK_DGRAM)
sock.sendto(data, ... | if match:
author = match.group(1)
data = ( | random_line_split |
test_yaml_update.py | '''
Copyright 2015 - 2018 University College London.
This file is part of Nammu.
Nammu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nam... | ():
"""
Ensure that, upon updating yaml settings files from jar, a user's
default project settings are not overwritten.
"""
pth = "resources/test/"
local_file = os.path.join(pth, "user_settings.yaml")
jar_file = os.path.join(pth, "jar_settings.yaml")
new_config = update_yaml_config(path_... | test_update_yaml_config | identifier_name |
test_yaml_update.py | '''
Copyright 2015 - 2018 University College London.
This file is part of Nammu.
Nammu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nam... | assert orig.readlines()
| """
Check that the settings are initialised correctly at first launch.
More specifically, this test ensures that, if the user starts Nammu without
already having any configuration files, then local configuration files with
the correct content will be created, without affecting the original files.
"... | identifier_body |
test_yaml_update.py | '''
Copyright 2015 - 2018 University College London.
This file is part of Nammu.
Nammu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nam... | """
Ensure that, upon updating yaml settings files from jar, a user's
default project settings are not overwritten.
"""
pth = "resources/test/"
local_file = os.path.join(pth, "user_settings.yaml")
jar_file = os.path.join(pth, "jar_settings.yaml")
new_config = update_yaml_config(path_to_j... |
def test_update_yaml_config(): | random_line_split |
test_yaml_update.py | '''
Copyright 2015 - 2018 University College London.
This file is part of Nammu.
Nammu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nam... | target_file = os.path.join(settings_dir, filename)
original_file = os.path.join('resources', 'config', filename)
assert os.path.isfile(target_file)
assert filecmp.cmp(target_file, original_file)
# Check that the original config files have not been emptied (see #347)
with open(ori... | conditional_block | |
styling.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | self.styledCredits.show() | random_line_split | |
styling.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... |
pychan.loadFonts("fonts/samanata.xml")
def start(self):
self.styledCredits = pychan.loadXML('gui/all_widgets.xml')
self.styledCredits.distributeInitialData({
'demoList' : [x for x in dir(pychan)],
'demoText' : pychan.__doc__
})
self.widget = pychan.loadXML(self.xmlFile)
self.widget.mapEvents({
... | pychan.manager.addStyle(name,style) | conditional_block |
styling.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | (self):
self.styledCredits = pychan.loadXML('gui/all_widgets.xml')
self.styledCredits.distributeInitialData({
'demoList' : [x for x in dir(pychan)],
'demoText' : pychan.__doc__
})
self.widget = pychan.loadXML(self.xmlFile)
self.widget.mapEvents({
'testStyle' : self.testStyle,
'closeButton':self.s... | start | identifier_name |
styling.py | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | style = self.styles[self.widget.collectData('styleList')]
self.styledCredits.stylize(style)
self.styledCredits.show() | identifier_body | |
login.js | Titanium.include("config/config.js");
Titanium.include("libs/library.js");
var wLoginWin = Ti.UI.currentWindow;
var image = Titanium.UI.createImageView({
top: 65,
width:200,
height:40,
image:'logo.png', | var lblUsername = forms.label("Username", "username", "textLabel");
var lblPassword = forms.label("Password", "password", "textLabel");
var ioUsername = forms.text('Username', 'ioUser', "textBox")
var ioPassword = forms.text('Password', 'ioPass', "textBox")
var btnLogin = forms.button("Login","btnLogin","button");
var... | backgroundImage:'logo.png'
});
| random_line_split |
speed_test.py | from timer import Timer
from back.application_mgmt import Application,Data_saver,View_control
view_control = View_control()
data_saver = Data_saver()
with Timer() as t:
view_control.top_6_background_today()
print "=> elasped top 6 today: %s s" % t.secs
with Timer() as t:
view_control.new_top_6_background_... |
with Timer() as t:
view_control.all_active_today()
print "=> elasped all active today: %s s" % t.secs
with Timer() as t:
view_control.get_all_ignored()
print "=> elasped get_all_ignored: %s s" % t.secs
with Timer() as t:
data_saver.get_file("saved_active_data")
print "=> elasped get_file (active): %s s"... | random_line_split | |
lib.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/. */
extern crate quote;
#[macro_use] extern crate syn;
#[macro_use] extern crate synstructure;
decl_derive!([JSTracea... | use ::dom::bindings::trace::JSTraceable;
match *self {
#match_body
}
}
}
};
tokens
}
| {
let match_body = s.each(|binding| {
Some(quote!(#binding.trace(tracer);))
});
let ast = s.ast();
let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
for p... | identifier_body |
lib.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/. */
extern crate quote;
#[macro_use] extern crate syn;
#[macro_use] extern crate synstructure;
decl_derive!([JSTracea... | (s: synstructure::Structure) -> quote::Tokens {
let match_body = s.each(|binding| {
Some(quote!(#binding.trace(tracer);))
});
let ast = s.ast();
let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let mut where_clause = where_clause.unwr... | js_traceable_derive | identifier_name |
lib.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/. */
extern crate quote;
#[macro_use] extern crate syn;
#[macro_use] extern crate synstructure;
| Some(quote!(#binding.trace(tracer);))
});
let ast = s.ast();
let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
for param in ast.generics.type_params() {
... | decl_derive!([JSTraceable] => js_traceable_derive);
fn js_traceable_derive(s: synstructure::Structure) -> quote::Tokens {
let match_body = s.each(|binding| { | random_line_split |
analytics.service.ts | _APPLICATION_IN_SEARCH_RESULT = 'Select Application in Search Result',
CLICK_NODE = 'Click Node',
CLICK_NODE_IN_GROUPED_VIEW = 'Click Node in Grouped View',
SHOW_GROUPED_NODE_VIEW = 'Show Grouped Node View',
CLICK_LINK = 'Click Link',
CLICK_LINK_IN_GROUPED_VIEW = 'Click Link in GROUPED View',
SH... | identifier_name | ||
analytics.service.ts | } from 'app/shared/services/web-app-setting-data.service';
export enum TRACKED_EVENT_LIST {
TOGGLE_HELP_VIEWER = 'Toggle HelpViewer',
VERSION = 'Version',
SELECT_APPLICATION = 'Select Application',
SELECT_PERIOD = 'Select Period',
SEARCH_NODE = 'Search Node',
SELECT_APPLICATION_IN_SEARCH_RESUL... |
});
}
/**
* eventCategory: 각 페이지 별 라우팅 주소
* eventAction: 액션 정보 ex. 동영상 다운로드
* eventLabel: 액션에 대한 추가 정보(Optional) ex. 동영상 이름
* eventValue: 액션에 대한 추가 정보2(Optional) 단 | {
this.currentPage = pageName;
ga('set', 'page', `/${pageName}`);
ga('send', 'pageview');
} | conditional_block |
analytics.service.ts | } from 'app/shared/services/web-app-setting-data.service';
export enum TRACKED_EVENT_LIST {
TOGGLE_HELP_VIEWER = 'Toggle HelpViewer',
VERSION = 'Version',
SELECT_APPLICATION = 'Select Application',
SELECT_PERIOD = 'Select Period',
SEARCH_NODE = 'Search Node',
SELECT_APPLICATION_IN_SEARCH_RESUL... |
trackPage(pageName: string): void {
this.isAllowed().subscribe((result: boolean) => {
if (this.windowRefService.nativeWindow.ga && typeof ga === 'function') {
this.currentPage = pageName;
ga('set', 'page', `/${pageName}`);
ga('send', 'pageview');... | {
return this.webAppSettingDataService.isDataUsageAllowed().pipe(
filter((result: boolean) => {
return result;
})
);
} | identifier_body |
analytics.service.ts | } from 'app/shared/services/web-app-setting-data.service';
export enum TRACKED_EVENT_LIST {
TOGGLE_HELP_VIEWER = 'Toggle HelpViewer',
VERSION = 'Version',
SELECT_APPLICATION = 'Select Application',
SELECT_PERIOD = 'Select Period',
SEARCH_NODE = 'Search Node',
SELECT_APPLICATION_IN_SEARCH_RESUL... | CLICK_LOGO_BUTTON = 'Click Logo Button',
REMOVE_FAVORITE_APPLICATION = 'Remove Favorite Application',
SHOW_USER_GROUP_CREATION_POPUP = 'Show User Group Creation Popup',
CREATE_USER_GROUP = 'Create User Group',
REMOVE_USER_GROUP = 'Remove User Group',
SELECT_USER_GROUP = 'Select User Group',
... | CLICK_CONFIGURATION_PAGE_EXIT_BUTTON = 'Click Configuration Page Exit Button', | random_line_split |
teeny-conf.ts | import * as fs from 'fs';
import * as path from 'path';
import * as atomicWrite from 'write-file-atomic';
const has = require('lodash.has');
const get = require('lodash.get');
const set = require('lodash.set');
const unset = require('lodash.unset');
type ConfigValue = any; // Matching JSON.parse implementation
type C... | {
_configPath: string;
_defaultConfig: Config;
_conf: Config;
constructor (configPath: string, defaultConfig: Config = {}) {
if (!configPath) throw (new TypeError('teenyconf needs a valid configPath'));
this._configPath = path.resolve(configPath);
this._defaultConfig = defaultConfig;
// Che... | TeenyConf | identifier_name |
teeny-conf.ts | import * as fs from 'fs';
import * as path from 'path';
import * as atomicWrite from 'write-file-atomic';
const has = require('lodash.has');
const get = require('lodash.get');
const set = require('lodash.set');
const unset = require('lodash.unset');
type ConfigValue = any; // Matching JSON.parse implementation
type C... | ;
}
export default TeenyConf;
| {
return has(this._conf, key);
} | identifier_body |
teeny-conf.ts | import * as fs from 'fs';
import * as path from 'path';
import * as atomicWrite from 'write-file-atomic';
const has = require('lodash.has');
const get = require('lodash.get');
const set = require('lodash.set');
const unset = require('lodash.unset');
type ConfigValue = any; // Matching JSON.parse implementation
type C... | * @param {String} key
*/
has(key: string): boolean {
return has(this._conf, key);
};
}
export default TeenyConf; |
/**
* Check if a key exists | random_line_split |
python.rs | use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use crate::atom::__pyo3_get_function_atom_grid;
use crate::atom::__pyo3_get_function_atom_grid_bse;
use crate::lebedev::__pyo3_get_function_angular_grid;
use crate::radial::__pyo3_get_function_radial_grid_kk;
use crate::radial::__pyo3_get_function_radial_grid_lmg;
use c... | (_py: Python, m: &PyModule) -> PyResult<()> {
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add_function(wrap_pyfunction!(atom_grid, m)?)?;
m.add_function(wrap_pyfunction!(atom_grid_bse, m)?)?;
m.add_function(wrap_pyfunction!(angular_grid, m)?)?;
m.add_function(wrap_pyfunction!(radial_grid_kk... | numgrid | identifier_name |
python.rs | use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use crate::atom::__pyo3_get_function_atom_grid; | use crate::lebedev::__pyo3_get_function_angular_grid;
use crate::radial::__pyo3_get_function_radial_grid_kk;
use crate::radial::__pyo3_get_function_radial_grid_lmg;
use crate::radial::__pyo3_get_function_radial_grid_lmg_bse;
#[pymodule]
fn numgrid(_py: Python, m: &PyModule) -> PyResult<()> {
m.add("__version__", e... | use crate::atom::__pyo3_get_function_atom_grid_bse; | random_line_split |
python.rs | use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use crate::atom::__pyo3_get_function_atom_grid;
use crate::atom::__pyo3_get_function_atom_grid_bse;
use crate::lebedev::__pyo3_get_function_angular_grid;
use crate::radial::__pyo3_get_function_radial_grid_kk;
use crate::radial::__pyo3_get_function_radial_grid_lmg;
use c... | {
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add_function(wrap_pyfunction!(atom_grid, m)?)?;
m.add_function(wrap_pyfunction!(atom_grid_bse, m)?)?;
m.add_function(wrap_pyfunction!(angular_grid, m)?)?;
m.add_function(wrap_pyfunction!(radial_grid_kk, m)?)?;
m.add_function(wrap_pyfunction!... | identifier_body | |
error.rs | //! A stand-in for `std::error`
use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The descript... |
}
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(not(feature = "unstable"))]
pub trait Error: Debug + Display {
/// A short description of the error.
///
/// The description should not contain newlines or sentence-ending
/// punctuation, to facilitate embedding in larger u... | {
TypeId::of::<Self>()
} | identifier_body |
error.rs | //! A stand-in for `std::error`
use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The descript... | /// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(not(feature = "unstable"))]
pub trait Error: Debug + Display {
/// A short description of the error.
///
/// The description should not contain newlines or sentence-ending
/// punctuation, to facilitate embedding in larger user-... | fn type_id(&self) -> TypeId where Self: 'static {
TypeId::of::<Self>()
}
}
| random_line_split |
error.rs | //! A stand-in for `std::error`
use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The descript... | (&self) -> TypeId where Self: 'static {
TypeId::of::<()>()
}
}
| type_id | identifier_name |
lib.rs | ///! Utilities for universally unique identifiers.
///!
///! The identifiers generated by this module:
///!
///! - are URL safe
///! - contain information on the type of object that they
///! are identifying
///! - have an extremely low probability of collision
///!
///! By default, generated identifiers have a fixed... | /// use uuids::uuid_family;
///
/// uuid_family!(MyId, "my");
/// let id = MyId::new();
/// ```
#[macro_export]
macro_rules! uuid_family {
($name:ident, $prefix:literal) => {
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct $name(uuids::Uuid);
impl $name {
... |
/// Create a family of UUIDs
///
/// ``` | random_line_split |
lib.rs | ///! Utilities for universally unique identifiers.
///!
///! The identifiers generated by this module:
///!
///! - are URL safe
///! - contain information on the type of object that they
///! are identifying
///! - have an extremely low probability of collision
///!
///! By default, generated identifiers have a fixed... |
// Generate a universally unique identifier with only lowercase letters and digits
pub fn generate_lower(prefix: &str) -> Uuid {
let chars = nanoid!(20, &CHARACTERS[..36]);
[prefix, SEPARATOR, &chars].concat().into()
}
// Test whether a string is an identifier for a particular prefix
pub fn matches(prefix: &... | {
let chars = nanoid!(20, &CHARACTERS);
[prefix, SEPARATOR, &chars].concat().into()
} | identifier_body |
lib.rs | ///! Utilities for universally unique identifiers.
///!
///! The identifiers generated by this module:
///!
///! - are URL safe
///! - contain information on the type of object that they
///! are identifying
///! - have an extremely low probability of collision
///!
///! By default, generated identifiers have a fixed... | () {
let id = generate_lower("pr");
assert_eq!(id.len(), 23);
assert!(matches("pr", &id));
assert("pr", id).unwrap();
}
}
| lower | identifier_name |
tagExclusion.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... |
const lines = docMatches[0].match(/[\r\n\s]*\*\s*@.*[\r\n\s]/g);
if (lines === null) {
return [];
}
return lines.map(
(line): [string, string] => {
const body = line.substring(line.indexOf("@"));
const firstSpaceIndex = body.sear... | {
return [];
} | conditional_block |
tagExclusion.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... | extends Exclusion<ITagExclusionDescriptor> {
private readonly contentTags: IContentTags =
this.descriptor.tags === undefined ? {} : this.descriptor.tags.content;
private readonly existenceTags = new Set(
this.descriptor.tags !== undefined && this.descriptor.tags.existence !== undefined
... | TagExclusion | identifier_name |
tagExclusion.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... | export interface ITagExclusionDescriptor {
tags?: {
content: IContentTags;
existence: string[];
};
}
export interface IContentTags {
[i: string]: string;
}
export class TagExclusion extends Exclusion<ITagExclusionDescriptor> {
private readonly contentTags: IContentTags =
this.d... | random_line_split | |
tagExclusion.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... |
private parseTagsWithContents(nodeText: string | undefined): Array<[string, string]> {
if (nodeText === undefined) {
return [];
}
const docMatches = nodeText.match(/\/\*\*\s*\n?([^\*]*(\*[^\/])?)*\*\//);
if (docMatches === null || docMatches.length === 0) {
... | {
if (node.kind === ts.SyntaxKind.VariableDeclaration) {
return node.parent;
}
return node;
} | identifier_body |
settings.py | import os
import dj_database_url
import re
from django.conf import settings
from cabot.celeryconfig import *
from cabot.cabot_config import *
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(settings_dir)
TEMPLATE_DEBUG = DEBUG = os.environ.get("DEBUG", False)
ADMINS = (
('Admin', os.envir... | 'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissions',
],
'DEFAULT_FILTER_BACKENDS': [
'rest_framework.filters.DjangoFilterBackend'... | 'DEFAULT_AUTHENTICATION_CLASSES': ( | random_line_split |
settings.py | import os
import dj_database_url
import re
from django.conf import settings
from cabot.celeryconfig import *
from cabot.cabot_config import *
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(settings_dir)
TEMPLATE_DEBUG = DEBUG = os.environ.get("DEBUG", False)
ADMINS = (
('Admin', os.envir... |
USE_TZ = True
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '*').split(',')
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will caus... | DATABASES['default']['OPTIONS'] = {'autocommit': True} | conditional_block |
state.ts | , by tracking changes and determining which files need to be emitted.
*/
export class IncrementalDriver implements DependencyTracker, ResourceDependencyRecorder {
/**
* State of the current build.
*
* This transitions as the compilation progresses.
*/
private state: BuildState;
/**
* Tracks metad... | {
/** A set of source files that this file depends upon. */
fileDependencies = new Set<ts.SourceFile>();
resourcePaths = new Set<string>();
}
type BuildState = PendingBuildState | AnalyzedBuildState;
enum BuildStateKind {
Pending,
Analyzed,
}
interface BaseBuildState {
kind: BuildStateKind;
/**
*... | FileMetadata | identifier_name |
state.ts | , by tracking changes and determining which files need to be emitted.
*/
export class IncrementalDriver implements DependencyTracker, ResourceDependencyRecorder {
/**
* State of the current build.
*
* This transitions as the compilation progresses.
*/
private state: BuildState;
/**
* Tracks metad... |
/**
* Construct an `IncrementalDriver` with a starting state that incorporates the results of a
* previous build.
*
* The previous build's `BuildState` is reconciled with the new program's changes, and the results
* are merged into the new build's `PendingBuildState`.
*/
static reconcile(
... | {
this.state = state;
} | identifier_body |
state.ts | , by tracking changes and determining which files need to be emitted.
*/
export class IncrementalDriver implements DependencyTracker, ResourceDependencyRecorder {
/**
* State of the current build.
*
* This transitions as the compilation progresses.
*/
private state: BuildState;
/** | * Tracks metadata related to each `ts.SourceFile` in the program.
*/
private metadata = new Map<ts.SourceFile, FileMetadata>();
private constructor(state: PendingBuildState, private allTsFiles: Set<ts.SourceFile>) {
this.state = state;
}
/**
* Construct an `IncrementalDriver` with a starting stat... | random_line_split | |
state.ts | , by tracking changes and determining which files need to be emitted.
*/
export class IncrementalDriver implements DependencyTracker, ResourceDependencyRecorder {
/**
* State of the current build.
*
* This transitions as the compilation progresses.
*/
private state: BuildState;
/**
* Tracks metad... |
if (oldFiles.has(newFile)) {
// This file hasn't changed; no need to look at it further.
continue;
}
// The file has changed since the last successful build. The appropriate reaction depends on
// what kind of file it is.
if (!newFile.isDeclarationFile) {
// It's... | {
// This file exists in the new program, so remove it from `deletedTsPaths`.
deletedTsPaths.delete(newFile.fileName);
} | conditional_block |
lib.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
/// returns tag type for PublicMpid type
fn public_id_type_tag(&self) -> u64 { data_tags::PUBLIC_MPID_TAG }
}
/// Random trait is used to generate random instances.
/// Used in the test mod
pub trait Random {
/// Generates a random instance and returns the created random instance
fn generate_random() ... | { data_tags::MPID_TAG } | identifier_body |
lib.rs | // Copyright 2015 MaidSafe.net limited. | //
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network So... | random_line_split | |
lib.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | {
/// Unknown Error Type
Unknown
}
/// All Maidsafe tagging should offset from this
pub const MAIDSAFE_TAG: u64 = 5483_000;
/// All Maidsafe Data tags
#[allow(missing_docs)]
pub mod data_tags {
pub const MAIDSAFE_DATA_TAG: u64 = ::MAIDSAFE_TAG + 100;
pub const IMMUTABLE_DATA_TAG: u64 = M... | CryptoError | identifier_name |
runtests.py | _count()))
if "CIRCLECI" in os.environ:
# Use fewer cores in circle CI because the inotify sysctls
# are pretty low, and we sometimes hit those limits.
level = level / 2
return int(level)
return 1
parser.add_argument(
"--concurrency",
default=default_co... | (self, test, reason):
elapsed = time.time() - self.startTime
super(Result, self).addSkip(test, reason)
if args.testpilot_json:
print(
json.dumps(
{
"op": "test_done",
"status": "skipped",
... | addSkip | identifier_name |
runtests.py | _count()))
if "CIRCLECI" in os.environ:
# Use fewer cores in circle CI because the inotify sysctls
# are pretty low, and we sometimes hit those limits.
level = level / 2
return int(level)
return 1
parser.add_argument(
"--concurrency",
default=default_co... |
def _getlock(self):
self.lock.acquire | self.f = f
self.lock = threading.RLock()
self.nesting = 0 | identifier_body |
runtests.py | _count()))
if "CIRCLECI" in os.environ:
# Use fewer cores in circle CI because the inotify sysctls
# are pretty low, and we sometimes hit those limits.
level = level / 2
return int(level)
return 1
parser.add_argument(
"--concurrency",
default=default_co... |
return False
return True
class Loader(unittest.TestLoader):
""" allows us to control the subset of which tests are run """
def __init__(self):
super(Loader, self).__init__()
def loadTestsFromTestCase(self, testCaseClass):
return super(Loader, self).loadTestsFromTestCase(test... | return True | conditional_block |
runtests.py | import math
import multiprocessing
import os
import os.path
import random
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import traceback
# in the FB internal test infra, ensure that we are running from the
# dir that houses this script rather than some other hig... | from __future__ import absolute_import, division, print_function
import argparse
import json | random_line_split | |
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... | {
event: Event,
key: DOMRefCell<Option<DOMString>>,
oldValue: DOMRefCell<Option<DOMString>>,
newValue: DOMRefCell<Option<DOMString>>,
url: DOMRefCell<DOMString>,
storageArea: MutNullableJS<Storage>
}
impl StorageEvent {
pub fn new_inherited(type_id: EventTypeId,
k... | StorageEvent | identifier_name |
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... |
fn Url(self) -> DOMString {
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let url = self.url.borrow();
url.clone()
}
fn GetStorageArea(self) -> Option<Temporary<Storage>> {
self.storageArea.get()
}
} | random_line_split | |
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... | else { EventCancelable::NotCancelable };
let event = StorageEvent::new(global, type_,
bubbles, cancelable,
key, oldValue, newValue,
url, storageArea);
Ok(event)
}
}
impl<'a> StorageEve... | { EventCancelable::Cancelable } | conditional_block |
storageevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... |
pub fn new(global: GlobalRef,
type_: DOMString,
bubbles: EventBubbles,
cancelable: EventCancelable,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
... | {
StorageEvent {
event: Event::new_inherited(type_id),
key: DOMRefCell::new(key),
oldValue: DOMRefCell::new(oldValue),
newValue: DOMRefCell::new(newValue),
url: DOMRefCell::new(url),
storageArea: MutNullableJS::new(storageArea)
}
... | identifier_body |
genesis_builder.py | # -*- coding: utf-8 -*-
from ethereum.utils import sha3, encode_hex, denoms
from raiden.utils import privatekey_to_address
from raiden.tests.utils.blockchain import GENESIS_STUB
CLUSTER_NAME = 'raiden'
def generate_accounts(seeds):
|
def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000):
"""
Create a genesis-block dict with allocation for all `accounts`.
:param accounts: list of account addresses (hex)
:param initial_alloc: the amount to allocate for the `accounts`
:return: genesis dict
"""
genesis = GENES... | """Create private keys and addresses for all seeds.
"""
return {
seed: dict(
privatekey=encode_hex(sha3(seed)),
address=encode_hex(privatekey_to_address(sha3(seed)))
) for seed in seeds} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.