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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0bbb0e5eaed5a44bcae30ca4 | train | class | class Post(models.Model):
text = models.TextField("Комментарий к треку")
pub_date = models.DateTimeField("Дата публикации",
auto_now_add=True, db_index=True)
author = models.ForeignKey(User, on_delete=models.CASCADE,
verbose_name="Автор")
... | class Post(models.Model):
| text = models.TextField("Комментарий к треку")
pub_date = models.DateTimeField("Дата публикации",
auto_now_add=True, db_index=True)
author = models.ForeignKey(User, on_delete=models.CASCADE,
verbose_name="Автор")
genre = models.ForeignKe... | = get_user_model()
class Genre(models.Model):
title = models.CharField("Название", max_length=200)
slug = models.SlugField("Путь", unique=True)
description = models.TextField("Описание")
def __str__(self):
return self.title
class Post(models.Model):
| 64 | 64 | 153 | 5 | 58 | kudinov-prog/music_square | posts/models.py | Python | Post | Post | 18 | 35 | 18 | 19 | 44284108f205f687d9583720cb0773e1296394b7 | bigcode/the-stack | train |
69f2fdf0f2caedcbf97a244c | train | class | class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE,
related_name="comments",
verbose_name="Пост")
author = models.ForeignKey(User, on_delete=models.CASCADE,
verbose_name="Автор коммент... | class Comment(models.Model):
| post = models.ForeignKey(Post, on_delete=models.CASCADE,
related_name="comments",
verbose_name="Пост")
author = models.ForeignKey(User, on_delete=models.CASCADE,
verbose_name="Автор комментария")
text = models.TextFiel... | image = models.ImageField(upload_to='posts/', blank=True, null=True)
content = models.FileField(upload_to='posts/', blank=True, null=True)
def __str__(self):
return self.text
class Meta:
ordering = ["-pub_date"]
class Comment(models.Model):
| 63 | 64 | 107 | 6 | 57 | kudinov-prog/music_square | posts/models.py | Python | Comment | Comment | 38 | 52 | 38 | 39 | fda97f407ed1cb6907d2c71fd1139091985c563c | bigcode/the-stack | train |
9c9a06db19ef8e753fa5a3e3 | train | function | def parse_arguments():
"""Reads program arguments
----------
:return: Parsed program arguments
"""
parser = argparse.ArgumentParser(description='Program that clusters characters')
parser.add_argument("images_list_file_path",
help="path to file with listed character imag... | def parse_arguments():
| """Reads program arguments
----------
:return: Parsed program arguments
"""
parser = argparse.ArgumentParser(description='Program that clusters characters')
parser.add_argument("images_list_file_path",
help="path to file with listed character images")
parser.add_arg... | import argparse
from .defaults import *
def parse_arguments():
| 12 | 84 | 281 | 4 | 8 | abrams27/mimuw | sem6/sus/bigtask1/characters_clustering/argument_parser.py | Python | parse_arguments | parse_arguments | 5 | 34 | 5 | 5 | 9a85a92bbd2414015e307c3b61be72bc58c99460 | bigcode/the-stack | train |
ecfec7adabc6bd45bc7981f3 | train | class | @pulumi.output_type
class GetExpressRouteCircuitAuthorizationResult:
"""
Authorization in an ExpressRouteCircuit resource.
"""
def __init__(__self__, authorization_key=None, authorization_use_status=None, etag=None, id=None, name=None, provisioning_state=None):
if authorization_key and not isins... | @pulumi.output_type
class GetExpressRouteCircuitAuthorizationResult:
| """
Authorization in an ExpressRouteCircuit resource.
"""
def __init__(__self__, authorization_key=None, authorization_use_status=None, etag=None, id=None, name=None, provisioning_state=None):
if authorization_key and not isinstance(authorization_key, str):
raise TypeError("Expected ... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... | 126 | 188 | 629 | 14 | 112 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/network/v20190201/get_express_route_circuit_authorization.py | Python | GetExpressRouteCircuitAuthorizationResult | GetExpressRouteCircuitAuthorizationResult | 17 | 88 | 17 | 18 | 7e3ff2d7abd73a20a5ab83e67cc2e0404e2fad6c | bigcode/the-stack | train |
f54ae7180daacf33299f379e | train | class | class AwaitableGetExpressRouteCircuitAuthorizationResult(GetExpressRouteCircuitAuthorizationResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetExpressRouteCircuitAuthorizationResult(
authorization_key=self.authorization_key,... | class AwaitableGetExpressRouteCircuitAuthorizationResult(GetExpressRouteCircuitAuthorizationResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetExpressRouteCircuitAuthorizationResult(
authorization_key=self.authorization_key,
authorization_use_status=self.authorization_use_status,
etag=self.etag,
id=self.id,
name=self.... | provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
"""
return pulumi.get(self, "provisioning_state")
class AwaitableGetExpressRouteCircuitAuthorizationResult(GetExpressRouteCircuitAuthorizationResult):
# pylint: disable=using-constant-test
| 64 | 64 | 93 | 27 | 37 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/network/v20190201/get_express_route_circuit_authorization.py | Python | AwaitableGetExpressRouteCircuitAuthorizationResult | AwaitableGetExpressRouteCircuitAuthorizationResult | 91 | 102 | 91 | 92 | feaed181ab9b235c3700d661bb60ea040693c9dd | bigcode/the-stack | train |
20748ed8ee5e87e9b06b9185 | train | function | def get_express_route_circuit_authorization(authorization_name: Optional[str] = None,
circuit_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.I... | def get_express_route_circuit_authorization(authorization_name: Optional[str] = None,
circuit_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.I... | """
Authorization in an ExpressRouteCircuit resource.
:param str authorization_name: The name of the authorization.
:param str circuit_name: The name of the express route circuit.
:param str resource_group_name: The name of the resource group.
"""
__args__ = dict()
__args__['authorizat... | _use_status,
etag=self.etag,
id=self.id,
name=self.name,
provisioning_state=self.provisioning_state)
def get_express_route_circuit_authorization(authorization_name: Optional[str] = None,
circuit_name: Optional[str] = None,
... | 92 | 92 | 308 | 63 | 29 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/network/v20190201/get_express_route_circuit_authorization.py | Python | get_express_route_circuit_authorization | get_express_route_circuit_authorization | 105 | 133 | 105 | 108 | bdaef50db295ab06a8e5193072bf45cdbb1e71ae | bigcode/the-stack | train |
4975d9c48c52eea6462e7908 | train | class | class ListCustomerOrdersRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_... | class ListCustomerOrdersRequest:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListCustomerOrdersRequest:
| 34 | 256 | 3,750 | 6 | 27 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-bss/huaweicloudsdkbss/v2/model/list_customer_orders_request.py | Python | ListCustomerOrdersRequest | ListCustomerOrdersRequest | 11 | 438 | 11 | 13 | 2e3d1a96da2b93f49182d53e3bae71c07db409e6 | bigcode/the-stack | train |
e4619fa60387d3c5aac689ba | train | function | @njit(cache=True)
def stoch_cache_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d,
k_windows: tp.List[int], d_windows: tp.List[int], d_ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]:
"""Caching function for `vectorbt.indicators.basi... | @njit(cache=True)
def stoch_cache_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d,
k_windows: tp.List[int], d_windows: tp.List[int], d_ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]:
| """Caching function for `vectorbt.indicators.basic.STOCH`."""
cache_dict = dict()
for i in range(len(k_windows)):
h = hash(k_windows[i])
if h not in cache_dict:
roll_min = generic_nb.rolling_min_nb(low, k_windows[i])
roll_max = generic_nb.rolling_max_nb(high, k_window... | @njit(cache=True)
def stoch_cache_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d,
k_windows: tp.List[int], d_windows: tp.List[int], d_ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]:
| 80 | 64 | 176 | 80 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | stoch_cache_nb | stoch_cache_nb | 128 | 140 | 128 | 131 | 6ccd3587534c5f15c860f47369e4e62004c2d1df | bigcode/the-stack | train |
33e0119a810327f67215ba27 | train | function | @njit(cache=True)
def mstd_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool, ddof: int,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Array2d:
"""Apply function for `vectorbt.indicators.basic.MSTD`."""
h = hash((window, ewm))
return cache_dict[h]
| @njit(cache=True)
def mstd_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool, ddof: int,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Array2d:
| """Apply function for `vectorbt.indicators.basic.MSTD`."""
h = hash((window, ewm))
return cache_dict[h]
| =ddof)
return cache_dict
@njit(cache=True)
def mstd_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool, ddof: int,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Array2d:
| 64 | 64 | 86 | 55 | 8 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | mstd_apply_nb | mstd_apply_nb | 68 | 73 | 68 | 70 | f0333419617c646a88003c363ab669b067888ab3 | bigcode/the-stack | train |
eb483ad8d8414c237e271615 | train | function | @njit(cache=True)
def atr_apply_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d, window: int, ewm: bool, adjust: bool,
tr: tp.Array2d, cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
"""Apply function for `vectorbt.indicators.basic.ATR`."""
h = hash((window, e... | @njit(cache=True)
def atr_apply_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d, window: int, ewm: bool, adjust: bool,
tr: tp.Array2d, cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
| """Apply function for `vectorbt.indicators.basic.ATR`."""
h = hash((window, ewm))
return tr, cache_dict[h]
| @njit(cache=True)
def atr_apply_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d, window: int, ewm: bool, adjust: bool,
tr: tp.Array2d, cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
| 78 | 64 | 111 | 78 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | atr_apply_nb | atr_apply_nb | 209 | 214 | 209 | 211 | 5660a3b0db21789b1df16921181087fb5eadeccf | bigcode/the-stack | train |
548bfe06f4f9088dd9fb1225 | train | function | @njit(cache=True)
def mstd_nb(a: tp.Array2d, window: int, ewm: int, adjust: bool = False, ddof: int = 0) -> tp.Array2d:
"""Compute simple or exponential moving STD (`ewm=True`)."""
if ewm:
return generic_nb.ewm_std_nb(a, window, minp=window, adjust=adjust, ddof=ddof)
return generic_nb.rolling_std_nb... | @njit(cache=True)
def mstd_nb(a: tp.Array2d, window: int, ewm: int, adjust: bool = False, ddof: int = 0) -> tp.Array2d:
| """Compute simple or exponential moving STD (`ewm=True`)."""
if ewm:
return generic_nb.ewm_std_nb(a, window, minp=window, adjust=adjust, ddof=ddof)
return generic_nb.rolling_std_nb(a, window, minp=window, ddof=ddof)
| )
return generic_nb.rolling_mean_nb(a, window, minp=window)
@njit(cache=True)
def mstd_nb(a: tp.Array2d, window: int, ewm: int, adjust: bool = False, ddof: int = 0) -> tp.Array2d:
| 64 | 64 | 116 | 46 | 18 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | mstd_nb | mstd_nb | 28 | 33 | 28 | 29 | 69ce73bee5c946d6bdbea30fa489b6289ea0f9d2 | bigcode/the-stack | train |
92c447fd68245a8089d5b1de | train | function | @njit(cache=True)
def macd_apply_nb(close: tp.Array2d, fast_window: int, slow_window: int,
signal_window: int, macd_ewm: bool, signal_ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
"""Apply function for `vectorbt.indicators.bas... | @njit(cache=True)
def macd_apply_nb(close: tp.Array2d, fast_window: int, slow_window: int,
signal_window: int, macd_ewm: bool, signal_ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
| """Apply function for `vectorbt.indicators.basic.MACD`."""
fast_h = hash((fast_window, macd_ewm))
slow_h = hash((slow_window, macd_ewm))
fast_ma = cache_dict[fast_h]
slow_ma = cache_dict[slow_h]
macd_ts = fast_ma - slow_ma
signal_ts = ma_nb(macd_ts, signal_window, signal_ewm, adjust=adjust)
... | @njit(cache=True)
def macd_apply_nb(close: tp.Array2d, fast_window: int, slow_window: int,
signal_window: int, macd_ewm: bool, signal_ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
| 80 | 64 | 188 | 80 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | macd_apply_nb | macd_apply_nb | 167 | 178 | 167 | 170 | 18e2443c42fd52450e7f0cd95c7fa3f60f93c580 | bigcode/the-stack | train |
7ee72f59c3bba91737e88266 | train | function | @njit(cache=True)
def true_range_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d) -> tp.Array2d:
"""Calculate true range."""
prev_close = generic_nb.fshift_nb(close, 1)
tr1 = high - low
tr2 = np.abs(high - prev_close)
tr3 = np.abs(low - prev_close)
tr = np.empty(prev_close.shape, dtype=n... | @njit(cache=True)
def true_range_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d) -> tp.Array2d:
| """Calculate true range."""
prev_close = generic_nb.fshift_nb(close, 1)
tr1 = high - low
tr2 = np.abs(high - prev_close)
tr3 = np.abs(low - prev_close)
tr = np.empty(prev_close.shape, dtype=np.float_)
for col in range(tr.shape[1]):
for i in range(tr.shape[0]):
tr[i, col] ... | ma_nb(macd_ts, signal_window, signal_ewm, adjust=adjust)
return macd_ts, signal_ts
@njit(cache=True)
def true_range_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d) -> tp.Array2d:
| 64 | 64 | 150 | 37 | 26 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | true_range_nb | true_range_nb | 181 | 192 | 181 | 182 | ce17ace3126c3eb76ee50c5632afbb9aade591c7 | bigcode/the-stack | train |
8d5558d9b3d69ab6fde85c1b | train | function | @njit(cache=True)
def rsi_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]) -> tp.Array2d:
"""Apply function for `vectorbt.indicators.basic.RSI`."""
h = hash((window, ewm))
roll_up, roll_down = cache_dict[h]
rs ... | @njit(cache=True)
def rsi_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]) -> tp.Array2d:
| """Apply function for `vectorbt.indicators.basic.RSI`."""
h = hash((window, ewm))
roll_up, roll_down = cache_dict[h]
rs = roll_up / roll_down
return 100 - 100 / (1 + rs)
|
return cache_dict
@njit(cache=True)
def rsi_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]) -> tp.Array2d:
| 64 | 64 | 116 | 58 | 5 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | rsi_apply_nb | rsi_apply_nb | 118 | 125 | 118 | 120 | 619027dd0a9dc77facb1748b1252efd7cc0d0471 | bigcode/the-stack | train |
223a38ab34710c823290e004 | train | function | @njit(cache=True)
def ma_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
"""Caching function for `vectorbt.indicators.basic.MA`."""
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[i], ewms[i]))
... | @njit(cache=True)
def ma_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
| """Caching function for `vectorbt.indicators.basic.MA`."""
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[i], ewms[i]))
if h not in cache_dict:
cache_dict[h] = ma_nb(close, windows[i], ewms[i], adjust=adjust)
return cache_dict
| rolling_std_nb(a, window, minp=window, ddof=ddof)
@njit(cache=True)
def ma_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
| 64 | 64 | 122 | 46 | 18 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | ma_cache_nb | ma_cache_nb | 36 | 45 | 36 | 38 | 768d0525967868b1e719aae64ee5ebd10c3cd69e | bigcode/the-stack | train |
e1d57f7ede7c60a3007e5899 | train | function | @njit(cache=True)
def bb_apply_nb(close: tp.Array2d, window: int, ewm: bool, alpha: float,
adjust: bool, ddof: int, ma_cache_dict: tp.Dict[int, tp.Array2d],
mstd_cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d, tp.Array2d]:
"""Apply function for `vectorbt.ind... | @njit(cache=True)
def bb_apply_nb(close: tp.Array2d, window: int, ewm: bool, alpha: float,
adjust: bool, ddof: int, ma_cache_dict: tp.Dict[int, tp.Array2d],
mstd_cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d, tp.Array2d]:
| """Apply function for `vectorbt.indicators.basic.BBANDS`."""
# Calculate lower, middle and upper bands
h = hash((window, ewm))
ma = np.copy(ma_cache_dict[h])
mstd = np.copy(mstd_cache_dict[h])
# # (MA + Kσ), MA, (MA - Kσ)
return ma, ma + alpha * mstd, ma - alpha * mstd
| @njit(cache=True)
def bb_apply_nb(close: tp.Array2d, window: int, ewm: bool, alpha: float,
adjust: bool, ddof: int, ma_cache_dict: tp.Dict[int, tp.Array2d],
mstd_cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Tuple[tp.Array2d, tp.Array2d, tp.Array2d]:
| 87 | 64 | 180 | 87 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | bb_apply_nb | bb_apply_nb | 85 | 95 | 85 | 88 | c8d530d892c854ee4ebe6365153927ef04ad722e | bigcode/the-stack | train |
3a48fa9a2566a58d378f499c | train | function | @njit(cache=True)
def mstd_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], adjust: bool,
ddof: int) -> tp.Dict[int, tp.Array2d]:
"""Caching function for `vectorbt.indicators.basic.MSTD`."""
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[... | @njit(cache=True)
def mstd_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], adjust: bool,
ddof: int) -> tp.Dict[int, tp.Array2d]:
| """Caching function for `vectorbt.indicators.basic.MSTD`."""
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[i], ewms[i]))
if h not in cache_dict:
cache_dict[h] = mstd_nb(close, windows[i], ewms[i], adjust=adjust, ddof=ddof)
return cache_dict
| ((window, ewm))
return cache_dict[h]
@njit(cache=True)
def mstd_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], adjust: bool,
ddof: int) -> tp.Dict[int, tp.Array2d]:
| 64 | 64 | 135 | 52 | 12 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | mstd_cache_nb | mstd_cache_nb | 56 | 65 | 56 | 58 | 274666451762ce2eba56ca754f7a7861ea311200 | bigcode/the-stack | train |
2f17b3771c65cc6488b53bae | train | function | @njit(cache=True)
def rsi_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]:
"""Caching function for `vectorbt.indicators.basic.RSI`."""
delta = generic_nb.diff_nb(close)
up, down = delta.copy(), delta.cop... | @njit(cache=True)
def rsi_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]:
| """Caching function for `vectorbt.indicators.basic.RSI`."""
delta = generic_nb.diff_nb(close)
up, down = delta.copy(), delta.copy()
up = generic_nb.set_by_mask_nb(up, up < 0, 0)
down = np.abs(generic_nb.set_by_mask_nb(down, down > 0, 0))
# Cache
cache_dict = dict()
for i in range(len(wi... | + alpha * mstd, ma - alpha * mstd
@njit(cache=True)
def rsi_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]:
| 68 | 68 | 227 | 55 | 12 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | rsi_cache_nb | rsi_cache_nb | 98 | 115 | 98 | 100 | 4dc1e46f7d25c636731694655b5abfbed046d3a7 | bigcode/the-stack | train |
8b0fa2e8338bc266fecf433c | train | function | @njit(cache=True)
def ma_nb(a: tp.Array2d, window: int, ewm: bool, adjust: bool = False) -> tp.Array2d:
"""Compute simple or exponential moving average (`ewm=True`)."""
if ewm:
return generic_nb.ewm_mean_nb(a, window, minp=window, adjust=adjust)
return generic_nb.rolling_mean_nb(a, window, minp=wind... | @njit(cache=True)
def ma_nb(a: tp.Array2d, window: int, ewm: bool, adjust: bool = False) -> tp.Array2d:
| """Compute simple or exponential moving average (`ewm=True`)."""
if ewm:
return generic_nb.ewm_mean_nb(a, window, minp=window, adjust=adjust)
return generic_nb.rolling_mean_nb(a, window, minp=window)
|
from numba import njit
from vectorbt import _typing as tp
from vectorbt.generic import nb as generic_nb
@njit(cache=True)
def ma_nb(a: tp.Array2d, window: int, ewm: bool, adjust: bool = False) -> tp.Array2d:
| 64 | 64 | 95 | 37 | 26 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | ma_nb | ma_nb | 20 | 25 | 20 | 21 | 1310a20a68188c254d574d98411464dfabd6d381 | bigcode/the-stack | train |
912041e5a214a15991ee5e3c | train | function | @njit(cache=True)
def atr_cache_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d, windows: tp.List[int],
ewms: tp.List[bool], adjust: bool) -> tp.Tuple[tp.Array2d, tp.Dict[int, tp.Array2d]]:
"""Caching function for `vectorbt.indicators.basic.ATR`."""
# Calculate TR here instead of re-cal... | @njit(cache=True)
def atr_cache_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d, windows: tp.List[int],
ewms: tp.List[bool], adjust: bool) -> tp.Tuple[tp.Array2d, tp.Dict[int, tp.Array2d]]:
| """Caching function for `vectorbt.indicators.basic.ATR`."""
# Calculate TR here instead of re-calculating it for each param in atr_apply_nb
tr = true_range_nb(high, low, close)
cache_dict = dict()
for i in range(len(windows)):
h = hash((windows[i], ewms[i]))
if h not in cache_dict:
... | @njit(cache=True)
def atr_cache_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d, windows: tp.List[int],
ewms: tp.List[bool], adjust: bool) -> tp.Tuple[tp.Array2d, tp.Dict[int, tp.Array2d]]:
| 68 | 64 | 178 | 68 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | atr_cache_nb | atr_cache_nb | 195 | 206 | 195 | 197 | ce4d13712aa2b67c13a4cbd5b3deeb3fafc01b63 | bigcode/the-stack | train |
8ab7eeea8a394b79fa8946ce | train | function | @njit(cache=True)
def ma_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Array2d:
"""Apply function for `vectorbt.indicators.basic.MA`."""
h = hash((window, ewm))
return cache_dict[h]
| @njit(cache=True)
def ma_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Array2d:
| """Apply function for `vectorbt.indicators.basic.MA`."""
h = hash((window, ewm))
return cache_dict[h]
| [i], ewms[i], adjust=adjust)
return cache_dict
@njit(cache=True)
def ma_apply_nb(close: tp.Array2d, window: int, ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Array2d]) -> tp.Array2d:
| 64 | 64 | 80 | 49 | 14 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | ma_apply_nb | ma_apply_nb | 48 | 53 | 48 | 50 | c76775c3d12cff7161fef0b18aba838f1b000d7f | bigcode/the-stack | train |
f193c4c972518d20e9f35bb9 | train | function | @njit(cache=True)
def bb_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], alphas: tp.List[float],
adjust: bool, ddof: int) -> tp.Tuple[tp.Dict[int, tp.Array2d], tp.Dict[int, tp.Array2d]]:
"""Caching function for `vectorbt.indicators.basic.BBANDS`."""
ma_cache_dict = ma_cac... | @njit(cache=True)
def bb_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], alphas: tp.List[float],
adjust: bool, ddof: int) -> tp.Tuple[tp.Dict[int, tp.Array2d], tp.Dict[int, tp.Array2d]]:
| """Caching function for `vectorbt.indicators.basic.BBANDS`."""
ma_cache_dict = ma_cache_nb(close, windows, ewms, adjust)
mstd_cache_dict = mstd_cache_nb(close, windows, ewms, adjust, ddof)
return ma_cache_dict, mstd_cache_dict
| @njit(cache=True)
def bb_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], alphas: tp.List[float],
adjust: bool, ddof: int) -> tp.Tuple[tp.Dict[int, tp.Array2d], tp.Dict[int, tp.Array2d]]:
| 71 | 64 | 137 | 71 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | bb_cache_nb | bb_cache_nb | 76 | 82 | 76 | 78 | 2f0659d2701d5fabf7ca07d594f746ce37a6b9ad | bigcode/the-stack | train |
7070b57ba20a6cd2dc7cdce3 | train | function | @njit(cache=True)
def stoch_apply_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d,
k_window: int, d_window: int, d_ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
"""Apply function for `vectorbt.i... | @njit(cache=True)
def stoch_apply_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d,
k_window: int, d_window: int, d_ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
| """Apply function for `vectorbt.indicators.basic.STOCH`."""
h = hash(k_window)
roll_min, roll_max = cache_dict[h]
percent_k = 100 * (close - roll_min) / (roll_max - roll_min)
percent_d = ma_nb(percent_k, d_window, d_ewm, adjust=adjust)
return percent_k, percent_d
| @njit(cache=True)
def stoch_apply_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d,
k_window: int, d_window: int, d_ewm: bool, adjust: bool,
cache_dict: tp.Dict[int, tp.Tuple[tp.Array2d, tp.Array2d]]) -> tp.Tuple[tp.Array2d, tp.Array2d]:
| 89 | 64 | 173 | 89 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | stoch_apply_nb | stoch_apply_nb | 143 | 152 | 143 | 146 | 99b8b2f87823581a7a645978d438b9d35461bf39 | bigcode/the-stack | train |
c36bcbed25719b082c6ea174 | train | function | @njit(cache=True)
def obv_custom_nb(close: tp.Array2d, volume_ts: tp.Array2d) -> tp.Array2d:
"""Custom calculation function for `vectorbt.indicators.basic.OBV`."""
obv = generic_nb.set_by_mask_mult_nb(volume_ts, close < generic_nb.fshift_nb(close, 1), -volume_ts)
obv = generic_nb.nancumsum_nb(obv)
retur... | @njit(cache=True)
def obv_custom_nb(close: tp.Array2d, volume_ts: tp.Array2d) -> tp.Array2d:
| """Custom calculation function for `vectorbt.indicators.basic.OBV`."""
obv = generic_nb.set_by_mask_mult_nb(volume_ts, close < generic_nb.fshift_nb(close, 1), -volume_ts)
obv = generic_nb.nancumsum_nb(obv)
return obv
| """Apply function for `vectorbt.indicators.basic.ATR`."""
h = hash((window, ewm))
return tr, cache_dict[h]
@njit(cache=True)
def obv_custom_nb(close: tp.Array2d, volume_ts: tp.Array2d) -> tp.Array2d:
| 64 | 64 | 97 | 32 | 32 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | obv_custom_nb | obv_custom_nb | 217 | 222 | 217 | 218 | 8c1649a91e3521196c420b965623650010764b29 | bigcode/the-stack | train |
95d562564ac2918ce7959990 | train | function | @njit(cache=True)
def macd_cache_nb(close: tp.Array2d, fast_windows: tp.List[int], slow_windows: tp.List[int],
signal_windows: tp.List[int], macd_ewms: tp.List[bool], signal_ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
"""Caching function for `vectorbt.indicato... | @njit(cache=True)
def macd_cache_nb(close: tp.Array2d, fast_windows: tp.List[int], slow_windows: tp.List[int],
signal_windows: tp.List[int], macd_ewms: tp.List[bool], signal_ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
| """Caching function for `vectorbt.indicators.basic.MACD`."""
windows = fast_windows.copy()
windows.extend(slow_windows)
ewms = macd_ewms.copy()
ewms.extend(macd_ewms)
return ma_cache_nb(close, windows, ewms, adjust)
| @njit(cache=True)
def macd_cache_nb(close: tp.Array2d, fast_windows: tp.List[int], slow_windows: tp.List[int],
signal_windows: tp.List[int], macd_ewms: tp.List[bool], signal_ewms: tp.List[bool],
adjust: bool) -> tp.Dict[int, tp.Array2d]:
| 76 | 64 | 141 | 76 | 0 | zhnagchulan/vectorbt | vectorbt/indicators/nb.py | Python | macd_cache_nb | macd_cache_nb | 155 | 164 | 155 | 158 | baac4920e8a40e804ba65d8d50c47093cb857026 | bigcode/the-stack | train |
8204ae9fe64218ba201fd3d8 | train | function | def substrCount(n, s):
cnt = 0
for start in range(n):
for end in range(start+1, n+1):
cnt += int(is_valid(s[start:end]))
return cnt
| def substrCount(n, s):
| cnt = 0
for start in range(n):
for end in range(start+1, n+1):
cnt += int(is_valid(s[start:end]))
return cnt
| # Initialize the character to check
if not last:
last = s[0]
# Check the condition
if not s[0] == s[-1] == last:
return False
return is_valid(s[1:-1], last)
def substrCount(n, s):
| 64 | 64 | 48 | 7 | 57 | KunyuHe/Hacker-Rank-Practice | ProblemSolving/SpecialStringAgain.py | Python | substrCount | substrCount | 17 | 24 | 17 | 17 | 7af1986af3c58c94c563a947281ad206802d2aa5 | bigcode/the-stack | train |
9c504de3986024149089a153 | train | function | def is_valid(s, last=None):
# If it is an empty string or just one letter, it meets the criteria
if len(s) in [0, 1]:
return True
# Initialize the character to check
if not last:
last = s[0]
# Check the condition
if not s[0] == s[-1] == last:
return False
... | def is_valid(s, last=None):
# If it is an empty string or just one letter, it meets the criteria
| if len(s) in [0, 1]:
return True
# Initialize the character to check
if not last:
last = s[0]
# Check the condition
if not s[0] == s[-1] == last:
return False
return is_valid(s[1:-1], last)
| def is_valid(s, last=None):
# If it is an empty string or just one letter, it meets the criteria
| 26 | 64 | 99 | 26 | 0 | KunyuHe/Hacker-Rank-Practice | ProblemSolving/SpecialStringAgain.py | Python | is_valid | is_valid | 1 | 14 | 1 | 2 | 8871c6f2e3e1165499653798c5176c78b252b3bd | bigcode/the-stack | train |
38af4c076e7e3bf88dd21a07 | train | function | def fenci(sentence):
seg_list = jieba.lcut(sentence)
return seg_list[:-1]
| def fenci(sentence):
| seg_list = jieba.lcut(sentence)
return seg_list[:-1]
| "[\u4e00-\u9fa5]+")
while words != "":
#words =pattern.findall(words)
words = words[:-1]
if words != []:
st.append(words)
words = texts.readline()
print(st)
return st
def fenci(sentence):
| 64 | 64 | 21 | 5 | 58 | skant626/observe_for_bilibili | GetData/wenbeifenci.py | Python | fenci | fenci | 41 | 43 | 41 | 41 | a3f93a6752374efe9de1a585d735f1afad7b38d0 | bigcode/the-stack | train |
88432dcbbef00c4d11f9a6f0 | train | function | def textwashing(src,savepath):
try:
savecontent = open(savepath,'w')
i = 0
while i<999:
i = i+1
if os.path.exists(str(src)+str(i)+".txt"):
content = open(str(src)+str(i)+".txt",'r')
strings = ""
texts = content.readline()
while texts != "":
pattern = re.compile(u"[\u4e00-\u9fa5]+")
... | def textwashing(src,savepath):
| try:
savecontent = open(savepath,'w')
i = 0
while i<999:
i = i+1
if os.path.exists(str(src)+str(i)+".txt"):
content = open(str(src)+str(i)+".txt",'r')
strings = ""
texts = content.readline()
while texts != "":
pattern = re.compile(u"[\u4e00-\u9fa5]+")
texts =pattern.findall(texts... | import jieba
import re
import os
import nltk
#src = "weibodata//2017-04-23//tieba"
#savepath = "tieba_sentence.txt"
def textwashing(src,savepath):
| 49 | 64 | 159 | 8 | 41 | skant626/observe_for_bilibili | GetData/wenbeifenci.py | Python | textwashing | textwashing | 8 | 27 | 8 | 8 | 3bb88c01fdf771eabe88a55ca40df3a529f25d7d | bigcode/the-stack | train |
1f5ffba9c69faaaa2cb44e25 | train | function | def stopwords(src):
texts = open(src)
words = texts.readline()
st = []
#pattern = re.compile(u"[\u4e00-\u9fa5]+")
while words != "":
#words =pattern.findall(words)
words = words[:-1]
if words != []:
st.append(words)
words = texts.readline()
print(st)
return st
| def stopwords(src):
| texts = open(src)
words = texts.readline()
st = []
#pattern = re.compile(u"[\u4e00-\u9fa5]+")
while words != "":
#words =pattern.findall(words)
words = words[:-1]
if words != []:
st.append(words)
words = texts.readline()
print(st)
return st
| 9fa5]+")
texts =pattern.findall(texts)
print(texts)
for text in texts:
savecontent.write(str(text)+"\n")
texts = content.readline()
print("texts:",texts)
except Exception as e:
print(e)
def stopwords(src):
| 64 | 64 | 86 | 5 | 59 | skant626/observe_for_bilibili | GetData/wenbeifenci.py | Python | stopwords | stopwords | 28 | 40 | 28 | 28 | 536a031548e5759c72fbf3c4a62cc63eb828b036 | bigcode/the-stack | train |
94b9394383e21fe0b9b4a4b0 | train | function | def test_create():
ds = datashape.dshape('5 * int32')
d = create(nd.array, dshape=ds)
assert discover(d) == ds
| def test_create():
| ds = datashape.dshape('5 * int32')
d = create(nd.array, dshape=ds)
assert discover(d) == ds
| convert, discover
from dynd import nd
import numpy as np
import datashape
@pytest.fixture
def x():
ds = datashape.dshape('3 * int32')
return convert(nd.array, [1, 2, 3], dshape=ds)
def test_create():
| 64 | 64 | 38 | 4 | 60 | wangyum/anaconda | pkgs/odo-0.4.2-py27_0/lib/python2.7/site-packages/odo/backends/tests/test_dynd.py | Python | test_create | test_create | 19 | 22 | 19 | 19 | d8e1b03dd0644a8999a81b4ded8c6a66e8bfab9a | bigcode/the-stack | train |
5bf4f86ddefd9eae31ec89bc | train | function | @pytest.fixture
def x():
ds = datashape.dshape('3 * int32')
return convert(nd.array, [1, 2, 3], dshape=ds)
| @pytest.fixture
def x():
| ds = datashape.dshape('3 * int32')
return convert(nd.array, [1, 2, 3], dshape=ds)
| from __future__ import absolute_import, division, print_function
import pytest
import sys
pytest.importorskip('dynd')
from odo import create, convert, discover
from dynd import nd
import numpy as np
import datashape
@pytest.fixture
def x():
| 58 | 64 | 40 | 6 | 51 | wangyum/anaconda | pkgs/odo-0.4.2-py27_0/lib/python2.7/site-packages/odo/backends/tests/test_dynd.py | Python | x | x | 13 | 16 | 13 | 14 | ad07c61d509ccd1aa62fe09158d10eb0fc98be43 | bigcode/the-stack | train |
995904477f2d608439f21351 | train | function | @pytest.mark.parametrize(['typ', 'expected'],
[(list, [1, 2, 3]),
(tuple, (1, 2, 3)),
(np.ndarray, np.array([1, 2, 3]))])
def test_convert_different_types(x, typ, expected):
y = convert(typ, x)
assert isinstance(y, typ)
assert isin... | @pytest.mark.parametrize(['typ', 'expected'],
[(list, [1, 2, 3]),
(tuple, (1, 2, 3)),
(np.ndarray, np.array([1, 2, 3]))])
def test_convert_different_types(x, typ, expected):
| y = convert(typ, x)
assert isinstance(y, typ)
assert isinstance(convert(nd.array, y), nd.array)
assert all(lhs == rhs for lhs, rhs in zip(y, expected))
| @pytest.mark.parametrize(['typ', 'expected'],
[(list, [1, 2, 3]),
(tuple, (1, 2, 3)),
(np.ndarray, np.array([1, 2, 3]))])
def test_convert_different_types(x, typ, expected):
| 64 | 64 | 108 | 64 | 0 | wangyum/anaconda | pkgs/odo-0.4.2-py27_0/lib/python2.7/site-packages/odo/backends/tests/test_dynd.py | Python | test_convert_different_types | test_convert_different_types | 30 | 38 | 30 | 34 | b1f725af639433c2fb7d1f2bc09a191f8660de48 | bigcode/the-stack | train |
a9b807bb2cd7dfbc56cde39d | train | function | def test_simple_convert(x):
assert isinstance(x, nd.array)
assert convert(list, x) == [1, 2, 3]
| def test_simple_convert(x):
| assert isinstance(x, nd.array)
assert convert(list, x) == [1, 2, 3]
| return convert(nd.array, [1, 2, 3], dshape=ds)
def test_create():
ds = datashape.dshape('5 * int32')
d = create(nd.array, dshape=ds)
assert discover(d) == ds
def test_simple_convert(x):
| 64 | 64 | 31 | 6 | 57 | wangyum/anaconda | pkgs/odo-0.4.2-py27_0/lib/python2.7/site-packages/odo/backends/tests/test_dynd.py | Python | test_simple_convert | test_simple_convert | 25 | 27 | 25 | 25 | 4d8ac78e3624b630a099078cd9e1a620cf641485 | bigcode/the-stack | train |
3c6f59ae17f9ba35e9962b7f | train | function | def get_mixnet_small(depth_multiplier=None):
blocks_args = [
'r1_k3_a1_p1_s11_e1_i16_o16',
'r1_k3_a1.1_p1.1_s22_e6_i16_o24',
'r1_k3_a1.1_p1.1_s11_e3_i24_o24',
'r1_k3.5.7_a1_p1_s22_e6_i24_o40_se0.5_sw',
'r3_k3.5_a1.1_p1.1_s11_e6_i40_o40_se0.5_sw',
'r1_k3.5.7_a1_p1.1_... | def get_mixnet_small(depth_multiplier=None):
| blocks_args = [
'r1_k3_a1_p1_s11_e1_i16_o16',
'r1_k3_a1.1_p1.1_s22_e6_i16_o24',
'r1_k3_a1.1_p1.1_s11_e3_i24_o24',
'r1_k3.5.7_a1_p1_s22_e6_i24_o40_se0.5_sw',
'r3_k3.5_a1.1_p1.1_s11_e6_i40_o40_se0.5_sw',
'r1_k3.5.7_a1_p1.1_s22_e6_i40_o80_se0.25_sw',
'r2_k3.5_a... | - X is replaced by a any number ranging from 0-9
- {} encapsulates optional arguments
To deserialize an encoded block string, use
the class method :
```python
BlockArgs.from_block_string(block_string)
```
Returns:
BlockArgs object initialized with ... | 105 | 105 | 353 | 9 | 95 | shenhao2954988368/keras_mixnets | keras_mixnets/config.py | Python | get_mixnet_small | get_mixnet_small | 156 | 177 | 156 | 156 | d47ff8919e0d7151d48542055ea215b94fd95070 | bigcode/the-stack | train |
6d6457007e13dd22bfefd5e5 | train | class | class BlockArgs(object):
def __init__(self, input_filters=None,
output_filters=None,
dw_kernel_size=None,
expand_kernel_size=None,
project_kernel_size=None,
strides=None,
num_repeat=None,
se_ratio... | class BlockArgs(object):
| def __init__(self, input_filters=None,
output_filters=None,
dw_kernel_size=None,
expand_kernel_size=None,
project_kernel_size=None,
strides=None,
num_repeat=None,
se_ratio=None,
ex... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 203 | 256 | 988 | 5 | 197 | shenhao2954988368/keras_mixnets | keras_mixnets/config.py | Python | BlockArgs | BlockArgs | 24 | 152 | 24 | 25 | 9513dd32edfb5c0e4f2fd3e3baa29ce24a4a872c | bigcode/the-stack | train |
82e56ddccfa3595b6e1d9845 | train | function | def get_mixnet_large(depth_multiplier=None):
return get_mixnet_medium(depth_multiplier)
| def get_mixnet_large(depth_multiplier=None):
| return get_mixnet_medium(depth_multiplier)
| 3.5.7.9_a1_p1.1_s11_e6_i200_o200_se0.5_sw',
]
DEFAULT_BLOCK_LIST = [BlockArgs.from_block_string(s)
for s in blocks_args]
return DEFAULT_BLOCK_LIST
def get_mixnet_large(depth_multiplier=None):
| 64 | 64 | 18 | 9 | 54 | shenhao2954988368/keras_mixnets | keras_mixnets/config.py | Python | get_mixnet_large | get_mixnet_large | 205 | 206 | 205 | 205 | a7d505a998b80bf43edd774b3c747cc926673bed | bigcode/the-stack | train |
4c4a26591a821785e8d2319b | train | function | def get_mixnet_medium(depth_multiplier=None):
blocks_args = [
'r1_k3_a1_p1_s11_e1_i24_o24',
'r1_k3.5.7_a1.1_p1.1_s22_e6_i24_o32',
'r1_k3_a1.1_p1.1_s11_e3_i32_o32',
'r1_k3.5.7.9_a1_p1_s22_e6_i32_o40_se0.5_sw',
'r3_k3.5_a1.1_p1.1_s11_e6_i40_o40_se0.5_sw',
'r1_k3.5.7_a... | def get_mixnet_medium(depth_multiplier=None):
| blocks_args = [
'r1_k3_a1_p1_s11_e1_i24_o24',
'r1_k3.5.7_a1.1_p1.1_s22_e6_i24_o32',
'r1_k3_a1.1_p1.1_s11_e3_i32_o32',
'r1_k3.5.7.9_a1_p1_s22_e6_i32_o40_se0.5_sw',
'r3_k3.5_a1.1_p1.1_s11_e6_i40_o40_se0.5_sw',
'r1_k3.5.7_a1_p1_s22_e6_i40_o80_se0.25_sw',
'r3_k3... | .5_sw',
'r1_k3.5.7.9.11_a1_p1_s22_e6_i120_o200_se0.5_sw',
'r2_k3.5.7.9_a1_p1.1_s11_e6_i200_o200_se0.5_sw',
]
DEFAULT_BLOCK_LIST = [BlockArgs.from_block_string(s)
for s in blocks_args]
return DEFAULT_BLOCK_LIST
def get_mixnet_medium(depth_multiplier=None):
| 105 | 105 | 353 | 9 | 95 | shenhao2954988368/keras_mixnets | keras_mixnets/config.py | Python | get_mixnet_medium | get_mixnet_medium | 180 | 202 | 180 | 180 | 723876c3722ff9f1aec6be6c25460a8e4c88a32a | bigcode/the-stack | train |
c1e4175fb05bdffcf63f5d39 | train | function | def VacuumMaxwellRHSs_rescaled():
global erhsU, arhsU, psi_rhs, Gamma_rhs, C, G, EU_Cart, AU_Cart
#Step 0: Set the spatial dimension parameter to 3.
par.set_parval_from_str("grid::DIM", 3)
DIM = par.parval_from_str("grid::DIM")
# Set reference metric related quantities
rfm.reference_metric()
... | def VacuumMaxwellRHSs_rescaled():
| global erhsU, arhsU, psi_rhs, Gamma_rhs, C, G, EU_Cart, AU_Cart
#Step 0: Set the spatial dimension parameter to 3.
par.set_parval_from_str("grid::DIM", 3)
DIM = par.parval_from_str("grid::DIM")
# Set reference metric related quantities
rfm.reference_metric()
# Register gridfunctions that ... | # Import needed core NRPy+ modules
import grid as gri # NRPy+: Functions having to do with numerical grids
import NRPy_param_funcs as par # NRPy+: Parameter interface
import reference_metric as rfm # NRPy+: Reference metric support
import sympy as sp # SymPy: The Python computer algebra ... | 143 | 256 | 2,261 | 10 | 133 | Harmohit-Singh/nrpytutorial | Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled.py | Python | VacuumMaxwellRHSs_rescaled | VacuumMaxwellRHSs_rescaled | 11 | 196 | 11 | 11 | ce5de76be62bffbb33d58b3a1b5a5d004bdd9eca | bigcode/the-stack | train |
6ff7373452c6cda4d2146659 | train | function | def checkout_branch(git, remote_exists, branch):
if remote_exists:
print("Checking out branch '%s'" % branch)
git.stash("--include-untracked")
git.checkout(branch)
try:
git.stash("pop")
except BaseException:
git.checkout("--theirs", ".")
gi... | def checkout_branch(git, remote_exists, branch):
| if remote_exists:
print("Checking out branch '%s'" % branch)
git.stash("--include-untracked")
git.checkout(branch)
try:
git.stash("pop")
except BaseException:
git.checkout("--theirs", ".")
git.reset()
else:
print("Creating new b... | % name)
def set_git_remote_url(git, token, github_repository):
git.remote(
"set-url",
"origin",
"https://x-access-token:%s@github.com/%s" % (token, github_repository),
)
def checkout_branch(git, remote_exists, branch):
| 64 | 64 | 95 | 11 | 53 | Singwai/create-pull-request | src/create-pull-request.py | Python | checkout_branch | checkout_branch | 61 | 73 | 61 | 61 | f795f02c2eec95048718beb2fc25e544b3b296f3 | bigcode/the-stack | train |
fe6a435ea16fb8813b151529 | train | function | def get_github_event(github_event_path):
with open(github_event_path) as f:
github_event = json.load(f)
if bool(os.environ.get("DEBUG_EVENT")):
print(os.environ["GITHUB_EVENT_NAME"])
print(json.dumps(github_event, sort_keys=True, indent=2))
return github_event
| def get_github_event(github_event_path):
| with open(github_event_path) as f:
github_event = json.load(f)
if bool(os.environ.get("DEBUG_EVENT")):
print(os.environ["GITHUB_EVENT_NAME"])
print(json.dumps(github_event, sort_keys=True, indent=2))
return github_event
| #!/usr/bin/env python3
""" Create Pull Request """
import json
import os
import random
import string
import sys
import time
from git import Repo
from github import Github, GithubException
def get_github_event(github_event_path):
| 53 | 64 | 71 | 10 | 42 | Singwai/create-pull-request | src/create-pull-request.py | Python | get_github_event | get_github_event | 13 | 19 | 13 | 13 | cd7847fa5712aca79a27cd5c77a9f2b7feea1402 | bigcode/the-stack | train |
a9ad94fbeab09c30397f5936 | train | function | def get_author_default(event_name, event_data):
if event_name == "push":
email = "{head_commit[author][email]}".format(**event_data)
name = "{head_commit[author][name]}".format(**event_data)
else:
email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com"
name = os.environ[... | def get_author_default(event_name, event_data):
| if event_name == "push":
email = "{head_commit[author][email]}".format(**event_data)
name = "{head_commit[author][name]}".format(**event_data)
else:
email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com"
name = os.environ["GITHUB_ACTOR"]
return email, name
| ):
return "".join(random.choice(chars) for _ in range(size))
def remote_branch_exists(repo, branch):
for ref in repo.remotes.origin.refs:
if ref.name == ("origin/%s" % branch):
return True
return False
def get_author_default(event_name, event_data):
| 64 | 64 | 92 | 10 | 53 | Singwai/create-pull-request | src/create-pull-request.py | Python | get_author_default | get_author_default | 37 | 44 | 37 | 37 | 35165ce3dd744b9f148851f0f099a252aaf5767e | bigcode/the-stack | train |
e6c7970520852f1ebddb1fc7 | train | function | def cs_string_to_list(str):
# Split the comma separated string into a list
l = [i.strip() for i in str.split(",")]
# Remove empty strings
return list(filter(None, l))
| def cs_string_to_list(str):
# Split the comma separated string into a list
| l = [i.strip() for i in str.split(",")]
# Remove empty strings
return list(filter(None, l))
| b=branch)
def push_changes(git, branch, commit_message):
git.add("-A")
git.commit(m=commit_message)
return git.push("-f", "--set-upstream", "origin", branch)
def cs_string_to_list(str):
# Split the comma separated string into a list
| 64 | 64 | 46 | 18 | 46 | Singwai/create-pull-request | src/create-pull-request.py | Python | cs_string_to_list | cs_string_to_list | 82 | 86 | 82 | 83 | e289298c71ccc523fb043cc1fefe8bac24366222 | bigcode/the-stack | train |
92bd9c65a446e8259c998c4e | train | function | def get_head_short_sha1(repo):
return repo.git.rev_parse("--short", "HEAD")
| def get_head_short_sha1(repo):
| return repo.git.rev_parse("--short", "HEAD")
| _event_path) as f:
github_event = json.load(f)
if bool(os.environ.get("DEBUG_EVENT")):
print(os.environ["GITHUB_EVENT_NAME"])
print(json.dumps(github_event, sort_keys=True, indent=2))
return github_event
def get_head_short_sha1(repo):
| 64 | 64 | 20 | 8 | 55 | Singwai/create-pull-request | src/create-pull-request.py | Python | get_head_short_sha1 | get_head_short_sha1 | 22 | 23 | 22 | 22 | 1841285aa9753bba2486d55c12992040cff583e7 | bigcode/the-stack | train |
903f1be54dc6c0125a391ee1 | train | function | def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
| def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
| return "".join(random.choice(chars) for _ in range(size))
| _EVENT_NAME"])
print(json.dumps(github_event, sort_keys=True, indent=2))
return github_event
def get_head_short_sha1(repo):
return repo.git.rev_parse("--short", "HEAD")
def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
| 64 | 64 | 34 | 20 | 44 | Singwai/create-pull-request | src/create-pull-request.py | Python | get_random_suffix | get_random_suffix | 26 | 27 | 26 | 26 | cd0d429689cc23a68fbef2881c4251aa5e501eb1 | bigcode/the-stack | train |
1426ee0872a2e962aafea765 | train | function | def set_git_remote_url(git, token, github_repository):
git.remote(
"set-url",
"origin",
"https://x-access-token:%s@github.com/%s" % (token, github_repository),
)
| def set_git_remote_url(git, token, github_repository):
| git.remote(
"set-url",
"origin",
"https://x-access-token:%s@github.com/%s" % (token, github_repository),
)
| Configuring git user as '%s <%s>'" % (name, email))
git.config("--global", "user.email", '"%s"' % email)
git.config("--global", "user.name", '"%s"' % name)
def set_git_remote_url(git, token, github_repository):
| 64 | 64 | 50 | 13 | 51 | Singwai/create-pull-request | src/create-pull-request.py | Python | set_git_remote_url | set_git_remote_url | 53 | 58 | 53 | 53 | da38036b404fb5f5745974f48f31ca83010c97c3 | bigcode/the-stack | train |
786a1ae4445e7558c77321f0 | train | function | def create_project_card(github_repo, project_name, project_column_name, pull_request):
# Locate the project by name
project = None
for project_item in github_repo.get_projects("all"):
if project_item.name == project_name:
project = project_item
break
if not project:
... | def create_project_card(github_repo, project_name, project_column_name, pull_request):
# Locate the project by name
| project = None
for project_item in github_repo.get_projects("all"):
if project_item.name == project_name:
project = project_item
break
if not project:
print("::warning::Project not found. Unable to create project card.")
return
# Locate the column by nam... | # Split the comma separated string into a list
l = [i.strip() for i in str.split(",")]
# Remove empty strings
return list(filter(None, l))
def create_project_card(github_repo, project_name, project_column_name, pull_request):
# Locate the project by name
| 64 | 64 | 214 | 26 | 38 | Singwai/create-pull-request | src/create-pull-request.py | Python | create_project_card | create_project_card | 89 | 117 | 89 | 90 | f3bf1e3323a4b7f76d02b378f0545c92c2fb0f99 | bigcode/the-stack | train |
421d96ca244a1e500bdc2f81 | train | function | def push_changes(git, branch, commit_message):
git.add("-A")
git.commit(m=commit_message)
return git.push("-f", "--set-upstream", "origin", branch)
| def push_changes(git, branch, commit_message):
| git.add("-A")
git.commit(m=commit_message)
return git.push("-f", "--set-upstream", "origin", branch)
| try:
git.stash("pop")
except BaseException:
git.checkout("--theirs", ".")
git.reset()
else:
print("Creating new branch '%s'" % branch)
git.checkout("HEAD", b=branch)
def push_changes(git, branch, commit_message):
| 64 | 64 | 42 | 11 | 53 | Singwai/create-pull-request | src/create-pull-request.py | Python | push_changes | push_changes | 76 | 79 | 76 | 76 | 06b9475a5f0b212814806ea5b89df5b010c61a5e | bigcode/the-stack | train |
21a788acc3cb62ae24ee35af | train | function | def remote_branch_exists(repo, branch):
for ref in repo.remotes.origin.refs:
if ref.name == ("origin/%s" % branch):
return True
return False
| def remote_branch_exists(repo, branch):
| for ref in repo.remotes.origin.refs:
if ref.name == ("origin/%s" % branch):
return True
return False
| _event
def get_head_short_sha1(repo):
return repo.git.rev_parse("--short", "HEAD")
def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
def remote_branch_exists(repo, branch):
| 64 | 64 | 39 | 8 | 56 | Singwai/create-pull-request | src/create-pull-request.py | Python | remote_branch_exists | remote_branch_exists | 30 | 34 | 30 | 30 | d266dd26fcde0be5ad1ed01ae97ac6e35c5d4622 | bigcode/the-stack | train |
4c4e6ddac9c433ff98d4de47 | train | function | def process_event(github_token, github_repository, repo, branch, base):
# Fetch optional environment variables with default values
commit_message = os.getenv(
"COMMIT_MESSAGE", "Auto-committed changes by create-pull-request action"
)
title = os.getenv(
"PULL_REQUEST_TITLE", "Auto-generat... | def process_event(github_token, github_repository, repo, branch, base):
# Fetch optional environment variables with default values
| commit_message = os.getenv(
"COMMIT_MESSAGE", "Auto-committed changes by create-pull-request action"
)
title = os.getenv(
"PULL_REQUEST_TITLE", "Auto-generated by create-pull-request action"
)
body = os.getenv(
"PULL_REQUEST_BODY",
"Auto-generated pull request by "
... | (",")]
# Remove empty strings
return list(filter(None, l))
def create_project_card(github_repo, project_name, project_column_name, pull_request):
# Locate the project by name
project = None
for project_item in github_repo.get_projects("all"):
if project_item.name == project_name:
... | 256 | 256 | 980 | 26 | 230 | Singwai/create-pull-request | src/create-pull-request.py | Python | process_event | process_event | 120 | 221 | 120 | 121 | 119820db7760197278d612ce24bac41b8f8d5cce | bigcode/the-stack | train |
15b2c68d8af913745b3190a2 | train | function | def set_git_config(git, email, name):
print("Configuring git user as '%s <%s>'" % (name, email))
git.config("--global", "user.email", '"%s"' % email)
git.config("--global", "user.name", '"%s"' % name)
| def set_git_config(git, email, name):
| print("Configuring git user as '%s <%s>'" % (name, email))
git.config("--global", "user.email", '"%s"' % email)
git.config("--global", "user.name", '"%s"' % name)
| head_commit[author][name]}".format(**event_data)
else:
email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com"
name = os.environ["GITHUB_ACTOR"]
return email, name
def set_git_config(git, email, name):
| 64 | 64 | 65 | 11 | 52 | Singwai/create-pull-request | src/create-pull-request.py | Python | set_git_config | set_git_config | 47 | 50 | 47 | 47 | 2a372ceb50489354981d69e06b84d44889f056fb | bigcode/the-stack | train |
faabae3065d809fde5d86e8a | train | class | class TGenImpl():
def __init__(self, fun, name, arg_count, datatypes_list, feat_constraints_list, tgraph, apply_all, col_names, col_dtypes, col_as_json_objects):
self._hyperparams = {
'fun': fun,
'name': name,
'arg_count': arg_count,
'datatypes_list': datatype... | class TGenImpl():
| def __init__(self, fun, name, arg_count, datatypes_list, feat_constraints_list, tgraph, apply_all, col_names, col_dtypes, col_as_json_objects):
self._hyperparams = {
'fun': fun,
'name': name,
'arg_count': arg_count,
'datatypes_list': datatypes_list,
... | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import autoai_libs.cognito.transforms.transform_utils
import lale.datasets.data_schemas
import lale.docstrings
import lale.helpers
import lale.operato... | 71 | 71 | 238 | 5 | 65 | ariffyasri/lale | lale/lib/autoai_libs/tgen.py | Python | TGenImpl | TGenImpl | 21 | 44 | 21 | 21 | cb0646a60d7b5dccd9ce684db9ac89895778f0fc | bigcode/the-stack | train |
a802e3e832fc26b9f3162895 | train | class | class JSONObjectField(models.Field):
"""Represents a JSON object.
Note: This might be missing a lot of Django infrastructure to
work correctly across edge cases. Also it was tested with MySQL
and no other db backends.
"""
empty_strings_allowed = False
description = _lazy(u'JSON Object')
... | class JSONObjectField(models.Field):
| """Represents a JSON object.
Note: This might be missing a lot of Django infrastructure to
work correctly across edge cases. Also it was tested with MySQL
and no other db backends.
"""
empty_strings_allowed = False
description = _lazy(u'JSON Object')
__metaclass__ = models.SubfieldBas... | .validators.append(EnhancedURLValidator())
def formfield(self, **kwargs):
defaults = {
'form_class': forms.EnhancedURLField,
}
defaults.update(kwargs)
return super(EnhancedURLField, self).formfield(**defaults)
def deconstruct(self):
name, path, args, kwargs ... | 141 | 141 | 472 | 6 | 134 | DESHRAJ/fjord | fjord/base/models.py | Python | JSONObjectField | JSONObjectField | 47 | 115 | 47 | 47 | e6868cb274094f6b083cc1d681731ae56636cc16 | bigcode/the-stack | train |
6424ab3b18a821449111fe45 | train | class | class EnhancedURLField(models.CharField):
"""URLField that also supports about: and chrome:// urls"""
description = 'Enhanced URL'
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
models.CharField.__init__(self, verbose_name, n... | class EnhancedURLField(models.CharField):
| """URLField that also supports about: and chrome:// urls"""
description = 'Enhanced URL'
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
models.CharField.__init__(self, verbose_name, name, **kwargs)
self.validators.app... | _lazy
from fjord.base import forms
from fjord.base.validators import EnhancedURLValidator
# Common base model for all fjord models
ModelBase = models.Model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class EnhancedURLField(models.CharField):
| 64 | 64 | 216 | 8 | 56 | DESHRAJ/fjord | fjord/base/models.py | Python | EnhancedURLField | EnhancedURLField | 20 | 44 | 20 | 20 | 9a3da56f58f5b3f620a3af9998944de4af654158 | bigcode/the-stack | train |
2f1467ac4be2edc9c266e1cb | train | class | class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
| class Profile(models.Model):
| user = models.OneToOneField(User, on_delete=models.CASCADE)
| json
from django.contrib.auth.models import User
from django.db import models
from tower import ugettext_lazy as _lazy
from fjord.base import forms
from fjord.base.validators import EnhancedURLValidator
# Common base model for all fjord models
ModelBase = models.Model
class Profile(models.Model):
| 64 | 64 | 20 | 5 | 58 | DESHRAJ/fjord | fjord/base/models.py | Python | Profile | Profile | 16 | 17 | 16 | 16 | 580459dc0b4e6543680808174b634ed8938a59de | bigcode/the-stack | train |
541f105f815b354d1c1c69da | train | class | class SimplePhantom:
def __init__(self):
# Create simple 40 cm cube water phantom in global coords
self.positions = np.mgrid[-20:20:41j, -20:20:41j, -40:0:41j]
_, xlen, ylen, zlen = self.positions.shape
self.densities = np.ones((xlen, ylen, zlen)) # Water
| class SimplePhantom:
| def __init__(self):
# Create simple 40 cm cube water phantom in global coords
self.positions = np.mgrid[-20:20:41j, -20:20:41j, -40:0:41j]
_, xlen, ylen, zlen = self.positions.shape
self.densities = np.ones((xlen, ylen, zlen)) # Water
| import numpy as np
class SimplePhantom:
| 10 | 64 | 94 | 5 | 4 | samuelpeet/conehead | conehead/phantom.py | Python | SimplePhantom | SimplePhantom | 4 | 10 | 4 | 5 | 1d6f1729d64168307db26d5ecbb281bc069ba771 | bigcode/the-stack | train |
212616d493f3670824725fb2 | train | function | @register.filter(name="get_value_from_dict")
def get_value_from_dict(dict_variable, dict_key):
return dict_variable[dict_key]
| @register.filter(name="get_value_from_dict")
def get_value_from_dict(dict_variable, dict_key):
| return dict_variable[dict_key]
| any template
from django import template
from wevote_functions import functions
register = template.Library()
@register.filter(name="convert_to_int")
def convert_to_int(value):
return functions.convert_to_int(value)
@register.filter(name="get_value_from_dict")
def get_value_from_dict(dict_variable, dict_key):
| 64 | 64 | 29 | 21 | 43 | mattare2/WeVoteServer | apis_v1/templatetags/template_filters.py | Python | get_value_from_dict | get_value_from_dict | 18 | 20 | 18 | 19 | 905f9c7dd2c3ee1541e1743be7c6b3024a9f954c | bigcode/the-stack | train |
4c22a8211542bea10363bfb1 | train | function | @register.filter(name="convert_to_int")
def convert_to_int(value):
return functions.convert_to_int(value)
| @register.filter(name="convert_to_int")
def convert_to_int(value):
| return functions.convert_to_int(value)
| Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
# Note: These template_filters can be used in any template
from django import template
from wevote_functions import functions
register = template.Library()
@register.filter(name="convert_to_int")
def convert_to_int(value):
| 64 | 64 | 23 | 15 | 49 | mattare2/WeVoteServer | apis_v1/templatetags/template_filters.py | Python | convert_to_int | convert_to_int | 13 | 15 | 13 | 14 | 5c6ec113fc68c09d7be4f774ed342ad86d628ff3 | bigcode/the-stack | train |
5227167242d4c8f97b1ffb4b | train | function | @pytest.mark.parametrize(("num_in", "num_out"), num_in_out_args.values(), ids=num_in_out_args.keys())
def test_i2s_basic_master(build, capfd, nightly, request, num_in, num_out):
test_level = "nightly" if nightly else "smoke"
id_string = f"{test_level}_{num_in}_{num_out}"
cwd = Path(request.fspath).parent
... | @pytest.mark.parametrize(("num_in", "num_out"), num_in_out_args.values(), ids=num_in_out_args.keys())
def test_i2s_basic_master(build, capfd, nightly, request, num_in, num_out):
| test_level = "nightly" if nightly else "smoke"
id_string = f"{test_level}_{num_in}_{num_out}"
cwd = Path(request.fspath).parent
binary = f'{cwd}/i2s_master_test/bin/{id_string}/i2s_master_test_{id_string}.xe'
clk = Clock("tile[0]:XS1_PORT_1A")
checker = I2SMasterChecker(
"tile[0]:XS1_P... | from pathlib import Path
import Pyxsim as px
import pytest
num_in_out_args = {"4ch_in,4ch_out": (4, 4),
"1ch_in,1ch_out": (1, 1),
"4ch_in,0ch_out": (4, 0),
"0ch_in,4ch_out": (0, 4)}
@pytest.mark.parametrize(("num_in", "num_out"), num_in_out_args.values(), ids=nu... | 129 | 129 | 430 | 46 | 83 | danielpieczko/xcore_sdk | test/hil/lib_i2s/test_i2s_basic_master.py | Python | test_i2s_basic_master | test_i2s_basic_master | 13 | 45 | 13 | 14 | 77c350b7250080696edfa25d89941a968a6003f7 | bigcode/the-stack | train |
a1e136a2e5b2d01d66c19e4c | train | class | class TamariIntervalPosets_all(DisjointUnionEnumeratedSets, TamariIntervalPosets):
r"""
The enumerated set of all Tamari interval-posets.
"""
def __init__(self):
r"""
TESTS::
sage: from sage.combinat.interval_posets import TamariIntervalPosets_all
sage: S = Tamar... | class TamariIntervalPosets_all(DisjointUnionEnumeratedSets, TamariIntervalPosets):
| r"""
The enumerated set of all Tamari interval-posets.
"""
def __init__(self):
r"""
TESTS::
sage: from sage.combinat.interval_posets import TamariIntervalPosets_all
sage: S = TamariIntervalPosets_all()
sage: S.cardinality()
+Infinity
... | 1 = TamariIntervalPoset(4,[(1,2),(2,3),(4,3)])
sage: ip2 = TamariIntervalPoset(4,[(1,2),(2,3)])
sage: TamariIntervalPosets().le(ip1,ip2)
False
sage: TamariIntervalPosets().le(ip2,ip1)
True
"""
cc1 = el1.cubical_coordinates()
cc2 = el2.c... | 167 | 168 | 563 | 21 | 146 | fchapoton/sage | src/sage/combinat/interval_posets.py | Python | TamariIntervalPosets_all | TamariIntervalPosets_all | 3,539 | 3,617 | 3,539 | 3,539 | b2b07784935d80d4db810e09b57e4f43f1078646 | bigcode/the-stack | train |
3c1ed1841453284ea07115e4 | train | class | class TamariIntervalPosets_size(TamariIntervalPosets):
r"""
The enumerated set of interval-posets of a given size.
"""
def __init__(self, size):
r"""
TESTS::
sage: S = TamariIntervalPosets(3)
sage: assert S is TamariIntervalPosets(3)
sage: for i in ra... | class TamariIntervalPosets_size(TamariIntervalPosets):
| r"""
The enumerated set of interval-posets of a given size.
"""
def __init__(self, size):
r"""
TESTS::
sage: S = TamariIntervalPosets(3)
sage: assert S is TamariIntervalPosets(3)
sage: for i in range(5): TestSuite(TamariIntervalPosets(i)).run()
... | return "Interval-posets"
def one(self):
"""
Return the unit of the monoid.
This is the empty interval poset, of size 0.
EXAMPLES::
sage: TamariIntervalPosets().one()
The Tamari interval of size 0 induced by relations []
"""
return T... | 256 | 256 | 2,005 | 14 | 242 | fchapoton/sage | src/sage/combinat/interval_posets.py | Python | TamariIntervalPosets_size | TamariIntervalPosets_size | 3,623 | 3,825 | 3,623 | 3,623 | 158b7eda454c6b0d77ee1d9e361818eb1fc58622 | bigcode/the-stack | train |
944108b5ef69752e63b97180 | train | class | @add_metaclass(InheritComparisonClasscallMetaclass)
class TamariIntervalPoset(Element):
r"""
The class of Tamari interval-posets.
An interval-poset is a labelled poset of size `n`, with labels
`1, 2, \ldots, n`, satisfying the following conditions:
- if `a < c` (as integers) and `a` precedes `c` i... | @add_metaclass(InheritComparisonClasscallMetaclass)
class TamariIntervalPoset(Element):
| r"""
The class of Tamari interval-posets.
An interval-poset is a labelled poset of size `n`, with labels
`1, 2, \ldots, n`, satisfying the following conditions:
- if `a < c` (as integers) and `a` precedes `c` in the poset, then,
for all `b` such that `a < b < c`, `b` precedes `c`,
- if ... | ets.posets import Poset, FinitePoset
from sage.categories.finite_posets import FinitePosets
from sage.combinat.binary_tree import BinaryTrees
from sage.combinat.binary_tree import LabelledBinaryTrees, LabelledBinaryTree
from sage.combinat.dyck_word import DyckWords
from sage.combinat.permutation import Permutation
from... | 256 | 256 | 26,380 | 20 | 235 | fchapoton/sage | src/sage/combinat/interval_posets.py | Python | TamariIntervalPoset | TamariIntervalPoset | 64 | 2,788 | 64 | 65 | 91bfcb88d1242cace5a23055cf163e125f6503da | bigcode/the-stack | train |
6d76f79f1eaebb7d23b8910d | train | class | class TamariIntervalPosets(UniqueRepresentation, Parent):
r"""
Factory for interval-posets.
INPUT:
- ``size`` -- (optional) an integer
OUTPUT:
- the set of all interval-posets (of the given ``size`` if specified)
EXAMPLES::
sage: TamariIntervalPosets()
Interval-posets
... | class TamariIntervalPosets(UniqueRepresentation, Parent):
| r"""
Factory for interval-posets.
INPUT:
- ``size`` -- (optional) an integer
OUTPUT:
- the set of all interval-posets (of the given ``size`` if specified)
EXAMPLES::
sage: TamariIntervalPosets()
Interval-posets
sage: TamariIntervalPosets(2)
Interval-pos... | (y)):
return False
return True
def is_indecomposable(self):
"""
Return whether ``self`` is an indecomposable Tamari interval.
This is the terminology of [Cha2008]_.
This means that the upper binary tree has an empty left subtree.
This condition is ... | 256 | 256 | 7,554 | 12 | 244 | fchapoton/sage | src/sage/combinat/interval_posets.py | Python | TamariIntervalPosets | TamariIntervalPosets | 2,792 | 3,532 | 2,792 | 2,792 | a717635eabb43ba6e46b704ddb6b48e0300f7d27 | bigcode/the-stack | train |
347be8ddbdac11b71489d3e5 | train | class | class CreateStreamForbiddenResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
""... | class CreateStreamForbiddenResponse(SdkResponse):
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class CreateStreamForbiddenResponse(SdkResponse):
| 39 | 127 | 426 | 10 | 28 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-live/huaweicloudsdklive/v1/model/create_stream_forbidden_response.py | Python | CreateStreamForbiddenResponse | CreateStreamForbiddenResponse | 12 | 81 | 12 | 14 | 82ea24ae97dcf5807830a79e1235bbd2849c3024 | bigcode/the-stack | train |
25b62ccc197dbf99e619a873 | train | class | class Embed_Author(API_Element):
"""
Represent a Embed Author
name:
Name of the author field
Max : 256 characters
url:
Url of the author field
icon_url:
Url of the icon of the author field
proxy_icon_url:
same than icon_url, but proxied
"""
def __init__(self,author):
self.name = author.get("name... | class Embed_Author(API_Element):
| """
Represent a Embed Author
name:
Name of the author field
Max : 256 characters
url:
Url of the author field
icon_url:
Url of the icon of the author field
proxy_icon_url:
same than icon_url, but proxied
"""
def __init__(self,author):
self.name = author.get("name")
self.url = author.get("url")
... | class Embed_Provider(API_Element):
"""
Represent a Embed Provider
name:
The provider name
url:
The provider url
"""
def __init__(self,provider):
self.name = provider.get("name")
self.url = provider.get("url")
class Embed_Author(API_Element):
| 64 | 64 | 123 | 7 | 57 | horus-4ever/Piscord | piscord/API_Elements2/embed.py | Python | Embed_Author | Embed_Author | 138 | 159 | 138 | 139 | 48d980354235271f74750db89cb5e18c5c5f2cf8 | bigcode/the-stack | train |
cd804c0045b862263645e53a | train | class | class Embed_Field(API_Element):
"""
Represent a Embed Field
name:
The title of the field
Max : 256 characters
value:
The description of the field
Max : 1024 characters
inline:
If the Embed is inline
"""
def __init__(self,field):
self.name = field.get("name")
self.value = field.get("value")
s... | class Embed_Field(API_Element):
| """
Represent a Embed Field
name:
The title of the field
Max : 256 characters
value:
The description of the field
Max : 1024 characters
inline:
If the Embed is inline
"""
def __init__(self,field):
self.name = field.get("name")
self.value = field.get("value")
self.inline = field.get("inline") | _url, but proxied
"""
def __init__(self,author):
self.name = author.get("name")
self.url = author.get("url")
self.icon_url = author.get("icon_url")
self.proxy_icon_url = author.get("proxy_icon_url")
class Embed_Field(API_Element):
| 64 | 64 | 93 | 6 | 58 | horus-4ever/Piscord | piscord/API_Elements2/embed.py | Python | Embed_Field | Embed_Field | 162 | 182 | 162 | 163 | 830ef542f7f4c735ad624c50384eaa452448633e | bigcode/the-stack | train |
29324b597e0009474cfd8137 | train | class | class Embed_Footer(API_Element):
"""
Represent the footer of an Embed
text:
The text of the footer
icon_url:
The url of the footer icon
proxy_icon_url:
Same than icon_url, but proxied
"""
def __init__(self,footer):
self.text = footer.get("text")
self.icon_url = footer.get("icon_url")
self.proxy_ic... | class Embed_Footer(API_Element):
| """
Represent the footer of an Embed
text:
The text of the footer
icon_url:
The url of the footer icon
proxy_icon_url:
Same than icon_url, but proxied
"""
def __init__(self,footer):
self.text = footer.get("text")
self.icon_url = footer.get("icon_url")
self.proxy_icon_url = footer.get("proxy_icon_ur... | ) for field in embed.get("fields",[])]
def add_field(self,**kwargs):
"""
Used to add a field on the Embed
Return the field
"""
self.fields.append(Embed_Field(kwargs))
return self.fields[-1]
class Embed_Footer(API_Element):
| 64 | 64 | 96 | 7 | 57 | horus-4ever/Piscord | piscord/API_Elements2/embed.py | Python | Embed_Footer | Embed_Footer | 81 | 97 | 81 | 82 | c6e7439ba2e6aa4c9934b1b57c5122a4071da433 | bigcode/the-stack | train |
4f8cf7da2539ed56f139d301 | train | class | class Embed_Image(API_Element):
"""
Represent a Embed Image, Embed Thumbnail and Embed Video
url:
The url of the image/video
proxy_url:
Same than url, but proxied. Video Dmbed does not have this attribute
height:
The height of the image
width:
The width of the image
"""
def __init__(self,image):
se... | class Embed_Image(API_Element):
| """
Represent a Embed Image, Embed Thumbnail and Embed Video
url:
The url of the image/video
proxy_url:
Same than url, but proxied. Video Dmbed does not have this attribute
height:
The height of the image
width:
The width of the image
"""
def __init__(self,image):
self.url = image.get("url")
self.... | xy_icon_url:
Same than icon_url, but proxied
"""
def __init__(self,footer):
self.text = footer.get("text")
self.icon_url = footer.get("icon_url")
self.proxy_icon_url = footer.get("proxy_icon_url")
class Embed_Image(API_Element):
| 64 | 64 | 119 | 6 | 58 | horus-4ever/Piscord | piscord/API_Elements2/embed.py | Python | Embed_Image | Embed_Image | 100 | 119 | 100 | 101 | 3a5e637b3630e8059c741227d5f3bbb55069ada8 | bigcode/the-stack | train |
408ce2ed857fb27bfffb2187 | train | class | class Embed_Provider(API_Element):
"""
Represent a Embed Provider
name:
The provider name
url:
The provider url
"""
def __init__(self,provider):
self.name = provider.get("name")
self.url = provider.get("url")
| class Embed_Provider(API_Element):
| """
Represent a Embed Provider
name:
The provider name
url:
The provider url
"""
def __init__(self,provider):
self.name = provider.get("name")
self.url = provider.get("url")
|
width:
The width of the image
"""
def __init__(self,image):
self.url = image.get("url")
self.proxy_url = image.get("proxy_url")
self.height = image.get("height")
self.width = image.get("width")
class Embed_Provider(API_Element):
| 64 | 64 | 57 | 7 | 57 | horus-4ever/Piscord | piscord/API_Elements2/embed.py | Python | Embed_Provider | Embed_Provider | 122 | 135 | 122 | 123 | 339b00124a004089bd00c1aac8d6ea2e83a72428 | bigcode/the-stack | train |
f17abc30399aee481ecb62a4 | train | class | class Embed(API_Element):
"""
Represent a message Embed
Params when you send a Embed:
https://discord.com/developers/docs/resources/channel#create-message-params
title:
The title of the embed
Max : 256 characters
type:
Type of embed
Embed types should be considered deprecated and might be removed
... | class Embed(API_Element):
| """
Represent a message Embed
Params when you send a Embed:
https://discord.com/developers/docs/resources/channel#create-message-params
title:
The title of the embed
Max : 256 characters
type:
Type of embed
Embed types should be considered deprecated and might be removed
- "rich" : Generic Embed
... | from .utilities import API_Element
class Embed(API_Element):
| 12 | 155 | 517 | 5 | 6 | horus-4ever/Piscord | piscord/API_Elements2/embed.py | Python | Embed | Embed | 3 | 78 | 3 | 4 | f04e4fc1a3e496e894a2bad27004d9bbaac444c7 | bigcode/the-stack | train |
31eddc5c182a62576590d40e | train | class | class RoleResource(Resource):
"""Role Resource
This resource represents a role associated with a client.
"""
def __init__(self):
self.role_schema = RoleSchema()
self.roles_schema = RoleSchema(many=True)
self.response_handler = ResponseBody()
@require_oauth()
def get(s... | class RoleResource(Resource):
| """Role Resource
This resource represents a role associated with a client.
"""
def __init__(self):
self.role_schema = RoleSchema()
self.roles_schema = RoleSchema(many=True)
self.response_handler = ResponseBody()
@require_oauth()
def get(self, id: str = None):
... | """Role API
An API for registering roles with Auth Server.
"""
from uuid import uuid4
from datetime import datetime
from flask import Blueprint
from flask_restful import Resource, Api, request
from werkzeug.security import gen_salt
from authserver.db import db, Role, RoleSchema, AuthorizedScope, AuthorizedScopeSchem... | 89 | 250 | 835 | 5 | 83 | brighthive/authserver | authserver/api/role.py | Python | RoleResource | RoleResource | 16 | 127 | 16 | 16 | de6df08bf2f6e31fd46bf3bb750fddab1a1c10a1 | bigcode/the-stack | train |
4031f4603c5c329bfe582180 | train | class | class AuthorizedScopeResource(Resource):
"""Authorized scope resource for linking roles to scopes.
This resource enables the notion of an OAuth2 scope to be shared between user roles and
OAuth2 clients. This way, the capabilities of specific clients can be restricted to the
scopes associated with a use... | class AuthorizedScopeResource(Resource):
| """Authorized scope resource for linking roles to scopes.
This resource enables the notion of an OAuth2 scope to be shared between user roles and
OAuth2 clients. This way, the capabilities of specific clients can be restricted to the
scopes associated with a user's role.
"""
def __init__(self... | and PATCH differ by a single parameter. This method abstracts that logic
and allows for switching the Marshmallow validation to partial for PATCH and complete for PUT.
"""
try:
request_data = request.get_json(force=True)
except Exception as e:
return self.respon... | 229 | 229 | 765 | 6 | 223 | brighthive/authserver | authserver/api/role.py | Python | AuthorizedScopeResource | AuthorizedScopeResource | 130 | 216 | 130 | 130 | ca4d96c722af3c2b23c235b8898dbe88fc8a6e0c | bigcode/the-stack | train |
224e561048689f996a9ae653 | train | function | def interact(s, command):
s.send(bytes(command, 'utf-8'))
temporary = s.recv(20480).decode()
if "ERROR" not in temporary:
victimpath = s.recv(20480).decode()
if "ERROR" not in victimpath:
breakit = False
while not breakit:
msg = input(victimpath)
... | def interact(s, command):
| s.send(bytes(command, 'utf-8'))
temporary = s.recv(20480).decode()
if "ERROR" not in temporary:
victimpath = s.recv(20480).decode()
if "ERROR" not in victimpath:
breakit = False
while not breakit:
msg = input(victimpath)
allofem = re.sp... |
else:
print(temp)
elif command == "":
print("[CONTROLLER] Nothing to be sent...\n")
else:
s.send(bytes(command, 'utf-8'))
print(s.recv(20480).decode())
return breakit, victimpath
def interact(s, command):
| 64 | 64 | 166 | 6 | 57 | fossabot/ShellBot | controller.py | Python | interact | interact | 143 | 161 | 143 | 143 | cd8273c19dce206cf78ca2b2841448e991654c4e | bigcode/the-stack | train |
66804269ec061d7c2efe41b6 | train | function | def recv_msg(sock):
while True:
data = sock.recv(20480).decode()
if data == 'stop':
sys.stdout.write("[Controller] - 'rawexec' finished\n")
return
sys.stdout.write(data)
| def recv_msg(sock):
| while True:
data = sock.recv(20480).decode()
if data == 'stop':
sys.stdout.write("[Controller] - 'rawexec' finished\n")
return
sys.stdout.write(data)
| .example.com:587:user@example.com:abcdefghi:4:6
"""
# Helper Functions
def send_msg(sock, sem):
while True:
data = sys.stdin.readline()
if sem.acquire(False):
return
sock.send(bytes(data, 'utf-8'))
def recv_msg(sock):
| 63 | 64 | 51 | 5 | 58 | fossabot/ShellBot | controller.py | Python | recv_msg | recv_msg | 95 | 101 | 95 | 95 | 31a747d0e06ca0b204f392a17105e12524812e44 | bigcode/the-stack | train |
df551148a74b78f330739257 | train | function | def process(s, command):
victimpath = ''
breakit = False
if command == "stop":
s.send(bytes("stop", 'utf-8'))
print("\n")
breakit = True
elif "rawexec" in command:
rawexec(s, command)
elif "cd " in command:
s.send(bytes(command, 'utf-8'))
temp = s.recv... | def process(s, command):
| victimpath = ''
breakit = False
if command == "stop":
s.send(bytes("stop", 'utf-8'))
print("\n")
breakit = True
elif "rawexec" in command:
rawexec(s, command)
elif "cd " in command:
s.send(bytes(command, 'utf-8'))
temp = s.recv(20480).decode()
... | sem,))
recver = threading.Thread(target=recv_msg, args=(s,))
sender.daemon = True
recver.daemon = True
sender.start()
recver.start()
while threading.active_count() > 2:
pass
sem.release()
def process(s, command):
| 64 | 64 | 165 | 6 | 58 | fossabot/ShellBot | controller.py | Python | process | process | 119 | 140 | 119 | 119 | 82fd649e93ccb00555186d6c1516fe7d7b1ce19e | bigcode/the-stack | train |
a98e0023cdbda42fa36cf8a6 | train | function | def main():
print(about)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
except Exception:
sys.exit("[ERROR] Can't connect to server")
s.send(bytes(password, 'utf-8'))
run(s)
| def main():
| print(about)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
except Exception:
sys.exit("[ERROR] Can't connect to server")
s.send(bytes(password, 'utf-8'))
run(s)
| Interrupt:
try:
s.send(bytes("quit", 'utf-8'))
s.close()
except Exception:
pass
print("")
return
except Exception as ex:
print("[CONTROLLER] Connection Closed Due to Error:", ex)
s.close()
return
def main():
| 64 | 64 | 63 | 3 | 60 | fossabot/ShellBot | controller.py | Python | main | main | 210 | 219 | 210 | 210 | 12c703367c410fc9a2dee9e166886a14ab30e547 | bigcode/the-stack | train |
eb2986975f2ec76ba15d718b | train | function | def rawexec(s, command):
sem = threading.Semaphore()
sem.acquire(False)
s.send(bytes(command, 'utf-8'))
sender = threading.Thread(target=send_msg, args=(s, sem,))
recver = threading.Thread(target=recv_msg, args=(s,))
sender.daemon = True
recver.daemon = True
sender.start()
recver.sta... | def rawexec(s, command):
| sem = threading.Semaphore()
sem.acquire(False)
s.send(bytes(command, 'utf-8'))
sender = threading.Thread(target=send_msg, args=(s, sem,))
recver = threading.Thread(target=recv_msg, args=(s,))
sender.daemon = True
recver.daemon = True
sender.start()
recver.start()
while threading.... | 'utf-8'))
def recv_msg(sock):
while True:
data = sock.recv(20480).decode()
if data == 'stop':
sys.stdout.write("[Controller] - 'rawexec' finished\n")
return
sys.stdout.write(data)
def rawexec(s, command):
| 64 | 64 | 102 | 7 | 57 | fossabot/ShellBot | controller.py | Python | rawexec | rawexec | 104 | 116 | 104 | 104 | 433826db2dde7d8d25c5d07b2159c4b6b2dbb434 | bigcode/the-stack | train |
e13aae1406d5b23df883498c | train | function | def run(s):
try:
while True:
command = input("SB> ")
if command.strip() is '': pass
elif command == "refresh":
s.send(bytes("refresh", 'utf-8'))
print(s.recv(20480).decode())
elif command == "list":
s.send(bytes(... | def run(s):
| try:
while True:
command = input("SB> ")
if command.strip() is '': pass
elif command == "refresh":
s.send(bytes("refresh", 'utf-8'))
print(s.recv(20480).decode())
elif command == "list":
s.send(bytes("list", 'utf... | ictimpath)
allofem = re.split(''';(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', msg)
for onebyone in allofem:
breakit, path = process(s, onebyone)
if not path == '':
victimpath = path
else:
print(victimpath)
... | 94 | 94 | 315 | 4 | 90 | fossabot/ShellBot | controller.py | Python | run | run | 164 | 207 | 164 | 164 | 9ce7066901e0d5b60eb7cd25601bb7f798632836 | bigcode/the-stack | train |
b92ec9f729234e48980f29f2 | train | function | def send_msg(sock, sem):
while True:
data = sys.stdin.readline()
if sem.acquire(False):
return
sock.send(bytes(data, 'utf-8'))
| def send_msg(sock, sem):
| while True:
data = sys.stdin.readline()
if sem.acquire(False):
return
sock.send(bytes(data, 'utf-8'))
| :6:8
custombruteforce <address>:<port>:<email>:<keys>:<min>:<max>
Example: custombruteforce smtp.example.com:587:user@example.com:abcdefghi:4:6
"""
# Helper Functions
def send_msg(sock, sem):
| 64 | 64 | 38 | 7 | 56 | fossabot/ShellBot | controller.py | Python | send_msg | send_msg | 87 | 92 | 87 | 87 | 9dc0ce622be8e41e75f59e62fa1c29f68411be7f | bigcode/the-stack | train |
fb605697695071f766945978 | train | function | def max_sum(d):
res = d[0]
max_i = 0
max_j = 1
i = 0
j = 0
max_count = 0
for item in d:
max_count += item
j += 1
if max_count > res:
res = max_count
max_i, max_j = i, j
if max_count <= 0:
max_count = 0
i = j
... | def max_sum(d):
| res = d[0]
max_i = 0
max_j = 1
i = 0
j = 0
max_count = 0
for item in d:
max_count += item
j += 1
if max_count > res:
res = max_count
max_i, max_j = i, j
if max_count <= 0:
max_count = 0
i = j
return res, max... | def max_sum(d):
| 5 | 64 | 117 | 5 | 0 | keybrl/xdu-coursework | projects/g3h2-algorithm/practice2/4_max_sum.py | Python | max_sum | max_sum | 1 | 18 | 1 | 1 | 3d964124ac7647663d8f085d43ca2589c475e55c | bigcode/the-stack | train |
c2ce9018a0c994b7d8022d1c | train | function | def deps():
"""Pull in external dependencies needed by rules in this repo.
Pull in all dependencies needed to run rules in this
repository. This function assumes the repositories imported by the macro
'repositories' in //repositories:repositories.bzl have been imported
already.
"""
go_deps(... | def deps():
| """Pull in external dependencies needed by rules in this repo.
Pull in all dependencies needed to run rules in this
repository. This function assumes the repositories imported by the macro
'repositories' in //repositories:repositories.bzl have been imported
already.
"""
go_deps()
py_dep... | el, this file should cease
# to exist.
"""
Provides functions to pull all external package dependencies of this
repository.
"""
load(":go_repositories.bzl", "go_deps")
load(":images.bzl", "images")
load(":py_repositories.bzl", "py_deps")
def deps():
| 64 | 64 | 74 | 3 | 61 | muhammadharis/rules_docker | repositories/deps.bzl | Python | deps | deps | 26 | 36 | 26 | 26 | 4802dfa6cd4a9180601ad0538c136dd778df69ac | bigcode/the-stack | train |
5a4daac78c5ac53f70e4dc25 | train | class | class TestHandshake(TestPlayer):
name = "Handshake"
player = axelrod.Handshake
expected_classifier = {
'memory_depth': float('inf'),
'stochastic': False,
'makes_use_of': set(),
'long_run_time': False,
'inspects_source': False,
'manipulates_source': False,
... | class TestHandshake(TestPlayer):
| name = "Handshake"
player = axelrod.Handshake
expected_classifier = {
'memory_depth': float('inf'),
'stochastic': False,
'makes_use_of': set(),
'long_run_time': False,
'inspects_source': False,
'manipulates_source': False,
'manipulates_state': False
... | """Test for the Handshake strategy."""
import axelrod
from .test_player import TestPlayer
C, D = axelrod.Actions.C, axelrod.Actions.D
class TestHandshake(TestPlayer):
| 43 | 73 | 244 | 6 | 36 | mattshirtliffe/Axelrod | axelrod/tests/unit/test_handshake.py | Python | TestHandshake | TestHandshake | 10 | 34 | 10 | 11 | 31cbb842901c631c778f1a99dd85870c1ff61f9f | bigcode/the-stack | train |
8c7ed4e70933b5e28b5d01fc | train | class | class TestOrder(base.TestCase):
def test_basic(self):
sot = order.Order()
self.assertIsNone(sot.resource_key)
self.assertEqual('orders', sot.resources_key)
self.assertEqual('/orders', sot.base_path)
self.assertTrue(sot.allow_create)
self.assertTrue(sot.allow_fetch)
... | class TestOrder(base.TestCase):
| def test_basic(self):
sot = order.Order()
self.assertIsNone(sot.resource_key)
self.assertEqual('orders', sot.resources_key)
self.assertEqual('/orders', sot.base_path)
self.assertTrue(sot.allow_create)
self.assertTrue(sot.allow_fetch)
self.assertTrue(sot.allow_... | meta': {'key': '3'},
'order_ref': IDENTIFIER,
'secret_ref': 'http://localhost/secrets/%s' % SECRET_ID,
'status': '6',
'sub_status': '7',
'sub_status_message': '8',
'type': '9',
'updated': '10'
}
class TestOrder(base.TestCase):
| 80 | 80 | 269 | 7 | 73 | NeCTAR-RC/openstacksdk | openstack/tests/unit/key_manager/v1/test_order.py | Python | TestOrder | TestOrder | 34 | 60 | 34 | 35 | 4f6d18381e6be584613a687d9f88c043529ee2ab | bigcode/the-stack | train |
ee1e8a75312231d002b3f7be | train | function | def sample_update_bucket():
"""Snippet for update_bucket"""
# Create a client
client = logging_v2.ConfigServiceV2Client()
# Initialize request argument(s)
project = "my-project-id"
location = "us-central1"
bucket = "bucket_value"
name = f"projects/{project}/locations/{location}/buckets... | def sample_update_bucket():
| """Snippet for update_bucket"""
# Create a client
client = logging_v2.ConfigServiceV2Client()
# Initialize request argument(s)
project = "my-project-id"
location = "us-central1"
bucket = "bucket_value"
name = f"projects/{project}/locations/{location}/buckets/{bucket}"
request = lo... | may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-logging
# [START logging_generated_logging_v2_ConfigServiceV2_UpdateBucket_sync]
from google.cloud import logging_v2
def sample_update_bucket():... | 64 | 64 | 118 | 5 | 58 | BenRKarl/gapic-generator-python | tests/integration/goldens/logging/samples/generated_samples/logging_generated_logging_v2_config_service_v2_update_bucket_sync.py | Python | sample_update_bucket | sample_update_bucket | 30 | 50 | 30 | 30 | 56fe123dc82a88f2fb4800193e278c3397523cd9 | bigcode/the-stack | train |
94c6b78e807f9e748121fe62 | train | function | def create_iot_policy():
try:
response = iotclient.create_policy(
policyName=ioTPolicyName,
policyDocument="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:*\",\"Resource\":\"*\"}]}"
)
except iotclient.exceptions.ResourceAlreadyExistsExc... | def create_iot_policy():
| try:
response = iotclient.create_policy(
policyName=ioTPolicyName,
policyDocument="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:*\",\"Resource\":\"*\"}]}"
)
except iotclient.exceptions.ResourceAlreadyExistsException:
print("IN... | _certificate(caCertificate=ca_pem.decode('utf-8'), verificationCertificate=ver_pem.decode('utf-8'), setAsActive=True, allowAutoRegistration=True)
except iotclient.exceptions.ResourceAlreadyExistsException:
print("INFO: Already have this CA registered")
def create_iot_policy():
| 64 | 64 | 86 | 6 | 58 | xiongyu0523/azure-sphere-aws-iot-device-sdk-embedded-c | script/preconfigure.py | Python | create_iot_policy | create_iot_policy | 70 | 77 | 70 | 70 | 7bfa1c990de7be2009dfbdff03140824d89cc995 | bigcode/the-stack | train |
3faa99fc2a7be4488adc5554 | train | function | def register_ca_certificate():
if utility_verison() < '20.10':
print('ERROR: update Azure Sphere SDK to the latest version')
return
response = iotclient.get_registration_code()
regCode = response['registrationCode']
if os.path.exists(CA_FILE_NAME):
os.remove(CA_FILE_NAME)
... | def register_ca_certificate():
| if utility_verison() < '20.10':
print('ERROR: update Azure Sphere SDK to the latest version')
return
response = iotclient.get_registration_code()
regCode = response['registrationCode']
if os.path.exists(CA_FILE_NAME):
os.remove(CA_FILE_NAME)
if os.path.exists(VER_FILE_NAME... | str else False
def utility_download_validation_certificate(code, file_name):
result = run(azsphere_program + 'ca-certificate download-proof -c ' + code + ' -o ' + file_name, capture_output=True)
str = result.stdout.decode('utf-8')
return True if 'Saved the requested proof of possession certificate' in... | 81 | 81 | 270 | 5 | 75 | xiongyu0523/azure-sphere-aws-iot-device-sdk-embedded-c | script/preconfigure.py | Python | register_ca_certificate | register_ca_certificate | 36 | 68 | 36 | 37 | 2524e5139d8d03a888e56fe4421f820eaeed4b85 | bigcode/the-stack | train |
26adaadf5d2d5cc759defff6 | train | function | def utility_download_validation_certificate(code, file_name):
result = run(azsphere_program + 'ca-certificate download-proof -c ' + code + ' -o ' + file_name, capture_output=True)
str = result.stdout.decode('utf-8')
return True if 'Saved the requested proof of possession certificate' in str else False
| def utility_download_validation_certificate(code, file_name):
| result = run(azsphere_program + 'ca-certificate download-proof -c ' + code + ' -o ' + file_name, capture_output=True)
str = result.stdout.decode('utf-8')
return True if 'Saved the requested proof of possession certificate' in str else False
| _name):
result = run(azsphere_program + 'ca-certificate download -o ' + file_name, capture_output=True)
str = result.stdout.decode('utf-8')
return True if 'Saved the requested CA certificate' in str else False
def utility_download_validation_certificate(code, file_name):
| 64 | 64 | 72 | 10 | 53 | xiongyu0523/azure-sphere-aws-iot-device-sdk-embedded-c | script/preconfigure.py | Python | utility_download_validation_certificate | utility_download_validation_certificate | 31 | 34 | 31 | 31 | d9eeb8a35edcc56e1f669098c9ded37a4c652b6f | bigcode/the-stack | train |
3938db3e4bda45978698d7c0 | train | function | def create_lambda_rule(fn_name):
role_name = fn_name + 'Role'
assume_role_policy_document = json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "st... | def create_lambda_rule(fn_name):
| role_name = fn_name + 'Role'
assume_role_policy_document = json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
})
... | f:
ver_pem = pem.armor('CERTIFICATE', f.read())
try:
response = iotclient.register_ca_certificate(caCertificate=ca_pem.decode('utf-8'), verificationCertificate=ver_pem.decode('utf-8'), setAsActive=True, allowAutoRegistration=True)
except iotclient.exceptions.ResourceAlreadyExistsException:
... | 179 | 179 | 597 | 7 | 172 | xiongyu0523/azure-sphere-aws-iot-device-sdk-embedded-c | script/preconfigure.py | Python | create_lambda_rule | create_lambda_rule | 79 | 166 | 79 | 80 | 6e33dac8da0f1c85fc21e5a98486582c86f8f9ae | bigcode/the-stack | train |
f284bbac7206a2b4c604a0b2 | train | function | def utility_download_ca_certificate(file_name):
result = run(azsphere_program + 'ca-certificate download -o ' + file_name, capture_output=True)
str = result.stdout.decode('utf-8')
return True if 'Saved the requested CA certificate' in str else False
| def utility_download_ca_certificate(file_name):
| result = run(azsphere_program + 'ca-certificate download -o ' + file_name, capture_output=True)
str = result.stdout.decode('utf-8')
return True if 'Saved the requested CA certificate' in str else False
| boto3.client('iam')
CA_FILE_NAME = 'ca.cer'
VER_FILE_NAME = 'ver.cer'
def utility_verison():
result = run(azsphere_program + 'show-version', capture_output=True)
return result.stdout.decode('utf-8')
def utility_download_ca_certificate(file_name):
| 64 | 64 | 60 | 8 | 56 | xiongyu0523/azure-sphere-aws-iot-device-sdk-embedded-c | script/preconfigure.py | Python | utility_download_ca_certificate | utility_download_ca_certificate | 26 | 29 | 26 | 26 | 01fcc02ab5847f870c8df47d176cbdccb1da8170 | bigcode/the-stack | train |
30eedfb036b086755205016a | train | function | def utility_verison():
result = run(azsphere_program + 'show-version', capture_output=True)
return result.stdout.decode('utf-8')
| def utility_verison():
| result = run(azsphere_program + 'show-version', capture_output=True)
return result.stdout.decode('utf-8')
| sts').get_caller_identity().get('Account')
iotclient = boto3.client('iot')
lambdaclient = boto3.client('lambda')
iamclient = boto3.client('iam')
CA_FILE_NAME = 'ca.cer'
VER_FILE_NAME = 'ver.cer'
def utility_verison():
| 64 | 64 | 32 | 5 | 59 | xiongyu0523/azure-sphere-aws-iot-device-sdk-embedded-c | script/preconfigure.py | Python | utility_verison | utility_verison | 22 | 24 | 22 | 22 | 52c42478b28b841fa5e42c460c6aa50cd376103c | bigcode/the-stack | train |
0f9515a2774f36415dc8984e | train | class | class House(object):
def __init__(self):
logger.info('Welcome to your new house')
self._door_open = False
self._lights_on = False
self.door_open_changed = Signal()
self.lights_on_changed = Signal()
self.color_changed = Signal()
self._pool = futures.ThreadP... | class House(object):
| def __init__(self):
logger.info('Welcome to your new house')
self._door_open = False
self._lights_on = False
self.door_open_changed = Signal()
self.lights_on_changed = Signal()
self.color_changed = Signal()
self._pool = futures.ThreadPoolExecutor(max_worker... | # -*- coding: utf-8 -*-
import time
import logging
from concurrent import futures
from pizco import Signal
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
logger.addHandler(ch)
COLORS = ('green', 'blue', 'white', 'yellow')
class House(objec... | 75 | 128 | 428 | 4 | 71 | hgrecco/pizco | examples/common.py | Python | House | House | 19 | 78 | 19 | 20 | b242e3b821a641ffc5aeb8c8490d8baffeb055b7 | bigcode/the-stack | train |
9c87d19c807a344b382ab0ec | train | class | class HistoryCommandTest(unittest.TestCase):
@patch("hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher")
def setUp(self, _: MagicMock) -> None:
super().setUp()
self.ev_loop = asyncio.get_event_loop()
self.async_run_with_timeout(read_system_configs_from_yml())
self.a... | class HistoryCommandTest(unittest.TestCase):
@patch("hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher")
| def setUp(self, _: MagicMock) -> None:
super().setUp()
self.ev_loop = asyncio.get_event_loop()
self.async_run_with_timeout(read_system_configs_from_yml())
self.app = HummingbotApplication()
self.cli_mock_assistant = CLIMockingAssistant(self.app.app)
self.cli_mock_a... | import asyncio
import datetime
import time
import unittest
from copy import deepcopy
from decimal import Decimal
from pathlib import Path
from typing import Awaitable, List
from unittest.mock import patch, MagicMock, AsyncMock
from hummingbot.client.config.config_helpers import read_system_configs_from_yml
from hummin... | 184 | 256 | 1,429 | 27 | 156 | cardosofede/hummingbot | test/hummingbot/client/command/test_history_command.py | Python | HistoryCommandTest | HistoryCommandTest | 22 | 180 | 22 | 23 | 119fc57f022b6f2fc74c40fdac3b1e7a35353e6c | bigcode/the-stack | train |
1e458adc6011d48d016fd475 | train | class | class ExtendParamEip:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
... | class ExtendParamEip:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
class ExtendParamEip:
| 22 | 234 | 783 | 6 | 15 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-bms/huaweicloudsdkbms/v1/model/extend_param_eip.py | Python | ExtendParamEip | ExtendParamEip | 12 | 109 | 12 | 14 | 065b3a370bc85f385e8bcaa696f5211ea104ec14 | bigcode/the-stack | train |
b51486ef9c939df30d69dd59 | train | function | def disable_randomness():
'''Make the random number generator produce deterministic (ie. non-random)
output. This is used for internal testing only, and must never be used
otherwise! A warning is printed.
'''
import random
import sys
print('', file=sys.stderr)
print('-- coldwallet running in test ... | def disable_randomness():
| '''Make the random number generator produce deterministic (ie. non-random)
output. This is used for internal testing only, and must never be used
otherwise! A warning is printed.
'''
import random
import sys
print('', file=sys.stderr)
print('-- coldwallet running in test mode - random number gener... | # Coldwallet encryption related functions. This is the heart of coldwallet.
from __future__ import absolute_import, division, print_function
import base64
import math
import os
import coldwallet.aes
import pylibscrypt
def disable_randomness():
| 54 | 64 | 190 | 5 | 48 | Anthchirp/python-coldwallet | coldwallet/crypto.py | Python | disable_randomness | disable_randomness | 12 | 30 | 12 | 12 | 8089a298794fbbbbd3ab19cb9e0fe736f3853310 | bigcode/the-stack | train |
9952af34f159f0d976cd1f36 | train | function | def encrypt_secret_key(secret, coldkey, public_address, scrypt_N=2**14, scrypt_p=1):
'''Encrypt a secret exponent using an individual symmetric key. The symmetric
key is generated from the shared coldwallet key (given as byte string) and
the public bitcoin address (given in human readable format) using the
... | def encrypt_secret_key(secret, coldkey, public_address, scrypt_N=2**14, scrypt_p=1):
| '''Encrypt a secret exponent using an individual symmetric key. The symmetric
key is generated from the shared coldwallet key (given as byte string) and
the public bitcoin address (given in human readable format) using the
memory-hard scrypt hash. The result is returned in base64 encoding.
'''
# Ge... | 100 - (2 ** zero_padding)
rand_string = rand_string[:-1] + bytes(bytearray((ord(rand_string[-1:]) & mask,)))
return rand_string
def encrypt_secret_key(secret, coldkey, public_address, scrypt_N=2**14, scrypt_p=1):
| 64 | 64 | 194 | 26 | 37 | Anthchirp/python-coldwallet | coldwallet/crypto.py | Python | encrypt_secret_key | encrypt_secret_key | 48 | 61 | 48 | 48 | 605a1740de9b8377f7dbcb28a4fb3c485d83e4b2 | bigcode/the-stack | train |
c9422fe84592aba734af55c1 | train | function | def generate_random_string(bits):
'''Generate a random string with a given number of bits. If the number of bits is
not divisible by 8 then pad with 0s.
'''
assert bits >= 1, "Cannot create 0 bit random strings"
stringbytes = int(math.ceil(bits / 8))
rand_string = os.urandom(stringbytes)
zero_padding... | def generate_random_string(bits):
| '''Generate a random string with a given number of bits. If the number of bits is
not divisible by 8 then pad with 0s.
'''
assert bits >= 1, "Cannot create 0 bit random strings"
stringbytes = int(math.ceil(bits / 8))
rand_string = os.urandom(stringbytes)
zero_padding = stringbytes * 8 - bits
if zer... | .random(), 10) * 256) for x in range(b))))
if sys.hexversion >= 0x03000000:
random.seed(a=0, version=1)
else:
random.seed(a=0)
os.urandom = fakerandom
def generate_random_string(bits):
| 64 | 64 | 141 | 6 | 57 | Anthchirp/python-coldwallet | coldwallet/crypto.py | Python | generate_random_string | generate_random_string | 32 | 46 | 32 | 32 | 3a5f1ef56703f1d7ac3d01645c2071238f1ec916 | bigcode/the-stack | train |
306bac184be19cf7c836a369 | train | function | def decrypt_secret_key(code, coldkey, public_address, scrypt_N=2**14, scrypt_p=1):
'''Decrypt a secret exponent, given in base64 encoding, using an individual
symmetric key. The symmetric key is generated as above. The result is
returned as a byte string.
'''
# Base64 decode the input
code = base64.b6... | def decrypt_secret_key(code, coldkey, public_address, scrypt_N=2**14, scrypt_p=1):
| '''Decrypt a secret exponent, given in base64 encoding, using an individual
symmetric key. The symmetric key is generated as above. The result is
returned as a byte string.
'''
# Base64 decode the input
code = base64.b64decode(code.encode('ascii'))
# Generate a 256 bit symmetric key from the coldwa... | encrypted_secret = coldwallet.aes.encrypt_block(secret, symmetric_key)
# Base64 encode the result
return base64.b64encode(encrypted_secret).decode('ascii')
def decrypt_secret_key(code, coldkey, public_address, scrypt_N=2**14, scrypt_p=1):
| 64 | 64 | 172 | 26 | 38 | Anthchirp/python-coldwallet | coldwallet/crypto.py | Python | decrypt_secret_key | decrypt_secret_key | 63 | 77 | 63 | 63 | 7659a34f54d99e27e2126340e6188ad453c7dc14 | bigcode/the-stack | train |
1f4b4203a832a167176e552e | train | class | @ctx.action_class("win")
class win_actions:
def filename():
title = actions.win.title()
result = title.split(" - ")[0]
if "." in result:
# print(result.split("\\")[-1])
return result.split("\\")[-1]
return ""
| @ctx.action_class("win")
class win_actions:
| def filename():
title = actions.win.title()
result = title.split(" - ")[0]
if "." in result:
# print(result.split("\\")[-1])
return result.split("\\")[-1]
return ""
| actions.key('shift-tab')
def jump_line(n: int):
actions.key("ctrl-g")
actions.insert(str(n))
actions.key("enter")
def find(text: str=None):
actions.key("ctrl-f")
actions.insert(text)
@ctx.action_class("win")
class win_actions:
| 64 | 64 | 60 | 11 | 53 | tpensyl-bw/knausj_talon | apps/platforms/win/notepad++/notepad++.py | Python | win_actions | win_actions | 55 | 63 | 55 | 56 | 11992b0f9389832f44da5e8e493335ccdddf907b | bigcode/the-stack | train |
d0f85b32374fddd03539ee4d | train | class | @ctx.action_class("user")
class UserActions:
def select_next_occurrence(text: str):
actions.edit.find(text)
actions.sleep("100ms")
actions.key("enter esc")
actions.sleep("100ms")
def select_previous_occurrence(text: str):
actions.edit.find(text)
actions.sleep("10... | @ctx.action_class("user")
class UserActions:
| def select_next_occurrence(text: str):
actions.edit.find(text)
actions.sleep("100ms")
actions.key("enter esc")
actions.sleep("100ms")
def select_previous_occurrence(text: str):
actions.edit.find(text)
actions.sleep("100ms")
actions.key("shift-enter esc")
... | def indent_less(): actions.key('shift-tab')
def jump_line(n: int):
actions.key("ctrl-g")
actions.insert(str(n))
actions.key("enter")
def find(text: str=None):
actions.key("ctrl-f")
actions.insert(text)
@ctx.action_class("win")
class win_actions:
def filename():
... | 129 | 129 | 433 | 11 | 118 | tpensyl-bw/knausj_talon | apps/platforms/win/notepad++/notepad++.py | Python | UserActions | UserActions | 65 | 143 | 65 | 66 | 34fa5c18f5545c9f6d50458c71125a6aa1e84867 | bigcode/the-stack | train |
f360f409603441dd61436e52 | train | class | @ctx.action_class('edit')
class EditActions:
def line_clone():
actions.key('ctrl-d')
def line_swap_up():
actions.key('ctrl-shift-up')
def line_swap_down():
actions.key('ctrl-shift-down')
def indent_more(): actions.key('tab')
def indent_less(): actions.key('shift-tab')
def... | @ctx.action_class('edit')
class EditActions:
| def line_clone():
actions.key('ctrl-d')
def line_swap_up():
actions.key('ctrl-shift-up')
def line_swap_down():
actions.key('ctrl-shift-down')
def indent_more(): actions.key('tab')
def indent_less(): actions.key('shift-tab')
def jump_line(n: int):
actions.key("ctrl... | ctrl-pageup')
def tab_next():
actions.key('ctrl-pagedown')
def tab_open():
actions.key('ctrl-n')
@ctx.action_class('code')
class CodeActions:
def toggle_comment():
actions.key('ctrl-q')
@ctx.action_class('edit')
class EditActions:
| 64 | 64 | 121 | 11 | 53 | tpensyl-bw/knausj_talon | apps/platforms/win/notepad++/notepad++.py | Python | EditActions | EditActions | 36 | 53 | 36 | 37 | ef6db1a79e57514d04318d6cda4751515dad83d3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.