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
timeranges.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use c...
fn is_overlapping(&self, other: &TimeRange) -> bool { // This also covers the case where `self` is entirely contained within `other`, // for example: `self` = [2,3) and `other` = [1,4). self.contains(other.start) || self.contains(other.end) || other.contains(self.start) } fn is_co...
{ self.start <= time && time < self.end }
identifier_body
timeranges.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use c...
} pub fn is_before(&self, other: &TimeRange) -> bool { other.start >= self.end } } impl fmt::Debug for TimeRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "[{},{})", self.start, self.end) } } #[derive(Debug)] pub enum TimeRangesError { E...
self.contains(other.start) || self.contains(other.end) || other.contains(self.start) } fn is_contiguous(&self, other: &TimeRange) -> bool { other.start == self.end || other.end == self.start
random_line_split
timeranges.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TimeRangesBinding; use c...
(&self, index: u32) -> Result<f64, TimeRangesError> { self.ranges .get(index as usize) .map(|r| r.end) .ok_or(TimeRangesError::OutOfRange) } pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> { if start > end { return Err(T...
end
identifier_name
validation.py
from voluptuous import Invalid import re def Url(msg=None):
def TrackableCid(msg=None): def f(v): regex = re.compile(r'^[A-Z]{2}-[A-Z]{2}-[1-9]{1}[0-9]*$', re.IGNORECASE) if re.match(regex, str(v)): return str(v) else: raise Invalid(msg or "value is not correct trackable CID") return f
def f(v): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(...
identifier_body
validation.py
from voluptuous import Invalid import re def Url(msg=None): def
(v): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d...
f
identifier_name
validation.py
from voluptuous import Invalid import re def Url(msg=None): def f(v): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... ...
else: raise Invalid(msg or "value is not correct trackable CID") return f
return str(v)
conditional_block
validation.py
from voluptuous import Invalid import re def Url(msg=None): def f(v): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... ...
else: raise Invalid(msg or "value is not correct Uniform Resource Locator") return f def TrackableCid(msg=None): def f(v): regex = re.compile(r'^[A-Z]{2}-[A-Z]{2}-[1-9]{1}[0-9]*$', re.IGNORECASE) if re.match(regex, str(v)): return str(v) else: ...
r'(?:/?|[/?]\S+)$', re.IGNORECASE) if re.match(regex, str(v)): return str(v)
random_line_split
calcAtRulePatternPriority.js
module.exports = function calcAtRulePatternPriority(pattern, node) { // 0 β€” it pattern doesn't match // 1 β€” pattern without `name` and `hasBlock` // 10010 β€” pattern match `hasBlock` // 10100 β€” pattern match `name` // 20110 β€” pattern match `name` and `hasBlock` // 21100 β€” patter match `name` and `parameter` // 31...
priority += 10000; } // match `name` if (pattern.hasOwnProperty('parameter') && pattern.parameter.test(node.parameter)) { priority += 1100; priority += 10000; } // doesn't have `name` and `hasBlock` if ( !pattern.hasOwnProperty('hasBlock') && !pattern.hasOwnProperty('name') && !pattern.hasOwnPropert...
} // match `name` if (pattern.hasOwnProperty('name') && node.name === pattern.name) { priority += 100;
random_line_split
calcAtRulePatternPriority.js
module.exports = function calcAtRulePatternPriority(pattern, node) { // 0 β€” it pattern doesn't match // 1 β€” pattern without `name` and `hasBlock` // 10010 β€” pattern match `hasBlock` // 10100 β€” pattern match `name` // 20110 β€” pattern match `name` and `hasBlock` // 21100 β€” patter match `name` and `parameter` // 31...
as `name` and `hasBlock`, but it doesn't match both properties if (pattern.hasOwnProperty('hasBlock') && pattern.hasOwnProperty('name') && priority < 20000) { priority = 0; } // patter has `name` and `parameter`, but it doesn't match both properties if (pattern.hasOwnProperty('name') && pattern.hasOwnProperty('p...
1; } // patter h
conditional_block
std_pf_readonly.py
from __future__ import unicode_literals def execute(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, ...
webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')
webnotes.conn.commit()
random_line_split
std_pf_readonly.py
from __future__ import unicode_literals def execute():
] for perms in new_perms: doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save() webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')
"""Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfield': '...
identifier_body
std_pf_readonly.py
from __future__ import unicode_literals def
(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfiel...
execute
identifier_name
std_pf_readonly.py
from __future__ import unicode_literals def execute(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, ...
webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')
doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save()
conditional_block
all_problems.py
"""Imports for problem modules.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import re MODULES = [ "problem_hparams", # pylint: disable=line-too-long "translate_ende", # pylint: disable=line-too-long "translate_enfr", #...
_handle_errors(errors)
try: importlib.import_module(module) except ImportError as error: errors.append((module, error))
conditional_block
all_problems.py
"""Imports for problem modules.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import re MODULES = [ "problem_hparams", # pylint: disable=line-too-long "translate_ende", # pylint: disable=line-too-long "translate_enfr", #...
(errors): """Log out and possibly reraise errors during import.""" if not errors: return log_all = True # pylint: disable=unused-variable err_msg = "Skipped importing {num_missing} data_generators modules." # BEGIN GOOGLE-INTERNAL err_msg += (" OK if no other errors. Depend on _heavy or problem-specifi...
_handle_errors
identifier_name
all_problems.py
"""Imports for problem modules.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib
"translate_enfr", # pylint: disable=line-too-long ] ALL_MODULES = list(MODULES) def _is_import_err_msg(err_str, module): module_pattern = "(.)?".join(["(%s)?" % m for m in module.split(".")]) return re.match("^No module named (')?%s(')?$" % module_pattern, err_str) def _handle_errors(errors): """Log out ...
import re MODULES = [ "problem_hparams", # pylint: disable=line-too-long "translate_ende", # pylint: disable=line-too-long
random_line_split
all_problems.py
"""Imports for problem modules.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import re MODULES = [ "problem_hparams", # pylint: disable=line-too-long "translate_ende", # pylint: disable=line-too-long "translate_enfr", #...
def import_modules(modules): errors = [] for module in modules: try: importlib.import_module(module) except ImportError as error: errors.append((module, error)) _handle_errors(errors)
"""Log out and possibly reraise errors during import.""" if not errors: return log_all = True # pylint: disable=unused-variable err_msg = "Skipped importing {num_missing} data_generators modules." # BEGIN GOOGLE-INTERNAL err_msg += (" OK if no other errors. Depend on _heavy or problem-specific " ...
identifier_body
quote.py
import discord from discord.ext import commands from random import choice as randomchoice from .utils.dataIO import fileIO from .utils import checks import os defaultQuotes = [ "Thats why I love switch hitting, I like to be in control ~ Jan, from the Hypermine Dragon Fight - 21st May 2016", "Thank you for wwaking wi...
await self.bot.say("That quote is already in the database!") else: self.quotes.append(quote) self.save_quotes() await self.bot.say("Quote: " + quote + " has been saved to the database!") @quote.command() @checks.mod_or_permissions(adminstrator=True) async def remove(self, quote): """Removes a Quote ...
"""Quote System for Red-DiscordBot Based on the MIRC Quote Script by Zsadist (Hawkee Link: http://hawkee.com/snippet/8378/ )""" def __init__(self, bot): self.bot = bot self.quotes = fileIO("data/quote/quotes.json", "load") def save_quotes(self): fileIO("data/quote/quotes.json", 'save', self.quotes) @comma...
identifier_body
quote.py
import discord from discord.ext import commands from random import choice as randomchoice from .utils.dataIO import fileIO from .utils import checks import os defaultQuotes = [ "Thats why I love switch hitting, I like to be in control ~ Jan, from the Hypermine Dragon Fight - 21st May 2016", "Thank you for wwaking wi...
else: self.quotes.append(quote) self.save_quotes() await self.bot.say("Quote: " + quote + " has been saved to the database!") @quote.command() @checks.mod_or_permissions(adminstrator=True) async def remove(self, quote): """Removes a Quote from the list""" if quote not in self.quotes: await self.b...
await self.bot.say("That quote is already in the database!")
conditional_block
quote.py
import discord from discord.ext import commands from random import choice as randomchoice from .utils.dataIO import fileIO from .utils import checks import os defaultQuotes = [ "Thats why I love switch hitting, I like to be in control ~ Jan, from the Hypermine Dragon Fight - 21st May 2016", "Thank you for wwaking wi...
: """Quote System for Red-DiscordBot Based on the MIRC Quote Script by Zsadist (Hawkee Link: http://hawkee.com/snippet/8378/ )""" def __init__(self, bot): self.bot = bot self.quotes = fileIO("data/quote/quotes.json", "load") def save_quotes(self): fileIO("data/quote/quotes.json", 'save', self.quotes) @co...
Quote
identifier_name
quote.py
import discord from discord.ext import commands from random import choice as randomchoice from .utils.dataIO import fileIO from .utils import checks import os defaultQuotes = [ "Thats why I love switch hitting, I like to be in control ~ Jan, from the Hypermine Dragon Fight - 21st May 2016", "Thank you for wwaking wi...
if quote not in self.quotes: await self.bot.say("That quote is already in the database!") else: self.quotes.remove(quote) self.save_quotes() await self.bot.say("Quote: " + quote + " has been removed from the database!") def check_folder(): if not os.path.exists("data/quote"): print("Creating data/qu...
"""Removes a Quote from the list"""
random_line_split
dynamo.py
import logging import pendulum from pynamodb.attributes import (UnicodeAttribute, UTCDateTimeAttribute) from pynamodb.exceptions import DoesNotExist from pynamodb.models import Model from . import BaseLocker, Lock, LockAccessDenied log = logging.getLogger(__name__) class DynamoLock(Model): class Meta: ...
(): self.release_lock(key, owner_name) # return lock return Lock(release, expires=rec.expires) def release_lock(self, key, owner_name='unknown'): try: lock = DynamoLock.get(key) if lock.owner_name != owner_name: log.debug(f"found lock: ...
release
identifier_name
dynamo.py
import logging import pendulum from pynamodb.attributes import (UnicodeAttribute, UTCDateTimeAttribute) from pynamodb.exceptions import DoesNotExist from pynamodb.models import Model from . import BaseLocker, Lock, LockAccessDenied log = logging.getLogger(__name__) class DynamoLock(Model): class Meta: ...
if (pendulum.now('UTC') < old.expires) and old.owner_name != owner_name: log.debug(f"Lock {key} denied") raise LockAccessDenied() # delete the old lock old.delete() except DoesNotExist: pass # create the new lock ...
""" Use DynamoDB for locking. """ def __init__(self, table=None, url=None, region='us-east-1'): DynamoLock.region = region # if url: # log.warning(f"Using DynamoDB url: {url}") # if table: # log.warning(f"Using DynamoDB table: {table}") DynamoLock.creat...
identifier_body
dynamo.py
import logging import pendulum from pynamodb.attributes import (UnicodeAttribute, UTCDateTimeAttribute) from pynamodb.exceptions import DoesNotExist from pynamodb.models import Model from . import BaseLocker, Lock, LockAccessDenied log = logging.getLogger(__name__) class DynamoLock(Model): class Meta: ...
# delete the old lock old.delete() except DoesNotExist: pass # create the new lock rec = DynamoLock( key = key, expires = pendulum.now('UTC').add(seconds = lease_time), owner_name = owner_name, ) ...
log.debug(f"Lock {key} denied") raise LockAccessDenied()
random_line_split
dynamo.py
import logging import pendulum from pynamodb.attributes import (UnicodeAttribute, UTCDateTimeAttribute) from pynamodb.exceptions import DoesNotExist from pynamodb.models import Model from . import BaseLocker, Lock, LockAccessDenied log = logging.getLogger(__name__) class DynamoLock(Model): class Meta: ...
# delete the old lock old.delete() except DoesNotExist: pass # create the new lock rec = DynamoLock( key = key, expires = pendulum.now('UTC').add(seconds = lease_time), owner_name = owner_name, ) ...
log.debug(f"Lock {key} denied") raise LockAccessDenied()
conditional_block
session_persistence.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c)2012 Rackspace US, Inc. # 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.ap...
print("New setting of session persistence:", lb.session_persistence or '""')
print("Setting persistence to HTTP_COOKIE...") lb.session_persistence = "HTTP_COOKIE"
conditional_block
session_persistence.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c)2012 Rackspace US, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may
# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # ...
# not use this file except in compliance with the License. You may obtain
random_line_split
consumer.js
var EventEmitter = require('events').EventEmitter, _ = require('lodash'), eventBatch = require('./eventbatch'), dbapi = require('./dbapi'); // pgq.Consumer() module.exports = function(config) { var self = new EventEmitter(); var initialize = function(config) { var requiredParams = { consumerName...
// at this point we hand the control over to the consumer implementation // once the consumer has marked each and every event in batch with // ev.tagDone ev.tagRetry the batch will try to update it's status // within the database. If it's successful it calls batchProcessed // when an error happens we ...
{ self.log('got ' + batchEvents.length + ' events '); }
conditional_block
consumer.js
var EventEmitter = require('events').EventEmitter, _ = require('lodash'), eventBatch = require('./eventbatch'), dbapi = require('./dbapi'); // pgq.Consumer() module.exports = function(config) { var self = new EventEmitter(); var initialize = function(config) { var requiredParams = { consumerName...
emitWhenDone('batchEventsLoaded') ); } }; // step 4 - emit events to client implementation where they get // handled and acknowledged via ev.tagDone ev.tagRetry self.emitEventsToHandler = function(batchId, batchEvents) { // with empty batch immediately mark it as processed if (batchEvents.len...
// build a new eventBatch for this consumer+batch and load events self.log('polling for batch events'); eventBatch(self).load( batch.batch_id,
random_line_split
test_db_rule_enforcement.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the 'License'); you may not use th...
(): created = RuleEnforcementDB(trigger_instance_id=str(bson.ObjectId()), rule={'ref': 'foo_pack.foo_rule', 'uid': 'rule:foo_pack:foo_rule'}, execution_id=str(bson.ObjectId())) return RuleEn...
_create_save_rule_enforcement
identifier_name
test_db_rule_enforcement.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the 'License'); you may not use th...
self.assertIsNone(retrieved, 'managed to retrieve after delete.') @staticmethod def _create_save_rule_enforcement(): created = RuleEnforcementDB(trigger_instance_id=str(bson.ObjectId()), rule={'ref': 'foo_pack.foo_rule', ...
def test_ruleenforcment_crud(self): saved = RuleEnforcementModelTest._create_save_rule_enforcement() retrieved = RuleEnforcement.get_by_id(saved.id) self.assertEqual(saved.rule.ref, retrieved.rule.ref, 'Same rule enforcement was not returned.') self.assertTrue(re...
identifier_body
test_db_rule_enforcement.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the 'License'); you may not use th...
model_object.delete()
conditional_block
test_db_rule_enforcement.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the 'License'); you may not use th...
# cleanup RuleEnforcementModelTest._delete([retrieved]) try: retrieved = RuleEnforcement.get_by_id(saved.id) except StackStormDBObjectNotFoundError: retrieved = None self.assertIsNone(retrieved, 'managed to retrieve after delete.') @staticmethod d...
retrieved = RuleEnforcement.get_by_id(saved.id) self.assertEqual(retrieved.rule.id, RULE_ID, 'Update to rule enforcement failed.')
random_line_split
config.py
# The default ``config.py`` # flake8: noqa def set_prefs(prefs): """This function is called before opening the project""" # Specify which files and folders to ignore in the project. # Changes to ignored resources are not added to the history and # VCSs. Also they are not returned in `Project.get_fil...
(project): """This function is called after opening the project""" # Do whatever you like here!
project_opened
identifier_name
config.py
# The default ``config.py`` # flake8: noqa def set_prefs(prefs): """This function is called before opening the project""" # Specify which files and folders to ignore in the project. # Changes to ignored resources are not added to the history and # VCSs. Also they are not returned in `Project.get_fil...
# How many undos to hold? prefs['max_history_items'] = 32 # Shows whether to save history across sessions. prefs['save_history'] = True prefs['compress_history'] = False # Set the number spaces used for indenting. According to # :PEP:`8`, it is best to use 4 spaces. Since most of rope's...
random_line_split
config.py
# The default ``config.py`` # flake8: noqa def set_prefs(prefs): """This function is called before opening the project""" # Specify which files and folders to ignore in the project. # Changes to ignored resources are not added to the history and # VCSs. Also they are not returned in `Project.get_fil...
"""This function is called after opening the project""" # Do whatever you like here!
identifier_body
extensionManagement.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
publisher: string; publisherDisplayName: string; description: string; installCount: number; rating: number; ratingCount: number; assets: IGalleryExtensionAssets; properties: IGalleryExtensionProperties; } export interface IGalleryMetadata { id: string; publisherId: string; publisherDisplayName: string; } e...
displayName: string; publisherId: string;
random_line_split
map.d.ts
import { Observable } from '../Observable'; /** * Applies a given `project` function to each value emitted by the source * Observable, and emits the resulting values as an Observable. * * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obj...
* @see {@link mapTo} * @see {@link pluck} * * @param {function(value: T, index: number): R} project The function to apply * to each `value` emitted by the source Observable. The `index` parameter is * the number `i` for the i-th emission that has happened since the * subscription, starting from the number `0`. ...
*
random_line_split
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { l...
fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>, msg: redis::Msg) -> redis::RedisResult<()> { let channel = msg.get_channel_name(); let payload: String = try!(msg.get_payload()); debug!("New message on Redis channel {}: '{}'", channel, payload); match chan...
{ let client = try!(redis::Client::open(url)); let mut pubsub: redis::PubSub = try!(client.get_pubsub()); try!(pubsub.subscribe("backend_add")); try!(pubsub.subscribe("backend_remove")); info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'"); Ok(pubsub) }
identifier_body
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { l...
msg: redis::Msg) -> redis::RedisResult<()> { let channel = msg.get_channel_name(); let payload: String = try!(msg.get_payload()); debug!("New message on Redis channel {}: '{}'", channel, payload); match channel { "backend_add" => { let mut backend...
info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'"); Ok(pubsub) } fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>,
random_line_split
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn
(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { let msg = pubsub.get_message().unwrap(); handle_message(backend.clone(), msg).unwrap(); } }); } fn subscribe_to_redi...
create_sync_thread
identifier_name
sync.rs
extern crate redis; use std::sync::{Arc, Mutex}; use std::thread; use backend::{RoundRobinBackend, GetBackend}; pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) { thread::spawn(move || { let pubsub = subscribe_to_redis(&redis_url).unwrap(); loop { l...
} } "backend_remove" => { let mut backend = backend.lock().unwrap(); match backend.remove(&payload) { Ok(_) => info!("Removed server {}", payload), _ => {} } } _ => info!("Cannot parse Redis message"), }...
{}
conditional_block
base.py
# -*- coding: utf-8 -*- """Generic feature selection mixin""" # Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman # License: BSD 3 clause from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from scipy.sparse import issparse, csc_matrix from ..base import TransformerMixin f...
(self, indices=False): """ Get a mask, or integer index, of the features selected Parameters ---------- indices : boolean (default False) If True, the return value will be an array of integers, rather than a boolean mask. Returns ------- ...
get_support
identifier_name
base.py
# -*- coding: utf-8 -*- """Generic feature selection mixin""" # Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman # License: BSD 3 clause from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from scipy.sparse import issparse, csc_matrix from ..base import TransformerMixin f...
support = self.get_support() X = check_array(X) if support.sum() != X.shape[1]: raise ValueError("X has a different shape than during fitting.") if X.ndim == 1: X = X[None, :] Xt = np.zeros((X.shape[0], support.size), dtype=X.dtype) Xt[:, suppor...
X = X.tocsc() # insert additional entries in indptr: # e.g. if transform changed indptr from [0 2 6 7] to [0 2 3] # col_nonzeros here will be [2 0 1] so indptr becomes [0 2 2 3] col_nonzeros = self.inverse_transform(np.diff(X.indptr)).ravel() indptr = np.conca...
conditional_block
base.py
# -*- coding: utf-8 -*- """Generic feature selection mixin""" # Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman # License: BSD 3 clause from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from scipy.sparse import issparse, csc_matrix from ..base import TransformerMixin f...
indptr = np.concatenate([[0], np.cumsum(col_nonzeros)]) Xt = csc_matrix((X.data, X.indices, indptr), shape=(X.shape[0], len(indptr) - 1), dtype=X.dtype) return Xt support = self.get_support() X = check_array(X) if support.sum() != ...
""" Reverse the transformation operation Parameters ---------- X : array of shape [n_samples, n_selected_features] The input samples. Returns ------- X_r : array of shape [n_samples, n_original_features] `X` with columns of zeros inserted...
identifier_body
base.py
# -*- coding: utf-8 -*- """Generic feature selection mixin""" # Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman # License: BSD 3 clause from abc import ABCMeta, abstractmethod from warnings import warn import numpy as np from scipy.sparse import issparse, csc_matrix from ..base import TransformerMixin f...
return Xt support = self.get_support() X = check_array(X) if support.sum() != X.shape[1]: raise ValueError("X has a different shape than during fitting.") if X.ndim == 1: X = X[None, :] Xt = np.zeros((X.shape[0], support.size), dtype=X.dtype)...
col_nonzeros = self.inverse_transform(np.diff(X.indptr)).ravel() indptr = np.concatenate([[0], np.cumsum(col_nonzeros)]) Xt = csc_matrix((X.data, X.indices, indptr), shape=(X.shape[0], len(indptr) - 1), dtype=X.dtype)
random_line_split
coordinates-constraint-config-form.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
} private resetForm() { this.form.clearValidators(); removeAllFormControls(this.form); } private createForm() { this.form.addControl( CoordinatesConstraintFormControl.Format, new FormControl((this.config && this.config.format) || CoordinatesFormat.DecimalDegrees) ); this.form....
{ this.resetForm(); this.createForm(); }
conditional_block
coordinates-constraint-config-form.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
(format: CoordinatesFormat): number { return format === CoordinatesFormat.DegreesMinutesSeconds ? 0 : 6; }
getDefaultPrecision
identifier_name
coordinates-constraint-config-form.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Gene...
random_line_split
index.tsx
/* * MIT License * * Copyright (c) 2018 Choko (choko@curioswitch.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * ...
}; domImage.src = src; }, []); useEffect(() => { if (!image) { return; } image.src = src; }, [src, image]); if (!image) { return null; } // eslint-disable-next-line react/jsx-props-no-spreading return <ReactKonvaImage image={image} {...props} />; }; export default React...
{ setImage(domImage); }
conditional_block
index.tsx
/* * MIT License * * Copyright (c) 2018 Choko (choko@curioswitch.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * ...
}, [src, image]); if (!image) { return null; } // eslint-disable-next-line react/jsx-props-no-spreading return <ReactKonvaImage image={image} {...props} />; }; export default React.memo(KonvaImage);
} image.src = src;
random_line_split
editor.js
var tinymce_cnf = { selector: 'textarea.tinymce', plugins: 'link table code fullscreen preview textcolor paste image media responsivefilemanager anchor codesample', toolbar: "responsivefilemanager undo redo | styleselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numli...
{ $("#"+repeater_id+"_"+row_id).remove(); }
identifier_body
editor.js
var tinymce_cnf = { selector: 'textarea.tinymce', plugins: 'link table code fullscreen preview textcolor paste image media responsivefilemanager anchor codesample', toolbar: "responsivefilemanager undo redo | styleselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numli...
$('.tinymce').each(function() { if ($(this).attr('addedmce') == undefined) { $(this).attr('addedmce', 'true'); tinymce.execCommand('mceRemoveEditor',true,$(this).attr('id')); tinymce.execCommand('mceAddEditor',true,$(this).attr('id')); } ...
function load_editor_js(rerun) { if (rerun != undefined) {
random_line_split
editor.js
var tinymce_cnf = { selector: 'textarea.tinymce', plugins: 'link table code fullscreen preview textcolor paste image media responsivefilemanager anchor codesample', toolbar: "responsivefilemanager undo redo | styleselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numli...
(rerun) { if (rerun != undefined) { $('.tinymce').each(function() { if ($(this).attr('addedmce') == undefined) { $(this).attr('addedmce', 'true'); tinymce.execCommand('mceRemoveEditor',true,$(this).attr('id')); tinymce.execCommand('mceAddEditor',tr...
load_editor_js
identifier_name
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 la...
() { let s = r#"{ "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", "caller" : "cd1722f2947def4cf144679da39c4c32bdc35681", "code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055", "data" : "0x", "gas...
transaction_deserialization
identifier_name
transaction.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity.
// the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Publ...
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by
random_line_split
SimpleToken.ts
/* * Copyright 2013 ZXing authors * * 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 wri...
(bitArray: BitArray, text: /*byte[]*/Uint8Array): void { bitArray.appendBits(this.value, this.bitCount); } public /*final*/ add(value: int, bitCount: int): Token { return new SimpleToken(this, value, bitCount); } public /*final*/ addBinaryShift(start: int, byteCount: int): Token { // no-op can't b...
appendTo
identifier_name
SimpleToken.ts
/* * Copyright 2013 ZXing authors * * 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 wri...
// no-op can't binary shift a simple token console.warn('addBinaryShift on SimpleToken, this simply returns a copy of this token'); return new SimpleToken(this, start, byteCount); } /** * @Override */ public toString(): String { let value: int = this.value & ((1 << this.bitCount) - 1); ...
random_line_split
manager.py
#coding:utf-8 import functools from cactus.utils.internal import getargspec from cactus.plugin import defaults class PluginManager(object): def __init__(self, site, loaders): self.site = site self.loaders = loaders self.reload() for plugin_method in defaults.DEFAULTS: ...
def call(self, method, *args, **kwargs): """ Call each plugin """ for plugin in self.plugins: _meth = getattr(plugin, method) _meth(*args, **kwargs) def preBuildPage(self, site, page, context, data): """ Special call as we have changed t...
plugins = [] for loader in self.loaders: plugins.extend(loader.load()) self.plugins = sorted(plugins, key=lambda plugin: plugin.ORDER)
identifier_body
manager.py
#coding:utf-8 import functools from cactus.utils.internal import getargspec
from cactus.plugin import defaults class PluginManager(object): def __init__(self, site, loaders): self.site = site self.loaders = loaders self.reload() for plugin_method in defaults.DEFAULTS: if not hasattr(self, plugin_method): setattr(self, plugin_me...
random_line_split
manager.py
#coding:utf-8 import functools from cactus.utils.internal import getargspec from cactus.plugin import defaults class PluginManager(object): def __init__(self, site, loaders): self.site = site self.loaders = loaders self.reload() for plugin_method in defaults.DEFAULTS: ...
(self): plugins = [] for loader in self.loaders: plugins.extend(loader.load()) self.plugins = sorted(plugins, key=lambda plugin: plugin.ORDER) def call(self, method, *args, **kwargs): """ Call each plugin """ for plugin in self.plugins: ...
reload
identifier_name
manager.py
#coding:utf-8 import functools from cactus.utils.internal import getargspec from cactus.plugin import defaults class PluginManager(object): def __init__(self, site, loaders): self.site = site self.loaders = loaders self.reload() for plugin_method in defaults.DEFAULTS: ...
def reload(self): plugins = [] for loader in self.loaders: plugins.extend(loader.load()) self.plugins = sorted(plugins, key=lambda plugin: plugin.ORDER) def call(self, method, *args, **kwargs): """ Call each plugin """ for plugin in self.pl...
setattr(self, plugin_method, functools.partial(self.call, plugin_method))
conditional_block
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread nee...
} impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout( url: ServoUrl, node: &Node, id: PendingImageId, cache: Arc<dyn ImageCache>, ) { let document = document_from_node(node); let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, ...
{ self.doc.root().global() }
identifier_body
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread nee...
node: &Node, id: PendingImageId, cache: Arc<dyn ImageCache>, ) { let document = document_from_node(node); let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource), doc: Truste...
url: ServoUrl,
random_line_split
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread nee...
(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache .notify_pending_response(self.id, FetchResponseMs...
process_response
identifier_name
global-header.js
import React from 'react'
import Logo from '../components/logo' import utility from '@salesforce-ux/design-system/assets/icons/utility-sprite/svg/symbols.svg' const GlobalHeader = () => { return ( <header className='slds-global-header_container'> <div className='slds-global-header slds-grid slds-grid--align-spread'> <div c...
random_line_split
tls.rs
#![allow(unused_variables)] #![allow(unused_imports)] /// Note: Fred must be compiled with the `enable-tls` feature for this to work. extern crate fred; extern crate tokio_core; extern crate futures; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use tokio_core::reactor::Core; use fut...
let commands = client.on_connect().and_then(|client| { println!("Client connected."); client.select(0) }) .and_then(|client| { println!("Selected database."); client.info(None) }) .and_then(|(client, info)| { println!("Redis server info: {}", info); client.get("foo") }) .and_the...
{ let config = RedisConfig::Centralized { // Note: this must match the hostname tied to the cert host: "foo.bar.com".into(), port: 6379, key: Some("key".into()), // if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless necess...
identifier_body
tls.rs
#![allow(unused_variables)] #![allow(unused_imports)] /// Note: Fred must be compiled with the `enable-tls` feature for this to work. extern crate fred; extern crate tokio_core; extern crate futures; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use tokio_core::reactor::Core; use fut...
() { let config = RedisConfig::Centralized { // Note: this must match the hostname tied to the cert host: "foo.bar.com".into(), port: 6379, key: Some("key".into()), // if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless nec...
main
identifier_name
tls.rs
#![allow(unused_variables)] #![allow(unused_imports)] /// Note: Fred must be compiled with the `enable-tls` feature for this to work. extern crate fred; extern crate tokio_core; extern crate futures; use fred::RedisClient; use fred::owned::RedisClientOwned; use fred::types::*; use tokio_core::reactor::Core; use fut...
let (reason, client) = match core.run(connection.join(commands)) { Ok((r, c)) => (r, c), Err(e) => panic!("Connection closed abruptly: {}", e) }; println!("Connection closed gracefully with error: {:?}", reason); }
});
random_line_split
rijndael.py
elif Nk > 6 and i%Nk == 4 : temp = [ Sbox[byte] for byte in temp ] # SubWord(temp) w.append( [ w[i-Nk][byte]^temp[byte] for byte in range(4) ] ) return w Rcon = (0,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36, # note extra '0' !!! 0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e...
mp = temp[1:]+[temp[0]] # RotWord(temp) temp = [ Sbox[byte] for byte in temp ] temp[0] ^= Rcon[i/Nk]
conditional_block
rijndael.py
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c, 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9, 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6, 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, 0x70,0x3...
xColumns(a
identifier_name
rijndael.py
------------------------------------- def SubBytes(algInstance): for column in range(algInstance.Nb): for row in range(4): algInstance.state[column][row] = Sbox[algInstance.state[column][row]] def InvSubBytes(algInstance): for column in range(algInstance.Nb): for row in range(4): ...
" XOR the algorithm state with a block of key material """ for column in range(algInstance.Nb): for row in range(4): algInstance.state[column][row] ^= keyBlock[column][row] #
identifier_body
rijndael.py
0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88, 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c, 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9, 0x6c,0x...
algInstance.state[c][r] = tmp[c] def InvShiftRows(algInstance):
random_line_split
addressbook_send.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
pub mod addressbook_capnp { include!(concat!(env!("OUT_DIR"), "/addressbook_capnp.rs")); } use capnp::message::{Builder, HeapAllocator, TypedReader}; use std::sync::mpsc; use std::thread; pub mod addressbook { use addressbook_capnp::{address_book, person}; use capnp::message::{Builder, HeapAllocator, TypedR...
random_line_split
addressbook_send.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
() -> TypedReader<Builder<HeapAllocator>, address_book::Owned> { let mut message = Builder::new_default(); { let address_book = message.init_root::<address_book::Builder>(); let mut people = address_book.init_people(2); { let mut alice = people.rebor...
build_address_book
identifier_name
addressbook_send.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
{ let book = addressbook::build_address_book(); let (tx_book, rx_book) = mpsc::channel::<TypedReader<Builder<HeapAllocator>, addressbook_capnp::address_book::Owned>>(); let (tx_id, rx_id) = mpsc::channel::<u32>(); thread::spawn(move || { let addressbook_reader = rx_book.recv().unwrap(); ...
identifier_body
value.js
module.exports = { config: { type: 'radar', data: { labels: [0, 1, 2, 3, 4, 5], datasets: [ {
pointBorderColor: '#ff0000' }, { // option in element (fallback) data: [4, -5, -10, null, 10, 5] } ] }, options: { legend: false, title: false, elements: { line: { fill: false }, point: { borderColor: '#00ff00', borderWidth: 5, radius: 10 } ...
// option in dataset data: [0, 5, 10, null, -10, -5],
random_line_split
mpl_package.py
# Copyright (c) 2014 Mirantis, 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...
else: ui_file = self._ui full_path = os.path.join(self._source_directory, 'UI', ui_file) if not os.path.isfile(full_path): self._raw_ui_cache = None self._ui_cache = None return try: with open(full_p...
self._ui_cache = yaml.load(self._raw_ui_cache, self.yaml_loader)
conditional_block
mpl_package.py
# Copyright (c) 2014 Mirantis, 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...
with open(full_path) as stream: self._classes_cache[name] = yaml.load(stream, self.yaml_loader) except Exception as ex: trace = sys.exc_info()[2] msg = 'Unable to load class definition due to "{0}"'.format( str(ex)) raise exceptions...
try:
random_line_split
mpl_package.py
# Copyright (c) 2014 Mirantis, 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...
@property def classes(self): return tuple(self._classes.keys()) @property def ui(self): if not self._ui_cache: self._load_ui(True) return self._ui_cache @property def raw_ui(self): if not self._raw_ui_cache: self._load_ui(False) ...
super(MuranoPlPackage, self).__init__( source_directory, manifest, loader) self._classes = None self._ui = None self._ui_cache = None self._raw_ui_cache = None self._classes_cache = {}
identifier_body
mpl_package.py
# Copyright (c) 2014 Mirantis, 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...
(self): return tuple(self._classes.keys()) @property def ui(self): if not self._ui_cache: self._load_ui(True) return self._ui_cache @property def raw_ui(self): if not self._raw_ui_cache: self._load_ui(False) return self._raw_ui_cache ...
classes
identifier_name
logger.js
Object.defineProperty(exports, '__esModule', { value: true }); const path = require('path'); // explicitly set the config dir, otherwise if oxygen is globally installed it will use cwd let originalNodeCfgDir = process.env.NODE_CONFIG_DIR; process.env.NODE_CONFIG_DIR = path.resolve(__dirname, '../..', 'config'); ...
return loggerFactory.get(name); }; const LEVEL_INFO = 'info'; const LEVEL_DEBUG = 'debug'; const LEVEL_ERROR = 'error'; const LEVEL_WARN = 'warn'; const ISSUER_SYSTEM = 'system'; const ISSUER_USER = 'user'; exports.DEFAULT_ISSUER = ISSUER_USER; exports.ISSUERS = { SYSTEM: ISSUER_SYSTEM, USER: ISSUER_USER }...
exports.default = function logger(name) {
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-04 17:41 from __future__ import unicode_literals from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.util...
(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, seri...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-04 17:41 from __future__ import unicode_literals from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.util...
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', rel...
initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*-
from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth...
# Generated by Django 1.11.4 on 2017-09-04 17:41 from __future__ import unicode_literals
random_line_split
functions_11.js
var searchData= [ ['visualizespecificmeasurements',['visualizeSpecificMeasurements',['../meshMeasurements_8cpp.html#a019257c4a7eff9845aded56ffdc33768',1,'visualizeSpecificMeasurements(int argc, char **argv, InputParameters inputParams):&#160;meshMeasurements.cpp'],['../meshMeasurements_8h.html#a019257c4a7eff9845aded5...
];
random_line_split
htmllielement.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::codegen::Bindings::HTMLLIElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
{ htmlelement: HTMLElement, } impl HTMLLIElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLLIElement { HTMLLIElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)...
HTMLLIElement
identifier_name
htmllielement.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::codegen::Bindings::HTMLLIElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
Node::reflect_node(box element, document, HTMLLIElementBinding::Wrap) } }
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLLIElement> { let element = HTMLLIElement::new_inherited(localName, prefix, document);
random_line_split
htmllielement.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::codegen::Bindings::HTMLLIElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
}
{ let element = HTMLLIElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLLIElementBinding::Wrap) }
identifier_body
templating.py
# -*- coding: utf-8 -*- """ flask.templating ~~~~~~~~~~~~~~~~ Implements the bridge to Jinja2. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import posixpath from jinja2 import BaseLoader, Environment as BaseEnvironment, \ TemplateNotFound from .glo...
(BaseLoader): """A loader that looks for templates in the application and all the blueprint folders. """ def __init__(self, app): self.app = app def get_source(self, environment, template): for loader, local_name in self._iter_loaders(template): try: ret...
DispatchingJinjaLoader
identifier_name
templating.py
# -*- coding: utf-8 -*- """ flask.templating ~~~~~~~~~~~~~~~~ Implements the bridge to Jinja2. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import posixpath from jinja2 import BaseLoader, Environment as BaseEnvironment, \ TemplateNotFound from .glo...
# old style module based loaders in case we are dealing with a # blueprint that is an old style module try: module, local_name = posixpath.normpath(template).split('/', 1) blueprint = self.app.blueprints[module] if blueprint_is_module(blueprint): ...
yield loader, template
conditional_block
templating.py
# -*- coding: utf-8 -*- """ flask.templating ~~~~~~~~~~~~~~~~ Implements the bridge to Jinja2. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import posixpath from jinja2 import BaseLoader, Environment as BaseEnvironment, \ TemplateNotFound from .glo...
def _iter_loaders(self, template): loader = self.app.jinja_loader if loader is not None: yield loader, template # old style module based loaders in case we are dealing with a # blueprint that is an old style module try: module, local_name = posixpat...
for loader, local_name in self._iter_loaders(template): try: return loader.get_source(environment, local_name) except TemplateNotFound: pass raise TemplateNotFound(template)
identifier_body
trait-bounds-in-arc.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that a heterogeneous list of existential types can be put inside an Arc // and shared between tasks as long as all types fulfill Send. // ignore-pretty #![allow(unknown_features)] #![feature(box_syntax)] #![...
// 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 http://opensource.org/licenses/MIT>, at your
random_line_split
trait-bounds-in-arc.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self) -> bool { self.bark_decibels < 70 || self.tricks_known > 20 } } impl Pet for Goldfyshe { fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) } fn num_legs(&self) -> uint { 0 } fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 } } pub fn main() { let catte...
of_good_pedigree
identifier_name
trait-bounds-in-arc.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let (tx1, rx1) = channel(); let arc1 = arc.clone(); let _t1 = Thread::spawn(move|| { check_legs(arc1); tx1.send(()); }); let (tx2, rx2) = channel(); let arc2 = arc.clone(); let _t2 = Thread::spawn(move|| { check_names(arc2); tx2.send(()); }); let (tx3, rx3) = channel(); let arc3 = arc.cl...
{ let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_string() }; let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: "alan_turing".to_string(), }; let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: "albert_einstein".to_...
identifier_body
camerastation.py
""" .. module:: camerastation.py :platform: Unix, Windows :synopsis: Ulyxes - an open source project to drive total stations and publish observation results. GPL v2.0 license Copyright (C) 2010- Zoltan Siki <siki.zoltan@epito.bme.hu> .. moduleauthor:: Bence Turak <bence.turak@gmail.com> """ impor...
#!/usr/bin/env python
random_line_split
camerastation.py
#!/usr/bin/env python """ .. module:: camerastation.py :platform: Unix, Windows :synopsis: Ulyxes - an open source project to drive total stations and publish observation results. GPL v2.0 license Copyright (C) 2010- Zoltan Siki <siki.zoltan@epito.bme.hu> .. moduleauthor:: Bence Turak <bence.turak...
img[int(picCoord[1]),:] = [0,255,255] img[:,int(picCoord[0])] = [0,255,255] cv2.imwrite(photoName, img) angles = {} angles['hz'] = Angle(1/math.sin(ang['v'].GetAngle('RAD'))*(self._affinParams[0,1]*(picCoord[0] - round(self._affinParams[0,0])) + self._affinParams[0,2]*(picCoor...
print(photoName) file = open(photoName, 'w+b') print((int(self._affinParams[0,3]), int(self._affinParams[1,3]))) ang = self.GetAngles() self.TakePhoto(file, (int(self._affinParams[0,3]), int(self._affinParams[1,3]))) file.close() try: ...
conditional_block
camerastation.py
#!/usr/bin/env python """ .. module:: camerastation.py :platform: Unix, Windows :synopsis: Ulyxes - an open source project to drive total stations and publish observation results. GPL v2.0 license Copyright (C) 2010- Zoltan Siki <siki.zoltan@epito.bme.hu> .. moduleauthor:: Bence Turak <bence.turak...
def LoadAffinParams(self, file): """Load affin params to measure on pictures :param file: name of the params file (It have to be .npy file) """ self._affinParams = np.load(file) def PicMes(self, photoName, targetType = None): '''Measure angles between the target an...
'''CameraStation class for TotalStation combinated with camera :param name: name of instrument :param measureUnit: measure unit part of instrument :param measureIface: interface to physical unit :param writerUnit: store data, default None ''' #constants #FOCUS_CLOSER = 1 ...
identifier_body
camerastation.py
#!/usr/bin/env python """ .. module:: camerastation.py :platform: Unix, Windows :synopsis: Ulyxes - an open source project to drive total stations and publish observation results. GPL v2.0 license Copyright (C) 2010- Zoltan Siki <siki.zoltan@epito.bme.hu> .. moduleauthor:: Bence Turak <bence.turak...
(self, file): """Load affin params to measure on pictures :param file: name of the params file (It have to be .npy file) """ self._affinParams = np.load(file) def PicMes(self, photoName, targetType = None): '''Measure angles between the target and the optical axis ...
LoadAffinParams
identifier_name
check_txn_status.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use txn_types::{Key, Lock, TimeStamp, WriteType}; use crate::storage::{ mvcc::txn::MissingLockAction, mvcc::{ metrics::MVCC_CHECK_TXN_STATUS_COUNTER_VEC, ErrorInner, LockType, MvccTxn, ReleasedLock, Result, TxnCommitRecord, ...
<S: Snapshot>( txn: &mut MvccTxn<S>, primary_key: Key, mismatch_lock: Option<Lock>, action: MissingLockAction, resolving_pessimistic_lock: bool, ) -> Result<TxnStatus> { MVCC_CHECK_TXN_STATUS_COUNTER_VEC.get_commit_info.inc(); match txn .reader .get_txn_commit_record(&primar...
check_txn_status_missing_lock
identifier_name