function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def onErrRtnExecOrderAction(self, data, error): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnQuote(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onErrRtnQuoteAction(self, data, error): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnCFMMCTradingAccountToken(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onErrRtnLockInsert(self, data, error): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onErrRtnCombActionInsert(self, data, error): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRspQryParkedOrder(self, data, error, n, last): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRspQryTradingNotice(self, data, error, n, last): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRspQryBrokerTradingAlgos(self, data, error, n, last): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnFromBankToFutureByBank(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnRepealFromBankToFutureByBank(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnFromBankToFutureByFuture(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnRepealFromBankToFutureByFutureManual(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnQueryBankBalanceByFuture(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onErrRtnFutureToBankByFuture(self, data, error): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onErrRtnRepealFutureToBankByFutureManual(self, data, error): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnRepealFromBankToFutureByFuture(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRspFromBankToFutureByFuture(self, data, error, n, last): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRspQueryBankAccountMoneyByFuture(self, data, error, n, last): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def onRtnCancelAccountByBank(self, data): """""" pass
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def connect(self): """初始化连接""" if not self.connected: if not os.path.exists(self.temp_path): os.makedirs(self.temp_path) self.createFtdcTraderApi(self.temp_path) self.subscribePrivateTopic(0) self.subscribePublicTopic(0) self.registerFront(self.address) self.init() else: if self.require_authentication: self.authenticate() else: self.login()
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def authenticate(self): """申请验证""" if self.authenticated: req = { 'UserID': self.user_id, 'BrokerID': self.broker_id, 'AuthCode': self.auth_code, 'UserProductInfo': self.user_production_info, } self.req_id += 1 self.reqAuthenticate(req, self.req_id) else: self.login() return self.req_id
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def qryInstrument(self): self.ins_cache = {} self.req_id += 1 self.reqQryInstrument({}, self.req_id) return self.req_id
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def qryAccount(self): """查询账户""" self.req_id += 1 self.reqQryTradingAccount({}, self.req_id) return self.req_id
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def qryOrder(self): """订单查询""" self.order_cache = {} self.req_id += 1 req = { 'BrokerID': self.broker_id, 'InvestorID': self.user_id, } self.reqQryOrder(req, self.req_id) return self.req_id
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def cancelOrder(self, order): """撤单""" ins_dict = self.gateway.get_ins_dict(order.order_book_id) if ins_dict is None: return None self.req_id += 1 req = { 'InstrumentID': ins_dict.instrument_id, 'ExchangeID': ins_dict.exchange_id, 'OrderRef': str(order.order_id), 'FrontID': int(self.front_id), 'SessionID': int(self.session_id), 'ActionFlag': defineDict['THOST_FTDC_AF_Delete'], 'BrokerID': self.broker_id, 'InvestorID': self.user_id, } self.reqOrderAction(req, self.req_id) return self.req_id
ricequant/rqalpha-mod-vnpy
[ 295, 58, 295, 5, 1488780949 ]
def get(self): # Get the default Cloud Storage Bucket name and create a file name for # the object in Cloud Storage. bucket = app_identity.get_default_gcs_bucket_name() # Cloud Storage file names are in the format /bucket/object. filename = '/{}/blobreader_demo'.format(bucket) # Create a file in Google Cloud Storage and write something to it. with cloudstorage.open(filename, 'w') as filehandle: filehandle.write('abcde\n') # In order to read the contents of the file using the Blobstore API, # you must create a blob_key from the Cloud Storage file name. # Blobstore expects the filename to be in the format of: # /gs/bucket/object blobstore_filename = '/gs{}'.format(filename) blob_key = blobstore.create_gs_key(blobstore_filename) # [START gae_blobstore_reader] # Instantiate a BlobReader for a given Blobstore blob_key. blob_reader = blobstore.BlobReader(blob_key) # Instantiate a BlobReader for a given Blobstore blob_key, setting the # buffer size to 1 MB. blob_reader = blobstore.BlobReader(blob_key, buffer_size=1048576) # Instantiate a BlobReader for a given Blobstore blob_key, setting the # initial read position. blob_reader = blobstore.BlobReader(blob_key, position=0) # Read the entire value into memory. This may take a while depending # on the size of the value and the size of the read buffer, and is not # recommended for large values. blob_reader_data = blob_reader.read() # Write the contents to the response. self.response.headers['Content-Type'] = 'text/plain' self.response.write(blob_reader_data) # Set the read position back to 0, then read and write 3 bytes. blob_reader.seek(0) blob_reader_data = blob_reader.read(3) self.response.write(blob_reader_data) self.response.write('\n') # Set the read position back to 0, then read and write one line (up to # and including a '\n' character) at a time. blob_reader.seek(0) for line in blob_reader: self.response.write(line) # [END gae_blobstore_reader] # Delete the file from Google Cloud Storage using the blob_key. blobstore.delete(blob_key)
GoogleCloudPlatform/python-docs-samples
[ 6120, 5980, 6120, 108, 1430781973 ]
def spec_is_valid(json): schema = { "type": "object", "properties": { "schema": { "$ref": "#/pScheduler/Cardinal" }, "duration": { "$ref": "#/pScheduler/Duration" }, "host": { "$ref": "#/pScheduler/Host" }, "host-node": { "$ref": "#/pScheduler/URLHostPort" }, "interval": { "$ref": "#/pScheduler/Duration" }, "parting-comment": { "$ref": "#/pScheduler/String" }, "starting-comment": { "$ref": "#/pScheduler/String" }, }, "required": [ "duration" ] } return json_validate(json, schema, max_schema=MAX_SCHEMA)
perfsonar/pscheduler
[ 45, 31, 45, 115, 1452259533 ]
def skip_member(app, what, name, obj, skip, options): if name in ['to_dict', 'to_str']: return True return skip
anpolsky/phaxio-python
[ 6, 1, 6, 2, 1482893887 ]
def remove_module_docstring(app, what, name, obj, options, lines): if name.startswith("phaxio.swagger_client"): lines[:] = [x for x in lines if 'rtype' in x]
anpolsky/phaxio-python
[ 6, 1, 6, 2, 1482893887 ]
def GetConfig(user_config): """Load and return benchmark config. Args: user_config: user supplied configuration (flags and config file) Returns: loaded benchmark configuration """ config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) if FLAGS['ycsb_client_vms'].present: config['container_cluster']['nodepools']['mongodb']['vm_count'] = ( FLAGS.ycsb_client_vms) return config
GoogleCloudPlatform/PerfKitBenchmarker
[ 1785, 474, 1785, 248, 1405617806 ]
def _PrepareDeployment(benchmark_spec): """Deploys MongoDB Operator and instance on the cluster.""" cluster = benchmark_spec.container_cluster admin_password = ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(20)) storage_class = STORAGE_CLASS.value or cluster.GetDefaultStorageClass() cluster.ApplyManifest( 'container/kubernetes_mongodb/kubernetes_mongodb_crd.yaml') cluster.ApplyManifest( 'container/kubernetes_mongodb/kubernetes_mongodb_operator.yaml.j2', cpu_request=FLAGS.kubernetes_mongodb_cpu_request, cpu_limit=FLAGS.kubernetes_mongodb_cpu_limit, memory_request=FLAGS.kubernetes_mongodb_memory_request, memory_limit=FLAGS.kubernetes_mongodb_memory_limit, disk_size=FLAGS.kubernetes_mongodb_disk_size, storage_class=storage_class, admin_password=admin_password) time.sleep(60) benchmark_spec.container_cluster.WaitForResource('pod/mongodb-0', 'Ready') mongodb_cluster_ip = benchmark_spec.container_cluster.GetClusterIP( 'mongodb-service') benchmark_spec.mongodb_url = 'mongodb://ycsb:{password}@{ip_address}:27017/ycsb?authSource=ycsb'.format( password=admin_password, ip_address=mongodb_cluster_ip)
GoogleCloudPlatform/PerfKitBenchmarker
[ 1785, 474, 1785, 248, 1405617806 ]
def Run(benchmark_spec): return mongodb_ycsb_benchmark.Run(benchmark_spec)
GoogleCloudPlatform/PerfKitBenchmarker
[ 1785, 474, 1785, 248, 1405617806 ]
def __init__(self): self.driver_type = self.__class__.__name__ # Get credentials from conf files for CMDB pass
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def get_ci(self, ci): pass
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def get_ci(self, ci): print("Get from itop") return True
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def get_ci(self,ci): print("Get from redfish") import redfish
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def set_ci(self, ci): print "Push to Redfish" return True
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def set_ci(self, ci): # Determine ci type so we can do the proper action. pp = pprint.PrettyPrinter(indent=4) if ci.ci_type == "Manager": print("We are in Fakecmdb driver !") pp.pprint(ci.data) # Simply write a json file with ci.data content. with open("Fakecmdb.json", "w") as jsonfile: json.dump(ci.data, jsonfile, indent=4) jsonfile.close() # #=======================================================================
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def get_ci(self, ci): # Simulate a driver that will provide Manager data. # TODO a connect method must be implemented # Assuming the connection is ok. # Now create a copy of manager model from reference model. #ci.ci_type = "Manager" #ci.data = config.alexandria.model.get_model("Manager") # Update the structure with data # TODO : think to encapsulate to not edit ci.data directly. # This could be also a way to check source of truth. # If data provided by our driver is not the source of truth # then discard it. #ci.data["ManagerType"] = "BMC" #ci.data["Model"] = "Néné Manager" #ci.data["FirmwareVersion"] = "1.00" #if ci.data is config.alexandria.model.Manager: # print "identical" pp = pprint.PrettyPrinter(indent=4) pp.pprint(ci.ci_type)
uggla/alexandria
[ 7, 3, 7, 10, 1433322402 ]
def _generate_password(): chars = string.letters + string.digits length = 8 return ''.join([choice(chars) for _ in range(length)])
StratusLab/client
[ 2, 1, 2, 1, 1335119615 ]
def _cb_cmd(func, host, options): opts = ' '.join(options) cmd = '/opt/couchbase/bin/couchbase-cli %s -c %s:8091 %s' % (func, host, opts) return cmd
StratusLab/client
[ 2, 1, 2, 1, 1335119615 ]
def _installFrontend(self): self._installPackages()
StratusLab/client
[ 2, 1, 2, 1, 1335119615 ]
def _startServicesFrontend(self): self._restartService()
StratusLab/client
[ 2, 1, 2, 1, 1335119615 ]
def _configure(self): Util.printStep('(Re-)starting Couchbase') cmd = 'service %s restart' % self._serviceName self._executeExitOnError(cmd) time.sleep(5) Util.printStep('Set Couchbase data location') options = ['--node-init-data-path=/opt/couchbase/var/lib/couchbase/data'] cmd = CouchbaseServer._cb_cmd('node-init', self.frontendIp, options) self._executeExitOnError(cmd) Util.printStep('Create default Couchbase bucket') options = ['--bucket=default', '--bucket-type=couchbase', '--bucket-ramsize=400', '--bucket-replica=1'] cmd = CouchbaseServer._cb_cmd('bucket-create', self.frontendIp, options) self._executeExitOnError(cmd) Util.printStep('Initialize Couchbase admin account') options = ['--cluster-init-username=%s' % self._cb_cluster_username, '--cluster-init-password=%s' % self._cb_cluster_password] cmd = CouchbaseServer._cb_cmd('cluster-init', self.frontendIp, options) self._executeExitOnError(cmd) Util.printStep('Saving cluster password in %s' % self._cb_cluster_password_path) with open(self._cb_cluster_password_path, 'w') as f: f.write(self._cb_cluster_password + "\n") Util.printStep('Reducing read access to password file') os.chmod(self._cb_cluster_password_path, 0400)
StratusLab/client
[ 2, 1, 2, 1, 1335119615 ]
def residual_dropout(inputs, output, dropout, training): """out = inputs + dropout(output).""" if training and dropout: output = tf.nn.dropout(output, dropout) output += inputs return output
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, dimension, resolution, **kwargs): """Init. Args: dimension: int, 0 to shift down, 1 to shift right. resolution: list of 2 ints, [H, W]. **kwargs: """ super(Shift, self).__init__(**kwargs) self.dimension = dimension self.resolution = resolution
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, canvas_shape, num_batch_axes=1, dtype=tf.float32, **kwargs): super(Cache, self).__init__(trainable=False, **kwargs) self.canvas_shape = canvas_shape self.num_batch_axes = num_batch_axes self._dtype = dtype
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def reset(self): self.cache = tf.zeros(shape=self.cache.shape, dtype=self._dtype)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, axes, max_lengths=None, **kwargs): """Init. Args: axes: list of ints, axis over which to apply the positional embeddings. max_lengths: list of ints, maximum length over each axis. **kwargs: """ super(PositionEmbed, self).__init__(**kwargs) if not isinstance(axes, (list, tuple)): axes = [axes] self.axes = axes self.max_lengths = None if max_lengths: if not isinstance(max_lengths, (list, tuple)): max_lengths = [max_lengths] self.max_lengths = max_lengths
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def call(self, inputs): out = inputs for e in self.embeddings: out += e return out
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, filters, contract_axes=1, use_bias=False, activation=None, kernel_initializer='glorot_uniform', bias_initializer='zeros', **kwargs): super(DenseND, self).__init__(**kwargs) if isinstance(filters, int): filters = [filters] self.filters = tuple(filters) self.contract_axes = contract_axes self.use_bias = use_bias self.activation = tf.keras.activations.get(activation) self.bias_initializer = bias_initializer self._kernel_initializer = kernel_initializer # Behaviours differ when shape(weights) > 2. # see: https://github.com/tensorflow/tensorflow/blob/r2.1/tensorflow/python/ops/init_ops_v2.py#L733 pylint: disable=line-too-long if self._kernel_initializer == 'glorot_uniform_nd': self._kernel_initializer = self._glorot_uniform
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def _glorot_uniform(self, shape, dtype=tf.float32): """Glorot uniform initializer.""" fan_out = functools.reduce(operator.mul, self.filters) fan_in = functools.reduce(operator.mul, shape[:self.contract_axes]) scale = 1. / max(1., (fan_in + fan_out) / 2.) limit = math.sqrt(3.0 * scale) return tf.random.uniform(shape, -limit, limit, dtype)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def call(self, inputs): # Workaround lack of ellipsis support. # pyformat: disable num_batch_axes = self._num_batch_axes(inputs.shape) batch_str = 'abcdefghijklm'[:num_batch_axes] contract_str = 'ABCDEFGHIJKLM'[:len(self.contract_shape)] output_str = 'nopqrstuvwxyz'[:len(self.filters)] # pyformat: enable einsum_str = '{}{},{}{}->{}{}'.format(batch_str, contract_str, contract_str, output_str, batch_str, output_str) result = tf.einsum(einsum_str, inputs, self.w) if self.use_bias: result += self.b if self.activation is not None: result = self.activation(result) return result
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, lengths, num_heads, **kwargs): self.num_heads = num_heads self.lengths = lengths super(RelativeAttentionBiasND, self).__init__(**kwargs)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def call(self, inputs=None): tile, index, biases = 1, None, [] len_q = self.total_length for i, s in enumerate(self.lengths): # Relative attention in every dimension separately. if s > 1: new_bias = att_utils.relative_attn_bias( self.biases[i], self.num_heads, index) repeat = self.total_length // (tile * s) if repeat > 1: new_bias = tf.expand_dims(new_bias, -1) new_bias = tf.tile(new_bias, [tile, repeat, tile, repeat]) new_bias = tf.reshape(new_bias, [len_q, self.num_heads, self.total_length]) elif tile > 1: new_bias = tf.tile(new_bias, [tile, 1, tile]) tile *= s biases.append(new_bias) return tf.add_n(biases)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, spatial_average='learnable', sequence='sc', out_init='glorot_uniform', out_act='identity', **kwargs): super(ConditionalLayerNorm, self).__init__(**kwargs) self.spatial_average = spatial_average self.sequence = sequence self.out_init = out_init self.out_act = out_act self.out_act_func = base_utils.act_to_func(out_act) if self.spatial_average not in ['mean', 'learnable']: raise ValueError('Expected spatial average to be "mean" or "learnable" ,' 'got %s' % self.spatial_average) if self.sequence not in ['sc', 'cs']: raise ValueError('Expected sequence to be "sc" or "cs" ,' 'got %s' % self.sequence)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def spatial_projection(self, cond_inputs): if self.spatial_average == 'learnable': cond_inputs = self.spatial_weights * cond_inputs return tf.reduce_mean(cond_inputs, axis=(1, 2), keepdims=True)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, hidden_size, num_heads=1, num_channels_per_head=None, mask=None, kernel_initializer='glorot_uniform', nd_block_size=None, resolution=None, cond_init='glorot_uniform', cond_k=False, cond_q=False, cond_v=False, cond_scale=False, cond_act='identity', **kwargs): super(SelfAttentionND, self).__init__(**kwargs) if nd_block_size: nd_block_size = list(nd_block_size) num_channels_per_head = num_channels_per_head or hidden_size // num_heads self.num_filters = [num_heads, num_channels_per_head] self.kernel_initializer = kernel_initializer self.hidden_size = hidden_size self.cond_k = cond_k self.cond_q = cond_q self.cond_v = cond_v self.cond_scale = cond_scale self.cond_init = cond_init self.cond_act_func = base_utils.act_to_func(cond_act) self.project_cond_q, self.project_cond_k, self.project_cond_v = None, None, None self.cond_filters = self.num_filters if cond_scale: self.cond_filters = [num_heads, 2*num_channels_per_head] self.nd_block_size = nd_block_size self.resolution = resolution self.mask = mask self.num_channels_per_head = num_channels_per_head self.num_heads = num_heads self.hidden_size = hidden_size # By default, apply attention in third last dimension. # Last 2 dimensions are heads, channels. self.attention_dim_q = self.attention_dim_k = -3 # Self attention type. self.is_block_attention = True if self.nd_block_size else False
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def cond_shift_and_scale(self, inputs, cond_inputs, is_cond, layer): if not is_cond: return inputs cond_out = layer(cond_inputs) if self.cond_scale: scale, shift = tf.split(cond_out, num_or_size_splits=2, axis=-1) scale = self.cond_act_func(scale) shift = self.cond_act_func(shift) inputs *= scale inputs += shift else: inputs += cond_out return inputs
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def _apply_mask_and_bias(self, alphas): bias = self.relative_attention(None) if self.mask: bias += self._mask expand_bias_dims = -self.attention_dim_q - 3 if expand_bias_dims: bias = tf.reshape(bias, [-1] + [1] * expand_bias_dims + list(bias.shape[1:])) return alphas + bias
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def _weighted_sum(self, alphas, v, contract_dim_a=-3, contract_dim_v=-3): num_batch_axes = len(alphas.shape) + contract_dim_a pre_str = 'abcdefghij' [:num_batch_axes] in_dim_a = -contract_dim_a - 2 in_dim_v = -contract_dim_v - 2 in_str_a = 'zyxwv' [:in_dim_a] in_str_v = 'zyxwv' [:in_dim_v] einsum_str = '{}Q{}M,{}M{}C->{}Q{}C'.format(pre_str, in_str_a, pre_str, in_str_v, pre_str, in_str_a) return tf.einsum(einsum_str, alphas, v)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def _prepare_full_attention(self, x): return tf.reshape(x, [x.shape[0], -1, x.shape[-1]])
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, config, **kwargs): super(FactorizedAttention, self).__init__(**kwargs) self.config = config self.dropout = self.config.get('dropout', 0.0)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def parse_doc(xml_text): """ Parse xml document from string """ # The minidom lib has some issue with unicode in python2. # Encode the string into utf-8 first xml_text = xml_text.encode('utf-8') return minidom.parseString(xml_text)
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def find(root, tag, namespace=None): """ Get first node by tag and namespace under Node root. """ nodes = findall(root, tag, namespace=namespace) if nodes is not None and len(nodes) >= 1: return nodes[0] else: return None
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def findtext(root, tag, namespace=None): """ Get text of node by tag and namespace under Node root. """ node = find(root, tag, namespace=namespace) return gettext(node)
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def unpack(buf, offset, value_range): """ Unpack bytes into python values. """ result = 0 for i in value_range: result = (result << 8) | str_to_ord(buf[offset + i]) return result
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def unpack_big_endian(buf, offset, length): """ Unpack big endian bytes into python values. """ return unpack(buf, offset, list(range(0, length)))
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def hex_dump2(buf): """ Dump buf in formatted hex. """ return hex_dump3(buf, 0, len(buf))
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def is_printable(ch): """ Return True if character is displayable. """ return (is_in_range(ch, str_to_ord('A'), str_to_ord('Z')) or is_in_range(ch, str_to_ord('a'), str_to_ord('z')) or is_in_range(ch, str_to_ord('0'), str_to_ord('9')))
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def str_to_ord(a): """ Allows indexing into a string or an array of integers transparently. Generic utility function. """ if type(a) == type(b'') or type(a) == type(u''): a = ord(a) return a
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def int_to_ip4_addr(a): """ Build DHCP request string. """ return "%u.%u.%u.%u" % ((a >> 24) & 0xFF, (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a) & 0xFF)
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def set_ssh_config(config, name, val): found = False no_match = -1 match_start = no_match for i in range(0, len(config)): if config[i].startswith(name) and match_start == no_match: config[i] = "{0} {1}".format(name, val) found = True elif config[i].lower().startswith("match"): if config[i].lower().startswith("match all"): # outside match block match_start = no_match elif match_start == no_match: # inside match block match_start = i if not found: if match_start != no_match: i = match_start config.insert(i, "{0} {1}".format(name, val)) return config
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def replace_non_ascii(incoming, replace_char=''): outgoing = '' if incoming is not None: for c in incoming: if str_to_ord(c) > 128: outgoing += replace_char else: outgoing += c return outgoing
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def gen_password_hash(password, crypt_id, salt_len): collection = string.ascii_letters + string.digits salt = ''.join(random.choice(collection) for _ in range(salt_len)) salt = "${0}${1}".format(crypt_id, salt) if sys.version_info[0] == 2: # if python 2.*, encode to type 'str' to prevent Unicode Encode Error from crypt.crypt password = password.encode('utf-8') return crypt.crypt(password, salt)
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def compress(s): """ Compress a string, and return the base64 encoded result of the compression. This method returns a string instead of a byte array. It is expected that this method is called to compress smallish strings, not to compress the contents of a file. The output of this method is suitable for embedding in log statements. """ from azurelinuxagent.common.version import PY_VERSION_MAJOR if PY_VERSION_MAJOR > 2: return base64.b64encode(zlib.compress(bytes(s, 'utf-8'))).decode('utf-8') return base64.b64encode(zlib.compress(s))
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def b64decode(s): from azurelinuxagent.common.version import PY_VERSION_MAJOR if PY_VERSION_MAJOR > 2: return base64.b64decode(s).decode('utf-8') return base64.b64decode(s)
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def swap_hexstring(s, width=2): r = len(s) % width if r != 0: s = ('0' * (width - (len(s) % width))) + s return ''.join(reversed( re.findall( r'[a-f0-9]{{{0}}}'.format(width), s, re.IGNORECASE)))
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def is_str_none_or_whitespace(s): return s is None or len(s) == 0 or s.isspace()
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def hash_strings(string_list): """ Compute a cryptographic hash of a list of strings :param string_list: The strings to be hashed :return: The cryptographic hash (digest) of the strings in the order provided """ sha1_hash = hashlib.sha1() for item in string_list: sha1_hash.update(item.encode()) return sha1_hash.digest()
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def str_to_encoded_ustr(s, encoding='utf-8'): """ This function takes the string and converts it into the corresponding encoded ustr if its not already a ustr. The encoding is utf-8 by default if not specified. Note: ustr() is a unicode object for Py2 and a str object for Py3. :param s: The string to convert to ustr :param encoding: Encoding to use. Utf-8 by default :return: Returns the corresponding ustr string. Returns None if input is None. """ # TODO: Import at the top of the file instead of a local import (using local import here to avoid cyclic dependency) from azurelinuxagent.common.version import PY_VERSION_MAJOR if s is None or type(s) is ustr: # If its already a ustr/None then return as is return s if PY_VERSION_MAJOR > 2: try: # For py3+, str() is unicode by default if isinstance(s, bytes): # str.encode() returns bytes which should be decoded to get the str. return s.decode(encoding) else: # If its not encoded, just return the string return ustr(s) except Exception: # If some issues in decoding, just return the string return ustr(s) # For Py2, explicitly convert the string to unicode with the specified encoding return ustr(s, encoding=encoding)
Azure/WALinuxAgent
[ 495, 376, 495, 85, 1339008955 ]
def build_configuration_profile_response(data, filename): response = HttpResponse(data, content_type="application/x-apple-aspen-config") response['Content-Disposition'] = 'attachment; filename="{}.mobileconfig"'.format(filename) return response
zentralopensource/zentral
[ 671, 87, 671, 23, 1445349783 ]
def build_payload(payload_type, payload_display_name, suffix, content, payload_version=1, encapsulate_content=False): payload = {"PayloadUUID": generate_payload_uuid(), "PayloadType": payload_type, "PayloadDisplayName": payload_display_name, "PayloadIdentifier": get_payload_identifier(suffix), "PayloadVersion": payload_version} if encapsulate_content: # for scep, certificates TODO: what else ? payload["PayloadContent"] = content else: payload.update(content) return payload
zentralopensource/zentral
[ 671, 87, 671, 23, 1445349783 ]
def build_root_ca_payloads(): root_certificate = split_certificate_chain(settings["api"]["tls_fullchain"])[-1] return [ build_payload("com.apple.security.pem", "Zentral - root CA", "tls-root-ca-cert", root_certificate.encode("utf-8"), encapsulate_content=True) ]
zentralopensource/zentral
[ 671, 87, 671, 23, 1445349783 ]
def build_scep_payload(enrollment_session): subject = [[["CN", enrollment_session.get_common_name()]]] serial_number = enrollment_session.get_serial_number() if serial_number: subject.append([["2.5.4.5", serial_number]]) subject.append([["O", enrollment_session.get_organization()]]) return build_payload("com.apple.security.scep", enrollment_session.get_payload_name(), "scep", {"URL": "{}/scep".format(settings["api"]["tls_hostname"]), # TODO: hardcoded scep url "Subject": subject, "Challenge": enrollment_session.get_challenge(), "Keysize": 2048, "KeyType": "RSA", "Key Usage": 5, # 1 is signing, 4 is encryption, 5 is both signing and encryption }, encapsulate_content=True)
zentralopensource/zentral
[ 671, 87, 671, 23, 1445349783 ]
def build_ota_scep_configuration_profile(ota_enrollment_session): return build_profile(ota_enrollment_session.get_payload_name(), "scep", [build_scep_payload(ota_enrollment_session)])
zentralopensource/zentral
[ 671, 87, 671, 23, 1445349783 ]
def main(): pygion.print_once("Hello, Legion!")
StanfordLegion/legion
[ 578, 131, 578, 430, 1353113038 ]
def pRunoff(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas, FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2): result = zeros((NYrs, 12, 10)) rur_q_runoff = RurQRunoff(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0) p_conc = PConc(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMonth2, LastManureMonth2) for Y in range(NYrs): for i in range(12): for l in range(NRur): # += changed to = result[Y][i][l] = 0.1 * p_conc[i][l] * rur_q_runoff[Y][l][i] * Area[l] return result
WikiWatershed/gwlf-e
[ 5, 11, 5, 3, 1456423397 ]
def connect_db(self): rv = sqlite3.connect(self) #rv.row_factory = sqlite3.Row return rv
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def before_request(): """ establish connection upon request """ g.db = connect_db(UNIGRAM)
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def after_request(response): """ Close connection after request """
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def query_db_dict(query, args=(), one=False): """ Return results as dictionary """
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def query_db_row(query, args=(), one=False): """ Return results as rows """
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def return_terms(terms): """Gets a string of terms and returns them as a list, with some clean-up"""
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def query_factory(ngrams, lang, case_sens, corpus): """ Creates a sql query for each item in the object """
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def extract_info(term): """ Extracts information after colon, returns only ngram and dictionary of arguments"""
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def wildcard_search(ngrams, lang, case_sens, corpus): """ Returns the ten most common ngrams matching query """
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def query_planner(where,args): """ NB N-gram query planner """ letters = ['f','s','t'] letterCombination = '' for idx,val in enumerate(where): if '=' in where[idx]: letterCombination += letters[idx] elif 'LIKE' in where[idx] and len(args[idx]) > 1: letterCombination = ''.join(letters[:len(where)]) return '_' + letterCombination + 'f_' return '_' + letterCombination + 'f_'
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]
def combination_gen(ngrams): """ Returns combinations for truncated expressions """
NationalLibraryOfNorway/NB-N-gram
[ 18, 5, 18, 1, 1433156314 ]