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
1d938643f65b54f7f885c268
train
class
class TestVagrantBaseBoxes(TestCase): def test_vagrant_base_boxes(self): with patch('burlap.vagrant.vagrant._box_list') as mock_list: mock_list.return_value = [ ('lucid32', 'virtualbox'), ('precise64', 'virtualbox'), ] from burlap.vagrant ...
class TestVagrantBaseBoxes(TestCase):
def test_vagrant_base_boxes(self): with patch('burlap.vagrant.vagrant._box_list') as mock_list: mock_list.return_value = [ ('lucid32', 'virtualbox'), ('precise64', 'virtualbox'), ] from burlap.vagrant import vagrant self.assertE...
") from burlap.vagrant import vagrant res = vagrant._box_list_human_readable() self.assertEqual(res, [ # ('lucid32', 'virtualbox'), ('precise64', 'virtualbox'), ]) class TestVagrantBaseBoxes(TestCase):
63
64
95
9
54
tutordelphia/burlap
burlap/tests/test_vagrant_base_boxes.py
Python
TestVagrantBaseBoxes
TestVagrantBaseBoxes
55
64
55
56
5589e508d42030563b93ed062b9a621a8869720c
bigcode/the-stack
train
0bf72fe9bc7abdd28389c945
train
function
def get_json_builder(obj): """Instantiate or retrieve a JSON representation builder for the given object. """ if type(obj) is type: cls = obj else: cls = obj.__class__ # Lookup the builder instance in the builder module builder = getattr(ggrc.builder, cls.__name__, None) if not builder: # Cr...
def get_json_builder(obj):
"""Instantiate or retrieve a JSON representation builder for the given object. """ if type(obj) is type: cls = obj else: cls = obj.__class__ # Lookup the builder instance in the builder module builder = getattr(ggrc.builder, cls.__name__, None) if not builder: # Create the builder and cache ...
RelationshipProperty from werkzeug.exceptions import BadRequest """JSON resource state representation handler for gGRC models.""" def view_url_for(obj): view = getattr(ggrc.views, obj.__class__.__name__, None) return view.url_for(obj) if view else None def get_json_builder(obj):
64
64
114
6
57
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
get_json_builder
get_json_builder
25
39
25
25
b45d11fb8eaf1c817508a979e6d748af169cb619
bigcode/the-stack
train
386fc05bd359c659dced80c7
train
function
def publish(obj, inclusions=()): """Translate ``obj`` into a valid JSON value. Objects with properties are translated into a ``dict`` object representing a JSON object while simple values are returned unchanged or specially formatted if needed. """ publisher = get_json_builder(obj) if publisher and hasattr(...
def publish(obj, inclusions=()):
"""Translate ``obj`` into a valid JSON value. Objects with properties are translated into a ``dict`` object representing a JSON object while simple values are returned unchanged or specially formatted if needed. """ publisher = get_json_builder(obj) if publisher and hasattr(publisher, '_publish_attrs') \ ...
builder = getattr(ggrc.builder, cls.__name__, None) if not builder: # Create the builder and cache it in the builder module builder = Builder(cls) setattr(ggrc.builder, cls.__name__, builder) return builder def publish(obj, inclusions=()):
64
64
165
8
55
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
publish
publish
41
59
41
41
fc4e15d6fe691a208383519a3e27962000b12c14
bigcode/the-stack
train
57f2ed4db40d3249b6d9e11d
train
class
class UpdateAttrHandler(object): """Performs the translation of a JSON state representation into update actions performed on a model object instance. """ @classmethod def do_update_attr(cls, obj, json_obj, attr): """Perform the update to ``obj`` required to make the attribute attr equivalent in ``obj`...
class UpdateAttrHandler(object):
"""Performs the translation of a JSON state representation into update actions performed on a model object instance. """ @classmethod def do_update_attr(cls, obj, json_obj, attr): """Perform the update to ``obj`` required to make the attribute attr equivalent in ``obj`` and ``json_obj``. """ i...
self_url: ret['selfLink'] = self_url view_url = view_url_for(obj) if view_url: ret['viewLink'] = view_url ret.update(publisher.publish_contribution(obj, inclusions)) return ret # Otherwise, just return the value itself by default return obj def update(obj, json_obj): """Translate the...
256
256
1,119
6
250
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
UpdateAttrHandler
UpdateAttrHandler
82
201
82
82
9891a0b9b91ebecc53ac5f3e9fa7e65f456f2394
bigcode/the-stack
train
e79b1fb5253b2be28527897a
train
class
class Builder(AttributeInfo): """JSON Dictionary builder for ggrc.models.* objects and their mixins.""" def generate_link_object_for(self, obj, inclusions, include): """Generate a link object for this object. If there are property paths to be included specified in the ``inclusions`` parameter, those proper...
class Builder(AttributeInfo):
"""JSON Dictionary builder for ggrc.models.* objects and their mixins.""" def generate_link_object_for(self, obj, inclusions, include): """Generate a link object for this object. If there are property paths to be included specified in the ``inclusions`` parameter, those properties will be added to the ...
attr_name, class_attr.property.uselist) @classmethod def AssociationProxy(cls, obj, json_obj, attr_name, class_attr): """Translate the JSON value for an ``AssociationProxy``.""" rel_class = class_attr.remote_attr.property.mapper.class_ return cls.query_for(rel_class, json_obj, attr_name, True) @cla...
256
256
1,121
5
250
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
Builder
Builder
203
324
203
203
dd778f648eaa3ca540ed06968827a1d94e376f23
bigcode/the-stack
train
21812268ba3d1a0c420fcd62
train
function
def create(obj, json_obj): """Translate the state represented by ``json_obj`` into update actions performed upon the new model object ``obj``. After performing the update ``obj`` and ``json_obj`` should be equivalent representations of the model state. """ creator = get_json_builder(obj) if creator: c...
def create(obj, json_obj):
"""Translate the state represented by ``json_obj`` into update actions performed upon the new model object ``obj``. After performing the update ``obj`` and ``json_obj`` should be equivalent representations of the model state. """ creator = get_json_builder(obj) if creator: creator.create(obj, json_obj...
json_obj`` should be equivalent representations of the model state. """ updater = get_json_builder(obj) if updater: updater.update(obj, json_obj) #FIXME what to do if no updater?? #Nothing, perhaps log, assume omitted by design def create(obj, json_obj):
64
64
80
7
56
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
create
create
72
80
72
72
5e5391ff626b300786775a17996c690860da22df
bigcode/the-stack
train
cb2a73fa515ce98f9a6adbbd
train
function
def view_url_for(obj): view = getattr(ggrc.views, obj.__class__.__name__, None) return view.url_for(obj) if view else None
def view_url_for(obj):
view = getattr(ggrc.views, obj.__class__.__name__, None) return view.url_for(obj) if view else None
from ggrc.services.util import url_for from sqlalchemy.ext.associationproxy import AssociationProxy from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.orm.properties import RelationshipProperty from werkzeug.exceptions import BadRequest """JSON resource state representation handler for gGRC m...
64
64
35
6
58
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
view_url_for
view_url_for
21
23
21
21
65aa664658a9f6e1cf31a7afe413b82b459f50bd
bigcode/the-stack
train
3d120e3c21fa725c0fc7c20d
train
function
def update(obj, json_obj): """Translate the state represented by ``json_obj`` into update actions performed upon the model object ``obj``. After performing the update ``obj`` and ``json_obj`` should be equivalent representations of the model state. """ updater = get_json_builder(obj) if updater: updater...
def update(obj, json_obj):
"""Translate the state represented by ``json_obj`` into update actions performed upon the model object ``obj``. After performing the update ``obj`` and ``json_obj`` should be equivalent representations of the model state. """ updater = get_json_builder(obj) if updater: updater.update(obj, json_obj)
view_url = view_url_for(obj) if view_url: ret['viewLink'] = view_url ret.update(publisher.publish_contribution(obj, inclusions)) return ret # Otherwise, just return the value itself by default return obj def update(obj, json_obj):
64
64
77
7
56
alaeddine10/ggrc-core
src/ggrc/builder/json.py
Python
update
update
61
68
61
61
3986915ecb1d0d459a262a5e72e0f9054c25f964
bigcode/the-stack
train
0913bf6bd0b23f4f76eacd86
train
function
def test_fetch_rcv1(): try: data1 = fetch_rcv1(shuffle=False, download_if_missing=False) except IOError as e: if e.errno == errno.ENOENT: raise SkipTest("Download RCV1 dataset to run this test.") X1, Y1 = data1.data, data1.target cat_list, s1 = data1.target_names.tolist(), d...
def test_fetch_rcv1():
try: data1 = fetch_rcv1(shuffle=False, download_if_missing=False) except IOError as e: if e.errno == errno.ENOENT: raise SkipTest("Download RCV1 dataset to run this test.") X1, Y1 = data1.data, data1.target cat_list, s1 = data1.target_names.tolist(), data1.sample_id # t...
"""Test the rcv1 loader. Skipped if rcv1 is not already downloaded to data_home. """ import errno import scipy.sparse as sp import numpy as np from functools import partial from sklearn.datasets import fetch_rcv1 from sklearn.datasets.tests.test_common import check_return_X_y from sklearn.utils.testing import assert_...
113
183
610
7
105
OlegMoiseev/introduction-to-ml
venv/lib/python3.7/site-packages/sklearn/datasets/tests/test_rcv1.py
Python
test_fetch_rcv1
test_fetch_rcv1
19
78
19
19
9018f4e6a18fced5dc42c19ff87bc8a406720b88
bigcode/the-stack
train
1104aeb737db6e966042cb02
train
class
class Client(QWebPage): def __init__(self,url): self.app = QApplication(sys.argv) #starting the application QWebPage.__init__(self) self.loadFinished.connect(self.on_page_load) #connecting method when method is finished -> Could work directly with webpage object self...
class Client(QWebPage):
def __init__(self,url): self.app = QApplication(sys.argv) #starting the application QWebPage.__init__(self) self.loadFinished.connect(self.on_page_load) #connecting method when method is finished -> Could work directly with webpage object self.mainFrame().load(QUrl(ur...
import sys #QT is system arguments from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage import bs4 as bs import urllib.request class Client(QWebPage):
58
64
92
6
51
jjohn50/Python3-by-practice
Training Modules/03 Regex/Parser using NLP/Web_scraping_Dynamic_Javascript_Scraping_DOES_NOT_WORK.py
Python
Client
Client
10
22
10
11
858dcbf0abada9bdf1873aeb5bebc9c6a5258082
bigcode/the-stack
train
e08a51f5f97c5325294fce45
train
function
def mass_metadata(config, library): logger.info("") util.separator(f"Mass Editing {'Movie' if library.is_movie else 'Show'} Library: {library.name}") logger.info("") radarr_adds = [] sonarr_adds = [] items = library.Plex.all() for i, item in enumerate(items, 1): util.print_return(f"P...
def mass_metadata(config, library):
logger.info("") util.separator(f"Mass Editing {'Movie' if library.is_movie else 'Show'} Library: {library.name}") logger.info("") radarr_adds = [] sonarr_adds = [] items = library.Plex.all() for i, item in enumerate(items, 1): util.print_return(f"Processing: {i}/{len(items)} {item.ti...
library_handler = logging.handlers.RotatingFileHandler(col_file_logger, mode="w", backupCount=3, encoding="utf-8") util.apply_formatter(library_handler) logger.addHandler(library_handler) library_handler.addFilter(fmt_filter) os.environ["PLEXAPI_PLEXAPI_T...
256
256
1,215
7
249
ItsCinnabar/Plex-Meta-Manager
plex_meta_manager.py
Python
mass_metadata
mass_metadata
247
356
247
247
70997fbac7afeee9d33a77af8881203c6c9615a8
bigcode/the-stack
train
ed4ced4efb28d02f8b73412d
train
function
def fmt_filter(record): record.levelname = f"[{record.levelname}]" record.filename = f"[{record.filename}:{record.lineno}]" return True
def fmt_filter(record):
record.levelname = f"[{record.levelname}]" record.filename = f"[{record.filename}:{record.lineno}]" return True
"config.yml")): raise util.Failed(f"Config Error: config not found at {os.path.abspath(default_dir)}") os.makedirs(os.path.join(default_dir, "logs"), exist_ok=True) logger = logging.getLogger("Plex Meta Manager") logger.setLevel(logging.DEBUG) def fmt_filter(record):
64
64
37
5
59
ItsCinnabar/Plex-Meta-Manager
plex_meta_manager.py
Python
fmt_filter
fmt_filter
79
82
79
79
28e3e6bc92daeb1bcfb5e19542954be3e14f9ad7
bigcode/the-stack
train
384bd640ae87cc0fceaf1727
train
function
def update_libraries(config): for library in config.libraries: os.makedirs(os.path.join(default_dir, "logs", library.mapping_name, "collections"), exist_ok=True) col_file_logger = os.path.join(default_dir, "logs", library.mapping_name, "library.log") should_roll_over = os.path.isfile(col_fil...
def update_libraries(config):
for library in config.libraries: os.makedirs(os.path.join(default_dir, "logs", library.mapping_name, "collections"), exist_ok=True) col_file_logger = os.path.join(default_dir, "logs", library.mapping_name, "library.log") should_roll_over = os.path.isfile(col_file_logger) library_hand...
")) logger.info(util.centered(" |___/ ")) logger.info(util.centered(" Version: 1.10.0 ")) if time_scheduled: start_type = f"{time_scheduled} " e...
256
256
1,072
6
250
ItsCinnabar/Plex-Meta-Manager
plex_meta_manager.py
Python
update_libraries
update_libraries
130
245
130
130
5603cd1a2b5f510213b7753d7f9215ee7fea1841
bigcode/the-stack
train
f063144f7a698563bc2abd8a
train
function
def start(config_path, is_test=False, time_scheduled=None, requested_collections=None, requested_libraries=None, resume_from=None): file_logger = os.path.join(default_dir, "logs", "meta.log") should_roll_over = os.path.isfile(file_logger) file_handler = logging.handlers.RotatingFileHandler(file_logger, dela...
def start(config_path, is_test=False, time_scheduled=None, requested_collections=None, requested_libraries=None, resume_from=None):
file_logger = os.path.join(default_dir, "logs", "meta.log") should_roll_over = os.path.isfile(file_logger) file_handler = logging.handlers.RotatingFileHandler(file_logger, delay=True, mode="w", backupCount=10, encoding="utf-8") util.apply_formatter(file_handler) file_handler.addFilter(fmt_filter) ...
found at {os.path.abspath(config_file)}") elif not os.path.exists(os.path.join(default_dir, "config.yml")): raise util.Failed(f"Config Error: config not found at {os.path.abspath(default_dir)}") os.makedirs(os.path.join(default_dir, "logs"), exist_ok=True) logger = logging.getLogger("Plex Meta Manager") logger.set...
183
183
613
28
154
ItsCinnabar/Plex-Meta-Manager
plex_meta_manager.py
Python
start
start
91
128
91
91
805cdb7016f7a0744b1faf7ead132da9056a6063
bigcode/the-stack
train
caa9531a9017116a5e286f32
train
function
def run_collection(config, library, metadata, requested_collections): logger.info("") for mapping_name, collection_attrs in requested_collections.items(): collection_start = datetime.now() if config.test_mode and ("test" not in collection_attrs or collection_attrs["test"] is not True): ...
def run_collection(config, library, metadata, requested_collections):
logger.info("") for mapping_name, collection_attrs in requested_collections.items(): collection_start = datetime.now() if config.test_mode and ("test" not in collection_attrs or collection_attrs["test"] is not True): no_template_test = True if "template" in collection_att...
(util.adjust_space(f"{item.title[:25]:<25} | No Rating Found")) else: if library.mass_audience_rating_update and str(item.audienceRating) != str(new_rating): library.edit_query(item, {"audienceRating.value": new_rating, "audienceRating.locked": 1}) ...
256
256
955
13
243
ItsCinnabar/Plex-Meta-Manager
plex_meta_manager.py
Python
run_collection
run_collection
358
466
358
358
437830415f78ef7a0c1b815c94c67766d8f6d127
bigcode/the-stack
train
3c07051ed5b22b60a60fe03c
train
function
def check_bool(env_str, default): env_var = os.environ.get(env_str) if env_var is not None: if env_var is True or env_var is False: return env_var elif env_var.lower() in ["t", "true"]: return True else: return False else: return default
def check_bool(env_str, default):
env_var = os.environ.get(env_str) if env_var is not None: if env_var is True or env_var is False: return env_var elif env_var.lower() in ["t", "true"]: return True else: return False else: return default
", help="Character that divides the sections (Default: '=')", default="=", type=str) parser.add_argument("-w", "--width", dest="width", help="Screen Width (Default: 100)", default=100, type=int) args = parser.parse_args() def check_bool(env_str, default):
64
64
74
8
56
ItsCinnabar/Plex-Meta-Manager
plex_meta_manager.py
Python
check_bool
check_bool
33
43
33
33
f8111c50a8758738d46e2da9cc7faf3e36ff7dca
bigcode/the-stack
train
723061c44836c994bca96719
train
class
class Button(ElementBase): def click(self): self._behavior.click(self.locator)
class Button(ElementBase):
def click(self): self._behavior.click(self.locator)
from common.elements.element_base import ElementBase class Button(ElementBase):
14
64
19
5
8
bobjiangps/python3_test_framework
common/elements/button.py
Python
Button
Button
4
7
4
5
e7e09d90191dddae14805595bf9b3301f072535e
bigcode/the-stack
train
66415f5eb9f07fc88aa13170
train
class
class ADF(logfileparser.Logfile): """An ADF log file""" def __init__(self, *args, **kwargs): # Call the __init__ method of the superclass super(ADF, self).__init__(logname="ADF", *args, **kwargs) def __str__(self): """Return a string representation of the object.""" ...
class ADF(logfileparser.Logfile):
"""An ADF log file""" def __init__(self, *args, **kwargs): # Call the __init__ method of the superclass super(ADF, self).__init__(logname="ADF", *args, **kwargs) def __str__(self): """Return a string representation of the object.""" return "ADF log file %s" % (sel...
## -*- coding: utf-8 -*- # # Copyright (c) 2017, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """Parser for ADF output files""" from __future__ import print_function import itertools import re impor...
112
256
11,404
9
102
alesgenova/cclib
cclib/parser/adfparser.py
Python
ADF
ADF
21
1,172
21
21
d5c2ff401a611b956f1b49d7f264cc88448fdde9
bigcode/the-stack
train
947bdd915ee9d16db32a6597
train
class
class StringArray(PandasArray): """ Extension array for string data. .. versionadded:: 1.0.0 .. warning:: StringArray is considered experimental. The implementation and parts of the API may change without warning. In particular, the NA value used may change to no longer be ...
class StringArray(PandasArray):
""" Extension array for string data. .. versionadded:: 1.0.0 .. warning:: StringArray is considered experimental. The implementation and parts of the API may change without warning. In particular, the NA value used may change to no longer be ``numpy.nan``. Parameters...
@property def type(self) -> Type: return str @property def name(self) -> str: """ The alias for StringDtype is ``'string'``. """ return "string" @classmethod def construct_from_string(cls, string: str) -> ExtensionDtype: if string == "string": ...
256
256
1,601
7
249
DorAmram/pandas
pandas/core/arrays/string_.py
Python
StringArray
StringArray
96
318
96
96
d9a5f097a03fb82fff8f0277bc05f45851256955
bigcode/the-stack
train
7597e31f6ca5736d56bbae6d
train
class
@register_extension_dtype class StringDtype(ExtensionDtype): """ Extension dtype for string data. .. versionadded:: 1.0.0 .. warning:: StringDtype is considered experimental. The implementation and parts of the API may change without warning. In particular, StringDtype.na_value ...
@register_extension_dtype class StringDtype(ExtensionDtype):
""" Extension dtype for string data. .. versionadded:: 1.0.0 .. warning:: StringDtype is considered experimental. The implementation and parts of the API may change without warning. In particular, StringDtype.na_value may change to no longer be ``numpy.nan``. Attribu...
from pandas.core.dtypes.base import ExtensionDtype from pandas.core.dtypes.common import pandas_dtype from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries from pandas.core.dtypes.inference import is_array_like from pandas import co...
116
116
387
14
101
DorAmram/pandas
pandas/core/arrays/string_.py
Python
StringDtype
StringDtype
21
93
21
22
8e1b9599b7cd4e655d079d28e8b028311e21971a
bigcode/the-stack
train
ee8e9b369f6cda1e3c19854a
train
class
class _DatasetIterGE(_DatasetIter): """Iter for ge""" def __init__(self, dataset): super(_DatasetIterGE, self).__init__(dataset) self.loop_count = self.get_loop_count(dataset) parallel_mode = _get_parallel_mode() self.need_to_full = parallel_mode in (ParallelMode.SEMI_AUTO_PARALL...
class _DatasetIterGE(_DatasetIter):
"""Iter for ge""" def __init__(self, dataset): super(_DatasetIterGE, self).__init__(dataset) self.loop_count = self.get_loop_count(dataset) parallel_mode = _get_parallel_mode() self.need_to_full = parallel_mode in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL) ...
MS, self).__init__(dataset) self.loop_count = dataset.get_dataset_size() self.loop_size = 1 queue_name = dataset.__ME_INITED__ self.op = GetNextSingleOp(self.dataset_types, self.dataset_shapes, queue_name) class _DatasetIterGE(_DatasetIter):
64
64
146
9
55
huxiaoman7/mindspore
mindspore/train/dataset_helper.py
Python
_DatasetIterGE
_DatasetIterGE
138
152
138
138
db3adc2cc46f359b062f5f4fa3bfa17eaaf249b3
bigcode/the-stack
train
5795d9d6357141fa3f8e25d6
train
class
class _DatasetIterFeed: """Iter for feed data""" def __init__(self, dataset): self.dataset = dataset self.device_num = _get_device_num() self.global_rank = _get_global_rank() self.repeat_count = dataset.get_repeat_count() self.repeat_ind = 0 self.loop_count = data...
class _DatasetIterFeed:
"""Iter for feed data""" def __init__(self, dataset): self.dataset = dataset self.device_num = _get_device_num() self.global_rank = _get_global_rank() self.repeat_count = dataset.get_repeat_count() self.repeat_ind = 0 self.loop_count = dataset.get_dataset_size() ...
ALLEL) batch_expand_num = 1 if self.need_to_full: batch_expand_num = _get_device_num() tensor_list_run = _construct_tensor_list(self.dataset_types, self.dataset_shapes, batch_expand_num) def op(): return tensor_list_run self.op = op class _DatasetIterFeed...
71
71
237
6
64
huxiaoman7/mindspore
mindspore/train/dataset_helper.py
Python
_DatasetIterFeed
_DatasetIterFeed
155
184
155
155
3da154ffba48bef996e282ced43d64e2517891ec
bigcode/the-stack
train
4df18520a0baece76c96ff01
train
class
class _DatasetIter: """Base iter for dataset help""" def __init__(self, dataset): self.loop_size = 1 if not hasattr(dataset, '__ME_INITED__'): if not hasattr(dataset, '__loop_size__'): self.loop_size = dataset.get_dataset_size() else: self....
class _DatasetIter:
"""Base iter for dataset help""" def __init__(self, dataset): self.loop_size = 1 if not hasattr(dataset, '__ME_INITED__'): if not hasattr(dataset, '__loop_size__'): self.loop_size = dataset.get_dataset_size() else: self.loop_size = dataset....
"): if context.get_context("enable_loop_sink"): iterclass = _DatasetIterMSLoopSink else: iterclass = _DatasetIterMS self.iter = iterclass(dataset) def __iter__(self): return self.iter.__iter__() # A temp solution for loop sink. Delete la...
121
121
405
5
115
huxiaoman7/mindspore
mindspore/train/dataset_helper.py
Python
_DatasetIter
_DatasetIter
71
114
71
71
85bb44ccb4d96d162af3ed21199afdb3cff4c2db
bigcode/the-stack
train
e314cc05f4f9c51cd3a9b6c2
train
class
class _DatasetIterMS(_DatasetIter): """Iter for context (enable_loop_sink=False)""" def __init__(self, dataset): super(_DatasetIterMS, self).__init__(dataset) self.loop_count = dataset.get_dataset_size() self.loop_size = 1 queue_name = dataset.__ME_INITED__ self.op = GetN...
class _DatasetIterMS(_DatasetIter):
"""Iter for context (enable_loop_sink=False)""" def __init__(self, dataset): super(_DatasetIterMS, self).__init__(dataset) self.loop_count = dataset.get_dataset_size() self.loop_size = 1 queue_name = dataset.__ME_INITED__ self.op = GetNextSingleOp(self.dataset_types, self...
enable_loop_sink=True)""" def __init__(self, dataset): super(_DatasetIterMSLoopSink, self).__init__(dataset) self.loop_count = self.get_loop_count(dataset) def op(): return tuple() self.op = op class _DatasetIterMS(_DatasetIter):
64
64
90
9
54
huxiaoman7/mindspore
mindspore/train/dataset_helper.py
Python
_DatasetIterMS
_DatasetIterMS
128
135
128
128
3a3df79444189e1759da1963d36aa3665bc559d8
bigcode/the-stack
train
2f7421c7140db476bafcc738
train
class
class _DatasetIterMSLoopSink(_DatasetIter): """Iter for context (enable_loop_sink=True)""" def __init__(self, dataset): super(_DatasetIterMSLoopSink, self).__init__(dataset) self.loop_count = self.get_loop_count(dataset) def op(): return tuple() self.op = op
class _DatasetIterMSLoopSink(_DatasetIter):
"""Iter for context (enable_loop_sink=True)""" def __init__(self, dataset): super(_DatasetIterMSLoopSink, self).__init__(dataset) self.loop_count = self.get_loop_count(dataset) def op(): return tuple() self.op = op
loop_size != 0: raise ValueError(f'Dataset size {dataset.get_dataset_size()} and ' f'loop_size {loop_size} are not matched.') loop_count = int(dataset.get_dataset_size()/loop_size) return loop_count class _DatasetIterMSLoopSink(_DatasetIter):
64
64
72
11
52
huxiaoman7/mindspore
mindspore/train/dataset_helper.py
Python
_DatasetIterMSLoopSink
_DatasetIterMSLoopSink
117
125
117
117
1159244f508ed6af1c7999b29123f8964e144a4d
bigcode/the-stack
train
2c278419a28b19c1bcacf031
train
class
class DatasetHelper: """ Help function to use the Minddata dataset. According to different context, change the iter of dataset, to use the same for loop in different context. Note: The iter of DatasetHelper will give one epoch data. Args: dataset (DataSet): The dataset. da...
class DatasetHelper:
""" Help function to use the Minddata dataset. According to different context, change the iter of dataset, to use the same for loop in different context. Note: The iter of DatasetHelper will give one epoch data. Args: dataset (DataSet): The dataset. dataset_sink_mode (bool...
import check_bool from .. import context from .parallel_utils import ParallelMode from ._utils import _exec_datagraph, _get_types_and_shapes, _to_tensor, \ _construct_tensor_list, _to_full_shapes, _to_full_tensor from ..nn.wrap import GetNextSingleOp from ..parallel._utils import _get_device_num, _get_global_rank,...
89
89
297
4
84
huxiaoman7/mindspore
mindspore/train/dataset_helper.py
Python
DatasetHelper
DatasetHelper
25
68
25
25
f099b3fca43834b16338e5cbe8838a9ece67c189
bigcode/the-stack
train
9a0352ac369536bfa43bbd02
train
class
class RARIngestor(PackageSupport, Ingestor): MIME_TYPES = ["application/rar" "application/x-rar"] EXTENSIONS = ["rar"] SCORE = 4 def unpack(self, file_path, entity, temp_dir): # FIXME: need to figure out how to unpack multi-part files. try: with rarfile.RarFile(file_path.as_...
class RARIngestor(PackageSupport, Ingestor):
MIME_TYPES = ["application/rar" "application/x-rar"] EXTENSIONS = ["rar"] SCORE = 4 def unpack(self, file_path, entity, temp_dir): # FIXME: need to figure out how to unpack multi-part files. try: with rarfile.RarFile(file_path.as_posix()) as rf: names = rf.na...
import logging import rarfile from ingestors.ingestor import Ingestor from ingestors.support.package import PackageSupport from ingestors.exc import ProcessingException log = logging.getLogger(__name__) class RARIngestor(PackageSupport, Ingestor):
56
96
322
14
42
simonwoerpel/ingest-file
ingestors/packages/rar.py
Python
RARIngestor
RARIngestor
11
43
11
11
99564b80d373591a05b4efccb1a22e24025a0438
bigcode/the-stack
train
6a0df453b2ae952eead446bc
train
class
class AlexNetModel(kserve.KFModel): def __init__(self, name: str): super().__init__(name) self.name = name self.load() def load(self): model = models.alexnet(pretrained=True) model.eval() self.model = model self.ready = True def predict(self, request...
class AlexNetModel(kserve.KFModel):
def __init__(self, name: str): super().__init__(name) self.name = name self.load() def load(self): model = models.alexnet(pretrained=True) model.eval() self.model = model self.ready = True def predict(self, request: Dict) -> Dict: inputs = re...
the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import kserve from torchvision import models, transforms from typing import Dict import torc...
85
85
286
10
74
Suresh-Nakkeran/kserve
python/custom_model/model.py
Python
AlexNetModel
AlexNetModel
24
63
24
24
52a0281bfdc38e7cce9883f193e4e63e62f39100
bigcode/the-stack
train
996362a925b8bc0b53e837ee
train
class
class AST_Matrix_Row(AST_Node): def __init__(self, context, elements): AST_Node.__init__(self, context) self.elements = elements if not isinstance(self.elements, list): raise ValueError( "AST_Matrix_Row() expects a list of elements, got " + str(typ...
class AST_Matrix_Row(AST_Node):
def __init__(self, context, elements): AST_Node.__init__(self, context) self.elements = elements if not isinstance(self.elements, list): raise ValueError( "AST_Matrix_Row() expects a list of elements, got " + str(type(self.elements))) def prov...
from .ast_node import AST_Node from .ast_values import AST_Constant import dace class AST_Matrix_Row(AST_Node):
28
84
283
8
19
gronerl/dace
dace/frontend/octave/ast_matrix.py
Python
AST_Matrix_Row
AST_Matrix_Row
7
49
7
7
3be9ec05082fdc37ffd8aa40615ba5c4291fc795
bigcode/the-stack
train
27698dc524a50554ad65bbcc
train
class
class AST_Transpose(AST_Node): def __init__(self, context, arg, op): AST_Node.__init__(self, context) self.arg = arg self.op = op def __repr__(self): return "AST_Transpose(" + str(self.arg) + ", " + str(self.op) + ")" def get_children(self): return [self.arg] d...
class AST_Transpose(AST_Node):
def __init__(self, context, arg, op): AST_Node.__init__(self, context) self.arg = arg self.op = op def __repr__(self): return "AST_Transpose(" + str(self.arg) + ", " + str(self.op) + ")" def get_children(self): return [self.arg] def get_dims(self): dims...
out", mx, None, dace.memlet.Memlet.from_array(trans.data, trans.desc(sdfg))) sdfg.nodes()[state].add_edge( mx, None, trans, None, dace.memlet.Memlet.from_array(trans.data, trans.desc(sdfg))) print("The const expr " + str(self) + " will be stored i...
180
181
604
7
173
gronerl/dace
dace/frontend/octave/ast_matrix.py
Python
AST_Transpose
AST_Transpose
152
214
152
152
c4183c705e2b016d18e466cabafcbbc1b1a5db9f
bigcode/the-stack
train
96d86d73c810326f54c45fb0
train
class
class AST_Matrix(AST_Node): def __init__(self, context, rows): AST_Node.__init__(self, context) self.rows = rows self.children = self.rows if not isinstance(self.rows, list): raise ValueError("AST_Matrix() expects a list of rows, got " + str(t...
class AST_Matrix(AST_Node):
def __init__(self, context, rows): AST_Node.__init__(self, context) self.rows = rows self.children = self.rows if not isinstance(self.rows, list): raise ValueError("AST_Matrix() expects a list of rows, got " + str(type(self.rows))) for...
raise ValueError( "AST_Matrix_Row() expects a list of elements, got " + str(type(self.elements))) def provide_parents(self, parent): self.parent = parent for e in self.elements: e.provide_parents(self) def __repr__(self): return "AST_MatrixR...
245
246
823
7
238
gronerl/dace
dace/frontend/octave/ast_matrix.py
Python
AST_Matrix
AST_Matrix
52
149
52
52
7d23689dd19d19b995d7c8e0304be69dae0aa2c8
bigcode/the-stack
train
093e0661ef7852ef2f7df095
train
function
@pytest.fixture(scope = "module") def lossless_prio_dscp_map(duthost): config_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts'] if "PORT_QOS_MAP" not in config_facts.keys(): return None port_qos_map = config_facts["PORT_QOS_MAP"] lossless_priorities = li...
@pytest.fixture(scope = "module") def lossless_prio_dscp_map(duthost):
config_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts'] if "PORT_QOS_MAP" not in config_facts.keys(): return None port_qos_map = config_facts["PORT_QOS_MAP"] lossless_priorities = list() intf = port_qos_map.keys()[0] if 'pfc_enable' not in port_...
import pytest from common.fixtures.conn_graph_facts import conn_graph_facts @pytest.fixture(scope = "module") def lossless_prio_dscp_map(duthost):
36
75
251
19
16
mykolaf/sonic-mgmt
tests/qos/qos_fixtures.py
Python
lossless_prio_dscp_map
lossless_prio_dscp_map
5
33
5
6
07120689b70ce09a82c83d44e0ccbe522ca2f2dd
bigcode/the-stack
train
ba2a41fb540425ea1b508c36
train
function
@pytest.fixture(scope = "module") def leaf_fanouts(conn_graph_facts): """ @summary: Fixture for getting the list of leaf fanout switches @param conn_graph_facts: Topology connectivity information @return: Return the list of leaf fanout switches """ leaf_fanouts = [] conn_facts = conn_graph_f...
@pytest.fixture(scope = "module") def leaf_fanouts(conn_graph_facts):
""" @summary: Fixture for getting the list of leaf fanout switches @param conn_graph_facts: Topology connectivity information @return: Return the list of leaf fanout switches """ leaf_fanouts = [] conn_facts = conn_graph_facts['device_conn'] """ for each interface of DUT """ for int...
dscp_to_tc_map[profile]: tc = dscp_to_tc_map[profile][dscp] if int(tc) in lossless_priorities: result[int(tc)].append(int(dscp)) return result @pytest.fixture(scope = "module") def leaf_fanouts(conn_graph_facts):
64
64
139
17
46
mykolaf/sonic-mgmt
tests/qos/qos_fixtures.py
Python
leaf_fanouts
leaf_fanouts
36
52
36
37
b444906f1006adaf94f8f4a612b7caee16fa24a0
bigcode/the-stack
train
d3f242b7cc578b0cabfc8e4c
train
class
class MigrationsEmulatorTest(spanner_emulator_testlib.TestCase): TEST_MIGRATIONS_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'migrations_for_emulator_test', ) def setUp(self): super().setUp() self.run_orm_migrations(self.TEST_MIGRATIONS_DIR) def test_basic(self): mo...
class MigrationsEmulatorTest(spanner_emulator_testlib.TestCase):
TEST_MIGRATIONS_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'migrations_for_emulator_test', ) def setUp(self): super().setUp() self.run_orm_migrations(self.TEST_MIGRATIONS_DIR) def test_basic(self): models.SmallTestModel({'key': 'key', 'value_1': 'value'}).save() ...
BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import logging import os import unittest import spanner_orm from spanner_orm.tests import models from spanner_orm.tes...
110
110
368
15
94
GavinDuggan/python-spanner-orm
spanner_orm/tests/migrations_emulator_test.py
Python
MigrationsEmulatorTest
MigrationsEmulatorTest
27
73
27
27
ba0621dd7f7bdbf2c9bedc8e6a1d662162fd1b1c
bigcode/the-stack
train
ce36de9c716f7345ff9794d1
train
function
def return_error(msg): print(msg, file=sys.stderr) sys.exit(1)
def return_error(msg):
print(msg, file=sys.stderr) sys.exit(1)
#!/usr/bin/env python from __future__ import print_function import json import sys import ast def return_error(msg):
28
64
19
5
22
bdclark/docker-telegraf-consul
bin/parse_config.py
Python
return_error
return_error
9
11
9
9
c2e68cdc856f2816e3dd7f97d314070919a87629
bigcode/the-stack
train
a9201c9d399bfee445733c0e
train
function
def is_num(val): if val is True or val is False: return False try: float(val) return True except ValueError: return False
def is_num(val):
if val is True or val is False: return False try: float(val) return True except ValueError: return False
#!/usr/bin/env python from __future__ import print_function import json import sys import ast def return_error(msg): print(msg, file=sys.stderr) sys.exit(1) def is_num(val):
47
64
39
5
42
bdclark/docker-telegraf-consul
bin/parse_config.py
Python
is_num
is_num
14
21
14
14
17745356f43ad4cec711ebac5e6b1af264120b3e
bigcode/the-stack
train
b7cb224d94ad5caa16d3e1e1
train
function
def convert_dict(d): if not isinstance(d, dict): error_out("{} not a map".format(d)) for k, v in d.iteritems(): if isinstance(v, dict): v = convert_dict(v) elif v.startswith('[') and v.endswith(']'): # treat as literal list d[k] = ast.literal_eval(v) ...
def convert_dict(d):
if not isinstance(d, dict): error_out("{} not a map".format(d)) for k, v in d.iteritems(): if isinstance(v, dict): v = convert_dict(v) elif v.startswith('[') and v.endswith(']'): # treat as literal list d[k] = ast.literal_eval(v) elif v == '{}'...
def return_error(msg): print(msg, file=sys.stderr) sys.exit(1) def is_num(val): if val is True or val is False: return False try: float(val) return True except ValueError: return False def convert_dict(d):
64
64
160
5
58
bdclark/docker-telegraf-consul
bin/parse_config.py
Python
convert_dict
convert_dict
24
43
24
24
e8e9859c1d08b84257aa203d92b81abfbf6a1b3a
bigcode/the-stack
train
8a1233757bcd4015fcd7f7ca
train
class
class ExecutionsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_cli...
class ExecutionsApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def delete_execution...
# coding: utf-8 """ LUSID API FINBOURNE Technology # noqa: E501 The version of the OpenAPI document: 0.11.3923 Contact: info@finbourne.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility lib...
247
256
8,158
6
240
finbourne/lusid-sdk-python-asyncio-preview
sdk/lusid_asyncio/api/executions_api.py
Python
ExecutionsApi
ExecutionsApi
35
730
35
35
f84af561d7f2da3b2cd38010493c63ca59618818
bigcode/the-stack
train
dfefd5aeefd390e0eeda5704
train
function
def get_imgs(img_path, imsize, bbox=None, transform=None, normalize=None): img = Image.open(img_path).convert('RGB') width, height = img.size if bbox is not None: r = int(np.maximum(bbox[2], bbox[3]) * 0.75) center_x = int((2 * bbox[0] + bbox[2]) / 2) center_y = int((2 *...
def get_imgs(img_path, imsize, bbox=None, transform=None, normalize=None):
img = Image.open(img_path).convert('RGB') width, height = img.size if bbox is not None: r = int(np.maximum(bbox[2], bbox[3]) * 0.75) center_x = int((2 * bbox[0] + bbox[2]) / 2) center_y = int((2 * bbox[1] + bbox[3]) / 2) y1 = np.maximum(0, center_y - r) y2 = np.minimu...
: captions = Variable(captions).cuda() sorted_cap_lens = Variable(sorted_cap_lens).cuda() else: captions = Variable(captions) sorted_cap_lens = Variable(sorted_cap_lens) return [real_imgs, captions, sorted_cap_lens, class_ids, keys] def get_imgs(img_path, imsize, bbo...
86
86
287
19
67
FangxiangFeng/DM-GAN-MDD
code/datasets.py
Python
get_imgs
get_imgs
59
88
59
60
42b87ec7a7874fc2fe1a65f303a2f1c62fa25f05
bigcode/the-stack
train
cee902639163e55a7e068531
train
function
def prepare_data(data): imgs, captions, captions_lens, class_ids, keys = data # sort data by the length in a decreasing order sorted_cap_lens, sorted_cap_indices = \ torch.sort(captions_lens, 0, True) real_imgs = [] for i in range(len(imgs)): imgs[i] = imgs[i][sorted_cap_indices] ...
def prepare_data(data):
imgs, captions, captions_lens, class_ids, keys = data # sort data by the length in a decreasing order sorted_cap_lens, sorted_cap_indices = \ torch.sort(captions_lens, 0, True) real_imgs = [] for i in range(len(imgs)): imgs[i] = imgs[i][sorted_cap_indices] if cfg.CUDA: ...
torch.utils.data as data from torch.autograd import Variable import torchvision.transforms as transforms import os import sys import numpy as np import pandas as pd from PIL import Image import numpy.random as random if sys.version_info[0] == 2: import cPickle as pickle else: import pickle def prepare_data(da...
76
76
256
5
70
FangxiangFeng/DM-GAN-MDD
code/datasets.py
Python
prepare_data
prepare_data
28
56
28
28
e55ad08943334f88f0b08a9a991513ff3788df4c
bigcode/the-stack
train
63d098fc78cc6a0abcfbf99c
train
class
class FlowersTextDataset(data.Dataset): def __init__(self, data_dir, split='train', base_size=64, transform=None, target_transform=None): self.transform = transform self.norm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(...
class FlowersTextDataset(data.Dataset):
def __init__(self, data_dir, split='train', base_size=64, transform=None, target_transform=None): self.transform = transform self.norm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) ...
mis_match_captions_len = torch.zeros(99) i = 0 while len(mis_match_captions_t) < 99: idx = random.randint(0, self.number_example) if cls_id == self.class_id[idx]: continue sent_ix = random.randint(0, self.embeddings_num) new_sent_ix...
256
256
2,138
7
249
FangxiangFeng/DM-GAN-MDD
code/datasets.py
Python
FlowersTextDataset
FlowersTextDataset
391
609
391
391
cb72e57f5139d65287866cd624ebd15a5299968f
bigcode/the-stack
train
66b616fcc673dac377d58196
train
function
def get_caption(raw_sent, dictionary): caption_ixs = [ ] tokenizer = RegexpTokenizer(r'\w+') tokens = tokenizer.tokenize(raw_sent.lower()) for tok in tokens: if tok in dictionary: caption_ixs.append(dictionary[tok]) # a list of indices for a sentence sent_caption = np.asarray...
def get_caption(raw_sent, dictionary):
caption_ixs = [ ] tokenizer = RegexpTokenizer(r'\w+') tokens = tokenizer.tokenize(raw_sent.lower()) for tok in tokens: if tok in dictionary: caption_ixs.append(dictionary[tok]) # a list of indices for a sentence sent_caption = np.asarray(caption_ixs).astype('int64') if (s...
)] else: for i in range(cfg.TREE.BRANCH_NUM): # print(imsize[i]) if i < (cfg.TREE.BRANCH_NUM - 1): re_img = transforms.Scale(imsize[i])(img) else: re_img = img ret.append(normalize(re_img)) return ret def get_caption(raw_se...
81
81
271
8
72
FangxiangFeng/DM-GAN-MDD
code/datasets.py
Python
get_caption
get_caption
90
114
90
90
a5ffabda9609f928d71e0a9b81eea81a598e1d5b
bigcode/the-stack
train
79bd81e5bd672cdcdc7c348a
train
class
class TextDataset(data.Dataset): def __init__(self, data_dir, split='train', base_size=64, transform=None, target_transform=None): self.transform = transform self.norm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0...
class TextDataset(data.Dataset):
def __init__(self, data_dir, split='train', base_size=64, transform=None, target_transform=None): self.transform = transform self.norm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) ...
.size if bbox is not None: r = int(np.maximum(bbox[2], bbox[3]) * 0.75) center_x = int((2 * bbox[0] + bbox[2]) / 2) center_y = int((2 * bbox[1] + bbox[3]) / 2) y1 = np.maximum(0, center_y - r) y2 = np.minimum(height, center_y + r) x1 = np.maximum(0, center_x - r) ...
256
256
2,302
6
249
FangxiangFeng/DM-GAN-MDD
code/datasets.py
Python
TextDataset
TextDataset
147
389
147
147
b954d7f2b750cf1a027718d020278e9a979d3bbd
bigcode/the-stack
train
38f484f03c277fc257d32da2
train
function
def get_imgs(img_path, imsize, bbox=None, transform=None, normalize=None): img = Image.open(img_path).convert('RGB') width, height = img.size if bbox is not None: r = int(np.maximum(bbox[2], bbox[3]) * 0.75) center_x = int((2 * bbox[0] + bbox[2]) / 2) center_y = int((2 *...
def get_imgs(img_path, imsize, bbox=None, transform=None, normalize=None):
img = Image.open(img_path).convert('RGB') width, height = img.size if bbox is not None: r = int(np.maximum(bbox[2], bbox[3]) * 0.75) center_x = int((2 * bbox[0] + bbox[2]) / 2) center_y = int((2 * bbox[1] + bbox[3]) / 2) y1 = np.maximum(0, center_y - r) y2 = np.minimu...
1, 2, 3,..., maxNum np.random.shuffle(ix) ix = ix[:cfg.TEXT.WORDS_NUM] ix = np.sort(ix) x[:, 0] = sent_caption[ix] x_len = cfg.TEXT.WORDS_NUM return x, x_len def get_imgs(img_path, imsize, bbox=None, transform=None, normalize=None):
86
86
287
19
66
FangxiangFeng/DM-GAN-MDD
code/datasets.py
Python
get_imgs
get_imgs
116
145
116
117
42b87ec7a7874fc2fe1a65f303a2f1c62fa25f05
bigcode/the-stack
train
a5da016b7fb95f341501d308
train
function
def prepare_train_and_show(neural_network: NeuralNetwork, train_data: np.ndarray, train_labels: np.ndarray, test_data: np.ndarray, test_labels: np.ndarray): data_scaler = MinMaxScaler((0, 1)) labels_scale...
def prepare_train_and_show(neural_network: NeuralNetwork, train_data: np.ndarray, train_labels: np.ndarray, test_data: np.ndarray, test_labels: np.ndarray):
data_scaler = MinMaxScaler((0, 1)) labels_scaler = MinMaxScaler((0, 1)) print("Press Ctrl + C to interrupt, exit button in window may not close the program") plt.ion() figure, ax = plt.subplots() figure.canvas.draw_idle() for i in range(1, FRAMES): neural_network.train( ...
import numpy as np from sklearn.preprocessing import MinMaxScaler from neural_network import NeuralNetwork ITERATION_PER_FRAME = 100 FRAMES = 1_000_000 def prepare_train_and_show(neural_network: NeuralNetwork, train_data: np.ndarray, train_labels: np.ndarray, ...
79
79
264
40
38
ErykKrupa/python-course
list6/train.py
Python
prepare_train_and_show
prepare_train_and_show
10
38
10
14
8af40b2eb871d56512acf2b243b3b492270a52ef
bigcode/the-stack
train
cbf6cae6827ec9cc0520fa26
train
class
class CommManager: def __init__(self): self.MPI = MPI self.communicators = {} self.intra_communicators = {} self.add_communicator('main', MPI.COMM_WORLD) def __getitem__(self, index): if index in self.intra_communicators: return self.intra_communicators[index...
class CommManager:
def __init__(self): self.MPI = MPI self.communicators = {} self.intra_communicators = {} self.add_communicator('main', MPI.COMM_WORLD) def __getitem__(self, index): if index in self.intra_communicators: return self.intra_communicators[index] elif inde...
from mpi4py import MPI class CommManager:
11
64
156
4
6
gandresr/PTSNET
ptsnet/parallel/comm.py
Python
CommManager
CommManager
3
22
3
3
6645b9a66cab4d0bad86af5243b3dfe8f767a9ce
bigcode/the-stack
train
023bae7dc620de636df04978
train
function
def canonicals_for_language(data, language): canonicals = set() for d in data: lang, dictionary, is_canonical, canonical = d.split(six.b('|')) if language is None or lang == language: canonicals.add(canonical) return canonicals
def canonicals_for_language(data, language):
canonicals = set() for d in data: lang, dictionary, is_canonical, canonical = d.split(six.b('|')) if language is None or lang == language: canonicals.add(canonical) return canonicals
.address_expansions.gazetteers import * from geodata.encoding import safe_decode, safe_encode from geodata.text.normalize import normalized_tokens from geodata.text.tokenize import tokenize_raw, token_types from geodata.text.utils import non_breaking_dash_regex def canonicals_for_language(data, language):
64
64
61
9
54
Fillr/libpostal
scripts/geodata/address_expansions/equivalence.py
Python
canonicals_for_language
canonicals_for_language
14
22
14
14
3d0b45af4f42a1f5edfe65f916e8d06a0bd1a69b
bigcode/the-stack
train
8dc241b11a8fcab958f3fa75
train
function
def equivalent(s1, s2, gazetteer, language): ''' Address/place equivalence ------------------------- OSM discourages abbreviations, but to make our training data map better to real-world input, we can safely replace the canonical phrase with an abbreviated version and retain the meaning of the ...
def equivalent(s1, s2, gazetteer, language):
''' Address/place equivalence ------------------------- OSM discourages abbreviations, but to make our training data map better to real-world input, we can safely replace the canonical phrase with an abbreviated version and retain the meaning of the words ''' tokens_s1 = normalized_tok...
token_types from geodata.text.utils import non_breaking_dash_regex def canonicals_for_language(data, language): canonicals = set() for d in data: lang, dictionary, is_canonical, canonical = d.split(six.b('|')) if language is None or lang == language: canonicals.add(canonical) ...
90
90
303
14
75
Fillr/libpostal
scripts/geodata/address_expansions/equivalence.py
Python
equivalent
equivalent
24
56
24
24
2748bacec80604aace9be170c27cb8e9cd782e5b
bigcode/the-stack
train
7e1cde9401f3571b3d74f4c6
train
function
def swap_case_string(str1): result_str = "" for item in str1: if item.isupper(): result_str += item.lower() else: result_str += item.upper() return result_str
def swap_case_string(str1):
result_str = "" for item in str1: if item.isupper(): result_str += item.lower() else: result_str += item.upper() return result_str
""" Write a Python program to swap cases of a given string. Sample Output: pYTHON eXERCISES jAVA nUMpy """ def swap_case_string(str1):
40
64
47
7
33
CodedLadiesInnovateTech/-python-challenge-solutions
Aniyom Ebenezer/Phase 2/STRINGS/Day_37_Challenge_Solution/Question 4 Solution.py
Python
swap_case_string
swap_case_string
8
15
8
8
a71e57b4faff1cdd7d34996c33469482b77b0e66
bigcode/the-stack
train
2dfdb815f9b59aa86b617e2f
train
function
def update_button(idx, pressed): curr_btns[idx] = pressed if curr_btns[idx] and not prev_btns[idx]: print("Exit menu") return True prev_btns[idx] = curr_btns[idx] return False
def update_button(idx, pressed):
curr_btns[idx] = pressed if curr_btns[idx] and not prev_btns[idx]: print("Exit menu") return True prev_btns[idx] = curr_btns[idx] return False
, 0.5), ) # Button management curr_btns = [False] * 4 prev_btns = [False] * 4 BTN_A = 0 BTN_B = 1 BTN_C = 2 BTN_D = 3 def update_button(idx, pressed):
64
64
56
7
56
albinger/Adafruit_Learning_System_Guides
MagTag_Flashcards/chapters/code.py
Python
update_button
update_button
87
93
87
87
92d7b6b887a0989573d87d13e8760bb3f1ba0248
bigcode/the-stack
train
7997f36c5af6fcd504329c07
train
class
class writer: def __init__(self): self.queue = [] self.max_queue_size = 1000 self.mutex = thread.allocate_lock() thread.start_new_thread(self.looper, ()) # # Writing thread # def looper(self): logger.dump('writer.looper() started!', 'info') while...
class writer:
def __init__(self): self.queue = [] self.max_queue_size = 1000 self.mutex = thread.allocate_lock() thread.start_new_thread(self.looper, ()) # # Writing thread # def looper(self): logger.dump('writer.looper() started!', 'info') while True: ...
#!/usr/bin/python3 import os import sys import time try: import thread except BaseException: import _thread as thread __DIR__ = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, __DIR__) sys.path.insert(0, __DIR__ + '/../') import logger class writer:
73
134
448
3
69
dpanic/honeypot
modules/writer.py
Python
writer
writer
20
99
20
21
d1e165fe045eb0f7ac5bb9b050ed2dab49351454
bigcode/the-stack
train
c8df2acca85ec424f47212a6
train
function
def get_environment_variable(key, default=sentinel, coerce=str): try: value = os.environ[key] return coerce(value) except KeyError: if default != sentinel: return default raise ValueError( "You must specify '{}' environment variable.".format(key)) exce...
def get_environment_variable(key, default=sentinel, coerce=str):
try: value = os.environ[key] return coerce(value) except KeyError: if default != sentinel: return default raise ValueError( "You must specify '{}' environment variable.".format(key)) except Exception as e: raise ValueError( "Error w...
import os sentinel = object() def get_environment_variable(key, default=sentinel, coerce=str):
23
64
95
15
8
sreekaransrinath/TearDrops
bot/utils.py
Python
get_environment_variable
get_environment_variable
6
18
6
6
3e3d30e67eb927e9162b3a2627898d2e4c5565a9
bigcode/the-stack
train
081cea8eb0fdef53b6b1a1c0
train
class
class Migration(migrations.Migration): dependencies = [ ('datapoint', '0002_auto_20160203_1929'), ] operations = [ migrations.AddField( model_name='datapoint', name='collected_at', field=models.DateTimeField(default=datetime.datetime(2016, 2, 3, 19, 43, ...
class Migration(migrations.Migration):
dependencies = [ ('datapoint', '0002_auto_20160203_1929'), ] operations = [ migrations.AddField( model_name='datapoint', name='collected_at', field=models.DateTimeField(default=datetime.datetime(2016, 2, 3, 19, 43, 23, 995365, tzinfo=utc)), pr...
-*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-02-03 19:43 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration):
64
64
129
7
56
p-v-o-s/hydro
Hydro/datapoint/migrations/0003_auto_20160203_1943.py
Python
Migration
Migration
10
28
10
11
5b8b48c47a2516bfff97af45394e13f4ec25ed03
bigcode/the-stack
train
981e5a437bdd831dcb85a2ed
train
class
class AsstesHelper(Helper): """Helper class for the unit test cases.""" @staticmethod def mock_request(*args, **kwargs): """To mock the requests method for unit test.""" if kwargs.get("auth")[0] == "wrong": return MockResponse(401, data={}) if kwargs.get("auth")[1] == "w...
class AsstesHelper(Helper):
"""Helper class for the unit test cases.""" @staticmethod def mock_request(*args, **kwargs): """To mock the requests method for unit test.""" if kwargs.get("auth")[0] == "wrong": return MockResponse(401, data={}) if kwargs.get("auth")[1] == "wrong": return Mo...
from urllib.parse import urlparse from insightconnect_plugin_runtime.exceptions import PluginException from icon_ibm_qradar.util.constants.constant import SUCCESS_RESPONSE_CODES from unit_test.helpers.helper import Helper, MockResponse class AsstesHelper(Helper):
50
64
205
7
42
lukaszlaszuk/insightconnect-plugins
plugins/ibm_qradar/unit_test/helpers/assets.py
Python
AsstesHelper
AsstesHelper
9
33
9
9
a046873840c427cb5989d1cd32d93a6b3a344909
bigcode/the-stack
train
6447fee19786cafc829626fd
train
function
def read_out_file(file, success=True): if success: with open(file) as f: lines = f.readlines() value = lines[-1].split()[1] return value else: return float("NaN")
def read_out_file(file, success=True):
if success: with open(file) as f: lines = f.readlines() value = lines[-1].split()[1] return value else: return float("NaN")
if os.path.isfile(im_csv_fname): # print_header = False # result_df = result_df.append(value_dict, ignore_index=True) # print(result_df) result_df.to_csv(im_csv_fname, header=print_header, columns=cols) def read_out_file(file, success=True):
64
64
52
9
55
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
read_out_file
read_out_file
273
283
273
273
79e86ab0b593428a2693738d7183604ec9bdd491
bigcode/the-stack
train
acd2dee7d1780f0823b8271c
train
function
def main(comp_000, comp_090, output_dir, OpenSees_path): if not os.path.exists(output_dir): os.makedirs(args.output_dir) script = [ OpenSees_path, os.path.join(model_dir, "Run_script.tcl"), comp_000, comp_090, output_dir, ] print(" ".join(script)) ...
def main(comp_000, comp_090, output_dir, OpenSees_path):
if not os.path.exists(output_dir): os.makedirs(args.output_dir) script = [ OpenSees_path, os.path.join(model_dir, "Run_script.tcl"), comp_000, comp_090, output_dir, ] print(" ".join(script)) subprocess.run(script) im_name = "Spear_3D_Model" ...
import argparse import glob import os import subprocess import numpy as np import pandas as pd from IM_calculation.Advanced_IM import runlibs_2d model_dir = os.path.dirname(__file__) def main(comp_000, comp_090, output_dir, OpenSees_path):
63
78
262
18
45
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
main
main
14
51
14
15
2cab9b57f3f03d95363648813b7b3d24da172cd2
bigcode/the-stack
train
ef46890b7a00bae57e159f31
train
function
def calculate_geom(output_dir, im_name): """ generates geom by globing results from 000 and 090 output_dir: folder that contains adv_im_comp.csv. used to grab data from 000, 090. im_name: adv_im model name """ df_000 = pd.read_csv( os.path.join(output_dir, f"{im_name}_000.csv"), dtype={"...
def calculate_geom(output_dir, im_name):
""" generates geom by globing results from 000 and 090 output_dir: folder that contains adv_im_comp.csv. used to grab data from 000, 090. im_name: adv_im model name """ df_000 = pd.read_csv( os.path.join(output_dir, f"{im_name}_000.csv"), dtype={"component": str} ) df_090 = pd.re...
_df = pd.DataFrame.from_dict(value_dict, orient="index") cols = list(result_df.columns) cols.sort() # test if file exist, if exist, no header if os.path.isfile(im_csv_fname): print_header = False result_df.to_csv(im_csv_fname, mode="a", header=print_header, columns=cols) def calculate_geo...
85
85
285
9
76
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
calculate_geom
calculate_geom
143
170
143
143
1462ac3d01950d1b1a090530204070f09bca2c9b
bigcode/the-stack
train
79de2235d722d4bdf9556e3b
train
function
def create_im_csv( output_dir, im_name, component, component_dir, check_converge=True, print_header=True, remove_gravity=True, ): """ create a csv file for each single component/analysis """ if check_converge: success_glob = os.path.join(component_dir, "Analysis_*") ...
def create_im_csv( output_dir, im_name, component, component_dir, check_converge=True, print_header=True, remove_gravity=True, ):
""" create a csv file for each single component/analysis """ if check_converge: success_glob = os.path.join(component_dir, "Analysis_*") success_files = glob.glob(success_glob) model_converged = False for f in success_files: with open(f) as fp: ...
csv that contains multiple rows 000,090, geom, norm """ # read all df # im_csv_glob = os.path.join(output_dir, im_name + "_*" + ".csv") df = pd.DataFrame() df.index.name = "component" for component in ["000", "090", "geom", "norm"]: component_csv_fname = os.path.join(output_dir, f"{...
224
224
749
39
184
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
create_im_csv
create_im_csv
195
270
195
203
392df2ae7caf10ca8a6459b4824353dc031cba51
bigcode/the-stack
train
e5a8d296eea52193320d6bd0
train
function
def calculate_norm(im_name, output_dir, print_header=True): # get 000 and 090 dir dir_000 = os.path.join(output_dir, "000") dir_090 = os.path.join(output_dir, "090") component = "norm" im_csv_fname = os.path.join(output_dir, f"{im_name}_{component}.csv") value_dict = {} # read data from r...
def calculate_norm(im_name, output_dir, print_header=True): # get 000 and 090 dir
dir_000 = os.path.join(output_dir, "000") dir_090 = os.path.join(output_dir, "090") component = "norm" im_csv_fname = os.path.join(output_dir, f"{im_name}_{component}.csv") value_dict = {} # read data from recordings for recorder_name in ["disp", "drift", "accl"]: # find recorder ...
os.path.exists(im_gravity_recorder): gr_value = float(read_out_file(im_gravity_recorder)) else: gr_value = 0 im_recorder = os.path.join( direction_dir, os.path.join(recorder_name, im_recorder_fname) ) with open(im_recorder) as f_im_recorder: im_records_list_tmp = [floa...
159
159
531
23
135
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
calculate_norm
calculate_norm
80
140
80
81
8f91370078862295a69b8d46feaf2333a9efbe6e
bigcode/the-stack
train
b7f2588825c3b6069e400555
train
function
def agg_csv(output_dir, im_name, print_header=True): """ aggregate all data into one huge csv that contains multiple rows 000,090, geom, norm """ # read all df # im_csv_glob = os.path.join(output_dir, im_name + "_*" + ".csv") df = pd.DataFrame() df.index.name = "component" for compon...
def agg_csv(output_dir, im_name, print_header=True):
""" aggregate all data into one huge csv that contains multiple rows 000,090, geom, norm """ # read all df # im_csv_glob = os.path.join(output_dir, im_name + "_*" + ".csv") df = pd.DataFrame() df.index.name = "component" for component in ["000", "090", "geom", "norm"]: compon...
")) cols = list(im_geom.columns) cols.sort() im_csv_fname = os.path.join(output_dir, f"{im_name}_geom.csv") im_geom.to_csv(im_csv_fname, columns=cols, index=True, header=True) def agg_csv(output_dir, im_name, print_header=True):
64
64
200
13
51
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
agg_csv
agg_csv
173
191
173
173
fd81d2674b826ad5a52825a92698f65854bf934c
bigcode/the-stack
train
6c14ae516e0804c90df7ff6b
train
function
def read_recorder_all(direction_dir, recorder_name, im_recorder_fname): # find corrosponding gravity file im_gravity_dir = os.path.join(direction_dir, f"gravity_{recorder_name}") im_gravity_recorder = os.path.join(im_gravity_dir, f"gr_{im_recorder_fname}") if os.path.exists(im_gravity_recorder): ...
def read_recorder_all(direction_dir, recorder_name, im_recorder_fname): # find corrosponding gravity file
im_gravity_dir = os.path.join(direction_dir, f"gravity_{recorder_name}") im_gravity_recorder = os.path.join(im_gravity_dir, f"gr_{im_recorder_fname}") if os.path.exists(im_gravity_recorder): gr_value = float(read_out_file(im_gravity_recorder)) else: gr_value = 0 im_recorder = os.pa...
# calculate the disp&drift Norm from records from 000 and 090 calculate_norm(im_name, output_dir) agg_csv(output_dir, im_name) # calc norm def read_recorder_all(direction_dir, recorder_name, im_recorder_fname): # find corrosponding gravity file
64
64
207
25
38
ucgmsim/IM_calculation
IM_calculation/Advanced_IM/Models/Spear_3D_Model/run.py
Python
read_recorder_all
read_recorder_all
55
77
55
57
4354e5109c2a8fbdb92768acdd1e2fdd92217999
bigcode/the-stack
train
b606945f5f0654c6adb940ed
train
function
def select_loss_fnc(loss_type,use_probabilities=False): """ Selects the type of loss function to use. Choices are currently Cross-entropy or Mean-Square-Estimate. :param loss_type: 'CE' or 'MSE' :param use_probabilities: :return: """ if loss_type == 'CE': if use_probabilities: ...
def select_loss_fnc(loss_type,use_probabilities=False):
""" Selects the type of loss function to use. Choices are currently Cross-entropy or Mean-Square-Estimate. :param loss_type: 'CE' or 'MSE' :param use_probabilities: :return: """ if loss_type == 'CE': if use_probabilities: loss_fnc = cross_entropy_probabilities(reduction='...
import torch import torch.nn as nn import torch.nn.functional as F def select_loss_fnc(loss_type,use_probabilities=False):
28
64
158
12
15
tueboesen/Active-Learning
src/losses.py
Python
select_loss_fnc
select_loss_fnc
5
22
5
5
2adc1f2813c770ffa44a1933045fb6e822508a0e
bigcode/the-stack
train
e844f62ba2c324911584950f
train
class
class MSE_custom(torch.nn.Module): """ This class works just like the normal MSE loss function, with the extra option of using reduction='sum_to_samples' which sums over all other dimension and reduce the dimension down to the number of samples. Which is useful if you want to put individual weight on each p...
class MSE_custom(torch.nn.Module):
""" This class works just like the normal MSE loss function, with the extra option of using reduction='sum_to_samples' which sums over all other dimension and reduce the dimension down to the number of samples. Which is useful if you want to put individual weight on each point. """ def __init__(self...
torch.log(F.softmax(input, dim=1))).sum(dim=1)) if self.reduction == 'none': return loss elif self.reduction == 'mean': return loss.mean() elif self.reduction == 'sum': return loss.sum() class MSE_custom(torch.nn.Module):
64
64
155
8
56
tueboesen/Active-Learning
src/losses.py
Python
MSE_custom
MSE_custom
48
61
48
48
e30c6f840e1eeed3b4cc176d40acd3d8f4b3bf50
bigcode/the-stack
train
51a07acef717c7fd4302b002
train
class
class cross_entropy_probabilities(torch.nn.Module): """ Cross entropy function that can handle probability targets """ def __init__(self,reduction='none'): self.reduction = reduction super(cross_entropy_probabilities,self).__init__() def forward(self, input, target, point_weight=1)...
class cross_entropy_probabilities(torch.nn.Module):
""" Cross entropy function that can handle probability targets """ def __init__(self,reduction='none'): self.reduction = reduction super(cross_entropy_probabilities,self).__init__() def forward(self, input, target, point_weight=1): assert input.size() == target.size() ...
EntropyLoss(ignore_index=-1,reduction='none') elif loss_type == 'MSE': loss_fnc = MSE_custom(reduction='sum_to_samples') else: raise ValueError("Undefined loss_fnc selected") return loss_fnc class cross_entropy_probabilities(torch.nn.Module):
64
64
214
9
54
tueboesen/Active-Learning
src/losses.py
Python
cross_entropy_probabilities
cross_entropy_probabilities
25
46
25
25
db20fa853ede96ea48c001cf04b4ecb129e6212b
bigcode/the-stack
train
0e065a3c21a85900d0770f62
train
function
def save_xml(data, xml_file): output = codecs.open(xml_file, 'w', 'utf-8') root = etree.Element('root') city_xml = etree.ElementTree(root) city = etree.SubElement(root, 'city') city.append(etree.Comment('城市信息')) city.text = str(data) output.write(etree.tounicode(city_xml.getroot())) outp...
def save_xml(data, xml_file):
output = codecs.open(xml_file, 'w', 'utf-8') root = etree.Element('root') city_xml = etree.ElementTree(root) city = etree.SubElement(root, 'city') city.append(etree.Comment('城市信息')) city.text = str(data) output.write(etree.tounicode(city_xml.getroot())) output.close()
rd.open_workbook(xlsx_file) table = data.sheets()[0] c = OrderedDict() for i in range(table.nrows): c[table.cell(i, 0).value] = table.row_values(i)[1:] return c def save_xml(data, xml_file):
64
64
86
8
55
feikon/Python_learning
show_me_the_code/problem_0018.py
Python
save_xml
save_xml
36
44
36
36
59871f1ee2388cf2567da0df709943004d598fb6
bigcode/the-stack
train
324256ac5494645d3c498392
train
function
def read_xlsx(xlsx_file): data = xlrd.open_workbook(xlsx_file) table = data.sheets()[0] c = OrderedDict() for i in range(table.nrows): c[table.cell(i, 0).value] = table.row_values(i)[1:] return c
def read_xlsx(xlsx_file):
data = xlrd.open_workbook(xlsx_file) table = data.sheets()[0] c = OrderedDict() for i in range(table.nrows): c[table.cell(i, 0).value] = table.row_values(i)[1:] return c
50 """ # Problem describe:Convert city.xlsx file to city.xml # Problem solve step: # 1.Read the city.xlsx; # 2.Write to city.xml; import xlrd import codecs from lxml import etree from collections import OrderedDict def read_xlsx(xlsx_file):
64
64
68
8
55
feikon/Python_learning
show_me_the_code/problem_0018.py
Python
read_xlsx
read_xlsx
27
33
27
27
73726de44dfbfdfc499bf29d51b9ac61d6a76943
bigcode/the-stack
train
9f740040c7d25d2e8078e0de
train
class
class ServiceAccountCreatePage(BasePage): def _get_new_service_account_form(self): return self.find_element_by_class_name("new-service-account-form") def set_name(self, name): form = self._get_new_service_account_form() field = form.find_element_by_name("name") field.send_keys(n...
class ServiceAccountCreatePage(BasePage):
def _get_new_service_account_form(self): return self.find_element_by_class_name("new-service-account-form") def set_name(self, name): form = self._get_new_service_account_form() field = form.find_element_by_name("name") field.send_keys(name) def submit(self): form =...
_enable_button(self): button = self.find_element_by_class_name("enable-service-account") button.click() def get_disable_modal(self): element = self.find_element_by_id("disableModal") self.wait_until_visible(element) return DisableServiceAccountModal(element) class ServiceAcc...
64
64
88
8
56
bonniech3n/merou
itests/pages/service_accounts.py
Python
ServiceAccountCreatePage
ServiceAccountCreatePage
21
32
21
21
19e165806bae7ac429f1b04c32edc57f1e11839b
bigcode/the-stack
train
25c1ededc2809b8dbb490609
train
class
class ServiceAccountViewPage(BasePage): def click_disable_button(self): button = self.find_element_by_class_name("disable-service-account") button.click() def click_enable_button(self): button = self.find_element_by_class_name("enable-service-account") button.click() def ge...
class ServiceAccountViewPage(BasePage):
def click_disable_button(self): button = self.find_element_by_class_name("disable-service-account") button.click() def click_enable_button(self): button = self.find_element_by_class_name("enable-service-account") button.click() def get_disable_modal(self): element =...
from selenium.webdriver.support.select import Select from itests.pages.base import BaseModal, BasePage class ServiceAccountViewPage(BasePage):
28
64
92
8
19
bonniech3n/merou
itests/pages/service_accounts.py
Python
ServiceAccountViewPage
ServiceAccountViewPage
6
18
6
6
78d3e1414ddd0ed866294568f6fe2e154ddd688c
bigcode/the-stack
train
3e2917dba13f7493a4d52dff
train
class
class DisableServiceAccountModal(BaseModal): pass
class DisableServiceAccountModal(BaseModal):
pass
): form = self._get_enable_service_account_form() owner_select = form.find_element_by_tag_name("select") Select(owner_select).select_by_visible_text(owner) def submit(self): form = self._get_enable_service_account_form() form.submit() class DisableServiceAccountModal(BaseMod...
64
64
11
8
56
bonniech3n/merou
itests/pages/service_accounts.py
Python
DisableServiceAccountModal
DisableServiceAccountModal
49
50
49
49
493025889e37eb4250f8bfc1d805cbfab98395bd
bigcode/the-stack
train
e42aa5af645ca75deb694ef6
train
class
class ServiceAccountEnablePage(BasePage): def _get_enable_service_account_form(self): return self.find_element_by_class_name("enable-service-account-form") def select_owner(self, owner): form = self._get_enable_service_account_form() owner_select = form.find_element_by_tag_name("select"...
class ServiceAccountEnablePage(BasePage):
def _get_enable_service_account_form(self): return self.find_element_by_class_name("enable-service-account-form") def select_owner(self, owner): form = self._get_enable_service_account_form() owner_select = form.find_element_by_tag_name("select") Select(owner_select).select_by_v...
def set_name(self, name): form = self._get_new_service_account_form() field = form.find_element_by_name("name") field.send_keys(name) def submit(self): form = self._get_new_service_account_form() form.submit() class ServiceAccountEnablePage(BasePage):
64
64
95
8
56
bonniech3n/merou
itests/pages/service_accounts.py
Python
ServiceAccountEnablePage
ServiceAccountEnablePage
35
46
35
35
2e5dc4c72b72912929fa63790e4d3eea4b899058
bigcode/the-stack
train
53e02b24c482f9c368855f7f
train
class
class ThrowStmt(Statement): def __init__(self, kwargs={}): super(Statement, self).__init__(kwargs) locs = _import() # Expression expr; e = kwargs.get(u'expr', {}) self._expr = locs[e[u'@t']](e) if e else None self.add_as_parent([self.expr]) @proper...
class ThrowStmt(Statement):
def __init__(self, kwargs={}): super(Statement, self).__init__(kwargs) locs = _import() # Expression expr; e = kwargs.get(u'expr', {}) self._expr = locs[e[u'@t']](e) if e else None self.add_as_parent([self.expr]) @property def expr(self): retur...
#!/usr/bin/env python from .statement import Statement from . import _import class ThrowStmt(Statement):
24
64
114
6
17
natebragg/java-sketch
jskparser/ast/stmt/throwstmt.py
Python
ThrowStmt
ThrowStmt
7
22
7
7
55b088749307837edf4165b9d6c1428ac1e88271
bigcode/the-stack
train
c7fc456fd6abf4bb0dbd4c15
train
class
class ZFSSAApi(object): """ZFSSA API proxy class""" def __init__(self): self.host = None self.url = None self.rclient = None def __del__(self): if self.rclient and self.rclient.islogin(): self.rclient.logout() def _is_pool_owned(self, pdata): """Ret...
class ZFSSAApi(object):
"""ZFSSA API proxy class""" def __init__(self): self.host = None self.url = None self.rclient = None def __del__(self): if self.rclient and self.rclient.islogin(): self.rclient.logout() def _is_pool_owned(self, pdata): """Returns True if the pool's ...
2014, 2015, Oracle and/or its affiliates. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
256
256
8,217
7
249
usernameisnull/cinder-explanation
cinder/volume/drivers/zfssa/zfssarest.py
Python
ZFSSAApi
ZFSSAApi
34
999
34
34
1ca408e4ffa6a0436d1d0087a04f1d0e4cac7c8a
bigcode/the-stack
train
fd200406cd1c9cdc0f272a8c
train
class
class ZFSSANfsApi(ZFSSAApi): """ZFSSA API proxy class for NFS driver""" projects_path = '/api/storage/v1/pools/%s/projects' project_path = projects_path + '/%s' shares_path = project_path + '/filesystems' share_path = shares_path + '/%s' share_snapshots_path = share_path + '/snapshots' shar...
class ZFSSANfsApi(ZFSSAApi):
"""ZFSSA API proxy class for NFS driver""" projects_path = '/api/storage/v1/pools/%s/projects' project_path = projects_path + '/%s' shares_path = project_path + '/filesystems' share_path = shares_path + '/%s' share_snapshots_path = share_path + '/snapshots' share_snapshot_path = share_snaps...
' svc = "%(base)s/%(prop)s" % {'base': base, 'prop': schema['property']} ret = self.rclient.get(svc) if ret.status == restclient.Status.OK: LOG.warning(_LW('Property %s already exists.'), schema['property']) return ret = self.rclient.post(base, schema) i...
256
256
2,251
12
243
usernameisnull/cinder-explanation
cinder/volume/drivers/zfssa/zfssarest.py
Python
ZFSSANfsApi
ZFSSANfsApi
1,002
1,272
1,002
1,002
713f77223332c8d55ba8b75810d82a619fc7ba14
bigcode/the-stack
train
c878f3e1415ec1367c27d58f
train
function
def factory_restclient(url, **kwargs): return restclient.RestClientURL(url, **kwargs)
def factory_restclient(url, **kwargs):
return restclient.RestClientURL(url, **kwargs)
from cinder import exception from cinder.i18n import _, _LE, _LW from cinder.volume.drivers.zfssa import restclient from cinder.volume.drivers.zfssa import webdavclient LOG = log.getLogger(__name__) def factory_restclient(url, **kwargs):
64
64
21
9
55
usernameisnull/cinder-explanation
cinder/volume/drivers/zfssa/zfssarest.py
Python
factory_restclient
factory_restclient
30
31
30
30
154fc3192dc3cc3f4329091a8fa15987dd750990
bigcode/the-stack
train
dbe63ef8018fd652582ec797
train
function
def erro(msg='ERRO'): """ -> Cria uma mensagem de erro :param msg:mensagem que será usada no erro (padrão = 'ERRO') :return:string da mensagem de erro criada criada """ return f"\t{color('vermelho')}{msg}{color()}"
def erro(msg='ERRO'):
""" -> Cria uma mensagem de erro :param msg:mensagem que será usada no erro (padrão = 'ERRO') :return:string da mensagem de erro criada criada """ return f"\t{color('vermelho')}{msg}{color()}"
{color('azul')}{i:<{tam - 6}}" interface += f"\n\t{color('amarelo')}{'='*tam}{color('azul')}\n\t {pos}{color('verde')}" return interface def erro(msg='ERRO'):
64
64
70
7
56
Felix-xilef/Curso-de-Python
Desafios/Desafio115Pacote/Menu/__init__.py
Python
erro
erro
74
80
74
74
2b3601e96ab0e8d3a6e56cf7c13337bcac4b0c57
bigcode/the-stack
train
bdf4adaf0afb07be2689dacd
train
function
def color(font=''): """ -> Fornece o código ANSI para a cor de texto desejada, não forneça entrada para a cor padrão :param font:nome da cor desejada opções - preto, vermelho, verde, amarelo, azul, magenta, cyan e cinza claro :return:código ANSI para texto na cor escolhida """ font.l...
def color(font=''):
""" -> Fornece o código ANSI para a cor de texto desejada, não forneça entrada para a cor padrão :param font:nome da cor desejada opções - preto, vermelho, verde, amarelo, azul, magenta, cyan e cinza claro :return:código ANSI para texto na cor escolhida """ font.lower() cor = '\0...
def color(font=''):
5
64
213
5
0
Felix-xilef/Curso-de-Python
Desafios/Desafio115Pacote/Menu/__init__.py
Python
color
color
1
26
1
1
4ce38a079b37531fd26dc1ef3134222a6cbc9c5e
bigcode/the-stack
train
60852c64d62c5250f7da0e0c
train
function
def cabecalho(msg=''): """ -> Cria um 'cabeçalho' no seguinte formato: =========== msg =========== :param msg:mensagem que será usada no cabeçalho do menu (padrão = '') :return:string cabeçalho criado """ tam = 50 if len(msg) > ...
def cabecalho(msg=''):
""" -> Cria um 'cabeçalho' no seguinte formato: =========== msg =========== :param msg:mensagem que será usada no cabeçalho do menu (padrão = '') :return:string cabeçalho criado """ tam = 50 if len(msg) > tam: tam = len(...
cor += '34' elif font == 'magenta': cor += '35' elif font == 'cyan': cor += '36' elif font == 'cinza claro': cor += '37' cor += 'm' return cor def cabecalho(msg=''):
64
64
146
7
56
Felix-xilef/Curso-de-Python
Desafios/Desafio115Pacote/Menu/__init__.py
Python
cabecalho
cabecalho
29
43
29
29
ac5f1e6fa4f7e3b8e5ebd24879352fbce32a364e
bigcode/the-stack
train
e3f58c65e8e6cf5877bfa4a9
train
function
def menu(msg='Menu', pos='Digite uma opção: ', *op): """ -> Cria um 'menu' no seguinte formato: =========== msg =========== op1 ... opn =========== pos :param msg:...
def menu(msg='Menu', pos='Digite uma opção: ', *op):
""" -> Cria um 'menu' no seguinte formato: =========== msg =========== op1 ... opn =========== pos :param msg:mensagem que será usada no cabeçalho do menu (padrão ...
) + 8 interface = f"\n\t{color('amarelo')}{'='*tam}\n\t{color('azul')}{msg:^{tam}}\n\t{color('amarelo')}{'='*tam}{color()}" return interface def menu(msg='Menu', pos='Digite uma opção: ', *op):
77
77
259
16
60
Felix-xilef/Curso-de-Python
Desafios/Desafio115Pacote/Menu/__init__.py
Python
menu
menu
46
71
46
46
3330b7a72a17690498ac3be5fddfc0e6bd0758d7
bigcode/the-stack
train
43a1c9408ab0699066d3330f
train
class
class Sequencer(SimpleElaboratable): """Sequences a 1x1 convolution. This is the control logic required to calculate all output channel values for a single input pixel. Public Interface --------------- start_run: Signal() in When the run commences. in_store_ready: Signal() in ...
class Sequencer(SimpleElaboratable):
"""Sequences a 1x1 convolution. This is the control logic required to calculate all output channel values for a single input pixel. Public Interface --------------- start_run: Signal() in When the run commences. in_store_ready: Signal() in Input store has data available ...
--------------- start_run: Signal() in High for a single cycle when a run is started. all_output_finished: Signal() in High when all of the output channels calculations have been started. in_store_ready: Signal() in High while input store has data available for read. fifo_ha...
244
244
815
8
236
keadwen/CFU-Playground
proj/mnv2_first/gateware/sequencing.py
Python
Sequencer
Sequencer
101
193
101
101
b95c9ab950db720fa262b005781ee7b56fc002a1
bigcode/the-stack
train
6b6ccbe110347813239f8ec8
train
class
class UpCounter(SimpleElaboratable): """Counts pulses. Parameters ---------- width: int Number of bits in counter Public Interface --------------- restart: Signal() in Zero all internal counter, get ready to start again. en: Signal() in Count up by one. done...
class UpCounter(SimpleElaboratable):
"""Counts pulses. Parameters ---------- width: int Number of bits in counter Public Interface --------------- restart: Signal() in Zero all internal counter, get ready to start again. en: Signal() in Count up by one. done: Signal() out Set high for o...
specific language governing permissions and # limitations under the License. from nmigen import Signal, Mux from nmigen_cfu import SimpleElaboratable from . import config from .delay import Delayer from .macc import Madd4Pipeline from .post_process import PostProcessor class UpCounter(SimpleElaboratable):
69
69
230
8
60
keadwen/CFU-Playground
proj/mnv2_first/gateware/sequencing.py
Python
UpCounter
UpCounter
26
62
26
26
5c5be30d90de6b6f6c7a650241b28feb2bbc2ed0
bigcode/the-stack
train
0677c72442ae00079d3b0d39
train
class
class GateCalculator(SimpleElaboratable): """Calcaulates the 'gate' signal Public Interface --------------- start_run: Signal() in High for a single cycle when a run is started. all_output_finished: Signal() in High when all of the output channels calculations have been started. ...
class GateCalculator(SimpleElaboratable):
"""Calcaulates the 'gate' signal Public Interface --------------- start_run: Signal() in High for a single cycle when a run is started. all_output_finished: Signal() in High when all of the output channels calculations have been started. in_store_ready: Signal() in High ...
1 next_count = Mux(count == last_count, 0, count + 1) with m.If(self.en): m.d.sync += count.eq(next_count) m.d.comb += self.done.eq(count == last_count) with m.If(self.restart): m.d.sync += count.eq(0) class GateCalculator(SimpleElaboratable):
77
77
258
8
69
keadwen/CFU-Playground
proj/mnv2_first/gateware/sequencing.py
Python
GateCalculator
GateCalculator
65
98
65
65
d234e359df9d0ffc269aaa9c7a27f8a2cd1dfaaf
bigcode/the-stack
train
d071c682c4f5e439fd30ace4
train
function
def setup(bot): bot.add_cog(Screenshare(bot))
def setup(bot):
bot.add_cog(Screenshare(bot))
from .screenshare import Screenshare __red_end_user_data_statement__ = ( "This cog does not persistently store data or metadata about users." ) def setup(bot):
37
64
14
4
33
pordino/kennnyshiwa-cogs
screenshare/__init__.py
Python
setup
setup
7
8
7
7
34c5b61560206f5fd2dc0de5f694805edcd7de62
bigcode/the-stack
train
b538841162abae04fd6f28be
train
function
def resolve_heap_object_factory(obj: Any, options: Options = None) -> HeapObjectFactory: if isinstance(obj, basic_types): return BasicHeapObjectFactory(obj, options) if isinstance(obj, sequence_types): return SequenceHeapObjectFactory(obj, options) if isinstance(obj, key_value_types): ...
def resolve_heap_object_factory(obj: Any, options: Options = None) -> HeapObjectFactory:
if isinstance(obj, basic_types): return BasicHeapObjectFactory(obj, options) if isinstance(obj, sequence_types): return SequenceHeapObjectFactory(obj, options) if isinstance(obj, key_value_types): return KvpHeapObjectFactory(obj, options) if isinstance(obj, named_types): ...
_factory import KvpHeapObjectFactory from .named_heap_object_factory import NamedHeapObjectFactory from .sequence_heap_object_factory import SequenceHeapObjectFactory from .unknown_heap_object_factory import UnknownHeapObjectFactory def resolve_heap_object_factory(obj: Any, options: Options = None) -> HeapObjectFactory...
64
64
155
20
43
vincentxavier/nbtutor
nbtutor/ipython/factories/heap_object_factory.py
Python
resolve_heap_object_factory
resolve_heap_object_factory
16
35
16
16
d4f4102fd533304b1b1cd8ec35044b04be1dd011
bigcode/the-stack
train
0c81922e4b515bbafba9eecb
train
function
def create_heap_object(obj: Any, options: Options = None) -> HeapObject: return resolve_heap_object_factory(obj, options).create()
def create_heap_object(obj: Any, options: Options = None) -> HeapObject:
return resolve_heap_object_factory(obj, options).create()
return ClassHeapObjectFactory(obj, options) if isinstance(type(obj), type) and hasattr(obj, '__dict__'): return InstanceHeapObjectFactory(obj, options) return UnknownHeapObjectFactory(obj, options) def create_heap_object(obj: Any, options: Options = None) -> HeapObject:
64
64
30
18
46
vincentxavier/nbtutor
nbtutor/ipython/factories/heap_object_factory.py
Python
create_heap_object
create_heap_object
38
39
38
38
6ff69eff4d3ad65d5064908fb9871dd720b6d919
bigcode/the-stack
train
81fe693c27fedd044c1b1eeb
train
function
def create_heap_objects(objects: Collection[Any], options: Options = None) -> Dict[str, HeapObject]: heap: Dict[str, HeapObject] = dict() reduce_heap_objects(objects, heap, options) return heap
def create_heap_objects(objects: Collection[Any], options: Options = None) -> Dict[str, HeapObject]:
heap: Dict[str, HeapObject] = dict() reduce_heap_objects(objects, heap, options) return heap
() objects_to_reduce = factory.get_objects_to_reduce() if objects_to_reduce is not None and len(objects_to_reduce) > 0: reduce_heap_objects(objects_to_reduce, heap, options) def create_heap_objects(objects: Collection[Any], options: Options = None) -> Dict[str, HeapObject]:
64
64
48
22
42
vincentxavier/nbtutor
nbtutor/ipython/factories/heap_object_factory.py
Python
create_heap_objects
create_heap_objects
56
59
56
56
e2f952674b509226f957b445c369030910700de6
bigcode/the-stack
train
d12469902ee4d53eea7f1494
train
function
def reduce_heap_objects(objects: Collection[Any], heap: Dict[str, HeapObject], options: Options = None) -> None: for obj in objects: obj_id = HeapObjectFactory.get_object_id(obj) if heap.get(obj_id, None) is not None: continue factory = resolve_heap_object_factory(obj, options) ...
def reduce_heap_objects(objects: Collection[Any], heap: Dict[str, HeapObject], options: Options = None) -> None:
for obj in objects: obj_id = HeapObjectFactory.get_object_id(obj) if heap.get(obj_id, None) is not None: continue factory = resolve_heap_object_factory(obj, options) heap[obj_id] = factory.create() objects_to_reduce = factory.get_objects_to_reduce() if o...
UnknownHeapObjectFactory(obj, options) def create_heap_object(obj: Any, options: Options = None) -> HeapObject: return resolve_heap_object_factory(obj, options).create() def reduce_heap_objects(objects: Collection[Any], heap: Dict[str, HeapObject], options: Options = None) -> None:
64
64
121
26
38
vincentxavier/nbtutor
nbtutor/ipython/factories/heap_object_factory.py
Python
reduce_heap_objects
reduce_heap_objects
42
53
42
42
d47fca210bac1aeec1d220a33a2a73b471f04423
bigcode/the-stack
train
e60d2b69f2d71926814fc621
train
class
class SQLiteMixin(object): @property def dbcur(self): pid = (os.getpid(), threading.current_thread().ident) if not (self.conn and pid == self.last_pid): self.last_pid = pid self.conn = sqlite3.connect(self.path, isolation_level=None) return self.conn.cursor()
class SQLiteMixin(object): @property
def dbcur(self): pid = (os.getpid(), threading.current_thread().ident) if not (self.conn and pid == self.last_pid): self.last_pid = pid self.conn = sqlite3.connect(self.path, isolation_level=None) return self.conn.cursor()
import os import time import sqlite3 import threading class SQLiteMixin(object): @property
22
64
69
9
12
rahman-mahmudur/PyART
simplejson_test/testdata/pyspider/database/sqlite/tmp.py
Python
SQLiteMixin
SQLiteMixin
7
15
7
9
39c29ca6cdad0849a9ac15e5ab47a929a81ff150
bigcode/the-stack
train
080b462134f204a7f761a99c
train
class
class SplitTableMixin(object): UPDATE_PROJECTS_TIME = 10 * 60 def _tablename(self, project): if self.__tablename__: return '%s_%s' % (self.__tablename__, project) else: return project @property def projects(self): if time.time() - getattr(self, '_last_up...
class SplitTableMixin(object):
UPDATE_PROJECTS_TIME = 10 * 60 def _tablename(self, project): if self.__tablename__: return '%s_%s' % (self.__tablename__, project) else: return project @property def projects(self): if time.time() - getattr(self, '_last_update_projects', 0) \ ...
dbcur(self): pid = (os.getpid(), threading.current_thread().ident) if not (self.conn and pid == self.last_pid): self.last_pid = pid self.conn = sqlite3.connect(self.path, isolation_level=None) return self.conn.cursor() class SplitTableMixin(object):
64
64
214
6
58
rahman-mahmudur/PyART
simplejson_test/testdata/pyspider/database/sqlite/tmp.py
Python
SplitTableMixin
SplitTableMixin
18
49
18
18
25bb1af22ceb0c26ddde8d40f549664aa8bf5ed1
bigcode/the-stack
train
a4ced511a4aff339d0e518f1
train
class
class Session: def __init__(self): self.__requests_session = requests.Session() # self.__requests_session.headers.update({"User-Agent": "medex"}) def api_request(self, url, params=None, auth=None, http_call="get"): if http_call == "get": response = self.__requests_session.ge...
class Session:
def __init__(self): self.__requests_session = requests.Session() # self.__requests_session.headers.update({"User-Agent": "medex"}) def api_request(self, url, params=None, auth=None, http_call="get"): if http_call == "get": response = self.__requests_session.get(url) ...
import requests import time class APIResponseError(Exception): """ Exception raise if the API replies with an HTTP code not in the 2xx range. """ pass class Session:
41
67
225
3
37
SiahaanBernard/python-indodax
indodax/common.py
Python
Session
Session
9
36
9
9
09d6ef4f195c04bb7f2e71e748d0bb66acb8aead
bigcode/the-stack
train
5b837200823bc8ad37d34cb4
train
class
class APIResponseError(Exception): """ Exception raise if the API replies with an HTTP code not in the 2xx range. """ pass
class APIResponseError(Exception):
""" Exception raise if the API replies with an HTTP code not in the 2xx range. """ pass
import requests import time class APIResponseError(Exception):
12
64
32
6
5
SiahaanBernard/python-indodax
indodax/common.py
Python
APIResponseError
APIResponseError
4
7
4
4
527dfcda3c69e416e50105267862c2529965b485
bigcode/the-stack
train
7442fbd262a349d70b0e5936
train
function
def threshold_choose(scores, threshold): mask = scores.gt(threshold) topk_scores = scores[mask] topk_inds = torch.arange(0, scores.numel())[mask.squeeze().flatten()] topk_inds = topk_inds.cuda().to(torch.int64) batch, cat, height, width = scores.size() topk_inds = topk_inds % (height * width) ...
def threshold_choose(scores, threshold):
mask = scores.gt(threshold) topk_scores = scores[mask] topk_inds = torch.arange(0, scores.numel())[mask.squeeze().flatten()] topk_inds = topk_inds.cuda().to(torch.int64) batch, cat, height, width = scores.size() topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().fl...
(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K) topk_xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, K) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def threshold_choose(scores, threshold):
86
86
288
7
78
chenjun2hao/facemask
facemask/model/decode.py
Python
threshold_choose
threshold_choose
33
52
33
33
5e7d4305684a2e9cf5ed4dd1493414b90dca2caa
bigcode/the-stack
train
ff2c4133098a60a3b0d31b51
train
function
def _nms(heat, kernel=3): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep
def _nms(heat, kernel=3):
pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep
import torch import torch.nn as nn from ..utils.util import _gather_feat,_tranpose_and_gather_feat def _nms(heat, kernel=3):
37
64
68
11
25
chenjun2hao/facemask
facemask/model/decode.py
Python
_nms
_nms
5
11
5
5
9cd4a0e682298ebb81e1182fa725e8839228d828
bigcode/the-stack
train
6498536ca14299a826e4ced0
train
function
def ctdet_decode(heat, wh, reg=None, cat_spec_wh=False, K=100): batch, cat, height, width = heat.size() heat = _nms(heat) scores, inds, clses, ys, xs = _topk(heat, K=K) # scores, inds, clses, ys, xs, K = threshold_choose(heat, threshold=threshold) if reg is not None: ...
def ctdet_decode(heat, wh, reg=None, cat_spec_wh=False, K=100):
batch, cat, height, width = heat.size() heat = _nms(heat) scores, inds, clses, ys, xs = _topk(heat, K=K) # scores, inds, clses, ys, xs, K = threshold_choose(heat, threshold=threshold) if reg is not None: reg = _tranpose_and_gather_feat(reg, inds) reg = reg.view...
-1, 1), topk_ind).view(batch, K) topk_ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K) topk_xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, K) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs, K def ctdet_decode(heat, wh, reg=None, cat_spec_wh=False, K=1...
128
128
427
22
105
chenjun2hao/facemask
facemask/model/decode.py
Python
ctdet_decode
ctdet_decode
55
84
55
55
28d23bb11eceff0909ad5ba855971d1b5c77530d
bigcode/the-stack
train
1e105055da02e77878ea6a8e
train
function
def _topk(scores, K=40): batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) # 前100个点 topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() ...
def _topk(scores, K=40):
batch, cat, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K) # 前100个点 topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() topk_score, topk_...
def _nms(heat, kernel=3): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep def _topk(scores, K=40):
78
78
263
10
67
chenjun2hao/facemask
facemask/model/decode.py
Python
_topk
_topk
14
30
14
14
6eac754fbf1a64aa12c7da95d13a6adf3d83de04
bigcode/the-stack
train
f9ddf30cbb62e91c1c5943ee
train
class
class FakeElasticsearch(Elasticsearch): __documents_dict = None def __init__(self, hosts=None, transport_class=None, **kwargs): self.__documents_dict = {} self.__scrolls = {} @query_params() def ping(self, params=None): return True @query_params() def info(self, params...
class FakeElasticsearch(Elasticsearch):
__documents_dict = None def __init__(self, hosts=None, transport_class=None, **kwargs): self.__documents_dict = {} self.__scrolls = {} @query_params() def ping(self, params=None): return True @query_params() def info(self, params=None): return { 'st...
# -*- coding: utf-8 -*- import json import sys from elasticsearch import Elasticsearch from elasticsearch.client.utils import query_params from elasticsearch.exceptions import NotFoundError from elasticmock.utilities import get_random_id, get_random_scroll_id PY3 = sys.version_info[0] == 3 if PY3: unicode = str...
82
256
2,236
8
73
AdamGold/elasticmock
elasticmock/fake_elasticsearch.py
Python
FakeElasticsearch
FakeElasticsearch
17
297
17
17
ff1b3e19488d4267394c3b6c9d788a33ff176b46
bigcode/the-stack
train
bda5a5f39e701077315554e1
train
function
def square_error(x, y): return (x-y).pow(2).sum()
def square_error(x, y):
return (x-y).pow(2).sum()
import torch def square_error(x, y):
10
64
19
7
2
nirvguy/annpy
annpy/metrics.py
Python
square_error
square_error
3
4
3
3
52877427c93a78878102ff6994f844962bfb892c
bigcode/the-stack
train
660e46d7b122e9d757197d44
train
function
def count_fails(x, y): return (x!=y).sum()
def count_fails(x, y):
return (x!=y).sum()
import torch def square_error(x, y): return (x-y).pow(2).sum() def count_fails(x, y):
30
64
17
8
22
nirvguy/annpy
annpy/metrics.py
Python
count_fails
count_fails
6
7
6
6
357e12631672f223a6f64a608181df6beaffec22
bigcode/the-stack
train
9b99633cc42ba2e301fe7c58
train
class
class DateTimeEncoder(JSONEncoder): #Override the default method def default(self, obj): if isinstance(obj, (datetime.date, datetime.datetime)): return obj.isoformat()
class DateTimeEncoder(JSONEncoder): #Override the default method
def default(self, obj): if isinstance(obj, (datetime.date, datetime.datetime)): return obj.isoformat()
datetime from json import JSONEncoder employee = { "id": 456, "name": "William Smith", "salary": 8000, "joindate": datetime.datetime.now() } # subclass JSONEncoder class DateTimeEncoder(JSONEncoder): #Override the default method
64
64
39
14
49
PatrickVienne/PythonAssessment
answers/q8.py
Python
DateTimeEncoder
DateTimeEncoder
17
21
17
18
02cd71aa919159c7379de49b15806552f7deab1d
bigcode/the-stack
train
ab5439960f4b65498bb283a5
train
function
def _add_learning_rate_args(parser): group = parser.add_argument_group(title='learning rate') group.add_argument('--lr', type=float, default=None, help='Initial learning rate. Depending on decay style ' 'and initial warmup, the learing rate at each ' ...
def _add_learning_rate_args(parser):
group = parser.add_argument_group(title='learning rate') group.add_argument('--lr', type=float, default=None, help='Initial learning rate. Depending on decay style ' 'and initial warmup, the learing rate at each ' 'iteration would be differen...
group.add_argument('--codecarbon-dir', type=str, default=None, help='Write CodeCarbon logs to this directory.') return parser def _add_initialization_args(parser): group = parser.add_argument_group(title='initialization') group.add_argument('--seed', type=int, default=1234, ...
160
160
535
8
151
adammoody/Megatron-DeepSpeed
megatron/arguments.py
Python
_add_learning_rate_args
_add_learning_rate_args
481
524
481
481
8598b39d54939b8140d996c45f18c3fab74f8a17
bigcode/the-stack
train
31861221e7bd156ab26c612e
train
function
def _add_zero_args(parser): """Text generate arguments.""" group = parser.add_argument_group('ZeRO configurations', 'configurations') group.add_argument("--zero-stage", type=int, default=1.0) group.add_argument('--zero-reduce-scatter', action='store_true', help='Use reduce scatte...
def _add_zero_args(parser):
"""Text generate arguments.""" group = parser.add_argument_group('ZeRO configurations', 'configurations') group.add_argument("--zero-stage", type=int, default=1.0) group.add_argument('--zero-reduce-scatter', action='store_true', help='Use reduce scatter if specified') group.a...
task') group.add_argument('--num-channels', type=int, default=3, help='Number of channels in input image data') group.add_argument('--patch-dim', type=int, default=16, help='patch dimension used in vit') return parser def _add_zero_args(parser):
65
65
217
7
57
adammoody/Megatron-DeepSpeed
megatron/arguments.py
Python
_add_zero_args
_add_zero_args
790
805
790
790
f4199caba48bf2940136fcf826f57966f676a619
bigcode/the-stack
train