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
c4cfc3a2ebd5298ffbd8c51a
train
function
def mapseries_combine(index, concat_result): final_series = concat_result.sort_index() final_series = index.to_series().map(final_series) return final_series
def mapseries_combine(index, concat_result):
final_series = concat_result.sort_index() final_series = index.to_series().map(final_series) return final_series
identity], kwargs) graph = HighLevelGraph.from_collections(name, dsk, dependencies=[ddf]) return new_dd_object(graph, name, meta, divisions) def mapseries(base_chunk, concat_map): return base_chunk.map(concat_map) def mapseries_combine(index, concat_result):
64
64
36
10
54
galipremsagar/dask
dask/dataframe/core.py
Python
mapseries_combine
mapseries_combine
6,917
6,920
6,917
6,917
5c02f0e21ac44260320da873a8243f6a49b8e75a
bigcode/the-stack
train
89894635a96e423154f221cf
train
function
def _repr_data_series(s, index): """A helper for creating the ``_repr_data`` property""" npartitions = len(index) - 1 if is_categorical_dtype(s): if has_known_categories(s): dtype = "category[known]" else: dtype = "category[unknown]" else: dtype = str(s.dt...
def _repr_data_series(s, index):
"""A helper for creating the ``_repr_data`` property""" npartitions = len(index) - 1 if is_categorical_dtype(s): if has_known_categories(s): dtype = "category[known]" else: dtype = "category[unknown]" else: dtype = str(s.dtype) return pd.Series([dtype]...
_partitions(pd.to_timedelta, arg, unit=unit, errors=errors, meta=meta) if hasattr(pd, "isna"): @wraps(pd.isna) def isna(arg): return map_partitions(pd.isna, arg) def _repr_data_series(s, index):
64
64
102
9
55
galipremsagar/dask
dask/dataframe/core.py
Python
_repr_data_series
_repr_data_series
6,626
6,636
6,626
6,626
ebd2c03cdbe12c337d7e852d1a2b8afc1e14d652
bigcode/the-stack
train
32b5aa31f920bbe4a12a009f
train
function
def has_parallel_type(x): """ Does this object have a dask dataframe equivalent? """ return get_parallel_type(x) is not Scalar
def has_parallel_type(x):
""" Does this object have a dask dataframe equivalent? """ return get_parallel_type(x) is not Scalar
@get_parallel_type.register(pd.Index) def get_parallel_type_index(_): return Index @get_parallel_type.register(_Frame) def get_parallel_type_frame(o): return get_parallel_type(o._meta) @get_parallel_type.register(object) def get_parallel_type_object(_): return Scalar def has_parallel_type(x):
64
64
30
6
57
galipremsagar/dask
dask/dataframe/core.py
Python
has_parallel_type
has_parallel_type
6,667
6,669
6,667
6,667
d225fa2d76671d1f2652056ec7b99278a6025505
bigcode/the-stack
train
9ae5fb4b1cb87d11cbfa6175
train
function
def _take_last(a, skipna=True): """ take last row (Series) of DataFrame / last value of Series considering NaN. Parameters ---------- a : pd.DataFrame or pd.Series skipna : bool, default True Whether to exclude NaN """ def _last_valid(s): for i in range(1, min(10, ...
def _take_last(a, skipna=True):
""" take last row (Series) of DataFrame / last value of Series considering NaN. Parameters ---------- a : pd.DataFrame or pd.Series skipna : bool, default True Whether to exclude NaN """ def _last_valid(s): for i in range(1, min(10, len(s) + 1)): val = ...
not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random_state) df = df.sample(frac=1.0, random_state=random_state) index = pseudorandom(len(df), p, random_state) return [df.iloc[index == i] for i in range(len(p))] def _take_last(a, skipna=True):
78
79
266
10
69
galipremsagar/dask
dask/dataframe/core.py
Python
_take_last
_take_last
6,059
6,097
6,059
6,059
36ce4f96a157ae957ede45983ffa970e716adf4f
bigcode/the-stack
train
e2c99c906c1f8b6794ffd2a0
train
function
@get_parallel_type.register(pd.DataFrame) def get_parallel_type_dataframe(_): return DataFrame
@get_parallel_type.register(pd.DataFrame) def get_parallel_type_dataframe(_):
return DataFrame
pd.Series([dtype] + ["..."] * npartitions, index=index, name=s.name) get_parallel_type = Dispatch("get_parallel_type") @get_parallel_type.register(pd.Series) def get_parallel_type_series(_): return Series @get_parallel_type.register(pd.DataFrame) def get_parallel_type_dataframe(_):
64
64
20
15
48
galipremsagar/dask
dask/dataframe/core.py
Python
get_parallel_type_dataframe
get_parallel_type_dataframe
6,647
6,649
6,647
6,648
71a7391fe45058507ec1d7b40b88d103c9b61e2d
bigcode/the-stack
train
47c0f501358e4bdd1d25d3e4
train
function
def cov_corr_agg(data, cols, min_periods=2, corr=False, scalar=False): out = cov_corr_combine(data, corr) counts = out["count"] C = out["cov"] C[counts < min_periods] = np.nan if corr: m2 = out["m"] den = np.sqrt(m2 * m2.T) else: den = np.where(counts, counts, np.nan) - 1...
def cov_corr_agg(data, cols, min_periods=2, corr=False, scalar=False):
out = cov_corr_combine(data, corr) counts = out["count"] C = out["cov"] C[counts < min_periods] = np.nan if corr: m2 = out["m"] den = np.sqrt(m2 * m2.T) else: den = np.where(counts, counts, np.nan) - 1 with np.errstate(invalid="ignore", divide="ignore"): mat =...
m = np.nansum(data["m"] + counts * (sums / counts_na - mu) ** 2, axis=0) out["m"] = m return out def cov_corr_agg(data, cols, min_periods=2, corr=False, scalar=False):
64
64
153
21
42
galipremsagar/dask
dask/dataframe/core.py
Python
cov_corr_agg
cov_corr_agg
6,013
6,027
6,013
6,013
b845fc51d10165eebcb1fb59043391cb141e62f7
bigcode/the-stack
train
d9faa65cd6a53bf9c30e5fd9
train
function
def idxmaxmin_agg(x, fn=None, skipna=True, scalar=False): res = idxmaxmin_combine(x, fn, skipna=skipna)["idx"] if len(res) == 0: raise ValueError("attempt to get argmax of an empty sequence") if scalar: return res[0] res.name = None return res
def idxmaxmin_agg(x, fn=None, skipna=True, scalar=False):
res = idxmaxmin_combine(x, fn, skipna=skipna)["idx"] if len(res) == 0: raise ValueError("attempt to get argmax of an empty sequence") if scalar: return res[0] res.name = None return res
: return x return ( x.groupby(level=0) .apply(idxmaxmin_row, fn=fn, skipna=skipna) .reset_index(level=1, drop=True) ) def idxmaxmin_agg(x, fn=None, skipna=True, scalar=False):
64
64
82
18
46
galipremsagar/dask
dask/dataframe/core.py
Python
idxmaxmin_agg
idxmaxmin_agg
6,526
6,533
6,526
6,526
878af6fd4c5d032f624c212f745bb5ff63ba089a
bigcode/the-stack
train
82a0d3aa00f19702871053fc
train
function
def hash_shard( df, nparts, split_out_setup=None, split_out_setup_kwargs=None, ignore_index=False ): if split_out_setup: h = split_out_setup(df, **(split_out_setup_kwargs or {})) else: h = df h = hash_object_dispatch(h, index=False) if is_series_like(h): h = h.values np....
def hash_shard( df, nparts, split_out_setup=None, split_out_setup_kwargs=None, ignore_index=False ):
if split_out_setup: h = split_out_setup(df, **(split_out_setup_kwargs or {})) else: h = df h = hash_object_dispatch(h, index=False) if is_series_like(h): h = h.values np.mod(h, nparts, out=h) return group_split_dispatch(df, h, nparts, ignore_index=ignore_index)
if (is_series_like(df) or is_dataframe_like(df)) and not is_dask_collection(df) else df for df in dfs ] return dfs def hash_shard( df, nparts, split_out_setup=None, split_out_setup_kwargs=None, ignore_index=False ):
64
64
111
27
36
galipremsagar/dask
dask/dataframe/core.py
Python
hash_shard
hash_shard
5,234
5,246
5,234
5,236
f4a665a9508fc40ab9ebeafc18620a9696dddd83
bigcode/the-stack
train
7f7e3f7cf59a2d35804946c9
train
class
class DataFrame(_Frame): """ Parallel Pandas DataFrame Do not use this class directly. Instead use functions like ``dd.read_csv``, ``dd.read_parquet``, or ``dd.from_pandas``. Parameters ---------- dsk: dict The dask graph to compute this DataFrame name: str The key pre...
class DataFrame(_Frame):
""" Parallel Pandas DataFrame Do not use this class directly. Instead use functions like ``dd.read_csv``, ``dd.read_parquet``, or ``dd.from_pandas``. Parameters ---------- dsk: dict The dask graph to compute this DataFrame name: str The key prefix that specifies which ...
) def to_series(self): return self.map_partitions(M.to_series, meta=self._meta.to_series()) @derived_from(pd.Index, ua_args=["index"]) def to_frame(self, index=True, name=None): if not index: raise NotImplementedError() return self.map_partitions( M.to_frame...
256
256
9,899
6
249
galipremsagar/dask
dask/dataframe/core.py
Python
DataFrame
DataFrame
3,735
4,994
3,735
3,735
1038eec9cd5fe719f3ddf716a6dd0be68a2c3edb
bigcode/the-stack
train
782ca93e342a824a5e7dd769
train
class
class Scalar(DaskMethodsMixin, OperatorMethodMixin): """ A Dask object to represent a pandas scalar""" def __init__(self, dsk, name, meta, divisions=None): # divisions is ignored, only present to be compatible with other # objects. if not isinstance(dsk, HighLevelGraph): dsk...
class Scalar(DaskMethodsMixin, OperatorMethodMixin):
""" A Dask object to represent a pandas scalar""" def __init__(self, dsk, name, meta, divisions=None): # divisions is ignored, only present to be compatible with other # objects. if not isinstance(dsk, HighLevelGraph): dsk = HighLevelGraph.from_collections(name, dsk, depende...
index_summary, insert_meta_param_description, is_categorical_dtype, is_dataframe_like, is_index_like, is_series_like, make_meta, meta_nonempty, raise_on_meta_error, valid_divisions, ) no_default = "__no_default__" pd.set_option("compute.use_numexpr", False) def _concat(args, ign...
256
256
1,046
11
245
galipremsagar/dask
dask/dataframe/core.py
Python
Scalar
Scalar
111
243
111
111
548fde3336fa5a71fe57ee5eb2c103b6bb226702
bigcode/the-stack
train
93766b43c752aaa108e3c713
train
function
def repartition_freq(df, freq=None): """ Repartition a timeseries dataframe by a new frequency """ if not isinstance(df.divisions[0], pd.Timestamp): raise TypeError("Can only repartition on frequency for timeseries") try: start = df.divisions[0].ceil(freq) except ValueError: star...
def repartition_freq(df, freq=None):
""" Repartition a timeseries dataframe by a new frequency """ if not isinstance(df.divisions[0], pd.Timestamp): raise TypeError("Can only repartition on frequency for timeseries") try: start = df.divisions[0].ceil(freq) except ValueError: start = df.divisions[0] divisions = m...
new:\n%s\n\ncombined:\n%s" % (pformat(a), pformat(b), pformat(c)) ) d[(out2, j - 1)] = (methods.concat, tmp) j += 1 return d def repartition_freq(df, freq=None):
64
64
177
9
54
galipremsagar/dask
dask/dataframe/core.py
Python
repartition_freq
repartition_freq
6,261
6,279
6,261
6,261
99884729ac04423b90906548e6b217ff95e09f3c
bigcode/the-stack
train
36105bb76f27d797bf0e02c4
train
function
def _emulate(func, *args, **kwargs): """ Apply a function using args / kwargs. If arguments contain dd.DataFrame / dd.Series, using internal cache (``_meta``) for calculation """ with raise_on_meta_error(funcname(func), udf=kwargs.pop("udf", False)): return func(*_extract_meta(args, True), *...
def _emulate(func, *args, **kwargs):
""" Apply a function using args / kwargs. If arguments contain dd.DataFrame / dd.Series, using internal cache (``_meta``) for calculation """ with raise_on_meta_error(funcname(func), udf=kwargs.pop("udf", False)): return func(*_extract_meta(args, True), **_extract_meta(kwargs, True))
= _extract_meta(x[k], nonempty) return res elif isinstance(x, Delayed): raise ValueError( "Cannot infer dataframe metadata with a `dask.delayed` argument" ) else: return x def _emulate(func, *args, **kwargs):
64
64
87
12
51
galipremsagar/dask
dask/dataframe/core.py
Python
_emulate
_emulate
5,504
5,510
5,504
5,504
d60cb9bd2307bd4abe99e864d32f84933f45e6aa
bigcode/the-stack
train
4616a9ea7be6a0c14faf8db9
train
function
def mapseries(base_chunk, concat_map): return base_chunk.map(concat_map)
def mapseries(base_chunk, concat_map):
return base_chunk.map(concat_map)
, f, [(name, n - 1 - i, 1, 1), identity], kwargs) graph = HighLevelGraph.from_collections(name, dsk, dependencies=[ddf]) return new_dd_object(graph, name, meta, divisions) def mapseries(base_chunk, concat_map):
64
64
18
9
55
galipremsagar/dask
dask/dataframe/core.py
Python
mapseries
mapseries
6,913
6,914
6,913
6,913
293687489c16b9b82297061e3a8ba30d7f6b2192
bigcode/the-stack
train
e7d6f0b6f60cf7705d3f76cd
train
function
def split_evenly(df, k): """ Split dataframe into k roughly equal parts """ divisions = np.linspace(0, len(df), k + 1).astype(int) return {i: df.iloc[divisions[i] : divisions[i + 1]] for i in range(k)}
def split_evenly(df, k):
""" Split dataframe into k roughly equal parts """ divisions = np.linspace(0, len(df), k + 1).astype(int) return {i: df.iloc[divisions[i] : divisions[i + 1]] for i in range(k)}
= df h = hash_object_dispatch(h, index=False) if is_series_like(h): h = h.values np.mod(h, nparts, out=h) return group_split_dispatch(df, h, nparts, ignore_index=ignore_index) def split_evenly(df, k):
64
64
62
8
56
galipremsagar/dask
dask/dataframe/core.py
Python
split_evenly
split_evenly
5,249
5,252
5,249
5,249
a1ffb49f99be1d0d4f0d0c0f4f206116c37e6a3c
bigcode/the-stack
train
31d286a0665392e5b54c26f2
train
function
def series_map(base_series, map_series): npartitions = base_series.npartitions split_out = map_series.npartitions dsk = {} base_token_key = tokenize(base_series, split_out) base_split_prefix = "base-split-{}".format(base_token_key) base_shard_prefix = "base-shard-{}".format(base_token_key) ...
def series_map(base_series, map_series):
npartitions = base_series.npartitions split_out = map_series.npartitions dsk = {} base_token_key = tokenize(base_series, split_out) base_split_prefix = "base-split-{}".format(base_token_key) base_shard_prefix = "base-shard-{}".format(base_token_key) for i, key in enumerate(base_series.__da...
(name, i + 2 * d - 1, 2 * d, 1)], kwargs, ) for i in range(n): dsk[(name, i)] = (apply, f, [(name, n - 1 - i, 1, 1), identity], kwargs) graph = HighLevelGraph.from_collections(name, dsk, dependencies=[ddf]) return new_dd_object(graph, name, meta, divisions) def mapse...
162
162
540
9
152
galipremsagar/dask
dask/dataframe/core.py
Python
series_map
series_map
6,923
6,979
6,923
6,923
963c3143340f5158d1a7ede627a2bf5ced8328ef
bigcode/the-stack
train
ac39facd364600e739649b4d
train
function
def total_mem_usage(df, index=True, deep=False): mem_usage = df.memory_usage(index=index, deep=deep) if is_series_like(mem_usage): mem_usage = mem_usage.sum() return mem_usage
def total_mem_usage(df, index=True, deep=False):
mem_usage = df.memory_usage(index=index, deep=deep) if is_series_like(mem_usage): mem_usage = mem_usage.sum() return mem_usage
))) new_partitions_boundaries = np.cumsum(new_npartitions) new_name = "repartition-{}-{}".format(size, tokenize(df)) return _repartition_from_boundaries(df, new_partitions_boundaries, new_name) def total_mem_usage(df, index=True, deep=False):
64
64
47
12
52
galipremsagar/dask
dask/dataframe/core.py
Python
total_mem_usage
total_mem_usage
6,311
6,315
6,311
6,311
c27aa8c32b78983bb7b674c1c0a962e07d7989de
bigcode/the-stack
train
e2dc5153aa25991ec1dc466a
train
class
class Index(Series): _partition_type = pd.Index _is_partition_type = staticmethod(is_index_like) _token_prefix = "index-" _accessors = set() _dt_attributes = { "nanosecond", "microsecond", "millisecond", "dayofyear", "minute", "hour", "day", ...
class Index(Series):
_partition_type = pd.Index _is_partition_type = staticmethod(is_index_like) _token_prefix = "index-" _accessors = set() _dt_attributes = { "nanosecond", "microsecond", "millisecond", "dayofyear", "minute", "hour", "day", "dayofweek", ...
frame.Series") if method != "pearson": raise NotImplementedError("Only Pearson correlation has been implemented") df = concat([self, other], axis=1) return cov_corr( df, min_periods, corr=True, scalar=True, split_every=split_every ) @derived_from(pd.Series) ...
256
256
1,099
5
250
galipremsagar/dask
dask/dataframe/core.py
Python
Index
Index
3,571
3,732
3,571
3,572
cbb7892d142804be286dca961ad6e325d13af915
bigcode/the-stack
train
eee24227208bfb8ef5ba7d65
train
function
def _rename_dask(df, names): """ Destructively rename columns of dd.DataFrame or name of dd.Series. Not for pd.DataFrame or pd.Series. Internally used to overwrite dd.DataFrame.columns and dd.Series.name We can't use map_partition because it applies function then rename Parameters --------...
def _rename_dask(df, names):
""" Destructively rename columns of dd.DataFrame or name of dd.Series. Not for pd.DataFrame or pd.Series. Internally used to overwrite dd.DataFrame.columns and dd.Series.name We can't use map_partition because it applies function then rename Parameters ---------- df : dd.DataFrame or d...
or is_index_like(df): if is_series_like(columns) or is_index_like(columns): columns = columns.name if df.name == columns: return df return df.rename(columns) # map_partition may pass other types return df def _rename_dask(df, names):
64
64
189
9
54
galipremsagar/dask
dask/dataframe/core.py
Python
_rename_dask
_rename_dask
5,725
5,747
5,725
5,725
adf5dd35ad3021d3f734e74733417a95d3887e0b
bigcode/the-stack
train
90c518ddc4466c590adde0c0
train
function
def _split_partitions(df, nsplits, new_name): """Split a Dask dataframe into new partitions Parameters ---------- df: DataFrame or Series nsplits: List[int] Number of target dataframes for each partition The length of nsplits should be the same as df.npartitions new_name: str ...
def _split_partitions(df, nsplits, new_name):
"""Split a Dask dataframe into new partitions Parameters ---------- df: DataFrame or Series nsplits: List[int] Number of target dataframes for each partition The length of nsplits should be the same as df.npartitions new_name: str See Also -------- repartition_npart...
_name, i] = (methods.concat, [(df._name, j) for j in range(start, end)]) divisions = [df.divisions[i] for i in new_partitions_boundaries] graph = HighLevelGraph.from_collections(new_name, dsk, dependencies=[df]) return new_dd_object(graph, new_name, df._meta, divisions) def _split_partitions(df, nsplits, ne...
90
90
302
13
77
galipremsagar/dask
dask/dataframe/core.py
Python
_split_partitions
_split_partitions
6,387
6,421
6,387
6,387
fc0b50bb63820d224f676076191a4f5eca992804
bigcode/the-stack
train
1edfc3db405995e01965b0da
train
function
def _reduction_combine(x, aca_combine=None, **kwargs): if isinstance(x, list): x = pd.Series(x) o = aca_combine(x, **kwargs) # Return a dataframe so that the concatenated version is also a dataframe return o.to_frame().T if is_series_like(o) else o
def _reduction_combine(x, aca_combine=None, **kwargs):
if isinstance(x, list): x = pd.Series(x) o = aca_combine(x, **kwargs) # Return a dataframe so that the concatenated version is also a dataframe return o.to_frame().T if is_series_like(o) else o
_chunk=None, **kwargs): o = aca_chunk(x, **kwargs) # Return a dataframe so that the concatenated version is also a dataframe return o.to_frame().T if is_series_like(o) else o def _reduction_combine(x, aca_combine=None, **kwargs):
64
64
73
16
47
galipremsagar/dask
dask/dataframe/core.py
Python
_reduction_combine
_reduction_combine
6,479
6,484
6,479
6,479
42998dc87fb451cee23f3a65851d7fbc352a3725
bigcode/the-stack
train
cc25bafaab355a4369780d7d
train
function
def _extract_meta(x, nonempty=False): """ Extract internal cache data (``_meta``) from dd.DataFrame / dd.Series """ if isinstance(x, (Scalar, _Frame)): return x._meta_nonempty if nonempty else x._meta elif isinstance(x, list): return [_extract_meta(_x, nonempty) for _x in x] elif...
def _extract_meta(x, nonempty=False):
""" Extract internal cache data (``_meta``) from dd.DataFrame / dd.Series """ if isinstance(x, (Scalar, _Frame)): return x._meta_nonempty if nonempty else x._meta elif isinstance(x, list): return [_extract_meta(_x, nonempty) for _x in x] elif isinstance(x, tuple): return ...
) ) graph = HighLevelGraph.from_collections(b, dsk, dependencies=dfs) divisions = [None] * (split_out + 1) return new_dd_object(graph, b, meta, divisions) aca = apply_concat_apply def _extract_meta(x, nonempty=False):
64
64
182
10
53
galipremsagar/dask
dask/dataframe/core.py
Python
_extract_meta
_extract_meta
5,481
5,501
5,481
5,481
076a550d8104cca04022fb88480a19418c91bbdd
bigcode/the-stack
train
cc6f720ba3c33468ce553153
train
function
def repartition_npartitions(df, npartitions): """ Repartition dataframe to a smaller number of partitions """ new_name = "repartition-%d-%s" % (npartitions, tokenize(df)) if df.npartitions == npartitions: return df elif df.npartitions > npartitions: npartitions_ratio = df.npartitions / n...
def repartition_npartitions(df, npartitions):
""" Repartition dataframe to a smaller number of partitions """ new_name = "repartition-%d-%s" % (npartitions, tokenize(df)) if df.npartitions == npartitions: return df elif df.npartitions > npartitions: npartitions_ratio = df.npartitions / npartitions new_partitions_boundaries =...
np.all(mem_usages <= size) new_npartitions = list(map(len, iter_chunks(mem_usages, size))) new_partitions_boundaries = np.cumsum(new_npartitions) new_name = "repartition-{}-{}".format(size, tokenize(df)) return _repartition_from_boundaries(df, new_partitions_boundaries, new_name) def total_mem_usage(...
136
136
456
12
123
galipremsagar/dask
dask/dataframe/core.py
Python
repartition_npartitions
repartition_npartitions
6,318
6,367
6,318
6,318
4ec87880126a44f67fc8e02f927201c7accb7d4f
bigcode/the-stack
train
a36a206614c5f6748cd8fbe3
train
function
@wraps(pd.to_datetime) def to_datetime(arg, meta=None, **kwargs): if meta is None: if isinstance(arg, Index): meta = pd.DatetimeIndex([]) meta.name = arg.name else: meta = pd.Series([pd.Timestamp("2000")]) meta.index = meta.index.astype(arg.index.dtype...
@wraps(pd.to_datetime) def to_datetime(arg, meta=None, **kwargs):
if meta is None: if isinstance(arg, Index): meta = pd.DatetimeIndex([]) meta.name = arg.name else: meta = pd.Series([pd.Timestamp("2000")]) meta.index = meta.index.astype(arg.index.dtype) meta.index.name = arg.index.name return map_part...
.divisions)), index=df.divisions) divisions = divs.shift(periods, freq=freq).index return type(df)(df.dask, df._name, df._meta, divisions) return df @wraps(pd.to_datetime) def to_datetime(arg, meta=None, **kwargs):
64
64
100
18
45
galipremsagar/dask
dask/dataframe/core.py
Python
to_datetime
to_datetime
6,600
6,610
6,600
6,601
916d94bf77435a76e0e57027939562f8c17b0300
bigcode/the-stack
train
6cf8c64e1697a01a22e4f58d
train
function
def quantile(df, q, method="default"): """Approximate quantiles of Series. Parameters ---------- q : list/array of floats Iterable of numbers ranging from 0 to 100 for the desired quantiles method : {'default', 'tdigest', 'dask'}, optional What method to use. By default will use das...
def quantile(df, q, method="default"):
"""Approximate quantiles of Series. Parameters ---------- q : list/array of floats Iterable of numbers ranging from 0 to 100 for the desired quantiles method : {'default', 'tdigest', 'dask'}, optional What method to use. By default will use dask's internal custom algorithm (...
) or is_index_like(df): if is_series_like(columns) or is_index_like(columns): columns = columns.name if df.name == columns: return df return df.rename(columns) # map_partition may pass other types return df def _rename_dask(df, names): """ Destructively ...
256
256
1,019
11
245
galipremsagar/dask
dask/dataframe/core.py
Python
quantile
quantile
5,750
5,864
5,750
5,750
22381d72f346ef9c700e653ce78b62493f6e8028
bigcode/the-stack
train
a69c728e535d1d697f0e5374
train
function
@get_parallel_type.register(_Frame) def get_parallel_type_frame(o): return get_parallel_type(o._meta)
@get_parallel_type.register(_Frame) def get_parallel_type_frame(o):
return get_parallel_type(o._meta)
) def get_parallel_type_series(_): return Series @get_parallel_type.register(pd.DataFrame) def get_parallel_type_dataframe(_): return DataFrame @get_parallel_type.register(pd.Index) def get_parallel_type_index(_): return Index @get_parallel_type.register(_Frame) def get_parallel_type_frame(o):
64
64
23
14
49
galipremsagar/dask
dask/dataframe/core.py
Python
get_parallel_type_frame
get_parallel_type_frame
6,657
6,659
6,657
6,658
1f140dbf66ed70da8e26b04e933a6685c471286c
bigcode/the-stack
train
445f0ab749008c1d2c9864bd
train
function
def _count_aggregate(x): return x.sum().astype("int64")
def _count_aggregate(x):
return x.sum().astype("int64")
.sum() max_val = value_count_series.max(skipna=dropna) mode_series = ( value_count_series[value_count_series == max_val] .index.to_series() .sort_values() .reset_index(drop=True) ) return mode_series def _count_aggregate(x):
64
64
17
7
56
galipremsagar/dask
dask/dataframe/core.py
Python
_count_aggregate
_count_aggregate
6,548
6,549
6,548
6,548
4d19607d44ea0db84a32425b1c305c8cfefc01df
bigcode/the-stack
train
6b1bb43b689e40886320ddba
train
function
def is_broadcastable(dfs, s): """ This Series is broadcastable against another dataframe in the sequence """ return ( isinstance(s, Series) and s.npartitions == 1 and s.known_divisions and any( s.divisions == (df.columns.min(), df.columns.max()) fo...
def is_broadcastable(dfs, s):
""" This Series is broadcastable against another dataframe in the sequence """ return ( isinstance(s, Series) and s.npartitions == 1 and s.known_divisions and any( s.divisions == (df.columns.min(), df.columns.max()) for df in dfs if isi...
"le", "ge", "ne", "eq"]: meth = getattr(pd.DataFrame, name) DataFrame._bind_comparison_method(name, meth) meth = getattr(pd.Series, name) Series._bind_comparison_method(name, meth) def is_broadcastable(dfs, s):
64
64
90
10
54
galipremsagar/dask
dask/dataframe/core.py
Python
is_broadcastable
is_broadcastable
5,055
5,068
5,055
5,055
a13697355f33e46e957a1af0c9e6cbb1fab48f96
bigcode/the-stack
train
2c17fd1f21cdde7ad15aa2a1
train
function
def _scalar_binary(op, self, other, inv=False): name = "{0}-{1}".format(funcname(op), tokenize(self, other)) dependencies = [self] dsk = {} return_type = get_parallel_type(other) if isinstance(other, Scalar): dependencies.append(other) other_key = (other._name, 0) elif is_dask_...
def _scalar_binary(op, self, other, inv=False):
name = "{0}-{1}".format(funcname(op), tokenize(self, other)) dependencies = [self] dsk = {} return_type = get_parallel_type(other) if isinstance(other, Scalar): dependencies.append(other) other_key = (other._name, 0) elif is_dask_collection(other): return NotImplemented...
_graph: dsk = self.__dask_optimize__(dsk, self.__dask_keys__()) name = "delayed-" + self._name dsk = HighLevelGraph.from_collections(name, dsk, dependencies=()) return Delayed(self.key, dsk) def _scalar_binary(op, self, other, inv=False):
76
76
256
13
63
galipremsagar/dask
dask/dataframe/core.py
Python
_scalar_binary
_scalar_binary
246
276
246
246
300e8d6d49536475d48de27a9f7f4a485642853f
bigcode/the-stack
train
a0b696789a2edb6333531da5
train
function
def _reduction_chunk(x, aca_chunk=None, **kwargs): o = aca_chunk(x, **kwargs) # Return a dataframe so that the concatenated version is also a dataframe return o.to_frame().T if is_series_like(o) else o
def _reduction_chunk(x, aca_chunk=None, **kwargs):
o = aca_chunk(x, **kwargs) # Return a dataframe so that the concatenated version is also a dataframe return o.to_frame().T if is_series_like(o) else o
1]) dsk = dict(((name, i), df) for i, df in enumerate(dfs)) return new_dd_object(dsk, name, df, divisions) raise ValueError("Data must be DataFrame or Series") def _reduction_chunk(x, aca_chunk=None, **kwargs):
64
64
56
14
50
galipremsagar/dask
dask/dataframe/core.py
Python
_reduction_chunk
_reduction_chunk
6,473
6,476
6,473
6,473
6b545446d5cd27c86443a306b000b5d9c4603f1d
bigcode/the-stack
train
cf7e1ff13098171b9ed66aad
train
function
@wraps(pd.to_timedelta) def to_timedelta(arg, unit="ns", errors="raise"): meta = pd.Series([pd.Timedelta(1, unit=unit)]) return map_partitions(pd.to_timedelta, arg, unit=unit, errors=errors, meta=meta)
@wraps(pd.to_timedelta) def to_timedelta(arg, unit="ns", errors="raise"):
meta = pd.Series([pd.Timedelta(1, unit=unit)]) return map_partitions(pd.to_timedelta, arg, unit=unit, errors=errors, meta=meta)
2000")]) meta.index = meta.index.astype(arg.index.dtype) meta.index.name = arg.index.name return map_partitions(pd.to_datetime, arg, meta=meta, **kwargs) @wraps(pd.to_timedelta) def to_timedelta(arg, unit="ns", errors="raise"):
64
64
62
22
42
galipremsagar/dask
dask/dataframe/core.py
Python
to_timedelta
to_timedelta
6,613
6,616
6,613
6,614
e54d1952eb7c3c015272a068cc7545cec525074f
bigcode/the-stack
train
40645f036d78f8f1bb490bc1
train
function
def mcrb(s,fs=None): ''' Frequency estimator based on the Dongming B., Gengxin Z., Xinying Y. estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns ...
def mcrb(s,fs=None):
''' Frequency estimator based on the Dongming B., Gengxin Z., Xinying Y. estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- ...
Digital Signal Processing. 2012. v. 12. p. 590–615. ''' s,N,fs = _check_input(s,fs) R = operators.correlation(s,mode='straight') n = np.arange(N) Wnum = 3*(N-n)*(N-n+1) Wdenum = N*(N**2-1) dR = R[1:]*np.conj(R[0:N-1]) fres = np.sum(Wnum[1:]*...
162
162
543
9
153
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
mcrb
mcrb
465
518
465
465
ea2305e7387954ca3fa892a739421822e8169d57
bigcode/the-stack
train
8d5807df1b160db91925cd04
train
function
def tretter_f(s,fs = None): ''' FUNCTION FOR TESTS. Freuquency estimation base on Tretter signal model. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns ---------------...
def tretter_f(s,fs = None):
''' FUNCTION FOR TESTS. Freuquency estimation base on Tretter signal model. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, ...
[1:]) fres = np.sum(Wnum*np.cumsum(incR)/Wdenum) #unwrapAngleR = np.cumsum(incR) else: fres1 = np.sum(incR)/(2*N-1) fres2 = np.sum(n*(n-1)*incR)/((2*N-1)*N*(N-1)) fres = 3*(fres1-fres2) fres = fs*fres/2/np.pi return fres #--------------------------------...
126
127
425
10
116
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
tretter_f
tretter_f
243
295
243
243
b6625710672d2ef990c19f76ccbd03e177ab3df1
bigcode/the-stack
train
3fd74f474d3fef32e659f214
train
function
def _check_input(s,fs=None): s = np.array(s) N = s.shape[0] if s.dtype not in \ [complex,np.complex,np.complex64, np.complex128,np.complex_]: s = scipy.signal.hilbert(s) if(fs is None): fs = N return s,N,fs
def _check_input(s,fs=None):
s = np.array(s) N = s.shape[0] if s.dtype not in \ [complex,np.complex,np.complex64, np.complex128,np.complex_]: s = scipy.signal.hilbert(s) if(fs is None): fs = N return s,N,fs
import numpy as np import scipy.signal from ... import operators __all__ = ['FitzR','Tretter_f','Kay','MCRB','MandM','Fitz','FandK','maxcorfreq_real'] #-------------------------------------------------------------- def _check_input(s,fs=None):
61
64
83
9
52
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
_check_input
_check_input
8
20
8
8
8caf8a6bd4b46556919f8ca6c5e0e0c7d0955f36
bigcode/the-stack
train
0dab7ea85f1b478ba0f79542
train
function
def maxcorfreq(s,fs=None, with_xcorr=True): ''' Fast signal frequency estimater for complex-valued single-tone short sample-size signals on the background of white gaussian noises with high signal-to-noise ratio (SNR). Parameters ----------- * s: 1d ndarray (float), is ...
def maxcorfreq(s,fs=None, with_xcorr=True):
''' Fast signal frequency estimater for complex-valued single-tone short sample-size signals on the background of white gaussian noises with high signal-to-noise ratio (SNR). Parameters ----------- * s: 1d ndarray (float), is the input signal. * fs: float or int, ...
corfreq_real(signal, fs=fs),f_exp) ''' s = np.array(s) if fs is None: fs = s.size if with_xcorr: s = operators.correlation(s,mode='full').real s1 = s[1:] s2 = s[:-1] corcof = np.sum(s1*s2)/np.sum(np.square(s)) angle = np.arccos(corcof) re...
131
131
438
15
116
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
maxcorfreq
maxcorfreq
89
153
89
89
fb0b93d306aa3e5588dea93d53771072887ef46c
bigcode/the-stack
train
f16cf7e2f51685880f425677
train
function
def f_and_k(s,fs=None): ''' Fu Н., Kam P.Y. frequency estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, estimated fre...
def f_and_k(s,fs=None):
''' Fu Н., Kam P.Y. frequency estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, estimated frequency. Notes...
,fs = _check_input(s,fs) R = operators.correlation(s,mode='straight') n = np.arange(N) Wnum = N*(N**2-1)-n*(n-1)*(3*N-2*n+1) Wdenum = (N**2)*(N**2-1) dR = R[1:]*np.conj(R[0:N-1]) fres = 2*np.sum(Wnum[1:]*np.angle(dR))/Wdenum fres = fs*(fres)/2/np.pi return ...
151
151
505
9
142
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
f_and_k
f_and_k
521
576
521
521
4ed1d9ab2f6e796cf083a750fdc8870d4e59cae8
bigcode/the-stack
train
75bb0e7f4302ea69f25b56e3
train
function
def _cfd_fulltest(s,fs,Nfft): fest = np.zeros(7) fest[0] = mlfft(s,fs,Nfft) fest[1] = fitz_r(s,fs) fest[2] = fitz (s,fs) fest[3] = kay (s,fs) fest[4] = f_and_k(s,fs) fest[5] = m_and_m(s,fs) fest[6] = mcrb (s,fs) return fest
def _cfd_fulltest(s,fs,Nfft):
fest = np.zeros(7) fest[0] = mlfft(s,fs,Nfft) fest[1] = fitz_r(s,fs) fest[2] = fitz (s,fs) fest[3] = kay (s,fs) fest[4] = f_and_k(s,fs) fest[5] = m_and_m(s,fs) fest[6] = mcrb (s,fs) return fest
TestHard'): fest = _cfd_fulltest(s,fs,2**20) else: fest = FitzR_est(s,fs) print ('It is wrong type of estimation') return fest #-------------------------------------------------------------- def _cfd_fulltest(s,fs,Nfft):
63
64
121
12
51
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
_cfd_fulltest
_cfd_fulltest
693
702
693
693
c146728e0e66333de41594c108475cdc764d217b
bigcode/the-stack
train
d2f8159975f2153e5fa1bd62
train
function
def mlfft(s,fs = None,Nfft = None): ''' Maximum-likelihood estimator of frequency, based on the maximum searching of the signal spectrum, obtained by fast Fourier transform with zero-padding. Parameters ----------------- * s: is the input 1d ndarray (input signal); * fs: ampling fre...
def mlfft(s,fs = None,Nfft = None):
''' Maximum-likelihood estimator of frequency, based on the maximum searching of the signal spectrum, obtained by fast Fourier transform with zero-padding. Parameters ----------------- * s: is the input 1d ndarray (input signal); * fs: ampling frequency (fs = Nfft, if None); * N...
(ms) beta = np.sum(n*ms) n2 = n**2 etta = np.sum((n2)*ms) Psi = alpha*etta-beta**2 args = np.unwrap(np.angle(s)) fres = alpha*np.sum(n*ms*args)-beta*np.sum(ms*args) fres = fres/Psi fres = fs*fres/2/np.pi return fres #-----------------------------------------...
118
119
399
13
105
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
mlfft
mlfft
579
629
579
579
d18cd32b0d68ed6b83ecb7f00371a16ada19677a
bigcode/the-stack
train
34afc7c2ab006f1e739d50a0
train
function
def fitz_r(s,fs = None, w_on = True): ''' Frequency estimator based on the phase-to-time approximation of signal correlation function by weighted least-square with correlation of signal modules as weights function. Parameters -------------- * s: 1d ndarray (complex), the input ...
def fitz_r(s,fs = None, w_on = True):
''' Frequency estimator based on the phase-to-time approximation of signal correlation function by weighted least-square with correlation of signal modules as weights function. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ...
ools.utilits as ut delay=5 f0=1 delta_f=0.5 fs = 10 SNR = 50 signal =\ dsatools.generator.beatsignal(delay=delay, f0=f0, delta_f=delta_f, fs=fs, ...
236
237
793
15
221
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
fitz_r
fitz_r
157
240
157
157
82e5d3385048bb65cb96a7a3a848f83352f3f747
bigcode/the-stack
train
5e18cd26fa62beaa93e4979a
train
function
def m_and_m(s,fs=None): ''' Frequency estimator based on the Mengali U., Morelli M., estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns --------------...
def m_and_m(s,fs=None):
''' Frequency estimator based on the Mengali U., Morelli M., estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, ...
Fowler M.L., Phase-based frequency estimation: a review, Digital Signal Processing. 2012. v. 12. p. 590–615. ''' s,N,fs = _check_input(s,fs) R = operators.correlation(s,mode='straight') n = np.arange(N) n2 = n**2 Wnum = np.sum(n*np.unwrap(np.angl...
149
149
498
9
140
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
m_and_m
m_and_m
409
462
409
409
1842360152739e1e7ac1b973d52192957de71e00
bigcode/the-stack
train
03c6b0d05c96ad92f45818ea
train
function
def kay(s,fs=None): ''' Kay S. Central finite-difference (CFD) frequency estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: ...
def kay(s,fs=None):
''' Kay S. Central finite-difference (CFD) frequency estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, estimated...
a noisy sinusoid by linear regression, IEEE Trans. Inform. Theory.. 1985. v. IT-3 1. p. 832-835. [2] Fowler M.L., Phase-based frequency estimation: a review, Digital Signal Processing. 2012. v. 12. p. 590–615. ''' s,N,fs = _check_input(s,fs) ...
164
164
547
8
156
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
kay
kay
298
353
298
298
53ebacba0e59acad00665cb80e8ed1783047aaa4
bigcode/the-stack
train
d4e267b87dec37fb777d7998
train
function
def maxcorfreq_real(s,fs=None,with_xcorr=True): ''' Fast signal frequency estimater for real-valued single-tone short sample-size signals on the background of white gaussian noises with high signal-to-noise ratio (SNR). Parameters ----------- * s: 1d ndarray (float), is...
def maxcorfreq_real(s,fs=None,with_xcorr=True):
''' Fast signal frequency estimater for real-valued single-tone short sample-size signals on the background of white gaussian noises with high signal-to-noise ratio (SNR). Parameters ----------- * s: 1d ndarray (float), is the input signal. * fs: float or int, ...
Kay','MCRB','MandM','Fitz','FandK','maxcorfreq_real'] #-------------------------------------------------------------- def _check_input(s,fs=None): s = np.array(s) N = s.shape[0] if s.dtype not in \ [complex,np.complex,np.complex64, np.complex128,np.complex_]: s = scipy.signal.hilbert(...
126
126
422
16
110
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
maxcorfreq_real
maxcorfreq_real
22
86
22
22
0b59057df3afd1f6bac23cd8bdb31d226b0d8a07
bigcode/the-stack
train
49871cdb8c53795487586c07
train
function
def fitz(s,fs=None): ''' Frequency estimator based on the M. Fitz estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, e...
def fitz(s,fs=None):
''' Frequency estimator based on the M. Fitz estimator. Parameters -------------- * s: 1d ndarray (complex), the input signal. * fs: float or None, ampling frequency (fs = s.size, if None). Returns -------------------- * f: float, estimated frequency. ...
s,N,fs = _check_input(s,fs) n = np.arange(N) w = (1.5*N/((N**2)-1))*(1-((n-0.5*N+1)/(N/2))**2) s_prod = s[1:]*np.conj(s[0:N-1]) fres = np.sum(w[0:N-1]*np.angle(s_prod)) fres = fs*fres/2/np.pi return fres #---------------------------------------------------------...
126
126
422
8
118
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
fitz
fitz
356
406
356
356
8d9697280f81b7504fc5b4c6694646574837eafe
bigcode/the-stack
train
aa704ab444b5ac9c8f136f19
train
function
def cfd_est(s,fs=None,mode='FitzR'): ''' United central-finite-difference (CFD) frequency estimator function, based on the phase-to-time approximation by least-square method. Parameters -------------- * s: is the input 1d ndarray (input signal); * fs: ampling frequency (fs = s...
def cfd_est(s,fs=None,mode='FitzR'):
''' United central-finite-difference (CFD) frequency estimator function, based on the phase-to-time approximation by least-square method. Parameters -------------- * s: is the input 1d ndarray (input signal); * fs: ampling frequency (fs = s.size, if None); * modes ...
''' s,N,fs = _check_input(s,fs) if(not Nfft): Nfft = N if(not fs): fs = Nfft LimOfFind = int(Nfft/2) S = np.abs(np.fft.fft(s,Nfft)) # расчет квадрата амплитуды спектра S = np.hstack((np.zeros(1),S[1:LimOfFind])) pp = np.flatnonzero(S==ma...
164
165
551
15
149
diarmaidocualain/dsatools
dsatools/_base/_frequency/_frequency_cfd.py
Python
cfd_est
cfd_est
632
691
632
632
18069f42e69da9e8fedda34c67f05b4e19dff235
bigcode/the-stack
train
61af2425b4d6cb387d8d1135
train
class
class UserData: def __init__(self, username, password): self.username = username self.password = password
class UserData:
def __init__(self, username, password): self.username = username self.password = password
from flask_login import UserMixin from .firestore_service import get_user class UserData:
20
64
27
4
15
oramirezperera/Flask_course
app/models.py
Python
UserData
UserData
5
8
5
5
cb89893ce47a4464ff53ad775f432b5e85418f60
bigcode/the-stack
train
73d38a87b3644c302e82c00d
train
class
class UserModel(UserMixin): def __init__(self, user_data): """ param user_data: UserData """ self.id = user_data.username self.password = user_data.password @staticmethod def query(user_id): user_doc = get_user(user_id) user_data = UserData...
class UserModel(UserMixin):
def __init__(self, user_data): """ param user_data: UserData """ self.id = user_data.username self.password = user_data.password @staticmethod def query(user_id): user_doc = get_user(user_id) user_data = UserData( username=u...
from flask_login import UserMixin from .firestore_service import get_user class UserData: def __init__(self, username, password): self.username = username self.password = password class UserModel(UserMixin):
49
64
95
6
42
oramirezperera/Flask_course
app/models.py
Python
UserModel
UserModel
10
26
10
10
efb4eff565c3725b5155de449c5384a31a37cf04
bigcode/the-stack
train
72e32a2fe87f9cada687433d
train
class
@skipIf(salt.utils.platform.is_windows(), 'This test cannot work on Windows') class ChrootTestCase(TestCase, LoaderModuleMockMixin): ''' Test cases for salt.modules.chroot ''' def setup_loader_modules(self): return { chroot: { '__salt__': {}, '__utils...
@skipIf(salt.utils.platform.is_windows(), 'This test cannot work on Windows') class ChrootTestCase(TestCase, LoaderModuleMockMixin):
''' Test cases for salt.modules.chroot ''' def setup_loader_modules(self): return { chroot: { '__salt__': {}, '__utils__': {}, '__opts__': {'cachedir': ''}, } } @patch('os.path.isdir') def test_exist(self, ...
2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS...
256
256
2,097
31
224
yuriks/salt
tests/unit/modules/test_chroot.py
Python
ChrootTestCase
ChrootTestCase
43
277
43
44
fddda0b3e5e4b7048adb759528c44348a0261c77
bigcode/the-stack
train
399a4549133da722c3ad5e49
train
class
class ProductAgentStatusInfo(object): def __init__(self): self._product_code = None self._product_name = None self._reject_reason = None self._status = None @property def product_code(self): return self._product_code @product_code.setter def product_code(se...
class ProductAgentStatusInfo(object):
def __init__(self): self._product_code = None self._product_name = None self._reject_reason = None self._status = None @property def product_code(self): return self._product_code @product_code.setter def product_code(self, value): self._product_code ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ProductAgentStatusInfo(object):
35
151
505
7
28
antopen/alipay-sdk-python-all
alipay/aop/api/domain/ProductAgentStatusInfo.py
Python
ProductAgentStatusInfo
ProductAgentStatusInfo
8
83
8
9
e7929ccc858dbbf913a8454ceca6868ba1a2690e
bigcode/the-stack
train
1914308348df8b958b1f7ef4
train
function
def get_exitcode_stdout_stderr(cmd): """ execute the external command and get its exitcode, stdout and stderr. """ args = shlex.split(cmd) proc = Popen(args, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() exitcode = proc.returncode return exitcode, out, err
def get_exitcode_stdout_stderr(cmd):
""" execute the external command and get its exitcode, stdout and stderr. """ args = shlex.split(cmd) proc = Popen(args, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() exitcode = proc.returncode return exitcode, out, err
= termios.tcgetattr(fd) tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch # end getchar() ######### def get_exitcode_stdout_stderr(cmd):
64
64
77
9
55
gicking/STM8_templates
Projects/STM8S_Discovery_Examples/echo_UART_with_ISR/STVD_Cosmic/upload.py
Python
get_exitcode_stdout_stderr
get_exitcode_stdout_stderr
64
72
64
64
6093e1b556fef84310abd94c7696e38f262c9025
bigcode/the-stack
train
03e1306784ad7096b0141502
train
function
def getchar(): """ python equivalent of getchar() """ ch = 0 if OS == 'Windows': import msvcrt as m ch = m.getch() sys.stdio.flush() sys.stderr.flush() else: import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) tty.setraw(sys.stdin.fileno()) ...
def getchar():
""" python equivalent of getchar() """ ch = 0 if OS == 'Windows': import msvcrt as m ch = m.getch() sys.stdio.flush() sys.stderr.flush() else: import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) tty.setraw(sys.stdin.fileno()) ch = sys.st...
'COM10' FLASHTOOL = 'stm8gal.exe' else: PORT = '/dev/ttyUSB0' FLASHTOOL = 'stm8gal' # set general TERMINAL = True ################## # helper functions ################## ######### def getchar():
64
64
123
3
61
gicking/STM8_templates
Projects/STM8S_Discovery_Examples/echo_UART_with_ISR/STVD_Cosmic/upload.py
Python
getchar
getchar
42
59
42
42
ee6b0ad3d785013d5e3b6dd468a29c6f2ae3dfdb
bigcode/the-stack
train
b95c179637d6952f3a94115b
train
function
def windows(): return platform.system() == "Windows"
def windows():
return platform.system() == "Windows"
/python2.7 import os import re import glob import platform import argparse import tarfile from distutils import util # handle input for pyton 2 vs 3 try: input = raw_input except NameError: input = input def windows():
64
64
12
3
60
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
windows
windows
28
29
28
28
5bcab4add8dd96f3f1d5fdf2549f6a5d5b3ca25c
bigcode/the-stack
train
381d46a0e02aae6660d530cd
train
function
def install_to_custom_dir(package): print('Please enter Houdini\'s path (e.g. {}):'.format(hfs_search_paths[0])) while True: path = input() if is_valid_install_dir(path): install_to_houdini_dir(path, package, force=True) break print('Invalid path. Please try again...
def install_to_custom_dir(package):
print('Please enter Houdini\'s path (e.g. {}):'.format(hfs_search_paths[0])) while True: path = input() if is_valid_install_dir(path): install_to_houdini_dir(path, package, force=True) break print('Invalid path. Please try again')
install package. Try running with root privileges') def install_to_houdini_dir(hfs, package, force=False): if macOS(): hfs = os.path.abspath(os.path.join(hfs, os.pardir)) install_package(hfs, package, force) def install_to_custom_dir(package):
64
64
76
7
57
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
install_to_custom_dir
install_to_custom_dir
88
95
88
88
c10092c5980dcc5ac3d8a42478fc1f44cba7d57a
bigcode/the-stack
train
509e4a23a321594ff0534f50
train
function
def query_agreement(install_dir): print('hdRpr will be installed to "{}"'.format(install_dir)) print('Do you agree? [y/n]') while True: try: return util.strtobool(input()) except ValueError: print('yes or no')
def query_agreement(install_dir):
print('hdRpr will be installed to "{}"'.format(install_dir)) print('Do you agree? [y/n]') while True: try: return util.strtobool(input()) except ValueError: print('yes or no')
_test') try: os.mkdir(test_dir) except OSError: print('No permission to create directories in {}. Run with root privileges to install here.'.format(path)) return False else: os.rmdir(test_dir) return True def query_agreement(install_dir):
64
64
65
8
55
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
query_agreement
query_agreement
60
67
60
60
3218e94789d77dbac64fee45ca7fb90250a6bc54
bigcode/the-stack
train
27ef5b58553691a960c1aa10
train
function
def install_package(install_dir, package, force=False): if force or query_agreement(install_dir): try: tar_file = tarfile.open(package[0], 'r:gz') tar_file.extractall(install_dir) for file in tar_file.getnames(): path = '{install_dir}/{file}'.format(instal...
def install_package(install_dir, package, force=False):
if force or query_agreement(install_dir): try: tar_file = tarfile.open(package[0], 'r:gz') tar_file.extractall(install_dir) for file in tar_file.getnames(): path = '{install_dir}/{file}'.format(install_dir=install_dir, file=file) if not os....
pr will be installed to "{}"'.format(install_dir)) print('Do you agree? [y/n]') while True: try: return util.strtobool(input()) except ValueError: print('yes or no') def install_package(install_dir, package, force=False):
64
64
127
12
52
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
install_package
install_package
69
81
69
69
6c806d51c2ece04846be754c8c8f5fd3b5f2463b
bigcode/the-stack
train
ec42cdf8bde3366d72fbe536
train
function
def linux(): return platform.system() == "Linux"
def linux():
return platform.system() == "Linux"
glob import platform import argparse import tarfile from distutils import util # handle input for pyton 2 vs 3 try: input = raw_input except NameError: input = input def windows(): return platform.system() == "Windows" def linux():
64
64
12
3
61
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
linux
linux
30
31
30
30
eb44450261ac62a840643fc428d72c384af043d4
bigcode/the-stack
train
776c03b2d9263a45504daabc
train
function
def is_valid_install_dir(path): if not os.path.isdir(path): return False setup_script_path = os.path.join(path, 'houdini_setup') if not os.path.isfile(setup_script_path): return False test_dir = os.path.join(path, 'create_access_test') try: os.mkdir(test_dir) except OSE...
def is_valid_install_dir(path):
if not os.path.isdir(path): return False setup_script_path = os.path.join(path, 'houdini_setup') if not os.path.isfile(setup_script_path): return False test_dir = os.path.join(path, 'create_access_test') try: os.mkdir(test_dir) except OSError: print('No permissi...
Effects Software\\Houdini 18*'] elif linux(): hfs_search_paths = ['/opt/hfs18*'] else: hfs_search_paths = ['/Applications/Houdini/Houdini18*/Frameworks/Houdini.framework/Versions/Current/Resources'] def is_valid_install_dir(path):
64
64
117
7
57
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
is_valid_install_dir
is_valid_install_dir
42
58
42
42
e12cd3605ee77a024e1e4110582951f89bee328a
bigcode/the-stack
train
e53347bb69acc704effd1a0a
train
function
def install_to_houdini_dir(hfs, package, force=False): if macOS(): hfs = os.path.abspath(os.path.join(hfs, os.pardir)) install_package(hfs, package, force)
def install_to_houdini_dir(hfs, package, force=False):
if macOS(): hfs = os.path.abspath(os.path.join(hfs, os.pardir)) install_package(hfs, package, force)
=file) if not os.path.isdir(path): print('-- Installing: ' + path) print('Successfully installed') except Exception as e: print(e) print('Could not install package. Try running with root privileges') def install_to_houdini_dir(hfs, package,...
64
64
48
15
49
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
install_to_houdini_dir
install_to_houdini_dir
83
86
83
83
fa5bbd2585452f6c72b585220e0961840ceb5e59
bigcode/the-stack
train
64e329b6f5936aa9298e2f3b
train
function
def macOS(): return platform.system() == "Darwin"
def macOS():
return platform.system() == "Darwin"
distutils import util # handle input for pyton 2 vs 3 try: input = raw_input except NameError: input = input def windows(): return platform.system() == "Windows" def linux(): return platform.system() == "Linux" def macOS():
64
64
14
4
60
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
macOS
macOS
32
33
32
32
3e8685fbfbee56c03b2d257e00e06a3f3d5e112d
bigcode/the-stack
train
afdc0379050a578c2210cfd5
train
function
def get_package_from_path(path): match = package_pattern.match(path) target = match.group('target') if target not in valid_targets: print('"{}": unknown target. Skipping.'.format(path)) return None return (path, target)
def get_package_from_path(path):
match = package_pattern.match(path) target = match.group('target') if target not in valid_targets: print('"{}": unknown target. Skipping.'.format(path)) return None return (path, target)
print('Invalid path. Please try again') valid_targets = ['Houdini'] package_pattern = re.compile(r'hdRpr-.*-(?P<target>.*?)-.*-(?P<platform_>.*?).tar.gz', re.VERBOSE) def get_package_from_path(path):
64
64
56
7
57
hshakula/RadeonProRenderUSD
pxr/imaging/plugin/hdRpr/package/install.py
Python
get_package_from_path
get_package_from_path
99
106
99
99
028dd8631f08e2ed2259cada13c5338f39d1c486
bigcode/the-stack
train
a697c412052e726ba78325e2
train
function
def fixup_dbi(): # We used to have a dbi.pyd with our .pyd files, but now have a .py file. # If the user didn't uninstall, they will find the .pyd which will cause # problems - so handle that. import win32api, win32con pyd_name = os.path.join(os.path.dirname(win32api.__file__), "dbi.pyd") ...
def fixup_dbi(): # We used to have a dbi.pyd with our .pyd files, but now have a .py file. # If the user didn't uninstall, they will find the .pyd which will cause # problems - so handle that.
import win32api, win32con pyd_name = os.path.join(os.path.dirname(win32api.__file__), "dbi.pyd") pyd_d_name = os.path.join(os.path.dirname(win32api.__file__), "dbi_d.pyd") py_name = os.path.join(os.path.dirname(win32con.__file__), "dbi.py") for this_pyd in (pyd_name, pyd_d_name): this_d...
, win32process.error): return win32api.GetSystemDirectory() except ImportError: return win32api.GetSystemDirectory() def fixup_dbi(): # We used to have a dbi.pyd with our .pyd files, but now have a .py file. # If the user didn't uninstall, they will find the .pyd which will cause ...
88
88
296
59
29
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
fixup_dbi
fixup_dbi
272
292
272
275
d271cc955d4d61875bc8178d32a373d5dc97fbfc
bigcode/the-stack
train
0262973ca1fd3d259e7362a8
train
class
class Tee: def __init__(self, file): self.f = file def write(self, what): if self.f is not None: try: self.f.write(what.replace("\n", "\r\n")) except IOError: pass tee_f.write(what) def flush(self): if self.f ...
class Tee:
def __init__(self, file): self.f = file def write(self, what): if self.f is not None: try: self.f.write(what.replace("\n", "\r\n")) except IOError: pass tee_f.write(what) def flush(self): if self.f is not None:...
pth file import os, sys, glob, shutil, time import winreg as winreg # Send output somewhere so it can be found if necessary... import tempfile tee_f = open(os.path.join(tempfile.gettempdir(), 'pywin32_postinstall.log'), "w") class Tee:
64
64
97
3
61
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
Tee
Tee
11
27
11
11
08939cec89966b2627a76acbf0abd69553b5d975
bigcode/the-stack
train
fdb1f6dd999b0c6869012b66
train
function
def usage(): msg = \ """%s: A post-install script for the pywin32 extensions. This should be run automatically after installation, but if it fails you can run it again with a '-install' parameter, to ensure the environment is setup correctly. Additional Options: -wait pid : Wait for the specified p...
def usage():
msg = \ """%s: A post-install script for the pywin32 extensions. This should be run automatically after installation, but if it fails you can run it again with a '-install' parameter, to ensure the environment is setup correctly. Additional Options: -wait pid : Wait for the specified process to term...
(dst) worked = 1 if verbose: print("Removed file %s" % (dst)) except Exception: print("FAILED to remove", dst) if worked: break except Exception as why: ...
64
64
121
3
61
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
usage
usage
567
580
567
567
2f1d232260fcb16767aff537dc67ff81a6c2dcc5
bigcode/the-stack
train
d40dc6c219c20df7e0e11648
train
function
def uninstall(): import distutils.sysconfig lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) # First ensure our system modules are loaded from pywin32_system, so # we can remove the ones we copied... LoadSystemModule(lib_dir, "pywintypes") LoadSystemModule(lib_dir, "pythoncom"...
def uninstall():
import distutils.sysconfig lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) # First ensure our system modules are loaded from pywin32_system, so # we can remove the ones we copied... LoadSystemModule(lib_dir, "pywintypes") LoadSystemModule(lib_dir, "pythoncom") try: ...
print("*" * 20, "WARNING", "*" * 20) print("It appears that the MFC DLL '%s' is not installed" % (mfc_dll,)) print("Pythonwin will not work without this DLL, and I haven't had the") print("time to package it in with the installer.") print() print("You can download th...
187
188
628
3
184
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
uninstall
uninstall
486
565
486
486
6d7155f0d7a7028ff5376f931a4d2367c5f4270b
bigcode/the-stack
train
c1cbbe62eb470d72e8225421
train
function
def RegisterPythonwin(register=True): """ Add (or remove) Pythonwin to context menu for python scripts. ??? Should probably also add Edit command for pys files also. Also need to remove these keys on uninstall, but there's no function like file_created to add registry entries to unin...
def RegisterPythonwin(register=True):
""" Add (or remove) Pythonwin to context menu for python scripts. ??? Should probably also add Edit command for pys files also. Also need to remove these keys on uninstall, but there's no function like file_created to add registry entries to uninstall log ??? """ import os, ...
): import win32com.server.register if register: func = win32com.server.register.RegisterClasses else: func = win32com.server.register.UnregisterClasses flags = {} if not verbose: flags['quiet']=1 for module, klass_name in com_modules: __import__(module) ...
139
139
466
7
132
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
RegisterPythonwin
RegisterPythonwin
193
234
193
193
f983e8f1fe4c7d30611440a440475b64c37b516e
bigcode/the-stack
train
1966375ec30d2d366e3cd5b4
train
function
def RegisterCOMObjects(register = 1): import win32com.server.register if register: func = win32com.server.register.RegisterClasses else: func = win32com.server.register.UnregisterClasses flags = {} if not verbose: flags['quiet']=1 for module, klass_name in com_mo...
def RegisterCOMObjects(register = 1):
import win32com.server.register if register: func = win32com.server.register.RegisterClasses else: func = win32com.server.register.UnregisterClasses flags = {} if not verbose: flags['quiet']=1 for module, klass_name in com_modules: __import__(module) ...
reg.REG_SZ, value) finally: my_key.Close() finally: root_key.Close() if verbose: print("-> %s\\%s[%s]=%r" % (root_key_name, key_name, value_name, value)) def RegisterCOMObjects(register = 1):
64
64
140
9
55
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
RegisterCOMObjects
RegisterCOMObjects
176
191
176
176
72bf3dfd85afad09d29194e37251efa188062fa0
bigcode/the-stack
train
48ee09a4dfdb4b89e1eb30d2
train
function
def install(): import distutils.sysconfig import traceback # The .pth file is now installed as a regular file. # Create the .pth file in the site-packages dir, and use only relative paths lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) # We used to write a .pth directly to sy...
def install():
import distutils.sysconfig import traceback # The .pth file is now installed as a regular file. # Create the .pth file in the site-packages dir, and use only relative paths lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) # We used to write a .pth directly to sys.prefix - clobb...
the .pyd which will cause # problems - so handle that. import win32api, win32con pyd_name = os.path.join(os.path.dirname(win32api.__file__), "dbi.pyd") pyd_d_name = os.path.join(os.path.dirname(win32api.__file__), "dbi_d.pyd") py_name = os.path.join(os.path.dirname(win32con.__file__), "dbi.py"...
256
256
1,872
3
253
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
install
install
294
484
294
294
bce15ec2c47cea2a0093f976a68bc265b6dab9dc
bigcode/the-stack
train
b3bb0a38e9053cd38f6a2d07
train
function
def CopyTo(desc, src, dest): import win32api, win32con while 1: try: win32api.CopyFile(src, dest, 0) return except win32api.error as details: if details.winerror==5: # access denied - user not admin. raise if silent: ...
def CopyTo(desc, src, dest):
import win32api, win32con while 1: try: win32api.CopyFile(src, dest, 0) return except win32api.error as details: if details.winerror==5: # access denied - user not admin. raise if silent: # Running silent mo...
""".split(): if maybe == path_name: csidl = getattr(shellcon, maybe) return shell.SHGetSpecialFolderPath(0, csidl, False) raise ValueError("%s is an unknown path ID" % (path_name,)) def CopyTo(desc, src, dest):
63
64
204
9
55
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
CopyTo
CopyTo
114
138
114
114
737a5ca1e3c8101e0942521dd907d3953472615a
bigcode/the-stack
train
e7f09d1ab04a21fe9aa94c30
train
function
def get_shortcuts_folder(): if get_root_hkey()==winreg.HKEY_LOCAL_MACHINE: try: fldr = get_special_folder_path("CSIDL_COMMON_PROGRAMS") except OSError: # No CSIDL_COMMON_PROGRAMS on this platform fldr = get_special_folder_path("CSIDL_PROGRAMS") else: ...
def get_shortcuts_folder():
if get_root_hkey()==winreg.HKEY_LOCAL_MACHINE: try: fldr = get_special_folder_path("CSIDL_COMMON_PROGRAMS") except OSError: # No CSIDL_COMMON_PROGRAMS on this platform fldr = get_special_folder_path("CSIDL_PROGRAMS") else: # non-admin install - ...
: # file not found raise finally: # tell windows about the change from win32com.shell import shell, shellcon shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None) def get_shortcuts_folder():
64
64
172
6
58
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
get_shortcuts_folder
get_shortcuts_folder
236
253
236
236
78c36ba5fc6599f092f1558b45bfa96a4e19112d
bigcode/the-stack
train
b9fc011828b58df9ab05e9e8
train
function
def SetPyKeyVal(key_name, value_name, value): root_hkey = get_root_hkey() root_key = winreg.OpenKey(root_hkey, root_key_name) try: my_key = winreg.CreateKey(root_key, key_name) try: winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value) finally: ...
def SetPyKeyVal(key_name, value_name, value):
root_hkey = get_root_hkey() root_key = winreg.OpenKey(root_hkey, root_key_name) try: my_key = winreg.CreateKey(root_key, key_name) try: winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value) finally: my_key.Close() finally: root_ke...
" % \ (modname, sys.version_info[0], sys.version_info[1], suffix) filename = os.path.join(lib_dir, "pywin32_system32", filename) mod = imp.load_dynamic(modname, filename) def SetPyKeyVal(key_name, value_name, value):
64
64
130
13
51
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
SetPyKeyVal
SetPyKeyVal
162
174
162
162
00972fd337b68851e58af4f83f8c6d24263e21ce
bigcode/the-stack
train
636496f6d31a66aa41a5e8e3
train
function
def LoadSystemModule(lib_dir, modname): # See if this is a debug build. import imp for suffix_item in imp.get_suffixes(): if suffix_item[0]=='_d.pyd': suffix = '_d' break else: suffix = "" filename = "%s%d%d%s.dll" % \ (modname, sys.ve...
def LoadSystemModule(lib_dir, modname): # See if this is a debug build.
import imp for suffix_item in imp.get_suffixes(): if suffix_item[0]=='_d.pyd': suffix = '_d' break else: suffix = "" filename = "%s%d%d%s.dll" % \ (modname, sys.version_info[0], sys.version_info[1], suffix) filename = os.path.join(lib_d...
.dll already in the system directory preventing us # from updating them! # So, we pull the same trick pywintypes.py does, but it loads from # our pywintypes_system32 directory. def LoadSystemModule(lib_dir, modname): # See if this is a debug build.
64
64
122
20
44
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
LoadSystemModule
LoadSystemModule
147
159
147
148
8b767431a0d6267bef48bac85ef4f6c3ee039b85
bigcode/the-stack
train
53f82ccdb5710527c9c6e194
train
function
def get_system_dir(): import win32api # we assume this exists. try: import pythoncom import win32process from win32com.shell import shell, shellcon try: if win32process.IsWow64Process(): return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYST...
def get_system_dir():
import win32api # we assume this exists. try: import pythoncom import win32process from win32com.shell import shell, shellcon try: if win32process.IsWow64Process(): return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEMX86) ret...
= "Python %d.%d" % (vi[0], vi[1]) return os.path.join(fldr, install_group) # Get the system directory, which may be the Wow64 directory if we are a 32bit # python on a 64bit OS. def get_system_dir():
64
64
129
5
59
Matchoc/python_env
python35/Scripts/pywin32_postinstall.py
Python
get_system_dir
get_system_dir
257
270
257
257
6551985702ff304b41af3680f8998735d8911a73
bigcode/the-stack
train
a7cc069f9a621543626f29fd
train
class
class SharedLib(object): '''Represents a single shared library in the build_products map. This can be used to configure build environments to link/build against this library. ''' def __init__(self, lib_name, lib_dir, include_dir, d...
class SharedLib(object):
'''Represents a single shared library in the build_products map. This can be used to configure build environments to link/build against this library. ''' def __init__(self, lib_name, lib_dir, include_dir, deps=[]): self.lib...
import os from .build_products import BuildProducts as products class SharedLib(object):
18
64
157
5
12
abingham/ackward
site_scons/bygg/tools.py
Python
SharedLib
SharedLib
5
27
5
5
45dddfef835a8f40f5ecdd790a2e372ff1c78d56
bigcode/the-stack
train
25e9a3d3fd5e347f4e94c829
train
function
def build_shared_library(env, name, sources, headers, lib_dir, include_dir, include_subdir='', deps=[], lib_name=None): ...
def build_shared_library(env, name, sources, headers, lib_dir, include_dir, include_subdir='', deps=[], lib_name=None):
'''A central rule for building shared libraries. ''' if not lib_name: lib_name = name local_env = env.Clone() lib = local_env.SharedLibrary(lib_name, sources) for dep in deps: products(env)[dep].configure(local_env) products(env)[name] = SharedLib( lib_name, ...
env.Alias( 'install', env.Install( os.path.join(include_dir, header_path), header)) def build_shared_library(env, name, sources, headers, lib_dir, ...
64
64
178
38
26
abingham/ackward
site_scons/bygg/tools.py
Python
build_shared_library
build_shared_library
39
75
39
47
5cf0bb5b9692df24351d67d5aaa21bc5dbbb8833
bigcode/the-stack
train
ff291106d8c86d1b5977ee78
train
function
def build_program(env, name, sources, bin_dir, deps=[]): local_env = env.Clone() bin = local_env.Program(name, sources) for dep in deps: products(env)[dep].configure(local_env) env.Alias('build', bin) env.Alias( ...
def build_program(env, name, sources, bin_dir, deps=[]):
local_env = env.Clone() bin = local_env.Program(name, sources) for dep in deps: products(env)[dep].configure(local_env) env.Alias('build', bin) env.Alias( 'install', env.Install( bin_dir, source = [bin]))
env.Alias( 'install', env.Install( lib_dir, source = [lib])) _install_headers( env, headers, os.path.join(include_dir, include_subdir)) def build_program(env, name, sources, bin_dir, ...
64
64
84
19
45
abingham/ackward
site_scons/bygg/tools.py
Python
build_program
build_program
77
92
77
81
1b4782e5a9fdc85a0339596efb93ee7e4dd0321c
bigcode/the-stack
train
25203d368c8d0d2f2b171777
train
function
def _install_headers(env, headers, include_dir): for header in headers: header_path, _ = os.path.split(str(header)) env.Alias( 'install', env.Install( os.path.join(include_dir, header_path), header))
def _install_headers(env, headers, include_dir):
for header in headers: header_path, _ = os.path.split(str(header)) env.Alias( 'install', env.Install( os.path.join(include_dir, header_path), header))
env.AppendUnique(LIBS=[self.lib_name]) env.AppendUnique(LIBPATH=[self.lib_dir]) env.AppendUnique(CPPPATH=[self.include_dir]) for dep in self.deps: products(env)[dep].configure(env) def _install_headers(env, headers, include_dir):
64
64
55
11
53
abingham/ackward
site_scons/bygg/tools.py
Python
_install_headers
_install_headers
29
37
29
29
ef081441e9cf72871b9a8bd8008352f14fab496a
bigcode/the-stack
train
e48727a507f33bce3542b033
train
function
def make_table(infos, table_cfg): df = pd.DataFrame(infos) eval_before = table_cfg.get("eval_before", None) if eval_before: for k, v in eval_before.items(): df[k] = df.eval(v) sort_key = table_cfg.get("sort_key", None) if sort_key: df = df.sort_values(by=sort_key, ascend...
def make_table(infos, table_cfg):
df = pd.DataFrame(infos) eval_before = table_cfg.get("eval_before", None) if eval_before: for k, v in eval_before.items(): df[k] = df.eval(v) sort_key = table_cfg.get("sort_key", None) if sort_key: df = df.sort_values(by=sort_key, ascending=False) calculate_weights_of...
list(df.Size)] langs = list(df.Language) # print(sizes) layout = go.Layout( paper_bgcolor="rgba(0,0,0,0)", # plot_bgcolor='rgba(0,0,0,0)' ) fig = go.Figure( go.Treemap( labels=names, parents=langs, values=weight, textinfo="lab...
180
180
603
9
171
entelecheia/eKorpKit
ekorpkit/info/docs.py
Python
make_table
make_table
222
284
222
223
6db0c693bc9cafd70bda22aa2a68f0009f8d132b
bigcode/the-stack
train
c0e4ac0877ca20acb82fd934
train
function
def make_figure(infos, fig_filepath): # import plotly.express as px import plotly.graph_objects as go values = [] # KB = float(1024) # MB = float(KB ** 2) # 1,048,576 # GB = float(KB ** 3) # 1,073,741,824 total_size = sum([x.size_in_bytes for x in infos]) total_size_en = sum([x.size_...
def make_figure(infos, fig_filepath): # import plotly.express as px
import plotly.graph_objects as go values = [] # KB = float(1024) # MB = float(KB ** 2) # 1,048,576 # GB = float(KB ** 3) # 1,073,741,824 total_size = sum([x.size_in_bytes for x in infos]) total_size_en = sum([x.size_in_bytes for x in infos if x.lang == "en"]) total_size_ko = sum([x.s...
info_fig_file make_figure(infos, fig_filepath) def save_sample_text(data_file_dir, sample_text_path, sample_max_lines=None): sample_paths = glob(data_file_dir + "/sample-*.txt") if len(sample_paths) > 0: sample_path = sample_paths[0] with open(sample_text_path, "w") as f: ...
160
160
536
20
140
entelecheia/eKorpKit
ekorpkit/info/docs.py
Python
make_figure
make_figure
160
219
160
161
11a069152c36c896fb9d2df12dad0ecfa23b5175
bigcode/the-stack
train
ff3fb8ba3f6841457242e2eb
train
function
def info_docs(**args): cfg = eKonf.to_config(args) info_cfg = cfg.info table_cfg = info_cfg.table info_name = info_cfg.name if info_cfg.base_dir is None: info_cfg.base_dir = Path(ekorpkit.__path__[0]).parent.as_posix() sample_output_dir = info_cfg.get("sample_output_dir", None) if ...
def info_docs(**args):
cfg = eKonf.to_config(args) info_cfg = cfg.info table_cfg = info_cfg.table info_name = info_cfg.name if info_cfg.base_dir is None: info_cfg.base_dir = Path(ekorpkit.__path__[0]).parent.as_posix() sample_output_dir = info_cfg.get("sample_output_dir", None) if sample_output_dir: ...
import os import re import time import codecs import pandas as pd from glob import glob from ekorpkit import eKonf from omegaconf.dictconfig import DictConfig from pytablewriter import MarkdownTableWriter from pytablewriter.style import Style from pathlib import Path from ekorpkit.utils.func import humanbytes, get_modi...
89
256
1,204
6
82
entelecheia/eKorpKit
ekorpkit/info/docs.py
Python
info_docs
info_docs
16
144
16
16
a3e1856bd970c651f89d9c7fac50ae1d878dae38
bigcode/the-stack
train
404759606f0799d3254ed1bb
train
function
def save_sample_text(data_file_dir, sample_text_path, sample_max_lines=None): sample_paths = glob(data_file_dir + "/sample-*.txt") if len(sample_paths) > 0: sample_path = sample_paths[0] with open(sample_text_path, "w") as f: with open(sample_path, "r") as sample_file: ...
def save_sample_text(data_file_dir, sample_text_path, sample_max_lines=None):
sample_paths = glob(data_file_dir + "/sample-*.txt") if len(sample_paths) > 0: sample_path = sample_paths[0] with open(sample_text_path, "w") as f: with open(sample_path, "r") as sample_file: sample = sample_file.read().strip() sample = sample.split("\...
) info_fig_file = info_cfg.get("info_fig_file", None) if info_fig_file: fig_filepath = Path(info_cfg.base_dir) / info_fig_file make_figure(infos, fig_filepath) def save_sample_text(data_file_dir, sample_text_path, sample_max_lines=None):
64
64
126
17
47
entelecheia/eKorpKit
ekorpkit/info/docs.py
Python
save_sample_text
save_sample_text
147
157
147
147
a0a276372c05685c90552b2511b0b928bc8d7936
bigcode/the-stack
train
e717769ddf5bb76c9f6e5430
train
function
@eval_ing.capture def save_eval_results(results, save_dir, epoch, n_artifacts, _run): # split results into episode metrics and other artifacts metrics_list = [epinfo.pop('episode') for epinfo in results] # list of dicts # save detailed metrics as .csv test_metrics_df = pd.DataFrame.from_records(metri...
@eval_ing.capture def save_eval_results(results, save_dir, epoch, n_artifacts, _run): # split results into episode metrics and other artifacts
metrics_list = [epinfo.pop('episode') for epinfo in results] # list of dicts # save detailed metrics as .csv test_metrics_df = pd.DataFrame.from_records(metrics_list) test_metrics_path = save_dir / f"test_metrics_epoch_{epoch:03}.csv" test_metrics_df.to_csv(path_or_buf=test_metrics_path, index=Fal...
.no_grad(): for i, test_sample in enumerate(self.data_loader): results[i] = run_episode(self.env, self.policy, test_sample) toc = time.time() logger.info(f"Evaluation took {toc-tic:.2f}s.") return results def close(self): logger.info(f"Closing evaluatio...
123
123
413
34
88
johny-c/noge
noge/evaluation.py
Python
save_eval_results
save_eval_results
77
118
77
80
d241707b39e8869704a96e3065a87b04dfba952c
bigcode/the-stack
train
fa7930f0f50f27707897cc13
train
function
def run_episode(env, policy, env_reset_kwargs): obs = env.reset(**env_reset_kwargs) done = False episode_info = None while not done: action = policy(obs) next_obs, reward, done, episode_info = env.step(action) obs = next_obs return episode_info
def run_episode(env, policy, env_reset_kwargs):
obs = env.reset(**env_reset_kwargs) done = False episode_info = None while not done: action = policy(obs) next_obs, reward, done, episode_info = env.step(action) obs = next_obs return episode_info
import tqdm import pickle import pandas as pd from sacred import Ingredient from xlog.utils import get_logger from xlog.sum_writer import sum_writer eval_ing = Ingredient('evaluator', ingredients=[sum_writer]) logger = get_logger(__name__) def run_episode(env, policy, env_reset_kwargs):
64
64
69
11
53
johny-c/noge
noge/evaluation.py
Python
run_episode
run_episode
16
26
16
17
c46fd57168a1c7932d91ff42996200b5f7d73f14
bigcode/the-stack
train
5a66bf16ace09024fe1bc6ab
train
class
class Evaluator: def __init__(self, data_loader, env, policy): self.data_loader = data_loader self.policy = policy self.env = env def run(self, network): n_test_graphs = len(self.data_loader) results = [None for _ in range(n_test_graphs)] logger.info(f"Evaluatin...
class Evaluator:
def __init__(self, data_loader, env, policy): self.data_loader = data_loader self.policy = policy self.env = env def run(self, network): n_test_graphs = len(self.data_loader) results = [None for _ in range(n_test_graphs)] logger.info(f"Evaluating . . .") ...
'], sample['source'] episode_info = run_episode(env, policy, sample) episode_infos.append(episode_info) eval_toc = time.time() _log.info(f"Evaluated in {eval_toc - eval_tic:.2f}s.") return episode_infos class Evaluator:
64
64
179
4
59
johny-c/noge
noge/evaluation.py
Python
Evaluator
Evaluator
49
74
49
49
0f290af55e278ee375acd70b851042afc54b8f16
bigcode/the-stack
train
429c178da0268baf561186e5
train
function
@eval_ing.capture def evaluate_policy(env, test_loader, policy, _run, _log): """Evaluate policy on test_data""" episode_infos = [] _log.info(f"Evaluating ...") eval_tic = time.time() for e, sample in tqdm.tqdm(enumerate(test_loader), total=len(test_loader)): # G, s = sample['graph'], samp...
@eval_ing.capture def evaluate_policy(env, test_loader, policy, _run, _log):
"""Evaluate policy on test_data""" episode_infos = [] _log.info(f"Evaluating ...") eval_tic = time.time() for e, sample in tqdm.tqdm(enumerate(test_loader), total=len(test_loader)): # G, s = sample['graph'], sample['source'] episode_info = run_episode(env, policy, sample) ...
episode_info = None while not done: action = policy(obs) next_obs, reward, done, episode_info = env.step(action) obs = next_obs return episode_info @eval_ing.capture def evaluate_policy(env, test_loader, policy, _run, _log):
64
64
142
21
42
johny-c/noge
noge/evaluation.py
Python
evaluate_policy
evaluate_policy
29
46
29
30
c364458421ae9ef78ef5805b64c8511af2eb9b79
bigcode/the-stack
train
bb12a10a9f6a596f485effa5
train
function
def test_update_request_for_redirect_raises_for_urn_redirects(): client = ClientSession() with pytest.raises(UnsupportedRedirect) as redirect_exception: client.update_request_for_redirect( Request("GET", b"/foo", None), Response( 302, [(b"Location", b"urn:uuid:6e...
def test_update_request_for_redirect_raises_for_urn_redirects():
client = ClientSession() with pytest.raises(UnsupportedRedirect) as redirect_exception: client.update_request_for_redirect( Request("GET", b"/foo", None), Response( 302, [(b"Location", b"urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66")] ), ) ...
://somewhere.org") request = Request("GET", b"/foo", None) assert request.url == URL(b"/foo") client.check_permanent_redirects(request) assert request.url == URL(b"https://somewhere.org") def test_update_request_for_redirect_raises_for_urn_redirects():
64
64
144
14
50
myusko/BlackSheep
tests/client/test_client.py
Python
test_update_request_for_redirect_raises_for_urn_redirects
test_update_request_for_redirect_raises_for_urn_redirects
57
71
57
57
11fbe3fde195715c130c46089cffeff5f01e77a4
bigcode/the-stack
train
e4f2d7e13282f65657c8db1e
train
function
def test_check_permanent_redirects(): client = ClientSession() client._permanent_redirects_urls._cache[b"/foo"] = URL(b"https://somewhere.org") request = Request("GET", b"/foo", None) assert request.url == URL(b"/foo") client.check_permanent_redirects(request) assert request.url == URL(b"https...
def test_check_permanent_redirects():
client = ClientSession() client._permanent_redirects_urls._cache[b"/foo"] = URL(b"https://somewhere.org") request = Request("GET", b"/foo", None) assert request.url == URL(b"/foo") client.check_permanent_redirects(request) assert request.url == URL(b"https://somewhere.org")
=world", b"https://foo.org?hello=world", ], ], ) def test_get_url_value_with_base_url(base_url, value, result): client = ClientSession(base_url=base_url) assert client.get_url_value(value) == result def test_check_permanent_redirects():
64
64
82
8
55
myusko/BlackSheep
tests/client/test_client.py
Python
test_check_permanent_redirects
test_check_permanent_redirects
46
54
46
46
a31999496a2af834bf480c297cae35478d845fe7
bigcode/the-stack
train
3fe5613b1e668e723a36538f
train
function
@pytest.mark.parametrize( "base_url,value,result", [ ["https://example.org", "/?hello=world", b"https://example.org/?hello=world"], ["https://example.org", "https://foo.org", b"https://foo.org"], [ "https://example.org", "https://foo.org/?hello=world", ...
@pytest.mark.parametrize( "base_url,value,result", [ ["https://example.org", "/?hello=world", b"https://example.org/?hello=world"], ["https://example.org", "https://foo.org", b"https://foo.org"], [ "https://example.org", "https://foo.org/?hello=world", ...
client = ClientSession(base_url=base_url) assert client.get_url_value(value) == result
@pytest.mark.parametrize( "base_url,value,result", [ ["https://example.org", "/?hello=world", b"https://example.org/?hello=world"], ["https://example.org", "https://foo.org", b"https://foo.org"], [ "https://example.org", "https://foo.org/?hello=world", ...
139
64
161
139
0
myusko/BlackSheep
tests/client/test_client.py
Python
test_get_url_value_with_base_url
test_get_url_value_with_base_url
24
43
24
41
6258a2b315ef8b4213063a8ef050edaf7149c341
bigcode/the-stack
train
7f6365e1f5fe9ea88c48c86d
train
function
@pytest.mark.asyncio async def test_client_session_without_middlewares_and_cookiejar(): called = False async def monkey_send_core(request): nonlocal called called = True async with ClientSession(cookie_jar=False) as client: assert client._handler is None assert not client.m...
@pytest.mark.asyncio async def test_client_session_without_middlewares_and_cookiejar():
called = False async def monkey_send_core(request): nonlocal called called = True async with ClientSession(cookie_jar=False) as client: assert client._handler is None assert not client.middlewares client._send_core = monkey_send_core # type: ignore await ...
DemoConnection(None, pool) with pytest.raises(ConnectionClosedError): async with DemoClient() as client: await client._send_using_connection( Request("GET", b"https://somewhere.org", None) ) @pytest.mark.asyncio async def test_client_session_without_middlewares_and_...
64
64
106
17
47
myusko/BlackSheep
tests/client/test_client.py
Python
test_client_session_without_middlewares_and_cookiejar
test_client_session_without_middlewares_and_cookiejar
96
112
96
97
9d64a95e1723d65b7d0ea635f32a8d76c1b40162
bigcode/the-stack
train
bee79ab0a6841da1751ee546
train
function
@pytest.mark.asyncio async def test_client_session_validate_url_for_relative_urls_with_base_url(): async with ClientSession(base_url=b"https://foo.org") as client: request = Request("GET", b"/home", None) client._validate_request_url(request) assert request.url == URL(b"https://foo.org/hom...
@pytest.mark.asyncio async def test_client_session_validate_url_for_relative_urls_with_base_url():
async with ClientSession(base_url=b"https://foo.org") as client: request = Request("GET", b"/home", None) client._validate_request_url(request) assert request.url == URL(b"https://foo.org/home")
async def test_client_session_validate_url_for_relative_urls_no_base_url(): async with ClientSession() as client: with pytest.raises(ValueError): client._validate_request_url(Request("GET", b"/", None)) @pytest.mark.asyncio async def test_client_session_validate_url_for_relative_urls_with_base_u...
64
64
69
19
45
myusko/BlackSheep
tests/client/test_client.py
Python
test_client_session_validate_url_for_relative_urls_with_base_url
test_client_session_validate_url_for_relative_urls_with_base_url
122
129
122
123
32eab60cdf0afe336c37954874abfc7565aee290
bigcode/the-stack
train
7f2f2efe58660ac225bfca87
train
function
@pytest.mark.asyncio async def test_client_session_validate_url_for_relative_urls_no_base_url(): async with ClientSession() as client: with pytest.raises(ValueError): client._validate_request_url(Request("GET", b"/", None))
@pytest.mark.asyncio async def test_client_session_validate_url_for_relative_urls_no_base_url():
async with ClientSession() as client: with pytest.raises(ValueError): client._validate_request_url(Request("GET", b"/", None))
assert not client.middlewares client._send_core = monkey_send_core # type: ignore await client.send(Request("GET", b"https://somewhere.org", None)) assert called is True @pytest.mark.asyncio async def test_client_session_validate_url_for_relative_urls_no_base_url():
64
64
50
19
44
myusko/BlackSheep
tests/client/test_client.py
Python
test_client_session_validate_url_for_relative_urls_no_base_url
test_client_session_validate_url_for_relative_urls_no_base_url
115
119
115
116
5e071f382bf4ae7907d27d3a63c637cc23126d9b
bigcode/the-stack
train
0742b66137206a3e8a90170c
train
function
@pytest.mark.asyncio async def test_client_send_handles_connection_closed_error(): attempt = 0 class DemoConnection(ClientConnection): async def send(self, request): nonlocal attempt attempt += 1 raise ConnectionClosedError(attempt < 2) class DemoClient(ClientSe...
@pytest.mark.asyncio async def test_client_send_handles_connection_closed_error():
attempt = 0 class DemoConnection(ClientConnection): async def send(self, request): nonlocal attempt attempt += 1 raise ConnectionClosedError(attempt < 2) class DemoClient(ClientSession): async def get_connection(self, url: URL) -> ClientConnection: ...
), ) assert ( redirect_exception.value.redirect_url == b"urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66" ) @pytest.mark.asyncio async def test_client_send_handles_connection_closed_error():
64
64
149
15
49
myusko/BlackSheep
tests/client/test_client.py
Python
test_client_send_handles_connection_closed_error
test_client_send_handles_connection_closed_error
74
93
74
75
4366907196da7ff3610eb6a38c4b60e345ae7dbf
bigcode/the-stack
train
eb93fdd1d309d2024de606d2
train
function
@pytest.mark.parametrize( "value,result", [ ["", b"/"], ["/?hello=world", b"/?hello=world"], ["https://foo.org", b"https://foo.org"], ["https://foo.org/?hello=world", b"https://foo.org/?hello=world"], ["https://foo.org?hello=world", b"https://foo.org?hello=world"], ],...
@pytest.mark.parametrize( "value,result", [ ["", b"/"], ["/?hello=world", b"/?hello=world"], ["https://foo.org", b"https://foo.org"], ["https://foo.org/?hello=world", b"https://foo.org/?hello=world"], ["https://foo.org?hello=world", b"https://foo.org?hello=world"], ],...
client = ClientSession() assert client.get_url_value(value) == result
@pytest.mark.parametrize( "value,result", [ ["", b"/"], ["/?hello=world", b"/?hello=world"], ["https://foo.org", b"https://foo.org"], ["https://foo.org/?hello=world", b"https://foo.org/?hello=world"], ["https://foo.org?hello=world", b"https://foo.org?hello=world"], ],...
99
64
116
99
0
myusko/BlackSheep
tests/client/test_client.py
Python
test_get_url_value
test_get_url_value
9
21
9
19
d5ed5fcfcf492392e46cb9a055a8c07e9454c6ad
bigcode/the-stack
train
135d85884a9b633da333b286
train
function
@cli.command('symmetry',short_help="Get symmetry of POSCAR") @click.argument('attr', type=str,autocompletion=get_symmetry_attr) @click.argument('poscar', metavar='<cell_file>', type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True), autocompletion=get_poscar_files...
@cli.command('symmetry',short_help="Get symmetry of POSCAR") @click.argument('attr', type=str,autocompletion=get_symmetry_attr) @click.argument('poscar', metavar='<cell_file>', type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True), autocompletion=get_poscar_files...
""" argument: poscar, the path of your initial POSCAR attr, the attribute you want to get Example: pyvasp symmetry space POSCAR # get space_group pyvasp symmetry equivalent POSCAR # get equivalent_atoms pyvasp symmetry primitive POSCAR # get primitive cell """ c = read_...
'] if k.startswith(incomplete)] @cli.command('symmetry',short_help="Get symmetry of POSCAR") @click.argument('attr', type=str,autocompletion=get_symmetry_attr) @click.argument('poscar', metavar='<cell_file>', type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True), ...
109
110
369
102
7
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
symmetry
symmetry
335
374
335
341
c9215f0771b8e5ccd217db10be08bd62f1370f9f
bigcode/the-stack
train
4407d14dea4c1ed8e70d33eb
train
function
def get_ele_sta(no_defect_outcar,number): number = int(number) tmp_match_line = _get_line(no_defect_outcar,rematch='electrostatic') rows = number // 5 col = number - rows * 5 - 1 if col == -1: rows -= 1 col = 4 tmp_line = lc.getlines(no_defect_outcar)[tmp_match_line[0]+rows+3].s...
def get_ele_sta(no_defect_outcar,number):
number = int(number) tmp_match_line = _get_line(no_defect_outcar,rematch='electrostatic') rows = number // 5 col = number - rows * 5 - 1 if col == -1: rows -= 1 col = 4 tmp_line = lc.getlines(no_defect_outcar)[tmp_match_line[0]+rows+3].split() return [str(i) for i in tmp_lin...
click.echo('vbm_down: ' + str(gap_res[1][0])+ '\ncbm_down: '+str(gap_res[1][1])+'\ngap_down: '+str(gap_res[1][2])) def get_ele_sta(no_defect_outcar,number):
64
64
127
12
52
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
get_ele_sta
get_ele_sta
127
136
127
127
6bd1dec4b6a95cc4d5c1ad588bfc7fcc877c3b5c
bigcode/the-stack
train
ecaed5fd45dd4645a93daacf
train
function
@cli.command('energy',short_help="Get total energy") @click.option('--wd','-w',default='.',help='your work direcroty',show_default=True, type=click.Path(exists=True,resolve_path=True),autocompletion=get_dir_name) def energy(wd): EV = ExtractValue(wd) click.echo(EV.get_energy())
@cli.command('energy',short_help="Get total energy") @click.option('--wd','-w',default='.',help='your work direcroty',show_default=True, type=click.Path(exists=True,resolve_path=True),autocompletion=get_dir_name) def energy(wd):
EV = ExtractValue(wd) click.echo(EV.get_energy())
_fermi()) @cli.command('energy',short_help="Get total energy") @click.option('--wd','-w',default='.',help='your work direcroty',show_default=True, type=click.Path(exists=True,resolve_path=True),autocompletion=get_dir_name) def energy(wd):
64
64
76
60
4
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
energy
energy
68
73
68
71
bc8d7ceac194a9bf751dffd962aa2144f44f70ed
bigcode/the-stack
train
35032e5288387372413d481c
train
function
@cli.command('get_magnetic_config',short_help="Get magnetic configurations") @click.argument('poscar', metavar='<primitive_cell_file>', type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True), autocompletion=get_poscar_files) @click.option('--magnetic_atom', '-ma',...
@cli.command('get_magnetic_config',short_help="Get magnetic configurations") @click.argument('poscar', metavar='<primitive_cell_file>', type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True), autocompletion=get_poscar_files) @click.option('--magnetic_atom', '-ma',...
""" argument: poscar, the path of your initial POSCAR Optional parameter: magnetic_atom, specify a magnetic atom magmon, magmon magmon_identity, the equivalent atoms will have equivalent spins. (True or False) sympre: system precision Example: pyvasp get_magnetic_config POSCAR -...
@cli.command('get_magnetic_config',short_help="Get magnetic configurations") @click.argument('poscar', metavar='<primitive_cell_file>', type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True), autocompletion=get_poscar_files) @click.option('--magnetic_atom', '-ma',...
180
90
303
180
0
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
get_magnetic_config
get_magnetic_config
247
269
247
256
8f70126347b42f248be921a2bfdbe96629e5ad60
bigcode/the-stack
train
c20ef4cbd36f457bcb500ecb
train
function
@cli.command('incar',short_help="Prepare INCAR for vasp calculation") @click.option('--attribute','-a', default='', type=str) @click.option('--incar_file','-f', default=None, type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True)) def incar(attribute,incar_file): ''' Example: pyvasp...
@cli.command('incar',short_help="Prepare INCAR for vasp calculation") @click.option('--attribute','-a', default='', type=str) @click.option('--incar_file','-f', default=None, type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True)) def incar(attribute,incar_file):
''' Example: pyvasp incar -f INCAR -a NSW=100,EDIFF=1e-6 For more help you can refer to https://pyvaspflow.readthedocs.io/zh_CN/latest/incar.html ''' wi(incar_file=incar_file,kw=us.get_kw(attribute))
@cli.command('incar',short_help="Prepare INCAR for vasp calculation") @click.option('--attribute','-a', default='', type=str) @click.option('--incar_file','-f', default=None, type=click.Path(exists=True, resolve_path=True, readable=True, file_okay=True)) def incar(attribute,incar_file):
72
64
149
72
0
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
incar
incar
377
391
377
381
af6f18017ff9b92fde00190f5d520f147de09acc
bigcode/the-stack
train
140aa2ab75bb4b003d5d586d
train
function
@cli.command('electron_defect_free',short_help="Get electron number of defect free system") @click.option('--wd','-w',default='.',help='your work direcroty',show_default=True, type=click.Path(exists=True,resolve_path=True),autocompletion=get_dir_name) def electron_defect_free(wd): EV = ExtractValue(wd) click.ec...
@cli.command('electron_defect_free',short_help="Get electron number of defect free system") @click.option('--wd','-w',default='.',help='your work direcroty',show_default=True, type=click.Path(exists=True,resolve_path=True),autocompletion=get_dir_name) def electron_defect_free(wd):
EV = ExtractValue(wd) click.echo(EV.get_Ne_defect_free())
@cli.command('electron_defect_free',short_help="Get electron number of defect free system") @click.option('--wd','-w',default='.',help='your work direcroty',show_default=True, type=click.Path(exists=True,resolve_path=True),autocompletion=get_dir_name) def electron_defect_free(wd):
70
64
90
70
0
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
electron_defect_free
electron_defect_free
75
80
75
78
71ce409eff5eaf53c2da40716ebdab9054f655b4
bigcode/the-stack
train
53fa7741884ab12d81f422d2
train
function
@cli.command('test_encut',short_help="test encut in vasp calculation") @click.argument('poscar', type=str, autocompletion=get_poscar_files) @click.option('-start','-s', default=0.8,type=float) @click.option('--end','-e', default=1.3,type=float) @click.option('--step','-t', default=10,type=float) @click.option('--attrib...
@cli.command('test_encut',short_help="test encut in vasp calculation") @click.argument('poscar', type=str, autocompletion=get_poscar_files) @click.option('-start','-s', default=0.8,type=float) @click.option('--end','-e', default=1.3,type=float) @click.option('--step','-t', default=10,type=float) @click.option('--attrib...
''' Example: pyvasp test_encut POSCAR -s 0.8 -e 1.3 -t 30 For more help you can refer to https://pyvaspflow.readthedocs.io/zh_CN/latest/test_para.html#id2 ''' tp = test_para.TestParameter(poscar=poscar) kw = {'start':start,'end':end,'step':step,'is_login_node':is_login_node} kw.u...
@cli.command('test_encut',short_help="test encut in vasp calculation") @click.argument('poscar', type=str, autocompletion=get_poscar_files) @click.option('-start','-s', default=0.8,type=float) @click.option('--end','-e', default=1.3,type=float) @click.option('--step','-t', default=10,type=float) @click.option('--attrib...
127
74
248
127
0
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
test_encut
test_encut
681
701
681
688
d73dbeaf2d1086b25d5d5cfe70bebe1795f83393
bigcode/the-stack
train
b34f54a2083a766fa9616f4c
train
function
@cli.command('run_multi_vasp_from_shell',short_help="run multiple vasp calculations from shell scripts") @click.argument('shell_file', metavar='<shell scripts file>',nargs=1) @click.argument('end_job_num', metavar='<the last number of jobs>',nargs=1,autocompletion=get_run_end_job_num) @click.option('--work_name','-w', ...
@cli.command('run_multi_vasp_from_shell',short_help="run multiple vasp calculations from shell scripts") @click.argument('shell_file', metavar='<shell scripts file>',nargs=1) @click.argument('end_job_num', metavar='<the last number of jobs>',nargs=1,autocompletion=get_run_end_job_num) @click.option('--work_name','-w', ...
''' Example: nohup pyvasp run_multi_vasp_from_shell band.sh 9 -w job -p 5 1>std 2>err & For more help you can refer to https://pyvaspflow.readthedocs.io/zh_CN/latest/execute.html#execute-multiple-vasp-tasks ''' rmvws(work_name,shell_file,end_job_num=end_job_num,start_job_num=start_job_num...
@cli.command('run_multi_vasp_from_shell',short_help="run multiple vasp calculations from shell scripts") @click.argument('shell_file', metavar='<shell scripts file>',nargs=1) @click.argument('end_job_num', metavar='<the last number of jobs>',nargs=1,autocompletion=get_run_end_job_num) @click.option('--work_name','-w', ...
142
85
285
142
0
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
run_multi_vasp_from_shell
run_multi_vasp_from_shell
581
599
581
587
620b78b7ff30650646c9d28496a568f8b748bfe3
bigcode/the-stack
train
93829032388c9b2143e733c6
train
function
@cli.command('kill',short_help="kill the pyvasp and cancel jobs have been submitted") @click.argument('pid', metavar='pid_of_pyvasp',nargs=1) @click.option('--cancel_or_not','-c',default=True,type=bool) def kill(pid,cancel_or_not): parent = psutil.Process(int(pid)) for child in parent.children(recursive=True): ...
@cli.command('kill',short_help="kill the pyvasp and cancel jobs have been submitted") @click.argument('pid', metavar='pid_of_pyvasp',nargs=1) @click.option('--cancel_or_not','-c',default=True,type=bool) def kill(pid,cancel_or_not):
parent = psutil.Process(int(pid)) for child in parent.children(recursive=True): # or parent.children() for recursive=False child.kill() parent.kill() click.echo(pid) job_id_file = os.path.join(os.path.expanduser("~"),'.config','pyvaspflow',str(pid)) with open(job_id_file,'r') as f: ...
) @cli.command('kill',short_help="kill the pyvasp and cancel jobs have been submitted") @click.argument('pid', metavar='pid_of_pyvasp',nargs=1) @click.option('--cancel_or_not','-c',default=True,type=bool) def kill(pid,cancel_or_not):
64
64
180
63
1
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
kill
kill
784
799
784
787
7c3ff19cf25087e1f5c8d3cacc6cb6a0f50ca20e
bigcode/the-stack
train
b14225d87261fb3b2081bd87
train
function
@cli.command('prep_multi_vasp_from_file',short_help="Prepare necessary files for multiple vasp calculation") @click.argument('job_list_file', metavar='<job list file>',nargs=1) @click.option('--attribute','-a', default='', type=str) def prep_multi_vasp_from_file(attribute,job_list_file): ''' Example: pyvas...
@cli.command('prep_multi_vasp_from_file',short_help="Prepare necessary files for multiple vasp calculation") @click.argument('job_list_file', metavar='<job list file>',nargs=1) @click.option('--attribute','-a', default='', type=str) def prep_multi_vasp_from_file(attribute,job_list_file):
''' Example: pyvasp prep_multi_vasp_from_file -a kppa=4000,node_name=super_q,cpu_num=12,job_name=struc_opt job_list_file For more help you can refer to https://pyvaspflow.readthedocs.io/zh_CN/latest/prepare.html#prep-multi-vasp ''' job_list = np.loadtxt(job_list_file,dtype=int) pmv(jo...
@cli.command('prep_multi_vasp_from_file',short_help="Prepare necessary files for multiple vasp calculation") @click.argument('job_list_file', metavar='<job list file>',nargs=1) @click.option('--attribute','-a', default='', type=str) def prep_multi_vasp_from_file(attribute,job_list_file):
67
64
177
67
0
Warmshawn/pyvaspflow
pyvaspflow/pyvasp.py
Python
prep_multi_vasp_from_file
prep_multi_vasp_from_file
500
514
500
503
7a9766aee9fa8980d2559346388e82abf54a0962
bigcode/the-stack
train