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
d804e3cb5191ebb02458ee39
train
function
def plot_deadtime(etable): 'Plot histogram of detector deadtime in microseconds.' us = etable['DEADTIME']*1.0e6 # Bin at 1 us resolution max = np.floor(us.max())+1 plot.hist(us,range=(0.0,max), bins=int(max),log=True) #plot.ticklabel_format(style = 'sci', axis='x', scilimits = (0,0)) plot.ti...
def plot_deadtime(etable):
'Plot histogram of detector deadtime in microseconds.' us = etable['DEADTIME']*1.0e6 # Bin at 1 us resolution max = np.floor(us.max())+1 plot.hist(us,range=(0.0,max), bins=int(max),log=True) #plot.ticklabel_format(style = 'sci', axis='x', scilimits = (0,0)) plot.title('Histogram of deadtime'...
avetxt(file('powspec.txt','w'), data, fmt=['%f','%f']) plot.title('Power Spectrum') plot.xlabel('Frequency') plot.ylabel('Power') return #-------------------------------THIS PLOTS THE DEADTIME HISTOGRAM------------------ def plot_deadtime(etable):
64
64
132
7
57
juliadeneva/NICERsoft
nicer/plotutils.py
Python
plot_deadtime
plot_deadtime
401
412
401
401
578381068b2084c079f96cd5757d26d45e43d94a
bigcode/the-stack
train
9bd1c0a5122aa36574dc5af8
train
function
def choose_N(orig_N): """ choose_N(orig_N): Choose a time series length that is larger than the input value but that is highly factorable. Note that the returned value must be divisible by at least the maximum downsample factor * 2. Currently, this is 8 * ...
def choose_N(orig_N):
""" choose_N(orig_N): Choose a time series length that is larger than the input value but that is highly factorable. Note that the returned value must be divisible by at least the maximum downsample factor * 2. Currently, this is 8 * 2 = 16. """ # ...
.yscale('log') plot.xscale('log') plot.xlim((0.1,20.0)) # Default option if plot_pos is None: plot.title('PI Spectrum') plot.xlabel('Energy (keV)') plot.ylabel('Counts/keV') ## Options for plot_all_spec if plot_pos == "corner": plot.xlabel('Energy (keV)') ...
220
220
734
6
214
juliadeneva/NICERsoft
nicer/plotutils.py
Python
choose_N
choose_N
323
363
323
323
4f5e0b08556f3020cb3349794283cf1fa40301c0
bigcode/the-stack
train
6e3d81f149e42e57585a83fd
train
function
def ordered_iteritems(adict): keys = list(adict.keys()) order = nm.argsort(keys) for ii in order: key = keys[ii] yield key, adict[key]
def ordered_iteritems(adict):
keys = list(adict.keys()) order = nm.argsort(keys) for ii in order: key = keys[ii] yield key, adict[key]
[1] setattr(new_val, replace[0], new_attr) else: new_attr = replace[1].get(val.name, old_attr) setattr(new_val, replace[0], new_attr) objs[key] = new_val return objs def ordered_iteritems(adict):
64
64
43
7
56
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
ordered_iteritems
ordered_iteritems
1,448
1,453
1,448
1,448
4478f7b4346e97f4a6672f15480ec9261d89b6c7
bigcode/the-stack
train
f39f69e3154a97b4dd94bbf0
train
class
class Container(Struct): def __init__(self, objs=None, **kwargs): Struct.__init__(self, **kwargs) if objs is not None: self._objs = objs self.update() else: self._objs = [] self.names = [] def update(self, objs=None): if objs is ...
class Container(Struct):
def __init__(self, objs=None, **kwargs): Struct.__init__(self, **kwargs) if objs is not None: self._objs = objs self.update() else: self._objs = [] self.names = [] def update(self, objs=None): if objs is not None: self...
, dict): other = other.to_dict() self.__dict__.update(other, **kwargs) def set_default(self, key, default=None): """ Behaves like dict.setdefault(). """ return self.__dict__.setdefault(key, default) def copy(self, deep=False, name=None): """Make a (d...
256
256
994
5
250
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
Container
Container
540
714
540
541
8809e1af567497ba1cd2323a92795271a6c8f44f
bigcode/the-stack
train
88def831869ea7c2614d166e
train
function
def insert_as_static_method(cls, name, function): setattr(cls, name, staticmethod(function))
def insert_as_static_method(cls, name, function):
setattr(cls, name, staticmethod(function))
= MethodType(function, instance) else: meth = MethodType(function, instance, type(instance)) setattr(instance, function.__name__, meth) def use_method_with_name(instance, method, new_name): setattr(instance, new_name, method) def insert_as_static_method(cls, name, function):
64
64
21
11
53
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
insert_as_static_method
insert_as_static_method
1,103
1,104
1,103
1,103
a49f76e02eb1903e0b79eb588dd6ed8791fb1895
bigcode/the-stack
train
c92b2f84efbc85c0eb581923
train
function
def ipython_shell(frame=0): from IPython.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() ipshell(stack_depth=frame+1)
def ipython_shell(frame=0):
from IPython.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() ipshell(stack_depth=frame+1)
: msgs.append(fail_msg) raise ValueError('\n'.join(msgs)) return locals() def python_shell(frame=0): import code frame = sys._getframe(frame+1) code.interact(local=frame.f_locals) def ipython_shell(frame=0):
64
64
38
8
56
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
ipython_shell
ipython_shell
232
236
232
232
6fe740f9a46147b6f4f010b1000fb6416b8f5482
bigcode/the-stack
train
a99e24b02979ca3ab255cb69
train
function
def get_default_attr(obj, attr, default, msg_if_none=None): if hasattr(obj, attr): out = getattr(obj, attr) else: out = default if (out is None) and (msg_if_none is not None): raise ValueError(msg_if_none) return out
def get_default_attr(obj, attr, default, msg_if_none=None):
if hasattr(obj, attr): out = getattr(obj, attr) else: out = default if (out is None) and (msg_if_none is not None): raise ValueError(msg_if_none) return out
if (out is None) and (msg_if_none is not None): raise ValueError(msg_if_none) return out ## # c: 28.04.2008, r: 28.04.2008 def get_default_attr(obj, attr, default, msg_if_none=None):
64
64
66
15
48
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
get_default_attr
get_default_attr
1,386
1,395
1,386
1,386
550d6c8826720e4a24e6a7f539f409ed1a292164
bigcode/the-stack
train
8d64a08a05bad6ea7d219c81
train
function
def structify(obj): """ Convert a (nested) dict `obj` into a (nested) Struct. """ out = Struct(**obj) for key, val in out.to_dict().items(): if isinstance(val, dict): out.__dict__[key] = structify(val) return out
def structify(obj):
""" Convert a (nested) dict `obj` into a (nested) Struct. """ out = Struct(**obj) for key, val in out.to_dict().items(): if isinstance(val, dict): out.__dict__[key] = structify(val) return out
: if flag[level]: aux.__dict__[key] = val else: aux[key] = val out.append(aux) else: out.append(arg) if len(out) == 1: out = out[0] return out def structify(obj):
64
64
68
5
58
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
structify
structify
1,053
1,061
1,053
1,053
0d11e46f9c717b04a51de36c67c1300e9b26b9e7
bigcode/the-stack
train
878cc7f09e32eaa3d5b6c8de
train
function
def is_derived_class(cls, parent): return issubclass(cls, parent) and (cls is not parent)
def is_derived_class(cls, parent):
return issubclass(cls, parent) and (cls is not parent)
)) ## # 23.01.2006, c def is_sequence(var): from collections import Sequence if isinstance(var, basestr): return False return isinstance(var, Sequence) ## # 17.10.2007, c def is_derived_class(cls, parent):
64
64
25
9
54
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
is_derived_class
is_derived_class
1,083
1,084
1,083
1,083
46c618930271f2b8053a4a38dfe401e8663062ca
bigcode/the-stack
train
cb4b79b6c828cc2627e45169
train
function
def as_float_or_complex(val): """ Try to cast val to Python float, and if this fails, to Python complex type. """ success = False try: out = float(val) except: pass else: success = True if not success: try: out = complex(val) excep...
def as_float_or_complex(val):
""" Try to cast val to Python float, and if this fails, to Python complex type. """ success = False try: out = float(val) except: pass else: success = True if not success: try: out = complex(val) except: pass el...
(adict[ik[0]]) out = nm.empty((ik.max() + 1,) + aux.shape, dtype=aux.dtype) out.fill(-1) for key, val in six.iteritems(adict): out[key] = val return out def as_float_or_complex(val):
64
64
114
7
56
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
as_float_or_complex
as_float_or_complex
1,475
1,499
1,475
1,475
29b0e378716fd9dba498ad15f5e7a06d9fd3c8f1
bigcode/the-stack
train
3bc22253723ffbd15e1bfb85
train
class
class Output(Struct): """ Factory class providing output (print) functions. All SfePy printing should be accomplished by this class. Examples -------- >>> from sfepy.base.base import Output >>> output = Output('sfepy:') >>> output(1, 2, 3, 'hello') sfepy: 1 2 3 hello >>> output....
class Output(Struct):
""" Factory class providing output (print) functions. All SfePy printing should be accomplished by this class. Examples -------- >>> from sfepy.base.base import Output >>> output = Output('sfepy:') >>> output(1, 2, 3, 'hello') sfepy: 1 2 3 hello >>> output.prefix = 'my_cool_app:...
# 21.11.2005, c def __getitem__(self, ii): if isinstance(ii, int): return list.__getitem__(self, ii) elif isinstance(ii, basestr): ir = self.find(ii, ret_indx=True) if ir: return list.__getitem__(self, ir[0]) else: rais...
256
256
1,096
5
251
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
Output
Output
779
956
779
779
2a9e00b54e39aa63c7fa0d65a33e15e90fc88735
bigcode/the-stack
train
e062477ec745f8d127baf0e7
train
function
def load_classes(filenames, classes, package_name=None, ignore_errors=False, name_attr='name'): """ For each filename in filenames, load all subclasses of classes listed. """ table = {} for filename in filenames: if not ignore_errors: mod = import_file(filename, ...
def load_classes(filenames, classes, package_name=None, ignore_errors=False, name_attr='name'):
""" For each filename in filenames, load all subclasses of classes listed. """ table = {} for filename in filenames: if not ignore_errors: mod = import_file(filename, package_name=package_name, can_reload=False) else: try: ...
omit_unnamed: continue else: key = var.__class__.__name__ table[key] = var break except TypeError: pass return table def load_classes(filenames, classes, package_name=None, ignore_erro...
64
64
159
22
41
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
load_classes
load_classes
1,142
1,166
1,142
1,143
2be134b4f6f625ce437847fa250d4c71be5b8c50
bigcode/the-stack
train
1d3611478b6e3d7f13f953d6
train
function
def invert_dict(d, is_val_tuple=False, unique=True): """ Invert a dictionary by making its values keys and vice versa. Parameters ---------- d : dict The input dictionary. is_val_tuple : bool If True, the `d` values are tuples and new keys are the tuple items. unique : bool ...
def invert_dict(d, is_val_tuple=False, unique=True):
""" Invert a dictionary by making its values keys and vice versa. Parameters ---------- d : dict The input dictionary. is_val_tuple : bool If True, the `d` values are tuples and new keys are the tuple items. unique : bool If True, the `d` values are unique and so the...
)) else: assert_(len(old) == len(new)) new_dict = dict(str_dict) for ii, _old in enumerate(old): new_dict.update(edit_dict_strings(new_dict, _old, new[ii], recur=recur)) return new_dict def invert_dict(d, is_val_tuple=False, un...
71
71
237
13
57
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
invert_dict
invert_dict
1,290
1,330
1,290
1,290
9849d239f1a1b46d04abb4c4d3725158ca7d9ecf
bigcode/the-stack
train
0ffb9a3847687088478cdd86
train
function
def remap_dict(d, map): """ Utility function to remap state dict keys according to var_map. """ out = {} for new_key, key in six.iteritems(map): out[new_key] = d[key] return out
def remap_dict(d, map):
""" Utility function to remap state dict keys according to var_map. """ out = {} for new_key, key in six.iteritems(map): out[new_key] = d[key] return out
: di[val] = key else: if is_val_tuple: for v in val: item = di.setdefault(v, []) item.append(key) else: item = di.setdefault(val, []) item.append(key) return di def remap_dict(d...
64
64
54
8
55
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
remap_dict
remap_dict
1,332
1,340
1,332
1,332
522324ea946f7e3bc673811d02fa0ca0306ee895
bigcode/the-stack
train
d94d0d357ba68c6821efd1b1
train
function
def get_default(arg, default, msg_if_none=None): if arg is None: out = default else: out = arg if (out is None) and (msg_if_none is not None): raise ValueError(msg_if_none) return out
def get_default(arg, default, msg_if_none=None):
if arg is None: out = default else: out = arg if (out is None) and (msg_if_none is not None): raise ValueError(msg_if_none) return out
adict) def set_defaults(dict_, defaults): for key, val in six.iteritems(defaults): dict_.setdefault(key, val) ## # c: 12.03.2007, r: 04.04.2008 def get_default(arg, default, msg_if_none=None):
64
64
59
12
51
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
get_default
get_default
1,373
1,382
1,373
1,373
c5fc01b4eabd90295a65b3adbd97e5ba38474279
bigcode/the-stack
train
cd1949651954e97cb0c794e8
train
function
def print_structs(objs): """Print Struct instances in a container, works recursively. Debugging utility function.""" if isinstance(objs, dict): for key, vals in six.iteritems(objs): print(key) print_structs(vals) elif isinstance(objs, list): for vals in objs: ...
def print_structs(objs):
"""Print Struct instances in a container, works recursively. Debugging utility function.""" if isinstance(objs, dict): for key, vals in six.iteritems(objs): print(key) print_structs(vals) elif isinstance(objs, list): for vals in objs: print_structs(val...
""" output_screen = options.get('output_screen', True) output_log_name = options.get('output_log_name', None) output.set_output(filename=output_log_name, quiet=not output_screen, combined=output_screen and (output_log_name is not None)) def print_structs(objs):
64
64
83
7
57
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
print_structs
print_structs
977
988
977
977
92f5e0df0f08fd258e81fcbbc163e627ebc3e351
bigcode/the-stack
train
fcdd39b4528e07a07b645ccf
train
function
def check_names(names1, names2, msg): """Check if all names in names1 are in names2, otherwise raise IndexError with the provided message msg. """ names = set(names1) both = names.intersection(names2) if both != names: missing = ', '.join(ii for ii in names.difference(both)) rais...
def check_names(names1, names2, msg):
"""Check if all names in names1 are in names2, otherwise raise IndexError with the provided message msg. """ names = set(names1) both = names.intersection(names2) if both != names: missing = ', '.join(ii for ii in names.difference(both)) raise IndexError(msg % missing)
omit = [] _args, _, _, _vars = getargvalues(stack()[1][0]) args = {} for name in _args: if name in omit: continue args[name] = _vars[name] return args def check_names(names1, names2, msg):
64
64
85
11
52
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
check_names
check_names
1,418
1,426
1,418
1,418
bb963c44590e9dbf125bf2261fe6af375796d0e4
bigcode/the-stack
train
893a45100c5de42ca3941ba8
train
function
def edit_dict_strings(str_dict, old, new, recur=False): """ Replace substrings `old` with `new` in string values of dictionary `str_dict`. Both `old` and `new` can be lists of the same length - items in `old` are replaced by items in `new` with the same index. Parameters ---------- str_dict...
def edit_dict_strings(str_dict, old, new, recur=False):
""" Replace substrings `old` with `new` in string values of dictionary `str_dict`. Both `old` and `new` can be lists of the same length - items in `old` are replaced by items in `new` with the same index. Parameters ---------- str_dict : dict The dictionary with string values or tup...
new_tuple : tuple The tuple with edited strings. """ new_tuple = [] for item in str_tuple: if isinstance(item, basestr): item = item.replace(old, new) elif recur and isinstance(item, tuple): item = edit_tuple_strings(item, old, new, recur=True) new_...
93
93
313
14
79
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
edit_dict_strings
edit_dict_strings
1,246
1,288
1,246
1,246
a2225317ea104012480e85f01192250cfa7f5ea8
bigcode/the-stack
train
25139dff5700c5fc047e47f6
train
function
def assert_(condition, msg='assertion failed!'): if not condition: raise ValueError(msg)
def assert_(condition, msg='assertion failed!'):
if not condition: raise ValueError(msg)
=0): """ Embed an IPython (if available) or regular Python shell in the given frame. """ try: ipython_shell(frame=frame+2) except ImportError: python_shell(frame=frame+1) def assert_(condition, msg='assertion failed!'):
64
64
23
12
52
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
assert_
assert_
248
250
248
248
3c72e4e17a2c95a16e8b4cba3fcf4a17d22532ee
bigcode/the-stack
train
cf4834a8a2dc6c39d0b19595
train
function
def import_file(filename, package_name=None, can_reload=True): """ Import a file as a module. The module is explicitly reloaded to prevent undesirable interactions. """ from sfepy import base_dir top_dir = os.path.normpath(os.path.join(base_dir, '..')) path = os.path.dirname(os.path.normpat...
def import_file(filename, package_name=None, can_reload=True):
""" Import a file as a module. The module is explicitly reloaded to prevent undesirable interactions. """ from sfepy import base_dir top_dir = os.path.normpath(os.path.join(base_dir, '..')) path = os.path.dirname(os.path.normpath(os.path.realpath(filename))) if (package_name is None) a...
0.10000000000000001, 0.050000000000000003] """ tt = time.clock() times.append(tt) if (msg is not None) and (len(times) > 1): print(msg, times[-1] - times[-2]) def import_file(filename, package_name=None, can_reload=True):
75
75
251
13
62
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
import_file
import_file
152
192
152
152
b5474470496068a8141ee1a4785feee692b96d2d
bigcode/the-stack
train
a1b33b8b8a0e0c06ab6a1721
train
function
def iter_dict_of_lists(dol, return_keys=False): for key, vals in six.iteritems(dol): for ii, val in enumerate(vals): if return_keys: yield key, ii, val else: yield val
def iter_dict_of_lists(dol, return_keys=False):
for key, vals in six.iteritems(dol): for ii, val in enumerate(vals): if return_keys: yield key, ii, val else: yield val
, dict): for key, vals in six.iteritems(objs): print(key) print_structs(vals) elif isinstance(objs, list): for vals in objs: print_structs(vals) else: print(objs) def iter_dict_of_lists(dol, return_keys=False):
64
64
52
12
52
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
iter_dict_of_lists
iter_dict_of_lists
990
996
990
990
dde12091b306b7788dae43dcf745139b203abecc
bigcode/the-stack
train
46f9a6874995fe35a02e6acc
train
function
def python_shell(frame=0): import code frame = sys._getframe(frame+1) code.interact(local=frame.f_locals)
def python_shell(frame=0):
import code frame = sys._getframe(frame+1) code.interact(local=frame.f_locals)
: try: exec(imp) break except Exception as inst: msgs.append(str(inst)) else: if fail_msg is not None: msgs.append(fail_msg) raise ValueError('\n'.join(msgs)) return locals() def python_shell(frame=0):
64
64
33
7
57
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
python_shell
python_shell
227
230
227
227
9b5193959bf831e438ea5b5498405114b19d1d25
bigcode/the-stack
train
2ad0b07fe5f2c8b82b2dbb9e
train
function
def find_subclasses(context, classes, omit_unnamed=False, name_attr='name'): """Find subclasses of the given classes in the given context. Examples -------- >>> solver_table = find_subclasses(vars().items(), [LinearSolver, NonlinearSolver, ...
def find_subclasses(context, classes, omit_unnamed=False, name_attr='name'):
"""Find subclasses of the given classes in the given context. Examples -------- >>> solver_table = find_subclasses(vars().items(), [LinearSolver, NonlinearSolver, TimeSteppingSolver, EigenvalueSolver, ...
__, meth) def use_method_with_name(instance, method, new_name): setattr(instance, new_name, method) def insert_as_static_method(cls, name, function): setattr(cls, name, staticmethod(function)) def find_subclasses(context, classes, omit_unnamed=False, name_attr='name'):
64
64
189
19
45
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
find_subclasses
find_subclasses
1,106
1,140
1,106
1,106
74c74198303b17693649a0ff73317d6260245e84
bigcode/the-stack
train
3b4c00a4d39b7269d2fd157d
train
function
def spause(msg=None): """ Waits for a keypress. If you press: "q" ............. it will call sys.exit() any other key ... it will continue execution of the program This is useful for debugging. This function is called from pause(). """ if (msg): print(msg) sys.stdout.flush(...
def spause(msg=None):
""" Waits for a keypress. If you press: "q" ............. it will call sys.exit() any other key ... it will continue execution of the program This is useful for debugging. This function is called from pause(). """ if (msg): print(msg) sys.stdout.flush() ch = getch() ...
d: %s(), %d' % (ff.co_filename, ff.co_firstlineno, ff.co_name, f.f_lineno)) spause() ## # Silent pause. # 18.02.2005, c # 12.02.2007 def spause(msg=None):
64
64
93
6
57
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
spause
spause
278
293
278
278
2742ce8f47e85967cb15f5d783f44c5dca074a63
bigcode/the-stack
train
0370eae034efb4ba80a408d2
train
function
def get_subdict(adict, keys): """ Get a sub-dictionary of `adict` with given `keys`. """ return dict((key, adict[key]) for key in keys if key in adict)
def get_subdict(adict, keys):
""" Get a sub-dictionary of `adict` with given `keys`. """ return dict((key, adict[key]) for key in keys if key in adict)
key in keys: out[key] = seq_class() return out ## # 16.10.2006, c def dict_extend(d1, d2): for key, val in six.iteritems(d1): val.extend(d2[key]) def get_subdict(adict, keys):
64
64
49
9
55
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
get_subdict
get_subdict
1,361
1,365
1,361
1,361
f9ca7ae07eb1f7ff475a9a46e36a95060fae1151
bigcode/the-stack
train
9101faa62379d5ede363d64d
train
function
def pause(msg=None): """ Prints the line number and waits for a keypress. If you press: "q" ............. it will call sys.exit() any other key ... it will continue execution of the program This is useful for debugging. """ f = sys._getframe(1) ff = f.f_code if (msg): p...
def pause(msg=None):
""" Prints the line number and waits for a keypress. If you press: "q" ............. it will call sys.exit() any other key ... it will continue execution of the program This is useful for debugging. """ f = sys._getframe(1) ff = f.f_code if (msg): print('%s, %d: %s(), %...
except ImportError: python_shell(frame=frame+1) def assert_(condition, msg='assertion failed!'): if not condition: raise ValueError(msg) ## # c: 06.04.2005, r: 05.05.2008 def pause(msg=None):
64
64
162
5
58
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
pause
pause
254
272
254
254
1d7e586550314a721e05db986854080422c62128
bigcode/the-stack
train
5d469cad549f7e9a41033fe2
train
function
def get_debug(): """ Utility function providing ``debug()`` function. """ try: import IPython except ImportError: debug = None else: old_excepthook = sys.excepthook def debug(frame=None, frames_back=1): if IPython.__version__ >= '0.11': ...
def get_debug():
""" Utility function providing ``debug()`` function. """ try: import IPython except ImportError: debug = None else: old_excepthook = sys.excepthook def debug(frame=None, frames_back=1): if IPython.__version__ >= '0.11': from IPython....
64] complex_types = [nm.complex128] nm.set_printoptions(threshold=100) from sfepy.base.goptions import goptions sfepy_config_dir = os.path.expanduser('~/.sfepy') if not os.path.exists(sfepy_config_dir): os.makedirs(sfepy_config_dir) if sys.version_info[0] < 3: PY3 = False basestr = basestring else: ...
105
105
352
4
100
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
get_debug
get_debug
32
95
32
32
83bf5d2d27975a8fb990e2d6bcf416686f36e2ca
bigcode/the-stack
train
314781d208a7aaca17d35c75
train
function
def insert_method(instance, function): if PY3: meth = MethodType(function, instance) else: meth = MethodType(function, instance, type(instance)) setattr(instance, function.__name__, meth)
def insert_method(instance, function):
if PY3: meth = MethodType(function, instance) else: meth = MethodType(function, instance, type(instance)) setattr(instance, function.__name__, meth)
ubclass(cls, parent) and (cls is not parent) ## # 23.10.2007, c def insert_static_method(cls, function): setattr(cls, function.__name__, staticmethod(function)) ## # 23.10.2007, c def insert_method(instance, function):
64
64
46
7
56
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
insert_method
insert_method
1,093
1,098
1,093
1,093
5f7c19aeb44e91482e4a6b5a082449e3d81651ba
bigcode/the-stack
train
bc750686fd142e6b709ec3f7
train
function
def try_imports(imports, fail_msg=None): """ Try import statements until one succeeds. Parameters ---------- imports : list The list of import statements. fail_msg : str If not None and no statement succeeds, a `ValueError` is raised with the given message, appended to a...
def try_imports(imports, fail_msg=None):
""" Try import statements until one succeeds. Parameters ---------- imports : list The list of import statements. fail_msg : str If not None and no statement succeeds, a `ValueError` is raised with the given message, appended to all failed messages. Returns ----...
__(name) if (name in sys.modules) and can_reload: if PY3: import importlib importlib.reload(mod) else: reload(mod) if remove_path: sys.path.remove(path) return mod def try_imports(imports, fail_msg=None):
64
64
158
11
52
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
try_imports
try_imports
194
225
194
194
92cec96262598645312ca470d6fd9cf241774cb6
bigcode/the-stack
train
65c51d13f7947a6d4eac9ce1
train
function
def dict_extend(d1, d2): for key, val in six.iteritems(d1): val.extend(d2[key])
def dict_extend(d1, d2):
for key, val in six.iteritems(d1): val.extend(d2[key])
(keys, seq_class=None): if seq_class is None: return {}.fromkeys(keys) out = {} for key in keys: out[key] = seq_class() return out ## # 16.10.2006, c def dict_extend(d1, d2):
64
64
27
9
54
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
dict_extend
dict_extend
1,357
1,359
1,357
1,357
0ca898166d1f08ec6902b1ee8b0bfd582c58eb6b
bigcode/the-stack
train
019c17c4733b9c54115a0315
train
function
def dict_to_struct(*args, **kwargs): """Convert a dict instance to a Struct instance.""" try: level = kwargs['level'] except: level = 0 try: flag = kwargs['flag'] except: flag = (1,) # For level 0 only... try: constructor = kwargs['constructor'] ...
def dict_to_struct(*args, **kwargs):
"""Convert a dict instance to a Struct instance.""" try: level = kwargs['level'] except: level = 0 try: flag = kwargs['flag'] except: flag = (1,) # For level 0 only... try: constructor = kwargs['constructor'] except: constructor = Struct ...
for key, vals in six.iteritems(dol): for ii, val in enumerate(vals): if return_keys: yield key, ii, val else: yield val ## # 19.07.2005, c # 26.05.2006 # 17.10.2007 def dict_to_struct(*args, **kwargs):
80
80
268
10
69
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
dict_to_struct
dict_to_struct
1,002
1,051
1,002
1,002
dc2f71a7ffc81021ad94e6152ef76621dfe3488f
bigcode/the-stack
train
bec32696993079181dfead3f
train
function
def is_integer(var): if PY3: return isinstance(var, int) else: return isinstance(var, (int, long))
def is_integer(var):
if PY3: return isinstance(var, int) else: return isinstance(var, (int, long))
Struct. """ out = Struct(**obj) for key, val in out.to_dict().items(): if isinstance(val, dict): out.__dict__[key] = structify(val) return out def is_string(var): return isinstance(var, basestr) def is_integer(var):
64
64
30
5
59
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
is_integer
is_integer
1,066
1,071
1,066
1,066
d09bbff8d722664e76c769701684edd1cdc44285
bigcode/the-stack
train
30e57d520601fdb6c21337e4
train
function
def set_defaults(dict_, defaults): for key, val in six.iteritems(defaults): dict_.setdefault(key, val)
def set_defaults(dict_, defaults):
for key, val in six.iteritems(defaults): dict_.setdefault(key, val)
): val.extend(d2[key]) def get_subdict(adict, keys): """ Get a sub-dictionary of `adict` with given `keys`. """ return dict((key, adict[key]) for key in keys if key in adict) def set_defaults(dict_, defaults):
64
64
27
7
57
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
set_defaults
set_defaults
1,367
1,369
1,367
1,367
b5ba95cedb0fc278f06267d22fbb0c4309f07f7e
bigcode/the-stack
train
4cfcf8346336d0d24919f65d
train
function
def insert_static_method(cls, function): setattr(cls, function.__name__, staticmethod(function))
def insert_static_method(cls, function):
setattr(cls, function.__name__, staticmethod(function))
return isinstance(var, Sequence) ## # 17.10.2007, c def is_derived_class(cls, parent): return issubclass(cls, parent) and (cls is not parent) ## # 23.10.2007, c def insert_static_method(cls, function):
64
64
20
8
55
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
insert_static_method
insert_static_method
1,088
1,089
1,088
1,088
6fb1662f091e5111118426883c00996833c265a1
bigcode/the-stack
train
89b27f31641af465c840106d
train
function
def dict_from_keys_init(keys, seq_class=None): if seq_class is None: return {}.fromkeys(keys) out = {} for key in keys: out[key] = seq_class() return out
def dict_from_keys_init(keys, seq_class=None):
if seq_class is None: return {}.fromkeys(keys) out = {} for key in keys: out[key] = seq_class() return out
_map. """ out = {} for new_key, key in six.iteritems(map): out[new_key] = d[key] return out ## # 24.08.2006, c # 05.09.2006 def dict_from_keys_init(keys, seq_class=None):
64
64
48
11
52
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
dict_from_keys_init
dict_from_keys_init
1,345
1,353
1,345
1,346
4a1b3209861b9d874d38626082bf7a805dd452ad
bigcode/the-stack
train
3b70c29109c8e29c9be56fa1
train
function
def shell(frame=0): """ Embed an IPython (if available) or regular Python shell in the given frame. """ try: ipython_shell(frame=frame+2) except ImportError: python_shell(frame=frame+1)
def shell(frame=0):
""" Embed an IPython (if available) or regular Python shell in the given frame. """ try: ipython_shell(frame=frame+2) except ImportError: python_shell(frame=frame+1)
= sys._getframe(frame+1) code.interact(local=frame.f_locals) def ipython_shell(frame=0): from IPython.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() ipshell(stack_depth=frame+1) def shell(frame=0):
64
64
55
6
58
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
shell
shell
238
246
238
238
07d941faeaf97634e39f7812f95e1c016f462092
bigcode/the-stack
train
e3fb89503181c82333f273e5
train
function
def configure_output(options): """ Configure the standard :func:`output()` function using `output_log_name` and `output_screen` attributes of `options`. Parameters ---------- options : Struct or dict The options with `output_screen` and `output_log_name` items. Defaults are prov...
def configure_output(options):
""" Configure the standard :func:`output()` function using `output_log_name` and `output_screen` attributes of `options`. Parameters ---------- options : Struct or dict The options with `output_screen` and `output_log_name` items. Defaults are provided if missing. """ ou...
basestr)) if len(prefix) > 0: prefix += ' ' self._prefix = prefix def get_output_prefix(self): return self._prefix[:-1] prefix = property(get_output_prefix, set_output_prefix) output = Output('sfepy:') def configure_output(options):
63
64
129
5
59
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
configure_output
configure_output
960
975
960
960
cb68f0d9230cbc6a1c21d74042e22e0e67fb7e7f
bigcode/the-stack
train
83e28bfb9ca97f7cf4b580dc
train
class
class IndexedStruct(Struct): ## # 12.07.2007, c def __getitem__(self, key): return getattr(self, key) ## # 12.07.2007, c def __setitem__(self, key, val): setattr(self, key, val)
class IndexedStruct(Struct): ## # 12.07.2007, c
def __getitem__(self, key): return getattr(self, key) ## # 12.07.2007, c def __setitem__(self, key, val): setattr(self, key, val)
other = copy(self) if hasattr(self, 'name'): other.name = get_default(name, self.name + '_copy') return other # # 12.07.2007, c class IndexedStruct(Struct): ## # 12.07.2007, c
64
64
70
20
43
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
IndexedStruct
IndexedStruct
526
536
526
529
be76d44b0f927153aa089fca907971a417ebb943
bigcode/the-stack
train
eddcb2ad187270558a42d404
train
function
def select_by_names(objs_all, names, replace=None, simple=True): objs = {} for key, val in six.iteritems(objs_all): if val.name in names: if replace is None: objs[key] = val else: new_val = copy(val) old_attr = getattr(val, replace[...
def select_by_names(objs_all, names, replace=None, simple=True):
objs = {} for key, val in six.iteritems(objs_all): if val.name in names: if replace is None: objs[key] = val else: new_val = copy(val) old_attr = getattr(val, replace[0]) if simple: new_attr = old...
names: missing = ', '.join(ii for ii in names.difference(both)) raise IndexError(msg % missing) ## # c: 27.02.2008, r: 27.02.2008 def select_by_names(objs_all, names, replace=None, simple=True):
64
64
142
16
47
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
select_by_names
select_by_names
1,430
1,446
1,430
1,430
edefcf7ce51e797da017ab8eb823e8dffa800923
bigcode/the-stack
train
40a699d2a137ae72cb4d25b8
train
function
def update_dict_recursively(dst, src, tuples_too=False, overwrite_by_none=True): """ Update `dst` dictionary recursively using items in `src` dictionary. Parameters ---------- dst : dict The destination dictionary. src : dict The source dictionary. ...
def update_dict_recursively(dst, src, tuples_too=False, overwrite_by_none=True):
""" Update `dst` dictionary recursively using items in `src` dictionary. Parameters ---------- dst : dict The destination dictionary. src : dict The source dictionary. tuples_too : bool If True, recurse also into dictionaries that are members of tuples. overwrite...
_name, can_reload=False) except: output('WARNING: module %s cannot be imported!' % filename) output('reason:\n', sys.exc_info()[1]) continue table.update(find_subclasses(vars(mod), classes, omit_unnamed=True, ...
88
88
295
20
67
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
update_dict_recursively
update_dict_recursively
1,168
1,211
1,168
1,169
c32eaa87345258b78a003427248aff5b46e2225f
bigcode/the-stack
train
efe1005a7861f346550af8db
train
function
def mark_time(times, msg=None): """ Time measurement utility. Measures times of execution between subsequent calls using time.clock(). The time is printed if the msg argument is not None. Examples -------- >>> times = [] >>> mark_time(times) ... do something >>> mark_time(time...
def mark_time(times, msg=None):
""" Time measurement utility. Measures times of execution between subsequent calls using time.clock(). The time is printed if the msg argument is not None. Examples -------- >>> times = [] >>> mark_time(times) ... do something >>> mark_time(times, 'elapsed') elapsed 0.1 ...
are NOT in interactive mode, print the exception... traceback.print_exception(etype, value, tb) print() # ...then start the debugger in post-mortem mode. pdb.post_mortem(tb) sys.excepthook = except_hook def mark_time(times, msg=None):
64
64
171
8
55
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
mark_time
mark_time
126
150
126
126
07a52d8218e0ae779643e1dafee5ebaa7d5c9d85
bigcode/the-stack
train
a9ad720dc7747dfa82fae25b
train
function
def use_method_with_name(instance, method, new_name): setattr(instance, new_name, method)
def use_method_with_name(instance, method, new_name):
setattr(instance, new_name, method)
.2007, c def insert_method(instance, function): if PY3: meth = MethodType(function, instance) else: meth = MethodType(function, instance, type(instance)) setattr(instance, function.__name__, meth) def use_method_with_name(instance, method, new_name):
64
64
21
12
52
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
use_method_with_name
use_method_with_name
1,100
1,101
1,100
1,100
26ce851620dc902f73fb63658c4ad47cdb0daa70
bigcode/the-stack
train
43663fa83da7fafda22e6354
train
function
def debug_on_error(): """ Start debugger at the line where an exception was raised. """ try: from IPython.core import ultratb except_hook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1) except ImportError: de...
def debug_on_error():
""" Start debugger at the line where an exception was raised. """ try: from IPython.core import ultratb except_hook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1) except ImportError: def except_hook(etype, v...
IPython`-enabled debugger using the `IPython` API. When this fails, the plain old `pdb` is used instead. With IPython, one can say in what frame the debugger can stop. """ return debug debug = get_debug() def debug_on_error():
64
64
201
5
59
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
debug_on_error
debug_on_error
99
124
99
99
d57d7164fb03e61d5addd67c661ec7d6a19d6e15
bigcode/the-stack
train
5b762b74d3142891194df8bd
train
class
class Struct(object): # 03.10.2005, c # 26.10.2005 def __init__(self, **kwargs): if kwargs: self.__dict__.update(kwargs) def _format_sequence(self, seq, threshold): threshold_half = threshold // 2 if len(seq) > threshold: out = ', '.join(str(ii) for ii i...
class Struct(object): # 03.10.2005, c # 26.10.2005
def __init__(self, **kwargs): if kwargs: self.__dict__.update(kwargs) def _format_sequence(self, seq, threshold): threshold_half = threshold // 2 if len(seq) > threshold: out = ', '.join(str(ii) for ii in seq[:threshold_half]) \ + ', ..., ' \ ...
= sys._getframe(1) ff = f.f_code if (msg): print('%s, %d: %s(), %d: %s' % (ff.co_filename, ff.co_firstlineno, ff.co_name, f.f_lineno, msg)) else: print('%s, %d: %s(), %d' % (ff.co_filename, ff.co_firstlineno, ff.co_...
256
256
1,730
26
229
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
Struct
Struct
297
523
297
299
c92ac26547b795fae4172ac51e979c43d37be793
bigcode/the-stack
train
5bff7ca9baf0fb0e4c3d88fe
train
function
def dict_to_array(adict): """ Convert a dictionary of nD arrays of the same shapes with non-negative integer keys to a single (n+1)D array. """ keys = list(adict.keys()) ik = nm.array(keys, dtype=nm.int32) assert_((ik >= 0).all()) if ik.shape[0] == 0: return nm.zeros((0,), dtype...
def dict_to_array(adict):
""" Convert a dictionary of nD arrays of the same shapes with non-negative integer keys to a single (n+1)D array. """ keys = list(adict.keys()) ik = nm.array(keys, dtype=nm.int32) assert_((ik >= 0).all()) if ik.shape[0] == 0: return nm.zeros((0,), dtype=nm.int32) aux = nm.a...
_attr) objs[key] = new_val return objs def ordered_iteritems(adict): keys = list(adict.keys()) order = nm.argsort(keys) for ii in order: key = keys[ii] yield key, adict[key] def dict_to_array(adict):
64
64
159
7
57
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
dict_to_array
dict_to_array
1,455
1,473
1,455
1,455
7f5bd437db99ca815431a439070e5306c51d2093
bigcode/the-stack
train
2168d10bfc51e5aaa37c6e6e
train
function
def get_arguments(omit=None): """Get a calling function's arguments. Returns: args : dict The calling function's arguments. """ from inspect import getargvalues, stack if omit is None: omit = [] _args, _, _, _vars = getargvalues(stack()[1][0]) args = {} for name ...
def get_arguments(omit=None):
"""Get a calling function's arguments. Returns: args : dict The calling function's arguments. """ from inspect import getargvalues, stack if omit is None: omit = [] _args, _, _, _vars = getargvalues(stack()[1][0]) args = {} for name in _args: if name in o...
, msg_if_none=None): if hasattr(obj, attr): out = getattr(obj, attr) else: out = default if (out is None) and (msg_if_none is not None): raise ValueError(msg_if_none) return out def get_arguments(omit=None):
64
64
104
7
56
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
get_arguments
get_arguments
1,397
1,416
1,397
1,397
15f1ba943eb7cc98dba08b751f9a40e4dc026308
bigcode/the-stack
train
65cb854dfbd7b1cd40e65617
train
function
def edit_tuple_strings(str_tuple, old, new, recur=False): """ Replace substrings `old` with `new` in items of tuple `str_tuple`. Non-string items are just copied to the new tuple. Parameters ---------- str_tuple : tuple The tuple with string values. old : str The old substri...
def edit_tuple_strings(str_tuple, old, new, recur=False):
""" Replace substrings `old` with `new` in items of tuple `str_tuple`. Non-string items are just copied to the new tuple. Parameters ---------- str_tuple : tuple The tuple with string values. old : str The old substring. new : str The new substring. recur : b...
[key], dst[key])) out = tuple(out) dst[key] = out[:len(dst[key])] continue if overwrite_by_none or not src[key] is None: dst[key] = src[key] return dst def edit_tuple_strings(str_tuple, old, new, recur=False):
64
64
187
14
49
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
edit_tuple_strings
edit_tuple_strings
1,213
1,244
1,213
1,213
89e48bd25715a07ec66580456a4ba7bdaba9cc0a
bigcode/the-stack
train
9eb90657358212cf6c38c7ef
train
function
def is_string(var): return isinstance(var, basestr)
def is_string(var):
return isinstance(var, basestr)
a (nested) dict `obj` into a (nested) Struct. """ out = Struct(**obj) for key, val in out.to_dict().items(): if isinstance(val, dict): out.__dict__[key] = structify(val) return out def is_string(var):
64
64
13
5
58
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
is_string
is_string
1,063
1,064
1,063
1,063
ca4fba048b40bd6a6b8a6b0f9b845f40a25de18c
bigcode/the-stack
train
639f50dd06202a7a9bb807bd
train
class
class OneTypeList(list): def __init__(self, item_class, seq=None): self.item_class = item_class if seq is not None: for obj in seq: self.append(obj) def __setitem__(self, key, value): if (type(value) in (list, tuple)): for ii, val in enumerate(v...
class OneTypeList(list):
def __init__(self, item_class, seq=None): self.item_class = item_class if seq is not None: for obj in seq: self.append(obj) def __setitem__(self, key, value): if (type(value) in (list, tuple)): for ii, val in enumerate(value): if ...
print([obj.name for obj in self._objs]) def get_names(self): return [obj.name for obj in self._objs] def as_dict(self): """ Return stored objects in a dictionary with object names as keys. """ out = {} for key, val in self.iteritems(): out[ke...
113
113
377
6
106
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
OneTypeList
OneTypeList
720
777
720
721
bdeac614a70d16d485fa05ca4dedccfb74947152
bigcode/the-stack
train
449a8413df4c6dfd06332564
train
function
def is_sequence(var): from collections import Sequence if isinstance(var, basestr): return False return isinstance(var, Sequence)
def is_sequence(var):
from collections import Sequence if isinstance(var, basestr): return False return isinstance(var, Sequence)
return out def is_string(var): return isinstance(var, basestr) def is_integer(var): if PY3: return isinstance(var, int) else: return isinstance(var, (int, long)) ## # 23.01.2006, c def is_sequence(var):
64
64
30
5
58
MarcusAndreasSvensson/sfepy
sfepy/base/base.py
Python
is_sequence
is_sequence
1,075
1,079
1,075
1,075
619d983652ab496d37b6e573013b3f45a4f5075d
bigcode/the-stack
train
0c58c8daf889eaf8f7628111
train
function
def extract_features_single_episode(data_raw, period, functions): global sub_periods extracted_features = [np.concatenate([calculate(data_raw[i], period, sub_period, functions) for sub_period in sub_periods], axis=0) ...
def extract_features_single_episode(data_raw, period, functions):
global sub_periods extracted_features = [np.concatenate([calculate(data_raw[i], period, sub_period, functions) for sub_period in sub_periods], axis=0) for i in range(len(data_raw))] return np.concate...
< t < R + 1e-6] if len(data) == 0: return np.full((len(functions, )), np.nan) return np.array([fn(data) for fn in functions], dtype=np.float32) def extract_features_single_episode(data_raw, period, functions):
64
64
73
12
52
stefanhgm/mimic3-benchmarks
mimic3models/feature_extractor.py
Python
extract_features_single_episode
extract_features_single_episode
73
79
73
73
98a368a778139b67114d3b1872202b5c5f48a89f
bigcode/the-stack
train
1cae4e08cf6f93e2648c1c0e
train
function
def calculate(channel_data, period, sub_period, functions): if len(channel_data) == 0: return np.full((len(functions, )), np.nan) L = channel_data[0][0] R = channel_data[-1][0] L, R = get_range(L, R, period) L, R = get_range(L, R, sub_period) data = [x for (t, x) in channel_data ...
def calculate(channel_data, period, sub_period, functions):
if len(channel_data) == 0: return np.full((len(functions, )), np.nan) L = channel_data[0][0] R = channel_data[-1][0] L, R = get_range(L, R, period) L, R = get_range(L, R, sub_period) data = [x for (t, x) in channel_data if L - 1e-6 < t < R + 1e-6] if len(data) == 0: ...
1] else: L = end + period[1] if period[2] == 0: R = begin + period[3] else: R = end + period[3] return (L, R) def calculate(channel_data, period, sub_period, functions):
64
64
159
12
52
stefanhgm/mimic3-benchmarks
mimic3models/feature_extractor.py
Python
calculate
calculate
56
70
56
56
9857c79b75a70435158da7d2ba03e758001a31cb
bigcode/the-stack
train
1bbe13d1255c26c8ebe3aab4
train
function
def extract_features(data_raw, period, features): # argument features is still the original cli argument, i.e. default value "all" period = periods_map[period] functions = functions_map[features] return np.array([extract_features_single_episode(x, period, functions) for x in data_ra...
def extract_features(data_raw, period, features): # argument features is still the original cli argument, i.e. default value "all"
period = periods_map[period] functions = functions_map[features] return np.array([extract_features_single_episode(x, period, functions) for x in data_raw])
for sub_period in sub_periods], axis=0) for i in range(len(data_raw))] return np.concatenate(extracted_features, axis=0) def extract_features(data_raw, period, features): # argument features is still the...
64
64
67
29
35
stefanhgm/mimic3-benchmarks
mimic3models/feature_extractor.py
Python
extract_features
extract_features
82
87
82
83
aecf03010b66e1d226434fe86f1d81fcc393b734
bigcode/the-stack
train
c2cd60314420af47d3552999
train
function
def get_range(begin, end, period): # first p % if period[0] == 2: return (begin, begin + (end - begin) * period[1] / 100.0) # last p % if period[0] == 3: return (end - (end - begin) * period[1] / 100.0, end) if period[0] == 0: L = begin + period[1] else: L = end ...
def get_range(begin, end, period): # first p %
if period[0] == 2: return (begin, begin + (end - begin) * period[1] / 100.0) # last p % if period[0] == 3: return (end - (end - begin) * period[1] / 100.0, end) if period[0] == 0: L = begin + period[1] else: L = end + period[1] if period[2] == 0: R = beg...
2, 25), (2, 50), # (3, 10), (3, 25), (3, 50)] # use full period as sub period sub_periods = [(2, 100)] def get_range(begin, end, period): # first p %
63
64
154
14
49
stefanhgm/mimic3-benchmarks
mimic3models/feature_extractor.py
Python
get_range
get_range
35
53
35
36
ede36f853142141fc07c082f631c1f89d1fe682e
bigcode/the-stack
train
03781b797ea53f457c74510d
train
function
async def test_create_entry(hass): """Test creating an entry.""" with mocked_ec(), patch( "homeassistant.components.environment_canada.async_setup_entry", return_value=True, ): flow = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOU...
async def test_create_entry(hass):
"""Test creating an entry.""" with mocked_ec(), patch( "homeassistant.components.environment_canada.async_setup_entry", return_value=True, ): flow = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result ...
ec_mock.metadata = metadata if update: ec_mock.update = update else: ec_mock.update = AsyncMock() return patch( "homeassistant.components.environment_canada.config_flow.ECWeather", return_value=ec_mock, ) async def test_create_entry(hass):
64
64
137
8
56
MrDelik/core
tests/components/environment_canada/test_config_flow.py
Python
test_create_entry
test_create_entry
54
69
54
54
3b1585142308ba4b4c5ebf43b449e23ccfc9bafe
bigcode/the-stack
train
42dfe170361c826c4a06b8c9
train
function
async def test_create_same_entry_twice(hass): """Test duplicate entries.""" entry = MockConfigEntry( domain=DOMAIN, data=FAKE_CONFIG, unique_id="ON/s1234567-english", ) entry.add_to_hass(hass) with mocked_ec(), patch( "homeassistant.components.environment_canada.asyn...
async def test_create_same_entry_twice(hass):
"""Test duplicate entries.""" entry = MockConfigEntry( domain=DOMAIN, data=FAKE_CONFIG, unique_id="ON/s1234567-english", ) entry.add_to_hass(hass) with mocked_ec(), patch( "homeassistant.components.environment_canada.async_setup_entry", return_value=True, ...
"], FAKE_CONFIG ) await hass.async_block_till_done() assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"] == FAKE_CONFIG assert result["title"] == FAKE_TITLE async def test_create_same_entry_twice(hass):
64
64
170
11
52
MrDelik/core
tests/components/environment_canada/test_config_flow.py
Python
test_create_same_entry_twice
test_create_same_entry_twice
72
93
72
72
89aed4c33ff287f5336fd0585028894ef1cafb76
bigcode/the-stack
train
cf1a066bd48d9f58ffdbc1b1
train
function
async def test_lat_lon_not_specified(hass): """Test that the import step works when coordinates are not specified.""" with mocked_ec(), patch( "homeassistant.components.environment_canada.async_setup_entry", return_value=True, ): fake_config = dict(FAKE_CONFIG) del fake_confi...
async def test_lat_lon_not_specified(hass):
"""Test that the import step works when coordinates are not specified.""" with mocked_ec(), patch( "homeassistant.components.environment_canada.async_setup_entry", return_value=True, ): fake_config = dict(FAKE_CONFIG) del fake_config[CONF_LATITUDE] del fake_config[CON...
result = await hass.config_entries.flow.async_configure( flow["flow_id"], {}, ) await hass.async_block_till_done() assert result["type"] == "form" assert result["errors"] == {"base": base_error} async def test_lat_lon_not_specified(hass):
64
64
156
11
53
MrDelik/core
tests/components/environment_canada/test_config_flow.py
Python
test_lat_lon_not_specified
test_lat_lon_not_specified
125
140
125
125
a080e06373f8b7a007bdbf49466084403bb79534
bigcode/the-stack
train
a3444ed0b83eb94d720c7450
train
function
@pytest.mark.parametrize( "error", [ (aiohttp.ClientResponseError(Mock(), (), status=404), "bad_station_id"), (aiohttp.ClientResponseError(Mock(), (), status=400), "error_response"), (aiohttp.ClientConnectionError, "cannot_connect"), (et.ParseError, "bad_station_id"), (Va...
@pytest.mark.parametrize( "error", [ (aiohttp.ClientResponseError(Mock(), (), status=404), "bad_station_id"), (aiohttp.ClientResponseError(Mock(), (), status=400), "error_response"), (aiohttp.ClientConnectionError, "cannot_connect"), (et.ParseError, "bad_station_id"), (Va...
"""Test exception handling.""" exc, base_error = error with patch( "homeassistant.components.environment_canada.config_flow.ECWeather", side_effect=exc, ): flow = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ...
@pytest.mark.parametrize( "error", [ (aiohttp.ClientResponseError(Mock(), (), status=404), "bad_station_id"), (aiohttp.ClientResponseError(Mock(), (), status=400), "error_response"), (aiohttp.ClientConnectionError, "cannot_connect"), (et.ParseError, "bad_station_id"), (Va...
92
64
212
92
0
MrDelik/core
tests/components/environment_canada/test_config_flow.py
Python
test_exception_handling
test_exception_handling
96
122
96
106
78a33b724ba347fa70bc715904bbf0c369cfa857
bigcode/the-stack
train
42ef510455a7ba45bfbaadbe
train
function
def mocked_ec( station_id=FAKE_CONFIG[CONF_STATION], lat=FAKE_CONFIG[CONF_LATITUDE], lon=FAKE_CONFIG[CONF_LONGITUDE], lang=FAKE_CONFIG[CONF_LANGUAGE], update=None, metadata={"location": FAKE_TITLE}, ): """Mock the env_canada library.""" ec_mock = MagicMock() ec_mock.station_id = stat...
def mocked_ec( station_id=FAKE_CONFIG[CONF_STATION], lat=FAKE_CONFIG[CONF_LATITUDE], lon=FAKE_CONFIG[CONF_LONGITUDE], lang=FAKE_CONFIG[CONF_LANGUAGE], update=None, metadata={"location": FAKE_TITLE}, ):
"""Mock the env_canada library.""" ec_mock = MagicMock() ec_mock.station_id = station_id ec_mock.lat = lat ec_mock.lon = lon ec_mock.language = lang ec_mock.metadata = metadata if update: ec_mock.update = update else: ec_mock.update = AsyncMock() return patch( ...
!" def mocked_ec( station_id=FAKE_CONFIG[CONF_STATION], lat=FAKE_CONFIG[CONF_LATITUDE], lon=FAKE_CONFIG[CONF_LONGITUDE], lang=FAKE_CONFIG[CONF_LANGUAGE], update=None, metadata={"location": FAKE_TITLE}, ):
63
64
164
62
1
MrDelik/core
tests/components/environment_canada/test_config_flow.py
Python
mocked_ec
mocked_ec
27
51
27
34
ea8111f584c972330ddea9efecbc7d6f8be83e6f
bigcode/the-stack
train
d5bfde54327d1a0cfea785f9
train
function
def initialize_class(ctrl, data): """ A helper function that initialize the storage of the controller. """ ctrl.update_storage(data, init=True)
def initialize_class(ctrl, data):
""" A helper function that initialize the storage of the controller. """ ctrl.update_storage(data, init=True)
temp[name+'_'+k] = v for k, v in ctrl['output'][now].items(): temp[name+'_'+k] = v if write_db(temp, db_address) == list(): print("An error occurred when writing to database.") def initialize_class(ctrl, data):
64
64
32
7
57
xiaoxstz/FMLC
src/fmlc/stackedclasses.py
Python
initialize_class
initialize_class
46
50
46
46
8fb59b829c95ae1f4c075c56dbc6c0e2810df1c1
bigcode/the-stack
train
af9fe7154759b1e24f228928
train
function
def log_to_db(name, ctrl, now, db_address): """ A helper function to write records into database. Input --- name(str): name of the controller. ctrl(dict): Corresponds to the dictionary retrieved by `self.controller[name]`. Contains information about the controller. See the function `__initi...
def log_to_db(name, ctrl, now, db_address):
""" A helper function to write records into database. Input --- name(str): name of the controller. ctrl(dict): Corresponds to the dictionary retrieved by `self.controller[name]`. Contains information about the controller. See the function `__initialize_controller` code for detailed informat...
DB.utility import PythonDB_wrapper, write_db, read_db from .triggering import triggering from concurrent.futures import ThreadPoolExecutor import threading # Setup logger logger = logging.getLogger(__name__) #logger.setLevel(logging.DEBUG) def log_to_db(name, ctrl, now, db_address):
64
64
187
13
51
xiaoxstz/FMLC
src/fmlc/stackedclasses.py
Python
log_to_db
log_to_db
27
44
27
27
e419128f8507138c0689808a377b5cc826a597c7
bigcode/the-stack
train
a88030a36f59ffd4768dffe7
train
class
class controller_stack(object): def __init__(self, controller, mapping, tz=-8, debug=False, name='Zone1', parallel=True, \ timeout=1e3, now=None, workers=os.cpu_count()*5, log_config={'clear_log_period': 24*60*60, 'refresh_period':60, 'log_path':'./log'}): """ Initialize the controller stack...
class controller_stack(object):
def __init__(self, controller, mapping, tz=-8, debug=False, name='Zone1', parallel=True, \ timeout=1e3, now=None, workers=os.cpu_count()*5, log_config={'clear_log_period': 24*60*60, 'refresh_period':60, 'log_path':'./log'}): """ Initialize the controller stack object. NOTE:...
from concurrent.futures import ThreadPoolExecutor import threading # Setup logger logger = logging.getLogger(__name__) #logger.setLevel(logging.DEBUG) def log_to_db(name, ctrl, now, db_address): """ A helper function to write records into database. Input --- name(str): name of the controlle...
256
256
4,019
5
251
xiaoxstz/FMLC
src/fmlc/stackedclasses.py
Python
controller_stack
controller_stack
52
534
52
52
dac3689a981db5ac50ec37090fcd9e5036e11ca1
bigcode/the-stack
train
3044207ac7ea27a5eff33044
train
function
def guessEmail(): return '%s@%s' % (subprocess.getoutput ('whoami'), '.'.join(subprocess.getoutput('hostname').split('.')[-2:]))
def guessEmail():
return '%s@%s' % (subprocess.getoutput ('whoami'), '.'.join(subprocess.getoutput('hostname').split('.')[-2:]))
.environ.get ('CMSSW_RELEASE_BASE') retval = "%s/src/PhysicsTools/Utilities/configuration/copyPickMerge_cfg.py" \ % base if os.path.exists (retval): return retval raise RuntimeError("Could not find copyPickMerge_cfg.py") def guessEmail():
64
64
39
4
60
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
guessEmail
guessEmail
153
155
153
153
f4b19ab19acbeaa758cb3cc0063842b8aa0b078f
bigcode/the-stack
train
db8ce0be1d17ca57a513bfdc
train
function
def setupCrabDict (options): date = datetime.now().strftime('%Y%m%d_%H%M%S') crab = {} base = options.base crab['runEvent'] = '%s_runEvents.txt' % base crab['copyPickMerge'] = fullCPMpath() crab['output'] = '%s.root' % base crab['crabcfg'] = '%s_crab.py' % base ...
def setupCrabDict (options):
date = datetime.now().strftime('%Y%m%d_%H%M%S') crab = {} base = options.base crab['runEvent'] = '%s_runEvents.txt' % base crab['copyPickMerge'] = fullCPMpath() crab['output'] = '%s.root' % base crab['crabcfg'] = '%s_crab.py' % base crab['json'] = '%s...
return retval raise RuntimeError("Could not find copyPickMerge_cfg.py") def guessEmail(): return '%s@%s' % (subprocess.getoutput ('whoami'), '.'.join(subprocess.getoutput('hostname').split('.')[-2:])) def setupCrabDict (options):
64
64
213
8
56
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
setupCrabDict
setupCrabDict
157
176
157
157
9bfac6b81ce14264c9f65e57b86833f50515aaaf
bigcode/the-stack
train
a078ac5bb3fb4c030b25822d
train
function
def getFileNames_dasgoclient(event): """Return files for given DAS query via dasgoclient""" query = "file dataset=%(dataset)s run=%(run)i lumi=%(lumi)i" % event cmd = ['dasgoclient', '-query', query, '-json'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) files = [] ...
def getFileNames_dasgoclient(event):
"""Return files for given DAS query via dasgoclient""" query = "file dataset=%(dataset)s run=%(run)i lumi=%(lumi)i" % event cmd = ['dasgoclient', '-query', query, '-json'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) files = [] err = proc.stderr.read() if err...
files = [] for row in data: file = [r for r in das_client.get_value(row, filters['grep'])][0] if len(file) > 0 and not file in files: files.append(file) return files def getFileNames_dasgoclient(event):
64
64
155
10
53
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
getFileNames_dasgoclient
getFileNames_dasgoclient
121
136
121
121
bd41229adb06344f5fe7401f311f94753133c26f
bigcode/the-stack
train
f87dd3c863581e3473ffe0c1
train
function
def fullCPMpath(): base = os.environ.get ('CMSSW_BASE') if not base: raise RuntimeError("CMSSW Environment not set") retval = "%s/src/PhysicsTools/Utilities/configuration/copyPickMerge_cfg.py" \ % base if os.path.exists (retval): return retval base = os.environ.get ('CMS...
def fullCPMpath():
base = os.environ.get ('CMSSW_BASE') if not base: raise RuntimeError("CMSSW Environment not set") retval = "%s/src/PhysicsTools/Utilities/configuration/copyPickMerge_cfg.py" \ % base if os.path.exists (retval): return retval base = os.environ.get ('CMSSW_RELEASE_BASE') ...
print("DAS error: %s" % err) else: for row in json.load(proc.stdout): for rec in row.get('file', []): fname = rec.get('name', '') if fname: files.append(fname) return files def fullCPMpath():
64
64
136
6
57
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
fullCPMpath
fullCPMpath
138
151
138
138
47cb5a835e2f9494a2071b45272572e91e04dae0
bigcode/the-stack
train
32c197eeb4961c418d73c3c8
train
function
def getFileNames(event, client=None): """Return files for given DAS query""" if client == 'das_client': return getFileNames_das_client(event) elif client == 'dasgoclient': return getFileNames_dasgoclient(event) # default action for path in os.getenv('PATH').split(':'): if o...
def getFileNames(event, client=None):
"""Return files for given DAS query""" if client == 'das_client': return getFileNames_das_client(event) elif client == 'dasgoclient': return getFileNames_dasgoclient(event) # default action for path in os.getenv('PATH').split(':'): if os.path.isfile(os.path.join(path, 'dasg...
): return self[key] def __str__ (self): return "run = %(run)i, lumi = %(lumi)i, event = %(event)i, dataset = %(dataset)s" % self ################# ## Subroutines ## ################# def getFileNames(event, client=None):
64
64
113
9
55
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
getFileNames
getFileNames
86
96
86
86
3017257b47c319df12ee247d4eeb7608dbf8824d
bigcode/the-stack
train
3821cc179ae331a497a49d8c
train
class
class Event (dict): dataset = None splitRE = re.compile (r'[\s:,]+') def __init__ (self, line, **kwargs): pieces = Event.splitRE.split (line.strip()) try: self['run'] = int( pieces[0] ) self['lumi'] = int( pieces[1] ) self['event'] = int( pieces[...
class Event (dict):
dataset = None splitRE = re.compile (r'[\s:,]+') def __init__ (self, line, **kwargs): pieces = Event.splitRE.split (line.strip()) try: self['run'] = int( pieces[0] ) self['lumi'] = int( pieces[1] ) self['event'] = int( pieces[2] ) self...
you don't know exact name you can provide a mask, e.g.: *QCD*RAW For updated information see Wiki: https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookPickEvents """ ######################## ## Event helper class ## ######################## class Event (dict):
65
65
218
5
59
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
Event
Event
57
79
57
58
806addd8e7f9a7c1a02636b6b2ac91febe299d70
bigcode/the-stack
train
afda627500b0694443ca4010
train
function
def getFileNames_das_client(event): """Return files for given DAS query via das_client""" files = [] query = "file dataset=%(dataset)s run=%(run)i lumi=%(lumi)i | grep file.name" % event jsondict = das_client.get_data(query) status = jsondict['status'] if status != 'ok': print("DAS quer...
def getFileNames_das_client(event):
"""Return files for given DAS query via das_client""" files = [] query = "file dataset=%(dataset)s run=%(run)i lumi=%(lumi)i | grep file.name" % event jsondict = das_client.get_data(query) status = jsondict['status'] if status != 'ok': print("DAS query status: %s"%(status)) retu...
# default action for path in os.getenv('PATH').split(':'): if os.path.isfile(os.path.join(path, 'dasgoclient')): return getFileNames_dasgoclient(event) return getFileNames_das_client(event) def getFileNames_das_client(event):
64
64
176
9
55
malbouis/cmssw
PhysicsTools/Utilities/scripts/edmPickEvents.py
Python
getFileNames_das_client
getFileNames_das_client
98
119
98
98
201ecf1bff7b36295afd8bbe6adeb91c6b4dee8c
bigcode/the-stack
train
b059d31e82f30cc8c9b681ce
train
function
def setup_module(module, here=_HERE): print("") # this is to get a newline after the dots lf = os.listdir(here) lf = [f for f in lf if all([s in f for s in ['.npz']])] lF = [] for f in lf: ff = f.split('_') v = [fff[len(keyVers):] for fff in ff if fff[:len(ke...
def setup_module(module, here=_HERE):
print("") # this is to get a newline after the dots lf = os.listdir(here) lf = [f for f in lf if all([s in f for s in ['.npz']])] lF = [] for f in lf: ff = f.split('_') v = [fff[len(keyVers):] for fff in ff if fff[:len(keyVers)] == keyVers] msg = f + ...
plt from tofu import __version__ from pathlib import Path _HERE = os.path.abspath(os.path.dirname(__file__)) _TFROOT = Path(_HERE).parent.parent.parent keyVers = 'Vers' ####################################################### # # Setup and Teardown # ####################################################### def s...
67
67
225
9
58
WinstonLHS/tofu
tofu/tests/tests09_tutorials/test_01_runall.py
Python
setup_module
setup_module
20
41
20
20
f60ed4f857037075255cd6bc3409ed24fc7e5250
bigcode/the-stack
train
ca64f9d84aa9acb869e95866
train
function
def get_list_toturials(path=_HERE): ltut = os.listdir(path) ltut = [tt[:-3] for tt in ltut if (all([ss in tt for ss in ['tuto', '.py']]) and not any([ss in tt for ss in ['__init__', '.swp']]))] return ltut
def get_list_toturials(path=_HERE):
ltut = os.listdir(path) ltut = [tt[:-3] for tt in ltut if (all([ss in tt for ss in ['tuto', '.py']]) and not any([ss in tt for ss in ['__init__', '.swp']]))] return ltut
F.append(f) if len(lF) > 0: print("Removing the following test files:") for f in lF: os.remove(os.path.join(here, f)) ####################################################### # # Struct subclasses # ####################################################### def get_list_toturials(path=_H...
64
64
79
10
54
WinstonLHS/tofu
tofu/tests/tests09_tutorials/test_01_runall.py
Python
get_list_toturials
get_list_toturials
78
83
78
78
89250be97b47a101d542c99ac05d68ccb328faa1
bigcode/the-stack
train
34e6c8d789fc70af2202f81a
train
class
class Test00_tuto(object): @classmethod def setup_class(cls, here=_HERE, pathtuto=_HERE, root=_TFROOT): # print("") # print("---- "+cls.__name__) # ii = 0 # for tuto in get_list_toturials(path=pathtuto): # # Create local temporary copy to make sure the # local ve...
class Test00_tuto(object): @classmethod
def setup_class(cls, here=_HERE, pathtuto=_HERE, root=_TFROOT): # print("") # print("---- "+cls.__name__) # ii = 0 # for tuto in get_list_toturials(path=pathtuto): # # Create local temporary copy to make sure the # local version of tofu is imported # method = ...
v = v[:v.index('.npz')] # print(v, __version__) if v == __version__: lF.append(f) if len(lF) > 0: print("Removing the following test files:") for f in lF: os.remove(os.path.join(here, f)) ####################################################### # ...
173
173
578
11
161
WinstonLHS/tofu
tofu/tests/tests09_tutorials/test_01_runall.py
Python
Test00_tuto
Test00_tuto
86
155
86
88
14fdc207ab12c8a134a0f2e20ff87a8db63824ed
bigcode/the-stack
train
68c11e6bc1d6eb2ece5719d5
train
function
def teardown_module(module, here=_HERE): # os.remove(VesTor.Id.SavePath + VesTor.Id.SaveName + '.npz') # os.remove(VesLin.Id.SavePath + VesLin.Id.SaveName + '.npz') # print("teardown_module after everything in this file") # print("") # this is to get a newline lf = os.listdir(here) lf = [f for f...
def teardown_module(module, here=_HERE): # os.remove(VesTor.Id.SavePath + VesTor.Id.SaveName + '.npz') # os.remove(VesLin.Id.SavePath + VesLin.Id.SaveName + '.npz') # print("teardown_module after everything in this file") # print("") # this is to get a newline
lf = os.listdir(here) lf = [f for f in lf if all([s in f for s in ['.npz']])] lF = [] for f in lf: ff = f.split('_') v = [fff[len(keyVers):] for fff in ff if fff[:len(keyVers)] == keyVers] msg = f + "\n "+str(ff) + "\n " + str(v) assert len(v)...
before anything in this file") def teardown_module(module, here=_HERE): # os.remove(VesTor.Id.SavePath + VesTor.Id.SaveName + '.npz') # os.remove(VesLin.Id.SavePath + VesLin.Id.SaveName + '.npz') # print("teardown_module after everything in this file") # print("") # this is to get a newline
82
82
275
76
6
WinstonLHS/tofu
tofu/tests/tests09_tutorials/test_01_runall.py
Python
teardown_module
teardown_module
45
69
45
49
118ff62f9d824eff3852d99784996fcdddb17037
bigcode/the-stack
train
e7faafec8c0c8a1bd9535347
train
function
def flip(image, random_flip): if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image
def flip(image, random_flip):
if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image
1)) else: (h, v) = (0,0) image = image[(sz1-sz2+v):(sz1+sz2+v),(sz1-sz2+h):(sz1+sz2+h),:] return image def flip(image, random_flip):
64
64
33
7
56
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
flip
flip
204
207
204
204
02e0e9c738adceda0fff1a7a520f922f2d711b26
bigcode/the-stack
train
c42303ff43cc5c8a6bae981b
train
function
def get_batch(image_data, batch_size, batch_index): nrof_examples = np.size(image_data, 0) j = batch_index*batch_size % nrof_examples if j+batch_size<=nrof_examples: batch = image_data[j:j+batch_size,:,:,:] else: x1 = image_data[j:nrof_examples,:,:,:] x2 = image_data[0:nrof_examp...
def get_batch(image_data, batch_size, batch_index):
nrof_examples = np.size(image_data, 0) j = batch_index*batch_size % nrof_examples if j+batch_size<=nrof_examples: batch = image_data[j:j+batch_size,:,:,:] else: x1 = image_data[j:nrof_examples,:,:,:] x2 = image_data[0:nrof_examples-j,:,:,:] batch = np.vstack([x1,x2]) ...
else: x1 = label_data[j:nrof_examples] x2 = label_data[0:nrof_examples-j] batch = np.vstack([x1,x2]) batch_int = batch.astype(np.int64) return batch_int def get_batch(image_data, batch_size, batch_index):
64
64
119
12
51
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_batch
get_batch
241
251
241
241
f7deea7c6504a8ea8c22df1c030691d6aab4c00e
bigcode/the-stack
train
27cd722d68d828f6ba8a9f6f
train
function
def calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10, distance_metric=0, subtract_mean=False): assert(embeddings1.shape[0] == embeddings2.shape[0]) assert(embeddings1.shape[1] == embeddings2.shape[1]) nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) nrof_thresho...
def calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10, distance_metric=0, subtract_mean=False):
assert(embeddings1.shape[0] == embeddings2.shape[0]) assert(embeddings1.shape[1] == embeddings2.shape[1]) nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) nrof_thresholds = len(thresholds) k_fold = KFold(n_splits=nrof_folds, shuffle=False) tprs = np.zeros((nrof_folds,nrof_threshol...
# Distance based on cosine similarity dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1) norm = np.linalg.norm(embeddings1, axis=1) * np.linalg.norm(embeddings2, axis=1) similarity = dot / norm dist = np.arccos(similarity) / math.pi else: raise 'Undefined distance m...
130
130
435
35
94
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
calculate_roc
calculate_roc
396
427
396
396
7e599be15ad9df2422266ef1a4fe6142d9b3eb40
bigcode/the-stack
train
65dfb2544273dc3a6621ad81
train
function
def list_variables(filename): reader = training.NewCheckpointReader(filename) variable_map = reader.get_variable_to_shape_map() names = sorted(variable_map.keys()) return names
def list_variables(filename):
reader = training.NewCheckpointReader(filename) variable_map = reader.get_variable_to_shape_map() names = sorted(variable_map.keys()) return names
) text_file.write('tensorflow version: %s\n--------------------\n' % tf.__version__) # @UndefinedVariable text_file.write('git hash: %s\n--------------------\n' % git_hash) text_file.write('%s' % git_diff) def list_variables(filename):
64
64
37
5
59
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
list_variables
list_variables
517
521
517
517
5563ae555989e495dc93a707398744f299370213
bigcode/the-stack
train
8d645c3826eeeef67e061600
train
function
def put_images_on_grid(images, shape=(16,8)): nrof_images = images.shape[0] img_size = images.shape[1] bw = 3 img = np.zeros((shape[1]*(img_size+bw)+bw, shape[0]*(img_size+bw)+bw, 3), np.float32) for i in range(shape[1]): x_start = i*(img_size+bw)+bw for j in range(shape[0]): ...
def put_images_on_grid(images, shape=(16,8)):
nrof_images = images.shape[0] img_size = images.shape[1] bw = 3 img = np.zeros((shape[1]*(img_size+bw)+bw, shape[0]*(img_size+bw)+bw, 3), np.float32) for i in range(shape[1]): x_start = i*(img_size+bw)+bw for j in range(shape[0]): img_index = i*shape[0]+j if i...
git_hash) text_file.write('%s' % git_diff) def list_variables(filename): reader = training.NewCheckpointReader(filename) variable_map = reader.get_variable_to_shape_map() names = sorted(variable_map.keys()) return names def put_images_on_grid(images, shape=(16,8)):
64
64
185
13
50
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
put_images_on_grid
put_images_on_grid
523
538
523
523
b00cb8e9a81998125f0a7a3be9dee6f21da18b9b
bigcode/the-stack
train
a3043195e856b5ae00cad347
train
function
def calculate_accuracy(threshold, dist, actual_issame): predict_issame = np.less(dist, threshold) tp = np.sum(np.logical_and(predict_issame, actual_issame)) fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame))) tn = np.sum(np.logical_and(np.logical_not(predict_issame), np.logical_no...
def calculate_accuracy(threshold, dist, actual_issame):
predict_issame = np.less(dist, threshold) tp = np.sum(np.logical_and(predict_issame, actual_issame)) fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame))) tn = np.sum(np.logical_and(np.logical_not(predict_issame), np.logical_not(actual_issame))) fn = np.sum(np.logical_and(np.log...
resholds[best_threshold_index], dist[test_set], actual_issame[test_set]) tpr = np.mean(tprs,0) fpr = np.mean(fprs,0) return tpr, fpr, accuracy def calculate_accuracy(threshold, dist, actual_issame):
64
64
183
13
50
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
calculate_accuracy
calculate_accuracy
429
439
429
429
229261075d872c3094939858fce9469ce9fb44e4
bigcode/the-stack
train
eb75c26c8a7eae1ce9e7b7b7
train
function
def store_revision_info(src_path, output_dir, arg_string): try: # Get git hash cmd = ['git', 'rev-parse', 'HEAD'] gitproc = Popen(cmd, stdout = PIPE, cwd=src_path) (stdout, _) = gitproc.communicate() git_hash = stdout.strip() except OSError as e: git_hash = ' '.jo...
def store_revision_info(src_path, output_dir, arg_string):
try: # Get git hash cmd = ['git', 'rev-parse', 'HEAD'] gitproc = Popen(cmd, stdout = PIPE, cwd=src_path) (stdout, _) = gitproc.communicate() git_hash = stdout.strip() except OSError as e: git_hash = ' '.join(cmd) + ': ' + e.strerror try: # Get loca...
= np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame))) n_same = np.sum(actual_issame) n_diff = np.sum(np.logical_not(actual_issame)) val = float(true_accept) / float(n_same) far = float(false_accept) / float(n_diff) return val, far def store_revision_info(src_path, output_dir, arg_...
88
88
296
13
74
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
store_revision_info
store_revision_info
490
515
490
490
e3f8ae123e7086540043a32a5ed0b10c5d74da9b
bigcode/the-stack
train
070b226b7b13d79f3f5b5dec
train
function
def get_label_batch(label_data, batch_size, batch_index): nrof_examples = np.size(label_data, 0) j = batch_index*batch_size % nrof_examples if j+batch_size<=nrof_examples: batch = label_data[j:j+batch_size] else: x1 = label_data[j:nrof_examples] x2 = label_data[0:nrof_examples-j]...
def get_label_batch(label_data, batch_size, batch_index):
nrof_examples = np.size(label_data, 0) j = batch_index*batch_size % nrof_examples if j+batch_size<=nrof_examples: batch = label_data[j:j+batch_size] else: x1 = label_data[j:nrof_examples] x2 = label_data[0:nrof_examples-j] batch = np.vstack([x1,x2]) batch_int = batch....
if do_prewhiten: img = prewhiten(img) img = crop(img, do_random_crop, image_size) img = flip(img, do_random_flip) images[i,:,:,:] = img return images def get_label_batch(label_data, batch_size, batch_index):
64
64
114
13
50
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_label_batch
get_label_batch
229
239
229
229
847f01a0e1874806ed120c20f08a8decc3a7b3a2
bigcode/the-stack
train
a25e803e199bc36fd84968e5
train
function
def to_rgb(img): w, h = img.shape ret = np.empty((w, h, 3), dtype=np.uint8) ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img return ret
def to_rgb(img):
w, h = img.shape ret = np.empty((w, h, 3), dtype=np.uint8) ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img return ret
1+sz2+v),(sz1-sz2+h):(sz1+sz2+h),:] return image def flip(image, random_flip): if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image def to_rgb(img):
64
64
59
5
58
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
to_rgb
to_rgb
209
213
209
209
fb9a78eccb25f3017bbc8b2423d28f11dc373d9b
bigcode/the-stack
train
b3766b70729ddd82f1e898be
train
function
def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10, distance_metric=0, subtract_mean=False): assert(embeddings1.shape[0] == embeddings2.shape[0]) assert(embeddings1.shape[1] == embeddings2.shape[1]) nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) ...
def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10, distance_metric=0, subtract_mean=False):
assert(embeddings1.shape[0] == embeddings2.shape[0]) assert(embeddings1.shape[1] == embeddings2.shape[1]) nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) nrof_thresholds = len(thresholds) k_fold = KFold(n_splits=nrof_folds, shuffle=False) val = np.zeros(nrof_folds) far = np.z...
(np.logical_not(predict_issame), actual_issame)) tpr = 0 if (tp+fn==0) else float(tp) / float(tp+fn) fpr = 0 if (fp+tn==0) else float(fp) / float(fp+tn) acc = float(tp+tn)/dist.size return tpr, fpr, acc def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10, ...
121
122
408
37
83
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
calculate_val
calculate_val
443
477
443
443
8cbf17f373e92e012e5369abb8261ff22e06af05
bigcode/the-stack
train
3e32e4df7346f43540df9055
train
class
class ImageClass(): "Stores the paths to images for a given class" def __init__(self, name, image_paths): self.name = name self.image_paths = image_paths def __str__(self): return self.name + ', ' + str(len(self.image_paths)) + ' images' def __len__(self): return le...
class ImageClass():
"Stores the paths to images for a given class" def __init__(self, name, image_paths): self.name = name self.image_paths = image_paths def __str__(self): return self.name + ', ' + str(len(self.image_paths)) + ' images' def __len__(self): return len(self.image_paths)
= line.strip().split(':') e = int(par[0]) if par[1]=='-': lr = -1 else: lr = float(par[1]) if e <= epoch: learning_rate = lr else: return learning_rate class I...
64
64
82
4
59
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
ImageClass
ImageClass
277
287
277
277
702919fc6d619d8c6b2ce1b69eeb65077be7fbd1
bigcode/the-stack
train
656cbb63adae9a40c89c528e
train
function
def get_dataset(path, has_class_directories=True): dataset = [] path_exp = os.path.expanduser(path) classes = [path for path in os.listdir(path_exp) \ if os.path.isdir(os.path.join(path_exp, path))] classes.sort() nrof_classes = len(classes) for i in range(nrof_classes): ...
def get_dataset(path, has_class_directories=True):
dataset = [] path_exp = os.path.expanduser(path) classes = [path for path in os.listdir(path_exp) \ if os.path.isdir(os.path.join(path_exp, path))] classes.sort() nrof_classes = len(classes) for i in range(nrof_classes): class_name = classes[i] facedir = os.pa...
.name = name self.image_paths = image_paths def __str__(self): return self.name + ', ' + str(len(self.image_paths)) + ' images' def __len__(self): return len(self.image_paths) def get_dataset(path, has_class_directories=True):
63
64
120
11
52
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_dataset
get_dataset
289
302
289
289
4593ce81606748d503f470302d8638cf4c0788fc
bigcode/the-stack
train
42c38efe34694f5d8609d3d4
train
function
def load_data(image_paths, do_random_crop, do_random_flip, image_size, do_prewhiten=True): nrof_samples = len(image_paths) images = np.zeros((nrof_samples, image_size, image_size, 3)) for i in range(nrof_samples): img = cv2.imread(image_paths[i]) if img.ndim == 2: img = to_rgb(im...
def load_data(image_paths, do_random_crop, do_random_flip, image_size, do_prewhiten=True):
nrof_samples = len(image_paths) images = np.zeros((nrof_samples, image_size, image_size, 3)) for i in range(nrof_samples): img = cv2.imread(image_paths[i]) if img.ndim == 2: img = to_rgb(img) if do_prewhiten: img = prewhiten(img) img = crop(img, do_ran...
((w, h, 3), dtype=np.uint8) ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img return ret def load_data(image_paths, do_random_crop, do_random_flip, image_size, do_prewhiten=True):
64
64
137
23
40
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
load_data
load_data
215
227
215
215
0c6c0439e1896228158333a87453217bc6a06400
bigcode/the-stack
train
db4389fbe671f491ecbf3c76
train
function
def create_input_pipeline(input_queue, image_size, nrof_preprocess_threads, batch_size_placeholder): images_and_labels_list = [] for _ in range(nrof_preprocess_threads): filenames, label, control = input_queue.dequeue() images = [] for filename in tf.unstack(filenames): file_...
def create_input_pipeline(input_queue, image_size, nrof_preprocess_threads, batch_size_placeholder):
images_and_labels_list = [] for _ in range(nrof_preprocess_threads): filenames, label, control = input_queue.dequeue() images = [] for filename in tf.unstack(filenames): file_contents = tf.read_file(filename) image = tf.image.decode_image(file_contents, 3) ...
angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic') # 1: Random rotate 2: Random crop 4: Random flip 8: Fixed image standardization 16: Flip RANDOM_ROTATE = 1 RANDOM_CROP = 2 RANDOM_FLIP = 4 FIXED_STANDARDIZATION = 8 FLIP = 16 def create_input_pipeline(input_queu...
122
122
409
20
101
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
create_input_pipeline
create_input_pipeline
75
109
75
75
e62547b767ee62a84655f695c7dbfeb1a9c3a5f2
bigcode/the-stack
train
af88c1bc572846603e7d0079
train
function
def crop(image, random_crop, image_size): if image.shape[1]>image_size: sz1 = int(image.shape[1]//2) sz2 = int(image_size//2) if random_crop: diff = sz1-sz2 (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1)) else: (h, v) ...
def crop(image, random_crop, image_size):
if image.shape[1]>image_size: sz1 = int(image.shape[1]//2) sz2 = int(image_size//2) if random_crop: diff = sz1-sz2 (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1)) else: (h, v) = (0,0) image = image[(sz1-sz2+v):...
(x): mean = np.mean(x) std = np.std(x) std_adj = np.maximum(std, 1.0/np.sqrt(x.size)) y = np.multiply(np.subtract(x, mean), 1/std_adj) return y def crop(image, random_crop, image_size):
64
64
140
10
53
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
crop
crop
192
202
192
192
0e432148a2aee7e1fd34885fa3fd348cca7ce7d3
bigcode/the-stack
train
aa9269ca91e10d9b7f9a6425
train
function
def triplet_loss(anchor, positive, negative, alpha): """Calculate the triplet loss according to the FaceNet paper Args: anchor: the embeddings for the anchor images. positive: the embeddings for the positive images. negative: the embeddings for the negative images. Returns: t...
def triplet_loss(anchor, positive, negative, alpha):
"""Calculate the triplet loss according to the FaceNet paper Args: anchor: the embeddings for the anchor images. positive: the embeddings for the positive images. negative: the embeddings for the negative images. Returns: the triplet loss according to the FaceNet paper as a f...
from scipy import misc from sklearn.model_selection import KFold from scipy import interpolate from tensorflow.python.training import training import random import re from tensorflow.python.platform import gfile import math from six import iteritems import cv2 def triplet_loss(anchor, positive, negative, alpha):
64
64
169
12
51
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
triplet_loss
triplet_loss
16
34
16
16
5e5dc1a452c0e3a375e5102810fb01d48109282a
bigcode/the-stack
train
e55a69d587c695a5f074c28c
train
function
def split_dataset(dataset, split_ratio, min_nrof_images_per_class, mode): if mode=='SPLIT_CLASSES': nrof_classes = len(dataset) class_indices = np.arange(nrof_classes) np.random.shuffle(class_indices) split = int(round(nrof_classes*(1-split_ratio))) train_set = [dataset[i] fo...
def split_dataset(dataset, split_ratio, min_nrof_images_per_class, mode):
if mode=='SPLIT_CLASSES': nrof_classes = len(dataset) class_indices = np.arange(nrof_classes) np.random.shuffle(class_indices) split = int(round(nrof_classes*(1-split_ratio))) train_set = [dataset[i] for i in class_indices[0:split]] test_set = [dataset[i] for i in cla...
_paths)) return dataset def get_image_paths(facedir): image_paths = [] if os.path.isdir(facedir): images = os.listdir(facedir) image_paths = [os.path.join(facedir,img) for img in images] return image_paths def split_dataset(dataset, split_ratio, min_nrof_images_per_class, mode):
78
78
262
17
60
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
split_dataset
split_dataset
311
334
311
311
b15c2be5fff98c57fa07aac96949da72cdac316a
bigcode/the-stack
train
99a5aa07037f07e1a2db0476
train
function
def center_loss(features, label, alfa, nrof_classes): """Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) """ nrof_features = features.get_shape()[1] centers = tf.get_variable('centers', [nrof_class...
def center_loss(features, label, alfa, nrof_classes):
"""Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) """ nrof_features = features.get_shape()[1] centers = tf.get_variable('centers', [nrof_classes, nrof_features], dtype=tf.float32, initiali...
(tf.subtract(anchor, negative)), 1) basic_loss = tf.add(tf.subtract(pos_dist,neg_dist), alpha) loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0) return loss def center_loss(features, label, alfa, nrof_classes):
64
64
181
13
50
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
center_loss
center_loss
36
49
36
36
9a36cc3db1c5909dac93cfbb4c584fd0c916d9b8
bigcode/the-stack
train
4e2ce35ca3b14c241c854dbe
train
function
def train(total_loss, global_step, optimizer, learning_rate, moving_average_decay, update_gradient_vars, log_histograms=True): # Generate moving averages of all losses and associated summaries. loss_averages_op = _add_loss_summaries(total_loss) # Compute gradients. with tf.control_dependencies([loss_av...
def train(total_loss, global_step, optimizer, learning_rate, moving_average_decay, update_gradient_vars, log_histograms=True): # Generate moving averages of all losses and associated summaries.
loss_averages_op = _add_loss_summaries(total_loss) # Compute gradients. with tf.control_dependencies([loss_averages_op]): if optimizer=='ADAGRAD': opt = tf.train.AdagradOptimizer(learning_rate) elif optimizer=='ADADELTA': opt = tf.train.AdadeltaOptimizer(learning_rat...
to all individual losses and the total loss; do the # same for the averaged version of the losses. for l in losses + [total_loss]: # Name each loss as '(raw)' and name the moving average version of the loss # as the original loss name. tf.summary.scalar(l.op.name +' (raw)', l) t...
135
135
451
38
96
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
train
train
140
183
140
141
805a331d56d0dc5cc75025b57346adb68a5febed
bigcode/the-stack
train
1db34d48d2a410789e083908
train
function
def write_arguments_to_file(args, filename): with open(filename, 'w') as f: for key, value in iteritems(vars(args)): f.write('%s: %s\n' % (key, str(value)))
def write_arguments_to_file(args, filename):
with open(filename, 'w') as f: for key, value in iteritems(vars(args)): f.write('%s: %s\n' % (key, str(value)))
_start = j*(img_size+bw)+bw img[x_start:x_start+img_size, y_start:y_start+img_size, :] = images[img_index, :, :, :] if img_index>=nrof_images: break return img def write_arguments_to_file(args, filename):
64
64
48
9
54
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
write_arguments_to_file
write_arguments_to_file
540
543
540
540
2a9dfaf220fc98e2e03e751c3623e4ccc4a81821
bigcode/the-stack
train
275cdf1f5ac58a27f97620f5
train
function
def random_rotate_image(image): angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic')
def random_rotate_image(image):
angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic')
_paths_flat, labels_flat def shuffle_examples(image_paths, labels): shuffle_list = list(zip(image_paths, labels)) random.shuffle(shuffle_list) image_paths_shuff, labels_shuff = zip(*shuffle_list) return image_paths_shuff, labels_shuff def random_rotate_image(image):
64
64
37
6
57
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
random_rotate_image
random_rotate_image
65
67
65
65
1d5cef126b4028c6c283d11db9a4ef153d3c8fce
bigcode/the-stack
train
17dff994e747f0adf1b73cb1
train
function
def get_triplet_batch(triplets, batch_index, batch_size): ax, px, nx = triplets a = get_batch(ax, int(batch_size/3), batch_index) p = get_batch(px, int(batch_size/3), batch_index) n = get_batch(nx, int(batch_size/3), batch_index) batch = np.vstack([a, p, n]) return batch
def get_triplet_batch(triplets, batch_index, batch_size):
ax, px, nx = triplets a = get_batch(ax, int(batch_size/3), batch_index) p = get_batch(px, int(batch_size/3), batch_index) n = get_batch(nx, int(batch_size/3), batch_index) batch = np.vstack([a, p, n]) return batch
_data[j:nrof_examples,:,:,:] x2 = image_data[0:nrof_examples-j,:,:,:] batch = np.vstack([x1,x2]) batch_float = batch.astype(np.float32) return batch_float def get_triplet_batch(triplets, batch_index, batch_size):
64
64
89
15
48
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_triplet_batch
get_triplet_batch
253
259
253
253
2df583e0660e3eaebf87a2087aa935daca6f5fd6
bigcode/the-stack
train
f32dd63d6970aa02a2cf855d
train
function
def distance(embeddings1, embeddings2, distance_metric=0): if distance_metric==0: # Euclidian distance diff = np.subtract(embeddings1, embeddings2) dist = np.sum(np.square(diff),1) elif distance_metric==1: # Distance based on cosine similarity dot = np.sum(np.multiply(emb...
def distance(embeddings1, embeddings2, distance_metric=0):
if distance_metric==0: # Euclidian distance diff = np.subtract(embeddings1, embeddings2) dist = np.sum(np.square(diff),1) elif distance_metric==1: # Distance based on cosine similarity dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1) norm = np.linalg.no...
_str.groups())>=2: step = int(step_str.groups()[1]) if step > max_step: max_step = step ckpt_file = step_str.groups()[0] return meta_file, ckpt_file def distance(embeddings1, embeddings2, distance_metric=0):
64
64
156
15
48
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
distance
distance
380
394
380
380
423ccee403ff4bc0660f2ae87d27b519ce59eee6
bigcode/the-stack
train
83aa6c3bc47f928a90814cf6
train
function
def get_image_paths_and_labels(dataset): image_paths_flat = [] labels_flat = [] for i in range(len(dataset)): image_paths_flat += dataset[i].image_paths labels_flat += [i] * len(dataset[i].image_paths) return image_paths_flat, labels_flat
def get_image_paths_and_labels(dataset):
image_paths_flat = [] labels_flat = [] for i in range(len(dataset)): image_paths_flat += dataset[i].image_paths labels_flat += [i] * len(dataset[i].image_paths) return image_paths_flat, labels_flat
= (1 - alfa) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff) with tf.control_dependencies([centers]): loss = tf.reduce_mean(tf.square(features - centers_batch)) return loss, centers def get_image_paths_and_labels(dataset):
64
64
62
8
55
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_image_paths_and_labels
get_image_paths_and_labels
51
57
51
51
a7d6131a021b422713da9ee032aa82d9cff10e9a
bigcode/the-stack
train
4061cb3a228e43952841aba5
train
function
def get_image_paths(facedir): image_paths = [] if os.path.isdir(facedir): images = os.listdir(facedir) image_paths = [os.path.join(facedir,img) for img in images] return image_paths
def get_image_paths(facedir):
image_paths = [] if os.path.isdir(facedir): images = os.listdir(facedir) image_paths = [os.path.join(facedir,img) for img in images] return image_paths
for i in range(nrof_classes): class_name = classes[i] facedir = os.path.join(path_exp, class_name) image_paths = get_image_paths(facedir) dataset.append(ImageClass(class_name, image_paths)) return dataset def get_image_paths(facedir):
64
64
54
8
55
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_image_paths
get_image_paths
304
309
304
304
c18a84ca6ae74eaeb51999effc8adc6a0d5e6b9e
bigcode/the-stack
train
2526f584df92566631ac8435
train
function
def load_model(model, input_map=None): # Check if the model is a model directory (containing a metagraph and a checkpoint file) # or if it is a protobuf file with a frozen graph model_exp = os.path.expanduser(model) if (os.path.isfile(model_exp)): print('Model filename: %s' % model_exp) ...
def load_model(model, input_map=None): # Check if the model is a model directory (containing a metagraph and a checkpoint file) # or if it is a protobuf file with a frozen graph
model_exp = os.path.expanduser(model) if (os.path.isfile(model_exp)): print('Model filename: %s' % model_exp) with gfile.FastGFile(model_exp,'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, input_map=inpu...
ValueError('Invalid train/test split mode "%s"' % mode) return train_set, test_set def load_model(model, input_map=None): # Check if the model is a model directory (containing a metagraph and a checkpoint file) # or if it is a protobuf file with a frozen graph
67
67
225
45
21
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
load_model
load_model
336
354
336
338
3b6b232de080af850ed1c6e3bb4fa97d9b3affc8
bigcode/the-stack
train
20fb82363635a390a5075fec
train
function
def get_learning_rate_from_file(filename, epoch): with open(filename, 'r') as f: for line in f.readlines(): line = line.split('#', 1)[0] if line: par = line.strip().split(':') e = int(par[0]) if par[1]=='-': lr = -1 ...
def get_learning_rate_from_file(filename, epoch):
with open(filename, 'r') as f: for line in f.readlines(): line = line.split('#', 1)[0] if line: par = line.strip().split(':') e = int(par[0]) if par[1]=='-': lr = -1 else: lr = flo...
/3), batch_index) p = get_batch(px, int(batch_size/3), batch_index) n = get_batch(nx, int(batch_size/3), batch_index) batch = np.vstack([a, p, n]) return batch def get_learning_rate_from_file(filename, epoch):
64
64
106
10
53
aashishrai3799/Automated-Attendance-System-using-CNN
facenet.py
Python
get_learning_rate_from_file
get_learning_rate_from_file
261
275
261
261
a71bb0fb2c730c1d558947495424e9fc2d447c97
bigcode/the-stack
train