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
JobStageExecutionLogs.tsx
import React from 'react'; import { template, isEmpty } from 'lodash'; import { Observable, Subject } from 'rxjs'; import { JobManifestPodLogs } from './JobManifestPodLogs'; import { IManifest } from 'core/domain/IManifest'; import { Application } from 'core/application'; import { IPodNameProvider } from '../PodNamePr...
() { const { account, location, deployedName } = this.props; Observable.from(ManifestReader.getManifest(account, location, deployedName)) .takeUntil(this.destroy$) .subscribe( (manifest) => this.setState({ manifest }), () => {}, ); } private renderExternalLink(link: string...
componentDidMount
identifier_name
JobStageExecutionLogs.tsx
import React from 'react'; import { template, isEmpty } from 'lodash'; import { Observable, Subject } from 'rxjs'; import { JobManifestPodLogs } from './JobManifestPodLogs'; import { IManifest } from 'core/domain/IManifest'; import { Application } from 'core/application'; import { IPodNameProvider } from '../PodNamePr...
return ( <> {location && ( <JobManifestPodLogs account={account} location={location} podNameProvider={podNameProvider} linkName="Console Output" /> )} </> ); } }
{ return ( <a target="_blank" href={this.renderExternalLink(externalLink, manifest)}> Console Output (External) </a> ); }
conditional_block
JobStageExecutionLogs.tsx
import React from 'react'; import { template, isEmpty } from 'lodash'; import { Observable, Subject } from 'rxjs'; import { JobManifestPodLogs } from './JobManifestPodLogs'; import { IManifest } from 'core/domain/IManifest'; import { Application } from 'core/application'; import { IPodNameProvider } from '../PodNamePr...
} }
random_line_split
feature_extraction.py
import librosa import numpy as np import help_functions def extract_mfccdd(fpath, n_mfcc=13, winsize=0.25, sampling_rate=16000): ''' Compute MFCCs, first and second derivatives :param fpath: the file path :param n_mfcc: the number of MFCC coefficients. Default = 13 coefficients :param winsize: the ...
#tonnetz_feature = np.reshape(tonnetz_feature,[l ,len(tonnetz_feature)]) zero_crossing_rate_feature = np.reshape(zero_crossing_rate_feature,[l ,len(zero_crossing_rate_feature)]) # Concatenate all features to a feature vector (length = 32) features = np.concatenate((chroma_feature,mfcc_feature,rmse_fea...
chroma_feature = librosa.feature.chroma_stft(fpath, sampling_rate) # 12 mfcc_feature = librosa.feature.mfcc(fpath, sampling_rate, n_mfcc=n_mfcc) # default = 20 rmse_feature = librosa.feature.rmse(fpath) # 1 spectral_centroid_feature = librosa.feature.spectral_centroid(fpath, sampling_rate) #1 spectral_b...
identifier_body
feature_extraction.py
import librosa import numpy as np import help_functions def
(fpath, n_mfcc=13, winsize=0.25, sampling_rate=16000): ''' Compute MFCCs, first and second derivatives :param fpath: the file path :param n_mfcc: the number of MFCC coefficients. Default = 13 coefficients :param winsize: the time length of the window for MFCC extraction. Default 0.25s (250ms) :p...
extract_mfccdd
identifier_name
feature_extraction.py
import librosa import numpy as np import help_functions def extract_mfccdd(fpath, n_mfcc=13, winsize=0.25, sampling_rate=16000): ''' Compute MFCCs, first and second derivatives :param fpath: the file path :param n_mfcc: the number of MFCC coefficients. Default = 13 coefficients :param winsize: the ...
return features
spectral_rolloff_feature, poly_features, zero_crossing_rate_feature),axis=1)
random_line_split
mark_set.rs
// Copyright 2021-2022 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
() { let mut bag = MarkSet::new(); let one = Rc::new(1i8); let three = Rc::new(3i64); assert!(!bag.contains_any::<i8>()); assert!(!bag.contains_any::<i64>()); assert_eq!(bag.push(one.clone()), None); assert!(bag.contains_any::<i8>()); assert!(!bag.contains...
confirms_push_with_contains_any
identifier_name
mark_set.rs
// Copyright 2021-2022 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
/// Return `true` if and only if a mark of type `T` was pushed into this [MarkSet] and has not /// yet been removed. pub fn contains_any<T: Any>(&self) -> bool { self.map.contains_key(&TypeId::of::<T>()) } /// Return a reference to the mark of type `T` that was last pushed into this [Mark...
{ self.get::<T>() == Some(m) }
identifier_body
mark_set.rs
// Copyright 2021-2022 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
fn pops_old_items_when_new_are_pushed() { let mut bag = MarkSet::new(); let one = Rc::new(1i8); let two = Rc::new(2i8); let three = Rc::new(3i64); let four = Rc::new(4i64); assert_eq!(bag.push(one.clone()), None); assert_eq!(bag.push(two.clone()), Some(one)); ...
#[test]
random_line_split
gyptest-dirname.py
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies simple rules when using an explicit build target of 'all'. """ import TestGyp import os import sys
test.run_gyp('actions.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('actions.gyp', chdir='relocate/src') expect = """\ no dir here hi c hello baz """ if test.format == 'xcode': chdir = 'relocate/src/subdir' else: chdir = 'relocate/src' test.run_built_executable('gencc_int_output', chdir=chd...
test = TestGyp.TestGyp(formats=['make', 'ninja', 'android', 'xcode', 'msvs'])
random_line_split
gyptest-dirname.py
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies simple rules when using an explicit build target of 'all'. """ import TestGyp import os import sys test = TestGyp.TestGyp(for...
test.run_built_executable('gencc_int_output', chdir=chdir, stdout=expect) if test.format == 'msvs': test.run_built_executable('gencc_int_output_external', chdir=chdir, stdout=expect) test.must_match('relocate/src/subdir/foo/bar/baz.dirname', os.path.join('foo', 'bar')) te...
chdir = 'relocate/src'
conditional_block
ChatWebAPIUtils.js
// ChatWebAPIUtils.js var ChatServerActionCreators = require('../actions/ChatServerActionCreators'); // !!! Please Note !!! // We are using localStorage as an example, but in a real-world scenario, this // would involve XMLHttpRequest, or perhaps a newer client-server protocol. // The function signatures below might ...
} };
}, 0);
random_line_split
p_roc.py
(cls): """Return coil config section.""" return "p_roc_coils" def configure_driver(self, config: DriverConfig, number: str, platform_settings: dict): """Create a P-ROC driver. Typically drivers are coils or flashers, but for the P-ROC this is also used for matrix-based ligh...
get_coil_config_section
identifier_name
p_roc.py
pinproc's decode() method # can provide the number. if self.machine_type == self.pinproc.MachineTypePDB: proc_num = self.pdbconfig.get_proc_coil_number(str(number)) if proc_num == -1: raise AssertionError("Driver {} cannot be controlled by the P-ROC. ".format(str...
def reset(self): """Reset aux port.""" commands = [self.platform.pinproc.aux_command_disable()] for _ in range(1, 255): commands += [self.platform.pinproc.aux_command_jump(0)] self.platform.run_proc_cmd_no_wait("aux_send_commands", 0, commands) def reserve_index(...
"""Initialise aux port.""" self.platform = platform self._commands = []
identifier_body
p_roc.py
pinproc's decode() method # can provide the number. if self.machine_type == self.pinproc.MachineTypePDB: proc_num = self.pdbconfig.get_proc_coil_number(str(number)) if proc_num == -1: raise AssertionError("Driver {} cannot be controlled by the P-ROC. ".format(str...
if event_type == self.pinproc.EventTypeDMDFrameDisplayed: # ignore this for now pass elif event_type in (self.pinproc.EventTypeSwitchClosedDebounced, self.pinproc.EventTypeSwitchClosedNondebounced): self.machine.swit...
for event in events: event_type = event['type'] event_value = event['value']
random_line_split
p_roc.py
pinproc's decode() method # can provide the number. if self.machine_type == self.pinproc.MachineTypePDB: proc_num = self.pdbconfig.get_proc_coil_number(str(number)) if proc_num == -1: raise AssertionError("Driver {} cannot be controlled by the P-ROC. ".format(str...
return self._configure_switch(config, proc_num) async def get_hw_switch_states(self) -> Dict[str, bool]: """Read in and set the initial switch state. The P-ROC uses the following values for hw switch states: 1 - closed (debounced) 2 - open (debounced) 3 - closed (n...
proc_num = self.pinproc.decode(self.machine_type, str(number))
conditional_block
decompile.py
field.get_descriptor() == 'Ljava/lang/String;': expr = literal_string(val) elif field.proto == 'B': expr = literal_hex_int(struct.unpack('<b', struct.pack("B", val))[0]) return { 'triple': triple, 'type': parse_descriptor(field.get_descriptor()), ...
(self, methanalysis): method = methanalysis.get_method() self.method = method self.start_block = next(methanalysis.get_basic_blocks().get(), None) self.cls_name = method.get_class_name() self.name = method.get_name() self.lparams = [] self.var_to_name = defaultdic...
__init__
identifier_name
decompile.py
logger.info('%s (%s, %s)', meth.get_method_idx(), self.name, meth.name) logger.info('') def get_methods(self): return self.methods def process_method(self, num, doAST=False): method = self.methods[num] if not isinstance(method, DvMethod): ...
cls = machine.get_class(cls_name) if cls is None: logger.error('%s not found.', cls_name) else: logger.info('======================') for i, method in enumerate(cls.get_methods()): logger.info('%d: %s', i, method.name) logger.info('========...
conditional_block
decompile.py
field.get_descriptor() == 'Ljava/lang/String;': expr = literal_string(val) elif field.proto == 'B': expr = literal_hex_int(struct.unpack('<b', struct.pack("B", val))[0]) return { 'triple': triple, 'type': parse_descriptor(field.get_descriptor()), ...
else: prototype = '%s class %s' self.access = util.get_access_class(access) self.prototype = prototype % (' '.join(self.access), self.name) self.interfaces = dvclass.get_interfaces() self.superclass = dvclass.get_superclassname() self.thisclass = dvclass.get...
name = dvclass.get_name() if name.find('/') > 0: pckg, name = name.rsplit('/', 1) else: pckg, name = '', name self.package = pckg[1:].replace('/', '.') self.name = name[:-1] self.vma = vma self.methods = dvclass.get_methods() self.fields =...
identifier_body
decompile.py
# 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 License for the specific language governing permissions and # limitations under the License. from...
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
jackal-mqtt.js
(function (angular) { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Gulp // Config angular .module('jackalMqtt.config', []) .value('jackalMq...
(chanel){ delete callbacks[chanel]; } function chanelMatch(chanel, destination) { var reg = '^'; destination += '/'; var levels = chanel.split('/'); for (var ind = 0; ind < levels.length; ind++){ var lvl = levels[ind]; if(lvl === '+'){ ...
deleteCallback
identifier_name
jackal-mqtt.js
(function (angular) { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Gulp // Config angular .module('jackalMqtt.config', []) .value('jackalMq...
else if(lvl === '#'){ reg += '(([a-z]|[0-9])|/)*'; }else{ reg += (lvl + '/'); } } reg += '$'; reg = new RegExp(reg); if(reg.test(destination)){ return true; } return false; } function onConne...
{ reg = '([a-z]|[0-9])+/'; }
conditional_block
jackal-mqtt.js
(function (angular) { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Gulp // Config angular .module('jackalMqtt.config', []) .value('jackalMq...
function MqttService ($rootScope, dataService) { var mqttc; var Paho = Paho; var callbacks = { }; function addCallback(chanel, callbackName, dataName) { callbacks[chanel] = [callbackName, dataName]; } function deleteCallback(chanel){ delete callbacks[chanel]; } func...
MqttService.$inject = ['$rootScope', 'dataService'];
random_line_split
jackal-mqtt.js
(function (angular) { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Gulp // Config angular .module('jackalMqtt.config', []) .value('jackalMq...
function publish(chanel, message, retained) { var payload = JSON.stringify(message); var mqttMessage = new Paho.MQTT.Message(payload); mqttMessage.retained = retained; mqttMessage.detinationName = chanel; mqttc.send(mqttMessage); } return { connect: conne...
{ mqttc.unsubscribe(chanel); deleteCallback(chanel); }
identifier_body
fill_config_dict_with_defaults.py
def fill_config_dict_with_defaults(config_dict: dict, defaults_dict: dict) -> dict:
config_dict[key] = config_value return config_dict
""" >>> fill_config_dict_with_defaults({a:2}, {b:3}) """ ## Substitute in default values from config_dict where missing from defaults_dict ## Works at multiple levels default_keys = list(defaults_dict.keys()) config_keys = list(config_dict.keys()) joint_keys = list(set(default_keys + config_...
identifier_body
fill_config_dict_with_defaults.py
def
(config_dict: dict, defaults_dict: dict) -> dict: """ >>> fill_config_dict_with_defaults({a:2}, {b:3}) """ ## Substitute in default values from config_dict where missing from defaults_dict ## Works at multiple levels default_keys = list(defaults_dict.keys()) config_keys = list(config_dict.ke...
fill_config_dict_with_defaults
identifier_name
fill_config_dict_with_defaults.py
def fill_config_dict_with_defaults(config_dict: dict, defaults_dict: dict) -> dict: """ >>> fill_config_dict_with_defaults({a:2}, {b:3}) """ ## Substitute in default values from config_dict where missing from defaults_dict ## Works at multiple levels
for key in joint_keys: config_value = config_dict.get(key, None) default_value = defaults_dict.get(key, None) if config_value is None: config_value = default_value elif default_value is None: continue elif type(config_value) is dict and type(default_v...
default_keys = list(defaults_dict.keys()) config_keys = list(config_dict.keys()) joint_keys = list(set(default_keys + config_keys))
random_line_split
fill_config_dict_with_defaults.py
def fill_config_dict_with_defaults(config_dict: dict, defaults_dict: dict) -> dict: """ >>> fill_config_dict_with_defaults({a:2}, {b:3}) """ ## Substitute in default values from config_dict where missing from defaults_dict ## Works at multiple levels default_keys = list(defaults_dict.keys()) ...
config_dict[key] = config_value return config_dict
config_value = fill_config_dict_with_defaults(config_value, default_value)
conditional_block
test_kernelspecs_api.py
# coding: utf-8 """Test the kernel specs webservice API.""" import errno import io import json import os import shutil pjoin = os.path.join import requests from IPython.kernel.kernelspec import NATIVE_KERNEL_NAME from IPython.html.utils import url_path_join from IPython.html.tests.launchnotebook import NotebookTest...
def is_default_kernelspec(s): return s['name'] == NATIVE_KERNEL_NAME and s['display_name'].startswith("IPython") assert any(is_sample_kernelspec(s) for s in specs.values()), specs assert any(is_default_kernelspec(s) for s in specs.values()), specs def test_get_kernelspec(self...
return s['name'] == 'sample' and s['display_name'] == 'Test kernel'
identifier_body
test_kernelspecs_api.py
# coding: utf-8 """Test the kernel specs webservice API.""" import errno import io import json import os import shutil pjoin = os.path.join import requests from IPython.kernel.kernelspec import NATIVE_KERNEL_NAME from IPython.html.utils import url_path_join from IPython.html.tests.launchnotebook import NotebookTest...
(object): """Wrapper for notebook API calls.""" def __init__(self, base_url): self.base_url = base_url def _req(self, verb, path, body=None): response = requests.request(verb, url_path_join(self.base_url, path), data=...
KernelSpecAPI
identifier_name
test_kernelspecs_api.py
# coding: utf-8 """Test the kernel specs webservice API.""" import errno import io import json import os import shutil pjoin = os.path.join import requests from IPython.kernel.kernelspec import NATIVE_KERNEL_NAME from IPython.html.utils import url_path_join from IPython.html.tests.launchnotebook import NotebookTest...
def is_default_kernelspec(s): return s['name'] == NATIVE_KERNEL_NAME and s['display_name'].startswith("IPython") assert any(is_sample_kernelspec(s) for s in specs.values()), specs assert any(is_default_kernelspec(s) for s in specs.values()), specs def test_get_kernelspec(self):...
random_line_split
test_kernelspecs_api.py
# coding: utf-8 """Test the kernel specs webservice API.""" import errno import io import json import os import shutil pjoin = os.path.join import requests from IPython.kernel.kernelspec import NATIVE_KERNEL_NAME from IPython.html.utils import url_path_join from IPython.html.tests.launchnotebook import NotebookTest...
with open(pjoin(bad_kernel_dir, 'kernel.json'), 'w') as f: f.write("garbage") model = self.ks_api.list().json() assert isinstance(model, dict) self.assertEqual(model['default'], NATIVE_KERNEL_NAME) specs = model['kernelspecs'] assert isinstance(specs, dict)...
raise
conditional_block
circle_network_0.py
# -*- coding: utf-8 -*- from __future__ import division import matplotlib.pyplot as plt import random import numpy as np class Player: def __init__(self, state, q): self.state = state self.gain_matrix = np.array([[q, 0], [0, 1-q]]) def action_distribution(self, N, m, players)...
def update_player(self): action = self.play() self.state = action def count_action(players): actions = [] for player in players: actions.append(player.state) return actions.count(1) num_0 = 15 num_1 = 1 N = num_0 + num_1 m = 2 #num_opponent q = 1/3 T = 200 ...
ction
conditional_block
circle_network_0.py
# -*- coding: utf-8 -*- from __future__ import division import matplotlib.pyplot as plt import random import numpy as np class Player: def __init__(self, state, q): self.state = state self.gain_matrix = np.array([[q, 0], [0, 1-q]]) def action_distribution(self, N, m, players)...
act_dist = self.action_distribution(N, m, players) payoff_vec = np.dot(self.gain_matrix, act_dist) if payoff_vec[0] > payoff_vec[1]: action = 0 elif payoff_vec[0] == payoff_vec[1]: action = random.choice...
adj_matrix = np.zeros((N, N)) #両隣と対戦する様にしました。 adj_matrix[N-1,0], adj_matrix[N-1,N-2] = 1, 1 for i in range(N-1): adj_matrix[i, i-1], adj_matrix[i, i+1] = 1, 1 current_state = [player.state for player in players] num_op_state_1 = np.dot(adj_matrix...
identifier_body
circle_network_0.py
# -*- coding: utf-8 -*- from __future__ import division import matplotlib.pyplot as plt import random import numpy as np class Player: def __init__(self, state, q): self.state = state self.gain_matrix = np.array([[q, 0], [0, 1-q]]) def action_distribution(self, N, m, players)...
action = 0 elif payoff_vec[0] == payoff_vec[1]: action = random.choice([0, 1]) else: action = 1 return action def update_player(self): action = self.play() self.state = action def count_action(players): actions = [] ...
payoff_vec = np.dot(self.gain_matrix, act_dist) if payoff_vec[0] > payoff_vec[1]:
random_line_split
circle_network_0.py
# -*- coding: utf-8 -*- from __future__ import division import matplotlib.pyplot as plt import random import numpy as np class Player: def __init__(self, state, q): self.state = state self.gain_matrix = np.array([[q, 0], [0, 1-q]]) def action_distribution(self, N, m, players)...
ion = self.play() self.state = action def count_action(players): actions = [] for player in players: actions.append(player.state) return actions.count(1) num_0 = 15 num_1 = 1 N = num_0 + num_1 m = 2 #num_opponent q = 1/3 T = 200 players = [Player(0, q) for i in range(num_0)]...
act
identifier_name
digest.rs
use std::io::{self, Write, Read}; use std::fmt::Display; use sha2::Sha256; use sha2::Digest as DigestTrait; pub struct Digest(Sha256); impl Digest { pub fn new() -> Digest { Digest(Sha256::new()) } pub fn result_str(&mut self) -> String { return self.0.result_str(); } pub fn inpu...
}; self.0.input(&buf[..len]); } Ok(()) } } impl Write for Digest { fn write(&mut self, chunk: &[u8]) -> io::Result<usize> { self.0.input(chunk); Ok(chunk.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
Err(e) => return Err(e),
random_line_split
digest.rs
use std::io::{self, Write, Read}; use std::fmt::Display; use sha2::Sha256; use sha2::Digest as DigestTrait; pub struct Digest(Sha256); impl Digest { pub fn new() -> Digest { Digest(Sha256::new()) } pub fn result_str(&mut self) -> String { return self.0.result_str(); } pub fn inpu...
fn flush(&mut self) -> io::Result<()> { Ok(()) } }
{ self.0.input(chunk); Ok(chunk.len()) }
identifier_body
digest.rs
use std::io::{self, Write, Read}; use std::fmt::Display; use sha2::Sha256; use sha2::Digest as DigestTrait; pub struct Digest(Sha256); impl Digest { pub fn new() -> Digest { Digest(Sha256::new()) } pub fn result_str(&mut self) -> String { return self.0.result_str(); } pub fn inpu...
} pub fn bool<K: AsRef<[u8]>>(&mut self, key: K, value: bool) { self.0.input(key.as_ref()); self.0.input(b"\0"); self.0.input(if value { b"0" } else { b"1" }); } pub fn sequence<K, I: IntoIterator>(&mut self, key: K, seq: I) where K: AsRef<[u8]>, I::Item: AsRef<[u8]>...
{ self.0.input(key.as_ref()); self.0.input(b"\0"); self.0.input(val.as_ref()); self.0.input(b"\0"); }
conditional_block
digest.rs
use std::io::{self, Write, Read}; use std::fmt::Display; use sha2::Sha256; use sha2::Digest as DigestTrait; pub struct
(Sha256); impl Digest { pub fn new() -> Digest { Digest(Sha256::new()) } pub fn result_str(&mut self) -> String { return self.0.result_str(); } pub fn input<V: AsRef<[u8]>>(&mut self, value: V) { self.0.input(value.as_ref()); } pub fn item<V: AsRef<[u8]>>(&mut self,...
Digest
identifier_name
lambda_function.py
# coding=utf-8 import time import json import boto3 from botocore.errorfactory import ClientError def lambda_handler(event, context): instance_id = event.get('instance_id') region_id = event.get('region_id', 'us-east-2') image_name = 'beam-automation-'+time.strftime("%Y-%m-%d-%H%M%S", time.gmtime()) ...
def stop_instance(instance_ids): return ec2.stop_instances(InstanceIds=instance_ids) def terminate_instance(instance_ids): return ec2.terminate_instances(InstanceIds=instance_ids)
for reservation in ec2.describe_instances()['Reservations']: for instance in reservation['Instances']: if instance['InstanceId'] in instance_ids: instance_ids.remove(instance['InstanceId']) return instance_ids
identifier_body
lambda_function.py
# coding=utf-8 import time import json import boto3 from botocore.errorfactory import ClientError def lambda_handler(event, context): instance_id = event.get('instance_id') region_id = event.get('region_id', 'us-east-2') image_name = 'beam-automation-'+time.strftime("%Y-%m-%d-%H%M%S", time.gmtime()) ...
def stop_instance(instance_ids): return ec2.stop_instances(InstanceIds=instance_ids) def terminate_instance(instance_ids): return ec2.terminate_instances(InstanceIds=instance_ids)
random_line_split
lambda_function.py
# coding=utf-8 import time import json import boto3 from botocore.errorfactory import ClientError def lambda_handler(event, context): instance_id = event.get('instance_id') region_id = event.get('region_id', 'us-east-2') image_name = 'beam-automation-'+time.strftime("%Y-%m-%d-%H%M%S", time.gmtime()) ...
(ec2, image_id): waiter = ec2.get_waiter('image_available') waiter.wait(Filters=[{'Name': 'state', 'Values': ['available']}], ImageIds=[image_id]) def update_lambda(image_ids): lm = boto3.client('lambda') en_var = lm.get_function_configuration(FunctionName='simulateBeam'...
wait4image
identifier_name
lambda_function.py
# coding=utf-8 import time import json import boto3 from botocore.errorfactory import ClientError def lambda_handler(event, context): instance_id = event.get('instance_id') region_id = event.get('region_id', 'us-east-2') image_name = 'beam-automation-'+time.strftime("%Y-%m-%d-%H%M%S", time.gmtime()) ...
return instance_ids def stop_instance(instance_ids): return ec2.stop_instances(InstanceIds=instance_ids) def terminate_instance(instance_ids): return ec2.terminate_instances(InstanceIds=instance_ids)
if instance['InstanceId'] in instance_ids: instance_ids.remove(instance['InstanceId'])
conditional_block
counter_style_rule.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/. */ // TODO(emilio): unify this, components/style/counter_style.rs, and // components/style/gecko/rules.rs #![allow(mi...
(&self) -> CounterStyleRule { self.deep_clone_from_gecko() } }
clone_conditionally_gecko_or_servo
identifier_name
counter_style_rule.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/. */ // TODO(emilio): unify this, components/style/counter_style.rs, and // components/style/gecko/rules.rs #![allow(mi...
#[cfg(feature = "gecko")] pub fn clone_conditionally_gecko_or_servo(&self) -> CounterStyleRule { self.deep_clone_from_gecko() } }
{ self.clone() }
identifier_body
counter_style_rule.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/. */ // TODO(emilio): unify this, components/style/counter_style.rs, and // components/style/gecko/rules.rs #![allow(mi...
pub use counter_style::CounterStyleRuleData as CounterStyleRule; #[cfg(feature = "gecko")] pub use gecko::rules::CounterStyleRule; impl CounterStyleRule { #[cfg(feature = "servo")] pub fn clone_conditionally_gecko_or_servo(&self) -> CounterStyleRule { self.clone() } #[cfg(feature = "gecko")] ...
#[cfg(feature = "servo")]
random_line_split
backend.py
"""Base material for signature backends.""" from django.urls import reverse class SignatureBackend(object): """Encapsulate signature workflow and integration with vendor backend. Here is a typical workflow: * :class:`~django_anysign.models.SignatureType` instance is created. It encapsulates the ba...
def get_signer_return_url(self, signer): """Return absolute URL where signer is redirected after signing. The URL must be **absolute** because it is typically used by external signature service: the signer uses external web UI to sign the document(s) and then the signature service...
"""Return URL name where signer signs document. Raise ``NotImplementedError`` in case the backend does not support "signer view" feature. Default implementation returns ``anysign:signer``. """ return '{ns}:signer'.format(ns=self.url_namespace)
identifier_body
backend.py
"""Base material for signature backends.""" from django.urls import reverse class
(object): """Encapsulate signature workflow and integration with vendor backend. Here is a typical workflow: * :class:`~django_anysign.models.SignatureType` instance is created. It encapsulates the backend type and its configuration. * A :class:`~django_anysign.models.Signature` instance is cre...
SignatureBackend
identifier_name
backend.py
"""Base material for signature backends.""" from django.urls import reverse class SignatureBackend(object): """Encapsulate signature workflow and integration with vendor backend. Here is a typical workflow: * :class:`~django_anysign.models.SignatureType` instance is created. It encapsulates the ba...
""" raise NotImplementedError() def get_signer_url(self, signer): """Return URL where signer signs document. Raise ``NotImplementedError`` in case the backend does not support "signer view" feature. Default implementation reverses :meth:`get_signer_url_name` with ...
Raise ``NotImplementedError`` if the backend does not support such a feature.
random_line_split
headerbar.rs
use gtk::{Inhibit}; use gtk::Orientation::{Vertical}; use gtk::prelude::*; use relm_derive::{Msg, widget}; use relm::{Component, Widget, init}; use self::HeaderMsg::*; use self::WinMsg::*; #[derive(Msg)] pub enum HeaderMsg { Add, Remove, } #[widget] impl Widget for Header { fn model() -> () { } ...
show_close_button: true, #[name="add_button"] gtk::Button { clicked => Add, label: "Add", }, #[name="remove_button"] gtk::Button { clicked => Remove, label: "Remove", }, ...
random_line_split
headerbar.rs
use gtk::{Inhibit}; use gtk::Orientation::{Vertical}; use gtk::prelude::*; use relm_derive::{Msg, widget}; use relm::{Component, Widget, init}; use self::HeaderMsg::*; use self::WinMsg::*; #[derive(Msg)] pub enum HeaderMsg { Add, Remove, } #[widget] impl Widget for Header { fn model() -> () { } ...
() -> Model { let header = init::<Header>(()).expect("Header"); Model { header } } fn update(&mut self, event: WinMsg) { match event { Quit => gtk::main_quit(), } } view! { #[name="window"] gtk::Window { title...
model
identifier_name
slice_pipe_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CommonModule, SlicePipe} from '@angular/common'; import {Component} from '@angular/core'; import {TestBed, wa...
{ data: any; } beforeEach(() => { TestBed.configureTestingModule({declarations: [TestComp], imports: [CommonModule]}); }); it('should work with mutable arrays', waitForAsync(() => { const fixture = TestBed.createComponent(TestComp); const mutable: number[...
TestComp
identifier_name
slice_pipe_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CommonModule, SlicePipe} from '@angular/common'; import {Component} from '@angular/core'; import {TestBed, wa...
}); it('should return an empty value if START is greater than END', () => { expect(pipe.transform(list, 4, 2)).toEqual([]); expect(pipe.transform(str, 4, 2)).toEqual(''); }); it('should return an empty value if START greater than input length', () => { expect(pipe.tr...
expect(pipe.transform(str, -4, -2)).toEqual('wx');
random_line_split
authentication.module.ts
import {AUTHENTICATION_INTERCEPTOR_SERVICE} from './authentication.interceptor.service'; import {AUTHENTICATION_INITIALIZER_SERVICE, AuthenticationInitializer} from './authentication.initializer.service'; import {REDIRECT_SERVICE} from './redirect.service'; import {AUTHENTICATION_SERVICE} from './authentication.service...
return config; } }; }) .run(function (schedulerFactory: SchedulerFactory, authenticationInitializer: AuthenticationInitializer) { if (SETTINGS.authEnabled) { // schedule deck to re-authenticate every 10 min. schedulerFactory.createScheduler(SETTINGS.authTtl || 600...
{ config.withCredentials = true; }
conditional_block
authentication.module.ts
import {AUTHENTICATION_INTERCEPTOR_SERVICE} from './authentication.interceptor.service'; import {AUTHENTICATION_INITIALIZER_SERVICE, AuthenticationInitializer} from './authentication.initializer.service'; import {REDIRECT_SERVICE} from './redirect.service'; import {AUTHENTICATION_SERVICE} from './authentication.service...
} return config; } }; }) .run(function (schedulerFactory: SchedulerFactory, authenticationInitializer: AuthenticationInitializer) { if (SETTINGS.authEnabled) { // schedule deck to re-authenticate every 10 min. schedulerFactory.createScheduler(SETTINGS.authT...
if (config.url.indexOf(SETTINGS.gateUrl) === 0) { config.withCredentials = true;
random_line_split
RadiusAxisView.js
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function (require) { 'use strict'; var zrUtil = require(...
(polar, radiusAxisModel, axisAngle) { return { position: [polar.cx, polar.cy], rotation: axisAngle / 180 * Math.PI, labelDirection: -1, tickDirection: -1, nameDirection: 1, labelRotation: radiusAxisModel.getModel('axisLabel').get('rotate'),...
layoutAxis
identifier_name
RadiusAxisView.js
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function (require) { 'use strict'; var zrUtil = require(...
}, /** * @private */ _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) { var splitAreaModel = radiusAxisModel.getModel('splitArea'); var areaStyleModel = splitAreaModel.getModel('areaStyle'); var areaColor...
{ this.group.add(graphic.mergePath(splitLines[i], { style: zrUtil.defaults({ stroke: lineColors[i % lineColors.length], fill: null }, lineStyleModel.getLineStyle()), silent: true }...
conditional_block
RadiusAxisView.js
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function (require) { 'use strict'; var zrUtil = require(...
});
{ return { position: [polar.cx, polar.cy], rotation: axisAngle / 180 * Math.PI, labelDirection: -1, tickDirection: -1, nameDirection: 1, labelRotation: radiusAxisModel.getModel('axisLabel').get('rotate'), // Over splitLine and s...
identifier_body
RadiusAxisView.js
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function (require) { 'use strict'; var zrUtil = require(...
r0: prevRadius, r: ticksCoords[i], startAngle: 0, endAngle: Math.PI * 2 }, silent: true })); prevRadius = ticksCoords[i]; } // ...
splitAreas[colorIndex].push(new graphic.Sector({ shape: { cx: polar.cx, cy: polar.cy,
random_line_split
lib.rs
#![crate_name="rustspec"] #![crate_type="dylib"] #![feature(plugin_registrar, rustc_private, collections, core, convert)] extern crate syntax; extern crate core; extern crate rustc; extern crate rustspec_assertions; pub use rustspec_assertions::{expect, eq, be_gt, be_ge, be_lt, be_le, contain, be_false, be_true, be_s...
let (name, block) = extract_test_node_data(parser); TestCaseNode::new(name, block, should_fail, should_be_ignored) } #[allow(unused_must_use)] fn parse_node(cx: &mut ExtCtxt, parser: &mut Parser) -> (Option<P<ast::Block>>, Vec<Box<TestNode + 'static>>) { let mut nodes: Vec<Box<TestNode>> = Vec::new(); ...
{ parser.bump(); let ident = parser.parse_ident().ok().unwrap(); let token_str = ident.as_str(); should_fail = token_str == "fails"; should_be_ignored = token_str == "ignores"; }
conditional_block
lib.rs
#![crate_name="rustspec"] #![crate_type="dylib"] #![feature(plugin_registrar, rustc_private, collections, core, convert)] extern crate syntax; extern crate core; extern crate rustc; extern crate rustspec_assertions; pub use rustspec_assertions::{expect, eq, be_gt, be_ge, be_lt, be_le, contain, be_false, be_true, be_s...
(token: syntax::parse::token::Token) -> bool { token == token::OpenDelim(token::Brace) || token == token::CloseDelim(token::Brace) || token == token::OpenDelim(token::Paren) || token == token::CloseDelim(token::Paren) || token == token::Comma || token == token::Semi } #[allow(unused...
is_skippable
identifier_name
lib.rs
#![crate_name="rustspec"] #![crate_type="dylib"] #![feature(plugin_registrar, rustc_private, collections, core, convert)] extern crate syntax; extern crate core; extern crate rustc; extern crate rustspec_assertions; pub use rustspec_assertions::{expect, eq, be_gt, be_ge, be_lt, be_le, contain, be_false, be_true, be_s...
#[allow(unused_must_use)] fn parse_node(cx: &mut ExtCtxt, parser: &mut Parser) -> (Option<P<ast::Block>>, Vec<Box<TestNode + 'static>>) { let mut nodes: Vec<Box<TestNode>> = Vec::new(); let mut before_block = None; while parser.token != token::Eof { if is_skippable(parser.token.clone()) { ...
{ let mut should_fail = false; let mut should_be_ignored = false; if parser.token == token::Dot { parser.bump(); let ident = parser.parse_ident().ok().unwrap(); let token_str = ident.as_str(); should_fail = token_str == "fails"; should_be_ignored = token_str == "igno...
identifier_body
lib.rs
#![crate_name="rustspec"] #![crate_type="dylib"] #![feature(plugin_registrar, rustc_private, collections, core, convert)] extern crate syntax; extern crate core; extern crate rustc; extern crate rustspec_assertions; pub use rustspec_assertions::{expect, eq, be_gt, be_ge, be_lt, be_le, contain, be_false, be_true, be_s...
let (name, _) = parser.parse_str().ok().unwrap(); parser.bump(); let block_tokens = parser.parse_block().ok().unwrap().to_tokens(cx); let mut block_parser = tts_to_parser(cx.parse_sess(), block_tokens, cx.cfg()); let (before, children) = parse_node(cx, &mut block_parser); let node = TestContext...
#[allow(unused_must_use)] pub fn macro_scenario(cx: &mut ExtCtxt, _: Span, tts: &[ast::TokenTree]) -> Box<MacResult + 'static> { let mut parser = cx.new_parser_from_tts(tts);
random_line_split
redis_semaphore.py
"""Redis Semaphore lock.""" import os import time SYSTEM_LOCK_ID = 'SYSTEM_LOCK' class Semaphore(object): """Semaphore lock using Redis ZSET.""" def __init__(self, redis, name, lock_id, timeout, max_locks=1): """ Semaphore lock. Semaphore logic is implemented in the lua/semaphore.l...
(self): """ Attempt to renew semaphore. Technically this doesn't know the difference between losing the lock but then successfully getting a new lock versus renewing your lock before the timeout. Both will return True. """ return self.acquire()
renew
identifier_name
redis_semaphore.py
"""Redis Semaphore lock.""" import os import time SYSTEM_LOCK_ID = 'SYSTEM_LOCK' class Semaphore(object): """Semaphore lock using Redis ZSET.""" def __init__(self, redis, name, lock_id, timeout, max_locks=1): """ Semaphore lock. Semaphore logic is implemented in the lua/semaphore.l...
args=[self.lock_id, self.max_locks, self.timeout, time.time()], ) # Convert Lua boolean returns to Python booleans acquired = True if acquired == 1 else False return acquired, locks def renew(self): """ Attempt to renew semaphore. Technically t...
""" acquired, locks = self._semaphore( keys=[self.name],
random_line_split
redis_semaphore.py
"""Redis Semaphore lock.""" import os import time SYSTEM_LOCK_ID = 'SYSTEM_LOCK' class Semaphore(object): """Semaphore lock using Redis ZSET.""" def __init__(self, redis, name, lock_id, timeout, max_locks=1): """ Semaphore lock. Semaphore logic is implemented in the lua/semaphore.l...
def renew(self): """ Attempt to renew semaphore. Technically this doesn't know the difference between losing the lock but then successfully getting a new lock versus renewing your lock before the timeout. Both will return True. """ return self.acquire()
""" Obtain a semaphore lock. Returns: Tuple that contains True/False if the lock was acquired and number of locks in semaphore. """ acquired, locks = self._semaphore( keys=[self.name], args=[self.lock_id, self.max_locks, self.timeout, time.time(...
identifier_body
settings.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. DJANGO_APPS = ['filebrowser'] NICE_NAME = "File Browser" REQUIRES_HADOOP ...
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
random_line_split
ftp_rmdir.py
#!/usr/bin/env python import ftplib import os.path import sys p_debug = False def ftp_rmdir(ftp, folder, remove_toplevel, dontremove):
def main(): p_host = sys.argv[1] p_user = sys.argv[2] p_pass = sys.argv[3] p_dir = sys.argv[4] if p_debug: print(p_host) print(p_user) print(p_pass) print(p_dir) ftp = ftplib.FTP(p_host) ftp.login(user=p_user, passwd=p_pass) # ftp_rmdir(ftp, p_dir, Fal...
for filename, attr in ftp.mlsd(folder): if attr['type'] == 'file' and filename not in dontremove: if p_debug: print( 'removing file [{0}] from folder [{1}]'.format(filename, folder)) ftp.delete(os.path.join(folder, filename)) if attr['type'] ==...
identifier_body
ftp_rmdir.py
#!/usr/bin/env python import ftplib import os.path import sys p_debug = False def
(ftp, folder, remove_toplevel, dontremove): for filename, attr in ftp.mlsd(folder): if attr['type'] == 'file' and filename not in dontremove: if p_debug: print( 'removing file [{0}] from folder [{1}]'.format(filename, folder)) ftp.delete(os.path.jo...
ftp_rmdir
identifier_name
ftp_rmdir.py
#!/usr/bin/env python import ftplib import os.path import sys p_debug = False def ftp_rmdir(ftp, folder, remove_toplevel, dontremove): for filename, attr in ftp.mlsd(folder): if attr['type'] == 'file' and filename not in dontremove: if p_debug: print( 'rem...
ftp = ftplib.FTP(p_host) ftp.login(user=p_user, passwd=p_pass) # ftp_rmdir(ftp, p_dir, False, set(['.ftpquota'])) ftp_rmdir(ftp, p_dir, False, set()) ftp.quit() if __name__ == '__main__': main()
print(p_host) print(p_user) print(p_pass) print(p_dir)
conditional_block
ftp_rmdir.py
#!/usr/bin/env python import ftplib import os.path import sys p_debug = False def ftp_rmdir(ftp, folder, remove_toplevel, dontremove): for filename, attr in ftp.mlsd(folder): if attr['type'] == 'file' and filename not in dontremove: if p_debug: print( 'rem...
print(p_dir) ftp = ftplib.FTP(p_host) ftp.login(user=p_user, passwd=p_pass) # ftp_rmdir(ftp, p_dir, False, set(['.ftpquota'])) ftp_rmdir(ftp, p_dir, False, set()) ftp.quit() if __name__ == '__main__': main()
print(p_pass)
random_line_split
rect2contour.js
/** * @file 矩形转换成轮廓 * @author mengke01(kekee000@gmail.com) */ /** * 矩形转换成轮廓 * * @param {number} x 左上角x * @param {number} y 左上角y * @param {number} width 宽度 * @param {number} height 高度 * @return {Array} 轮廓数组 */ export default function rect2contour(x, y, width, height) { x = +x; y = +y; width = +wi...
y: y + height, onCurve: true } ]; }
= +height; return [ { x, y, onCurve: true }, { x: x + width, y, onCurve: true }, { x: x + width, y: y + height, onCurve: true }, { x,
identifier_body
rect2contour.js
/** * @file 矩形转换成轮廓 * @author mengke01(kekee000@gmail.com) */ /** * 矩形转换成轮廓 * * @param {number} x 左上角x * @param {number} y 左上角y * @param {number} width 宽度 * @param {number} height 高度 * @return {Array} 轮廓数组 */ export default function rect2contour(x, y, width, height) { x = +x; y =
h = +width; height = +height; return [ { x, y, onCurve: true }, { x: x + width, y, onCurve: true }, { x: x + width, y: y + height, onCurve: true }, ...
+y; widt
identifier_name
rect2contour.js
/** * @file 矩形转换成轮廓 * @author mengke01(kekee000@gmail.com) */ /** * 矩形转换成轮廓 * * @param {number} x 左上角x * @param {number} y 左上角y * @param {number} width 宽度 * @param {number} height 高度 * @return {Array} 轮廓数组 */ export default function rect2contour(x, y, width, height) { x = +x; y = +y; width = +wi...
}, { x: x + width, y: y + height, onCurve: true }, { x, y: y + height, onCurve: true } ]; }
onCurve: true
random_line_split
signals.py
""" This creates Django signals that automatically update the elastic search Index When an item is created, a signal is thrown that runs the create / update index API of the Search Manager When an item is deleted, a signal is thrown that executes the delete index API of the Search Manager This way the Policy compass da...
@receiver(post_delete, sender=Metric) def remove_metric_link_from_datasets(sender, **kwargs): instance = kwargs['instance'] internal_api.remove_metric_link(instance.id)
instance = kwargs['instance'] search_index_delete('metric', instance.id)
identifier_body
signals.py
""" This creates Django signals that automatically update the elastic search Index When an item is created, a signal is thrown that runs the create / update index API of the Search Manager When an item is deleted, a signal is thrown that executes the delete index API of the Search Manager This way the Policy compass da...
(sender, **kwargs): instance = kwargs['instance'] internal_api.remove_metric_link(instance.id)
remove_metric_link_from_datasets
identifier_name
signals.py
""" This creates Django signals that automatically update the elastic search Index When an item is created, a signal is thrown that runs the create / update index API of the Search Manager When an item is deleted, a signal is thrown that executes the delete index API of the Search Manager This way the Policy compass da...
@receiver(post_delete, sender=Metric) def delete_document_on_search_service(sender, **kwargs): instance = kwargs['instance'] search_index_delete('metric', instance.id) @receiver(post_delete, sender=Metric) def remove_metric_link_from_datasets(sender, **kwargs): instance = kwargs['instance'] interna...
instance = kwargs['instance'] search_index_update('metric', instance.id)
conditional_block
signals.py
""" This creates Django signals that automatically update the elastic search Index When an item is created, a signal is thrown that runs the create / update index API of the Search Manager When an item is deleted, a signal is thrown that executes the delete index API of the Search Manager This way the Policy compass da...
search_index_update('metric', instance.id) @receiver(post_delete, sender=Metric) def delete_document_on_search_service(sender, **kwargs): instance = kwargs['instance'] search_index_delete('metric', instance.id) @receiver(post_delete, sender=Metric) def remove_metric_link_from_datasets(sender, **kwar...
if not kwargs.get('raw', False): instance = kwargs['instance']
random_line_split
App.tsx
import React from 'react'; import Container from 'react-bootstrap/Container'; import Nav from 'react-bootstrap/Nav'; import Navbar from 'react-bootstrap/Navbar'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import { MasterForm } from './MasterForm'; import './App.css'; // Multi-step wi...
</Navbar> </header> <main role="main"> <Container> <Row className="justify-content-md-center"> <Col> <MasterForm currentStep={1} /> </Col> </Row> </Container> </main> <footer className="text...
<Nav.Link href="http://app.paraesthesia.com">Other Apps</Nav.Link> </Nav> </Navbar.Collapse>
random_line_split
formatters.ts
/* Copyright 2016 Google 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.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
if (precision) { value = d3.round(value, d3_format_precision(value, precision)); } i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); } return d3_formatPrefixes[8 + i / 3]; ...
value *= -1; }
conditional_block
formatters.ts
/* Copyright 2016 Google 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.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
: number) { return value < 0 ? '-' : '+'; } // Formats a fractional value to a signed percentage. // // e.g., +2.14 => '+214%', -0.3 => '-30%' export function percentFormatter(fraction) { return `${getSign(fraction)}${Math.floor(Math.abs(fraction) * 100)}%`; } // Formats a fractional value to a unsigned perce...
n(value
identifier_name
formatters.ts
/* Copyright 2016 Google 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.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
ormats a fractional value to a signed percentage. // // e.g., +2.14 => '+214%', -0.3 => '-30%' export function percentFormatter(fraction) { return `${getSign(fraction)}${Math.floor(Math.abs(fraction) * 100)}%`; } // Formats a fractional value to a unsigned percentage. export function percentFormatterNoSign(fractio...
return value < 0 ? '-' : '+'; } // F
identifier_body
formatters.ts
/* Copyright 2016 Google 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.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
// Formats a value as a fractional megawatt-hour. export function fractionMWhFormatter(fractionMWh: number) { return `${fractionMWh.toFixed(2)} MWh`; } // The following modifies the default d3 large value formatting to use // 'business units' instead of SI units (i.e., 'Billions' instead of 'Giga-'). // // The code ...
export function percentFormatterNoSign(fraction) { return `${Math.floor(Math.abs(fraction) * 100)}%`; }
random_line_split
migration_context.py
# Copyright 2015 Red Hat 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 ag...
@base.remotable_classmethod def get_by_instance_uuid(cls, context, instance_uuid): db_extra = db.instance_extra_get_by_instance_uuid( context, instance_uuid, columns=['migration_context']) if not db_extra: raise exception.MigrationContextNotFound( in...
primitive = jsonutils.loads(db_obj) return cls.obj_from_primitive(primitive)
identifier_body
migration_context.py
# Copyright 2015 Red Hat 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 ag...
return cls.obj_from_db_obj(db_extra['migration_context'])
return None
conditional_block
migration_context.py
# Copyright 2015 Red Hat 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 ag...
(cls, db_obj): primitive = jsonutils.loads(db_obj) return cls.obj_from_primitive(primitive) @base.remotable_classmethod def get_by_instance_uuid(cls, context, instance_uuid): db_extra = db.instance_extra_get_by_instance_uuid( context, instance_uuid, columns=['migration_c...
obj_from_db_obj
identifier_name
migration_context.py
# Copyright 2015 Red Hat 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 ag...
return cls.obj_from_db_obj(db_extra['migration_context'])
random_line_split
my_elbow_angle_tcr_imgt.py
representation of the vectors used to determine the angle. NOTE: There is no automatic checking of the validity of limit_l and limit_h values or of the assignment of light and heavy chain IDs. If these are entered incorrectly or omitted, the reported angle will likely be incorrect. As always with these things, you...
T = cmd.get_object_matrix(mobile) R = numpy.identity(4) k=0 for i in range (0,4): for j in range (0,4): R[i][j] = T[k] k+=1 return R ################################################################################ #def elbow_angle(obj,light='L',heavy='H',...
# cmd.super(mobile,static)
random_line_split
my_elbow_angle_tcr_imgt.py
.6 http://numpy.scipy.org transformations.py, version 2012.01.01 by Christoph Gohlke www.lfd.uci.edu/~gohlke/code May also require an edit to transformations.py: Changes `1e-8` to `1e-7` in lines 357 & 363 to avoid a numerical error. com.py by Jason Vertree...
my_struc = cmd.load("1mhp_ch.pdb") my_elbow = elbow_angle(my_struc) print(my_elbow) return 0
identifier_body
my_elbow_angle_tcr_imgt.py
of the vectors used to determine the angle. NOTE: There is no automatic checking of the validity of limit_l and limit_h values or of the assignment of light and heavy chain IDs. If these are entered incorrectly or omitted, the reported angle will likely be incorrect. As always with these things, your mileage may v...
return R ################################################################################ #def elbow_angle(obj,light='L',heavy='H',limit_l=110,limit_h=113,draw=1): # alpha = light, beta = heavy # def elbow_angle(obj,light,heavy,limit_l=128,limit_h=127,draw=0): def elbow_angle(obj,heavy,light,limit_h="1001E...
R[i][j] = T[k] k+=1
conditional_block
my_elbow_angle_tcr_imgt.py
of the vectors used to determine the angle. NOTE: There is no automatic checking of the validity of limit_l and limit_h values or of the assignment of light and heavy chain IDs. If these are entered incorrectly or omitted, the reported angle will likely be incorrect. As always with these things, your mileage may v...
(mobile,static): ''' DESCRIPTION Aligns two objects (or selections), returns the transformation matrix, and resets the matrix of the mobile object. Uses CEAlign PyMOL function for alignment. ARGUMENTS mobile = string: selection describing the mobile object whose rotation matrix will be...
calc_super_matrix
identifier_name
spaceletmanager.js
/** * Spacelet Manager, 2013 Spaceify Inc. * SpaceletManager is a class for managing Spacelets and their processes. It launches spacelet processes, manages their quotas and access rights and terminates them when needed. * * @class SpaceletManager */ var fs = require("fs"); var fibrous = require("fibrous"); var Co...
try { database.open(Config.SPACEIFY_DATABASE_FILE); if(unique_name) // Build one application _applications = [database.sync.getApplication(unique_name)]; else // Build all applications _applications = database.sync.getApplication([Config.SPACELET], true); for(var i=0;...
self.build = fibrous( function(unique_name) { var application = null; var _applications = null;
random_line_split
spaceletmanager.js
/** * Spacelet Manager, 2013 Spaceify Inc. * SpaceletManager is a class for managing Spacelets and their processes. It launches spacelet processes, manages their quotas and access rights and terminates them when needed. * * @class SpaceletManager */ var fs = require("fs"); var fibrous = require("fibrous"); var Co...
try { var build_application = self.find(applications, "unique_name", unique_name); // Application by this unique name alredy build? // SHARE SPACELET OR START A NEW //if(!build_application || (build_application && !build_application.isShared())) // 'No' OR 'yes and is not shared' -> add the build applicat...
{ var self = this; var applications = Object(); var ordinal = 0; var database = new Database(); var isStarting = false; var delayedStart = []; self.start = function(unique_name, callback) { var application = null; if(isStarting) // Start one application at a time - retain call order delayedS...
identifier_body
spaceletmanager.js
/** * Spacelet Manager, 2013 Spaceify Inc. * SpaceletManager is a class for managing Spacelets and their processes. It launches spacelet processes, manages their quotas and access rights and terminates them when needed. * * @class SpaceletManager */ var fs = require("fs"); var fibrous = require("fibrous"); var Co...
() { var self = this; var applications = Object(); var ordinal = 0; var database = new Database(); var isStarting = false; var delayedStart = []; self.start = function(unique_name, callback) { var application = null; if(isStarting) // Start one application at a time - retain call order delay...
SpaceletManager
identifier_name
utils.py
#!/usr/bin/python2.7 from dragonnest.settings import STATIC_ROOT from skills.models import * from PIL import Image, ImageDraw, ImageFont import os _ASCIIMAP = [chr(n) for n in ([45] + range(48, 58) + range(65, 91) + [95] + range(97, 123))] _ALPHABET = dict(zip(range(64), _ASCIIMAP)) _ALPHABET_REVERSE = dict(zip(_ASCII...
else: img_path = os.path.join(STATIC_ROOT, 'img', 'lo', '%d.png'%img_path) # Crop the icon from the imagemap cropx = iconw*((slevel[n][0].icon%100)%10) cropy = iconw*((slevel[n][0].icon%100)/10) box = (cropx, cropy, cropx+iconw, cropy+iconw) skill_img = Imag...
img_path = os.path.join(STATIC_ROOT, 'img', 'hi', '%d.png'%img_path)
conditional_block
utils.py
#!/usr/bin/python2.7 from dragonnest.settings import STATIC_ROOT from skills.models import * from PIL import Image, ImageDraw, ImageFont import os _ASCIIMAP = [chr(n) for n in ([45] + range(48, 58) + range(65, 91) + [95] + range(97, 123))] _ALPHABET = dict(zip(range(64), _ASCIIMAP)) _ALPHABET_REVERSE = dict(zip(_ASCII...
if portrait: imgw = gridw imgh = len(jobs) * (gridh + titleh + gridm) - gridm img = Image.new('RGBA', (imgw, imgh), (0,0,0,0)) else: imgw = len(jobs) * (gridw + gridm) - gridm imgh = gridh + titleh img = Image.new('RGBA', (imgw, imgh), (0,0,0,0)) for n in ran...
num = unhash_(build_hash.split('.')[1]) assert num > 128 job = Job.objects.get(id=num>>7) level = num&127 jobs = [] while True: jobs.append(job) if not job.parent: break job = job.parent jobs.sort(key=lambda x: x.id) slevel = unhash_build(build_hash.split...
identifier_body
utils.py
#!/usr/bin/python2.7 from dragonnest.settings import STATIC_ROOT from skills.models import * from PIL import Image, ImageDraw, ImageFont import os _ASCIIMAP = [chr(n) for n in ([45] + range(48, 58) + range(65, 91) + [95] + range(97, 123))] _ALPHABET = dict(zip(range(64), _ASCIIMAP)) _ALPHABET_REVERSE = dict(zip(_ASCII...
bw, bh = (w+h)*scale, h*2*scale badge = Image.new('RGBA', (bw, bh), (0,0,0,0)) draw = ImageDraw.Draw(badge) draw.pieslice((0,0,bh,bh), 90, 270, fill='#999999') draw.pieslice((bw-bh,0,bw,bh), -90, 90, fill='#999999') draw.rectangle((bh/2,0,bw-bh/2,bh), fill='#999999') badge = badge.resize((w...
scale = 16
random_line_split
utils.py
#!/usr/bin/python2.7 from dragonnest.settings import STATIC_ROOT from skills.models import * from PIL import Image, ImageDraw, ImageFont import os _ASCIIMAP = [chr(n) for n in ([45] + range(48, 58) + range(65, 91) + [95] + range(97, 123))] _ALPHABET = dict(zip(range(64), _ASCIIMAP)) _ALPHABET_REVERSE = dict(zip(_ASCII...
(msg, font=_FONT): w, h = font.getsize(msg) m = h/2 scale = 16 bw, bh = (w+h)*scale, h*2*scale badge = Image.new('RGBA', (bw, bh), (0,0,0,0)) draw = ImageDraw.Draw(badge) draw.pieslice((0,0,bh,bh), 90, 270, fill='#999999') draw.pieslice((bw-bh,0,bw,bh), -90, 90, fill='#999999') ...
draw_text
identifier_name
config.js
System.config({ "baseURL": "/", "transpiler": "babel", "babelOptions": { "optional": [ "runtime" ] }, "paths": { "*": "*.js", "github:*": "jspm_packages/github/*.js", "npm:*": "jspm_packages/npm/*.js" }
"babel": "npm:babel-core@5.2.6", "babel-runtime": "npm:babel-runtime@5.2.6", "chai": "npm:chai@2.3.0", "core-js": "npm:core-js@0.9.6", "github:jspm/nodelibs-buffer@0.1.0": { "buffer": "npm:buffer@3.2.1" }, "github:jspm/nodelibs-process@0.1.1": { "process": "npm:process@0.10.1" ...
}); System.config({ "map": {
random_line_split