file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
app.py | import sys
sys.path.append('../..')
import web
from web.contrib.template import render_jinja
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from social.utils import setting_name
from social.apps.webpy_app.utils import psa, backends
from social.apps.webpy_app import app ... | 'social.backends.stripe.StripeOAuth2',
'social.backends.persona.PersonaAuth',
'social.backends.facebook.FacebookOAuth2',
'social.backends.facebook.FacebookAppOAuth2',
'social.backends.yahoo.YahooOAuth',
'social.backends.angel.AngelOAuth2',
'social.backends.behance.BehanceOAuth2',
'social... | 'social.backends.google.GoogleOAuth2',
'social.backends.google.GoogleOAuth',
'social.backends.twitter.TwitterOAuth',
'social.backends.yahoo.YahooOpenId', | random_line_split |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements dir... |
if self.args.table_names:
table_names = self.args.table_names.split(',')
else:
table_names = []
# If one or more filenames are specified, we need to add stdin ourselves (if available)
if sys.stdin not in self.input_files:
try:
if not... | self.input_files.append(self._open_input_file(path)) | conditional_block |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements dir... |
if __name__ == "__main__":
launch_new_instance()
| utility = CSVSQL()
utility.main() | identifier_body |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements dir... | if self.args.table_names:
table_names = self.args.table_names.split(',')
else:
table_names = []
# If one or more filenames are specified, we need to add stdin ourselves (if available)
if sys.stdin not in self.input_files:
try:
if not s... | for path in self.args.input_paths:
self.input_files.append(self._open_input_file(path))
| random_line_split |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements dir... | ():
utility = CSVSQL()
utility.main()
if __name__ == "__main__":
launch_new_instance()
| launch_new_instance | identifier_name |
erdfparser.js | /**
* Copyright (c) 2006
*
* Philipp Berger, Martin Czuchra, Gero Decker, Ole Eckermann, Lutz Gericke,
* Alexander Hold, Alexander Koglin, Oliver Kopp, Stefan Krumnow,
* Matthias Kunze, Philipp Maschke, Falko Menge, Christoph Neijenhuis,
* Hagen Overdick, Zhen Peng, Nicolas Peters, Kerstin Pfitzner, Daniel Pol... | });
},
_parseTypeTriplesFrom: function(subjectType, subject, properties, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( ... |
property = property.substring(
schema.prefix.length+1, property.length);
var triple = ERDF.registerTriple(
new ERDF.Resource(subject),
{prefix: schema.prefix, name: property},
(objectType == ERDF.RESOURCE) ?
new ERDF.Resource(object) :
new ERDF.Literal(object));
if(ca... | conditional_block |
erdfparser.js | /**
* Copyright (c) 2006
*
* Philipp Berger, Martin Czuchra, Gero Decker, Ole Eckermann, Lutz Gericke,
* Alexander Hold, Alexander Koglin, Oliver Kopp, Stefan Krumnow,
* Matthias Kunze, Philipp Maschke, Falko Menge, Christoph Neijenhuis,
* Hagen Overdick, Zhen Peng, Nicolas Peters, Kerstin Pfitzner, Daniel Pol... | var value = meta.getAttribute('content');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
property,
ERDF.LITERAL, value);
});
return true;
},
_parseFromTag: function(node, subject, depth) {
// avoid parsing non-xhtml content.
if(!node || !node.namespaceURI || node.namespaceURI != XMLNS.... | random_line_split | |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def | (self, plate, name,path):
self.plate=plate
self.name=name
self.path=path
class PlateManager(QtCore.QObject):
'''
PlateManager holds all plates, and handles related actions,
such as plate open,save,close,select, etc
'''
signalPlateListUpdated=QtCore.pyqtSignal(QtCore.QStringL... | __init__ | identifier_name |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def __init__(self, plate, name,path):
self.plate=plate
self.name=name
self.pat... |
def isDirty(self):
return self.plates[self.currentPlateIndex].plate.dirty
def isEmpty(self):
return self.plates == []
def names(self):
return QtCore.QStringList([QtCore.QString(record.name) for record in self.plates])
def setCurrentPlate(self, inde... | if self.currentPlateIndex < 0 :
return
self.signalCurrentPlateSet.emit(None)
self.plates[self.currentPlateIndex].plate.signalApplyReference.disconnect()
del self.plates[self.currentPlateIndex]
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
... | identifier_body |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def __init__(self, plate, name,path):
self.plate=plate
self.name=name
self.pat... | such as plate open,save,close,select, etc
'''
signalPlateListUpdated=QtCore.pyqtSignal(QtCore.QStringList)
signalCurrentPlateSet=QtCore.pyqtSignal(object)
signalCurrentIndexChanged=QtCore.pyqtSignal(int)
signalApproximationSelected = QtCore.pyqtSignal(int)
def __init__(self, parent=None... | random_line_split | |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def __init__(self, plate, name,path):
self.plate=plate
self.name=name
self.pat... | plate = plateRecord.plate
if not plate is sender:
plate.setReference(reference) | conditional_block | |
classStateFixtureReselectMocked.tsx | import { StateMock } from '@react-mock/state';
import React from 'react';
import { createValues } from '../../fixtureState';
import { uuid } from '../../util';
import { testFixtureLoader } from '../testHelpers';
import { Counter } from '../testHelpers/components';
import { anyClassState, anyProps } from '../testHelpers... | </StateMock>
),
});
const fixtureId = { path: 'first' };
// NOTE: This is a regression test that was created for a bug that initally
// slipped unnoticed in https://github.com/react-cosmos/react-cosmos/pull/893.
// Because element refs from unmounted FixtureCapture instances were
// incorrectly reused, component... | random_line_split | |
gradient_boosting_regression_example.py | #
# 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 us... | # $example on$
# Load and parse the data file.
data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])
# Train a GradientBoostedTrees model.
# Note... | # $example off$
if __name__ == "__main__":
sc = SparkContext(appName="PythonGradientBoostedTreesRegressionExample") | random_line_split |
gradient_boosting_regression_example.py | #
# 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 us... | sc = SparkContext(appName="PythonGradientBoostedTreesRegressionExample")
# $example on$
# Load and parse the data file.
data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.rando... | conditional_block | |
associated-types-eq-3.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 ... | baz(&a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar`
} | random_line_split | |
associated-types-eq-3.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 ... | () {
let a = 42;
foo1(a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar`
baz(&a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar`
}
| main | identifier_name |
util.py | # Copyright 2013-2021 Aerospike, 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 applicable law or agreed to in writ... |
def is_bool(x):
if x in ("True", "true", "False", "false"):
return True
return False
def check_list_against_types(a_list):
if a_list is None or expected_types is None:
return False
if len(a_list) == len(expected_types):
for idx in range(len(... | try:
int(x)
if "." in x:
return False
return True
except ValueError:
return False | identifier_body |
util.py | # Copyright 2013-2021 Aerospike, 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 applicable law or agreed to in writ... | (x):
try:
int(x)
if "." in x:
return False
return True
except ValueError:
return False
def is_bool(x):
if x in ("True", "true", "False", "false"):
return True
return False
def check_list_against_types(a... | is_int | identifier_name |
util.py | # Copyright 2013-2021 Aerospike, 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 applicable law or agreed to in writ... | field_values = []
for name in record:
if isinstance(record[name], dict):
new_parent_field = parent_field.copy()
new_parent_field.append(name)
names = " ".join(new_parent_field)
if "converted" in record[name]:
field_names.append(names)
... | field_names = [] | random_line_split |
util.py | # Copyright 2013-2021 Aerospike, 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 applicable law or agreed to in writ... |
return title, description, data_names, data_values, num_records
def get_separate_output(in_str=""):
_regex = re.compile(r"((?<=^{).*?(?=^}))", re.MULTILINE | re.DOTALL)
out = re.findall(_regex, in_str)
ls = []
for item in out:
item = remove_escape_sequence(item)
item = "{" + item... | temp_names, temp_values = parse_record([], record)
# We assume every record has the same set of names
if len(data_names) == 0:
data_names = temp_names
data_values.append(temp_values)
num_records += 1 | conditional_block |
test_large_ops.py | # Copyright 2013 NEC Corporation
# 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 ... | (cls):
super(TestLargeOpsScenario, cls).resource_setup()
# list of cleanup calls to be executed in reverse order
cls._cleanup_resources = []
@classmethod
def resource_cleanup(cls):
while cls._cleanup_resources:
function, args, kwargs = cls._cleanup_resources.pop(-1)
... | resource_setup | identifier_name |
test_large_ops.py | # Copyright 2013 NEC Corporation
# 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 ... | }
network = self.get_tenant_network()
create_kwargs = fixed_network.set_networks_kwarg(network,
create_kwargs)
#self.servers_client.create_server(
self.create_server(
name,
'',
flavor... | self.addCleanupClass(self.security_groups_client.delete_security_group,
secgroup['id'])
create_kwargs = {
'min_count': CONF.scenario.large_ops_number,
'security_groups': [{'name': secgroup['name']}] | random_line_split |
test_large_ops.py | # Copyright 2013 NEC Corporation
# 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 ... | """
Test large operations.
This test below:
* Spin up multiple instances in one nova call, and repeat three times
* as a regular user
* TODO: same thing for cinder
"""
@classmethod
def skip_checks(cls):
super(TestLargeOpsScenario, cls).skip_checks()
if CONF.scenario.la... | identifier_body | |
test_large_ops.py | # Copyright 2013 NEC Corporation
# 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 ... |
@classmethod
def setup_credentials(cls):
cls.set_network_resources()
super(TestLargeOpsScenario, cls).setup_credentials()
@classmethod
def resource_setup(cls):
super(TestLargeOpsScenario, cls).resource_setup()
# list of cleanup calls to be executed in reverse order
... | raise cls.skipException("large_ops_number not set to multiple "
"instances") | conditional_block |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| f | identifier_name |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
trait Quux: Foo + Bar + Baz { }
struct A { x: isize }
impl Foo for A { fn f(&self) -> isize { 10 } }
impl Bar for A { fn g(&self) -> isize { 20 } }
impl Baz for A { fn h(&self) -> isize { 30 } }
fn f<T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {... | trait Baz { fn h(&self) -> isize; } | random_line_split |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn f<T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| { 30 } | identifier_body |
stylesheet.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 {Namespace, Prefix};
use context::QuirksMode;
use cssparser::{Parser, ParserInput, RuleListParser};
use error_... | {
/// The lock used for user-agent stylesheets.
pub shared_lock: SharedRwLock,
/// The user or user agent stylesheets.
pub user_or_user_agent_stylesheets: Vec<DocumentStyleSheet>,
/// The quirks mode stylesheet.
pub quirks_mode_stylesheet: DocumentStyleSheet,
}
/// A set of namespaces applying... | UserAgentStylesheets | identifier_name |
stylesheet.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 {Namespace, Prefix};
use context::QuirksMode;
use cssparser::{Parser, ParserInput, RuleListParser};
use error_... | Arc::ptr_eq(&self.0, &other.0)
}
}
impl ToMediaListKey for DocumentStyleSheet {
fn to_media_list_key(&self) -> MediaListKey {
self.0.to_media_list_key()
}
}
impl StylesheetInDocument for DocumentStyleSheet {
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin {
self.0.ori... | impl PartialEq for DocumentStyleSheet {
fn eq(&self, other: &Self) -> bool { | random_line_split |
stylesheet.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 {Namespace, Prefix};
use context::QuirksMode;
use cssparser::{Parser, ParserInput, RuleListParser};
use error_... |
/// Records that the stylesheet has been explicitly disabled through the
/// CSSOM.
///
/// Returns whether the the call resulted in a change in disabled state.
///
/// Disabled stylesheets remain in the document, but their rules are not
/// added to the Stylist.
pub fn set_disabled(&s... | {
self.disabled.load(Ordering::SeqCst)
} | identifier_body |
base_ovh_konnector.js | // Generated by CoffeeScript 1.10.0
var Bill, baseKonnector, filterExisting, linkBankOperation, ovhFetcher, saveDataAndFile;
ovhFetcher = require('../lib/ovh_fetcher');
filterExisting = require('../lib/filter_existing');
saveDataAndFile = require('../lib/save_data_and_file');
linkBankOperation = require('../lib/lin... | }
}; | amountDelta: 0.1
})
]
}); | random_line_split |
test.rs | use quickcheck::{TestResult, quickcheck};
use rand::Rng;
use super::{integer_value, regex_value};
use expectest::prelude::*;
use pact_matching::s;
#[test]
fn validates_integer_value() {
fn prop(s: String) -> TestResult {
let mut rng = ::rand::thread_rng();
if rng.gen() && s.chars().any(|ch| !ch.is_... | quickcheck(prop as fn(_) -> _);
expect!(integer_value(s!("1234"))).to(be_ok());
expect!(integer_value(s!("1234x"))).to(be_err());
}
#[test]
fn validates_regex_value() {
expect!(regex_value(s!("1234"))).to(be_ok());
expect!(regex_value(s!("["))).to(be_err());
} | random_line_split | |
test.rs | use quickcheck::{TestResult, quickcheck};
use rand::Rng;
use super::{integer_value, regex_value};
use expectest::prelude::*;
use pact_matching::s;
#[test]
fn validates_integer_value() {
fn prop(s: String) -> TestResult {
let mut rng = ::rand::thread_rng();
if rng.gen() && s.chars().any(|ch| !ch.is_... | () {
expect!(regex_value(s!("1234"))).to(be_ok());
expect!(regex_value(s!("["))).to(be_err());
}
| validates_regex_value | identifier_name |
test.rs | use quickcheck::{TestResult, quickcheck};
use rand::Rng;
use super::{integer_value, regex_value};
use expectest::prelude::*;
use pact_matching::s;
#[test]
fn validates_integer_value() {
fn prop(s: String) -> TestResult {
let mut rng = ::rand::thread_rng();
if rng.gen() && s.chars().any(|ch| !ch.is_... | {
expect!(regex_value(s!("1234"))).to(be_ok());
expect!(regex_value(s!("["))).to(be_err());
} | identifier_body | |
iterator.js | 'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d')
, Iterator = require('es6-iterator')
, toStringTagSymbol = require('es6-symbol').toStringTag
, kinds = require('./iterator-kinds')
, defineProperties = Object.defi... | });
};
if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
MapIterator.prototype = Object.create(Iterator.prototype, {
constructor: d(MapIterator),
_resolve: d(function (i) {
if (this.__kind__ === 'value') return this.__values__[i];
if (this.__kind__ === 'key') return this.__list__[i];
return ... | __values__: d('w', map.__mapValuesData__)
| random_line_split |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinaryS... |
class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice):
"""A binary sensor implementation for ESPHome."""
@property
def _static_info(self) -> 'BinarySensorInfo':
return super()._static_info
@property
def _state(self) -> Optional['BinarySensorState']:
return super()._state
... | """Set up ESPHome binary sensors based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='binary_sensor',
info_type=Binar... | identifier_body |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinaryS... | (self) -> Optional['BinarySensorState']:
return super()._state
@property
def is_on(self):
"""Return true if the binary sensor is on."""
if self._static_info.is_status_binary_sensor:
# Status binary sensors indicated connected state.
# So in their case what's usua... | _state | identifier_name |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinaryS... |
if self._state is None:
return None
return self._state.state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._static_info.device_class
@property
def available(self):
"""Return True ... | return self._entry_data.available | conditional_block |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinaryS... | if self._static_info.is_status_binary_sensor:
return True
return super().available | random_line_split | |
purecss.js | /*******************************
Build Task
*******************************/
var
gulp = require('gulp'),
// node dependencies
console = require('better-console'),
fs = require('fs'),
// gulp dependencies
autoprefixer = require('gulp-autoprefixer'),
chmod = requir... | ;
console.info('Building CSS');
if( !install.isSetup() ) {
console.error('Cannot build files. Run "gulp install" to set-up Semantic');
return;
}
// unified css stream
stream = gulp.src(source.definitions + '/**/' + globs.components + '.less')
.pipe(plumber(settings.plumber.less))
.pipe(le... | }
},
stream,
uncompressedStream | random_line_split |
purecss.js | /*******************************
Build Task
*******************************/
var
gulp = require('gulp'),
// node dependencies
console = require('better-console'),
fs = require('fs'),
// gulp dependencies
autoprefixer = require('gulp-autoprefixer'),
chmod = requir... |
},
stream,
uncompressedStream
;
console.info('Building CSS');
if( !install.isSetup() ) {
console.error('Cannot build files. Run "gulp install" to set-up Semantic');
return;
}
// unified css stream
stream = gulp.src(source.definitions + '/**/' + globs.components + '.less')
.pipe(... | {
callback();
} | conditional_block |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software 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, ... | def on_serverConf_changed(self, entry):
if not self.update_server_conf:
return
self.server_conf.get_chef_conf().set_url(self.ui.txtUrlChef.get_text())
self.server_conf.get_chef_conf().set_pem_url(self.ui.txtUrlChefCert.get_text())
self.server_conf.get_chef_conf().set_defa... | not self.unlink_from_chef:
result, messages = self.validate_conf()
if result == True:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_ldap=False,
unlink_ldap=False,
l... | identifier_body |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software 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, ... | load_page_callback(firstboot.pages.linkToChef)
def next_page(self, load_page_callback):
if not self.unlink_from_chef:
result, messages = self.validate_conf()
if result == True:
result, messages = serverconf.setup_server(
server_conf=sel... | self.ui.lblHostname.set_label(_('Node Name'))
self.ui.lblDefaultRole.set_label(_('Default Group'))
def previous_page(self, load_page_callback): | random_line_split |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software 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, ... | elf, entry):
if not self.update_server_conf:
return
self.server_conf.get_chef_conf().set_url(self.ui.txtUrlChef.get_text())
self.server_conf.get_chef_conf().set_pem_url(self.ui.txtUrlChefCert.get_text())
self.server_conf.get_chef_conf().set_default_role(self.ui.txtDefaultRole... | _serverConf_changed(s | identifier_name |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software 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, ... | load_page_callback(LinkToChefResultsPage, {
'server_conf': self.server_conf,
'result': result,
'messages': messages
})
else:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
... | sult, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_ldap=False,
unlink_ldap=False,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
| conditional_block |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Joel Grand-Guillaume. Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | 'version': '1.1',
'depends': ['account'],
'author': 'Camptocamp',
'license': 'AGPL-3',
'category': 'Generic Modules/Accounting',
'description': """
Account Constraints
===================
Add constraints in the accounting module of OpenERP to avoid bad usage
by users that lead to corrupted data... | random_line_split | |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Valu... |
"args" => {
if let Ok(args) = serde_json::from_str::<Vec<String>>(value) {
// Normalize the first argument to "hg".
let mut full = "hg".to_string();
fo... | {
if let Ok(names) = serde_json::from_str::<Vec<String>>(value) {
let name = names.get(0).cloned().unwrap_or_default();
row.insert("parent".into(), name.into());
}
... | conditional_block |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Valu... | (span: &TreeSpan<&str>, row: &mut Row) {
for (&name, &value) in span.meta.iter() {
match name {
// Those keys are likely generated. Skip them.
"module_path" | "cat" | "line" | "name" => {}
// Attempt to convert it to an integer (since tracing data is
// strin... | extract_span | identifier_name |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Valu... | {
for (&name, &value) in span.meta.iter() {
match name {
// Those keys are likely generated. Skip them.
"module_path" | "cat" | "line" | "name" => {}
// Attempt to convert it to an integer (since tracing data is
// string only).
_ => match value.p... | identifier_body | |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Valu... | }
_ => {}
}
}
}
// The "log:command-row" event is used by code that wants to
// log to columns of the main command row easily.
"log:command-row" if span.is... | } | random_line_split |
lib.rs | #![crate_name = "graphics"]
#![deny(missing_docs)]
#![deny(missing_copy_implementations)]
//! A library for 2D graphics that works with multiple back-ends.
//!
//! Piston-Graphics was started in 2014 by Sven Nilsen to test
//! back-end agnostic design for 2D in Rust.
//! This means generic code can be reused across pr... | <G>(
image: &<G as Graphics>::Texture,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Image::new().draw(image, &Default::default(), transform, g);
}
/// Draws ellipse.
pub fn ellipse<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
... | image | identifier_name |
lib.rs | #![crate_name = "graphics"]
#![deny(missing_docs)]
#![deny(missing_copy_implementations)]
//! A library for 2D graphics that works with multiple back-ends.
//!
//! Piston-Graphics was started in 2014 by Sven Nilsen to test
//! back-end agnostic design for 2D in Rust.
//! This means generic code can be reused across pr... | {
Text::new_color(color, font_size)
.draw(text, cache, &Default::default(), transform, g)
} | identifier_body | |
lib.rs | #![crate_name = "graphics"]
#![deny(missing_docs)]
#![deny(missing_copy_implementations)]
//! A library for 2D graphics that works with multiple back-ends.
//!
//! Piston-Graphics was started in 2014 by Sven Nilsen to test
//! back-end agnostic design for 2D in Rust.
//! This means generic code can be reused across pr... | pub mod text;
pub mod triangulation;
pub mod math;
pub mod deform;
pub mod grid;
pub mod radians {
//! Reexport radians helper trait from vecmath
pub use vecmath::traits::Radians;
}
/// Clears the screen.
pub fn clear<G>(
color: types::Color, g: &mut G
)
where G: Graphics
{
g.clear_color(color);
... | pub mod image;
pub mod types;
pub mod modular_index; | random_line_split |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CEr... | (&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(t... | is_valid | identifier_name |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CEr... |
}
impl<T: Authenticator + Send + Sync + 'static,
X: CDRSTransport + Send + Sync + 'static> r2d2::ManageConnection
for ClusterConnectionManager<T, X> {
type Connection = Session<T, X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CRe... | {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
} | identifier_body |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CEr... | X: CDRSTransport + Send + Sync + 'static> r2d2::ManageConnection
for ClusterConnectionManager<T, X> {
type Connection = Session<T, X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer
.next()
... | }
impl<T: Authenticator + Send + Sync + 'static, | random_line_split |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `ByteString` struct.
use chrono::prelude::{Utc, Weekday};
use chrono::{Datelike, TimeZone};
use cssparser... | ing, PhantomData<*const ()>);
impl DOMString {
/// Creates a new `DOMString`.
pub fn new() -> DOMString {
DOMString(String::new(), PhantomData)
}
/// Creates a new `DOMString` from a `String`.
pub fn from_string(s: String) -> DOMString {
DOMString(s, PhantomData)
}
/// App... | tring(Str | identifier_name |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `ByteString` struct.
use chrono::prelude::{Utc, Weekday};
use chrono::{Datelike, TimeZone};
use cssparser... |
/// Appends a given string slice onto the end of this String.
pub fn push_str(&mut self, string: &str) {
self.0.push_str(string)
}
/// Clears this `DOMString`, removing all contents.
pub fn clear(&mut self) {
self.0.clear()
}
/// Shortens this String to the specified lengt... | pub fn from_string(s: String) -> DOMString {
DOMString(s, PhantomData)
} | random_line_split |
app.js | angular.module('app', ['app.controllers', 'app.services', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "/html/home.html",
data: {
... | event.preventDefault();
$state.go('entrar');
}
});
}); | $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
if(requireLogin && !AuthToken.isAuthenticated()) {
| random_line_split |
app.js | angular.module('app', ['app.controllers', 'app.services', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "/html/home.html",
data: {
... |
});
});
| {
event.preventDefault();
$state.go('entrar');
} | conditional_block |
grunt.js | /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: '<json:jquery-disqus.jquery.json>',
meta: {
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homep... | sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true
},
globals: {
jQuery: true
}
},
uglify: {}
});
// Default task.
grunt.registerTask('default', 'lint qunit concat min');
}; | immed: true,
latedef: true,
newcap: true,
noarg: true, | random_line_split |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
"""
Contains functions that checks project present for conversion and
also function... |
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'The subcircuit does not contain any Kicad netlist file' +
' for conversi... | self.projName = os.path.basename(self.projDir)
self.project = os.path.join(self.projDir, self.projName)
var1 = self.project + ".cir"
var2 = "sub"
self.obj_dockarea.kicadToNgspiceEditor(var1, var2) | conditional_block |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
"""
Contains functions that checks project present for conversion and
also function... | This function create command to call KiCad to Ngspice converter.
If the netlist is not generated for selected project it will show
error **The subcircuit does not contain any Kicad netlist file for
conversion.**
And if no project is selected for conversion, it aga... |
def createSub(self):
""" | random_line_split |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
| """
Contains functions that checks project present for conversion and
also function to convert Kicad Netlist to Ngspice Netlist.
"""
def __init__(self, dockarea):
super(convertSub, self).__init__()
self.obj_validation = Validation()
self.obj_appconfig = Appconfig()
self.... | identifier_body | |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
"""
Contains functions that checks project present for conversion and
also function... | (self, dockarea):
super(convertSub, self).__init__()
self.obj_validation = Validation()
self.obj_appconfig = Appconfig()
self.obj_dockarea = dockarea
def createSub(self):
"""
This function create command to call KiCad to Ngspice converter.
If the netlist ... | __init__ | identifier_name |
Config.js | /**
* @author mrdoob / http://mrdoob.com/
*/
var Config = function () {
var namespace = 'threejs-inspector';
var storage = {
'selectionBoxEnabled': false,
'rafEnabled' : false,
'rafFps' : 30,
}
if ( window.localStorage[ namespace ] === undefined ) | else {
var data = JSON.parse( window.localStorage[ namespace ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
}
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l;... | {
window.localStorage[ namespace ] = JSON.stringify( storage );
} | conditional_block |
Config.js | /**
* @author mrdoob / http://mrdoob.com/
*/
var Config = function () {
var namespace = 'threejs-inspector';
var storage = {
'selectionBoxEnabled': false,
'rafEnabled' : false,
'rafFps' : 30,
}
if ( window.localStorage[ namespace ] === undefined ) {
window.localStorage[ namespace ] = JSON.stringify( ... | },
clear: function () {
delete window.localStorage[ namespace ];
}
}
}; |
window.localStorage[ namespace ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );
| random_line_split |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
de... | ,b, matrix):
if b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
return matrix[(tuple(reversed((a,b))))]
else:
return matrix[(a,b)]
def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C... | ore_match(a | identifier_name |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
de... | def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C","G"]
# on commence par déterminer quels acides aminés de x et y sont "ciblés"
aaX = Seq("", IUPAC.protein)
aaY = Seq("", IUPAC.protein)
q_bis = 0.
q_bis += q
if(z<=0):
aaX += x[i]
q_b... | b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
return matrix[(tuple(reversed((a,b))))]
else:
return matrix[(a,b)]
| identifier_body |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
de... | currentDNAx += a + b + ldna[doublon+2]
currentaaX = currentDNAx.translate()
currentDNAy += ldna[doublon-1] +a + b
currentaaY = currentDNAy.reverse_complement().translate()
score = score_match(aaX[0].upper(),currentaaX[0].upper(),blosum62)
score += ... | for a in ATCG:
for b in ATCG:
currentDNAx = Seq("", IUPAC.unambiguous_dna)
currentDNAy = Seq("", IUPAC.unambiguous_dna) | random_line_split |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
de... |
scores = []
for a in ATCG:
for b in ATCG:
currentDNAx = Seq("", IUPAC.unambiguous_dna)
currentDNAy = Seq("", IUPAC.unambiguous_dna)
currentDNAx += a + b + ldna[doublon+2]
currentaaX = currentDNAx.translate()
currentDNAy += ldna[doublon-1] ... | =y[-i + z//3]
q_bis*=patternY[-i + z//3]
| conditional_block |
index.d.ts | // Type definitions for react-particles-js v3.0.0
// Project: https://github.com/wufe/react-particles-js
// Definitions by: Simone Bembi <https://github.com/wufe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="react" />
import { ComponentClass } from "react";
import { Containe... | width?: string;
height?: string;
params?: IParticlesParams;
style?: any;
className?: string;
canvasClassName?: string;
particlesRef?: React.RefObject<Container>;
}
type Particles = ComponentClass<ParticlesProps>;
declare const Particles: Particles;
export default Particles; | export * from "tsparticles/Plugins/PolygonMask/Enums";
export interface ParticlesProps { | random_line_split |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""doc... | print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after outlier filtering:",len(self.viruses) | identifier_body | |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""doc... | (self):
from seq_util import hamming_distance
outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq
return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain])
def clean_distances(self):
"""Remove viruses that don't follow a loose clock """
times = self.times_from_o... | distance_from_outgroup | identifier_name |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""doc... |
self.viruses = MultipleSeqAlignment(new_viruses)
def clean_generic(self):
print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after ou... | print "\t\tresidual:", r, "\nremoved ",v.strain | conditional_block |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""doc... | for v in self.viruses:
v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq)))
def unique_date(self):
'''
add a unique numerical date to each leaf. uniqueness is achieved adding a small number
'''
from date_util import numerical_date
og = self.sequence_lookup[self.outgroup['strain']]
if hasa... | ancestral inference will interpret this as missing data
''' | random_line_split |
macro_parser.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | erTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
sep: Option<Token>,
idx: usize,
up: Option<Box<MatcherPos>>,
matches: Vec<Vec<Rc<NamedMatch>>>,
match_lo: usize,
match_cur: usize,
match_hi: usize,
sp_lo: BytePos,
}
pub fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, ... | Vec<Match | identifier_name |
macro_parser.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | r_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos)
-> Box<MatcherPos> {
let match_idx_hi = count_names(&ms[..]);
let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect();
Box::new(MatcherPos {
stack: vec![],
top_elts: TtSeq(ms),
sep... | |count, elt| {
count + match elt {
&TtSequence(_, ref seq) => {
seq.num_captures
}
&TtDelimited(_, ref delim) => {
count_names(&delim.tts)
}
&TtToken(_, MatchNt(..)) => {
1
}
&TtT... | identifier_body |
macro_parser.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | if seq.op == ast::ZeroOrMore {
let mut new_ei = ei.clone();
new_ei.match_cur += seq.num_captures;
new_ei.idx += 1;
//we specifically matched zero repeats.
f... | match ei.top_elts.get_tt(idx) {
/* need to descend into sequence */
TtSequence(sp, seq) => { | random_line_split |
transitionService.d.ts | /**
* @coreapi
* @module transition
*/
/** for typedoc */
import { IHookRegistry, TransitionOptions, TransitionHookScope, TransitionHookPhase, TransitionCreateHookFn, HookMatchCriteria, HookRegOptions, PathTypes, PathType, RegisteredHooks, TransitionHookFn, TransitionStateHookFn } from "./interface";
import { Transi... | implements IHookRegistry, Disposable {
/** @hidden */
_transitionCount: number;
/**
* Registers a [[TransitionHookFn]], called *while a transition is being constructed*.
*
* Registers a transition lifecycle hook, which is invoked during transition construction.
*
* This low level h... | TransitionService | identifier_name |
transitionService.d.ts | /**
* @coreapi
* @module transition
*/
/** for typedoc */
import { IHookRegistry, TransitionOptions, TransitionHookScope, TransitionHookPhase, TransitionCreateHookFn, HookMatchCriteria, HookRegOptions, PathTypes, PathType, RegisteredHooks, TransitionHookFn, TransitionStateHookFn } from "./interface";
import { Transi... | _pluginapi: TransitionServicePluginAPI;
/**
* This object has hook de-registration functions for the built-in hooks.
* This can be used by third parties libraries that wish to customize the behaviors
*
* @hidden
*/
_deregisterHookFns: {
addCoreResolves: Function;
red... | /** @hidden The paths on a criteria object */
private _criteriaPaths;
/** @hidden */
private _router;
/** @internalapi */ | random_line_split |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... | keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3',
'Pro... | author_email='azpysdkhelp@microsoft.com',
url='https://github.com/Azure/azure-sdk-for-python', | random_line_split |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + ... | raise RuntimeError('Cannot find version information') | conditional_block |
variable.rs | //! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use cretonne... |
}
impl EntityRef for Variable {
fn new(index: usize) -> Self {
debug_assert!(index < (u32::MAX as usize));
Variable(index as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}
| {
debug_assert!(index < u32::MAX);
Variable(index)
} | identifier_body |
variable.rs | //! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use cretonne... |
fn index(self) -> usize {
self.0 as usize
}
} | random_line_split | |
variable.rs | //! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use cretonne... | (self) -> usize {
self.0 as usize
}
}
| index | identifier_name |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch =... |
def should_flush(self):
return len(self.actions) > self.batch_size
def flush(self):
if self.actions:
try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
... | self.actions.append(action)
self.flush_or_not() | identifier_body |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch =... | (self):
return len(self.actions) > self.batch_size
def flush(self):
if self.actions:
try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is rais... | should_flush | identifier_name |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch =... | log.warning(
'error sending bulk update to ElasticSearch',
exc_info=True)
self.actions = [] | random_line_split | |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch =... | try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is raised, and other documents are not inserted
log.warning(
'error sending bulk update t... | conditional_block | |
enclosure_getters.rs | // This file is part of feed.
//
// Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
... | }
|
self.mime_type.clone()
}
| identifier_body |
enclosure_getters.rs | // This file is part of feed.
//
// Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
... | ///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_ref())
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///... | ///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters}; | random_line_split |
enclosure_getters.rs | // This file is part of feed.
//
// Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
... | &self) -> String
{
self.length.clone()
}
/// Get the enclosure type that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let enclosure_type = "audio/ogg";
///
/// let url = "http://www.podtrac.... | ength( | identifier_name |
Search.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import {connect} from 'react... | props) {
super(props);
this.state = {
includedWords: []
};
this.getWords = this.getWords.bind(this);
}
getWords(words) {
this.setState({
includedWords: words
});
}
render() {
const styles = {
fontFamily: 'Helvetica Neue',
fontSize: 14,
lineHeight: '10p... | onstructor( | identifier_name |
Search.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import {connect} from 'react... | this.getWords = this.getWords.bind(this);
}
getWords(words) {
this.setState({
includedWords: words
});
}
render() {
const styles = {
fontFamily: 'Helvetica Neue',
fontSize: 14,
lineHeight: '10px',
color: 'white',
display: 'flex',
alignItems: 'center',
... | constructor(props) {
super(props);
this.state = {
includedWords: []
}; | random_line_split |
deref_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cell::RefCell;
use core::cell::RefMut;
use core::ops::DerefMut;
use core::ops::Deref;
// pub struct RefCell<T: ?Sized> {
// borrow: Cell<BorrowFlag>,
// value: UnsafeCell<T>,
// }
// impl<T> RefCell<T... |
}
| {
let value: T = 68;
let refcell: RefCell<T> = RefCell::<T>::new(value);
let mut value_refmut: RefMut<T> = refcell.borrow_mut();
{
let deref_mut: &mut T = value_refmut.deref_mut();
*deref_mut = 500;
}
let value_ref: &T = value_refmut.deref();
assert_eq!(*value_ref, 500);
} | identifier_body |
deref_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cell::RefCell;
use core::cell::RefMut;
use core::ops::DerefMut;
use core::ops::Deref;
// pub struct RefCell<T: ?Sized> {
// borrow: Cell<BorrowFlag>,
// value: UnsafeCell<T>,
// }
// impl<T> RefCell<T... | () {
let value: T = 68;
let refcell: RefCell<T> = RefCell::<T>::new(value);
let mut value_refmut: RefMut<T> = refcell.borrow_mut();
{
let deref_mut: &mut T = value_refmut.deref_mut();
*deref_mut = 500;
}
let value_ref: &T = value_refmut.deref();
assert_eq!(*value_ref, 500);
}
}
| deref_test1 | identifier_name |
deref_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cell::RefCell;
use core::cell::RefMut;
use core::ops::DerefMut;
use core::ops::Deref;
// pub struct RefCell<T: ?Sized> {
// borrow: Cell<BorrowFlag>,
// value: UnsafeCell<T>,
// }
// impl<T> RefCell<T... | // /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// ///
// /// let five = c.into_inner();
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn into_inner(self) -> T {
// ... | // ///
// /// # Examples
// /// | random_line_split |
main.py | import re
import datetime
import time
#niru's git commit
while True:
#open the file for reading
file = open("test.txt")
content = file.read()
#Get timestamp
ts = time.time()
ist = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#open file for read and close it nea... | time.sleep(5) | random_line_split | |
main.py | import re
import datetime
import time
#niru's git commit
while True:
#open the file for reading
| file = open("test.txt")
content = file.read()
#Get timestamp
ts = time.time()
ist = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#open file for read and close it neatly(wrap code in try/except)
#with open('test.txt', 'r') as r:
#content = r.read()
#pri... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.