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
81c2427071e10bdd2f91d805
train
function
@contextlib.contextmanager def profile_context(profile=True, profiler_path='./seq2seq.profile'): if profile: with profiler.profiler('All', 'total', profiler_path): yield else: yield
@contextlib.contextmanager def profile_context(profile=True, profiler_path='./seq2seq.profile'):
if profile: with profiler.profiler('All', 'total', profiler_path): yield else: yield
[0] == '2': reload(sys) sys.setdefaultencoding("utf-8") from args import * from base_model import BaseModel from attention_model import AttentionModel import logging import pickle @contextlib.contextmanager def profile_context(profile=True, profiler_path='./seq2seq.profile'):
64
64
47
20
43
weiwei1115/models
PaddleNLP/legacy/seq2seq/seq2seq/train.py
Python
profile_context
profile_context
49
55
49
50
96ce1a93a479da08a6d2b39d70f8e4627156ae2b
bigcode/the-stack
train
c8ae8102a0cb2bc0e5aa9df8
train
function
def binarize_categorical_columns( input_train_df, input_test_df, categorical_columns): """Function to converting categorical features to one-hot encodings.""" # Binarize categorical columns. binarized_train_df = pd.get_dummies( input_train_df, columns=categorical_columns) binarized_test_df = pd.get_d...
def binarize_categorical_columns( input_train_df, input_test_df, categorical_columns):
"""Function to converting categorical features to one-hot encodings.""" # Binarize categorical columns. binarized_train_df = pd.get_dummies( input_train_df, columns=categorical_columns) binarized_test_df = pd.get_dummies( input_test_df, columns=categorical_columns) # Make sure the train and test...
# Bucketize using provided bin cut-points. input_train_df[continuous_column_name] = pd.cut( input_train_df[continuous_column_name], bins, labels=False) input_test_df[continuous_column_name] = pd.cut( input_test_df[continuous_column_name], bins, labels=False) def binarize_categorical_columns( ...
84
84
281
20
64
jrmendeshurb/google-research
generalized_rates/datasets/load_adult.py
Python
binarize_categorical_columns
binarize_categorical_columns
72
96
72
73
95a253c9213da9dceab7578095ffcda96cc45aaf
bigcode/the-stack
train
387f8dc9077095299bb2ca7e
train
function
def bucketize_continuous_column( input_train_df, input_test_df, continuous_column_name, num_quantiles=None, bins=None): """Bucketize continuous columns using either bin cut-points or quantiles.""" assert (num_quantiles is None or bins is None) if num_quantiles is not None: # Compute quantile cut-point...
def bucketize_continuous_column( input_train_df, input_test_df, continuous_column_name, num_quantiles=None, bins=None):
"""Bucketize continuous columns using either bin cut-points or quantiles.""" assert (num_quantiles is None or bins is None) if num_quantiles is not None: # Compute quantile cut-points and bucketize. _, bins_quantized = pd.qcut( input_train_df[continuous_column_name], num_quantiles, retbins=True, ...
test_file", "adult.test", "Path to Adult test data file.") flags.DEFINE_string("output_directory", "datasets/", "Path to store processed dataset.") FLAGS = flags.FLAGS def bucketize_continuous_column( input_train_df, input_test_df, continuous_column_name, num_quantiles=None...
72
72
241
30
41
jrmendeshurb/google-research
generalized_rates/datasets/load_adult.py
Python
bucketize_continuous_column
bucketize_continuous_column
50
69
50
52
269a398a1f1836e51b7fe86edf72e1df240dda6f
bigcode/the-stack
train
2aa58b2b080235eb5aca49f3
train
function
def main(argv): if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") # Load and pre-process Adult train and test datasets. train_set, test_set = load_data() x_train, y_train, z_train = test_set # Split train data into train and validation sets. train_indices, vali_indices = model...
def main(argv):
if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") # Load and pre-process Adult train and test datasets. train_set, test_set = load_data() x_train, y_train, z_train = test_set # Split train data into train and validation sets. train_indices, vali_indices = model_selection.train...
train_df[feature_names].to_numpy() features_test = test_df[feature_names].to_numpy() # Return train and test set tuples. train_set = (features_train, labels_train, groups_train) test_set = (features_test, labels_test, groups_test) return train_set, test_set def main(argv):
71
71
239
4
66
jrmendeshurb/google-research
generalized_rates/datasets/load_adult.py
Python
main
main
168
193
168
168
0d55fe737b8d2ba7efd7febb22526dc2937a5268
bigcode/the-stack
train
06ee11fc333c34f119e9a75f
train
function
def load_data(): """Load and process train and test datasets at provided data paths.""" columns = [ "age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation", "relationship", "race", "gender", "capital_gain", "capital_loss", "hours_per_week", "native_country", ...
def load_data():
"""Load and process train and test datasets at provided data paths.""" columns = [ "age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation", "relationship", "race", "gender", "capital_gain", "capital_loss", "hours_per_week", "native_country", "income_bracket...
) binarized_test_df = pd.get_dummies( input_test_df, columns=categorical_columns) # Make sure the train and test dataframes have the same binarized columns. # Identify columns in train set not in test set and fill them in test set. test_df_missing_cols = set(binarized_train_df.columns) - set( binar...
223
223
744
4
218
jrmendeshurb/google-research
generalized_rates/datasets/load_adult.py
Python
load_data
load_data
99
165
99
99
b11f23e80e031cca7de4f5732d30d87c5e862579
bigcode/the-stack
train
84c5aa9921d95108b7b3b450
train
function
@mod.capture(rule="{self.ordinal_words}") def ordinals(m) -> int: "Returns a single ordinial as a digit" o = m[0] return int(ordinal_words[o])
@mod.capture(rule="{self.ordinal_words}") def ordinals(m) -> int:
"Returns a single ordinial as a digit" o = m[0] return int(ordinal_words[o])
join(ordinal_list) return result for n in range(1, 100): ordinal_words[ordinal_word(n)] = n mod = Module() mod.list("ordinal_words", desc="list of ordinals") @mod.capture(rule="{self.ordinal_words}") def ordinals(m) -> int:
64
64
43
17
47
gimpf/talon-conf
base/number_ordinals.py
Python
ordinals
ordinals
95
99
95
96
888e96fdf11a105b17bd91603deb69e44048f6d9
bigcode/the-stack
train
366cdba4454cc7c47925ab83
train
function
def ordinal_word(n): n = int(n) ordinal_list = [] if n > 19: if n % 10 == 0: ordinal_list.append(ordinal_tens[floor((n / 10)) - 2]) else: ordinal_list.append(ordinal_tenty[floor(n / 10) - 2]) ordinal_list.append(ordinal_ones[(n % 10) - 1]) elif n > 9: ...
def ordinal_word(n):
n = int(n) ordinal_list = [] if n > 19: if n % 10 == 0: ordinal_list.append(ordinal_tens[floor((n / 10)) - 2]) else: ordinal_list.append(ordinal_tenty[floor(n / 10) - 2]) ordinal_list.append(ordinal_ones[(n % 10) - 1]) elif n > 9: ordinal_list....
int(n) suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)] if 11 <= (n % 100) <= 13: suffix = "th" return str(n) + suffix def ordinal_word(n):
64
64
143
5
58
gimpf/talon-conf
base/number_ordinals.py
Python
ordinal_word
ordinal_word
70
85
70
70
0206b767723b8967e26ce0526d3022816d1c9851
bigcode/the-stack
train
073af9de5acfcdcdc58a2c51
train
function
def ordinal(n): """ Convert an integer into its ordinal representation:: ordinal(0) => '0th' ordinal(3) => '3rd' ordinal(122) => '122nd' ordinal(213) => '213th' """ n = int(n) suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)] if 11 <= (n % 100) <= 13: ...
def ordinal(n):
""" Convert an integer into its ordinal representation:: ordinal(0) => '0th' ordinal(3) => '3rd' ordinal(122) => '122nd' ordinal(213) => '213th' """ n = int(n) suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)] if 11 <= (n % 100) <= 13: suffix = "...
"eightieth", "ninetieth", ] ordinal_tenty = [ "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", ] def ordinal(n):
64
64
121
4
60
gimpf/talon-conf
base/number_ordinals.py
Python
ordinal
ordinal
55
67
55
55
164e4c6752ed19735c01eef6f2c79f77e4a921b0
bigcode/the-stack
train
6d9cfee1675f8207183f20da
train
function
def test_without_thickness_surface(): clientModel.service.begin_modification('new') # Testing the standard surface function Node(1, 0, -30, 0), Node(2, 10, -30, 0), Node(3, 10, -20, 0), Node(4, 0, -20, 0) Line(1, '1 2'), Line(2, '2 3'), Line(3, '3 4'), Line(4, '4 1') Material(name='C30/37') Th...
def test_without_thickness_surface():
clientModel.service.begin_modification('new') # Testing the standard surface function Node(1, 0, -30, 0), Node(2, 10, -30, 0), Node(3, 10, -20, 0), Node(4, 0, -20, 0) Line(1, '1 2'), Line(2, '2 3'), Line(3, '3 4'), Line(4, '4 1') Material(name='C30/37') Thickness() Surface() # Standard...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path.append(".") ## Import the relevant Libraries from os import name from RFEM.enums import * #from RFEM.window import * from RFEM.dataTypes import * from RFEM.initModel import * from RFEM.BasicObjects.material import * from RFEM.BasicObjects.section impor...
253
256
955
7
246
r0m30d4c/DlubalRFEM6
UnitTests/test_WithoutThicknessSurface_Test.py
Python
test_without_thickness_surface
test_without_thickness_surface
34
88
34
35
cf99d2548bf65ac544ac028f4e8f75030cbc478c
bigcode/the-stack
train
cdeb7a7c1ad3f73165a37aa2
train
class
class Migration(migrations.Migration): dependencies = [ ('smart_contract', '0004_auto_20180711_2050'), ] operations = [ migrations.AlterField( model_name='comment', name='date_update', field=models.DateTimeField(auto_now=True, null=True), ), ...
class Migration(migrations.Migration):
dependencies = [ ('smart_contract', '0004_auto_20180711_2050'), ] operations = [ migrations.AlterField( model_name='comment', name='date_update', field=models.DateTimeField(auto_now=True, null=True), ), ]
# Generated by Django 2.0.7 on 2018-07-12 18:41 from django.db import migrations, models class Migration(migrations.Migration):
38
64
68
7
30
RustamSultanov/Python-test-registry-
registry/smart_contract/migrations/0005_auto_20180712_1841.py
Python
Migration
Migration
6
18
6
7
f06bde29728215b44a171251d83c754b4a4540ee
bigcode/the-stack
train
cb30cea972d3dfad86c6e101
train
class
class ColorSchemeBuilder(object): """A class for building a color scheme.""" _scope_name_template = "CH_color_%s" _color_scope_template = """ <dict> <key>name</key> <string>CH_color</string> <key>scope</key> <string>CH_color_%s</string> <key>settings</key> <dict> <key>background</key> <string>%s</string> <...
class ColorSchemeBuilder(object):
"""A class for building a color scheme.""" _scope_name_template = "CH_color_%s" _color_scope_template = """ <dict> <key>name</key> <string>CH_color</string> <key>scope</key> <string>CH_color_%s</string> <key>settings</key> <dict> <key>background</key> <string>%s</string> <key>foreground</key> <string>%s</s...
"""A color highlighter that uses color scheme scopes to highlight colors.""" import threading from xml.etree import ElementTree try: from .st_helper import running_in_st, is_st3 from . import colors from .color_highlighter import ColorHighlighter except ValueError: from st_helper import running_in_st,...
120
232
775
6
113
EatBreatheCode/ColorHighlighter
color_scheme_color_highlighter.py
Python
ColorSchemeBuilder
ColorSchemeBuilder
21
122
21
21
4f7c515161786a980405f812e146a3b15f0aa49b
bigcode/the-stack
train
713e07e9ef2af62c3db34881
train
class
class ColorSchemeColorHighlighter(ColorHighlighter): """A color highlighter that uses color scheme scopes to highlight colors.""" region_name_template = "CH_color_%s_%d_%d" if is_st3(): _region_style_flags = { "filled": sublime.DRAW_NO_OUTLINE, "text": sublime.DRAW_NO_OUTLI...
class ColorSchemeColorHighlighter(ColorHighlighter):
"""A color highlighter that uses color scheme scopes to highlight colors.""" region_name_template = "CH_color_%s_%d_%d" if is_st3(): _region_style_flags = { "filled": sublime.DRAW_NO_OUTLINE, "text": sublime.DRAW_NO_OUTLINE, "outlined": sublime.DRAW_NO_FILL, ...
scopes = [] for color in for_colors: if color in existing_colors: continue opposite_color = colors.complementary_color(color) background_color = self._color_scheme_data.background_color fixed_color = colors.background_colo...
237
237
791
10
226
EatBreatheCode/ColorHighlighter
color_scheme_color_highlighter.py
Python
ColorSchemeColorHighlighter
ColorSchemeColorHighlighter
125
212
125
125
029d2cc17fb7407ca9e658e7209fa1fc3881acfa
bigcode/the-stack
train
55cf65870c78d903f9afe8b5
train
class
class BadBlockBlock(Block): def __init__(self, blkdev, blk_num=0): Block.__init__(self, blkdev, blk_num, chk_loc=2, is_type=Block.BADB) def create(self, block_pairs, host_id, size=128, next=0): Block.create(self) self.size = size self.host_id = host_id self.next = next self.block_pairs = ...
class BadBlockBlock(Block):
def __init__(self, blkdev, blk_num=0): Block.__init__(self, blkdev, blk_num, chk_loc=2, is_type=Block.BADB) def create(self, block_pairs, host_id, size=128, next=0): Block.create(self) self.size = size self.host_id = host_id self.next = next self.block_pairs = block_pairs def wri...
from __future__ import absolute_import from __future__ import print_function from ..Block import Block class BadBlockBlock(Block):
28
127
424
6
21
limi/AGSImager
dependencies/amitools-0.1.0/amitools/fs/block/rdb/BadBlocksBlock.py
Python
BadBlockBlock
BadBlockBlock
6
61
6
6
dd15eb5c07e0aa1288b9355a0f6f4c38334a8353
bigcode/the-stack
train
c8fa2fb8dc3c451c79b4304c
train
function
def try_simplify_traceback(tb: TracebackType) -> Optional[TracebackType]: """ Simplify the traceback. It removes the tracebacks in the current package, and only shows the traceback that is related to the thirdparty and user-specified codes. Returns ------- TracebackType or None Simplified...
def try_simplify_traceback(tb: TracebackType) -> Optional[TracebackType]:
""" Simplify the traceback. It removes the tracebacks in the current package, and only shows the traceback that is related to the thirdparty and user-specified codes. Returns ------- TracebackType or None Simplified traceback instance. It returns None if it fails to simplify. Notes ...
d+)(\..*)?$", sparkVersion) if m is not None: return (int(m.group(1)), int(m.group(2))) else: raise ValueError( "Spark tried to parse '%s' as a Spark" % sparkVersion + " version string, but it could not find the major and minor" + "...
256
256
1,206
20
235
yangwwei/spark
python/pyspark/util.py
Python
try_simplify_traceback
try_simplify_traceback
96
226
96
96
a28b51bbc311c9d61956dca920e2b6ada8bf0572
bigcode/the-stack
train
ed71ec70812930f655184021
train
function
def walk_tb(tb: Optional[TracebackType]) -> Iterator[TracebackType]: while tb is not None: yield tb tb = tb.tb_next
def walk_tb(tb: Optional[TracebackType]) -> Iterator[TracebackType]:
while tb is not None: yield tb tb = tb.tb_next
try: return f(*args, **kwargs) except StopIteration as exc: raise RuntimeError( "Caught StopIteration thrown from user's code; failing the task", exc ) return wrapper def walk_tb(tb: Optional[TracebackType]) -> Iterator[TracebackType]:
64
64
36
18
45
yangwwei/spark
python/pyspark/util.py
Python
walk_tb
walk_tb
90
93
90
90
47d6a52ec6d9ef93b40a58677881770bd9f958d8
bigcode/the-stack
train
74409a5471fcc4d9ce556f2d
train
function
def _parse_memory(s: str) -> int: """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB Examples -------- >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {"g": 1024, "m": 1, "t": 1 << 20, "k": 1.0 / 1024}...
def _parse_memory(s: str) -> int:
""" Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB Examples -------- >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {"g": 1024, "m": 1, "t": 1 << 20, "k": 1.0 / 1024} if s[-1].lower() not in units...
<spark-%(jar_name)s.jar> ... ________________________________________________________________________________________________ """ % { "lib_name": lib_name, "pkg_name": pkg_name, "jar_name": jar_name, "spark_version": spark_version, } ) def _parse_me...
64
64
158
11
53
yangwwei/spark
python/pyspark/util.py
Python
_parse_memory
_parse_memory
259
274
259
259
116dfb01e860d6694d0bd0a3ad711cc3989955aa
bigcode/the-stack
train
a3d958db5cb129f7e934b731
train
function
def inheritable_thread_target(f: Callable) -> Callable: """ Return thread target wrapper which is recommended to be used in PySpark when the pinned thread mode is enabled. The wrapper function, before calling original thread target, it inherits the inheritable properties specific to JVM thread such ...
def inheritable_thread_target(f: Callable) -> Callable:
""" Return thread target wrapper which is recommended to be used in PySpark when the pinned thread mode is enabled. The wrapper function, before calling original thread target, it inherits the inheritable properties specific to JVM thread such as ``InheritableThreadLocal``. Also, note that pinn...
} ) def _parse_memory(s: str) -> int: """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB Examples -------- >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {"g": 1024, "m": 1, "t": 1 << 20, "k": ...
173
174
581
12
162
yangwwei/spark
python/pyspark/util.py
Python
inheritable_thread_target
inheritable_thread_target
277
344
277
277
d03d099115ffd4730648223071d7c62b6b5c410e
bigcode/the-stack
train
079281a96f33b66b0903eed2
train
function
def _print_missing_jar(lib_name: str, pkg_name: str, jar_name: str, spark_version: str) -> None: print( """ ________________________________________________________________________________________________ Spark %(lib_name)s libraries not found in class path. Try one of the following. 1. Include the %(...
def _print_missing_jar(lib_name: str, pkg_name: str, jar_name: str, spark_version: str) -> None:
print( """ ________________________________________________________________________________________________ Spark %(lib_name)s libraries not found in class path. Try one of the following. 1. Include the %(lib_name)s library and its dependencies with in the spark-submit command as $ bin/spar...
tb_lineno=cur_tb.tb_frame.f_lineno if cur_tb.tb_frame.f_lineno is not None else -1, ) tb_next = new_tb return new_tb def _print_missing_jar(lib_name: str, pkg_name: str, jar_name: str, spark_version: str) -> None:
67
67
224
29
37
yangwwei/spark
python/pyspark/util.py
Python
_print_missing_jar
_print_missing_jar
229
256
229
229
b8c69eded07aa37ffae7455b50f0cb3aa18a8367
bigcode/the-stack
train
161e37815e1af06678563571
train
class
class InheritableThread(threading.Thread): """ Thread that is recommended to be used in PySpark instead of :class:`threading.Thread` when the pinned thread mode is enabled. The usage of this class is exactly same as :class:`threading.Thread` but correctly inherits the inheritable properties specific ...
class InheritableThread(threading.Thread):
""" Thread that is recommended to be used in PySpark instead of :class:`threading.Thread` when the pinned thread mode is enabled. The usage of this class is exactly same as :class:`threading.Thread` but correctly inherits the inheritable properties specific to JVM thread such as ``InheritableThreadL...
(PYSPARK_PIN_THREAD) is on. # NOTICE the internal difference vs `InheritableThread`. `InheritableThread` # copies local properties when the thread starts but `inheritable_thread_target` # copies when the function is wrapped. assert SparkContext._active_spark_context is not None ...
204
204
681
9
194
yangwwei/spark
python/pyspark/util.py
Python
InheritableThread
InheritableThread
347
421
347
347
aa2d70405a419bcf329660ee6af8aee22a7a97b4
bigcode/the-stack
train
eeeb6a4dbc538f00337b43a2
train
function
def print_exec(stream: TextIO) -> None: ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, stream)
def print_exec(stream: TextIO) -> None:
ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, stream)
from typing import Any, Callable, Iterator, List, Optional, TextIO, Tuple from py4j.clientserver import ClientServer # type: ignore[import] __all__: List[str] = [] from py4j.java_gateway import JavaObject def print_exec(stream: TextIO) -> None:
64
64
39
11
52
yangwwei/spark
python/pyspark/util.py
Python
print_exec
print_exec
37
39
37
37
ec5b902f78e1f7e2a7cd7b016874ef80d337d6d8
bigcode/the-stack
train
bfe549bb31b5fe2fb25377df
train
function
def fail_on_stopiteration(f: Callable) -> Callable: """ Wraps the input function to fail on 'StopIteration' by raising a 'RuntimeError' prevents silent loss of data when 'f' is used in a for loop in Spark code """ def wrapper(*args: Any, **kwargs: Any) -> Any: try: return f(*arg...
def fail_on_stopiteration(f: Callable) -> Callable:
""" Wraps the input function to fail on 'StopIteration' by raising a 'RuntimeError' prevents silent loss of data when 'f' is used in a for loop in Spark code """ def wrapper(*args: Any, **kwargs: Any) -> Any: try: return f(*args, **kwargs) except StopIteration as exc: ...
(2))) else: raise ValueError( "Spark tried to parse '%s' as a Spark" % sparkVersion + " version string, but it could not find the major and minor" + " version numbers." ) def fail_on_stopiteration(f: Callable) -> Callable:
64
64
118
12
52
yangwwei/spark
python/pyspark/util.py
Python
fail_on_stopiteration
fail_on_stopiteration
73
87
73
73
eaf5ecb49daf173bc9138a6b56c3bb2b3ee929f2
bigcode/the-stack
train
1f0c70256699aca1088a9913
train
class
class VersionUtils: """ Provides utility method to determine Spark versions with given input string. """ @staticmethod def majorMinorVersion(sparkVersion: str) -> Tuple[int, int]: """ Given a Spark version string, return the (major version number, minor version number). E.g....
class VersionUtils:
""" Provides utility method to determine Spark versions with given input string. """ @staticmethod def majorMinorVersion(sparkVersion: str) -> Tuple[int, int]: """ Given a Spark version string, return the (major version number, minor version number). E.g., for 2.0.1-SNAPSHOT...
.clientserver import ClientServer # type: ignore[import] __all__: List[str] = [] from py4j.java_gateway import JavaObject def print_exec(stream: TextIO) -> None: ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, stream) class VersionUtils:
74
74
249
4
70
yangwwei/spark
python/pyspark/util.py
Python
VersionUtils
VersionUtils
42
70
42
42
44570e95951a1b2140d4e8110a9c1e80f417c6dc
bigcode/the-stack
train
0c1a1e2c6fc72a24eb018f42
train
class
class TestUsersRealApi: @classmethod def setup_class(cls): configuration = Configuration() api_key = os.getenv('JC_API_KEY') assert (api_key is not None),\ "The environmental variable `JC_API_KEY` must contain a valid Jumpcloud API key" configuration.api_key['x-api-ke...
class TestUsersRealApi: @classmethod
def setup_class(cls): configuration = Configuration() api_key = os.getenv('JC_API_KEY') assert (api_key is not None),\ "The environmental variable `JC_API_KEY` must contain a valid Jumpcloud API key" configuration.api_key['x-api-key'] = api_key cls.systemusers_api...
import json import os from jcapiv1 import ApiClient, Configuration, Systemuserslist, Systemuserputpost from jccli import cli from click.testing import CliRunner, Result from jcapiv1.api.systemusers_api import SystemusersApi class TestUsersRealApi: @classmethod
65
196
656
10
54
cascadianblue/jccli
integration_tests/test_users_real_api.py
Python
TestUsersRealApi
TestUsersRealApi
11
110
11
12
ed87d4c207e16440e20f90551289af62a82201b9
bigcode/the-stack
train
ce766699a4fdf727fda13878
train
function
def transcribe_streaming(stream_file): """Streams transcription of the given audio file.""" import io from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types client = speech.SpeechClient() # [START speech_python_migration_streaming_request...
def transcribe_streaming(stream_file):
"""Streams transcription of the given audio file.""" import io from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types client = speech.SpeechClient() # [START speech_python_migration_streaming_request] with io.open(stream_file, 'rb') a...
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google Cloud Spee...
105
105
352
8
97
summersab/python-docs-samples
speech/cloud-client/transcribe_streaming.py
Python
transcribe_streaming
transcribe_streaming
27
66
27
27
44cb335f27eb1f96d6f864a0f8a22eea6095d3d7
bigcode/the-stack
train
21aebff1b09777aa45478621
train
function
def view_mpl(points: list, splits: list, bounds: V, palette: int or list, titles: Tuple[str]): numpy_images = [] bounding_box = extrude_bounds(bounds) titles = [titles[i] if i < len(titles) else '' for i in range(len(points))] for pts, split, color, title in zip(points, splits, palette, titles): ...
def view_mpl(points: list, splits: list, bounds: V, palette: int or list, titles: Tuple[str]):
numpy_images = [] bounding_box = extrude_bounds(bounds) titles = [titles[i] if i < len(titles) else '' for i in range(len(points))] for pts, split, color, title in zip(points, splits, palette, titles): ax, fig = init_fig(bounds, 1) add_points(ax, bounding_box, bounds, V([0, 8], dtype=np....
bounding_box[corner, axis] = bounds[(corner % (f * 2)) // f, axis] f = f * 2 return bounding_box def view_mpl(points: list, splits: list, bounds: V, palette: int or list, titles: Tuple[str]):
64
64
161
27
36
haohlin/pointgmm-primitive-detection
show/viewer_mpl.py
Python
view_mpl
view_mpl
78
90
78
78
525bbe4746badc5fd63e53c3e36760f5498d99b1
bigcode/the-stack
train
ae8914a137c43dbaa12c98ab
train
function
def fig2data(fig: plt.Figure): # taken from http://www.icare.univ-lille1.fr/tutorials/convert_a_matplotlib_figure # Thanks! fig.canvas.draw() w, h = fig.canvas.get_width_height() buf = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8) buf.shape = (h, w, 3) return buf
def fig2data(fig: plt.Figure): # taken from http://www.icare.univ-lille1.fr/tutorials/convert_a_matplotlib_figure # Thanks!
fig.canvas.draw() w, h = fig.canvas.get_width_height() buf = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8) buf.shape = (h, w, 3) return buf
.set_yticks([]) ax.set_zticks([]) ax.dist = 7 return ax, fig def fig2data(fig: plt.Figure): # taken from http://www.icare.univ-lille1.fr/tutorials/convert_a_matplotlib_figure # Thanks!
64
64
88
39
24
haohlin/pointgmm-primitive-detection
show/viewer_mpl.py
Python
fig2data
fig2data
58
65
58
60
44588eaba51e343dd862661ea1cb952e4b363e69
bigcode/the-stack
train
ad5d5f1c3f192754ca030b6a
train
function
def extrude_bounds(bounds:V) -> V: bounding_box = np.zeros((2 ** bounds.shape[1], bounds.shape[1])) f = 1 for axis in range(bounding_box.shape[1]): for corner in range(bounding_box.shape[0]): bounding_box[corner, axis] = bounds[(corner % (f * 2)) // f, axis] f = f * 2 return ...
def extrude_bounds(bounds:V) -> V:
bounding_box = np.zeros((2 ** bounds.shape[1], bounds.shape[1])) f = 1 for axis in range(bounding_box.shape[1]): for corner in range(bounding_box.shape[0]): bounding_box[corner, axis] = bounds[(corner % (f * 2)) // f, axis] f = f * 2 return bounding_box
# Thanks! fig.canvas.draw() w, h = fig.canvas.get_width_height() buf = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8) buf.shape = (h, w, 3) return buf def extrude_bounds(bounds:V) -> V:
64
64
97
11
52
haohlin/pointgmm-primitive-detection
show/viewer_mpl.py
Python
extrude_bounds
extrude_bounds
68
75
68
68
3271658308908fa20c421691fc9621121293a175
bigcode/the-stack
train
d69f019c9d4a41aaa55a6d92
train
function
def add_points(container, points, bounds, split, color: int or list or tuple): if type(color) is int or type(color) is tuple: color = (split.shape[0] - 1) * [color] for i in range(0, split.shape[0] - 1): c = color[i] if type(c) is int or type(c) is float: c = (c, c, c) ...
def add_points(container, points, bounds, split, color: int or list or tuple):
if type(color) is int or type(color) is tuple: color = (split.shape[0] - 1) * [color] for i in range(0, split.shape[0] - 1): c = color[i] if type(c) is int or type(c) is float: c = (c, c, c) if type(c[0]) is int: c = [float(c[i]) / 255. for i in range(3)] ...
axis_mask = np.logical_and(bounds[0][i] <= points[:, i], points[:, i] <= bounds[1][i]) mask = np.logical_and(mask, axis_mask) return points[mask] def add_points(container, points, bounds, split, color: int or list or tuple):
64
64
207
19
45
haohlin/pointgmm-primitive-detection
show/viewer_mpl.py
Python
add_points
add_points
18
29
18
18
2fcadedeb5c2f73a845c2fe4a25bb95644fd032b
bigcode/the-stack
train
624e28c3543dad26a3d9ef00
train
function
def init_fig(bounds: V, num_objects:int): fig = plt.figure(figsize=(max(num_objects * 2, 3.5), 3.5)) ax = fig.gca(projection='3d') scale = bounds[1] - bounds[0] scale = np.diag([scale[0], scale[1], scale[2], 1.0]) scale = scale * (1.0 / scale.max()) scale[3, 3] = 1.0 def short_proj(): ...
def init_fig(bounds: V, num_objects:int):
fig = plt.figure(figsize=(max(num_objects * 2, 3.5), 3.5)) ax = fig.gca(projection='3d') scale = bounds[1] - bounds[0] scale = np.diag([scale[0], scale[1], scale[2], 1.0]) scale = scale * (1.0 / scale.max()) scale[3, 3] = 1.0 def short_proj(): return np.dot(Axes3D.get_proj(ax), scale...
float(c[i]) / 255. for i in range(3)] cur_points = clear_outside_points(points[split[i]: split[i + 1], :], bounds) if len(cur_points) > 0: container.scatter(cur_points[:, 0], cur_points[:, 1], cur_points[:, 2], marker='o', s=3, c=((c[0],c[1],c[2]),), alpha=.4) def init_fig(bounds: V, num_obj...
107
107
358
11
96
haohlin/pointgmm-primitive-detection
show/viewer_mpl.py
Python
init_fig
init_fig
32
55
32
32
0033ae90da00a1bd64f2f1c5d4a370fc11aeda11
bigcode/the-stack
train
1ac43012cbc58b90ba20614d
train
function
def clear_outside_points(points, bounds): mask = np.ones(points.shape[0], dtype=np.bool) for i in range(points.shape[1]): axis_mask = np.logical_and(bounds[0][i] <= points[:, i], points[:, i] <= bounds[1][i]) mask = np.logical_and(mask, axis_mask) return points[mask]
def clear_outside_points(points, bounds):
mask = np.ones(points.shape[0], dtype=np.bool) for i in range(points.shape[1]): axis_mask = np.logical_and(bounds[0][i] <= points[:, i], points[:, i] <= bounds[1][i]) mask = np.logical_and(mask, axis_mask) return points[mask]
from mpl_toolkits.mplot3d.axes3d import Axes3D from mpl_toolkits.mplot3d import proj3d import matplotlib as mpl import matplotlib.pyplot as plt from custom_types import * mpl.use('Agg') def clear_outside_points(points, bounds):
60
64
79
9
51
haohlin/pointgmm-primitive-detection
show/viewer_mpl.py
Python
clear_outside_points
clear_outside_points
10
15
10
10
f6ff8a0dbf95f6a737fc06215e2bc3f93770961d
bigcode/the-stack
train
f1154bf92fdaa6fcf52cbc5d
train
function
@pytest.fixture def graphql_client(release_test_map, retrying_requests): dagit_host = os.environ.get("BACKCOMPAT_TESTS_DAGIT_HOST", "localhost") dagit_version = release_test_map["dagit"] user_code_version = release_test_map["user_code"] with docker_service_up( file_relative_path(__file__, "./d...
@pytest.fixture def graphql_client(release_test_map, retrying_requests):
dagit_host = os.environ.get("BACKCOMPAT_TESTS_DAGIT_HOST", "localhost") dagit_version = release_test_map["dagit"] user_code_version = release_test_map["user_code"] with docker_service_up( file_relative_path(__file__, "./dagit_service/docker-compose.yml"), build_args=[dagit_version, use...
: yield finally: subprocess.check_output(["docker-compose", "-f", docker_compose_file, "stop"]) subprocess.check_output(["docker-compose", "-f", docker_compose_file, "rm", "-f"]) @pytest.fixture def graphql_client(release_test_map, retrying_requests):
63
64
145
15
48
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
graphql_client
graphql_client
106
119
106
107
2674ba138fe2009eb2206e55c8d72a0fc5dc8991
bigcode/the-stack
train
572a40e13ec4a1091db281e2
train
function
def test_backcompat_deployed_pipeline(graphql_client): assert_runs_and_exists(graphql_client, "the_pipeline")
def test_backcompat_deployed_pipeline(graphql_client):
assert_runs_and_exists(graphql_client, "the_pipeline")
_version], ): result = retrying_requests.get(f"http://{dagit_host}:3000/dagit_info") assert result.json().get("dagit_version") yield DagsterGraphQLClient(dagit_host, port_number=3000) def test_backcompat_deployed_pipeline(graphql_client):
64
64
24
11
53
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
test_backcompat_deployed_pipeline
test_backcompat_deployed_pipeline
122
123
122
122
33df1f27338dbdcc390e2e0153ad366cf04a92dd
bigcode/the-stack
train
eac0e1061871eea579a18f27
train
function
@contextmanager def docker_service_up(docker_compose_file, build_args=None): if IS_BUILDKITE: yield # buildkite pipeline handles the service return try: subprocess.check_output(["docker-compose", "-f", docker_compose_file, "stop"]) subprocess.check_output(["docker-compose", "-f...
@contextmanager def docker_service_up(docker_compose_file, build_args=None):
if IS_BUILDKITE: yield # buildkite pipeline handles the service return try: subprocess.check_output(["docker-compose", "-f", docker_compose_file, "stop"]) subprocess.check_output(["docker-compose", "-f", docker_compose_file, "rm", "-f"]) except subprocess.CalledProcessError...
= dagster_most_recent_release user_code_version = request.param[1] if user_code_version == MOST_RECENT_RELEASE_PLACEHOLDER: user_code_version = dagster_most_recent_release return {"dagit": dagit_version, "user_code": user_code_version} @contextmanager def docker_service_up(docker_compose_file, bui...
80
80
269
18
62
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
docker_service_up
docker_service_up
73
103
73
74
8b355c72ba32e63861af3c57ce2d46653830d8ca
bigcode/the-stack
train
ee150ca75074d05a285d5c9f
train
function
def test_backcompat_deployed_pipeline_subset(graphql_client): assert_runs_and_exists(graphql_client, "the_pipeline", subset_selection=["my_solid"])
def test_backcompat_deployed_pipeline_subset(graphql_client):
assert_runs_and_exists(graphql_client, "the_pipeline", subset_selection=["my_solid"])
assert result.json().get("dagit_version") yield DagsterGraphQLClient(dagit_host, port_number=3000) def test_backcompat_deployed_pipeline(graphql_client): assert_runs_and_exists(graphql_client, "the_pipeline") def test_backcompat_deployed_pipeline_subset(graphql_client):
64
64
32
12
52
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
test_backcompat_deployed_pipeline_subset
test_backcompat_deployed_pipeline_subset
126
127
126
126
a19e245e37c36fdb21b3369e4612df4f6f82c3c4
bigcode/the-stack
train
da035a3b7a6b0a2041b9ff74
train
function
def test_backcompat_deployed_job_subset(graphql_client): assert_runs_and_exists(graphql_client, "the_job", subset_selection=["my_op"])
def test_backcompat_deployed_job_subset(graphql_client):
assert_runs_and_exists(graphql_client, "the_job", subset_selection=["my_op"])
ployed_pipeline_subset(graphql_client): assert_runs_and_exists(graphql_client, "the_pipeline", subset_selection=["my_solid"]) def test_backcompat_deployed_job(graphql_client): assert_runs_and_exists(graphql_client, "the_job") def test_backcompat_deployed_job_subset(graphql_client):
64
64
31
12
52
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
test_backcompat_deployed_job_subset
test_backcompat_deployed_job_subset
134
135
134
134
0af5a3c3e28c20d707af09f61928504998796467
bigcode/the-stack
train
01639ccdb10c318bb8f044ab
train
function
def test_backcompat_deployed_job(graphql_client): assert_runs_and_exists(graphql_client, "the_job")
def test_backcompat_deployed_job(graphql_client):
assert_runs_and_exists(graphql_client, "the_job")
_deployed_pipeline(graphql_client): assert_runs_and_exists(graphql_client, "the_pipeline") def test_backcompat_deployed_pipeline_subset(graphql_client): assert_runs_and_exists(graphql_client, "the_pipeline", subset_selection=["my_solid"]) def test_backcompat_deployed_job(graphql_client):
63
64
24
11
52
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
test_backcompat_deployed_job
test_backcompat_deployed_job
130
131
130
130
678e61563b02cea5bdee021e71a6f318a527ccf9
bigcode/the-stack
train
8388bf5a2c12deceec36c0e5
train
function
@pytest.fixture( params=[ pytest.param(value, marks=getattr(pytest.mark, key), id=key) for key, value in RELEASE_TEST_MAP.items() ], ) def release_test_map(request, dagster_most_recent_release): dagit_version = request.param[0] if dagit_version == MOST_RECENT_RELEASE_PLACEHOLDER: ...
@pytest.fixture( params=[ pytest.param(value, marks=getattr(pytest.mark, key), id=key) for key, value in RELEASE_TEST_MAP.items() ], ) def release_test_map(request, dagster_most_recent_release):
dagit_version = request.param[0] if dagit_version == MOST_RECENT_RELEASE_PLACEHOLDER: dagit_version = dagster_most_recent_release user_code_version = request.param[1] if user_code_version == MOST_RECENT_RELEASE_PLACEHOLDER: user_code_version = dagster_most_recent_release return {"da...
_version.is_prerelease: return str(release_version) @pytest.fixture( params=[ pytest.param(value, marks=getattr(pytest.mark, key), id=key) for key, value in RELEASE_TEST_MAP.items() ], ) def release_test_map(request, dagster_most_recent_release):
64
64
141
51
13
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
release_test_map
release_test_map
56
70
56
62
344e0f30b88468419b573e81d538b908fb1a9aaa
bigcode/the-stack
train
bcf4c025f143ab0b4e1736ce
train
function
def assert_runs_and_exists(client: DagsterGraphQLClient, name, subset_selection=None): run_id = client.submit_pipeline_execution( pipeline_name=name, mode="default", run_config={}, solid_selection=subset_selection, ) assert_run_success(client, run_id) locations = ( ...
def assert_runs_and_exists(client: DagsterGraphQLClient, name, subset_selection=None):
run_id = client.submit_pipeline_execution( pipeline_name=name, mode="default", run_config={}, solid_selection=subset_selection, ) assert_run_success(client, run_id) locations = ( client._get_repo_locations_and_names_with_pipeline( # pylint: disable=protected-acc...
assert_runs_and_exists(graphql_client, "the_job") def test_backcompat_deployed_job_subset(graphql_client): assert_runs_and_exists(graphql_client, "the_job", subset_selection=["my_op"]) def assert_runs_and_exists(client: DagsterGraphQLClient, name, subset_selection=None):
63
64
115
19
44
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
assert_runs_and_exists
assert_runs_and_exists
138
153
138
138
7190ecf35ed3ea14bf1e36b3c2d187b76aed9909
bigcode/the-stack
train
1e3df3e0bc39d936e2cec3e4
train
function
def assert_run_success(client, run_id: int): start_time = time.time() while True: if time.time() - start_time > MAX_TIMEOUT_SECONDS: raise Exception("Timed out waiting for launched run to complete") status = client.get_run_status(run_id) assert status and status != PipelineR...
def assert_run_success(client, run_id: int):
start_time = time.time() while True: if time.time() - start_time > MAX_TIMEOUT_SECONDS: raise Exception("Timed out waiting for launched run to complete") status = client.get_run_status(run_id) assert status and status != PipelineRunStatus.FAILURE if status == Pipelin...
LIEST_TESTED_RELEASE], "dagit-latest-release": [MOST_RECENT_RELEASE_PLACEHOLDER, DAGSTER_CURRENT_BRANCH], "user-code-latest-release": [DAGSTER_CURRENT_BRANCH, MOST_RECENT_RELEASE_PLACEHOLDER], } def assert_run_success(client, run_id: int):
64
64
88
11
53
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
assert_run_success
assert_run_success
31
42
31
31
015e887af51cb482fa17627465b50a790ed10db8
bigcode/the-stack
train
ec1c1a557e833973e3f12dac
train
function
@pytest.fixture(name="dagster_most_recent_release", scope="session") def dagster_most_recent_release(): res = requests.get("https://pypi.org/pypi/dagster/json") module_json = res.json() releases = module_json["releases"] release_versions = [packaging.version.parse(release) for release in releases.keys()...
@pytest.fixture(name="dagster_most_recent_release", scope="session") def dagster_most_recent_release():
res = requests.get("https://pypi.org/pypi/dagster/json") module_json = res.json() releases = module_json["releases"] release_versions = [packaging.version.parse(release) for release in releases.keys()] for release_version in reversed(sorted(release_versions)): if not release_version.is_prere...
") status = client.get_run_status(run_id) assert status and status != PipelineRunStatus.FAILURE if status == PipelineRunStatus.SUCCESS: break time.sleep(1) @pytest.fixture(name="dagster_most_recent_release", scope="session") def dagster_most_recent_release():
64
64
105
23
41
souterjk/dagster
integration_tests/test_suites/backcompat-test-suite/test_backcompat.py
Python
dagster_most_recent_release
dagster_most_recent_release
45
53
45
46
820a644daa5c5c196d196449cec69b5759a2f166
bigcode/the-stack
train
c89956d864c52b3e4fa4bbd0
train
class
class TestModmailConversation(IntegrationTest): @mock.patch('time.sleep', return_value=None) def test_archive(self, _): self.reddit.read_only = False conversation = self.reddit.subreddit('all').modmail('ik72') with self.recorder.use_cassette( 'TestModmailConversation.test...
class TestModmailConversation(IntegrationTest): @mock.patch('time.sleep', return_value=None)
def test_archive(self, _): self.reddit.read_only = False conversation = self.reddit.subreddit('all').modmail('ik72') with self.recorder.use_cassette( 'TestModmailConversation.test_archive'): conversation.archive() conversation = self.reddit.subreddit('...
from praw.models import ModmailMessage import mock from ... import IntegrationTest class TestModmailConversation(IntegrationTest): @mock.patch('time.sleep', return_value=None)
38
256
927
21
16
Theonefoster/praw
tests/integration/models/reddit/test_modmail.py
Python
TestModmailConversation
TestModmailConversation
7
96
7
8
989ab7fee7c72a8dedb81c6646cc7c20910263c4
bigcode/the-stack
train
837fc4fceb524f3ef15a816d
train
class
class Doom(object): '''Wrapper for Doom environment. Gym-style interface''' def __init__(self, visiable=False): self.env = self._setup(visiable) self.state_dim = 84 * 84 * 1 self.action_dim = 3 # Identity bool matrix, transfer action to bool one-hot self.bool_onehot = np....
class Doom(object):
'''Wrapper for Doom environment. Gym-style interface''' def __init__(self, visiable=False): self.env = self._setup(visiable) self.state_dim = 84 * 84 * 1 self.action_dim = 3 # Identity bool matrix, transfer action to bool one-hot self.bool_onehot = np.identity(self.action...
from __future__ import print_function from __future__ import division import numpy as np from vizdoom import * class Doom(object):
29
134
449
4
25
syd951186545/reinforce_py
algorithms/A3C/doom/env_doom.py
Python
Doom
Doom
8
63
8
8
94b6f46a7798bd089f86c14541ae7d005bae1eef
bigcode/the-stack
train
e150f33e23fc9ae5ea34d7aa
train
class
class RobustExchange(Exchange): """ Exchange abstraction """ def __init__(self, loop, future_store, channel, publish_method, name=None, type=ExchangeType.DIRECT, passive=False, ...
class RobustExchange(Exchange):
""" Exchange abstraction """ def __init__(self, loop, future_store, channel, publish_method, name=None, type=ExchangeType.DIRECT, passive=False, durable=False, ...
from __future__ import absolute_import from logging import getLogger from tornado import gen from . import compat from .common import FutureStore from .exchange import Exchange, ExchangeType from .channel import Channel _LOGGER = getLogger(__name__) class RobustExchange(Exchange):
60
201
672
6
54
sphuber/topika
topika/robust_exchange.py
Python
RobustExchange
RobustExchange
13
104
13
13
97bebf62a6ea4e83dfd13a4ba8a11f74c8b4076a
bigcode/the-stack
train
d53c97a27349c476faafb5d0
train
class
class TestSuite: def test(self): # EVEX.128.66.0F38.W0 42 /r # VGETEXPPS xmm1 {k1}{z}, xmm2/m128/m32bcst myEVEX = EVEX('EVEX.128.66.0F38.W0') Buffer = bytes.fromhex('{}420e'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myD...
class TestSuite:
def test(self): # EVEX.128.66.0F38.W0 42 /r # VGETEXPPS xmm1 {k1}{z}, xmm2/m128/m32bcst myEVEX = EVEX('EVEX.128.66.0F38.W0') Buffer = bytes.fromhex('{}420e'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instr...
#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This progra...
191
256
985
4
187
CrackerCat/rp
src/third_party/beaengine/tests/0f3842.py
Python
TestSuite
TestSuite
21
88
21
21
660025b04445c6d0dee9852172a9d80dad7d25e5
bigcode/the-stack
train
949b3e8d65b5438bd75722f4
train
class
class strategy: """ 携带一个函数句柄 """ @classmethod def setting(self): pass @classmethod def predict(self, market, account, hold): """ 一个极其简单的示例策略,随机 随机真的随机 """ if hold == 0: __dat = random.random() if __dat > 0.5: r...
class strategy:
""" 携带一个函数句柄 """ @classmethod def setting(self): pass @classmethod def predict(self, market, account, hold): """ 一个极其简单的示例策略,随机 随机真的随机 """ if hold == 0: __dat = random.random() if __dat > 0.5: return {'if_buy':...
# coding:utf-8 import random import QUANTAXIS as QA class strategy:
20
64
171
3
16
danfengzi/QUANTAXIS
test/new_test/strategy.py
Python
strategy
strategy
7
33
7
7
9088a22d1a6ff38632013c3f1ab06b9f296c6c32
bigcode/the-stack
train
413670e2eb810f81338d5a74
train
class
class User(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.String(80), unique=True) user_key = db.Column(db.String(120), unique=True) user_secret = db.Column(db.String(120), unique=True) def __init__(self, user_id, user_key, user_secret): self.user_id = user_i...
class User(db.Model):
id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.String(80), unique=True) user_key = db.Column(db.String(120), unique=True) user_secret = db.Column(db.String(120), unique=True) def __init__(self, user_id, user_key, user_secret): self.user_id = user_id self.user_ke...
from app import db # Add database model to store user_id, user_key and user_secret # Used for accessing API class User(db.Model):
31
64
118
5
25
ctaloi/Fitboard
models.py
Python
User
User
7
19
7
7
7da307441ac77ec8a956886304ae82faec56313d
bigcode/the-stack
train
5d62093e6f87da4887801098
train
class
class NextMiddleware(MiddlewareMixin): # 老版本写法,后面会废弃 @staticmethod def process_request(request): # 若请求的是登陆页面 则往下执行 next = request.GET.get('next', None) if next: request.next = next
class NextMiddleware(MiddlewareMixin): # 老版本写法,后面会废弃 @staticmethod
def process_request(request): # 若请求的是登陆页面 则往下执行 next = request.GET.get('next', None) if next: request.next = next
django.conf import settings import random from django.urls import Resolver404, resolve, reverse import sys import re from django.views.debug import technical_500_response, technical_404_response class NextMiddleware(MiddlewareMixin): # 老版本写法,后面会废弃 @staticmethod
64
64
64
24
39
crazypenguin/devops
util/middleware.py
Python
NextMiddleware
NextMiddleware
12
18
12
13
320c6b66605310e18a34925ea1b0e9379ff7c1e5
bigcode/the-stack
train
2a06e1ff720507f04d6c94d2
train
class
class BlackListMiddleware: """ 黑名单中间件,可以在 settings.py 中添加一个 BLACKLIST(全大写)列表 """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.META['REMOTE_ADDR'] in getattr(settings, "BLACKLIST", []): return HttpResponseForbi...
class BlackListMiddleware:
""" 黑名单中间件,可以在 settings.py 中添加一个 BLACKLIST(全大写)列表 """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.META['REMOTE_ADDR'] in getattr(settings, "BLACKLIST", []): return HttpResponseForbidden('<h1>该IP地址被限制访问!</h1>'...
: if request.META.get('HTTP_X_FORWARDED_FOR'): request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0] except Exception: pass response = self.get_response(request) return response class BlackListMiddleware:
64
64
109
5
58
crazypenguin/devops
util/middleware.py
Python
BlackListMiddleware
BlackListMiddleware
68
79
68
68
33212a76adcc9cf366749836d9cf178f5f3c7250
bigcode/the-stack
train
46d831d9dbc552e1a1a6f9f6
train
class
class LockScreenMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path not in [reverse('user:lockscreen'), reverse('user:login'), reverse('user:logout'), reverse('scheduler_api:client_upload')]: if request.session....
class LockScreenMiddleware:
def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path not in [reverse('user:lockscreen'), reverse('user:login'), reverse('user:logout'), reverse('scheduler_api:client_upload')]: if request.session.get('locked', False): ...
def __call__(self, request): if request.META['REMOTE_ADDR'] in getattr(settings, "BLACKLIST", []): return HttpResponseForbidden('<h1>该IP地址被限制访问!</h1>') response = self.get_response(request) return response class LockScreenMiddleware:
64
64
99
5
58
crazypenguin/devops
util/middleware.py
Python
LockScreenMiddleware
LockScreenMiddleware
82
91
82
82
d7da9bd215cdd1883bec75b01fb18c7c788b1f1d
bigcode/the-stack
train
7219efa0b90ec506e376d545
train
class
class DebugMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # 当 debug 设置为 False 时,返回 404 时 # 如果是管理员,则返回一个特殊的响应对象,也就是Debug页面 # 如果是普通用户,则返回None,交给默认的流程处理 response = self.get_response(request) if not setting...
class DebugMiddleware:
def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # 当 debug 设置为 False 时,返回 404 时 # 如果是管理员,则返回一个特殊的响应对象,也就是Debug页面 # 如果是普通用户,则返回None,交给默认的流程处理 response = self.get_response(request) if not settings.DEBUG: if...
): if request.path not in [reverse('user:lockscreen'), reverse('user:login'), reverse('user:logout'), reverse('scheduler_api:client_upload')]: if request.session.get('locked', False): return redirect(reverse('user:lockscreen')) response = self.get_response(request) re...
72
72
240
4
67
crazypenguin/devops
util/middleware.py
Python
DebugMiddleware
DebugMiddleware
94
120
94
94
1245cb8661d888b93955ab34bf4f8c8428a1d3db
bigcode/the-stack
train
9a709c8dd9e92d5f06156184
train
class
class PermissionMiddleware: """ 根据 session 里面记录的 url, 判断当前请求是否有权限 """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): current_url = request.path_info for valid in settings.VALID_URL: # 白名单直接返回 if re.match('^%s$' ...
class PermissionMiddleware:
""" 根据 session 里面记录的 url, 判断当前请求是否有权限 """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): current_url = request.path_info for valid in settings.VALID_URL: # 白名单直接返回 if re.match('^%s$' % valid, current_url): ...
): # 当 debug 设置为 False 时,返回服务器错误时 # 如果是管理员,则返回一个特殊的响应对象,也就是Debug页面 # 如果是普通用户,则返回None,交给默认的流程处理 if not settings.DEBUG: if request.session['issuperuser']: return technical_500_response(request, *sys.exc_info()) class PermissionMiddleware:
81
81
272
4
77
crazypenguin/devops
util/middleware.py
Python
PermissionMiddleware
PermissionMiddleware
123
152
123
123
f3c69630d1d280e66caf93345e6f336fff415ba6
bigcode/the-stack
train
28d3449457761d62a6518f1b
train
class
class GetRealClientMiddleware: """ 前端有 nginx 代理时,配置: proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.META.get(...
class GetRealClientMiddleware:
""" 前端有 nginx 代理时,配置: proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.META.get('HTTP_X_REAL_IP'): ...
.get('next', None) if next: request.next = next response = self.get_response(request) # 在这里编写视图调用后需要执行的代码 # 这里其实就是旧的process_response()方法的代码 return response class GetRealClientMiddleware:
64
64
182
6
57
crazypenguin/devops
util/middleware.py
Python
GetRealClientMiddleware
GetRealClientMiddleware
43
65
43
43
ae73eb4bb63ca1a3ed56212ade305ce5dc4c52b6
bigcode/the-stack
train
821a47003663f5142ecf7ed6
train
class
class NewNextMiddleware: # 新版 2.2 写法 def __init__(self, get_response): self.get_response = get_response # 配置和初始化 def __call__(self, request): # 在这里编写视图和后面的中间件被调用之前需要执行的代码 # 这里其实就是旧的process_request()方法的代码 next = request.GET.get('next', None) if nex...
class NewNextMiddleware: # 新版 2.2 写法
def __init__(self, get_response): self.get_response = get_response # 配置和初始化 def __call__(self, request): # 在这里编写视图和后面的中间件被调用之前需要执行的代码 # 这里其实就是旧的process_request()方法的代码 next = request.GET.get('next', None) if next: request.next = next response =...
next = request.GET.get('next', None) if next: request.next = next # def process_response(self, request, response): # response.status_code = 500 # return response class NewNextMiddleware: # 新版 2.2 写法
64
64
150
16
47
crazypenguin/devops
util/middleware.py
Python
NewNextMiddleware
NewNextMiddleware
25
40
25
25
2a9a2726cddd2ce1d1de94aa191a30d0b31fe71b
bigcode/the-stack
train
00f92cd097f69c9cc4715331
train
function
def test_resume_with_recovery(): export_dir = tempfile.mkdtemp() grid_id = "resume_with_recovery_gbm" print("Using directory %s" % export_dir) hyper_parameters = { "learn_rate": [0.01, 0.05], "ntrees": [100, 110, 120, 130] } grid_size = 1 for p in hyper_parameters: gr...
def test_resume_with_recovery():
export_dir = tempfile.mkdtemp() grid_id = "resume_with_recovery_gbm" print("Using directory %s" % export_dir) hyper_parameters = { "learn_rate": [0.01, 0.05], "ntrees": [100, 110, 120, 130] } grid_size = 1 for p in hyper_parameters: grid_size *= len(hyper_parameters[p...
print("%s not trained yet after %ss" % (models, times_waited / 10)) grid.cancel() grid = h2o.get_grid(grid_id) old_grid_model_count = len(grid.model_ids) print("Grid has %d models" % old_grid_model_count) assert old_grid_model_count < grid_size, "The full grid should not have finished yet." h2o...
180
180
602
7
173
vishalbelsare/h2o-3
h2o-py/tests/testdir_algos/grid/pyunit_grid_resume_with_recovery.py
Python
test_resume_with_recovery
test_resume_with_recovery
42
88
42
42
49db96c47af3a24194972c43433b3de68671e5c2
bigcode/the-stack
train
ae5abe85608f3d3718cf5b7c
train
function
def _wait_for_grid_models(grid, grid_id, models, grid_size): grid_in_progress = None times_waited = 0 while (times_waited < 3000) and (grid_in_progress is None or len(grid_in_progress.model_ids) < models): time.sleep(0.1) # give it tome to train some models times_waited += 1 try: ...
def _wait_for_grid_models(grid, grid_id, models, grid_size):
grid_in_progress = None times_waited = 0 while (times_waited < 3000) and (grid_in_progress is None or len(grid_in_progress.model_ids) < models): time.sleep(0.1) # give it tome to train some models times_waited += 1 try: grid_in_progress = h2o.get_grid(grid_id) ex...
..", "..", "..")) import h2o from tests import pyunit_utils from h2o.grid.grid_search import H2OGridSearch from h2o.estimators.gbm import H2OGradientBoostingEstimator def _wait_for_grid_models(grid, grid_id, models, grid_size):
66
66
222
16
49
vishalbelsare/h2o-3
h2o-py/tests/testdir_algos/grid/pyunit_grid_resume_with_recovery.py
Python
_wait_for_grid_models
_wait_for_grid_models
14
32
14
14
09530afbede32ceadfdccc79ac43745a3df3193c
bigcode/the-stack
train
2f8efbef8788b6533949e0db
train
function
def _check_grid_loaded_properly(loaded, train, old_grid_model_count): assert loaded is not None assert len(loaded.model_ids) == old_grid_model_count loaded_train = h2o.H2OFrame.get_frame(train.frame_id) assert loaded_train is not None, "Train frame was not loaded"
def _check_grid_loaded_properly(loaded, train, old_grid_model_count):
assert loaded is not None assert len(loaded.model_ids) == old_grid_model_count loaded_train = h2o.H2OFrame.get_frame(train.frame_id) assert loaded_train is not None, "Train frame was not loaded"
% old_grid_model_count) assert old_grid_model_count < grid_size, "The full grid should not have finished yet." h2o.remove_all() time.sleep(5) return old_grid_model_count def _check_grid_loaded_properly(loaded, train, old_grid_model_count):
64
64
71
18
45
vishalbelsare/h2o-3
h2o-py/tests/testdir_algos/grid/pyunit_grid_resume_with_recovery.py
Python
_check_grid_loaded_properly
_check_grid_loaded_properly
35
39
35
35
97308d3f748f5790ae77cece4226d661e5e03c80
bigcode/the-stack
train
e5a2f78fb3c08b1482d5a046
train
class
class TestNode(NodeConnCB): def __init__(self): super().__init__() self.getdataset = set() def on_getdata(self, conn, message): for inv in message.inv: self.getdataset.add(inv.hash) def announce_tx_and_wait_for_getdata(self, tx, timeout=60): with mininode_lock: ...
class TestNode(NodeConnCB):
def __init__(self): super().__init__() self.getdataset = set() def on_getdata(self, conn, message): for inv in message.inv: self.getdataset.add(inv.hash) def announce_tx_and_wait_for_getdata(self, tx, timeout=60): with mininode_lock: self.last_messag...
bit used to signal activation of SegWit VB_WITNESS_BIT = 1 VB_PERIOD = 144 VB_ACTIVATION_THRESHOLD = 108 VB_TOP_BITS = 0x20000000 MAX_SIGOP_COST = 80000 # Calculate the virtual size of a witness block: # (base + witness/4) def get_virtual_size(witness_block): base_size = len(witness_block.serialize()) total...
147
147
492
7
139
Arthurb101/cougarCoin
test/functional/p2p-segwit.py
Python
TestNode
TestNode
35
90
35
35
ce7997a458d9f52b57d59011d14be0efb6f0374d
bigcode/the-stack
train
908266e916bdec8685e14801
train
class
class SegWitTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [["-whitelist=127.0.0.1"], ["-whitelist=127.0.0.1", "-acceptnonstdtxn=0"], ["-whitelist=127.0.0.1", "-vbparams=segwit:0:0"]] def set...
class SegWitTest(BitcoinTestFramework):
def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [["-whitelist=127.0.0.1"], ["-whitelist=127.0.0.1", "-acceptnonstdtxn=0"], ["-whitelist=127.0.0.1", "-vbparams=segwit:0:0"]] def setup_network(self): self.setup_node...
assert_equal(self.connection.rpc.getbestblockhash() == block.hash, accepted) # Used to keep track of anyone-can-spend outputs that we can use in the tests class UTXO(object): def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue # Helper for ge...
256
256
22,216
10
246
Arthurb101/cougarCoin
test/functional/p2p-segwit.py
Python
SegWitTest
SegWitTest
111
1,956
111
112
8847ce98e565fd59f747d2527053efc1821a6e0a
bigcode/the-stack
train
3b7233da54fc56614ee24c54
train
function
def get_virtual_size(witness_block): base_size = len(witness_block.serialize()) total_size = len(witness_block.serialize(with_witness=True)) # the "+3" is so we round up vsize = int((3*base_size + total_size + 3)/4) return vsize
def get_virtual_size(witness_block):
base_size = len(witness_block.serialize()) total_size = len(witness_block.serialize(with_witness=True)) # the "+3" is so we round up vsize = int((3*base_size + total_size + 3)/4) return vsize
1 VB_PERIOD = 144 VB_ACTIVATION_THRESHOLD = 108 VB_TOP_BITS = 0x20000000 MAX_SIGOP_COST = 80000 # Calculate the virtual size of a witness block: # (base + witness/4) def get_virtual_size(witness_block):
64
64
68
8
56
Arthurb101/cougarCoin
test/functional/p2p-segwit.py
Python
get_virtual_size
get_virtual_size
28
33
28
28
9851ec511b95ebdb7aeaf107b9aaceb24b4f1edb
bigcode/the-stack
train
f21203cf2a55e25ce4352083
train
class
class UTXO(object): def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue
class UTXO(object):
def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue
_witness_block(block)) else: self.send_message(msg_block(block)) self.sync_with_ping() assert_equal(self.connection.rpc.getbestblockhash() == block.hash, accepted) # Used to keep track of anyone-can-spend outputs that we can use in the tests class UTXO(object):
64
64
43
6
57
Arthurb101/cougarCoin
test/functional/p2p-segwit.py
Python
UTXO
UTXO
93
97
93
93
047cf32010ac5dae4fdba3a17d78e52cc0867c75
bigcode/the-stack
train
1584b328eed530abd2514031
train
function
def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key): tx_hash = SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, value) signature = key.sign(tx_hash) + chr(hashtype).encode('latin-1') txTo.wit.vtxinwit[inIdx].scriptWitness.stack = [signature, script] txTo.rehash()
def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key):
tx_hash = SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, value) signature = key.sign(tx_hash) + chr(hashtype).encode('latin-1') txTo.wit.vtxinwit[inIdx].scriptWitness.stack = [signature, script] txTo.rehash()
Op(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)]) # Add signature for a P2PK witness program. def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key):
64
64
95
24
40
Arthurb101/cougarCoin
test/functional/p2p-segwit.py
Python
sign_P2PK_witness_input
sign_P2PK_witness_input
104
108
104
104
128492c48fbf8c7a6c7325ffeb037fb03a87cffd
bigcode/the-stack
train
418ab75196bc037a30c0d2d7
train
function
def GetP2PKHScript(pubkeyhash): return CScript([CScriptOp(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)])
def GetP2PKHScript(pubkeyhash):
return CScript([CScriptOp(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)])
(object): def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue # Helper for getting the script associated with a P2PKH def GetP2PKHScript(pubkeyhash):
64
64
47
11
52
Arthurb101/cougarCoin
test/functional/p2p-segwit.py
Python
GetP2PKHScript
GetP2PKHScript
100
101
100
100
5cb442152a5d374b99481f0aa22bdbe8e73bdc99
bigcode/the-stack
train
1f2a370c7249611e0b1a0dd6
train
function
def main(): args = get_run_args() getattr(api, args.cli, no_cli_error)(args)
def main():
args = get_run_args() getattr(api, args.cli, no_cli_error)(args)
, 'yellow'), v) for k, v in sorted(vars(args).items())]) print('usage: %s\n%s\n%s\n' % (' '.join(sys.argv), '_' * 50, param_str)) return args else: parser.print_help() exit() def main():
64
64
23
3
61
awesome-archive/gnes
gnes/cli/__init__.py
Python
main
main
42
44
42
42
c63486c1c299a01c316c3791237e48e99ad71960
bigcode/the-stack
train
a3bd6d1675577b960e08ce8a
train
function
def no_cli_error(*args, **kwargs): get_main_parser().print_help() exit()
def no_cli_error(*args, **kwargs):
get_main_parser().print_help() exit()
' % (' '.join(sys.argv), '_' * 50, param_str)) return args else: parser.print_help() exit() def main(): args = get_run_args() getattr(api, args.cli, no_cli_error)(args) def no_cli_error(*args, **kwargs):
64
64
21
10
54
awesome-archive/gnes
gnes/cli/__init__.py
Python
no_cli_error
no_cli_error
47
49
47
47
87a6fb5a96d4a29086ba048f508d6d8ce04338ec
bigcode/the-stack
train
dbdc896591428700f60ac2ae
train
function
def get_run_args(parser_fn=get_main_parser, printed=True): parser = parser_fn() if len(sys.argv) > 1: args = parser.parse_args() if printed: param_str = '\n'.join(['%20s = %s' % (colored(k, 'yellow'), v) for k, v in sorted(vars(args).items())]) print('usage: %s\n%s\n%s\n'...
def get_run_args(parser_fn=get_main_parser, printed=True):
parser = parser_fn() if len(sys.argv) > 1: args = parser.parse_args() if printed: param_str = '\n'.join(['%20s = %s' % (colored(k, 'yellow'), v) for k, v in sorted(vars(args).items())]) print('usage: %s\n%s\n%s\n' % (' '.join(sys.argv), '_' * 50, param_str)) retur...
language governing permissions and # limitations under the License. # pylint: disable=low-comment-ratio import sys from termcolor import colored from . import api from .parser import get_main_parser __all__ = ['main'] def get_run_args(parser_fn=get_main_parser, printed=True):
64
64
121
13
51
awesome-archive/gnes
gnes/cli/__init__.py
Python
get_run_args
get_run_args
29
39
29
29
cbdadcfe89e063e49e2b4b65345500d1f6ff0254
bigcode/the-stack
train
ea912e38726de6af3a9936d7
train
function
def emb_sz_rule(n_cat:int)->int: return min(600, round(1.6 * n_cat**0.56))
def emb_sz_rule(n_cat:int)->int:
return min(600, round(1.6 * n_cat**0.56))
TabularList', 'TabularProcessor', 'tabular_learner'] OptTabTfms = Optional[Collection[TabularProc]] #def emb_sz_rule(n_cat:int)->int: return min(50, (n_cat//2)+1) def emb_sz_rule(n_cat:int)->int:
64
64
28
11
53
pjarnhus/fastai
fastai/tabular/data.py
Python
emb_sz_rule
emb_sz_rule
15
15
15
15
13ed055381f3e7b7e0c93f7d5091f480081ac885
bigcode/the-stack
train
209ab12a02610cec7259eeb9
train
class
class TabularProcessor(PreProcessor): "Regroup the `procs` in one `PreProcessor`." def __init__(self, ds:ItemBase=None, procs=None): procs = ifnone(procs, ds.procs if ds is not None else None) self.procs = listify(procs) def process_one(self, item): df = pd.DataFrame([item,item]) ...
class TabularProcessor(PreProcessor):
"Regroup the `procs` in one `PreProcessor`." def __init__(self, ds:ItemBase=None, procs=None): procs = ifnone(procs, ds.procs if ds is not None else None) self.procs = listify(procs) def process_one(self, item): df = pd.DataFrame([item,item]) for proc in self.procs: proc(df,...
(classes[n]) sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb return n_cat,sz class TabularLine(ItemBase): "Basic item for tabular data." def __init__(self, cats, conts, classes, names): self.cats,self.conts,self.classes,self.names = cats,conts,classes,names self.data = [te...
189
189
631
8
180
pjarnhus/fastai
fastai/tabular/data.py
Python
TabularProcessor
TabularProcessor
38
83
38
38
eb1f58f8d12eb34619d48f3b843eeeb039be86bd
bigcode/the-stack
train
dbb2bb7953c71ec17b3749f1
train
class
class TabularLine(ItemBase): "Basic item for tabular data." def __init__(self, cats, conts, classes, names): self.cats,self.conts,self.classes,self.names = cats,conts,classes,names self.data = [tensor(cats), tensor(conts)] def __str__(self): res = '' for c, n in zip(self.cat...
class TabularLine(ItemBase):
"Basic item for tabular data." def __init__(self, cats, conts, classes, names): self.cats,self.conts,self.classes,self.names = cats,conts,classes,names self.data = [tensor(cats), tensor(conts)] def __str__(self): res = '' for c, n in zip(self.cats, self.names[:len(self.cats)...
` if not given in `sz_dict`." sz_dict = ifnone(sz_dict, {}) n_cat = len(classes[n]) sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb return n_cat,sz class TabularLine(ItemBase):
64
64
149
7
56
pjarnhus/fastai
fastai/tabular/data.py
Python
TabularLine
TabularLine
24
36
24
24
dcb8f6271508ad3fca6ecb9d9e5671c3a83cf0eb
bigcode/the-stack
train
7b62f22f3b0f2d329453faa5
train
class
class TabularList(ItemList): "Basic `ItemList` for tabular data." _item_cls=TabularLine _processor=TabularProcessor _bunch=TabularDataBunch def __init__(self, items:Iterator, cat_names:OptStrList=None, cont_names:OptStrList=None, procs=None, **kwargs)->'TabularList': super()...
class TabularList(ItemList):
"Basic `ItemList` for tabular data." _item_cls=TabularLine _processor=TabularProcessor _bunch=TabularDataBunch def __init__(self, items:Iterator, cat_names:OptStrList=None, cont_names:OptStrList=None, procs=None, **kwargs)->'TabularList': super().__init__(range_of(items), **...
collate_fn:Callable=data_collate, no_check:bool=False)->DataBunch: "Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`." cat_names = ifnone(cat_names, []).copy() cont_names = ifnone(cont_names, list(set(df)-set(cat_names)-{dep_var})) ...
256
256
903
7
249
pjarnhus/fastai
fastai/tabular/data.py
Python
TabularList
TabularList
104
169
104
104
40ff04f26bf88a1b84fd43f0314bd6bb7d1b0dec
bigcode/the-stack
train
b3f06c8cef49dc8f30214bec
train
function
def tabular_learner(data:DataBunch, layers:Collection[Union[int, Tuple[int, nn.Module]]], emb_szs:Dict[str,int]=None, metrics=None, ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs): "Get a `Learner` using `data`, with `met...
def tabular_learner(data:DataBunch, layers:Collection[Union[int, Tuple[int, nn.Module]]], emb_szs:Dict[str,int]=None, metrics=None, ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs):
"Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params." emb_szs = data.get_emb_szs(ifnone(emb_szs, {})) model = TabularModel(emb_szs, len(data.cont_names), out_sz=data.c, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range,...
def tabular_learner(data:DataBunch, layers:Collection[Union[int, Tuple[int, nn.Module]]], emb_szs:Dict[str,int]=None, metrics=None, ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs):
73
64
184
73
0
pjarnhus/fastai
fastai/tabular/data.py
Python
tabular_learner
tabular_learner
171
178
171
173
22f241861535ea781130b90d295ee33a99586a82
bigcode/the-stack
train
74cacc6779ad564e39961218
train
function
def def_emb_sz(classes, n, sz_dict=None): "Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`." sz_dict = ifnone(sz_dict, {}) n_cat = len(classes[n]) sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb return n_cat,sz
def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`." sz_dict = ifnone(sz_dict, {}) n_cat = len(classes[n]) sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb return n_cat,sz
#def emb_sz_rule(n_cat:int)->int: return min(50, (n_cat//2)+1) def emb_sz_rule(n_cat:int)->int: return min(600, round(1.6 * n_cat**0.56)) def def_emb_sz(classes, n, sz_dict=None):
64
64
83
12
52
pjarnhus/fastai
fastai/tabular/data.py
Python
def_emb_sz
def_emb_sz
17
22
17
17
1e09ea935b2b6ad3e9215c941cabdd4aa097a56e
bigcode/the-stack
train
a8e49eedaa7abdd60dc9247e
train
class
class TabularDataBunch(DataBunch): "Create a `DataBunch` suitable for tabular data." @classmethod def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None, cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None, ...
class TabularDataBunch(DataBunch):
"Create a `DataBunch` suitable for tabular data." @classmethod def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None, cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None, test_df=None, bs:int=64, val_bs:...
.classes,self.classes,cat_cols = None,None,None,[] if len(ds.cont_names) != 0: ds.conts = np.stack([c.astype('float32').values for n,c in ds.inner_df[ds.cont_names].items()], 1) cont_cols = list(ds.inner_df[ds.cont_names].columns.values) else: ds.conts,cont_cols = None,[] ...
112
112
376
10
101
pjarnhus/fastai
fastai/tabular/data.py
Python
TabularDataBunch
TabularDataBunch
85
102
85
85
99cb33879cc52a1cac4d7f7407feeeb84c6fd171
bigcode/the-stack
train
6a33981a2d917f3eb4bd6e26
train
class
class TextMelodyEncoder(TextMelodyEncoderBase): """Convert melody sequences (with metric timing) to integer indices.""" def __init__(self, steps_per_quarter, min_pitch, max_pitch): super(TextMelodyEncoder, self).__init__(min_pitch, max_pitch) self._steps_per_quarter = steps_per_quarter def _quantize_not...
class TextMelodyEncoder(TextMelodyEncoderBase):
"""Convert melody sequences (with metric timing) to integer indices.""" def __init__(self, steps_per_quarter, min_pitch, max_pitch): super(TextMelodyEncoder, self).__init__(min_pitch, max_pitch) self._steps_per_quarter = steps_per_quarter def _quantize_note_sequence(self, ns): return note_seq.quanti...
: List of encoded melody event indices. """ return self._encode_melody_events([int(a) for a in s.split()]) @property def vocab_size(self): return self._encoding.num_classes + self.num_reserved_ids class TextMelodyEncoder(TextMelodyEncoderBase):
64
64
101
11
52
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
TextMelodyEncoder
TextMelodyEncoder
339
347
339
339
dd5ad2671a607af68e40ed2a3321acfeaec3cd49
bigcode/the-stack
train
e9e3dcae2ae147c64af69e2a
train
class
class TextMelodyEncoderBase(object): """Convert melody sequences to integer indices, abstract base class.""" def __init__(self, min_pitch, max_pitch): self._encoding = note_seq.MelodyOneHotEncoding( min_note=min_pitch, max_note=max_pitch + 1) @property def num_reserved_ids(self): return text_e...
class TextMelodyEncoderBase(object):
"""Convert melody sequences to integer indices, abstract base class.""" def __init__(self, min_pitch, max_pitch): self._encoding = note_seq.MelodyOneHotEncoding( min_note=min_pitch, max_note=max_pitch + 1) @property def num_reserved_ids(self): return text_encoder.NUM_RESERVED_TOKENS def _en...
ord] * (qns.total_quantized_steps - current_step) return self._encode_chord_symbols(chords) def encode(self, s): """Transform a space-delimited chord symbols string into indices. Args: s: Space delimited string containing a chord symbol sequence, e.g. 'C C G G Am Am F F'. Returns: ...
131
131
439
8
122
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
TextMelodyEncoderBase
TextMelodyEncoderBase
284
336
284
284
a56540263d6edf167d6681944c440e92f27707c2
bigcode/the-stack
train
1fa57d1f3dfc9ceeb1ebc993
train
class
class FlattenedTextMelodyEncoderAbsolute(TextMelodyEncoderAbsolute): """Encodes a melody that is flattened into only rhythm (with velocity). TextMelodyEncoderAbsolute encodes the melody as a sequence of MELODY_NO_EVENT, MELODY_NOTE_OFF, and pitch ids. This representation contains no MELODY_NOTE_OFF events, and...
class FlattenedTextMelodyEncoderAbsolute(TextMelodyEncoderAbsolute):
"""Encodes a melody that is flattened into only rhythm (with velocity). TextMelodyEncoderAbsolute encodes the melody as a sequence of MELODY_NO_EVENT, MELODY_NOTE_OFF, and pitch ids. This representation contains no MELODY_NOTE_OFF events, and instead of pitch ids, uses velocity-bin ids. To take advantage of ...
): """Transform a MusicXML filename into a list of score event index tuples. Args: s: Path to the MusicXML file. Returns: ids: List of score event index tuples. """ if s: ns = note_seq.musicxml_file_to_sequence_proto(s) else: ns = note_seq.NoteSequence() return self...
120
120
403
14
106
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
FlattenedTextMelodyEncoderAbsolute
FlattenedTextMelodyEncoderAbsolute
395
443
395
395
b6ab481c7d91945d673c4f6d48c84c53732f2030
bigcode/the-stack
train
41920eba1e8c7368ee694326
train
class
class MidiPerformanceEncoder(object): """Convert between performance event indices and (filenames of) MIDI files.""" def __init__(self, steps_per_second, num_velocity_bins, min_pitch, max_pitch, add_eos=False, ngrams=None): """Initialize a MidiPerformanceEncoder object. Encodes MIDI using a...
class MidiPerformanceEncoder(object):
"""Convert between performance event indices and (filenames of) MIDI files.""" def __init__(self, steps_per_second, num_velocity_bins, min_pitch, max_pitch, add_eos=False, ngrams=None): """Initialize a MidiPerformanceEncoder object. Encodes MIDI using a performance event encoding. Index 0 i...
# Copyright 2022 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
212
256
1,461
6
205
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
MidiPerformanceEncoder
MidiPerformanceEncoder
33
215
33
33
7db537e5748fde2efd9181f89a4085ae2413b7f4
bigcode/the-stack
train
347a147aff1e55f1f4cd6bba
train
class
class CompositeScoreEncoder(object): """Convert multi-component score sequences to tuples of integer indices.""" def __init__(self, encoders): self._encoders = encoders @property def num_reserved_ids(self): return text_encoder.NUM_RESERVED_TOKENS def encode_note_sequence(self, ns): return zip(*...
class CompositeScoreEncoder(object):
"""Convert multi-component score sequences to tuples of integer indices.""" def __init__(self, encoders): self._encoders = encoders @property def num_reserved_ids(self): return text_encoder.NUM_RESERVED_TOKENS def encode_note_sequence(self, ns): return zip(*[encoder.encode_note_sequence(ns) ...
): super(TextMelodyEncoderAbsolute, self).__init__(min_pitch, max_pitch) self._steps_per_second = steps_per_second def _quantize_note_sequence(self, ns): return note_seq.quantize_note_sequence_absolute(ns, self._steps_per_second) class CompositeScoreEncoder(object):
64
64
200
6
58
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
CompositeScoreEncoder
CompositeScoreEncoder
361
392
361
361
59088cfdf24f57c1bba07e91cc4b2463e30b09df
bigcode/the-stack
train
be14ac562dd28acdbde600a5
train
class
class TextChordsEncoder(object): """Convert chord symbol sequences to integer indices.""" def __init__(self, steps_per_quarter): """Initialize a TextChordsEncoder object. Encodes chord symbols using a vocabulary of triads. Indices 0 and 1 are reserved and unused, and the remaining 48 + 1 indices repre...
class TextChordsEncoder(object):
"""Convert chord symbol sequences to integer indices.""" def __init__(self, steps_per_quarter): """Initialize a TextChordsEncoder object. Encodes chord symbols using a vocabulary of triads. Indices 0 and 1 are reserved and unused, and the remaining 48 + 1 indices represent each of 4 triad types ov...
stemp('_decode.mid') note_seq.sequence_proto_to_midi_file(ns, tmp_file_path) return tmp_file_path def decode_list(self, ids): """Transform a sequence of event indices into a performance MIDI file. Args: ids: List of performance event indices. Returns: Single-element list containing...
147
147
493
7
140
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
TextChordsEncoder
TextChordsEncoder
218
281
218
218
f5b7b188cb83c8d33f8b3a615cde7df84e2632fd
bigcode/the-stack
train
ce834917eefb38f1d8280d57
train
class
class TextMelodyEncoderAbsolute(TextMelodyEncoderBase): """Convert melody sequences (with absolute timing) to integer indices.""" def __init__(self, steps_per_second, min_pitch, max_pitch): super(TextMelodyEncoderAbsolute, self).__init__(min_pitch, max_pitch) self._steps_per_second = steps_per_second de...
class TextMelodyEncoderAbsolute(TextMelodyEncoderBase):
"""Convert melody sequences (with absolute timing) to integer indices.""" def __init__(self, steps_per_second, min_pitch, max_pitch): super(TextMelodyEncoderAbsolute, self).__init__(min_pitch, max_pitch) self._steps_per_second = steps_per_second def _quantize_note_sequence(self, ns): return note_seq...
, self).__init__(min_pitch, max_pitch) self._steps_per_quarter = steps_per_quarter def _quantize_note_sequence(self, ns): return note_seq.quantize_note_sequence(ns, self._steps_per_quarter) class TextMelodyEncoderAbsolute(TextMelodyEncoderBase):
64
64
100
12
52
sandutsar/magenta
magenta/models/score2perf/music_encoders.py
Python
TextMelodyEncoderAbsolute
TextMelodyEncoderAbsolute
350
358
350
350
cacdf5a4e91c0cd6f5c6f9b927435ce3534ea626
bigcode/the-stack
train
acc46c74977f5d54f6c706f2
train
function
def check_voice(): for voice in voices: engine.setProperty('voice', voice.id) engine.say("hello world") print("hello wolrd",voice) engine.runAndWait() engine.stop
def check_voice():
for voice in voices: engine.setProperty('voice', voice.id) engine.say("hello world") print("hello wolrd",voice) engine.runAndWait() engine.stop
import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') def check_voice():
26
64
46
4
22
saishan27/Green
kural.py
Python
check_voice
check_voice
6
12
6
6
92478100831b487c9d1c4f1e029fc0ea7a043afc
bigcode/the-stack
train
b253ff4667bf2d4da1896d81
train
function
def green_voice(out): engine.setProperty('voice', "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0") engine.setProperty('rate',150) # engine.setProperty('volume',100) engine.say(out) engine.runAndWait() engine.stop
def green_voice(out):
engine.setProperty('voice', "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0") engine.setProperty('rate',150) # engine.setProperty('volume',100) engine.say(out) engine.runAndWait() engine.stop
ttsx3.init() voices = engine.getProperty('voices') def check_voice(): for voice in voices: engine.setProperty('voice', voice.id) engine.say("hello world") print("hello wolrd",voice) engine.runAndWait() engine.stop def green_voice(out):
64
64
76
5
58
saishan27/Green
kural.py
Python
green_voice
green_voice
15
21
15
15
970cfeca368264877d49ff0586f6f95e5d88e2b8
bigcode/the-stack
train
ea98c51652d88d8f4edacc9f
train
function
@numba.njit def points_transform_(points, centers, point_masks, loc_transform, rot_transform, valid_mask): """Apply transforms to points and box centers. Args: points (np.ndarray): Input points. centers (np.ndarray): Input box centers. point_masks (np.ndarray): Mas...
@numba.njit def points_transform_(points, centers, point_masks, loc_transform, rot_transform, valid_mask):
"""Apply transforms to points and box centers. Args: points (np.ndarray): Input points. centers (np.ndarray): Input box centers. point_masks (np.ndarray): Mask to indicate which points need to be transformed. loc_transform (np.ndarray): Location transform to be appli...
== 0: rot_mat_T[1, 1] = rot_cos rot_mat_T[1, 2] = -rot_sin rot_mat_T[2, 1] = rot_sin rot_mat_T[2, 2] = rot_cos @numba.njit def points_transform_(points, centers, point_masks, loc_transform, rot_transform, valid_mask):
90
90
302
27
62
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
points_transform_
points_transform_
281
308
281
283
29c7c609af9aa1fd6c6ee850a76cf798c283f15d
bigcode/the-stack
train
6ae962362a7858b3d96d0919
train
function
@numba.njit def box3d_transform_(boxes, loc_transform, rot_transform, valid_mask): """Transform 3D boxes. Args: boxes (np.ndarray): 3D boxes to be transformed. loc_transform (np.ndarray): Location transform to be applied. rot_transform (np.ndarray): Rotation transform to be applied. ...
@numba.njit def box3d_transform_(boxes, loc_transform, rot_transform, valid_mask):
"""Transform 3D boxes. Args: boxes (np.ndarray): 3D boxes to be transformed. loc_transform (np.ndarray): Location transform to be applied. rot_transform (np.ndarray): Rotation transform to be applied. valid_mask (np.ndarray | None): Mask to indicate which boxes are valid. ""...
_mat_T[j] points[i, :3] += centers[j, :3] points[i, :3] += loc_transform[j] break # only apply first box's transform @numba.njit def box3d_transform_(boxes, loc_transform, rot_transform, valid_mask):
64
64
140
23
40
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
box3d_transform_
box3d_transform_
311
325
311
312
7dcf44c38878c22272209e2b45f0657336ae02c6
bigcode/the-stack
train
31beda0684abe6a0951b6519
train
function
def noise_per_object_v3_(gt_boxes, points=None, valid_mask=None, rotation_perturb=np.pi / 4, center_noise_std=1.0, global_random_rot_range=np.pi / 4, num_try=100): ""...
def noise_per_object_v3_(gt_boxes, points=None, valid_mask=None, rotation_perturb=np.pi / 4, center_noise_std=1.0, global_random_rot_range=np.pi / 4, num_try=100):
"""Random rotate or remove each groundtruth independently. use kitti viewer to test this function points_transform_ Args: gt_boxes (np.ndarray): Ground truth boxes with shape (N, 7). points (np.ndarray | None): Input point cloud with shape (M, 4). Default: None. valid_ma...
1, :3] = points[i:i + 1, :3] @ rot_mat_T[j] points[i, :3] += centers[j, :3] points[i, :3] += loc_transform[j] break # only apply first box's transform @numba.njit def box3d_transform_(boxes, loc_transform, rot_transform, valid_mask): """Transform 3D bo...
256
256
877
56
200
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
noise_per_object_v3_
noise_per_object_v3_
328
408
328
334
c7f4babf44d516ff02feb3b82551b21231802f9f
bigcode/the-stack
train
ac168771115e605318cb9aa9
train
function
def _select_transform(transform, indices): """Select transform. Args: transform (np.ndarray): Transforms to select from. indices (np.ndarray): Mask to indicate which transform to select. Returns: np.ndarray: Selected transforms. """ result = np.zeros((transform.shape[0], *t...
def _select_transform(transform, indices):
"""Select transform. Args: transform (np.ndarray): Transforms to select from. indices (np.ndarray): Mask to indicate which transform to select. Returns: np.ndarray: Selected transforms. """ result = np.zeros((transform.shape[0], *transform.shape[2:]), ...
orners[i] = current_corners loc_noises[i, j, :2] += (dst_pos - boxes[i, :2]) rot_noises[i, j] += (dst_grot - current_grot) break return success_mask def _select_transform(transform, indices):
64
64
112
8
55
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
_select_transform
_select_transform
234
249
234
234
0a9eb49719a03f6a5b0bd9bc0216341c71fcb457
bigcode/the-stack
train
abfc8975c1b7c44e0acefa48
train
function
@numba.njit def noise_per_box(boxes, valid_mask, loc_noises, rot_noises): """Add noise to every box (only on the horizontal plane). Args: boxes (np.ndarray): Input boxes with shape (N, 5). valid_mask (np.ndarray): Mask to indicate which boxes are valid with shape (N). loc_no...
@numba.njit def noise_per_box(boxes, valid_mask, loc_noises, rot_noises):
"""Add noise to every box (only on the horizontal plane). Args: boxes (np.ndarray): Input boxes with shape (N, 5). valid_mask (np.ndarray): Mask to indicate which boxes are valid with shape (N). loc_noises (np.ndarray): Location noises with shape (N, M, 3). rot_noise...
-= vec[0] * ( qboxes[j, k, 1] - boxes[i, box_l, 1]) if cross >= 0: # qbox_overlap_box = False break if qbox_overlap_box is False: ...
121
121
406
24
96
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
noise_per_box
noise_per_box
126
164
126
127
0a7ef9e0aac51170e40a4efe5904519a60754ff9
bigcode/the-stack
train
90a0dd7357ab013c9e3f5614
train
function
@numba.njit def _rotation_box2d_jit_(corners, angle, rot_mat_T): """Rotate 2D boxes. Args: corners (np.ndarray): Corners of boxes. angle (float): Rotation angle. rot_mat_T (np.ndarray): Transposed rotation matrix. """ rot_sin = np.sin(angle) rot_cos = np.cos(angle) rot_m...
@numba.njit def _rotation_box2d_jit_(corners, angle, rot_mat_T):
"""Rotate 2D boxes. Args: corners (np.ndarray): Corners of boxes. angle (float): Rotation angle. rot_mat_T (np.ndarray): Transposed rotation matrix. """ rot_sin = np.sin(angle) rot_cos = np.cos(angle) rot_mat_T[0, 0] = rot_cos rot_mat_T[0, 1] = -rot_sin rot_mat_T...
# from numba.errors import NumbaPerformanceWarning from mmdet3d.core.bbox import box_np_ops # warnings.filterwarnings('ignore', category=NumbaPerformanceWarning) @numba.njit def _rotation_box2d_jit_(corners, angle, rot_mat_T):
64
64
155
24
40
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
_rotation_box2d_jit_
_rotation_box2d_jit_
11
26
11
12
45931ef6b14e16ad285fe4d85288bce2548efe89
bigcode/the-stack
train
d6e2632ecc8cbae24f16e751
train
function
@numba.jit(nopython=True) def box_collision_test(boxes, qboxes, clockwise=True): """Box collision test. Args: boxes (np.ndarray): Corners of current boxes. qboxes (np.ndarray): Boxes to be avoid colliding. clockwise (bool): Whether the corners are in clockwise order. Default...
@numba.jit(nopython=True) def box_collision_test(boxes, qboxes, clockwise=True):
"""Box collision test. Args: boxes (np.ndarray): Corners of current boxes. qboxes (np.ndarray): Boxes to be avoid colliding. clockwise (bool): Whether the corners are in clockwise order. Default: True. """ N = boxes.shape[0] K = qboxes.shape[0] ret = np.zeros...
import numba import numpy as np import warnings # from numba.errors import NumbaPerformanceWarning from mmdet3d.core.bbox import box_np_ops # warnings.filterwarnings('ignore', category=NumbaPerformanceWarning) @numba.njit def _rotation_box2d_jit_(corners, angle, rot_mat_T): """Rotate 2D boxes. Args: ...
229
256
1,074
23
205
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
box_collision_test
box_collision_test
29
123
29
30
d82249a29bcd24a5e12b0e4d8c0edc405a7f7495
bigcode/the-stack
train
b23a1f1acaa3a9991478d7aa
train
function
@numba.njit def noise_per_box_v2_(boxes, valid_mask, loc_noises, rot_noises, global_rot_noises): """Add noise to every box (only on the horizontal plane). Version 2 used when enable global rotations. Args: boxes (np.ndarray): Input boxes with shape (N, 5). valid_mask (...
@numba.njit def noise_per_box_v2_(boxes, valid_mask, loc_noises, rot_noises, global_rot_noises):
"""Add noise to every box (only on the horizontal plane). Version 2 used when enable global rotations. Args: boxes (np.ndarray): Input boxes with shape (N, 5). valid_mask (np.ndarray): Mask to indicate which boxes are valid with shape (N). loc_noises (np.ndarray): Locati...
2), dtype=boxes.dtype) rot_mat_T = np.zeros((2, 2), dtype=boxes.dtype) success_mask = -np.ones((num_boxes, ), dtype=np.int64) # print(valid_mask) for i in range(num_boxes): if valid_mask[i]: for j in range(num_tests): current_corners[:] = box_corners[i] ...
249
249
833
32
216
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
noise_per_box_v2_
noise_per_box_v2_
167
231
167
169
806a2d8d791f01b17a34504973e759bee703e157
bigcode/the-stack
train
0960c711316338327a917206
train
function
@numba.njit def _rotation_matrix_3d_(rot_mat_T, angle, axis): """Get the 3D rotation matrix. Args: rot_mat_T (np.ndarray): Transposed rotation matrix. angle (float): Rotation angle. axis (int): Rotation axis. """ rot_sin = np.sin(angle) rot_cos = np.cos(angle) rot_mat_T[...
@numba.njit def _rotation_matrix_3d_(rot_mat_T, angle, axis):
"""Get the 3D rotation matrix. Args: rot_mat_T (np.ndarray): Transposed rotation matrix. angle (float): Rotation angle. axis (int): Rotation axis. """ rot_sin = np.sin(angle) rot_cos = np.cos(angle) rot_mat_T[:] = np.eye(3) if axis == 1: rot_mat_T[0, 0] = rot...
np.ndarray: Selected transforms. """ result = np.zeros((transform.shape[0], *transform.shape[2:]), dtype=transform.dtype) for i in range(transform.shape[0]): if indices[i] != -1: result[i] = transform[i, indices[i]] return result @numba.njit def _rotatio...
89
89
297
22
66
xiaoMrzhang/mmdetection3d
mmdet3d/datasets/pipelines/data_augment_utils.py
Python
_rotation_matrix_3d_
_rotation_matrix_3d_
252
278
252
253
bf7a052a3492a51499a8589e3ff55aedbdaa2288
bigcode/the-stack
train
18034ef2309afd7d784996e4
train
class
class VocSegmentationConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.segmentation super().__init__(*args, **kwargs)
class VocSegmentationConverter(VocConverter):
def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.segmentation super().__init__(*args, **kwargs)
_layout super().__init__(*args, **kwargs) class VocActionConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.action_classification super().__init__(*args, **kwargs) class VocSegmentationConverter(VocConverter):
64
64
43
9
55
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
VocSegmentationConverter
VocSegmentationConverter
701
704
701
701
9bd4186695a369b1e23ebcbdb08207d425b87ad3
bigcode/the-stack
train
ffa0369ac7a406fc60d4b525
train
function
def _convert_attr(name, attributes, type_conv, default=None): d = object() value = attributes.get(name, d) if value is d: return default try: return type_conv(value) except Exception as e: log.warning("Failed to convert attribute '%s'='%s': %s" % \ (name, value, ...
def _convert_attr(name, attributes, type_conv, default=None):
d = object() value = attributes.get(name, d) if value is d: return default try: return type_conv(value) except Exception as e: log.warning("Failed to convert attribute '%s'='%s': %s" % \ (name, value, e)) return default
aro.util.mask_tools import paint_mask, remap_mask from .format import ( VocInstColormap, VocPath, VocTask, make_voc_categories, make_voc_label_map, parse_label_map, write_label_map, ) def _convert_attr(name, attributes, type_conv, default=None):
64
64
84
14
50
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
_convert_attr
_convert_attr
32
43
32
32
14e6f0e37f4edbe5314c726aca8f6c3863f8c750
bigcode/the-stack
train
715636880e8ac839138be31c
train
class
class VocActionConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.action_classification super().__init__(*args, **kwargs)
class VocActionConverter(VocConverter):
def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.action_classification super().__init__(*args, **kwargs)
Task.detection super().__init__(*args, **kwargs) class VocLayoutConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.person_layout super().__init__(*args, **kwargs) class VocActionConverter(VocConverter):
64
64
43
8
56
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
VocActionConverter
VocActionConverter
696
699
696
696
f57ac401696758d97e2fdc5de33630d302c62c22
bigcode/the-stack
train
7f8a582269c492380bde49de
train
class
class VocConverter(Converter): DEFAULT_IMAGE_EXT = VocPath.IMAGE_EXT BUILTIN_ATTRS = {'difficult', 'pose', 'truncated', 'occluded' } @staticmethod def _split_tasks_string(s): return [VocTask[i.strip()] for i in s.split(',')] @staticmethod def _get_labelmap(s): if osp.isfile(s):...
class VocConverter(Converter):
DEFAULT_IMAGE_EXT = VocPath.IMAGE_EXT BUILTIN_ATTRS = {'difficult', 'pose', 'truncated', 'occluded' } @staticmethod def _split_tasks_string(s): return [VocTask[i.strip()] for i in s.split(',')] @staticmethod def _get_labelmap(s): if osp.isfile(s): return s t...
.format import ( VocInstColormap, VocPath, VocTask, make_voc_categories, make_voc_label_map, parse_label_map, write_label_map, ) def _convert_attr(name, attributes, type_conv, default=None): d = object() value = attributes.get(name, d) if value is d: return default try: retur...
256
256
5,398
6
250
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
VocConverter
VocConverter
59
679
59
59
d8286a19b8a8df16d60b4e84befbbaaccf00692e
bigcode/the-stack
train
7356e40d4538c7087cf3545d
train
function
def _write_xml_bbox(bbox, parent_elem): x, y, w, h = bbox bbox_elem = ET.SubElement(parent_elem, 'bndbox') ET.SubElement(bbox_elem, 'xmin').text = str(x) ET.SubElement(bbox_elem, 'ymin').text = str(y) ET.SubElement(bbox_elem, 'xmax').text = str(x + w) ET.SubElement(bbox_elem, 'ymax').text = str(...
def _write_xml_bbox(bbox, parent_elem):
x, y, w, h = bbox bbox_elem = ET.SubElement(parent_elem, 'bndbox') ET.SubElement(bbox_elem, 'xmin').text = str(x) ET.SubElement(bbox_elem, 'ymin').text = str(y) ET.SubElement(bbox_elem, 'xmax').text = str(x + w) ET.SubElement(bbox_elem, 'ymax').text = str(y + h) return bbox_elem
is d: return default try: return type_conv(value) except Exception as e: log.warning("Failed to convert attribute '%s'='%s': %s" % \ (name, value, e)) return default def _write_xml_bbox(bbox, parent_elem):
64
64
113
11
52
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
_write_xml_bbox
_write_xml_bbox
45
52
45
45
4096e8908422923c51701309526214600a6cd36c
bigcode/the-stack
train
6af975c68e6fc785c576ca86
train
class
class VocClassificationConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.classification super().__init__(*args, **kwargs)
class VocClassificationConverter(VocConverter):
def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.classification super().__init__(*args, **kwargs)
+ VocPath.SEGM_EXT) if osp.isfile(path): os.unlink(path) path = osp.join(save_dir, VocPath.INSTANCES_DIR, item.id + VocPath.SEGM_EXT) if osp.isfile(path): os.unlink(path) class VocClassificationConverter(VocCon...
64
64
42
8
56
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
VocClassificationConverter
VocClassificationConverter
681
684
681
681
851ba0a4868a9d20f3116551a907a79744696471
bigcode/the-stack
train
825aa5e5097bf755e4477a74
train
class
class VocLayoutConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.person_layout super().__init__(*args, **kwargs)
class VocLayoutConverter(VocConverter):
def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.person_layout super().__init__(*args, **kwargs)
Task.classification super().__init__(*args, **kwargs) class VocDetectionConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.detection super().__init__(*args, **kwargs) class VocLayoutConverter(VocConverter):
64
64
42
8
56
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
VocLayoutConverter
VocLayoutConverter
691
694
691
691
f9a3ad026700ee850daf599233aaa87ef426f06f
bigcode/the-stack
train
6747383dbcd23b03978a8a67
train
class
class VocDetectionConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.detection super().__init__(*args, **kwargs)
class VocDetectionConverter(VocConverter):
def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.detection super().__init__(*args, **kwargs)
M_EXT) if osp.isfile(path): os.unlink(path) class VocClassificationConverter(VocConverter): def __init__(self, *args, **kwargs): kwargs['tasks'] = VocTask.classification super().__init__(*args, **kwargs) class VocDetectionConverter(VocConverter):
64
64
42
8
56
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
VocDetectionConverter
VocDetectionConverter
686
689
686
686
79a6900b013b0d22e4d4850ed68a22e27445e6c6
bigcode/the-stack
train
4e65f51498c66205cba16895
train
class
class LabelmapType(Enum): voc = auto() source = auto()
class LabelmapType(Enum):
voc = auto() source = auto()
.SubElement(bbox_elem, 'ymin').text = str(y) ET.SubElement(bbox_elem, 'xmax').text = str(x + w) ET.SubElement(bbox_elem, 'ymax').text = str(y + h) return bbox_elem class LabelmapType(Enum):
64
64
16
6
57
IRDonch/datumaro
datumaro/plugins/voc_format/converter.py
Python
LabelmapType
LabelmapType
55
57
55
55
97a99fa8aa56c0a8ee9f470229ad97eea0992122
bigcode/the-stack
train
95a4935f63c570022d285bf9
train
class
class CustomAuthExample: # tag::custom-auth[] def __init__(self, uri, principal, credentials, realm, scheme, **parameters): self._driver = GraphDatabase.driver(uri, auth=custom_auth(principal, credentials, realm, scheme, **parameters)) # end::custom-auth[] def close(self): self._driver....
class CustomAuthExample: # tag::custom-auth[]
def __init__(self, uri, principal, credentials, realm, scheme, **parameters): self._driver = GraphDatabase.driver(uri, auth=custom_auth(principal, credentials, realm, scheme, **parameters)) # end::custom-auth[] def close(self): self._driver.close() def can_connect(self): with s...
, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # tag::custom-auth-import[] from neo4j.v1 import GraphDatabase, custom_auth # end::custom-auth-import[] class CustomAuthExample: # tag::custom-auth[]
63
64
113
12
51
jsoref/neo4j-python-driver
test/examples/custom_auth_example.py
Python
CustomAuthExample
CustomAuthExample
26
38
26
27
b1aabf12122215c889c13780f1f66eb00e275555
bigcode/the-stack
train