uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
fb8241eec3a6f0d806f0ad54
train
function
def _stream_disk(session, image_service_func, image_type, virtual_size, dev): offset = 0 if image_type == ImageType.DISK: offset = MBR_SIZE_BYTES _write_partition(session, virtual_size, dev) dev_path = utils.make_dev_path(dev) with utils.temporary_chown(dev_path): with open(dev...
def _stream_disk(session, image_service_func, image_type, virtual_size, dev):
offset = 0 if image_type == ImageType.DISK: offset = MBR_SIZE_BYTES _write_partition(session, virtual_size, dev) dev_path = utils.make_dev_path(dev) with utils.temporary_chown(dev_path): with open(dev_path, 'wb') as f: f.seek(offset) image_service_func(f...
_vm_ref(session): return session.call_xenapi("VM.get_by_uuid", get_this_vm_uuid(session)) def _get_partitions(dev): return nova.privsep.fs.list_partitions(utils.make_dev_path(dev)) def _stream_disk(session, image_service_func, image_type, virtual_size, dev):
64
64
96
18
46
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_stream_disk
_stream_disk
2,249
2,260
2,249
2,249
72913955148b44e7ef09eb5a722318d6102e38cc
bigcode/the-stack
train
15d4b2665e108b3a0389422f
train
function
def _add_memory_usage(session, vm_ref, diag_obj): total_mem = _vm_query_data_source(session, vm_ref, "memory") free_mem = _vm_query_data_source(session, vm_ref, "memory_internal_free") used_mem = None if total_mem is not None: # total_mem provided from XenServer is in Bytes. Converting it to MB....
def _add_memory_usage(session, vm_ref, diag_obj):
total_mem = _vm_query_data_source(session, vm_ref, "memory") free_mem = _vm_query_data_source(session, vm_ref, "memory_internal_free") used_mem = None if total_mem is not None: # total_mem provided from XenServer is in Bytes. Converting it to MB. total_mem /= units.Mi if free_me...
bd_rec['device']) write_bytes = _vm_query_data_source(session, vm_ref, "vbd_%s_write" % vbd_rec['device']) diag_obj.add_disk(read_bytes=read_bytes, write_bytes=write_bytes) def _add_memory_usage(session, vm_ref, diag_obj):
64
64
150
13
51
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_add_memory_usage
_add_memory_usage
1,765
1,778
1,765
1,765
1a0eff7cabc9ba11ca85ea774c5ceb1c9a3fd855
bigcode/the-stack
train
5d241238d4f04e3b825f6694
train
function
def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False): """Create a VDI record and returns its reference.""" vdi_ref = session.call_xenapi("VDI.create", {'name_label': name_label, 'name_description': disk_type, 'SR': sr_ref, ...
def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False):
"""Create a VDI record and returns its reference.""" vdi_ref = session.call_xenapi("VDI.create", {'name_label': name_label, 'name_description': disk_type, 'SR': sr_ref, 'virtual_size': str(virtual_size), 'type': 'User', 'sharable': False, 'rea...
di_ref in vdi_refs: try: destroy_vdi(session, vdi_ref) except exception.StorageError: LOG.debug("Ignoring error while destroying VDI: %s", vdi_ref) def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False):
69
69
230
25
44
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
create_vdi
create_vdi
448
468
448
449
8fdb82d5b883bd7f8d3714457451355309e2460a
bigcode/the-stack
train
b435766bd6cbcbea46255e2d
train
function
def resize_disk(session, instance, vdi_ref, flavor): size_gb = flavor.root_gb if size_gb == 0: reason = _("Can't resize a disk to 0 GB.") raise exception.ResizeError(reason=reason) sr_ref = safe_find_sr(session) clone_ref = _clone_vdi(session, vdi_ref) try: # Resize partiti...
def resize_disk(session, instance, vdi_ref, flavor):
size_gb = flavor.root_gb if size_gb == 0: reason = _("Can't resize a disk to 0 GB.") raise exception.ResizeError(reason=reason) sr_ref = safe_find_sr(session) clone_ref = _clone_vdi(session, vdi_ref) try: # Resize partition and filesystem down _auto_configure_disk(s...
"than flavor size of %(new_disk_size)d bytes.") msg = msg % {'vdi_ref': vdi_ref, 'virtual_size': virtual_size, 'new_disk_size': new_disk_size} LOG.debug(msg, instance=instance) raise exception.ResizeError(reason=msg) def resize_disk(session, instance, vdi_ref, flavo...
75
75
252
13
62
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
resize_disk
resize_disk
890
918
890
890
7ff483849c48399ae5874e3f211bd5b440e23820
bigcode/the-stack
train
69ed3bfc4781b2eabd7af9d4
train
function
def _make_uuid_stack(): # NOTE(sirp): The XenAPI plugins run under Python 2.4 # which does not have the `uuid` module. To work around this, # we generate the uuids here (under Python 2.6+) and # pass them as arguments return [uuidutils.generate_uuid() for i in range(MAX_VDI_CHAIN_SIZE)]
def _make_uuid_stack(): # NOTE(sirp): The XenAPI plugins run under Python 2.4 # which does not have the `uuid` module. To work around this, # we generate the uuids here (under Python 2.6+) and # pass them as arguments
return [uuidutils.generate_uuid() for i in range(MAX_VDI_CHAIN_SIZE)]
def _make_uuid_stack(): # NOTE(sirp): The XenAPI plugins run under Python 2.4 # which does not have the `uuid` module. To work around this, # we generate the uuids here (under Python 2.6+) and # pass them as arguments
66
64
84
66
0
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_make_uuid_stack
_make_uuid_stack
1,372
1,377
1,372
1,376
f432e64dc0fa2ace7357d35b1aed045acbf13d79
bigcode/the-stack
train
e550e9f5cd4549ffff76d1db
train
function
def _generate_disk(session, instance, vm_ref, userdevice, name_label, disk_type, size_mb, fs_type, fs_label=None): """Steps to programmatically generate a disk: 1. Create VDI of desired size 2. Attach VDI to Dom0 3. Create partition 3.a. If the partition type is supported by do...
def _generate_disk(session, instance, vm_ref, userdevice, name_label, disk_type, size_mb, fs_type, fs_label=None):
"""Steps to programmatically generate a disk: 1. Create VDI of desired size 2. Attach VDI to Dom0 3. Create partition 3.a. If the partition type is supported by dom0 (currently ext3, swap) then create it while the VDI is attached to dom0. 3.b. If the partition type is not supported by dom...
) nova.privsep.fs.create_partition( dev_path, 'primary', partition_start, partition_end, check_exit_code=not session.is_local_connection) partition_path = utils.make_dev_path(dev, partition=1) if session.is_local_connection: # Need to refresh the partitions nova.privsep.fs.c...
168
168
561
31
136
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_generate_disk
_generate_disk
1,001
1,057
1,001
1,002
cbc686140ba25c09ef597293c4350a1e5ae2df00
bigcode/the-stack
train
1ef66edef6e0016454dfa50d
train
function
def _should_retry_unplug_vbd(err): """Retry if failed with some specific errors. The retrable errors include: 1. DEVICE_DETACH_REJECTED For reasons which we don't understand, we're seeing the device still in use, even when all processes using the device should be dead. 2. INTERNAL_...
def _should_retry_unplug_vbd(err):
"""Retry if failed with some specific errors. The retrable errors include: 1. DEVICE_DETACH_REJECTED For reasons which we don't understand, we're seeing the device still in use, even when all processes using the device should be dead. 2. INTERNAL_ERROR Since XenServer 6.2, w...
instance): flavor = instance.get_flavor() mem = int(flavor.memory_mb) * units.Mi host_free_mem = int(session.call_xenapi("host.compute_free_memory", session.host_ref)) return host_free_mem >= mem def _should_retry_unplug_vbd(err):
64
64
210
10
53
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_should_retry_unplug_vbd
_should_retry_unplug_vbd
318
341
318
318
5ab7a58c02d927fa37635720c15ee97e3a01825a
bigcode/the-stack
train
5082487e619a8fb1d6ba8ebd
train
class
class InferredAssetGCSDataConnector(InferredAssetFilePathDataConnector): """ Extension of ConfiguredAssetFilePathDataConnector used to connect to GCS DataConnectors produce identifying information, called "batch_spec" that ExecutionEngines can use to get individual batches of data. They add flexibility...
class InferredAssetGCSDataConnector(InferredAssetFilePathDataConnector):
""" Extension of ConfiguredAssetFilePathDataConnector used to connect to GCS DataConnectors produce identifying information, called "batch_spec" that ExecutionEngines can use to get individual batches of data. They add flexibility in how to obtain data such as with time-based partitioning, splittin...
import logging import os from typing import List, Optional from great_expectations.core.batch import BatchDefinition from great_expectations.core.batch_spec import GCSBatchSpec, PathBatchSpec from great_expectations.datasource.data_connector.inferred_asset_file_path_data_connector import ( InferredAssetFilePathDat...
170
256
1,198
16
154
victorcouste/great_expectations
great_expectations/datasource/data_connector/inferred_asset_gcs_data_connector.py
Python
InferredAssetGCSDataConnector
InferredAssetGCSDataConnector
26
160
26
26
f7ec689cfcf634f88a5305828524a3888fac59f2
bigcode/the-stack
train
d14e8a1dc5c5b1c793c2775d
train
class
class TestUtils(unittest.TestCase): def test_hash_phone(self): digest = hash_phone("41791234567") expected = "ad398f4d7ebe63c6550a486cc6e07f9baa09bd9d8b3d8cb9d9be106d35a7fdbc" self.assertEqual(digest, expected) def test_hash_email(self): digest = hash_email("Test@Threema.ch") ...
class TestUtils(unittest.TestCase):
def test_hash_phone(self): digest = hash_phone("41791234567") expected = "ad398f4d7ebe63c6550a486cc6e07f9baa09bd9d8b3d8cb9d9be106d35a7fdbc" self.assertEqual(digest, expected) def test_hash_email(self): digest = hash_email("Test@Threema.ch") expected = "1ea093239cc5f0e1b6...
from thr.utils import hash_email, hash_phone import unittest class TestUtils(unittest.TestCase):
20
64
151
7
12
coffeemakr/python-thr
tests/test_utils.py
Python
TestUtils
TestUtils
5
14
5
5
22110772f82e7fcaaf3e3d1b815006aaa300084a
bigcode/the-stack
train
11a105219ebc47cbd1e38565
train
class
@dataclass class CriticalRegion: r""" Critical region is a polytope that defines a region in the uncertainty space with an associated optimal value, active set, lagrange multipliers and constraints .. math:: \begin{align} x(\theta) &= A\theta + b\\ \lambda(\theta) &...
@dataclass class CriticalRegion:
r""" Critical region is a polytope that defines a region in the uncertainty space with an associated optimal value, active set, lagrange multipliers and constraints .. math:: \begin{align} x(\theta) &= A\theta + b\\ \lambda(\theta) &= C\theta + d\\ \Thet...
from dataclasses import dataclass, field from typing import List, Union import numpy from .utils.chebyshev_ball import chebyshev_ball @dataclass class CriticalRegion:
39
221
737
7
31
TAMUparametric/PPOPT
src/ppopt/critical_region.py
Python
CriticalRegion
CriticalRegion
9
85
9
10
5e38b9fe026c1fc410142afae66391ab504aef41
bigcode/the-stack
train
058be8d9bec40aa57dd0b01c
train
function
def update_contact_cache(contacts): cached_contacts = frappe.cache().hget("contacts", frappe.session.user) or [] uncached_contacts = [d for d in contacts if d not in cached_contacts] cached_contacts.extend(uncached_contacts) frappe.cache().hset("contacts", frappe.session.user, cached_contacts)
def update_contact_cache(contacts):
cached_contacts = frappe.cache().hget("contacts", frappe.session.user) or [] uncached_contacts = [d for d in contacts if d not in cached_contacts] cached_contacts.extend(uncached_contacts) frappe.cache().hset("contacts", frappe.session.user, cached_contacts)
frappe.session.user) or [] if not contacts: return if not txt: return contacts match = [d for d in contacts if (d.value and ((d.value and txt in d.value) or (d.description and txt in d.description)))] return match def update_contact_cache(contacts):
64
64
68
7
56
marwand/frappe
frappe/email/__init__.py
Python
update_contact_cache
update_contact_cache
99
105
99
99
d23d6fb9b12a6dbfb4ba0d03059863bc4f7f0650
bigcode/the-stack
train
17b665c13f6ee67340a2d272
train
function
@frappe.whitelist() def get_contact_list(txt, page_length=20): """Returns contacts (from autosuggest)""" cached_contacts = get_cached_contacts(txt) if cached_contacts: return cached_contacts[:page_length] try: match_conditions = build_match_conditions('Contact') match_conditions = "and {0}".format(match_con...
@frappe.whitelist() def get_contact_list(txt, page_length=20):
"""Returns contacts (from autosuggest)""" cached_contacts = get_cached_contacts(txt) if cached_contacts: return cached_contacts[:page_length] try: match_conditions = build_match_conditions('Contact') match_conditions = "and {0}".format(match_conditions) if match_conditions else "" out = frappe.db.sql("""...
_literals import frappe from frappe.desk.reportview import build_match_conditions def sendmail_to_system_managers(subject, content): frappe.sendmail(recipients=get_system_managers(), subject=subject, content=content) @frappe.whitelist() def get_contact_list(txt, page_length=20):
64
64
203
17
47
marwand/frappe
frappe/email/__init__.py
Python
get_contact_list
get_contact_list
11
40
11
12
36683834f0608eb9fdc6dcffffe3393b6dcbf06f
bigcode/the-stack
train
7e09e0677df0de666908ec01
train
function
@frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_communication_doctype(doctype, txt, searchfield, start, page_len, filters): user_perms = frappe.utils.user.UserPermissions(frappe.session.user) user_perms.build_permissions() can_read = user_perms.can_read from frappe.modules import load_doctyp...
@frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_communication_doctype(doctype, txt, searchfield, start, page_len, filters):
user_perms = frappe.utils.user.UserPermissions(frappe.session.user) user_perms.build_permissions() can_read = user_perms.can_read from frappe.modules import load_doctype_module com_doctypes = [] if len(txt)<2: for name in ["Customer", "Supplier"]: try: module = load_doctype_module(name, suffix='_dashboa...
"Linked" where communication_type = "Communication" and name = %s""", (reference_doctype, reference_name, name)) @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_communication_doctype(doctype, txt, searchfield, start, page_len, filters):
70
70
236
37
33
marwand/frappe
frappe/email/__init__.py
Python
get_communication_doctype
get_communication_doctype
60
85
60
62
bd4cfb8c6ec67d800dcd3d0ec5bb63a57f902b77
bigcode/the-stack
train
bd2096b0cf4fce1858e3a476
train
function
@frappe.whitelist() def relink(name, reference_doctype=None, reference_name=None): frappe.db.sql("""update `tabCommunication` set reference_doctype = %s, reference_name = %s, status = "Linked" where communication_type = "Communication" and name = %s""", (reference_doctype, reference_name, name))
@frappe.whitelist() def relink(name, reference_doctype=None, reference_name=None):
frappe.db.sql("""update `tabCommunication` set reference_doctype = %s, reference_name = %s, status = "Linked" where communication_type = "Communication" and name = %s""", (reference_doctype, reference_name, name))
return frappe.db.sql_list("""select parent FROM `tabHas Role` WHERE role='System Manager' AND parent!='Administrator' AND parent IN (SELECT email FROM tabUser WHERE enabled=1)""") @frappe.whitelist() def relink(name, reference_doctype=None, reference_name=None):
64
64
89
20
44
marwand/frappe
frappe/email/__init__.py
Python
relink
relink
48
58
48
49
2702ceeda698caecae5a171e6a9728cfe50058cf
bigcode/the-stack
train
d055d54269a35d8f6a0728f7
train
function
def get_cached_contacts(txt): contacts = frappe.cache().hget("contacts", frappe.session.user) or [] if not contacts: return if not txt: return contacts match = [d for d in contacts if (d.value and ((d.value and txt in d.value) or (d.description and txt in d.description)))] return match
def get_cached_contacts(txt):
contacts = frappe.cache().hget("contacts", frappe.session.user) or [] if not contacts: return if not txt: return contacts match = [d for d in contacts if (d.value and ((d.value and txt in d.value) or (d.description and txt in d.description)))] return match
": 0, "istable": 0, "hide_toolbar": 0})] out = [] for dt in com_doctypes: if txt.lower().replace("%", "") in dt.lower() and dt in can_read: out.append([dt]) return out def get_cached_contacts(txt):
64
64
74
6
57
marwand/frappe
frappe/email/__init__.py
Python
get_cached_contacts
get_cached_contacts
87
97
87
87
e424cce63e93742cc135dc7061599144399bddac
bigcode/the-stack
train
8f6a2e2454e480e8562f6315
train
function
def get_system_managers(): return frappe.db.sql_list("""select parent FROM `tabHas Role` WHERE role='System Manager' AND parent!='Administrator' AND parent IN (SELECT email FROM tabUser WHERE enabled=1)""")
def get_system_managers():
return frappe.db.sql_list("""select parent FROM `tabHas Role` WHERE role='System Manager' AND parent!='Administrator' AND parent IN (SELECT email FROM tabUser WHERE enabled=1)""")
", { 'txt': '%' + txt + '%', 'condition': match_conditions, 'page_length': page_length }, as_dict=True) out = filter(None, out) except: raise update_contact_cache(out) return out def get_system_managers():
64
64
50
6
57
marwand/frappe
frappe/email/__init__.py
Python
get_system_managers
get_system_managers
42
46
42
42
6dbd660e7de61f4951f41fdf9650fec1c441ede7
bigcode/the-stack
train
b1ac13d1a5fbc459d73f5869
train
function
def sendmail_to_system_managers(subject, content): frappe.sendmail(recipients=get_system_managers(), subject=subject, content=content)
def sendmail_to_system_managers(subject, content):
frappe.sendmail(recipients=get_system_managers(), subject=subject, content=content)
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe.desk.reportview import build_match_conditions def sendmail_to_system_managers(subject, content):
61
64
31
11
49
marwand/frappe
frappe/email/__init__.py
Python
sendmail_to_system_managers
sendmail_to_system_managers
8
9
8
8
4cbcbe427ddf2ae1ff7cff7d402fa365a910d5b4
bigcode/the-stack
train
86915846dd2c76c689f68821
train
class
class UserChangesTest(ZulipTestCase): def test_update_api_key(self) -> None: user = self.example_user('hamlet') email = user.email self.login(email) old_api_keys = get_all_api_keys(user) # Ensure the old API keys are in the authentication cache, so # that the below l...
class UserChangesTest(ZulipTestCase):
def test_update_api_key(self) -> None: user = self.example_user('hamlet') email = user.email self.login(email) old_api_keys = get_all_api_keys(user) # Ensure the old API keys are in the authentication cache, so # that the below logic can test whether we have a cache-...
with self.settings(AVATAR_CHANGES_DISABLED=True): with get_test_image_file('img.png') as fp1: result = self.client_post("/json/users/me/avatar", {'f1': fp1}) self.assert_json_error(result, "Avatar changes are disabled in this organization.", 400) class UserChangesTest(ZulipTestC...
73
73
246
10
63
ray-kraesig/zulip
zerver/tests/test_settings.py
Python
UserChangesTest
UserChangesTest
392
417
392
392
9fab37572851bddbcbeb205f434de41c440511ab
bigcode/the-stack
train
740640ca380c68abc4595030
train
class
class ChangeSettingsTest(ZulipTestCase): def check_well_formed_change_settings_response(self, result: Dict[str, Any]) -> None: self.assertIn("full_name", result) # DEPRECATED, to be deleted after all uses of check_for_toggle_param # are converted into check_for_toggle_param_patch. def check_fo...
class ChangeSettingsTest(ZulipTestCase):
def check_well_formed_change_settings_response(self, result: Dict[str, Any]) -> None: self.assertIn("full_name", result) # DEPRECATED, to be deleted after all uses of check_for_toggle_param # are converted into check_for_toggle_param_patch. def check_for_toggle_param(self, pattern: str, param: ...
import mock import time import ujson from django.http import HttpResponse from django.test import override_settings from typing import Any, Dict, Union from zerver.lib.initial_password import initial_password from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import get_test_image_file fro...
129
256
3,264
10
118
ray-kraesig/zulip
zerver/tests/test_settings.py
Python
ChangeSettingsTest
ChangeSettingsTest
17
390
17
18
4e5f4305cfce5977a3ae8e2b91f8dc39d1d71c51
bigcode/the-stack
train
f60f4eb5cba5cda97820d762
train
function
def main(): parser = argparse.ArgumentParser() parser.add_argument('--ckpt', type=str) parser.add_argument('--val_path', type=str, default="../data/data40k/validation.txt") parser.add_argument('--data_dir', type=str, default="../data/data40k/") parser.add_argument('--samples_dir', type=str, default=...
def main():
parser = argparse.ArgumentParser() parser.add_argument('--ckpt', type=str) parser.add_argument('--val_path', type=str, default="../data/data40k/validation.txt") parser.add_argument('--data_dir', type=str, default="../data/data40k/") parser.add_argument('--samples_dir', type=str, default="/home/andre...
print(os.path.abspath(path)) import pandas as pd import numpy as np from PIL import Image from IPython.display import display import collections.abc as container_abcs from matplotlib import pyplot as plt from tqdm import tqdm, trange from glob import glob import argparse import torch from torchvision import transfor...
135
135
451
3
131
gxxu-ml/Natural-Disaster-Image-Generation-to-raise-Environmental-Awareness
src/eval_clip_score.py
Python
main
main
34
75
34
34
65f542e0c4158552ce046ed8e6338edcb0ebe8b6
bigcode/the-stack
train
b8fb862144f0c0eac593e8d0
train
function
@under_name_scope() def fastrcnn_predictions(boxes, scores): """ Generate final results from predictions of all proposals. Args: boxes: n#classx4 floatbox in float32 scores: nx#class Returns: boxes: Kx4 scores: K labels: K """ assert boxes.shape[1] == cf...
@under_name_scope() def fastrcnn_predictions(boxes, scores):
""" Generate final results from predictions of all proposals. Args: boxes: n#classx4 floatbox in float32 scores: nx#class Returns: boxes: Kx4 scores: K labels: K """ assert boxes.shape[1] == cfg.DATA.NUM_CLASS assert scores.shape[1] == cfg.DATA.NUM_C...
fg_inds), axis=1) num_zero = tf.reduce_sum(tf.cast(tf.equal(fg_label_pred, 0), tf.int64), name='num_zero') false_negative = tf.where( empty_fg, 0., tf.cast(tf.truediv(num_zero, num_fg), tf.float32), name='false_negative') fg_accuracy = tf.where( empty_fg, 0., tf.reduce_m...
217
217
724
15
202
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_predictions
fastrcnn_predictions
175
247
175
176
fee4de97072464c101d803ad7564f1cb2b5c0d6c
bigcode/the-stack
train
e27d052c950616c64bd1c6ee
train
class
class FastRCNNHead(object): """ A class to process & decode inputs/outputs of a fastrcnn classification+regression head. """ def __init__(self, proposals, box_logits, label_logits, gt_boxes, bbox_regression_weights): """ Args: proposals: BoxProposals box_logits: N...
class FastRCNNHead(object):
""" A class to process & decode inputs/outputs of a fastrcnn classification+regression head. """ def __init__(self, proposals, box_logits, label_logits, gt_boxes, bbox_regression_weights): """ Args: proposals: BoxProposals box_logits: Nx#classx4 or Nx1x4, the outp...
: boxes: Nx4 labels: N, each in [0, #class), the true label for each input box fg_inds_wrt_gt: #fg, each in [0, M) The last four arguments could be None when not training. """ for k, v in locals().items(): if k != 'self' and v is not None: ...
222
222
740
7
215
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
FastRCNNHead
FastRCNNHead
339
426
339
339
0a9147bcd9ae73f996a13ee9fc8c09bafcc4f433
bigcode/the-stack
train
7f322dcae11fa57d289582bf
train
function
@layer_register(log_shape=True) def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None): """ Args: feature (NCHW): num_classes(int): num_category + 1 num_convs (int): number of conv layers norm (str or None): either None or 'GN' Returns: 2D head feature """ ...
@layer_register(log_shape=True) def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None):
""" Args: feature (NCHW): num_classes(int): num_category + 1 num_convs (int): number of conv layers norm (str or None): either None or 'GN' Returns: 2D head feature """ assert norm in [None, 'GN'], norm l = feature with argscope(Conv2D, data_format='c...
_scaling_initializer() hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu) hidden = FullyConnected('fc7', hidden, dim, kernel_initializer=init, activation=tf.nn.relu) return hidden @layer_register(log_shape=True) def fastrcnn_Xconv1fc_head(feature, num_convs, norm=No...
79
79
266
25
53
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_Xconv1fc_head
fastrcnn_Xconv1fc_head
271
295
271
272
e430267e3084717660cc17b68f3de4fbce40fd90
bigcode/the-stack
train
8357c758052f7dd537640860
train
class
class BoxProposals(object): """ A structure to manage box proposals and their relations with ground truth. """ def __init__(self, boxes, labels=None, fg_inds_wrt_gt=None): """ Args: boxes: Nx4 labels: N, each in [0, #class), the true label for each input box ...
class BoxProposals(object):
""" A structure to manage box proposals and their relations with ground truth. """ def __init__(self, boxes, labels=None, fg_inds_wrt_gt=None): """ Args: boxes: Nx4 labels: N, each in [0, #class), the true label for each input box fg_inds_wrt_gt: #fg, ...
(*args, **kwargs): return fastrcnn_Xconv1fc_head(*args, num_convs=4, **kwargs) def fastrcnn_4conv1fc_gn_head(*args, **kwargs): return fastrcnn_Xconv1fc_head(*args, num_convs=4, norm='GN', **kwargs) class BoxProposals(object):
78
78
262
6
72
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
BoxProposals
BoxProposals
306
336
306
306
15a1735b06ce0b36fe884df72dbea9a241e7ca98
bigcode/the-stack
train
a0d2da55b8e9bc7fde748ce0
train
function
def fastrcnn_4conv1fc_head(*args, **kwargs): return fastrcnn_Xconv1fc_head(*args, num_convs=4, **kwargs)
def fastrcnn_4conv1fc_head(*args, **kwargs):
return fastrcnn_Xconv1fc_head(*args, num_convs=4, **kwargs)
('gn{}'.format(k), l) l = FullyConnected('fc', l, cfg.FPN.FRCNN_FC_HEAD_DIM, kernel_initializer=tf.variance_scaling_initializer(), activation=tf.nn.relu) return l def fastrcnn_4conv1fc_head(*args, **kwargs):
64
64
38
16
47
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_4conv1fc_head
fastrcnn_4conv1fc_head
298
299
298
298
0c63eaa622ce86cfa14bb60aeb9553d06e5639cb
bigcode/the-stack
train
cc5a503552f27b6737c844db
train
function
@under_name_scope() def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits): """ Args: labels: n, label_logits: nxC fg_boxes: nfgx4, encoded fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic Returns: label_loss, box_loss """ label_loss = tf.nn.sp...
@under_name_scope() def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits):
""" Args: labels: n, label_logits: nxC fg_boxes: nfgx4, encoded fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic Returns: label_loss, box_loss """ label_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=labels, logits=label_logits) ...
reg_logits: N x num_classx4 or Nx2x4 if class agnostic """ classification = FullyConnected( 'class', feature, num_classes, kernel_initializer=tf.random_normal_initializer(stddev=0.01)) num_classes_for_box = 1 if class_agnostic_regression else num_classes box_regression = FullyCon...
163
163
545
22
140
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_losses
fastrcnn_losses
127
172
127
128
1bf60e66e0d8920cdde41f2f266b0955ed145965
bigcode/the-stack
train
221a3cf6e792fa2eb0cc9b7e
train
function
@under_name_scope() def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels): """ Sample some boxes from all proposals for training. #fg is guaranteed to be > 0, because ground truth boxes will be added as proposals. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox ...
@under_name_scope() def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels):
""" Sample some boxes from all proposals for training. #fg is guaranteed to be > 0, because ground truth boxes will be added as proposals. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox gt_labels: m, int32 Returns: A BoxProposals instance. ...
@under_name_scope() def proposal_metrics(iou): """ Add summaries for RPN proposals. Args: iou: nxm, #proposal x #gt """ # find best roi for each gt, for summary only best_iou = tf.reduce_max(iou, axis=0) mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt') summaries ...
198
198
660
20
178
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
sample_fast_rcnn_targets
sample_fast_rcnn_targets
41
101
41
42
3bc858522873be769c4c1f51e352a7c8cf240d95
bigcode/the-stack
train
3120079495ec27c5d5bc5a6a
train
function
def fastrcnn_4conv1fc_gn_head(*args, **kwargs): return fastrcnn_Xconv1fc_head(*args, num_convs=4, norm='GN', **kwargs)
def fastrcnn_4conv1fc_gn_head(*args, **kwargs):
return fastrcnn_Xconv1fc_head(*args, num_convs=4, norm='GN', **kwargs)
=tf.nn.relu) return l def fastrcnn_4conv1fc_head(*args, **kwargs): return fastrcnn_Xconv1fc_head(*args, num_convs=4, **kwargs) def fastrcnn_4conv1fc_gn_head(*args, **kwargs):
64
64
44
18
46
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_4conv1fc_gn_head
fastrcnn_4conv1fc_gn_head
302
303
302
302
8b46cee8d89b2153594ac0075dfcc4d5bab7ab2b
bigcode/the-stack
train
a0cae60533a345b345ea2aa5
train
function
@under_name_scope() def proposal_metrics(iou): """ Add summaries for RPN proposals. Args: iou: nxm, #proposal x #gt """ # find best roi for each gt, for summary only best_iou = tf.reduce_max(iou, axis=0) mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt') summaries ...
@under_name_scope() def proposal_metrics(iou):
""" Add summaries for RPN proposals. Args: iou: nxm, #proposal x #gt """ # find best roi for each gt, for summary only best_iou = tf.reduce_max(iou, axis=0) mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt') summaries = [mean_best_iou] with tf.device('/cpu:0'):...
add_moving_summary from tensorpack.utils.argtools import memoized_method from basemodel import GroupNorm from config import config as cfg from model_box import decode_bbox_target, encode_bbox_target from utils.box_ops import pairwise_iou @under_name_scope() def proposal_metrics(iou):
64
64
178
11
52
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
proposal_metrics
proposal_metrics
19
38
19
20
f620a3890f32098ec85476d15707b6be42f1a083
bigcode/the-stack
train
e302f4284d0788401cb69e07
train
function
@layer_register(log_shape=True) def fastrcnn_2fc_head(feature): """ Args: feature (any shape): Returns: 2D head feature """ dim = cfg.FPN.FRCNN_FC_HEAD_DIM init = tf.variance_scaling_initializer() hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activati...
@layer_register(log_shape=True) def fastrcnn_2fc_head(feature):
""" Args: feature (any shape): Returns: 2D head feature """ dim = cfg.FPN.FRCNN_FC_HEAD_DIM init = tf.variance_scaling_initializer() hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu) hidden = FullyConnected('fc7', hidden, dim, k...
=1, name='all_ids') final_boxes = tf.gather_nd(boxes, final_ids, name='boxes') return final_boxes, final_scores, final_labels """ FastRCNN heads for FPN: """ @layer_register(log_shape=True) def fastrcnn_2fc_head(feature):
64
64
114
17
47
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_2fc_head
fastrcnn_2fc_head
255
268
255
256
fdb551a88213ac8003c39f284d24e52b75372da4
bigcode/the-stack
train
12e9a0d06acbd74fec1d2c6c
train
function
@layer_register(log_shape=True) def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False): """ Args: feature (any shape): num_classes(int): num_category + 1 class_agnostic_regression (bool): if True, regression to N x 1 x 4 Returns: cls_logits: N x num_clas...
@layer_register(log_shape=True) def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
""" Args: feature (any shape): num_classes(int): num_category + 1 class_agnostic_regression (bool): if True, regression to N x 1 x 4 Returns: cls_logits: N x num_class classification logits reg_logits: N x num_classx4 or Nx2x4 if class agnostic """ classifica...
Proposals( tf.stop_gradient(ret_boxes, name='sampled_proposal_boxes'), tf.stop_gradient(ret_labels, name='sampled_labels'), tf.stop_gradient(fg_inds_wrt_gt)) @layer_register(log_shape=True) def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
67
67
225
25
42
awesome-archive/tensorpack
examples/FasterRCNN/model_frcnn.py
Python
fastrcnn_outputs
fastrcnn_outputs
104
124
104
105
5915a9e35a76fa304974f2760cbba2a969e5cb3f
bigcode/the-stack
train
328d31b8e976937ebceff0ac
train
class
class External_World(object): def __init__(self,tasktype): if tasktype is 'mnist': # pdb.set_trace() dir_path = os.path.dirname(os.path.abspath(__file__)) path = dir_path+os.sep+"mnist.pkl.gz" # DOWNLOAD MNIST DATASET if not os.path.isfi...
class External_World(object):
def __init__(self,tasktype): if tasktype is 'mnist': # pdb.set_trace() dir_path = os.path.dirname(os.path.abspath(__file__)) path = dir_path+os.sep+"mnist.pkl.gz" # DOWNLOAD MNIST DATASET if not os.path.isfile(path): impor...
import pickle as cpickle import gzip import numpy as np import os import theano import theano.tensor as T import theano.tensor.extra_ops import scipy.io as sio import pdb class External_World(object):
50
250
835
6
43
lcx1997213/sbp
SBP_ANN_RBM/external_world.py
Python
External_World
External_World
10
76
10
11
19fd9738de63dd8e4a11de306b4827f297668d2e
bigcode/the-stack
train
bdb3f1c4bcb1efe1ca959fdc
train
class
class Reactor(salt.utils.process.SignalHandlingMultiprocessingProcess, salt.state.Compiler): ''' Read in the reactor configuration variable and compare it to events processed on the master. The reactor has the capability to execute pre-programmed executions as reactions to events ''' def __i...
class Reactor(salt.utils.process.SignalHandlingMultiprocessingProcess, salt.state.Compiler):
''' Read in the reactor configuration variable and compare it to events processed on the master. The reactor has the capability to execute pre-programmed executions as reactions to events ''' def __init__(self, opts, log_queue=None): super(Reactor, self).__init__(log_queue=log_queue)...
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import import fnmatch import glob import logging # Import salt libs import salt.runner import salt.state import salt.utils import salt.utils.cache import salt.utils.event import salt.utils.process import salt.defaults.exitcodes # Import 3rd...
112
256
1,739
16
96
l2ol33rt/salt
salt/utils/reactor.py
Python
Reactor
Reactor
25
246
25
25
6674b9e2acb8ecf33eb5d1872f2982bee9ae3678
bigcode/the-stack
train
f40cec0cca009bd2c2da778d
train
class
class ReactWrap(object): ''' Create a wrapper that executes low data for the reaction system ''' # class-wide cache of clients client_cache = None event_user = 'Reactor' def __init__(self, opts): self.opts = opts if ReactWrap.client_cache is None: ReactWrap.clien...
class ReactWrap(object):
''' Create a wrapper that executes low data for the reaction system ''' # class-wide cache of clients client_cache = None event_user = 'Reactor' def __init__(self, opts): self.opts = opts if ReactWrap.client_cache is None: ReactWrap.client_cache = salt.utils.cach...
get('user') == self.wrap.event_user: continue if data['tag'].endswith('salt/reactors/manage/add'): _data = data['data'] res = self.add_reactor(_data['event'], _data['reactors']) self.event.fire_event({'reactors': self.list_all(), ...
256
256
1,027
5
251
l2ol33rt/salt
salt/utils/reactor.py
Python
ReactWrap
ReactWrap
249
359
249
249
9c57d3ea2cea8e198702c9518c85ea753264a785
bigcode/the-stack
train
2f9bd60fca861a570c39f954
train
class
class Test_Processing(object): def test_preemphasis(self): # Performing the operation on the generated signal. signal_preemphasized = processing.preemphasis(signal, cof=0.98) # Shape matcher assert signal_preemphasized.ndim == 1 assert signal_preemphasized.shape =...
class Test_Processing(object):
def test_preemphasis(self): # Performing the operation on the generated signal. signal_preemphasized = processing.preemphasis(signal, cof=0.98) # Shape matcher assert signal_preemphasized.ndim == 1 assert signal_preemphasized.shape == signal.shape def t...
') assert hasattr(feature, 'lmfe') assert hasattr(feature, 'extract_derivative_feature') def test_functions(self): # Cheching the availibility of functions in the chosen attribute assert hasattr(functions, 'frequency_to_mel') assert hasattr(functions, 'mel_to_fr...
92
93
313
6
86
yorange1/speechpy
tests/test_speechpy.py
Python
Test_Processing
Test_Processing
54
92
54
55
da1ffdf392cfad3c35a42864f9c6b53574b679ba
bigcode/the-stack
train
fcc36b24ee232f07f87c0f23
train
class
class Test_feature(object): def test_mfcc(self): num_cepstral = 13 mfcc = feature.mfcc(signal, sampling_frequency=fs, frame_length=0.020, num_cepstral=num_cepstral, frame_stride=0.01, num_filters=num_filters, fft_length=512, low_freque...
class Test_feature(object):
def test_mfcc(self): num_cepstral = 13 mfcc = feature.mfcc(signal, sampling_frequency=fs, frame_length=0.020, num_cepstral=num_cepstral, frame_stride=0.01, num_filters=num_filters, fft_length=512, low_frequency=0, ...
mean of the output vector assert np.allclose(np.mean(normalized_feature,axis=0), np.zeros((1,normalized_feature.shape[1]))) assert np.allclose(np.std(normalized_feature,axis=0), np.ones((1,normalized_feature.shape[1]))) class Test_feature(object):
63
64
104
5
58
yorange1/speechpy
tests/test_speechpy.py
Python
Test_feature
Test_feature
95
106
95
96
90dae562e65145f0e836e4b0c87415d343d78571
bigcode/the-stack
train
ba7ca15c08c8df6df9a9a12a
train
class
class Test_Methods_Exists(object): def test_processing(self): # Cheching the availibility of functions in the chosen attribute assert hasattr(processing, 'preemphasis') assert hasattr(processing, 'stack_frames') assert hasattr(processing, 'fft_spectrum') assert hasat...
class Test_Methods_Exists(object):
def test_processing(self): # Cheching the availibility of functions in the chosen attribute assert hasattr(processing, 'preemphasis') assert hasattr(processing, 'stack_frames') assert hasattr(processing, 'fft_spectrum') assert hasattr(processing, 'power_spectrum') ...
, sigma = 0, 0.1 # mean and standard deviation signal = np.random.normal(mu, sigma, 1000000) fs = 16000 # Generating stached frames with SpeechPy frame_length = 0.02 frame_stride = 0.02 num_filters=40 class Test_Methods_Exists(object):
75
75
250
8
66
yorange1/speechpy
tests/test_speechpy.py
Python
Test_Methods_Exists
Test_Methods_Exists
23
51
23
23
921832df1bcd21f625bd4b3e1f9bfccfca375448
bigcode/the-stack
train
248b6b25effee9fd458c7336
train
class
class ListInstanceConfigsPager(object): """A pager for iterating through ``list_instance_configs`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstanceConfigsResponse` object, and provides an ``__iter__`` method to iterate through its ``instance_configs`` field...
class ListInstanceConfigsPager(object):
"""A pager for iterating through ``list_instance_configs`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstanceConfigsResponse` object, and provides an ``__iter__`` method to iterate through its ``instance_configs`` field. If there are more pages, the ``__...
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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WI...
149
149
499
7
141
Ahmah2009/python-spanner
google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py
Python
ListInstanceConfigsPager
ListInstanceConfigsPager
30
89
30
30
3e7e664d1a4dbe7198e0acfa7a2e23d60da39399
bigcode/the-stack
train
fca0cf94ba7c76d78d4f01a4
train
class
class ListInstancesAsyncPager(object): """A pager for iterating through ``list_instances`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstancesResponse` object, and provides an ``__aiter__`` method to iterate through its ``instances`` field. If there are ...
class ListInstancesAsyncPager(object):
"""A pager for iterating through ``list_instances`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstancesResponse` object, and provides an ``__aiter__`` method to iterate through its ``instances`` field. If there are more pages, the ``__aiter__`` method wi...
InstancesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name): return getattr(self._response, name) @property def pages(self): yield self._response while self._response.next_page_token: self._request.page_token...
154
154
515
7
147
Ahmah2009/python-spanner
google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py
Python
ListInstancesAsyncPager
ListInstancesAsyncPager
222
287
222
222
c5503dbdd88c3a22c4789b87b009ee4d67ad4fcf
bigcode/the-stack
train
7ad0490cd0927653182bf91c
train
class
class ListInstanceConfigsAsyncPager(object): """A pager for iterating through ``list_instance_configs`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstanceConfigsResponse` object, and provides an ``__aiter__`` method to iterate through its ``instance_configs``...
class ListInstanceConfigsAsyncPager(object):
"""A pager for iterating through ``list_instance_configs`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstanceConfigsResponse` object, and provides an ``__aiter__`` method to iterate through its ``instance_configs`` field. If there are more pages, the ``_...
InstanceConfigsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name): return getattr(self._response, name) @property def pages(self): yield self._response while self._response.next_page_token: self._request.page...
157
157
526
8
149
Ahmah2009/python-spanner
google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py
Python
ListInstanceConfigsAsyncPager
ListInstanceConfigsAsyncPager
92
157
92
92
eeb2b7c519389c681fee289130947d1990869603
bigcode/the-stack
train
728f111c713693427080ded0
train
class
class ListInstancesPager(object): """A pager for iterating through ``list_instances`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstancesResponse` object, and provides an ``__iter__`` method to iterate through its ``instances`` field. If there are more p...
class ListInstancesPager(object):
"""A pager for iterating through ``list_instances`` requests. This class thinly wraps an initial :class:`~.spanner_instance_admin.ListInstancesResponse` object, and provides an ``__iter__`` method to iterate through its ``instances`` field. If there are more pages, the ``__iter__`` method will...
._response, name) @property async def pages( self, ): yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) ...
146
146
488
6
140
Ahmah2009/python-spanner
google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py
Python
ListInstancesPager
ListInstancesPager
160
219
160
160
b0012b97eda12628a8c91a537c680de33e8115f1
bigcode/the-stack
train
eaa792e8673fc10d6ec65fdc
train
function
def view_camera(camera_config): # cctvs = list() # for camera_config in camera_configs: ip_camera_url = f"{camera_config['protocol']}://{camera_config['ip']}:{camera_config['port']}/{camera_config['path']}" print(ip_camera_url) cctv = CCTV(ip_camera_url) # verifier = Verifier('instagram.json') ...
def view_camera(camera_config): # cctvs = list() # for camera_config in camera_configs:
ip_camera_url = f"{camera_config['protocol']}://{camera_config['ip']}:{camera_config['port']}/{camera_config['path']}" print(ip_camera_url) cctv = CCTV(ip_camera_url) # verifier = Verifier('instagram.json') for frame in cctv.start_streaming(): for detected_face in detector.detect_faces(fra...
dotenv import load_dotenv from menu_pages import * import json from threading import Thread import time from multiprocessing import Process detector = Detector() verifier = Verifier('instagram.json') def view_camera(camera_config): # cctvs = list() # for camera_config in camera_configs:
64
64
211
23
41
mghorbani2357/Face-Match
main.py
Python
view_camera
view_camera
18
41
18
20
541acd45ef17b2dab332be31ec2022ccd916eddc
bigcode/the-stack
train
9177ea0284b35c81e578dddd
train
class
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ output = '' idx = 0 if not strs: # list裡沒有單字 return output while(True): flag = True check_letter = strs[0][idx:id...
class Solution(object):
def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ output = '' idx = 0 if not strs: # list裡沒有單字 return output while(True): flag = True check_letter = strs[0][idx:idx+1] for wor...
class Solution(object):
4
64
154
4
0
C24054057/leetcode
Longest Common Prefix/LongestCommonPrefix.py
Python
Solution
Solution
1
24
1
1
4e23bdfbf58948f9322f509b467d16e0866fb7f3
bigcode/the-stack
train
aec4ab491c96aae0ee2fe56d
train
class
class GetBackendConfigurationTestCase(test.TestCase): def test_get_backend_configuration_success(self): backend_name = 'fake_backend_name' self.mock_object( zfs_driver.CONF, 'list_all_sections', mock.Mock(return_value=['fake1', backend_name, 'fake2'])) mock_config = ...
class GetBackendConfigurationTestCase(test.TestCase):
def test_get_backend_configuration_success(self): backend_name = 'fake_backend_name' self.mock_object( zfs_driver.CONF, 'list_all_sections', mock.Mock(return_value=['fake1', backend_name, 'fake2'])) mock_config = self.mock_object( zfs_driver.configuration,...
_id, key): return self.storage.get(entity_id, {}).get(key) def delete(self, entity_id): self.storage.pop(entity_id, None) class FakeTempDir(object): def __enter__(self, *args, **kwargs): return '/foo/path' def __exit__(self, *args, **kwargs): pass class GetBackendConfigu...
84
84
282
10
73
sapcc/manila
manila/tests/share/drivers/zfsonlinux/test_driver.py
Python
GetBackendConfigurationTestCase
GetBackendConfigurationTestCase
105
141
105
106
4c9f890528cb51694dfb1244317fffbbc203148f
bigcode/the-stack
train
c4d51ec5ffa47424ed11bc3d
train
class
class FakeDriverPrivateStorage(object): def __init__(self): self.storage = {} def update(self, entity_id, data): if entity_id not in self.storage: self.storage[entity_id] = {} self.storage[entity_id].update(data) def get(self, entity_id, key): return self.stora...
class FakeDriverPrivateStorage(object):
def __init__(self): self.storage = {} def update(self, entity_id, data): if entity_id not in self.storage: self.storage[entity_id] = {} self.storage[entity_id].update(data) def get(self, entity_id, key): return self.storage.get(entity_id, {}).get(key) def d...
.filter_function = kwargs.get("filter_function", None) self.goodness_function = kwargs.get("goodness_function", None) def safe_get(self, key): return getattr(self, key) def append_config_values(self, *args, **kwargs): pass class FakeDriverPrivateStorage(object):
64
64
96
7
56
sapcc/manila
manila/tests/share/drivers/zfsonlinux/test_driver.py
Python
FakeDriverPrivateStorage
FakeDriverPrivateStorage
79
93
79
80
02a1fd9608622eba589e3657e9134bd8460bbddc
bigcode/the-stack
train
fccdbc9a1dce983de55801bd
train
class
class FakeTempDir(object): def __enter__(self, *args, **kwargs): return '/foo/path' def __exit__(self, *args, **kwargs): pass
class FakeTempDir(object):
def __enter__(self, *args, **kwargs): return '/foo/path' def __exit__(self, *args, **kwargs): pass
self.storage[entity_id] = {} self.storage[entity_id].update(data) def get(self, entity_id, key): return self.storage.get(entity_id, {}).get(key) def delete(self, entity_id): self.storage.pop(entity_id, None) class FakeTempDir(object):
64
64
41
6
58
sapcc/manila
manila/tests/share/drivers/zfsonlinux/test_driver.py
Python
FakeTempDir
FakeTempDir
96
102
96
97
6139320fa4958a64823814f57fb68aca9ab0432e
bigcode/the-stack
train
6d643bff46b815e6509e0535
train
class
class FakeConfig(object): def __init__(self, *args, **kwargs): self.driver_handles_share_servers = False self.share_driver = 'fake_share_driver_name' self.share_backend_name = 'FAKE_BACKEND_NAME' self.zfs_share_export_ip = kwargs.get( "zfs_share_export_ip", "1.1.1.1") ...
class FakeConfig(object):
def __init__(self, *args, **kwargs): self.driver_handles_share_servers = False self.share_driver = 'fake_share_driver_name' self.share_backend_name = 'FAKE_BACKEND_NAME' self.zfs_share_export_ip = kwargs.get( "zfs_share_export_ip", "1.1.1.1") self.zfs_service_ip =...
at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific...
171
171
572
5
165
sapcc/manila
manila/tests/share/drivers/zfsonlinux/test_driver.py
Python
FakeConfig
FakeConfig
31
76
31
31
85ebf4afea977eea98aaa5b4c98844c17317e04a
bigcode/the-stack
train
f2b5e4fe919203d63b2f452d
train
class
@ddt.ddt class ZFSonLinuxShareDriverTestCase(test.TestCase): def setUp(self): self.mock_object(zfs_driver.CONF, '_check_required_opts') super(ZFSonLinuxShareDriverTestCase, self).setUp() self._context = context.get_admin_context() self.ssh_executor = self.mock_object(ganesha_utils, ...
@ddt.ddt class ZFSonLinuxShareDriverTestCase(test.TestCase):
def setUp(self): self.mock_object(zfs_driver.CONF, '_check_required_opts') super(ZFSonLinuxShareDriverTestCase, self).setUp() self._context = context.get_admin_context() self.ssh_executor = self.mock_object(ganesha_utils, 'SSHExecutor') self.configuration = FakeConfig() ...
mock.Mock(return_value=['fake1', backend_name, 'fake2'])) mock_config = self.mock_object( zfs_driver.configuration, 'Configuration') result = zfs_driver.get_backend_configuration(backend_name) self.assertEqual(mock_config.return_value, result) mock_config.assert...
256
256
22,222
19
237
sapcc/manila
manila/tests/share/drivers/zfsonlinux/test_driver.py
Python
ZFSonLinuxShareDriverTestCase
ZFSonLinuxShareDriverTestCase
144
2,600
144
146
35fd78583c9a2fb42fc389a0d2c4a5a459579261
bigcode/the-stack
train
fe6c6cdfeeaad5dfb2ef8614
train
class
class EfficientNetFeatureExtractor(nn.Module): def __init__(self): super().__init__() effnet = models.efficientnet_b7(pretrained=True) self.enc_1 = nn.Sequential(*effnet.features[:2]) self.enc_2 = nn.Sequential(*effnet.features[2:4]) self.enc_3 = nn.Sequential(*effnet.feature...
class EfficientNetFeatureExtractor(nn.Module):
def __init__(self): super().__init__() effnet = models.efficientnet_b7(pretrained=True) self.enc_1 = nn.Sequential(*effnet.features[:2]) self.enc_2 = nn.Sequential(*effnet.features[2:4]) self.enc_3 = nn.Sequential(*effnet.features[4:6]) self.enc_4 = nn.Sequential(*eff...
False def forward(self, image): results = [image] for i in range(4): func = getattr(self, 'enc_{:d}'.format(i + 1)) results.append(func(results[-1])) return results[1:] class EfficientNetFeatureExtractor(nn.Module):
63
64
195
8
55
SorenAsger/RFR-Inpainting
modules/RFRNet.py
Python
EfficientNetFeatureExtractor
EfficientNetFeatureExtractor
51
70
51
51
eb9ee266baf3f9918d2847c8714984c531dbbc29
bigcode/the-stack
train
9461cdb92176df6bf584f31a
train
class
class VGG16FeatureExtractor(nn.Module): def __init__(self): super().__init__() vgg16 = models.vgg16(pretrained=True) self.enc_1 = nn.Sequential(*vgg16.features[:5]) self.enc_2 = nn.Sequential(*vgg16.features[5:10]) self.enc_3 = nn.Sequential(*vgg16.features[10:17]) #...
class VGG16FeatureExtractor(nn.Module):
def __init__(self): super().__init__() vgg16 = models.vgg16(pretrained=True) self.enc_1 = nn.Sequential(*vgg16.features[:5]) self.enc_2 = nn.Sequential(*vgg16.features[5:10]) self.enc_3 = nn.Sequential(*vgg16.features[10:17]) # fix the encoder for i in range(...
import torch import torch.nn as nn import torch.nn.functional as F from modules.partialconv2d import PartialConv2d from modules.Attention import AttentionModule from torchvision import models class VGG16FeatureExtractor(nn.Module):
50
64
181
9
40
SorenAsger/RFR-Inpainting
modules/RFRNet.py
Python
VGG16FeatureExtractor
VGG16FeatureExtractor
9
27
9
9
f2fabb0874e775288d7be8a38f1438950b065831
bigcode/the-stack
train
f6d6f711958657ca47f54412
train
class
class RFRNet(nn.Module): def __init__(self): super(RFRNet, self).__init__() self.Pconv1 = PartialConv2d(3, 64, 7, 2, 3, multi_channel=True, bias=False) self.bn1 = nn.BatchNorm2d(64) self.Pconv2 = PartialConv2d(64, 64, 7, 1, 3, multi_channel=True, bias=False) self.bn20 = nn.Ba...
class RFRNet(nn.Module):
def __init__(self): super(RFRNet, self).__init__() self.Pconv1 = PartialConv2d(3, 64, 7, 2, 3, multi_channel=True, bias=False) self.bn1 = nn.BatchNorm2d(64) self.Pconv2 = PartialConv2d(64, 64, 7, 1, 3, multi_channel=True, bias=False) self.bn20 = nn.BatchNorm2d(64) sel...
.BatchNorm2d(64), nn.LeakyReLU(0.2, inplace=True)] self.dec_1 = nn.Sequential(*block) def forward(self, input, mask): h_dict = {} # for the output of enc_N h_dict['h_0'] = input h_key_prev = 'h_0' for i in range(1, self.layer_size + 1): l_key...
256
256
895
7
248
SorenAsger/RFR-Inpainting
modules/RFRNet.py
Python
RFRNet
RFRNet
174
235
174
174
f9c97eb06f4a39783b6e8c81c5a9e429aa5336fd
bigcode/the-stack
train
82a19426f6e3aaf3920cd381
train
class
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=...
class Bottleneck(nn.Module):
expansion = 4 def __init__(self, inplanes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, ...
d}'.format(i + 1)).parameters(): param.requires_grad = False def forward(self, image): results = [image] for i in range(4): func = getattr(self, 'enc_{:d}'.format(i + 1)) results.append(func(results[-1])) return results[1:] class Bottleneck(nn.Module)...
76
77
258
6
70
SorenAsger/RFR-Inpainting
modules/RFRNet.py
Python
Bottleneck
Bottleneck
73
104
73
73
50fbb9926e53328cfc52d2bf5745740f51047176
bigcode/the-stack
train
d64f95a2781ff8916e4a3a27
train
class
class RFRModule(nn.Module): def __init__(self, layer_size=6, in_channel=64): super(RFRModule, self).__init__() self.freeze_enc_bn = False self.layer_size = layer_size for i in range(3): name = 'enc_{:d}'.format(i + 1) out_channel = in_channel * 2 b...
class RFRModule(nn.Module):
def __init__(self, layer_size=6, in_channel=64): super(RFRModule, self).__init__() self.freeze_enc_bn = False self.layer_size = layer_size for i in range(3): name = 'enc_{:d}'.format(i + 1) out_channel = in_channel * 2 block = [nn.Conv2d(in_channel...
(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_s...
218
218
729
7
210
SorenAsger/RFR-Inpainting
modules/RFRNet.py
Python
RFRModule
RFRModule
107
171
107
107
a4ed64e37d5ac0b593df98be1e3cf415d99f7b95
bigcode/the-stack
train
459aa7090e4cac5283ce5010
train
class
class MobileNetFeatureExtractor(nn.Module): def __init__(self): super().__init__() mnet = models.mobilenet_v3_large(pretrained=True) self.enc_1 = nn.Sequential(*mnet.features[:3]) self.enc_2 = nn.Sequential(*mnet.features[3:6]) self.enc_3 = nn.Sequential(*mnet.features[6:9]) ...
class MobileNetFeatureExtractor(nn.Module):
def __init__(self): super().__init__() mnet = models.mobilenet_v3_large(pretrained=True) self.enc_1 = nn.Sequential(*mnet.features[:3]) self.enc_2 = nn.Sequential(*mnet.features[3:6]) self.enc_3 = nn.Sequential(*mnet.features[6:9]) self.enc_4 = nn.Sequential(*mnet.fea...
False def forward(self, image): results = [image] for i in range(3): func = getattr(self, 'enc_{:d}'.format(i + 1)) results.append(func(results[-1])) return results[1:] class MobileNetFeatureExtractor(nn.Module):
63
64
194
8
55
SorenAsger/RFR-Inpainting
modules/RFRNet.py
Python
MobileNetFeatureExtractor
MobileNetFeatureExtractor
30
48
30
30
cff6dbac2ded976b1c2c57f79d6a7341a0a64041
bigcode/the-stack
train
e0f6b459b3bd7351e93afb39
train
class
class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_...
class SimpleJudgingObject:
def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_exemplary = False s...
Baseline: just verifies that the standard steps did not crash. # JudgeSuperior: also verifies that the validation steps are not in error. # JudgeExemplary: same as intermediate badge. # We import an assistant script that includes the common verifications # methods. The assistant buffers its checks, so that runnin...
116
117
390
6
110
KhronosGroup/COLLADA-CTS
StandardDataSets/collada/library_visual_scenes/visual_scene/node/instance_geometry/bind_material/instance_material/instance_material_same_geometry/instance_material_same_geometry.py
Python
SimpleJudgingObject
SimpleJudgingObject
29
69
29
29
bbef25cbc2f3c596e7f17180fa3a24a391e10761
bigcode/the-stack
train
da8819675f87a7732f3793e0
train
function
def recommend(item_id, num): print("Recommending " + str(num) + " products similar to " + item(item_id) + "...") print("-------") recs = results[item_id][:num] for rec in recs: print("Recommended: " + item(rec[1]) + " (score:" + str(rec[0]) + ")")
def recommend(item_id, num):
print("Recommending " + str(num) + " products similar to " + item(item_id) + "...") print("-------") recs = results[item_id][:num] for rec in recs: print("Recommended: " + item(rec[1]) + " (score:" + str(rec[0]) + ")")
'][i]) for i in similar_indices] results[row['id']] = similar_items[1:] print('done!') def item(id): return ds.loc[ds['id'] == id]['description'].tolist()[0].split(' - ')[0] def recommend(item_id, num):
63
64
80
7
56
dady-mlops/simple_recommender
main.py
Python
recommend
recommend
27
32
27
27
f97523d55245bbfa46ec44859d303b7b0fbd7bf6
bigcode/the-stack
train
40a50776bfdfbe31732ed7f6
train
function
def item(id): return ds.loc[ds['id'] == id]['description'].tolist()[0].split(' - ')[0]
def item(id):
return ds.loc[ds['id'] == id]['description'].tolist()[0].split(' - ')[0]
= cosine_similarities[idx].argsort()[:-100:-1] similar_items = [(cosine_similarities[idx][i], ds['id'][i]) for i in similar_indices] results[row['id']] = similar_items[1:] print('done!') def item(id):
62
64
28
4
59
dady-mlops/simple_recommender
main.py
Python
item
item
23
24
23
23
37ece327e468e4f3417ee72209319ab16c43b03c
bigcode/the-stack
train
2eacf9f9d304a1b99c407692
train
class
class Graph: def __init__(self): pass
class Graph:
def __init__(self): pass
from Node import * class Graph:
7
64
13
3
4
3phase/ombudsman-website
story_generator/Graph.py
Python
Graph
Graph
3
5
3
3
361a64bc392acad102a3b32799d04af245135331
bigcode/the-stack
train
1be85c125ebd21e30f1d8e8c
train
class
class _BaseTestLibrary: get_handler_error_level = 'INFO' def __init__(self, libcode, name, args, source, logger, variables): if os.path.exists(name): name = os.path.splitext(os.path.basename(os.path.abspath(name)))[0] self._libcode = libcode self._libinst = None self...
class _BaseTestLibrary:
get_handler_error_level = 'INFO' def __init__(self, libcode, name, args, source, logger, variables): if os.path.exists(name): name = os.path.splitext(os.path.basename(os.path.abspath(name)))[0] self._libcode = libcode self._libinst = None self.version = self._get_ver...
KeywordDocumentation, GetKeywordNames, GetKeywordTags, RunKeyword) from .handlers import Handler, InitHandler, DynamicHandler, EmbeddedArgumentsHandler from .handlerstore import HandlerStore from .libraryscopes import LibraryScope from .outputcapture import OutputCapturer def TestLibrary(...
256
256
2,177
6
249
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
_BaseTestLibrary
_BaseTestLibrary
62
335
62
62
195d704220fa77072f427093c40cd89130eaa5a2
bigcode/the-stack
train
0d8ff3cdb949a046db57847f
train
class
class _ClassLibrary(_BaseTestLibrary): def _get_handler_method(self, libinst, name): # Type is checked before using getattr to avoid calling properties. for item in (libinst,) + inspect.getmro(libinst.__class__): if item is object: continue if hasattr(item, '...
class _ClassLibrary(_BaseTestLibrary):
def _get_handler_method(self, libinst, name): # Type is checked before using getattr to avoid calling properties. for item in (libinst,) + inspect.getmro(libinst.__class__): if item is object: continue if hasattr(item, '__dict__') and name in item.__dict__: ...
arguments %s' % seq2str2(args) else: args_text = 'no arguments' raise DataError("Initializing library '%s' with %s failed: %s\n%s" % (self.name, args_text, msg, details)) class _ClassLibrary(_BaseTestLibrary):
64
64
112
9
55
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
_ClassLibrary
_ClassLibrary
338
348
338
339
c27f9bd768037dab74ecb89ffa7432c2c052737c
bigcode/the-stack
train
f4d257de40b6a3a2f543745a
train
class
class _DynamicLibrary(_BaseTestLibrary): get_handler_error_level = 'ERROR' def __init__(self, libcode, name, args, source, logger, variables=None): _BaseTestLibrary.__init__(self, libcode, name, args, source, logger, variables) @property def doc(self): ...
class _DynamicLibrary(_BaseTestLibrary):
get_handler_error_level = 'ERROR' def __init__(self, libcode, name, args, source, logger, variables=None): _BaseTestLibrary.__init__(self, libcode, name, args, source, logger, variables) @property def doc(self): if self._doc is None: self._...
self._libcode if self.has_listener is None: self.has_listener = bool(self.get_listeners(self._libcode)) return self._libcode def _create_init_handler(self, libcode): return InitHandler(self) class _HybridLibrary(_BaseTestLibrary): get_handler_error_level = 'ERROR' de...
97
97
326
9
88
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
_DynamicLibrary
_DynamicLibrary
377
417
377
377
26f8dddc9734dc44448721e8970c5ea8a0752e94
bigcode/the-stack
train
3be562466f1ff1caf4b6fc95
train
function
def TestLibrary(name, args=None, variables=None, create_handlers=True, logger=LOGGER): if name in STDLIBS: import_name = 'robot.libraries.' + name else: import_name = name with OutputCapturer(library_import=True): importer = Importer('library', logger=LOGGER) libcode, source ...
def TestLibrary(name, args=None, variables=None, create_handlers=True, logger=LOGGER):
if name in STDLIBS: import_name = 'robot.libraries.' + name else: import_name = name with OutputCapturer(library_import=True): importer = Importer('library', logger=LOGGER) libcode, source = importer.import_class_or_module(import_name, ...
RunKeyword) from .handlers import Handler, InitHandler, DynamicHandler, EmbeddedArgumentsHandler from .handlerstore import HandlerStore from .libraryscopes import LibraryScope from .outputcapture import OutputCapturer def TestLibrary(name, args=None, variables=None, create_handlers=True, logger=LOGGER):
64
64
134
19
44
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
TestLibrary
TestLibrary
35
48
35
35
53f2037d7d94bab6119921bf70451da3d3775cc1
bigcode/the-stack
train
f792ab8cf6d1525c17b6ae43
train
class
class _HybridLibrary(_BaseTestLibrary): get_handler_error_level = 'ERROR' def _get_handler_names(self, instance): return GetKeywordNames(instance)()
class _HybridLibrary(_BaseTestLibrary):
get_handler_error_level = 'ERROR' def _get_handler_names(self, instance): return GetKeywordNames(instance)()
: return self._libcode if self.has_listener is None: self.has_listener = bool(self.get_listeners(self._libcode)) return self._libcode def _create_init_handler(self, libcode): return InitHandler(self) class _HybridLibrary(_BaseTestLibrary):
64
64
36
9
55
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
_HybridLibrary
_HybridLibrary
370
374
370
370
9dd62d47e6a2c588ba5c4eb535cc2888ad0174b3
bigcode/the-stack
train
1540d03d2d918da703090bde
train
function
def _get_lib_class(libcode): if inspect.ismodule(libcode): return _ModuleLibrary if GetKeywordNames(libcode): if RunKeyword(libcode): return _DynamicLibrary else: return _HybridLibrary return _ClassLibrary
def _get_lib_class(libcode):
if inspect.ismodule(libcode): return _ModuleLibrary if GetKeywordNames(libcode): if RunKeyword(libcode): return _DynamicLibrary else: return _HybridLibrary return _ClassLibrary
.import_class_or_module(import_name, return_source=True) libclass = _get_lib_class(libcode) lib = libclass(libcode, name, args or [], source, logger, variables) if create_handlers: lib.create_handlers() return lib def _get_lib_class(libco...
64
64
59
8
55
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
_get_lib_class
_get_lib_class
51
59
51
51
ed3d3be86c1a7e52a23da562f0a9666159058218
bigcode/the-stack
train
9a52586c554c98bec547755e
train
class
class _ModuleLibrary(_BaseTestLibrary): def _get_handler_method(self, libcode, name): method = _BaseTestLibrary._get_handler_method(self, libcode, name) if hasattr(libcode, '__all__') and name not in libcode.__all__: raise DataError('Not exposed as a keyword.') return method ...
class _ModuleLibrary(_BaseTestLibrary):
def _get_handler_method(self, libcode, name): method = _BaseTestLibrary._get_handler_method(self, libcode, name) if hasattr(libcode, '__all__') and name not in libcode.__all__: raise DataError('Not exposed as a keyword.') return method def get_instance(self, create=True): ...
object: continue if hasattr(item, '__dict__') and name in item.__dict__: self._validate_handler_method(item.__dict__[name]) return getattr(libinst, name) raise DataError('No non-implicit implementation found.') class _ModuleLibrary(_BaseTestLibrary): ...
63
64
143
9
54
d-biehl/robotframework
src/robot/running/testlibraries.py
Python
_ModuleLibrary
_ModuleLibrary
351
367
351
352
4edbd9e60ed222447d95a613b16b22a5033e6d8a
bigcode/the-stack
train
55350a4d393ff9c0c64e2dfd
train
class
class Input_Error(DbError): """Exception raised for invalid input. """ pass
class Input_Error(DbError):
"""Exception raised for invalid input. """ pass
(Exception): """ Exception raised for Database errors. Attributes: expression -- input expression in which error occurred message -- explanation of error """ def __init__(self, expression, message): self.expression = expression self.message = message class Input_Er...
64
64
19
6
57
placiflury/gridmonitor-infocache
infocache/errors/db.py
Python
Input_Error
Input_Error
13
16
13
13
e12561501a7fb780a9380b949a8dbe64a8b1f861
bigcode/the-stack
train
884a094a75724ff030aefdc5
train
class
class DbError(Exception): """ Exception raised for Database errors. Attributes: expression -- input expression in which error occurred message -- explanation of error """ def __init__(self, expression, message): self.expression = expression self.message = message
class DbError(Exception):
""" Exception raised for Database errors. Attributes: expression -- input expression in which error occurred message -- explanation of error """ def __init__(self, expression, message): self.expression = expression self.message = message
class DbError(Exception):
5
64
61
5
0
placiflury/gridmonitor-infocache
infocache/errors/db.py
Python
DbError
DbError
1
10
1
1
78e104089f2d437b6578b6ffdb0275e05a4922f5
bigcode/the-stack
train
f4af28d4f813c7edeb85559a
train
class
class iOSTestRunner(TestRunner): def getToolchain(self): toolchain = os.path.join(self.script_dir, "cmake", "Toolchains", "Toolchain-%s_Xcode.cmake" % self.target) return toolchain def getCMakeArgs(self): args = TestRunner.getCMakeArgs(self) args = args + [ "-DIOS_A...
class iOSTestRunner(TestRunner):
def getToolchain(self): toolchain = os.path.join(self.script_dir, "cmake", "Toolchains", "Toolchain-%s_Xcode.cmake" % self.target) return toolchain def getCMakeArgs(self): args = TestRunner.getCMakeArgs(self) args = args + [ "-DIOS_ARCH=%s" % self.arch, "...
testcmd = [ "xcodebuild", "test", "-project", "OpenCVTest.xcodeproj", "-scheme", "OpenCVTestTests", "-destination", "platform=%s" % self.platform ] return testcmd class iOSTestRunner(TestRunner):
64
64
121
8
55
artun3e/opencv
platforms/ios/run_tests.py
Python
iOSTestRunner
iOSTestRunner
82
94
82
83
efb5adbdca8de2abf543e50e7c863e47ffd0a57a
bigcode/the-stack
train
562b75a11e52f7b0d13702c2
train
class
class TestRunner: def __init__(self, script_dir, tests_dir, build_dir, framework_dir, framework_name, arch, target, platform): self.script_dir = script_dir self.tests_dir = tests_dir self.build_dir = build_dir self.framework_dir = framework_dir self.framework_name = framework...
class TestRunner:
def __init__(self, script_dir, tests_dir, build_dir, framework_dir, framework_name, arch, target, platform): self.script_dir = script_dir self.tests_dir = tests_dir self.build_dir = build_dir self.framework_dir = framework_dir self.framework_name = framework_name self...
, re, os, os.path, shutil, string, sys, argparse, traceback, multiprocessing from subprocess import check_call, check_output, CalledProcessError IPHONEOS_DEPLOYMENT_TARGET='8.0' # default, can be changed via command line options or environment variable def execute(cmd, cwd = None): print("Executing: %s in %s" % ...
135
135
452
4
131
artun3e/opencv
platforms/ios/run_tests.py
Python
TestRunner
TestRunner
19
80
19
19
5c2f1d28574d5fbab3bc7345a147f05bb8b6d109
bigcode/the-stack
train
6b6d998509e9f9ceb95386eb
train
function
def execute(cmd, cwd = None): print("Executing: %s in %s" % (cmd, cwd), file=sys.stderr) print('Executing: ' + ' '.join(cmd)) retcode = check_call(cmd, cwd = cwd) if retcode != 0: raise Exception("Child returned:", retcode)
def execute(cmd, cwd = None):
print("Executing: %s in %s" % (cmd, cwd), file=sys.stderr) print('Executing: ' + ' '.join(cmd)) retcode = check_call(cmd, cwd = cwd) if retcode != 0: raise Exception("Child returned:", retcode)
, os.path, shutil, string, sys, argparse, traceback, multiprocessing from subprocess import check_call, check_output, CalledProcessError IPHONEOS_DEPLOYMENT_TARGET='8.0' # default, can be changed via command line options or environment variable def execute(cmd, cwd = None):
64
64
71
8
55
artun3e/opencv
platforms/ios/run_tests.py
Python
execute
execute
12
17
12
12
d496dd401fffe51c91acaf252ad6893aa39a356d
bigcode/the-stack
train
3bfdbf6375730d8ed932389f
train
function
def test_external_repo(erepo): url = erepo.root_dir # We will share cache dir, to fetch version file cache_dir = erepo.dvc.cache.local.cache_dir with patch.object(Git, "clone", wraps=Git.clone) as mock: with external_repo(url, cache_dir=cache_dir) as repo: with repo.open(os.path.joi...
def test_external_repo(erepo):
url = erepo.root_dir # We will share cache dir, to fetch version file cache_dir = erepo.dvc.cache.local.cache_dir with patch.object(Git, "clone", wraps=Git.clone) as mock: with external_repo(url, cache_dir=cache_dir) as repo: with repo.open(os.path.join(repo.root_dir, "version")) as...
import os from mock import patch from dvc.external_repo import external_repo from dvc.scm.git import Git from dvc.utils.fs import path_isin def test_external_repo(erepo):
44
64
187
8
35
Abrosimov-a-a/dvc
tests/func/test_external_repo.py
Python
test_external_repo
test_external_repo
10
28
10
10
0e2d4438a8b06027fd9d2249746bed92957872b3
bigcode/the-stack
train
afb4f2384d192883c2790a78
train
function
def addSS3Constellation(sc, satIDs=None): """Add OneWeb SS3 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- Optional parameter to specify which satellites should be added. A 4 digit number or string thereof, or list of those, to identify plane and sat ...
def addSS3Constellation(sc, satIDs=None):
"""Add OneWeb SS3 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- Optional parameter to specify which satellites should be added. A 4 digit number or string thereof, or list of those, to identify plane and sat number. For instance, 1208 is the 8th sate...
plane and sat number. For instance, 1208 is the 8th satellite in the 12th plane (default: all satellites) """ return _addConstellation(sc, 18, 36, satIDs) def addSS3Constellation(sc, satIDs=None):
64
64
116
12
52
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
addSS3Constellation
addSS3Constellation
39
50
39
39
7a3f894f5aeddbe0288b0bd908aa7f4b4f218858
bigcode/the-stack
train
84d17ef0915a7f619925cf0c
train
function
def addSS2Constellation(sc, satIDs=None): """Add OneWeb SS2 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- Optional parameter to specify which satellites should be added. A 4 digit number or string thereof, or list of those, to identify plane and sat ...
def addSS2Constellation(sc, satIDs=None):
"""Add OneWeb SS2 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- Optional parameter to specify which satellites should be added. A 4 digit number or string thereof, or list of those, to identify plane and sat number. For instance, 1208 is the 8th sate...
plane and sat number. For instance, 1208 is the 8th satellite in the 12th plane (default: all satellites) """ return _addConstellation(sc, 9, 32, satIDs) def addSS2Constellation(sc, satIDs=None):
64
64
116
12
52
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
addSS2Constellation
addSS2Constellation
26
37
26
26
116ea72762c220004fd59d791931212705d7b085
bigcode/the-stack
train
9b37885834ff847dec8003f2
train
function
def addSS1Constellation(sc, satIDs=None): """Add OneWeb SS1 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- Optional parameter to specify which satellites should be added. A 4 digit number or string thereof, or list of those, to identify plane and sat ...
def addSS1Constellation(sc, satIDs=None):
"""Add OneWeb SS1 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- Optional parameter to specify which satellites should be added. A 4 digit number or string thereof, or list of those, to identify plane and sat number. For instance, 1208 is the 8th sate...
.. import sensor as stk_sensor from .. import graphics from .. import facility import xlrd import pkg_resources resource_package = __name__ snpListFilename = pkg_resources.resource_filename(resource_package,'SNP sites v3.2.xlsx') def addSS1Constellation(sc, satIDs=None):
64
64
116
12
52
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
addSS1Constellation
addSS1Constellation
13
24
13
13
3617e4b5b42079d509b87c40a9a4e5884cfed257
bigcode/the-stack
train
ad0bd8968c66f9227b419713
train
function
def attachUserAntennas(sat): """Attach Ku antennas to a satellite.""" sensors = [] dim1 = 23.7 dim2 = 1.568 for k in range(16): if k < 8: el = 90 + ((k-8) + 0.5) * 2 * dim2 az = 0 else: el = 90 - ((k-8) + 0.5) * 2 * dim2 az = 180 ...
def attachUserAntennas(sat):
"""Attach Ku antennas to a satellite.""" sensors = [] dim1 = 23.7 dim2 = 1.568 for k in range(16): if k < 8: el = 90 + ((k-8) + 0.5) * 2 * dim2 az = 0 else: el = 90 - ((k-8) + 0.5) * 2 * dim2 az = 180 sensor = stk_sensor.addF...
(len(label)): if k in snpIDs: facility1 = facility.add(sc, label[k], lat[k], lon[k]) facilities.append(facility1) print('.',end='') print('\n', end='') return facilities def attachUserAntennas(sat):
64
64
172
9
54
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
attachUserAntennas
attachUserAntennas
210
231
210
210
e20bc9c17fae5b5ee27446464a25f349bd63fa57
bigcode/the-stack
train
4ba8c9ea5532c4f62c8d0132
train
function
def attachGatewayAntenna(sat, snps): """Attach Ka antennas to a satellite.""" ang = 1 sensor = stk_sensor.addTargeted(sat, 'GW', 'conic', ang, None, snps) return sensor
def attachGatewayAntenna(sat, snps):
"""Attach Ka antennas to a satellite.""" ang = 1 sensor = stk_sensor.addTargeted(sat, 'GW', 'conic', ang, None, snps) return sensor
= stk_sensor.addFixed(sat,'Ku%02d' % k, 'rectangle', dim1, dim2, az, el) sensors.append(sensor) print('.',end='') print('\n', end='') return sensors def attachGatewayAntenna(sat, snps):
64
64
56
12
51
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
attachGatewayAntenna
attachGatewayAntenna
233
238
233
233
ade7ff0553e294adab292f20da7c358da7c6eebc
bigcode/the-stack
train
01a716267d778f4552c00feb
train
function
def _addConstellation(sc, numPlanes, numSatsPerPlane, satIDs): """Add OneWeb constellation to the scenario.""" def createSatellite(sc, plane, sat, sma, ecc, inc, raan): trueAnomaly = sat * 360 / numSatsPerPlane satName = 'OneWeb%02d%02d' % (plane, sat) satObj = stk_sat.add(sc, satName,...
def _addConstellation(sc, numPlanes, numSatsPerPlane, satIDs):
"""Add OneWeb constellation to the scenario.""" def createSatellite(sc, plane, sat, sma, ecc, inc, raan): trueAnomaly = sat * 360 / numSatsPerPlane satName = 'OneWeb%02d%02d' % (plane, sat) satObj = stk_sat.add(sc, satName, sma, ecc, inc, raan, trueAnomaly) stk_sat.graphics(sat...
sat number. For instance, 1208 is the 8th satellite in the 12th plane (default: all satellites) """ return _addConstellation(sc, 18, 36, satIDs) def addSS3Constellation(sc, satIDs=None): """Add OneWeb SS3 constellation to the scenario. Keyword arguments: sc -- scenario satIDs -- ...
183
183
613
19
164
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
_addConstellation
_addConstellation
52
143
52
52
f40fad0e7daee4eeb7e144729891cd3cf07450c6
bigcode/the-stack
train
e133ba3bcdecf8981b60ca4c
train
function
def addSNPs(sc, snpIDs=None): """Add the OneWeb SNP sites to the scenario. IDs are integers in the order of rollout. If no IDs are provided, all are added. """ snpBook = xlrd.open_workbook(snpListFilename) snpSheet = snpBook.sheet_by_index(0) label = [] lat = [] lon = [] for ...
def addSNPs(sc, snpIDs=None):
"""Add the OneWeb SNP sites to the scenario. IDs are integers in the order of rollout. If no IDs are provided, all are added. """ snpBook = xlrd.open_workbook(snpListFilename) snpSheet = snpBook.sheet_by_index(0) label = [] lat = [] lon = [] for k in range(snpSheet.nrows): ...
satIDs plane = int(satID/100) sma1 = sma[plane] ecc = stk_sat.frozenEcc(sma1, inc) sat = satID % 100 raan = 0 + plane * 180 / numPlanes satObj = createSatellite(sc, plane, sat, sma1, ecc, inc, raan) print('.',end='') print('\n', end='') return ...
113
113
377
12
100
Tfitzpatrick846/OWSTK
owstk/oneweb/gen1.py
Python
addSNPs
addSNPs
145
208
145
145
4fd28457c8ca2e663e61c4f3e9cbc77cd64c03c3
bigcode/the-stack
train
d4b8653e46ca450047c3db33
train
function
def test_main(): cmd_line = ['--topology', '2737/2-Wire 4x64 Matrix', '--simulate', '--device', '--channel', '--relay', ] _main(cmd_line)
def test_main():
cmd_line = ['--topology', '2737/2-Wire 4x64 Matrix', '--simulate', '--device', '--channel', '--relay', ] _main(cmd_line)
_help() sys.exit(1) example(args.resource_name, args.topology, args.simulate, args.device, args.channel, args.relay) def test_example(): example('', '2737/2-Wire 4x64 Matrix', True, True, True, True) def test_main():
64
64
45
4
60
imranadamjee/nimi-python
src/niswitch/examples/niswitch_get_device_info.py
Python
test_main
test_main
60
62
60
60
f85c2ff34c3a172998346bfda2d220cb497608af
bigcode/the-stack
train
7700adb052d3f339bebb8195
train
function
def main(): _main(sys.argv[1:])
def main():
_main(sys.argv[1:])
-Wire 4x64 Matrix', True, True, True, True) def test_main(): cmd_line = ['--topology', '2737/2-Wire 4x64 Matrix', '--simulate', '--device', '--channel', '--relay', ] _main(cmd_line) def main():
64
64
11
3
61
imranadamjee/nimi-python
src/niswitch/examples/niswitch_get_device_info.py
Python
main
main
65
66
65
65
b3ac2e754ca1fcff506f42b1ea1faa6b19872494
bigcode/the-stack
train
bbd0a5ea3031e400ae2903e0
train
function
def _main(argsv): parser = argparse.ArgumentParser(description='Prints information for the specified NI Switch module.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--resource-name', default='PXI1Slot2', help='Resource name of a NI Switch.') parser.add_argument('-d', '...
def _main(argsv):
parser = argparse.ArgumentParser(description='Prints information for the specified NI Switch module.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--resource-name', default='PXI1Slot2', help='Resource name of a NI Switch.') parser.add_argument('-d', '--device', default...
Number', 'Name', 'Position', 'Count')) for i in range(1, session.number_of_relays + 1): relay_name = session.get_relay_name(index=i) print(row_format.format(i, relay_name, session.get_relay_position(relay_name=relay_name), session.get_relay_count(relay_name=relay_name))) def ...
80
81
273
6
74
imranadamjee/nimi-python
src/niswitch/examples/niswitch_get_device_info.py
Python
_main
_main
38
53
38
38
fb5f6513273891f38b213488a68765e57cee138d
bigcode/the-stack
train
7f839ae3db6dcbd3d89de20c
train
function
def test_example(): example('', '2737/2-Wire 4x64 Matrix', True, True, True, True)
def test_example():
example('', '2737/2-Wire 4x64 Matrix', True, True, True, True)
or args.relay): print('You must specify at least one of -d, -c, or -r!') parser.print_help() sys.exit(1) example(args.resource_name, args.topology, args.simulate, args.device, args.channel, args.relay) def test_example():
64
64
28
4
60
imranadamjee/nimi-python
src/niswitch/examples/niswitch_get_device_info.py
Python
test_example
test_example
56
57
56
56
1b7140f8dd45e9a9384a27af752b1fe0ba69be09
bigcode/the-stack
train
2ee8d51842b3758d460dc326
train
function
def example(resource_name, topology, simulate, device, channel, relay): # if we are simulating resource name must be blank resource_name = '' if simulate else resource_name with niswitch.Session(resource_name=resource_name, topology=topology, simulate=simulate) as session: if device: pr...
def example(resource_name, topology, simulate, device, channel, relay): # if we are simulating resource name must be blank
resource_name = '' if simulate else resource_name with niswitch.Session(resource_name=resource_name, topology=topology, simulate=simulate) as session: if device: print('Device Info:') row_format = '{:<18}' * (2) print(row_format.format('Device Name: ', session.io_res...
#!/usr/bin/python import argparse import niswitch import sys def example(resource_name, topology, simulate, device, channel, relay): # if we are simulating resource name must be blank
43
115
384
28
14
imranadamjee/nimi-python
src/niswitch/examples/niswitch_get_device_info.py
Python
example
example
8
35
8
9
0923c0f6034db48e6170b237404e7ee3391e8d69
bigcode/the-stack
train
85b0d2688b0632d1a45b7925
train
class
class InfoForm(FlaskForm): name = StringField('Enter a name:') submit = SubmitField('Count_Vowel')
class InfoForm(FlaskForm):
name = StringField('Enter a name:') submit = SubmitField('Count_Vowel')
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField,SubmitField app = Flask(__name__,template_folder='templates') app.config['SECRET_KEY'] = 'mysecretkey' class InfoForm(FlaskForm):
57
64
28
8
49
LAKSHMI-PANNEER/Project-works
Web Development/Forms in Flask/vowel.py
Python
InfoForm
InfoForm
8
10
8
8
8df0e547d175ee4266c8abc5e0224dd552775020
bigcode/the-stack
train
588ea4975ef36e1085a71bc6
train
function
@app.route('/', methods=['GET', 'POST']) def index(): name = False count = 0 form = InfoForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' for i in name: if i=="a" or i=="e" or i=="o" or i == "u" or i == "i": count = count+1...
@app.route('/', methods=['GET', 'POST']) def index():
name = False count = 0 form = InfoForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' for i in name: if i=="a" or i=="e" or i=="o" or i == "u" or i == "i": count = count+1 return render_template('vow.html', **locals())
app = Flask(__name__,template_folder='templates') app.config['SECRET_KEY'] = 'mysecretkey' class InfoForm(FlaskForm): name = StringField('Enter a name:') submit = SubmitField('Count_Vowel') @app.route('/', methods=['GET', 'POST']) def index():
64
64
103
13
51
LAKSHMI-PANNEER/Project-works
Web Development/Forms in Flask/vowel.py
Python
index
index
12
23
12
13
f44c69315d9c14fe6196897c9b6387920cc51bcb
bigcode/the-stack
train
1f086e105e89db21a432fb75
train
class
class MessageR(Message): def __init__(self, sender, receiver, message): ''' sender: NodeFunction sender receiver: NodeVariable receiver message: list of the message's values ''' Message.__init__(self, sender, receiver, message) def getReceive...
class MessageR(Message):
def __init__(self, sender, receiver, message): ''' sender: NodeFunction sender receiver: NodeVariable receiver message: list of the message's values ''' Message.__init__(self, sender, receiver, message) def getReceiver(self): ''' ...
8 ''' Created on 22 apr 2017 @author: Andrea Montanari This is class manages a r-message ''' import sys, os sys.path.append(os.path.abspath('../Graph/')) sys.path.append(os.path.abspath('../messages/')) from Message import Message class MessageR(Message):
64
64
179
6
57
utkarshjp7/Multi_Robot_Task_Allocation
catkin_ws/src/mrta/src/DCOP/messages/MessageR.py
Python
MessageR
MessageR
19
53
19
20
16955b3c507bbe7966322f02004e9c042bda63da
bigcode/the-stack
train
cf247c9f8abf1fcbff89c566
train
function
def find_library_nt(name): # modified from ctypes.util # ctypes.util.find_library just returns first result he found # but we want to try them all # because on Windows, users may have both 32bit and 64bit version installed results = [] for directory in os.environ['PATH'].split(os.pathsep): ...
def find_library_nt(name): # modified from ctypes.util # ctypes.util.find_library just returns first result he found # but we want to try them all # because on Windows, users may have both 32bit and 64bit version installed
results = [] for directory in os.environ['PATH'].split(os.pathsep): fname = os.path.join(directory, name) if os.path.isfile(fname): results.append(fname) if fname.lower().endswith(".dll"): continue fname += ".dll" if os.path.isfile(fname): ...
_statement import os import logging def find_library_nt(name): # modified from ctypes.util # ctypes.util.find_library just returns first result he found # but we want to try them all # because on Windows, users may have both 32bit and 64bit version installed
64
64
131
56
7
plus1s/shadowsocks-py-mu
shadowsocks/crypto/util.py
Python
find_library_nt
find_library_nt
24
39
24
28
25188a54e8f1b1f7fbf86327bd3fab82570d27c1
bigcode/the-stack
train
49c23ee93a1646dbd106490a
train
function
def test_find_library(): assert find_library('c', 'strcpy', 'libc') is not None assert find_library(['c'], 'strcpy', 'libc') is not None assert find_library(('c',), 'strcpy', 'libc') is not None assert find_library(('crypto', 'eay32'), 'EVP_CipherUpdate', 'libcrypto') is not None...
def test_find_library():
assert find_library('c', 'strcpy', 'libc') is not None assert find_library(['c'], 'strcpy', 'libc') is not None assert find_library(('c',), 'strcpy', 'libc') is not None assert find_library(('crypto', 'eay32'), 'EVP_CipherUpdate', 'libcrypto') is not None assert find_library(...
= len(c) plain_results.append(decipher.decrypt_once(c)) pos += l end = time.time() print('speed: %d bytes/s' % (block_size * rounds / (end - start))) assert b''.join(plain_results) == plain def test_find_library():
64
64
164
5
58
plus1s/shadowsocks-py-mu
shadowsocks/crypto/util.py
Python
test_find_library
test_find_library
140
149
140
140
e028a61f235d89a7d8fdf9769770e3336be1540f
bigcode/the-stack
train
838251362eb9f4050433bdde
train
function
def run_cipher(cipher, decipher): from os import urandom import random import time block_size = 16384 rounds = 1 * 1024 plain = urandom(block_size * rounds) cipher_results = [] pos = 0 print('test start') start = time.time() while pos < len(plain): l = random.randin...
def run_cipher(cipher, decipher):
from os import urandom import random import time block_size = 16384 rounds = 1 * 1024 plain = urandom(block_size * rounds) cipher_results = [] pos = 0 print('test start') start = time.time() while pos < len(plain): l = random.randint(100, 32768) # print(pos,...
-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[hyphen:] return None def run_cipher(cipher, decipher):
68
68
227
7
60
plus1s/shadowsocks-py-mu
shadowsocks/crypto/util.py
Python
run_cipher
run_cipher
108
137
108
108
0fc8b910c7f171bd6c3bdcdd67713a155526cce5
bigcode/the-stack
train
5e824d73c41c952532f3d7c4
train
function
def parse_mode(cipher_nme): """ Parse the cipher mode from cipher name e.g. aes-128-gcm, the mode is gcm :param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[h...
def parse_mode(cipher_nme):
""" Parse the cipher mode from cipher name e.g. aes-128-gcm, the mode is gcm :param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[hyphen:] return None
_symbol): logging.info('loading %s from %s', library_name, path) return lib else: logging.warn('can\'t find symbol %s in %s', search_symbol, path) except Exception: pass return None def parse_mode(cipher_nme...
64
64
107
7
56
plus1s/shadowsocks-py-mu
shadowsocks/crypto/util.py
Python
parse_mode
parse_mode
95
105
95
95
35a61b8c30d7efdaae4f162dff3df0d601622072
bigcode/the-stack
train
1ba221284a0a3b4fb3d82b76
train
function
def find_library(possible_lib_names, search_symbol, library_name): import ctypes.util from ctypes import CDLL paths = [] if type(possible_lib_names) not in (list, tuple): possible_lib_names = [possible_lib_names] lib_names = [] for lib_name in possible_lib_names: lib_names.app...
def find_library(possible_lib_names, search_symbol, library_name):
import ctypes.util from ctypes import CDLL paths = [] if type(possible_lib_names) not in (list, tuple): possible_lib_names = [possible_lib_names] lib_names = [] for lib_name in possible_lib_names: lib_names.append(lib_name) lib_names.append('lib' + lib_name) for n...
32bit and 64bit version installed results = [] for directory in os.environ['PATH'].split(os.pathsep): fname = os.path.join(directory, name) if os.path.isfile(fname): results.append(fname) if fname.lower().endswith(".dll"): continue fname += ".dll" ...
99
99
332
14
84
plus1s/shadowsocks-py-mu
shadowsocks/crypto/util.py
Python
find_library
find_library
42
92
42
42
6138d3cd108551a46705d2a0336650b91fac3afd
bigcode/the-stack
train
06507fa46fc071a8ba2ab618
train
class
class Piece(): def __init__(self): self.avatar = None self.direction = None self.boardRow = self.boardColumn = None self.x = self.y = 0 self.isKing = False def move(self,): pass
class Piece():
def __init__(self): self.avatar = None self.direction = None self.boardRow = self.boardColumn = None self.x = self.y = 0 self.isKing = False def move(self,): pass
class Piece():
3
64
58
3
0
Glenn-Po/Checkers
piece.py
Python
Piece
Piece
1
13
1
1
a6996c550f7f86efaad33dbfa3c1e637a8e3f695
bigcode/the-stack
train
2c3c0be62c8949240e9d0831
train
class
class LimitNumber(CloudFormationLintRule): """Check if maximum Mapping limit is exceeded""" id = 'E7010' shortdesc = 'Mapping limit not exceeded' description = 'Check the number of Mappings in the template is less ' \ 'than the upper limit' source_url = 'https://docs.aws.amazon.com...
class LimitNumber(CloudFormationLintRule):
"""Check if maximum Mapping limit is exceeded""" id = 'E7010' shortdesc = 'Mapping limit not exceeded' description = 'Check the number of Mappings in the template is less ' \ 'than the upper limit' source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudfo...
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch from cfnlint.helpers import LIMITS class LimitNumber(CloudFormationLintRule):
64
64
198
9
54
KeyCore/cfn-python-lint
src/cfnlint/rules/mappings/LimitNumber.py
Python
LimitNumber
LimitNumber
22
42
22
22
2b68fa5e13af6c82b7800fe8e1879b9260aab460
bigcode/the-stack
train
83e95cb81202183ca949d6e2
train
class
class MaskRCNNMapper(FasterRCNNMapper): ''' Maps mmdetection state dict to torchvision model. ''' def m_to_t(self, k): tokens = k.split('.') if 'mask_head.convs' in k: return self.dotty('roi_heads.mask_head.mask_fcn' + str(1+int(tokens[-3])), tokens[-1]) elif 'ma...
class MaskRCNNMapper(FasterRCNNMapper):
''' Maps mmdetection state dict to torchvision model. ''' def m_to_t(self, k): tokens = k.split('.') if 'mask_head.convs' in k: return self.dotty('roi_heads.mask_head.mask_fcn' + str(1+int(tokens[-3])), tokens[-1]) elif 'mask_head.upsample' in k: retu...
detect(self, image): assert isinstance(image, str) or isinstance(image, Image.Image) image = Image.open(image) if isinstance(image, str) else image transform = transforms.ToTensor() return self(transform(image).unsqueeze(0)) class MaskRCNNMapper(FasterRCNNMapper):
64
64
155
11
53
codexponent/smd
models/detectors/maskrcnn.py
Python
MaskRCNNMapper
MaskRCNNMapper
26
40
26
26
69cef31adb989915c91e9fa8c76cc53942105b35
bigcode/the-stack
train
01af35ad17756220fd6ace81
train
class
class MaskRCNN(mask_rcnn.MaskRCNN): ''' For MaskRCNN we simply use torchvision implementation with weight transformation from mmdetection. ''' def __init__(self, backbone, num_classes): super().__init__(backbone, num_classes) def detect(self, image): assert isinstance...
class MaskRCNN(mask_rcnn.MaskRCNN):
''' For MaskRCNN we simply use torchvision implementation with weight transformation from mmdetection. ''' def __init__(self, backbone, num_classes): super().__init__(backbone, num_classes) def detect(self, image): assert isinstance(image, str) or isinstance(image, Im...
import torchvision import torchvision.models.detection.mask_rcnn as mask_rcnn import torchvision.transforms as transforms from PIL import Image from ..transforms import transform, scale_factor, scale_size from .fasterrcnn import FasterRCNNMapper class MaskRCNN(mask_rcnn.MaskRCNN):
64
64
114
11
52
codexponent/smd
models/detectors/maskrcnn.py
Python
MaskRCNN
MaskRCNN
10
23
10
10
90c5f4829a8d64ed8fc31d9f7cd74eef1cf79c64
bigcode/the-stack
train
6a79bbb406b8d32827b55c5c
train
function
def string_to_list(string): #This function pulls apart a character a character string into list components. list_result = list(string.split(";")) return list_result
def string_to_list(string): #This function pulls apart a character a character string into list components.
list_result = list(string.split(";")) return list_result
# -*- coding: utf-8 -*- import numpy as np import ast import pandas as pd import pymysql.cursors import json #Functions def string_to_list(string): #This function pulls apart a character a character string into list components.
54
64
35
21
32
Meluiscruz/Tuxedo_WebScrapper_Farmacias
Tuxedo_5_Simi/Insert_to_database_Tx5.py
Python
string_to_list
string_to_list
10
12
10
10
b25684dc2311dbf6422c085d70a163d248ba5193
bigcode/the-stack
train
49acbfcf6c07f28024ee82f0
train
function
def run_s3_test(): """run_s3_test Run the S3 verification test """ access_key = os.getenv( 'S3_ACCESS_KEY', 'trexaccesskey') secret_key = os.getenv( 'S3_SECRET_KEY', 'trex123321') region_name = os.getenv( 'S3_REGION_NAME' 'us-east-1') service_...
def run_s3_test():
"""run_s3_test Run the S3 verification test """ access_key = os.getenv( 'S3_ACCESS_KEY', 'trexaccesskey') secret_key = os.getenv( 'S3_SECRET_KEY', 'trex123321') region_name = os.getenv( 'S3_REGION_NAME' 'us-east-1') service_address = os.getenv...
#!/usr/bin/env python """ S3 verification tool """ import os import sys import boto3 import datetime def run_s3_test():
32
201
672
6
25
govinr/kube-deploy
minio/run_s3_test.py
Python
run_s3_test
run_s3_test
13
115
13
13
88ec6f45a3cc4a8908c37cadb44ab8c1510fdba0
bigcode/the-stack
train
2470f4e49f6eed28cea1eb38
train
function
def test_jims_example2(): example1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5]) example2 = ak._v2.Array( [ {"x": [1.1, 1.2, 1.3]}, {"x": [2.2, 2.21]}, {"x": [3.3]}, {"x": [4.4, 4.41, 4.42, 4.44]}, {"x": [5.5]}, ] ) data_frame = ak...
def test_jims_example2():
example1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5]) example2 = ak._v2.Array( [ {"x": [1.1, 1.2, 1.3]}, {"x": [2.2, 2.21]}, {"x": [3.3]}, {"x": [4.4, 4.41, 4.42, 4.44]}, {"x": [5.5]}, ] ) data_frame = ak._v2.operations.to_rdatafr...
== {"some_array", "y"} cpp_list = ", ".join(str(e) for e in array.x.to_list()) done = compiler( f""" int i_y1 = 0; double y1_val[5] = {{ {cpp_list} }}; template<typename T> struct MyFunctorY_1 {{ void operator()(T const& y) {{ R__ASSERT(y =...
149
150
502
7
142
jpivarski/awkward-1.0
tests/v2/test_1374-to-rdataframe.py
Python
test_jims_example2
test_jims_example2
223
278
223
223
777e27ee5e2b869febab8ef7539ab2f33d7cee76
bigcode/the-stack
train
1d7775d314bfd4f4f60f575f
train
function
def test_two_columns(): array = ak._v2.Array( [ [{"x": 1, "y": [1.1]}, {"x": 2, "y": [2.2, 0.2]}], [], [{"x": 3, "y": [3.0, 0.3, 3.3]}], ] ) ak_array_1 = array["x"] ak_array_2 = array["y"] data_frame = ak._v2.to_rdataframe( {"x": ak_array_1...
def test_two_columns():
array = ak._v2.Array( [ [{"x": 1, "y": [1.1]}, {"x": 2, "y": [2.2, 0.2]}], [], [{"x": 3, "y": [3.0, 0.3, 3.3]}], ] ) ak_array_1 = array["x"] ak_array_2 = array["y"] data_frame = ak._v2.to_rdataframe( {"x": ak_array_1, "y": ak_array_2}, flat...
import awkward as ak # noqa: F401 import awkward._v2._lookup # noqa: E402 import awkward._v2._connect.cling # noqa: E402 ROOT = pytest.importorskip("ROOT") compiler = ROOT.gInterpreter.Declare def test_two_columns():
64
64
200
5
58
jpivarski/awkward-1.0
tests/v2/test_1374-to-rdataframe.py
Python
test_two_columns
test_two_columns
16
31
16
16
98b0c4cff8a59b6f1fd8284ec9c69da3dc2abc46
bigcode/the-stack
train
991e8739b4f711686cbf9a66
train
function
def test_two_columns_as_rvecs(): ak_array_1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5]) ak_array_2 = ak._v2.Array( [{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}] ) data_frame = ak._v2.to_rdataframe({"x": ak_array_1, "y": ak_array_2}) assert set(data_frame.GetColumnNames()) == {"...
def test_two_columns_as_rvecs():
ak_array_1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5]) ak_array_2 = ak._v2.Array( [{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}] ) data_frame = ak._v2.to_rdataframe({"x": ak_array_1, "y": ak_array_2}) assert set(data_frame.GetColumnNames()) == {"x", "y"} assert data_frame.Ge...
_1 = array["x"] ak_array_2 = array["y"] data_frame = ak._v2.to_rdataframe( {"x": ak_array_1, "y": ak_array_2}, flatlist_as_rvec=True ) assert set(data_frame.GetColumnNames()) == {"x", "y"} assert data_frame.GetColumnType("x") == "ROOT::VecOps::RVec<int64_t>" assert data_frame.GetColumnTy...
123
123
411
9
114
jpivarski/awkward-1.0
tests/v2/test_1374-to-rdataframe.py
Python
test_two_columns_as_rvecs
test_two_columns_as_rvecs
34
77
34
34
7a1d35c36afcc890152fc8378e250a1366917c31
bigcode/the-stack
train