index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
29,991
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/task/task.py
346,347
334,373
get_state
TaskRunnable
347,363
347,363
class TaskRunnable(BaseCondition): """Condition for checking whether a given task has not run (for given period). Useful to set the given task to run once in given period. """ def __init__(self, task=None, period=None): self.period = period self.task = task super().__ini...
class TaskRunnable(BaseCondition): """Condition for checking whether a given task has not run (for given period). Useful to set the given task to run once in given period. """ def __init__(self, task=None, period=None): self.period = period self.task = task super().__ini...
task = self.task if self.task is not None else task period = self.period has_not_run = TaskStarted(period=period, task=task) == 0 isin_period = ( True if isinstance(period, TimeDelta) else IsPeriod(period=period).observe(session=session) ) ...
task = self.task if self.task is not None else task period = self.period has_not_run = TaskStarted(period=period, task=task) == 0 isin_period = ( True if isinstance(period, TimeDelta) else IsPeriod(period=period).observe(session=session) ) ...
36
216
140
356
from typing import Optional import datetime from redbird.oper import in_, greater_equal, between from rocketry.core.condition import BaseCondition, BaseComparable from rocketry.log.utils import get_field_value from rocketry.pybox.time import to_timestamp from rocketry.time.construct import get_before, get_between, ge...
from typing import Optional import datetime from redbird.oper import in_, greater_equal, between from rocketry.core.condition import BaseCondition, BaseComparable from rocketry.log.utils import get_field_value from rocketry.pybox.time import to_timestamp from rocketry.time.construct import get_before, get_between, ge...
29,992
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/task/task.py
167,168
147,232
get_measurement
TaskRunning
168,224
168,224
class TaskRunning(BaseComparable): """Condition for whether a task is currently running. Examples -------- **Parsing example:** >>> from rocketry.parse import parse_condition >>> parse_condition("task 'mytask' is running") TaskRunning(task='mytask') """ def __init__(self, ta...
class TaskRunning(BaseComparable): """Condition for whether a task is currently running. Examples -------- **Parsing example:** >>> from rocketry.parse import parse_condition >>> parse_condition("task 'mytask' is running") TaskRunning(task='mytask') """ def __init__(self, ta...
task = session[self.task] if self.task is not None else task allow_optimization = not self.session.config.force_status_from_logs start, end = get_period_span(self.period, session=session) if allow_optimization: task = session[self.task] if self.task is not None else task ...
task = session[self.task] if self.task is not None else task allow_optimization = not self.session.config.force_status_from_logs start, end = get_period_span(self.period, session=session) if allow_optimization: task = session[self.task] if self.task is not None else task ...
177
229
592
821
from typing import Optional import datetime from redbird.oper import in_, greater_equal, between from rocketry.core.condition import BaseCondition, BaseComparable from rocketry.log.utils import get_field_value from rocketry.pybox.time import to_timestamp from rocketry.time.construct import get_before, get_between, ge...
from typing import Optional import datetime from redbird.oper import in_, greater_equal, between from rocketry.core.condition import BaseCondition, BaseComparable from rocketry.log.utils import get_field_value from rocketry.pybox.time import to_timestamp from rocketry.time.construct import get_before, get_between, ge...
29,993
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/task/utils.py
36,37
11,53
get_state
DependMixin
37,53
37,53
class DependMixin(BaseCondition): _dep_actions = None def __init__(self, depend_task, task=None): self.task = task self.depend_task = depend_task super().__init__() @classmethod def _parse_multi_all(cls, depend_tasks:str, task=None): from rocketry.parse import ParserEr...
class DependMixin(BaseCondition): _dep_actions = None def __init__(self, depend_task, task=None): self.task = task self.depend_task = depend_task super().__init__() @classmethod def _parse_multi_all(cls, depend_tasks:str, task=None): from rocketry.parse import ParserEr...
actual_task = session[self.task] if self.task is not None else task depend_task = session[self.depend_task] #! TODO: use Task._last_success & Task._last_run if not none and not forced last_depend_finish = depend_task.logger.get_latest(action=in_(self._dep_actions)) last_actual_s...
actual_task = session[self.task] if self.task is not None else task depend_task = session[self.depend_task] #! TODO: use Task._last_success & Task._last_run if not none and not forced last_depend_finish = depend_task.logger.get_latest(action=in_(self._dep_actions)) last_actual_s...
64
281
218
499
from redbird.oper import in_, between from rocketry.core.condition import All, Any from rocketry.args import Task, Session from rocketry.core.condition import BaseCondition from rocketry.core.condition.base import BaseComparable from rocketry.core.time.utils import get_period_span from rocketry.pybox.time import to_ti...
from redbird.oper import in_, between from rocketry.core.condition import All, Any from rocketry.args import Task, Session from rocketry.core.condition import BaseCondition from rocketry.core.condition.base import BaseComparable from rocketry.core.time.utils import get_period_span from rocketry.pybox.time import to_ti...
29,994
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/task/utils.py
62,63
53,119
get_measurement
TaskStatusMixin
63,113
63,113
class TaskStatusMixin(BaseComparable): _action = None def __init__(self, period=None, task=None): self.task = task self.period = period super().__init__() def get_measurement(self, task=Task(default=None), session=Session()): FILL_FUNC_BODY def __str__(self): if hasattr...
class TaskStatusMixin(BaseComparable): _action = None def __init__(self, period=None, task=None): self.task = task self.period = period super().__init__() def get_measurement(self, task=Task(default=None), session=Session()): FILL_FUNC_BODY def __str__(self): if hasattr...
task = session[self.task] if self.task is not None else task _start_, _end_ = get_period_span(self.period if self.period is not None else task.period, session=session) allow_optimization = not self.session.config.force_status_from_logs if allow_optimization: # Get features...
task = session[self.task] if self.task is not None else task _start_, _end_ = get_period_span(self.period if self.period is not None else task.period, session=session) allow_optimization = not self.session.config.force_status_from_logs if allow_optimization: # Get features...
196
152
599
751
from redbird.oper import in_, between from rocketry.core.condition import All, Any from rocketry.args import Task, Session from rocketry.core.condition import BaseCondition from rocketry.core.condition.base import BaseComparable from rocketry.core.time.utils import get_period_span from rocketry.pybox.time import to_ti...
from redbird.oper import in_, between from rocketry.core.condition import All, Any from rocketry.args import Task, Session from rocketry.core.condition import BaseCondition from rocketry.core.condition.base import BaseComparable from rocketry.core.time.utils import get_period_span from rocketry.pybox.time import to_ti...
29,995
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/conditions/time.py
36,37
7,50
get_state
IsPeriod
37,40
37,40
class IsPeriod(BaseCondition): """Condition for checking whether current time is in the given time period. Parameters ---------- period : rocketry.core.time.TimePeriod Time period to check. Examples -------- **Parsing example:** >>> from rocketry.parse import parse_condit...
class IsPeriod(BaseCondition): """Condition for checking whether current time is in the given time period. Parameters ---------- period : rocketry.core.time.TimePeriod Time period to check. Examples -------- **Parsing example:** >>> from rocketry.parse import parse_condit...
now = session._get_datetime_now() return now in self.period
now = session._get_datetime_now() return now in self.period
7
385
24
409
import datetime from rocketry.time import TimeDelta from rocketry.core.condition.base import BaseCondition from rocketry.args import Session class IsPeriod(BaseCondition): """Condition for checking whether current time is in the given time period. Parameters ---------- period : rocketry.core.time...
import datetime from rocketry.time import TimeDelta from rocketry.core.condition.base import BaseCondition from rocketry.args import Session class IsPeriod(BaseCondition): """Condition for checking whether current time is in the given time period. Parameters ---------- period : rocketry.core.time...
29,996
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/hook.py
30,31
1,37
clear_hooks
32,37
31,37
from typing import Dict, List, Callable, Tuple import inspect class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks...
from typing import Dict, List, Callable, Tuple import inspect class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks...
from rocketry.core import Task, Scheduler Task.init_hooks = [] Scheduler.startup_hooks = [] Scheduler.cycle_hooks = [] Scheduler.shutdown_hooks = []
"Remove all hooks." from rocketry.core import Task, Scheduler Task.init_hooks = [] Scheduler.startup_hooks = [] Scheduler.cycle_hooks = [] Scheduler.shutdown_hooks = []
17
300
66
366
from typing import Dict, List, Callable, Tuple import inspect class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks...
from typing import Dict, List, Callable, Tuple import inspect class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks...
29,997
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/hook.py
12,13
4,30
prerun
_Hooker
13,23
13,23
class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks = hooks def prerun(self, *args, **kwargs): FILL_FUNC_BODY...
class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks = hooks def prerun(self, *args, **kwargs): FILL_FUNC_BODY...
from rocketry.core import Parameters self._post_hooks = [] for hook in self.hooks: kwds = Parameters._from_signature(hook).materialize(**kwargs) result = hook(*args, **kwds) if inspect.isgeneratorfunction(hook): gener = result n...
from rocketry.core import Parameters self._post_hooks = [] for hook in self.hooks: kwds = Parameters._from_signature(hook).materialize(**kwargs) result = hook(*args, **kwds) if inspect.isgeneratorfunction(hook): gener = result n...
30
161
116
277
from typing import Dict, List, Callable, Tuple import inspect class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks...
from typing import Dict, List, Callable, Tuple import inspect class _Hooker: # No, this is not what you think. def __init__(self, hooks:List[Callable], args:Tuple=None, kwargs:Dict=None): self.args = () if args is None else args self.kwargs = {} if kwargs is None else kwargs self.hooks...
29,998
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/log/adapter.py
36,38
14,154
_modify_record
TaskAdapter
38,47
38,47
class TaskAdapter(logging.LoggerAdapter): """Logging adapter for tasks. The adapter includes the name of the given task to the log records and allows reading the log records if a handler with reading capability is found. Parameters ---------- logger : logging.Logger Logger the ...
class TaskAdapter(logging.LoggerAdapter): """Logging adapter for tasks. The adapter includes the name of the given task to the log records and allows reading the log records if a handler with reading capability is found. Parameters ---------- logger : logging.Logger Logger the ...
# Set custom created time to LogRecords def wrapper(record, *args, **kwargs): ct = session.get_time() record = method(record, *args, **kwargs) record.created = ct record.msec = (ct - int(ct)) * 1000 return record return wrapper
# Set custom created time to LogRecords def wrapper(record, *args, **kwargs): ct = session.get_time() record = method(record, *args, **kwargs) record.created = ct record.msec = (ct - int(ct)) * 1000 return record return wrapper
33
1,317
95
1,412
import logging import warnings from typing import TYPE_CHECKING, Iterable, Dict, Union from redbird import BaseRepo from redbird.logging import RepoHandler from rocketry.core.utils import is_main_subprocess if TYPE_CHECKING: from rocketry.core import Task class TaskAdapter(logging.LoggerAdapter): """Loggin...
import logging import warnings from typing import TYPE_CHECKING, Iterable, Dict, Union from redbird import BaseRepo from redbird.logging import RepoHandler from rocketry.core.utils import is_main_subprocess if TYPE_CHECKING: from rocketry.core import Task class TaskAdapter(logging.LoggerAdapter): """Loggin...
29,999
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/parameters/arguments.py
49,50
9,104
stage
BaseArgument
79,81
50,81
class BaseArgument(RedBase): """Base class for Arguments. Argument is a wrapper for value that can be passed to a task. The value can be formulated on the fly or it can be a constant variable. Examples -------- Minimum example: >>> from rocketry.core import BaseArgument >>> class...
class BaseArgument(RedBase): """Base class for Arguments. Argument is a wrapper for value that can be passed to a task. The value can be formulated on the fly or it can be a constant variable. Examples -------- Minimum example: >>> from rocketry.core import BaseArgument >>> class...
return self.get_value(**kwargs)
"""Get (a copy of) the argument with a value that can be passed to child threads or processes. Override for custom behaviour. Example use cases: - Save a complex object to disk and read it again later with ``get_value``. - Shut a file buffer and re...
2
722
15
737
from typing import Any, TYPE_CHECKING from abc import abstractmethod from rocketry._base import RedBase if TYPE_CHECKING: import rocketry class BaseArgument(RedBase): """Base class for Arguments. Argument is a wrapper for value that can be passed to a task. The value can be formulated on the fly...
from typing import Any, TYPE_CHECKING from abc import abstractmethod from rocketry._base import RedBase if TYPE_CHECKING: import rocketry class BaseArgument(RedBase): """Base class for Arguments. Argument is a wrapper for value that can be passed to a task. The value can be formulated on the fly...
30,000
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/parameters/arguments.py
112,113
104,119
get_value
PipeArg
113,119
113,119
class PipeArg(BaseArgument): def __init__(self, args:list): self._args = args def __iter__(self): return iter(self._args) def get_value(self, **kwargs) -> Any: FILL_FUNC_BODY
class PipeArg(BaseArgument): def __init__(self, args:list): self._args = args def __iter__(self): return iter(self._args) def get_value(self, **kwargs) -> Any: FILL_FUNC_BODY
for arg in self: try: return arg.get_value(**kwargs) except KeyError: continue raise KeyError("No value found")
for arg in self: try: return arg.get_value(**kwargs) except KeyError: continue raise KeyError("No value found")
14
74
48
122
from typing import Any, TYPE_CHECKING from abc import abstractmethod from rocketry._base import RedBase if TYPE_CHECKING: import rocketry class BaseArgument(RedBase): """Base class for Arguments. Argument is a wrapper for value that can be passed to a task. The value can be formulated on the fly...
from typing import Any, TYPE_CHECKING from abc import abstractmethod from rocketry._base import RedBase if TYPE_CHECKING: import rocketry class BaseArgument(RedBase): """Base class for Arguments. Argument is a wrapper for value that can be passed to a task. The value can be formulated on the fly...
30,001
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/parameters/parameters.py
213,214
1,217
get_kwargs
215,217
214,217
from collections.abc import Mapping from typing import Callable, Type, Union, TYPE_CHECKING from functools import partial import inspect from rocketry._base import RedBase from rocketry.core.utils import is_pickleable from rocketry.core.utils import filter_keyword_args from .arguments import BaseArgument if TYPE_CHE...
from collections.abc import Mapping from typing import Callable, Type, Union, TYPE_CHECKING from functools import partial import inspect from rocketry._base import RedBase from rocketry.core.utils import is_pickleable from rocketry.core.utils import filter_keyword_args from .arguments import BaseArgument if TYPE_CHE...
sig_kwargs = Parameters._from_signature(__func).materialize(**kwargs) return {**sig_kwargs, **kwargs}
"Get function arguments" sig_kwargs = Parameters._from_signature(__func).materialize(**kwargs) return {**sig_kwargs, **kwargs}
6
1,774
34
1,808
from collections.abc import Mapping from typing import Callable, Type, Union, TYPE_CHECKING from functools import partial import inspect from rocketry._base import RedBase from rocketry.core.utils import is_pickleable from rocketry.core.utils import filter_keyword_args from .arguments import BaseArgument if TYPE_CHE...
from collections.abc import Mapping from typing import Callable, Type, Union, TYPE_CHECKING from functools import partial import inspect from rocketry._base import RedBase from rocketry.core.utils import is_pickleable from rocketry.core.utils import filter_keyword_args from .arguments import BaseArgument if TYPE_CHE...
30,002
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/parameters/parameters.py
70,71
15,213
_get
Parameters
71,77
71,77
class Parameters(RedBase, Mapping): # Mapping so that mytask(**Parameters(...)) would work """Parameter set for tasks. Parameter set is a mapping (like dictionary). The parameter set materializes the arguments so that those can be passed to the tasks. Parameters ---------- _param : dict, P...
class Parameters(RedBase, Mapping): # Mapping so that mytask(**Parameters(...)) would work """Parameter set for tasks. Parameter set is a mapping (like dictionary). The parameter set materializes the arguments so that those can be passed to the tasks. Parameters ---------- _param : dict, P...
item = __item if callable(item) and hasattr(item, "__rocketry__") and "param_name" in item.__rocketry__: item = item.__rocketry__['param_name'] value = self._params[item] return value if not isinstance(value, BaseArgument) else value.get_value(**kwargs)
item = __item if callable(item) and hasattr(item, "__rocketry__") and "param_name" in item.__rocketry__: item = item.__rocketry__['param_name'] value = self._params[item] return value if not isinstance(value, BaseArgument) else value.get_value(**kwargs)
26
1,570
94
1,664
from collections.abc import Mapping from typing import Callable, Type, Union, TYPE_CHECKING from functools import partial import inspect from rocketry._base import RedBase from rocketry.core.utils import is_pickleable from rocketry.core.utils import filter_keyword_args from .arguments import BaseArgument if TYPE_CHE...
from collections.abc import Mapping from typing import Callable, Type, Union, TYPE_CHECKING from functools import partial import inspect from rocketry._base import RedBase from rocketry.core.utils import is_pickleable from rocketry.core.utils import filter_keyword_args from .arguments import BaseArgument if TYPE_CHE...
30,003
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/time/utils.py
8,9
1,33
get_period_span
9,33
9,33
import time import datetime from typing import Tuple from .base import TimePeriod def get_period_span(period:'TimePeriod', session=None) -> Tuple[datetime.datetime, datetime.datetime]: FILL_FUNC_BODY
import time import datetime from typing import Tuple from .base import TimePeriod def get_period_span(period:'TimePeriod', session=None) -> Tuple[datetime.datetime, datetime.datetime]: FILL_FUNC_BODY
# To prevent circular import from rocketry.parse import parse_time if period is None: return TimePeriod.min, TimePeriod.max if isinstance(period, str): period = parse_time(period) if session is None: now = datetime.datetime.fromtimestamp(time.time()) else: now ...
# To prevent circular import from rocketry.parse import parse_time if period is None: return TimePeriod.min, TimePeriod.max if isinstance(period, str): period = parse_time(period) if session is None: now = datetime.datetime.fromtimestamp(time.time()) else: now ...
66
62
206
268
import time import datetime from typing import Tuple from .base import TimePeriod def get_period_span(period:'TimePeriod', session=None) -> Tuple[datetime.datetime, datetime.datetime]: FILL_FUNC_BODY
import time import datetime from typing import Tuple from .base import TimePeriod def get_period_span(period:'TimePeriod', session=None) -> Tuple[datetime.datetime, datetime.datetime]: FILL_FUNC_BODY
30,004
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/utils/meta.py
6,7
1,25
filter_keyword_args
9,25
7,25
import inspect # Copied from rocketry.pybox\meta\func\func.py def filter_keyword_args(_func, _params:dict=None, **kwargs): FILL_FUNC_BODY
import inspect # Copied from rocketry.pybox\meta\func\func.py def filter_keyword_args(_func, _params:dict=None, **kwargs): """Filter only keyword arguments that the function requires.""" FILL_FUNC_BODY
if _params: kwargs.update(_params) sig = inspect.signature(_func) kw_args = [ val.name for name, val in sig.parameters.items() if val.kind in ( inspect.Parameter.POSITIONAL_OR_KEYWORD, # Normal argument inspect.Parameter.KEYWORD_ONLY # Keyword argumen...
"""Filter only keyword arguments that the function requires.""" if _params: kwargs.update(_params) sig = inspect.signature(_func) kw_args = [ val.name for name, val in sig.parameters.items() if val.kind in ( inspect.Parameter.POSITIONAL_OR_KEYWORD, # Norm...
43
68
148
216
import inspect # Copied from rocketry.pybox\meta\func\func.py def filter_keyword_args(_func, _params:dict=None, **kwargs): FILL_FUNC_BODY
import inspect # Copied from rocketry.pybox\meta\func\func.py def filter_keyword_args(_func, _params:dict=None, **kwargs): """Filter only keyword arguments that the function requires.""" FILL_FUNC_BODY
30,005
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/utils/pickle.py
4,5
1,11
is_pickleable
5,11
5,11
import pickle def is_pickleable(obj): FILL_FUNC_BODY
import pickle def is_pickleable(obj): FILL_FUNC_BODY
try: pickle.dumps(obj) except Exception: return False else: return True
try: pickle.dumps(obj) except Exception: return False else: return True
9
27
37
64
import pickle def is_pickleable(obj): FILL_FUNC_BODY
import pickle def is_pickleable(obj): FILL_FUNC_BODY
30,006
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/core/utils/process.py
3,4
1,5
is_main_subprocess
4,5
4,5
from multiprocessing import current_process def is_main_subprocess(): FILL_FUNC_BODY
from multiprocessing import current_process def is_main_subprocess(): FILL_FUNC_BODY
return current_process().name == 'MainProcess'
return current_process().name == 'MainProcess'
4
30
14
44
from multiprocessing import current_process def is_main_subprocess(): FILL_FUNC_BODY
from multiprocessing import current_process def is_main_subprocess(): FILL_FUNC_BODY
30,007
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/log/defaults.py
5,6
1,10
create_default_handler
7,10
6,10
from redbird.logging import RepoHandler from redbird.repos import MemoryRepo from .log_record import MinimalRecord def create_default_handler(): FILL_FUNC_BODY
from redbird.logging import RepoHandler from redbird.repos import MemoryRepo from .log_record import MinimalRecord def create_default_handler(): "Create default handler that can be read" FILL_FUNC_BODY
return RepoHandler( repo=MemoryRepo(model=MinimalRecord) )
"Create default handler that can be read" return RepoHandler( repo=MemoryRepo(model=MinimalRecord) )
4
61
27
88
from redbird.logging import RepoHandler from redbird.repos import MemoryRepo from .log_record import MinimalRecord def create_default_handler(): FILL_FUNC_BODY
from redbird.logging import RepoHandler from redbird.repos import MemoryRepo from .log_record import MinimalRecord def create_default_handler(): "Create default handler that can be read" FILL_FUNC_BODY
30,008
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/log/handlers.py
16,17
9,47
prepare
QueueHandler
32,47
17,47
class QueueHandler(_QueueHandler): """ The logging.handlers.QueueHandler gives priority for the message but does not maintain the other info in a record when passing it to the queue. These """ def prepare(self, record): FILL_FUNC_BODY
class QueueHandler(_QueueHandler): """ The logging.handlers.QueueHandler gives priority for the message but does not maintain the other info in a record when passing it to the queue. These """ def prepare(self, record): """ Prepare a record for queuing. The object returned by th...
# The format operation gets traceback text into record.exc_text # (if there's exception data), and also returns the formatted # message. We can then use this to replace the original # msg + args, as these might be unpickleable. We also zap the # exc_info and exc_text attributes, ...
""" Prepare a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message and arguments, and removes unpickleable items from the record in-place. Specifically, it overwrites the record's `msg` and ...
103
242
209
451
from logging.handlers import QueueHandler as _QueueHandler from logging import Formatter import copy # Copying the default formatter mechanism from logging _DEFAULT_FORMATTER = Formatter() class QueueHandler(_QueueHandler): """ The logging.handlers.QueueHandler gives priority for the message but does not...
from logging.handlers import QueueHandler as _QueueHandler from logging import Formatter import copy # Copying the default formatter mechanism from logging _DEFAULT_FORMATTER = Formatter() class QueueHandler(_QueueHandler): """ The logging.handlers.QueueHandler gives priority for the message but does not...
30,009
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/log/utils.py
1,2
1,5
get_field_value
2,5
2,5
def get_field_value(record, field:str): FILL_FUNC_BODY
def get_field_value(record, field:str): FILL_FUNC_BODY
if isinstance(record, dict): return record[field] return getattr(record, field)
if isinstance(record, dict): return record[field] return getattr(record, field)
8
24
30
54
def get_field_value(record, field:str): FILL_FUNC_BODY
def get_field_value(record, field:str): FILL_FUNC_BODY
30,010
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parameters/func.py
46,47
4,50
_get_name
FuncParam
47,50
47,50
class FuncParam: """A parameter from a function. This class is to create parameters directly from functions. Parameters ---------- name : str Name of the parameter, by default the name of the function. Examples -------- Simple example: >>> from ro...
class FuncParam: """A parameter from a function. This class is to create parameters directly from functions. Parameters ---------- name : str Name of the parameter, by default the name of the function. Examples -------- Simple example: >>> from ro...
if self.name is not None: return self.name return func.__name__
if self.name is not None: return self.name return func.__name__
9
307
26
333
from typing import Callable from rocketry.args import FuncArg class FuncParam: """A parameter from a function. This class is to create parameters directly from functions. Parameters ---------- name : str Name of the parameter, by default the name of the function. ...
from typing import Callable from rocketry.args import FuncArg class FuncParam: """A parameter from a function. This class is to create parameters directly from functions. Parameters ---------- name : str Name of the parameter, by default the name of the function. ...
30,011
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/_condition/condition_item.py
22,23
1,49
parse_condition_item
24,49
23,49
from typing import Callable, Dict, Pattern, Union from rocketry.core.condition.base import BaseCondition from rocketry.session import Session from ..utils import ParserError, CondParser CONDITION_PARSERS = [] def add_condition_parser(d: Dict[Union[str, Pattern], Union[Callable, 'BaseCondition']]): """Add a pars...
from typing import Callable, Dict, Pattern, Union from rocketry.core.condition.base import BaseCondition from rocketry.session import Session from ..utils import ParserError, CondParser CONDITION_PARSERS = [] def add_condition_parser(d: Dict[Union[str, Pattern], Union[Callable, 'BaseCondition']]): """Add a pars...
# TODO: Don't use global session = Session.session if session is None else session for statement, parser in session.get_cond_parsers().items(): if isinstance(statement, Pattern): res = statement.fullmatch(s) if res: args = () kwargs = res.gro...
"Parse one condition" # TODO: Don't use global session = Session.session if session is None else session for statement, parser in session.get_cond_parsers().items(): if isinstance(statement, Pattern): res = statement.fullmatch(s) if res: args = () ...
71
200
219
419
from typing import Callable, Dict, Pattern, Union from rocketry.core.condition.base import BaseCondition from rocketry.session import Session from ..utils import ParserError, CondParser CONDITION_PARSERS = [] def add_condition_parser(d: Dict[Union[str, Pattern], Union[Callable, 'BaseCondition']]): """Add a pars...
from typing import Callable, Dict, Pattern, Union from rocketry.core.condition.base import BaseCondition from rocketry.session import Session from ..utils import ParserError, CondParser CONDITION_PARSERS = [] def add_condition_parser(d: Dict[Union[str, Pattern], Union[Callable, 'BaseCondition']]): """Add a pars...
30,012
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/_condition/string.py
21,22
1,48
_parse_not
22,28
22,28
from rocketry.conditions import Any, All, Not from ..utils.string_parser import InstructionParser from .condition_item import parse_condition_item def _flatten(*args, types, with_attr): comps = [] for arg in args: if isinstance(arg, types): comps += getattr(arg, with_attr) else: ...
from rocketry.conditions import Any, All, Not from ..utils.string_parser import InstructionParser from .condition_item import parse_condition_item def _flatten(*args, types, with_attr): comps = [] for arg in args: if isinstance(arg, types): comps += getattr(arg, with_attr) else: ...
if hasattr(arg, "__invert__"): return ~arg if isinstance(arg, Not): return ~arg return Not(arg)
if hasattr(arg, "__invert__"): return ~arg if isinstance(arg, Not): return ~arg return Not(arg)
12
332
49
381
from rocketry.conditions import Any, All, Not from ..utils.string_parser import InstructionParser from .condition_item import parse_condition_item def _flatten(*args, types, with_attr): comps = [] for arg in args: if isinstance(arg, types): comps += getattr(arg, with_attr) else: ...
from rocketry.conditions import Any, All, Not from ..utils.string_parser import InstructionParser from .condition_item import parse_condition_item def _flatten(*args, types, with_attr): comps = [] for arg in args: if isinstance(arg, types): comps += getattr(arg, with_attr) else: ...
30,014
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/_time/string.py
5,6
1,37
_flatten
6,14
6,14
from rocketry.core.time import Any, All from ..utils.string_parser import InstructionParser from .time_item import parse_time_item def _flatten(*args, types, with_attr): FILL_FUNC_BODYdef _parse_any(*args): comps = _flatten(*args, types=Any, with_attr="periods") return Any(*comps) def _parse_all(*args): c...
from rocketry.core.time import Any, All from ..utils.string_parser import InstructionParser from .time_item import parse_time_item def _flatten(*args, types, with_attr): FILL_FUNC_BODYdef _parse_any(*args): comps = _flatten(*args, types=Any, with_attr="periods") return Any(*comps) def _parse_all(*args): c...
comps = [] for arg in args: if isinstance(arg, types): comps += getattr(arg, with_attr) else: comps.append(arg) return comps
comps = [] for arg in args: if isinstance(arg, types): comps += getattr(arg, with_attr) else: comps.append(arg) return comps
18
236
64
300
from rocketry.core.time import Any, All from ..utils.string_parser import InstructionParser from .time_item import parse_time_item def _flatten(*args, types, with_attr): FILL_FUNC_BODYdef _parse_any(*args): comps = _flatten(*args, types=Any, with_attr="periods") return Any(*comps) def _parse_all(*args): c...
from rocketry.core.time import Any, All from ..utils.string_parser import InstructionParser from .time_item import parse_time_item def _flatten(*args, types, with_attr): FILL_FUNC_BODYdef _parse_any(*args): comps = _flatten(*args, types=Any, with_attr="periods") return Any(*comps) def _parse_all(*args): c...
30,015
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/_time/time_item.py
8,9
1,32
parse_time_item
10,32
9,32
from typing import Pattern from rocketry.core.time.base import TimePeriod from rocketry.session import Session from ..utils import ParserError def parse_time_item(s:str, session=None): FILL_FUNC_BODY
from typing import Pattern from rocketry.core.time.base import TimePeriod from rocketry.session import Session from ..utils import ParserError def parse_time_item(s:str, session=None): "Parse one condition" FILL_FUNC_BODY
if session is None: # Old way session = Session.session parsers = session._time_parsers for statement, parser in parsers.items(): if isinstance(statement, Pattern): res = statement.fullmatch(s) if res: args = () kwargs = res.gro...
"Parse one condition" if session is None: # Old way session = Session.session parsers = session._time_parsers for statement, parser in parsers.items(): if isinstance(statement, Pattern): res = statement.fullmatch(s) if res: args = () ...
61
71
191
262
from typing import Pattern from rocketry.core.time.base import TimePeriod from rocketry.session import Session from ..utils import ParserError def parse_time_item(s:str, session=None): FILL_FUNC_BODY
from typing import Pattern from rocketry.core.time.base import TimePeriod from rocketry.session import Session from ..utils import ParserError def parse_time_item(s:str, session=None): "Parse one condition" FILL_FUNC_BODY
30,016
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/condition.py
21,22
1,25
parse_condition
22,25
22,25
from rocketry.core.condition.base import BaseCondition from rocketry.conds import true, false from ._condition import parse_condition_string from .utils import ParserPicker def _parse_condition_string(s:str, **kwargs) -> BaseCondition: cond = parse_condition_string(s, **kwargs) cond._str = s return cond d...
from rocketry.core.condition.base import BaseCondition from rocketry.conds import true, false from ._condition import parse_condition_string from .utils import ParserPicker def _parse_condition_string(s:str, **kwargs) -> BaseCondition: cond = parse_condition_string(s, **kwargs) cond._str = s return cond d...
if isinstance(conf, BaseCondition): return conf return PARSER(conf, **kwargs)
if isinstance(conf, BaseCondition): return conf return PARSER(conf, **kwargs)
8
176
29
205
from rocketry.core.condition.base import BaseCondition from rocketry.conds import true, false from ._condition import parse_condition_string from .utils import ParserPicker def _parse_condition_string(s:str, **kwargs) -> BaseCondition: cond = parse_condition_string(s, **kwargs) cond._str = s return cond d...
from rocketry.core.condition.base import BaseCondition from rocketry.conds import true, false from ._condition import parse_condition_string from .utils import ParserPicker def _parse_condition_string(s:str, **kwargs) -> BaseCondition: cond = parse_condition_string(s, **kwargs) cond._str = s return cond d...
30,017
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/time.py
6,7
1,15
_parse_time_string
7,10
7,10
#from rocketry.core.time.base import CLS from ._time import parse_time_string from .utils import ParserPicker def _parse_time_string(s:str, **kwargs): FILL_FUNC_BODYparse_time = ParserPicker( { str: _parse_time_string, } )
#from rocketry.core.time.base import CLS from ._time import parse_time_string from .utils import ParserPicker def _parse_time_string(s:str, **kwargs): FILL_FUNC_BODYparse_time = ParserPicker( { str: _parse_time_string, } )
time = parse_time_string(s, **kwargs) return time
time = parse_time_string(s, **kwargs) return time
6
91
23
114
#from rocketry.core.time.base import CLS from ._time import parse_time_string from .utils import ParserPicker def _parse_time_string(s:str, **kwargs): FILL_FUNC_BODYparse_time = ParserPicker( { str: _parse_time_string, } )
#from rocketry.core.time.base import CLS from ._time import parse_time_string from .utils import ParserPicker def _parse_time_string(s:str, **kwargs): FILL_FUNC_BODYparse_time = ParserPicker( { str: _parse_time_string, } )
30,018
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/utils/string_parser.py
140,141
1,152
_flatten_tuples
141,152
141,152
from functools import partial import re from typing import Callable, Dict, List from rocketry.pybox.string.parse import ClosureParser from rocketry.pybox.container.visitor import Visitor class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_pa...
from functools import partial import re from typing import Callable, Dict, List from rocketry.pybox.string.parse import ClosureParser from rocketry.pybox.container.visitor import Visitor class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_pa...
for i, item in enumerate(cont): if isinstance(item, tuple): cont.pop(i) for j, tpl_item in enumerate(item): cont.insert(i+j, tpl_item) return cont # Conditions
for i, item in enumerate(cont): if isinstance(item, tuple): cont.pop(i) for j, tpl_item in enumerate(item): cont.insert(i+j, tpl_item) return cont # Conditions
20
1,289
83
1,372
from functools import partial import re from typing import Callable, Dict, List from rocketry.pybox.string.parse import ClosureParser from rocketry.pybox.container.visitor import Visitor class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_pa...
from functools import partial import re from typing import Callable, Dict, List from rocketry.pybox.string.parse import ClosureParser from rocketry.pybox.container.visitor import Visitor class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_pa...
30,019
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/utils/string_parser.py
121,122
10,140
_split_operations
InstructionParser
122,140
122,140
class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_parser = item_parser self.operators = operators self.symbols = set(oper["symbol"] for oper in operators) def __call__(self, s:str, **kwargs): """Parse a string to ...
class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_parser = item_parser self.operators = operators self.symbols = set(oper["symbol"] for oper in operators) def __call__(self, s:str, **kwargs): """Parse a string to ...
# The following are considered as reserved operators # "&" : and operator # "|" : or operator # "~" : not operator symbols = ''.join(self.symbols) regex = r'([' + symbols + '])' s = s.strip() if bool(re.search(regex, s)): l = re.split(reg...
# The following are considered as reserved operators # "&" : and operator # "|" : or operator # "~" : not operator symbols = ''.join(self.symbols) regex = r'([' + symbols + '])' s = s.strip() if bool(re.search(regex, s)): l = re.split(reg...
66
1,068
171
1,239
from functools import partial import re from typing import Callable, Dict, List from rocketry.pybox.string.parse import ClosureParser from rocketry.pybox.container.visitor import Visitor class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_pa...
from functools import partial import re from typing import Callable, Dict, List from rocketry.pybox.string.parse import ClosureParser from rocketry.pybox.container.visitor import Visitor class InstructionParser: def __init__(self, item_parser:Callable, operators:List[Dict[str, Callable]]): self.item_pa...
30,020
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/parse/utils/utils.py
1,2
1,5
_get_session
3,5
2,5
def _get_session(): FILL_FUNC_BODY
def _get_session(): "Get session in a way to prevent circular imports" FILL_FUNC_BODY
from rocketry import session return session
"Get session in a way to prevent circular imports" from rocketry import session return session
6
31
13
44
def _get_session(): FILL_FUNC_BODY
def _get_session(): "Get session in a way to prevent circular imports" FILL_FUNC_BODY
30,021
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/pybox/container/visitor.py
139,140
3,171
iter
Visitor
140,158
140,158
class Visitor: """A visitor class to visit elements of nested containers Example: -------- v = Visitor( visit_types=(list, tuple) ) # Apply a function to each element (return None) v.apply([[11, 12, 13], 2, [311, [321, 322, 323], 33], 3], print) # Flatt...
class Visitor: """A visitor class to visit elements of nested containers Example: -------- v = Visitor( visit_types=(list, tuple) ) # Apply a function to each element (return None) v.apply([[11, 12, 13], 2, [311, [321, 322, 323], 33], 3], print) # Flatt...
# List: # [1,2,3] # 1, 2, 3 # Dict: # {"a": 1, "b": 2, "c": 3} # 1, 2, 3 cont = self._get_container(obj) if self.iter_func: return self.iter_func(cont) # Try to figure it out if isinstance(cont, dict): ret...
# List: # [1,2,3] # 1, 2, 3 # Dict: # {"a": 1, "b": 2, "c": 3} # 1, 2, 3 cont = self._get_container(obj) if self.iter_func: return self.iter_func(cont) # Try to figure it out if isinstance(cont, dict): ret...
47
1,614
166
1,780
from collections.abc import Iterable class Visitor: """A visitor class to visit elements of nested containers Example: -------- v = Visitor( visit_types=(list, tuple) ) # Apply a function to each element (return None) v.apply([[11, 12, 13], 2, [311, [321, 322, ...
from collections.abc import Iterable class Visitor: """A visitor class to visit elements of nested containers Example: -------- v = Visitor( visit_types=(list, tuple) ) # Apply a function to each element (return None) v.apply([[11, 12, 13], 2, [311, [321, 322, ...
30,022
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/pybox/pkg/path.py
4,5
1,19
find_package_root
9,19
5,19
from pathlib import Path from typing import Union def find_package_root(path) -> Union[Path, None]: FILL_FUNC_BODY
from pathlib import Path from typing import Union def find_package_root(path) -> Union[Path, None]: """Find package root from the path's parents. In other words, find first dir that don't contain __init__.py""" FILL_FUNC_BODY
for i, path in enumerate(Path(path).parents): # Check whether "path/.git" exists and is a directory init_file = path / "__init__.py" if not init_file.is_file(): if i == 0: # There is no package (no __init__.py file at all) return None ...
"""Find package root from the path's parents. In other words, find first dir that don't contain __init__.py""" for i, path in enumerate(Path(path).parents): # Check whether "path/.git" exists and is a directory init_file = path / "__init__.py" if not init_file.is_file(): ...
45
76
114
190
from pathlib import Path from typing import Union def find_package_root(path) -> Union[Path, None]: FILL_FUNC_BODY
from pathlib import Path from typing import Union def find_package_root(path) -> Union[Path, None]: """Find package root from the path's parents. In other words, find first dir that don't contain __init__.py""" FILL_FUNC_BODY
30,023
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/pybox/query/parse.py
33,34
12,143
from_dict
Parser
49,63
34,63
class Parser: """Parse various formats to a generic query language The query language is used to translate filtering from conditions to loggers and APIs to the session in a uniform way. """ operators = { 'min': GreaterEqual, 'max': LessEqual, 'not': NotEqual, 'r...
class Parser: """Parse various formats to a generic query language The query language is used to translate filtering from conditions to loggers and APIs to the session in a uniform way. """ operators = { 'min': GreaterEqual, 'max': LessEqual, 'not': NotEqual, 'r...
statement = None for key, val in d.items(): substatement = self._get_operation(key, val) if statement is None: statement = substatement else: statement &= substatement if statement is None: return true ret...
"""Parse query from dict Examples -------- >>> from rocketry.pybox.query import parser >>> qry = parser.from_dict({ ... 'mydate$min': '2021-07-01', ... 'mydate$max': '2021-07-15', ... 'mykey1': 10, ... 'mystring$regex': r'all of .+...
31
1,188
91
1,279
from typing import List from collections import Counter from .base import ( Key, Any, Equal, NotEqual, GreaterEqual, LessEqual, true ) from .string import Regex class Parser: """Parse various formats to a generic query language The query language is used to translate filtering from condit...
from typing import List from collections import Counter from .base import ( Key, Any, Equal, NotEqual, GreaterEqual, LessEqual, true ) from .string import Regex class Parser: """Parse various formats to a generic query language The query language is used to translate filtering from condit...
30,024
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/pybox/query/string.py
27,28
6,32
match
Regex
28,30
28,30
class Regex(Expression): """Regex expression Parameters ---------- regex : Pattern Regex pattern key : Key Value of the key to match Examples -------- .. code-block:: python Regex(Key('mycol'), regex=r'this .+ thing') """ def __init__(self, key:Key, re...
class Regex(Expression): """Regex expression Parameters ---------- regex : Pattern Regex pattern key : Key Value of the key to match Examples -------- .. code-block:: python Regex(Key('mycol'), regex=r'this .+ thing') """ def __init__(self, key:Key, re...
return bool(re.match(self.regex, self.key.get_value(item)))
return bool(re.match(self.regex, self.key.get_value(item)))
3
170
26
196
import re from typing import Pattern from .base import Expression, Key class Regex(Expression): """Regex expression Parameters ---------- regex : Pattern Regex pattern key : Key Value of the key to match Examples -------- .. code-block:: python Regex(Key('my...
import re from typing import Pattern from .base import Expression, Key class Regex(Expression): """Regex expression Parameters ---------- regex : Pattern Regex pattern key : Key Value of the key to match Examples -------- .. code-block:: python Regex(Key('my...
30,026
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/tasks/code.py
51,52
4,59
execute
CodeTask
52,57
52,57
class CodeTask(Task): """Task to run a piece of Python code This task may be useful for APIs where a trusted user can create tasks or if you have your tasks stored, for example, in a database. Parameters ---------- code : str Piece of Python code to execute. Variable ``return_value...
class CodeTask(Task): """Task to run a piece of Python code This task may be useful for APIs where a trusted user can create tasks or if you have your tasks stored, for example, in a database. Parameters ---------- code : str Piece of Python code to execute. Variable ``return_value...
loc = params glob = {} exec(self.code, glob, loc) return loc.get(self.output_variable, None)
loc = params glob = {} exec(self.code, glob, loc) return loc.get(self.output_variable, None)
12
384
43
427
from rocketry.core import Task class CodeTask(Task): """Task to run a piece of Python code This task may be useful for APIs where a trusted user can create tasks or if you have your tasks stored, for example, in a database. Parameters ---------- code : str Piece of Python code to...
from rocketry.core import Task class CodeTask(Task): """Task to run a piece of Python code This task may be useful for APIs where a trusted user can create tasks or if you have your tasks stored, for example, in a database. Parameters ---------- code : str Piece of Python code to...
30,027
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/tasks/maintain/os.py
14,15
6,18
get_default_name
Restart
15,18
15,18
class Restart(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerRestart() def get_default_name(self, **kwargs): FILL_FUNC_BODY
class Restart(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerRestart() def get_default_name(self, **kwargs): FILL_FUNC_BODY
return "restart"
return "restart"
2
82
12
94
from rocketry.core.task import Task from rocketry.exc import SchedulerRestart, SchedulerExit class Restart(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerRestart() def get_default_name(self, **k...
from rocketry.core.task import Task from rocketry.exc import SchedulerRestart, SchedulerExit class Restart(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerRestart() def get_default_name(self, **k...
30,028
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/tasks/maintain/os.py
27,28
18,29
get_default_name
ShutDown
28,29
28,29
class ShutDown(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerExit() def get_default_name(self, **kwargs): FILL_FUNC_BODY
class ShutDown(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerExit() def get_default_name(self, **kwargs): FILL_FUNC_BODY
return "shutdown"
return "shutdown"
2
83
8
91
from rocketry.core.task import Task from rocketry.exc import SchedulerRestart, SchedulerExit class Restart(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerRestart() def get_default_name(self, **k...
from rocketry.core.task import Task from rocketry.exc import SchedulerRestart, SchedulerExit class Restart(Task): def __init__(self, **kwargs): super().__init__(**kwargs) self.execution = "main" def execute(self, **kwargs): raise SchedulerRestart() def get_default_name(self, **k...
30,029
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/tasks/run_id.py
4,5
1,14
increment
6,12
5,12
import itertools import uuid as _uuid def increment(task, params=None) -> str: FILL_FUNC_BODYdef uuid(task, params=None) -> str: return _uuid.uuid4().hex
import itertools import uuid as _uuid def increment(task, params=None) -> str: "Generate Run IDs that are increment numbers" FILL_FUNC_BODYdef uuid(task, params=None) -> str: return _uuid.uuid4().hex
ids = [run.run_id for run in task._run_stack] for i in itertools.count(1): i = str(i) if i not in ids: return i
"Generate Run IDs that are increment numbers" ids = [run.run_id for run in task._run_stack] for i in itertools.count(1): i = str(i) if i not in ids: return i
21
74
60
134
import itertools import uuid as _uuid def increment(task, params=None) -> str: FILL_FUNC_BODYdef uuid(task, params=None) -> str: return _uuid.uuid4().hex
import itertools import uuid as _uuid def increment(task, params=None) -> str: "Generate Run IDs that are increment numbers" FILL_FUNC_BODYdef uuid(task, params=None) -> str: return _uuid.uuid4().hex
30,030
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/time/construct.py
45,46
1,54
get_on
46,50
46,50
from rocketry.time import ( TimeOfWeek, TimeOfDay, TimeOfHour, TimeOfMinute, TimeOfMonth ) TIME_CLASSES = { "monthly": TimeOfMonth, "weekly": TimeOfWeek, "daily": TimeOfDay, "hourly": TimeOfHour, "minutely": TimeOfMinute, "month": TimeOfMonth, "week": TimeOfWeek, "d...
from rocketry.time import ( TimeOfWeek, TimeOfDay, TimeOfHour, TimeOfMinute, TimeOfMonth ) TIME_CLASSES = { "monthly": TimeOfMonth, "weekly": TimeOfWeek, "daily": TimeOfDay, "hourly": TimeOfHour, "minutely": TimeOfMinute, "month": TimeOfMonth, "week": TimeOfWeek, "d...
type_ = type_.lower() cls = TIME_CLASSES[type_] return cls(start, time_point=True)
type_ = type_.lower() cls = TIME_CLASSES[type_] return cls(start, time_point=True)
9
421
44
465
from rocketry.time import ( TimeOfWeek, TimeOfDay, TimeOfHour, TimeOfMinute, TimeOfMonth ) TIME_CLASSES = { "monthly": TimeOfMonth, "weekly": TimeOfWeek, "daily": TimeOfDay, "hourly": TimeOfHour, "minutely": TimeOfMinute, "month": TimeOfMonth, "week": TimeOfWeek, "d...
from rocketry.time import ( TimeOfWeek, TimeOfDay, TimeOfHour, TimeOfMinute, TimeOfMonth ) TIME_CLASSES = { "monthly": TimeOfMonth, "weekly": TimeOfWeek, "daily": TimeOfDay, "hourly": TimeOfHour, "minutely": TimeOfMinute, "month": TimeOfMonth, "week": TimeOfWeek, "d...
30,031
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/time/cron.py
37,38
8,112
_get_period_from_expr
Cron
38,89
38,89
@dataclass(frozen=True) class Cron(TimePeriod): minute: str = "*" hour: str = "*" day_of_month: str = "*" month: str = "*" day_of_week: str = "*" def __init__(self, minute="*", hour="*", day_of_month="*", month="*", day_of_week="*"): object.__setattr__(self, "minute", minute) o...
@dataclass(frozen=True) class Cron(TimePeriod): minute: str = "*" hour: str = "*" day_of_month: str = "*" month: str = "*" day_of_week: str = "*" def __init__(self, minute="*", hour="*", day_of_month="*", month="*", day_of_week="*"): object.__setattr__(self, "minute", minute) o...
conv = (lambda i: i) if conv is None else conv exprs = expression.split(",") full_period = None for expr in exprs: if expr == "*": # Any continue if "/" in expr: expr, step = expr.split("/") step_per...
conv = (lambda i: i) if conv is None else conv exprs = expression.split(",") full_period = None for expr in exprs: if expr == "*": # Any continue if "/" in expr: expr, step = expr.split("/") step_per...
166
666
480
1,146
from typing import Callable from dataclasses import dataclass from rocketry.core.time.base import TimePeriod, always from .interval import TimeOfHour, TimeOfDay, TimeOfMinute, TimeOfWeek, TimeOfMonth, TimeOfYear @dataclass(frozen=True) class Cron(TimePeriod): minute: str = "*" hour: str = "*" day_of_mon...
from typing import Callable from dataclasses import dataclass from rocketry.core.time.base import TimePeriod, always from .interval import TimeOfHour, TimeOfDay, TimeOfMinute, TimeOfWeek, TimeOfMonth, TimeOfYear @dataclass(frozen=True) class Cron(TimePeriod): minute: str = "*" hour: str = "*" day_of_mon...
30,032
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/time/delta.py
37,38
9,61
rollback
TimeSpanDelta
39,43
38,43
@dataclass(frozen=True, init=False) class TimeSpanDelta(TimeDelta): near: int far: int reference: Union[datetime.datetime, Callable] = field(default=None) def __init__(self, near=None, far=None, reference=None, **kwargs): near = 0 if near is None else near object.__setattr__(self, "ne...
@dataclass(frozen=True, init=False) class TimeSpanDelta(TimeDelta): near: int far: int reference: Union[datetime.datetime, Callable] = field(default=None) def __init__(self, near=None, far=None, reference=None, **kwargs): near = 0 if near is None else near object.__setattr__(self, "ne...
start = dt - self.far if self.far is not None else self.min end = dt - self.near return Interval(start, end)
"Get previous interval (including currently ongoing)" start = dt - self.far if self.far is not None else self.min end = dt - self.near return Interval(start, end)
20
533
44
577
import time import datetime from dataclasses import dataclass, field from typing import Callable, Union from rocketry.core.time import TimeDelta from rocketry.pybox.time import to_timedelta, Interval @dataclass(frozen=True, init=False) class TimeSpanDelta(TimeDelta): near: int far: int reference: Union[d...
import time import datetime from dataclasses import dataclass, field from typing import Callable, Union from rocketry.core.time import TimeDelta from rocketry.pybox.time import to_timedelta, Interval @dataclass(frozen=True, init=False) class TimeSpanDelta(TimeDelta): near: int far: int reference: Union[d...
30,033
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/utils/dependencies.py
72,73
1,75
get_dependencies
74,75
73,75
from typing import List, Optional, Union from pydantic import BaseModel from rocketry.conditions import Any, All, DependFinish, DependSuccess from rocketry.conditions.task import DependFailure from rocketry.core import Task from rocketry import Session class Link: def __init__(self, parent: Ta...
from typing import List, Optional, Union from pydantic import BaseModel from rocketry.conditions import Any, All, DependFinish, DependSuccess from rocketry.conditions.task import DependFailure from rocketry.core import Task from rocketry import Session class Link: def __init__(self, parent: Ta...
return list(Dependencies(session))
"Get list of dependency links" return list(Dependencies(session))
2
702
11
713
from typing import List, Optional, Union from pydantic import BaseModel from rocketry.conditions import Any, All, DependFinish, DependSuccess from rocketry.conditions.task import DependFailure from rocketry.core import Task from rocketry import Session class Link: def __init__(self, parent: Ta...
from typing import List, Optional, Union from pydantic import BaseModel from rocketry.conditions import Any, All, DependFinish, DependSuccess from rocketry.conditions.task import DependFailure from rocketry.core import Task from rocketry import Session class Link: def __init__(self, parent: Ta...
30,034
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry
/home/hieuvd/dung_repo/raw/stars_02/Miksus_rocketry/rocketry/rocketry/utils/dependencies.py
58,59
45,72
_get_links
Dependencies
59,72
59,72
class Dependencies(BaseModel): class Config: arbitrary_types_allowed = True session: Session def __init__(self, session, **kwargs): super().__init__(session=session, **kwargs) def __iter__(self): for task in self.session.tasks: yield from self._get_links(task) ...
class Dependencies(BaseModel): class Config: arbitrary_types_allowed = True session: Session def __init__(self, session, **kwargs): super().__init__(session=session, **kwargs) def __iter__(self): for task in self.session.tasks: yield from self._get_links(task) ...
cond = task.start_cond if isinstance(cond, (Any, All)): for subcond in cond: if isinstance(subcond, (DependFinish, DependSuccess, DependFailure)): req_task = subcond.depend_task req_task = self.session[req_task] yiel...
cond = task.start_cond if isinstance(cond, (Any, All)): for subcond in cond: if isinstance(subcond, (DependFinish, DependSuccess, DependFailure)): req_task = subcond.depend_task req_task = self.session[req_task] yiel...
42
123
187
310
from typing import List, Optional, Union from pydantic import BaseModel from rocketry.conditions import Any, All, DependFinish, DependSuccess from rocketry.conditions.task import DependFailure from rocketry.core import Task from rocketry import Session class Link: def __init__(self, parent: Ta...
from typing import List, Optional, Union from pydantic import BaseModel from rocketry.conditions import Any, All, DependFinish, DependSuccess from rocketry.conditions.task import DependFailure from rocketry.core import Task from rocketry import Session class Link: def __init__(self, parent: Ta...
30,122
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts/yt_fts/config.py
96,97
1,120
get_or_make_chroma_path
97,116
97,116
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): platform = sys.platform if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') if not os.path.exists(config_path): return None else: ...
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): platform = sys.platform if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') if not os.path.exists(config_path): return None else: ...
config_path = get_config_path() if config_path is None: config_path = make_config_dir() if config_path is None: print("unable to make config path, using current directory") return os.path.join(os.getcwd(), "chroma") chroma_path = os.path.join(config_path, "chr...
config_path = get_config_path() if config_path is None: config_path = make_config_dir() if config_path is None: print("unable to make config path, using current directory") return os.path.join(os.getcwd(), "chroma") chroma_path = os.path.join(config_path, "chr...
38
847
173
1,020
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): platform = sys.platform if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') if not os.path.exists(config_path): return None else: ...
import sys import os import chromadb from chromadb.config import Settings def get_config_path(): platform = sys.platform if platform == 'win32': config_path = os.path.join(os.getenv('APPDATA'), 'yt-fts') if not os.path.exists(config_path): return None else: ...
30,124
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts/yt_fts/embeddings.py
7,8
1,44
add_embeddings_to_chroma
8,38
8,38
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
chroma_client = get_chroma_client() collection = chroma_client.get_or_create_collection(name="subEmbeddings") for sub in track(subs, description="Getting embeddings"): channel_id = sub[0] video_id = sub[1] start_time = sub[2] text = sub[3] if text == '': ...
chroma_client = get_chroma_client() collection = chroma_client.get_or_create_collection(name="subEmbeddings") for sub in track(subs, description="Getting embeddings"): channel_id = sub[0] video_id = sub[1] start_time = sub[2] text = sub[3] if text == '': ...
54
146
275
421
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
from openai import OpenAI from rich.progress import track from rich.console import Console from .config import get_chroma_client def add_embeddings_to_chroma(subs, openai_client): FILL_FUNC_BODYdef get_embedding(text, model="text-embedding-ada-002", client=None): if client is None: client = OpenAI() tex...
30,125
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts/yt_fts/list.py
12,13
1,138
show_video_transcript
13,41
13,41
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
con = sqlite3.connect(get_db_path()) cur = con.cursor() cur.execute("SELECT * FROM subtitles WHERE video_id=?", (video_id,)) rows = cur.fetchall() console = Console() word_count = 0 for row in rows: timestamp = row[2] time = time_to_secs(timestamp) url = f"https://ww...
con = sqlite3.connect(get_db_path()) cur = con.cursor() cur.execute("SELECT * FROM subtitles WHERE video_id=?", (video_id,)) rows = cur.fetchall() console = Console() word_count = 0 for row in rows: timestamp = row[2] time = time_to_secs(timestamp) url = f"https://ww...
64
1,095
364
1,459
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
import sqlite3 from rich.console import Console from rich.table import Table from .db_utils import get_title_from_db from .utils import time_to_secs, get_time_delta from .config import get_db_path def show_video_transcript(video_id): FILL_FUNC_BODYdef show_video_list(channel_id): con = sqlite3.connect(get_db...
30,126
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts/yt_fts/update.py
6,7
1,42
update_channel
10,42
7,42
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): FILL_FUNC_BODY
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): """ Downloads all the videos from a channel to a tmp directory """ ...
with tempfile.TemporaryDirectory() as tmp_dir: channel_url = f"https://www.youtube.com/channel/{channel_id}/videos" public_video_ids = get_videos_list(channel_url) num_public_vids = len(public_video_ids) num_local_vids = get_num_vids(channel_id) if num_public_vids == num_l...
""" Downloads all the videos from a channel to a tmp directory """ with tempfile.TemporaryDirectory() as tmp_dir: channel_url = f"https://www.youtube.com/channel/{channel_id}/videos" public_video_ids = get_videos_list(channel_url) num_public_vids = len(public_video_ids) ...
97
117
447
564
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): FILL_FUNC_BODY
import tempfile, os from .download import get_videos_list, download_vtts, vtt_to_db from .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id def update_channel(channel_id, channel_name, language, number_of_jobs, s): """ Downloads all the videos from a channel to a tmp directory """ ...
30,127
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts/yt_fts/utils.py
73,74
1,188
get_api_key
74,82
74,82
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
import os api_key = os.environ.get("OPENAI_API_KEY") if api_key is None: return None return api_key
import os api_key = os.environ.get("OPENAI_API_KEY") if api_key is None: return None return api_key
13
1,722
55
1,777
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
""" This is where I'm putting all the functions that don't belong anywhere else """ import re import sqlite3 def show_message(code): error_dict = { "search_too_long": "Error: Search text must be less than 40 characters", "no_matches_found": "No matches found.\n- Try shortening the search text or us...
30,128
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts
/home/hieuvd/dung_repo/raw/stars_02/NotJoeMartinez_yt-fts/yt-fts/yt_fts/vector_search.py
72,73
1,130
print_vector_search_results
82,121
73,121
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
console = Console() channel_names = [] for match in reversed(res): distance = match["distance"] link = match["link"] text = bold_query_matches(match["subs"], query) time_stamp = match["start_time"] channel_id = match["channel_id"] video_id = match["...
""" { 'channel_name': 'Peter Whidden', 'video_title': 'Training AI to Play Pokemon with Reinforcement Learning - YouTube', 'subs': 'choosing a Pokemon and winning its first', 'start_time': '00:22:14.909', 'video_id': 'DcYLT37ImBY', 'link': 'https://youtu.be/DcYLT37ImBY?t=1331'} ...
92
906
472
1,378
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
import chromadb from rich.console import Console from sqlite_utils import Database from .utils import time_to_secs, bold_query_matches from .embeddings import get_embedding from .config import get_chroma_client from .db_utils import get_channel_name_from_video_id, get_title_from_db from .download import get_channel...
30,129
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/api_calls/censys.py
27,28
12,46
search
CensysAPIHook
31,46
28,46
class CensysAPIHook(object): """ Censys API hook """ def __init__(self, identity=None, token=None, query=None, proxy=None, agent=None, save_mode=None, **kwargs): self.id = identity self.token = token self.query = query self.proxy = proxy self.user_agent = agent ...
class CensysAPIHook(object): """ Censys API hook """ def __init__(self, identity=None, token=None, query=None, proxy=None, agent=None, save_mode=None, **kwargs): self.id = identity self.token = token self.query = query self.proxy = proxy self.user_agent = agent ...
discovered_censys_hosts = set() try: lib.settings.start_animation("searching Censys with given query '{}'".format(self.query)) req = requests.post( API_URLS["censys"], auth=(self.id, self.token), json={"query": self.query}, headers=self.user_agent,...
""" connect to the Censys API and pull all IP addresses from the provided query """ discovered_censys_hosts = set() try: lib.settings.start_animation("searching Censys with given query '{}'".format(self.query)) req = requests.post( API_URLS...
40
164
221
385
import requests import lib.settings from lib.errors import AutoSploitAPIConnectionError from lib.settings import ( HOST_FILE, API_URLS, write_to_file ) class CensysAPIHook(object): """ Censys API hook """ def __init__(self, identity=None, token=None, query=None, proxy=None, agent=None, ...
import requests import lib.settings from lib.errors import AutoSploitAPIConnectionError from lib.settings import ( HOST_FILE, API_URLS, write_to_file ) class CensysAPIHook(object): """ Censys API hook """ def __init__(self, identity=None, token=None, query=None, proxy=None, agent=None, ...
30,130
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/api_calls/honeyscore_hook.py
15,16
4,22
make_request
HoneyHook
16,22
16,22
class HoneyHook(object): def __init__(self, ip_addy, api_key): self.ip = ip_addy self.api_key = api_key self.url = "https://api.shodan.io/labs/honeyscore/{ip}?key={key}" self.headers = { "Referer": "https://honeyscore.shodan.io/", "Origin": "https://honeyscor...
class HoneyHook(object): def __init__(self, ip_addy, api_key): self.ip = ip_addy self.api_key = api_key self.url = "https://api.shodan.io/labs/honeyscore/{ip}?key={key}" self.headers = { "Referer": "https://honeyscore.shodan.io/", "Origin": "https://honeyscor...
try: req = requests.get(self.url.format(ip=self.ip, key=self.api_key), headers=self.headers) honeyscore = float(req.content) except Exception: honeyscore = 0.0 return honeyscore
try: req = requests.get(self.url.format(ip=self.ip, key=self.api_key), headers=self.headers) honeyscore = float(req.content) except Exception: honeyscore = 0.0 return honeyscore
16
145
73
218
import requests class HoneyHook(object): def __init__(self, ip_addy, api_key): self.ip = ip_addy self.api_key = api_key self.url = "https://api.shodan.io/labs/honeyscore/{ip}?key={key}" self.headers = { "Referer": "https://honeyscore.shodan.io/", "Origin": ...
import requests class HoneyHook(object): def __init__(self, ip_addy, api_key): self.ip = ip_addy self.api_key = api_key self.url = "https://api.shodan.io/labs/honeyscore/{ip}?key={key}" self.headers = { "Referer": "https://honeyscore.shodan.io/", "Origin": ...
30,131
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/api_calls/shodan.py
28,29
14,48
search
ShodanAPIHook
32,48
29,48
class ShodanAPIHook(object): """ Shodan API hook, saves us from having to install another dependency """ def __init__(self, token=None, query=None, proxy=None, agent=None, save_mode=None, **kwargs): self.token = token self.query = query self.proxy = proxy self.user_agen...
class ShodanAPIHook(object): """ Shodan API hook, saves us from having to install another dependency """ def __init__(self, token=None, query=None, proxy=None, agent=None, save_mode=None, **kwargs): self.token = token self.query = query self.proxy = proxy self.user_agen...
start_animation("searching Shodan with given query '{}'".format(self.query)) discovered_shodan_hosts = set() try: req = requests.get( API_URLS["shodan"].format(query=self.query, token=self.token), proxies=self.proxy, headers=self.user_agent ...
""" connect to the API and grab all IP addresses associated with the provided query """ start_animation("searching Shodan with given query '{}'".format(self.query)) discovered_shodan_hosts = set() try: req = requests.get( API_URLS["shodan"].for...
37
160
219
379
import json import requests from lib.settings import start_animation from lib.errors import AutoSploitAPIConnectionError from lib.settings import ( API_URLS, HOST_FILE, write_to_file ) class ShodanAPIHook(object): """ Shodan API hook, saves us from having to install another dependency """ ...
import json import requests from lib.settings import start_animation from lib.errors import AutoSploitAPIConnectionError from lib.settings import ( API_URLS, HOST_FILE, write_to_file ) class ShodanAPIHook(object): """ Shodan API hook, saves us from having to install another dependency """ ...
30,132
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/api_calls/zoomeye.py
57,58
16,90
search
ZoomEyeAPIHook
62,90
58,90
class ZoomEyeAPIHook(object): """ API hook for the ZoomEye API, in order to connect you need to provide a phone number so we're going to use some 'lifted' credentials to login for us """ def __init__(self, query=None, proxy=None, agent=None, save_mode=None, **kwargs): self.query = query ...
class ZoomEyeAPIHook(object): """ API hook for the ZoomEye API, in order to connect you need to provide a phone number so we're going to use some 'lifted' credentials to login for us """ def __init__(self, query=None, proxy=None, agent=None, save_mode=None, **kwargs): self.query = query ...
start_animation("searching ZoomEye with given query '{}'".format(self.query)) discovered_zoomeye_hosts = set() try: token = self.__get_auth() if self.user_agent is None: headers = {"Authorization": "JWT {}".format(str(token["access_token"]))} e...
""" connect to the API and pull all the IP addresses that are associated with the given query """ start_animation("searching ZoomEye with given query '{}'".format(self.query)) discovered_zoomeye_hosts = set() try: token = self.__get_auth() ...
79
478
399
877
import os import base64 import json import requests from lib.settings import start_animation from lib.errors import AutoSploitAPIConnectionError from lib.settings import ( API_URLS, HOST_FILE, write_to_file ) class ZoomEyeAPIHook(object): """ API hook for the ZoomEye API, in order to connect yo...
import os import base64 import json import requests from lib.settings import start_animation from lib.errors import AutoSploitAPIConnectionError from lib.settings import ( API_URLS, HOST_FILE, write_to_file ) class ZoomEyeAPIHook(object): """ API hook for the ZoomEye API, in order to connect yo...
30,133
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/lib/banner.py
18,19
1,130
banner_2
19,34
19,34
import os import random VERSION = "4.0" def banner_1(line_sep="#--", space=" " * 30): banner = """\033[1m\033[36m{space_sep}_____ _ _____ _ _ _ {sep1}Author : Vector/NullArray | _ |_ _| |_ ___| __|___| |___|_| |_ {sep1}Twitter: @Real__Vector | | | | _| . |__ | . | | . | | _| {sep...
import os import random VERSION = "4.0" def banner_1(line_sep="#--", space=" " * 30): banner = """\033[1m\033[36m{space_sep}_____ _ _____ _ _ _ {sep1}Author : Vector/NullArray | _ |_ _| |_ ___| __|___| |___|_| |_ {sep1}Twitter: @Real__Vector | | | | _| . |__ | . | | . | | _| {sep...
banner = r""" {blue}--+{end} {red}Graffiti the world with exploits{end} {blue}+--{end} {blue}--+{end} __ ____ {blue}+--{end} {blue}--+{end} / _\ / ___) {blue}+--{end} {blue}--+{end} / \\___ \ {blue}+--{end} {blue}--+{end} \_/\_/(____/ ...
banner = r""" {blue}--+{end} {red}Graffiti the world with exploits{end} {blue}+--{end} {blue}--+{end} __ ____ {blue}+--{end} {blue}--+{end} / _\ / ___) {blue}+--{end} {blue}--+{end} / \\___ \ {blue}+--{end} {blue}--+{end} \_/\_/(____/ ...
63
1,582
342
1,924
import os import random VERSION = "4.0" def banner_1(line_sep="#--", space=" " * 30): banner = """\033[1m\033[36m{space_sep}_____ _ _____ _ _ _ {sep1}Author : Vector/NullArray | _ |_ _| |_ ___| __|___| |___|_| |_ {sep1}Twitter: @Real__Vector | | | | _| . |__ | . | | . | | _| {sep...
import os import random VERSION = "4.0" def banner_1(line_sep="#--", space=" " * 30): banner = """\033[1m\033[36m{space_sep}_____ _ _____ _ _ _ {sep1}Author : Vector/NullArray | _ |_ _| |_ ___| __|___| |___|_| |_ {sep1}Twitter: @Real__Vector | | | | _| . |__ | . | | . | | _| {sep...
30,135
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/lib/creation/ip_generator.py
41,42
1,67
check_ip_wrapper
46,67
42,67
import socket import itertools from multiprocessing import Pool def generate_ip_range(selected_range): """ generate an IP address range from each provided node. for example `10.0.1-10.1-10` will return a generator object that has IP `10.0.1.1 - 10.0.10.10` in it """ octets = selected_range.sp...
import socket import itertools from multiprocessing import Pool def generate_ip_range(selected_range): """ generate an IP address range from each provided node. for example `10.0.1-10.1-10` will return a generator object that has IP `10.0.1.1 - 10.0.10.10` in it """ octets = selected_range.sp...
alive_ips = [] ips_to_use = [] i = 0 proc_pool = Pool(processes=35) for ip in generated_ips: ips_to_use.append(ip) i += 1 if i == limit: break for ip in ips_to_use: try: result = proc_pool.apply_async(check_ip_alive, args=(ip,)).get() ...
""" multiprocess the check_ip_alive function in order to proces a large amount of IP addresses quickly """ alive_ips = [] ips_to_use = [] i = 0 proc_pool = Pool(processes=35) for ip in generated_ips: ips_to_use.append(ip) i += 1 if i == limit: bre...
46
389
183
572
import socket import itertools from multiprocessing import Pool def generate_ip_range(selected_range): """ generate an IP address range from each provided node. for example `10.0.1-10.1-10` will return a generator object that has IP `10.0.1.1 - 10.0.10.10` in it """ octets = selected_range.sp...
import socket import itertools from multiprocessing import Pool def generate_ip_range(selected_range): """ generate an IP address range from each provided node. for example `10.0.1-10.1-10` will return a generator object that has IP `10.0.1.1 - 10.0.10.10` in it """ octets = selected_range.sp...
30,140
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit
/home/hieuvd/dung_repo/raw/stars_02/NullArray_AutoSploit/AutoSploit/lib/settings.py
34,35
24,46
complete_text
AutoSploitCompleter
35,46
35,46
class AutoSploitCompleter(object): """ object to create an auto completer for the terminal """ def __init__(self, opts): self.opts = sorted(opts) self.possibles = [] def complete_text(self, text, state): FILL_FUNC_BODY
class AutoSploitCompleter(object): """ object to create an auto completer for the terminal """ def __init__(self, opts): self.opts = sorted(opts) self.possibles = [] def complete_text(self, text, state): FILL_FUNC_BODY
if state == 0: if text: self.possibles = [m for m in self.opts if m.startswith(text)] else: self.possibles = self.opts[:] try: return self.possibles[state] except IndexError: return None
if state == 0: if text: self.possibles = [m for m in self.opts if m.startswith(text)] else: self.possibles = self.opts[:] try: return self.possibles[state] except IndexError: return None
26
84
89
173
import os import re import sys import time import socket import random import platform import getpass import tempfile import readline import distutils.spawn from subprocess import ( PIPE, Popen ) import psutil import lib.output import lib.banner import lib.jsonize class AutoSploitCompleter(object): """...
import os import re import sys import time import socket import random import platform import getpass import tempfile import readline import distutils.spawn from subprocess import ( PIPE, Popen ) import psutil import lib.output import lib.banner import lib.jsonize class AutoSploitCompleter(object): """...
30,164
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/GPEN/face_detect/utils/timer.py
35,36
11,41
clear
Timer
36,41
36,41
class Timer(object): """A simple timer.""" def __init__(self): self.total_time = 0. self.calls = 0 self.start_time = 0. self.diff = 0. self.average_time = 0. def tic(self): # using time.time instead of time.clock because time time.clock # does not nor...
class Timer(object): """A simple timer.""" def __init__(self): self.total_time = 0. self.calls = 0 self.start_time = 0. self.diff = 0. self.average_time = 0. def tic(self): # using time.time instead of time.clock because time time.clock # does not nor...
self.total_time = 0. self.calls = 0 self.start_time = 0. self.diff = 0. self.average_time = 0.
self.total_time = 0. self.calls = 0 self.start_time = 0. self.diff = 0. self.average_time = 0.
15
227
52
279
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import time class Timer(object): """A simple timer.""" def __...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import time class Timer(object): """A simple timer.""" def __...
30,165
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/data/template_dataset.py
21,23
19,76
modify_commandline_options
TemplateDataset
32,36
23,36
class TemplateDataset(BaseDataset): """A template dataset class for you to implement custom datasets.""" @staticmethod def modify_commandline_options(parser, is_train): FILL_FUNC_BODY def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) --...
class TemplateDataset(BaseDataset): """A template dataset class for you to implement custom datasets.""" @staticmethod def modify_commandline_options(parser, is_train): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser ...
parser.add_argument('--new_dataset_option', type=float, default=1.0, help='new dataset option') parser.set_defaults(max_dataset_size=10, new_dataset_option=2.0) # specify dataset-specific default values return parser
"""Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. ...
15
628
76
704
"""Dataset class template This module provides a template for users to implement custom datasets. You can specify '--dataset_mode template' to use this dataset. The class name should be consistent with both the filename and its dataset_mode option. The filename should be <dataset_mode>_dataset.py The class name should...
"""Dataset class template This module provides a template for users to implement custom datasets. You can specify '--dataset_mode template' to use this dataset. The class name should be consistent with both the filename and its dataset_mode option. The filename should be <dataset_mode>_dataset.py The class name should...
30,166
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/models/arcface_torch/utils/utils_config.py
5,6
1,17
get_config
6,17
6,17
import importlib import os.path as osp def get_config(config_file): FILL_FUNC_BODY
import importlib import os.path as osp def get_config(config_file): FILL_FUNC_BODY
assert config_file.startswith('configs/'), 'config file setting must start with configs/' temp_config_name = osp.basename(config_file) temp_module_name = osp.splitext(temp_config_name)[0] config = importlib.import_module("configs.base") cfg = config.config config = importlib.import_module("confi...
assert config_file.startswith('configs/'), 'config file setting must start with configs/' temp_config_name = osp.basename(config_file) temp_module_name = osp.splitext(temp_config_name)[0] config = importlib.import_module("configs.base") cfg = config.config config = importlib.import_module("confi...
40
34
183
217
import importlib import os.path as osp def get_config(config_file): FILL_FUNC_BODY
import importlib import os.path as osp def get_config(config_file): FILL_FUNC_BODY
30,167
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/models/arcface_torch/utils/utils_logging.py
30,31
1,42
init_logging
31,42
31,42
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): self.val = 0 ...
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): self.val = 0 ...
if rank == 0: log_root = logging.getLogger() log_root.setLevel(logging.INFO) formatter = logging.Formatter("Training: %(asctime)s-%(message)s") handler_file = logging.FileHandler(os.path.join(models_root, "training.log")) handler_stream = logging.StreamHandler(sys.stdout) ...
if rank == 0: log_root = logging.getLogger() log_root.setLevel(logging.INFO) formatter = logging.Formatter("Training: %(asctime)s-%(message)s") handler_file = logging.FileHandler(os.path.join(models_root, "training.log")) handler_stream = logging.StreamHandler(sys.stdout) ...
27
191
181
372
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): self.val = 0 ...
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): self.val = 0 ...
30,168
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/models/arcface_torch/utils/utils_logging.py
17,18
6,30
reset
AverageMeter
18,23
18,23
class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): FILL_FUNC_BODY def update(self, val, n=1): self.va...
class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): FILL_FUNC_BODY def update(self, val, n=1): self.va...
self.val = 0 self.avg = 0 self.sum = 0 self.count = 0
self.val = 0 self.avg = 0 self.sum = 0 self.count = 0
12
138
35
173
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): FILL_FUNC_BODY def u...
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): FILL_FUNC_BODY def u...
30,169
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/options/test_options.py
13,14
7,22
initialize
TestOptions
14,22
14,22
class TestOptions(BaseOptions): """This class includes test options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): FILL_FUNC_BODY
class TestOptions(BaseOptions): """This class includes test options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): FILL_FUNC_BODY
parser = BaseOptions.initialize(self, parser) # define shared options parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc') parser.add_argument('--dataset_mode', type=str, default=None, help='chooses how datasets are loaded. [None | flist]') parser.add_a...
parser = BaseOptions.initialize(self, parser) # define shared options parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc') parser.add_argument('--dataset_mode', type=str, default=None, help='chooses how datasets are loaded. [None | flist]') parser.add_a...
49
53
158
211
"""This script contains the test options for Deep3DFaceRecon_pytorch """ from .base_options import BaseOptions class TestOptions(BaseOptions): """This class includes test options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): FILL_FUNC_BODY
"""This script contains the test options for Deep3DFaceRecon_pytorch """ from .base_options import BaseOptions class TestOptions(BaseOptions): """This class includes test options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): FILL_FUNC_BODY
30,170
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/options/train_options.py
13,14
7,54
initialize
TrainOptions
14,54
14,54
class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): FILL_FUNC_BODY
class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): FILL_FUNC_BODY
parser = BaseOptions.initialize(self, parser) # dataset parameters # for train parser.add_argument('--data_root', type=str, default='./', help='dataset root') parser.add_argument('--flist', type=str, default='datalist/train/masks.txt', help='list of mask names of training set') ...
parser = BaseOptions.initialize(self, parser) # dataset parameters # for train parser.add_argument('--data_root', type=str, default='./', help='dataset root') parser.add_argument('--flist', type=str, default='datalist/train/masks.txt', help='list of mask names of training set') ...
279
53
1,077
1,130
"""This script contains the training options for Deep3DFaceRecon_pytorch """ from .base_options import BaseOptions from util import util class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser):...
"""This script contains the training options for Deep3DFaceRecon_pytorch """ from .base_options import BaseOptions from util import util class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser):...
30,171
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/third_part/face3d/util/generate_list.py
21,22
1,35
check_list
22,35
22,35
"""This script is to generate training list files for Deep3DFaceRecon_pytorch """ import os # save path to training data def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''): save_path = os.path.join(save_folder, mode) if not os.path.isdir(save_path): os.ma...
"""This script is to generate training list files for Deep3DFaceRecon_pytorch """ import os # save path to training data def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''): save_path = os.path.join(save_folder, mode) if not os.path.isdir(save_path): os.ma...
lms_list, imgs_list, msks_list = [], [], [] for i in range(len(rlms_list)): flag = 'false' lm_path = rlms_list[i] im_path = rimgs_list[i] msk_path = rmsks_list[i] if os.path.isfile(lm_path) and os.path.isfile(im_path) and os.path.isfile(msk_path): flag = 'true...
lms_list, imgs_list, msks_list = [], [], [] for i in range(len(rlms_list)): flag = 'false' lm_path = rlms_list[i] im_path = rimgs_list[i] msk_path = rmsks_list[i] if os.path.isfile(lm_path) and os.path.isfile(im_path) and os.path.isfile(msk_path): flag = 'true...
42
324
227
551
"""This script is to generate training list files for Deep3DFaceRecon_pytorch """ import os # save path to training data def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''): save_path = os.path.join(save_folder, mode) if not os.path.isdir(save_path): os.ma...
"""This script is to generate training list files for Deep3DFaceRecon_pytorch """ import os # save path to training data def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''): save_path = os.path.join(save_folder, mode) if not os.path.isdir(save_path): os.ma...
30,172
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/utils/hparams.py
134,135
1,138
hparams_debug_string
135,138
135,138
import os class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, valu...
import os class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, valu...
values = hparams.values() hp = [" %s: %s" % (name, values[name]) for name in sorted(values) if name != "sentences"] return "Hyperparameters:\n" + "\n".join(hp)
values = hparams.values() hp = [" %s: %s" % (name, values[name]) for name in sorted(values) if name != "sentences"] return "Hyperparameters:\n" + "\n".join(hp)
23
1,896
64
1,960
import os class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, valu...
import os class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, valu...
30,173
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking
/home/hieuvd/dung_repo/raw/stars_02/OpenTalker_video-retalking/video-retalking/utils/hparams.py
15,16
3,20
set_hparam
HParams
16,20
16,20
class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, value): FILL_FU...
class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, value): FILL_FU...
self.data[key] = value # Default hyperparameters
self.data[key] = value # Default hyperparameters
6
127
22
149
import os class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, valu...
import os class HParams: def __init__(self, **kwargs): self.data = {} for key, value in kwargs.items(): self.data[key] = value def __getattr__(self, key): if key not in self.data: raise AttributeError("'HParams' object has no attribute %s" % key) return self.data[key] def set_hparam(self, key, valu...
30,209
/home/hieuvd/dung_repo/raw/stars_02/PowerDNS-Admin_PowerDNS-Admin/PowerDNS-Admin
/home/hieuvd/dung_repo/raw/stars_02/PowerDNS-Admin_PowerDNS-Admin/PowerDNS-Admin/powerdnsadmin/lib/errors.py
9,10
1,21
to_dict
StructuredException
10,21
10,21
class StructuredException(Exception): status_code = 0 def __init__(self, name=None, message="You want override this error!"): Exception.__init__(self) self.message = message self.name = name def to_dict(self): FILL_FUNC_BODY
class StructuredException(Exception): status_code = 0 def __init__(self, name=None, message="You want override this error!"): Exception.__init__(self) self.message = message self.name = name def to_dict(self): FILL_FUNC_BODY
rv = dict() msg = '' if self.name: msg = '{0} {1}'.format(self.message, self.name) else: msg = self.message rv['msg'] = msg return rv
rv = dict() msg = '' if self.name: msg = '{0} {1}'.format(self.message, self.name) else: msg = self.message rv['msg'] = msg return rv
22
80
80
160
class StructuredException(Exception): status_code = 0 def __init__(self, name=None, message="You want override this error!"): Exception.__init__(self) self.message = message self.name = name def to_dict(self): FILL_FUNC_BODYclass DomainNotExists(StructuredException): status_cod...
class StructuredException(Exception): status_code = 0 def __init__(self, name=None, message="You want override this error!"): Exception.__init__(self) self.message = message self.name = name def to_dict(self): FILL_FUNC_BODYclass DomainNotExists(StructuredException): status_cod...
30,211
/home/hieuvd/dung_repo/raw/stars_02/PowerDNS-Admin_PowerDNS-Admin/PowerDNS-Admin
/home/hieuvd/dung_repo/raw/stars_02/PowerDNS-Admin_PowerDNS-Admin/PowerDNS-Admin/powerdnsadmin/models/record_entry.py
26,27
1,28
is_allowed_delete
RecordEntry
27,28
27,28
class RecordEntry(object): """ This is not a model, it's just an object which will store records entries from PowerDNS API """ def __init__(self, name=None, type=None, status=None, ttl=None, data=None, ...
class RecordEntry(object): """ This is not a model, it's just an object which will store records entries from PowerDNS API """ def __init__(self, name=None, type=None, status=None, ttl=None, data=None, ...
return self._is_allowed_delete
return self._is_allowed_delete
2
222
11
233
class RecordEntry(object): """ This is not a model, it's just an object which will store records entries from PowerDNS API """ def __init__(self, name=None, type=None, status=None, ttl=None, data=None, ...
class RecordEntry(object): """ This is not a model, it's just an object which will store records entries from PowerDNS API """ def __init__(self, name=None, type=None, status=None, ttl=None, data=None, ...
30,254
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/examples/python/circuit_draw.py
20,21
1,34
build_bell_circuit
22,30
21,30
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit
"""Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit
17
241
75
316
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,255
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/examples/python/qft.py
33,34
1,77
qft
35,41
34,41
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
for j in range(n): for k in range(j): circ.cp(math.pi / float(2 ** (j - k)), j, k) circ.h(j)
"""n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cp(math.pi / float(2 ** (j - k)), j, k) circ.h(j)
18
678
57
735
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,256
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/examples/python/rippleadd.py
71,72
1,114
unmajority
73,80
72,80
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b
"""Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b
23
1,124
65
1,189
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,260
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/assembler/run_config.py
71,72
18,78
to_dict
RunConfig
77,78
72,78
class RunConfig(SimpleNamespace): """Class for Run Configuration. Attributes: shots (int): the number of shots seed_simulator (int): the seed to use in the simulator memory (bool): whether to request memory from backend (per-shot readouts) parameter_binds (list[dict]...
class RunConfig(SimpleNamespace): """Class for Run Configuration. Attributes: shots (int): the number of shots seed_simulator (int): the seed to use in the simulator memory (bool): whether to request memory from backend (per-shot readouts) parameter_binds (list[dict]...
return self.__dict__
"""Return a dictionary format representation of the RunConfig Returns: dict: The dictionary form of the RunConfig. """ return self.__dict__
2
476
8
484
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,263
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/annotated_operation.py
137,138
59,223
to_matrix
AnnotatedOperation
139,158
138,158
class AnnotatedOperation(Operation): """Annotated operation.""" def __init__(self, base_op: Operation, modifiers: Union[Modifier, List[Modifier]]): """ Create a new AnnotatedOperation. An "annotated operation" allows to add a list of modifiers to the "base" operation. For now, ...
class AnnotatedOperation(Operation): """Annotated operation.""" def __init__(self, base_op: Operation, modifiers: Union[Modifier, List[Modifier]]): """ Create a new AnnotatedOperation. An "annotated operation" allows to add a list of modifiers to the "base" operation. For now, ...
from qiskit.quantum_info.operators import Operator # pylint: disable=cyclic-import operator = Operator(self.base_op) for modifier in self.modifiers: if isinstance(modifier, InverseModifier): operator = operator.power(-1) elif isinstance(modifier, Contro...
"""Return a matrix representation (allowing to construct Operator).""" from qiskit.quantum_info.operators import Operator # pylint: disable=cyclic-import operator = Operator(self.base_op) for modifier in self.modifiers: if isinstance(modifier, InverseModifier): ...
45
1,552
207
1,759
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,264
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/barrier.py
43,44
25,49
inverse
Barrier
45,47
44,47
class Barrier(Instruction): """A directive for circuit compilation to separate pieces of a circuit so that any optimizations or re-writes are constrained to only act between barriers. This will also appear in visualizations as a visual marker. """ _directive = True def __init__(self, num_qubi...
class Barrier(Instruction): """A directive for circuit compilation to separate pieces of a circuit so that any optimizations or re-writes are constrained to only act between barriers. This will also appear in visualizations as a visual marker. """ _directive = True def __init__(self, num_qubi...
return Barrier(self.num_qubits)
"""Special case. Return self.""" return Barrier(self.num_qubits)
2
229
16
245
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,265
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classical/types/types.py
58,60
49,83
kind
Type
63,67
60,67
class Type: """Root base class of all nodes in the type tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code.""" ...
class Type: """Root base class of all nodes in the type tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code.""" ...
return self.__class__ # Enforcement of immutability. The constructor methods need to manually skip this.
"""Get the kind of this type. This is exactly equal to the Python type object that defines this type, that is ``t.kind is type(t)``, but is exposed like this to make it clear that this a hashable enum-like discriminator you can rely on.""" return self.__class__ # Enforcement of imm...
14
307
34
341
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,266
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classical/types/types.py
35,36
31,49
_get_singleton_instance
_Singleton
36,38
36,38
class _Singleton(type): """Metaclass to make the child, which should take zero initialisation arguments, a singleton object.""" def _get_singleton_instance(cls): FILL_FUNC_BODY @classmethod def __prepare__(mcs, name, bases): # pylint: disable=unused-argument return {"__new__": mcs._get_sing...
class _Singleton(type): """Metaclass to make the child, which should take zero initialisation arguments, a singleton object.""" def _get_singleton_instance(cls): FILL_FUNC_BODY @classmethod def __prepare__(mcs, name, bases): # pylint: disable=unused-argument return {"__new__": mcs._get_sing...
return cls._INSTANCE
return cls._INSTANCE
2
173
11
184
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,267
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classicalfunction/boolean_expression.py
101,103
23,130
from_dimacs_file
BooleanExpression
113,130
103,130
@HAS_TWEEDLEDUM.require_in_instance class BooleanExpression(ClassicalElement): """The Boolean Expression gate.""" def __init__(self, expression: str, name: str = None, var_order: list = None) -> None: """ Args: expression (str): The logical expression string. name (str):...
@HAS_TWEEDLEDUM.require_in_instance class BooleanExpression(ClassicalElement): """The Boolean Expression gate.""" def __init__(self, expression: str, name: str = None, var_order: list = None) -> None: """ Args: expression (str): The logical expression string. name (str):...
HAS_TWEEDLEDUM.require_now("BooleanExpression") from tweedledum import BoolFunction # pylint: disable=import-error expr_obj = cls.__new__(cls) if not isfile(filename): raise FileNotFoundError("The file %s does not exists." % filename) expr_obj._tweedledum_bool_expr...
"""Create a BooleanExpression from the string in the DIMACS format. Args: filename: A file in DIMACS format. Returns: BooleanExpression: A gate for the input string Raises: FileNotFoundError: If filename is not found. """ HAS_TWEEDLED...
41
942
234
1,176
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,268
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classicalfunction/classical_element.py
52,53
20,55
_define
ClassicalElement
54,55
53,55
class ClassicalElement(Gate, metaclass=ABCMeta): """The classical element gate.""" @abstractmethod def simulate(self, bitstring: str) -> bool: """Evaluate the expression on a bitstring. This evaluation is done classically. Args: bitstring: The bitstring for which to ev...
class ClassicalElement(Gate, metaclass=ABCMeta): """The classical element gate.""" @abstractmethod def simulate(self, bitstring: str) -> bool: """Evaluate the expression on a bitstring. This evaluation is done classically. Args: bitstring: The bitstring for which to ev...
self.definition = self.synth()
"""The definition of the boolean expression is its synthesis""" self.definition = self.synth()
3
299
12
311
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,269
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classicalfunction/classical_function_visitor.py
52,53
24,156
visit_FunctionDef
ClassicalFunctionVisitor
54,68
53,68
@HAS_TWEEDLEDUM.require_in_instance class ClassicalFunctionVisitor(ast.NodeVisitor): """Node visitor as defined in https://docs.python.org/3/library/ast.html#ast.NodeVisitor""" # pylint: disable=invalid-name bitops = { _ast.BitAnd: "create_and", _ast.BitOr: "create_or", _ast.BitXor:...
@HAS_TWEEDLEDUM.require_in_instance class ClassicalFunctionVisitor(ast.NodeVisitor): """Node visitor as defined in https://docs.python.org/3/library/ast.html#ast.NodeVisitor""" # pylint: disable=invalid-name bitops = { _ast.BitAnd: "create_and", _ast.BitOr: "create_or", _ast.BitXor:...
if node.returns is None: raise ClassicalFunctionParseError("return type is needed") scope = {"return": (node.returns.id, None), node.returns.id: ("type", None)} # Extend scope with the decorator's names scope.update({decorator.id: ("decorator", None) for decorator in node.de...
"""The function definition should have type hints""" if node.returns is None: raise ClassicalFunctionParseError("return type is needed") scope = {"return": (node.returns.id, None), node.returns.id: ("type", None)} # Extend scope with the decorator's names scope.updat...
45
1,408
179
1,587
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,270
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classicalfunction/classicalfunction.py
85,87
26,174
types
ClassicalFunction
93,98
87,98
@HAS_TWEEDLEDUM.require_in_instance class ClassicalFunction(ClassicalElement): """Represent a classical function and its logic network.""" def __init__(self, source, name=None): """Creates a ``ClassicalFunction`` from Python source code in ``source``. The code should be a single function with ...
@HAS_TWEEDLEDUM.require_in_instance class ClassicalFunction(ClassicalElement): """Represent a classical function and its logic network.""" def __init__(self, source, name=None): """Creates a ``ClassicalFunction`` from Python source code in ``source``. The code should be a single function with ...
ret = [] for scope in self.scopes: ret.append({k: v[0] for k, v in scope.items()}) return ret
"""Dumps a list of scopes with their variables and types. Returns: list(dict): A list of scopes as dicts, where key is the variable name and value is its type. """ ret = [] for scope in self.scopes: ret.append({k: v[0] for k, v in scope.items(...
16
1,337
47
1,384
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,271
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/classicalfunction/utils.py
43,45
1,92
_convert_tweedledum_operator
45,64
45,64
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
base_gate = _QISKIT_OPS.get(op.kind()) if base_gate is None: if op.kind() == "py_operator": return op.py_op() else: raise RuntimeError("Unrecognized operator: %s" % op.kind()) # TODO: need to deal with cbits too! if op.num_controls() > 0: from tweedledum....
base_gate = _QISKIT_OPS.get(op.kind()) if base_gate is None: if op.kind() == "py_operator": return op.py_op() else: raise RuntimeError("Unrecognized operator: %s" % op.kind()) # TODO: need to deal with cbits too! if op.num_controls() > 0: from tweedledum....
60
839
247
1,086
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,273
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/commutation_checker.py
150,157
37,195
check_commutation_entries
CommutationChecker
168,195
157,195
class CommutationChecker: """This code is essentially copy-pasted from commutative_analysis.py. This code cleverly hashes commutativity and non-commutativity results between DAG nodes and seems quite efficient for large Clifford circuits. They may be other possible efficiency improvements: using rule-ba...
class CommutationChecker: """This code is essentially copy-pasted from commutative_analysis.py. This code cleverly hashes commutativity and non-commutativity results between DAG nodes and seems quite efficient for large Clifford circuits. They may be other possible efficiency improvements: using rule-ba...
# We don't precompute commutations for parameterized gates, yet commutation = _query_commutation( first_op, first_qargs, second_op, second_qargs, self._standard_commutations, ) if commutation is not None: return co...
"""Returns stored commutation relation if any Args: first_op: first operation. first_qargs: first operation's qubits. second_op: second operation. second_qargs: second operation's qubits. Return: bool: True if the gates commute and fa...
47
1,487
202
1,689
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,275
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/break_loop.py
49,50
36,57
concrete_instruction
BreakLoopPlaceholder
50,55
50,55
class BreakLoopPlaceholder(InstructionPlaceholder): """A placeholder instruction for use in control-flow context managers, when the number of qubits and clbits is not yet known. .. warning:: This is an internal interface and no part of it should be relied upon outside of Qiskit Terra. ...
class BreakLoopPlaceholder(InstructionPlaceholder): """A placeholder instruction for use in control-flow context managers, when the number of qubits and clbits is not yet known. .. warning:: This is an internal interface and no part of it should be relied upon outside of Qiskit Terra. ...
return ( self._copy_mutable_properties(BreakLoopOp(len(qubits), len(clbits), label=self.label)), InstructionResources(qubits=tuple(qubits), clbits=tuple(clbits)), )
return ( self._copy_mutable_properties(BreakLoopOp(len(qubits), len(clbits), label=self.label)), InstructionResources(qubits=tuple(qubits), clbits=tuple(clbits)), )
8
165
67
232
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,276
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/continue_loop.py
57,58
36,59
placeholder_resources
ContinueLoopPlaceholder
58,59
58,59
class ContinueLoopPlaceholder(InstructionPlaceholder): """A placeholder instruction for use in control-flow context managers, when the number of qubits and clbits is not yet known. .. warning:: This is an internal interface and no part of it should be relied upon outside of Qiskit Terra. ...
class ContinueLoopPlaceholder(InstructionPlaceholder): """A placeholder instruction for use in control-flow context managers, when the number of qubits and clbits is not yet known. .. warning:: This is an internal interface and no part of it should be relied upon outside of Qiskit Terra. ...
return InstructionResources()
return InstructionResources()
2
227
8
235
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,277
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/control_flow.py
77,78
28,85
iter_captured_vars
ControlFlowOp
79,85
78,85
class ControlFlowOp(Instruction, ABC): """Abstract class to encapsulate all control flow operations. All subclasses of :class:`ControlFlowOp` have an internal attribute, :attr:`~ControlFlowOp.blocks`, which exposes the inner subcircuits used in the different blocks of the control flow. """ def...
class ControlFlowOp(Instruction, ABC): """Abstract class to encapsulate all control flow operations. All subclasses of :class:`ControlFlowOp` have an internal attribute, :attr:`~ControlFlowOp.blocks`, which exposes the inner subcircuits used in the different blocks of the control flow. """ def...
seen = set() for block in self.blocks: for var in block.iter_captured_vars(): if var not in seen: seen.add(var) yield var
"""Get an iterator over the unique captured variables in all blocks of this construct.""" seen = set() for block in self.blocks: for var in block.iter_captured_vars(): if var not in seen: seen.add(var) yield var
19
534
55
589
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,278
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/for_loop.py
59,61
28,117
params
ForLoopOp
61,108
61,108
class ForLoopOp(ControlFlowOp): """A circuit operation which repeatedly executes a subcircuit (``body``) parameterized by a parameter ``loop_parameter`` through the set of integer values provided in ``indexset``. """ def __init__( self, indexset: Iterable[int], loop_paramete...
class ForLoopOp(ControlFlowOp): """A circuit operation which repeatedly executes a subcircuit (``body``) parameterized by a parameter ``loop_parameter`` through the set of integer values provided in ``indexset``. """ def __init__( self, indexset: Iterable[int], loop_paramete...
# pylint: disable=cyclic-import from qiskit.circuit import QuantumCircuit indexset, loop_parameter, body = parameters if not isinstance(loop_parameter, (Parameter, type(None))): raise CircuitError( "ForLoopOp expects a loop_parameter parameter to " ...
# pylint: disable=cyclic-import from qiskit.circuit import QuantumCircuit indexset, loop_parameter, body = parameters if not isinstance(loop_parameter, (Parameter, type(None))): raise CircuitError( "ForLoopOp expects a loop_parameter parameter to " ...
215
373
596
969
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,279
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/if_else.py
362,364
308,405
in_loop
IfContext
365,367
364,367
class IfContext: """A context manager for building up ``if`` statements onto circuits in a natural order, without having to construct the statement body first. The return value of this context manager can be used immediately following the block to create an attached ``else`` statement. This contex...
class IfContext: """A context manager for building up ``if`` statements onto circuits in a natural order, without having to construct the statement body first. The return value of this context manager can be used immediately following the block to create an attached ``else`` statement. This contex...
return self._in_loop
"""Whether this context manager is enclosed within a loop.""" return self._in_loop
2
1,108
11
1,119
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,280
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/if_else.py
96,98
42,164
params
IfElseOp
98,134
98,134
class IfElseOp(ControlFlowOp): """A circuit operation which executes a program (``true_body``) if a provided condition (``condition``) evaluates to true, and optionally evaluates another program (``false_body``) otherwise. If provided, ``false_body`` must be of the same ``num_qubits`` and ``num_clb...
class IfElseOp(ControlFlowOp): """A circuit operation which executes a program (``true_body``) if a provided condition (``condition``) evaluates to true, and optionally evaluates another program (``false_body``) otherwise. If provided, ``false_body`` must be of the same ``num_qubits`` and ``num_clb...
# pylint: disable=cyclic-import from qiskit.circuit import QuantumCircuit true_body, false_body = parameters if not isinstance(true_body, QuantumCircuit): raise CircuitError( "IfElseOp expects a true_body parameter of type " f"QuantumCircuit,...
# pylint: disable=cyclic-import from qiskit.circuit import QuantumCircuit true_body, false_body = parameters if not isinstance(true_body, QuantumCircuit): raise CircuitError( "IfElseOp expects a true_body parameter of type " f"QuantumCircuit,...
134
913
535
1,448
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,281
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/if_else.py
205,206
164,308
with_false_block
IfElsePlaceholder
221,230
206,230
class IfElsePlaceholder(InstructionPlaceholder): """A placeholder instruction to use in control-flow context managers, when calculating the number of resources this instruction should block is deferred until the construction of the outer loop. This generally should not be instantiated manually; only :o...
class IfElsePlaceholder(InstructionPlaceholder): """A placeholder instruction to use in control-flow context managers, when calculating the number of resources this instruction should block is deferred until the construction of the outer loop. This generally should not be instantiated manually; only :o...
if self.__false_block is not None: raise CircuitError(f"false block is already set to {self.__false_block}") true_block = self.__true_block.copy() true_bits = true_block.qubits() | true_block.clbits() false_bits = false_block.qubits() | false_block.clbits() true_block...
"""Return a new placeholder instruction, with the false block set to the given value, updating the bits used by both it and the true body, if necessary. It is an error to try and set the false block on a placeholder that already has one. Args: false_block: The (unbuilt) ins...
37
1,656
161
1,817
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,282
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/switch_case.py
163,164
50,192
cases
SwitchCaseOp
173,175
164,175
class SwitchCaseOp(ControlFlowOp): """A circuit operation that executes one particular circuit block based on matching a given ``target`` against an ordered list of ``values``. The special value :data:`.CASE_DEFAULT` can be used to represent a default condition. """ def __init__( self, ...
class SwitchCaseOp(ControlFlowOp): """A circuit operation that executes one particular circuit block based on matching a given ``target`` against an ordered list of ``values``. The special value :data:`.CASE_DEFAULT` can be used to represent a default condition. """ def __init__( self, ...
return {key: self._params[index] for key, index in self._case_map.items()}
"""Return a lookup table from case labels to the circuit that would be executed in that case. This object is not generally suitable for creating a new :class:`.SwitchCaseOp` because any keys that point to the same object will not be grouped. .. seealso:: :meth:`.SwitchCaseO...
8
1,782
29
1,811
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,283
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/switch_case.py
254,255
192,277
concrete_instruction
SwitchCasePlaceholder
255,277
255,277
class SwitchCasePlaceholder(InstructionPlaceholder): """A placeholder instruction to use in control-flow context managers, when calculating the number of resources this instruction should block is deferred until the construction of the outer loop. This generally should not be instantiated manually; onl...
class SwitchCasePlaceholder(InstructionPlaceholder): """A placeholder instruction to use in control-flow context managers, when calculating the number of resources this instruction should block is deferred until the construction of the outer loop. This generally should not be instantiated manually; onl...
cases = [ (labels, unified_body) for (labels, _), unified_body in zip( self.__cases, unify_circuit_resources(body.build(qubits, clbits) for _, body in self.__cases), ) ] if cases: resources = InstructionResources( ...
cases = [ (labels, unified_body) for (labels, _), unified_body in zip( self.__cases, unify_circuit_resources(body.build(qubits, clbits) for _, body in self.__cases), ) ] if cases: resources = InstructionResources( ...
42
583
228
811
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,284
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/switch_case.py
322,323
277,362
label_in_use
SwitchContext
324,326
323,326
class SwitchContext: """A context manager for building up ``switch`` statements onto circuits in a natural order, without having to construct the case bodies first. The return value of this context manager can be used within the created context to build up the individual ``case`` statements. No other ...
class SwitchContext: """A context manager for building up ``switch`` statements onto circuits in a natural order, without having to construct the case bodies first. The return value of this context manager can be used within the created context to build up the individual ``case`` statements. No other ...
return label in self._label_set
"""Return whether a case label is already accounted for in the switch statement.""" return label in self._label_set
4
1,000
13
1,013
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,285
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/controlflow/while_loop.py
62,64
29,100
params
WhileLoopOp
64,85
64,85
class WhileLoopOp(ControlFlowOp): """A circuit operation which repeatedly executes a subcircuit (``body``) until a condition (``condition``) evaluates as False. The classical bits used in ``condition`` must be a subset of those attached to ``body``. """ def __init__( self, cond...
class WhileLoopOp(ControlFlowOp): """A circuit operation which repeatedly executes a subcircuit (``body``) until a condition (``condition``) evaluates as False. The classical bits used in ``condition`` must be a subset of those attached to ``body``. """ def __init__( self, cond...
# pylint: disable=cyclic-import from qiskit.circuit import QuantumCircuit (body,) = parameters if not isinstance(body, QuantumCircuit): raise CircuitError( "WhileLoopOp expects a body parameter of type " f"QuantumCircuit, but received {type(b...
# pylint: disable=cyclic-import from qiskit.circuit import QuantumCircuit (body,) = parameters if not isinstance(body, QuantumCircuit): raise CircuitError( "WhileLoopOp expects a body parameter of type " f"QuantumCircuit, but received {type(b...
70
473
265
738
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,287
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/delay.py
71,72
24,107
validate_parameter
Delay
73,107
72,107
@_utils.with_gate_array(np.eye(2, dtype=complex)) class Delay(Instruction): """Do nothing and just delay/wait/idle for a specified duration.""" def __init__(self, duration, unit="dt"): """ Args: duration: the length of time of the duration. Given in units of ``unit``. u...
@_utils.with_gate_array(np.eye(2, dtype=complex)) class Delay(Instruction): """Do nothing and just delay/wait/idle for a specified duration.""" def __init__(self, duration, unit="dt"): """ Args: duration: the length of time of the duration. Given in units of ``unit``. u...
if isinstance(parameter, int): if parameter < 0: raise CircuitError( f"Duration for Delay instruction must be positive. Found {parameter}" ) return parameter elif isinstance(parameter, float): if parameter < 0: ...
"""Delay parameter (i.e. duration) must be int, float or ParameterExpression.""" if isinstance(parameter, int): if parameter < 0: raise CircuitError( f"Duration for Delay instruction must be positive. Found {parameter}" ) return...
159
507
405
912
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,288
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/duration.py
45,46
1,96
convert_durations_to_dt
61,96
46,96
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
if inplace: circ = qc else: circ = qc.copy() for instruction in circ.data: operation = instruction.operation if operation.unit == "dt" or operation.duration is None: continue if not operation.unit.endswith("s"): raise CircuitError(f"Invalid t...
"""Convert all the durations in SI (seconds) into those in dt. Returns a new circuit if `inplace=False`. Parameters: qc (QuantumCircuit): Duration of dt in seconds used for conversion. dt_in_sec (float): Duration of dt in seconds used for conversion. inplace (bool): All durations a...
94
596
331
927
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,293
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/instructionset.py
108,109
28,181
c_if
InstructionSet
136,161
109,161
class InstructionSet: """Instruction collection, and their contexts.""" __slots__ = ("_instructions", "_requester") def __init__( # pylint: disable=bad-docstring-quotes self, *, resource_requester: Callable[..., ClassicalRegister | Clbit] | None = None, ): """New colle...
class InstructionSet: """Instruction collection, and their contexts.""" __slots__ = ("_instructions", "_requester") def __init__( # pylint: disable=bad-docstring-quotes self, *, resource_requester: Callable[..., ClassicalRegister | Clbit] | None = None, ): """New colle...
if self._requester is None and not isinstance(classical, (Clbit, ClassicalRegister)): raise CircuitError( "Cannot pass an index as a condition variable without specifying a requester" " when creating this InstructionSet." ) if self._requester is no...
"""Set a classical equality condition on all the instructions in this set between the :obj:`.ClassicalRegister` or :obj:`.Clbit` ``classical`` and value ``val``. .. note:: You should prefer to use the :meth:`.QuantumCircuit.if_test` builder interface, rather than using t...
104
1,409
299
1,708
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
30,294
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/library/arithmetic/adders/adder.py
51,53
18,59
num_state_qubits
Adder
58,59
53,59
class Adder(QuantumCircuit): r"""Compute the sum of two equally sized qubit registers. For two registers :math:`|a\rangle_n` and :math:|b\rangle_n` with :math:`n` qubits each, an adder performs the following operation .. math:: |a\rangle_n |b\rangle_n \mapsto |a\rangle_n |a + b\rangle_{n + 1}...
class Adder(QuantumCircuit): r"""Compute the sum of two equally sized qubit registers. For two registers :math:`|a\rangle_n` and :math:|b\rangle_n` with :math:`n` qubits each, an adder performs the following operation .. math:: |a\rangle_n |b\rangle_n \mapsto |a\rangle_n |a + b\rangle_{n + 1}...
return self._num_state_qubits
"""The number of state qubits, i.e. the number of bits in each input register. Returns: The number of state qubits. """ return self._num_state_qubits
2
433
12
445
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,295
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/library/arithmetic/functional_pauli_rotations.py
45,47
22,115
basis
FunctionalPauliRotations
54,56
47,56
class FunctionalPauliRotations(BlueprintCircuit, ABC): """Base class for functional Pauli rotations.""" def __init__( self, num_state_qubits: Optional[int] = None, basis: str = "Y", name: str = "F" ) -> None: r"""Create a new functional Pauli rotation circuit. Args: num...
class FunctionalPauliRotations(BlueprintCircuit, ABC): """Base class for functional Pauli rotations.""" def __init__( self, num_state_qubits: Optional[int] = None, basis: str = "Y", name: str = "F" ) -> None: r"""Create a new functional Pauli rotation circuit. Args: num...
return self._basis
"""The kind of Pauli rotation to be used. Set the basis to 'X', 'Y' or 'Z' for controlled-X, -Y, or -Z rotations respectively. Returns: The kind of Pauli rotation used in controlled rotation. """ return self._basis
2
868
10
878
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,299
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/library/arithmetic/linear_pauli_rotations.py
161,162
24,190
_build
LinearPauliRotations
163,190
162,190
class LinearPauliRotations(FunctionalPauliRotations): r"""Linearly-controlled X, Y or Z rotation. For a register of state qubits :math:`|x\rangle`, a target qubit :math:`|0\rangle` and the basis ``'Y'`` this circuit acts as: .. parsed-literal:: q_0: ─────────────────────────■───────── ......
class LinearPauliRotations(FunctionalPauliRotations): r"""Linearly-controlled X, Y or Z rotation. For a register of state qubits :math:`|x\rangle`, a target qubit :math:`|0\rangle` and the basis ``'Y'`` this circuit acts as: .. parsed-literal:: q_0: ─────────────────────────■───────── ......
if self._is_built: return super()._build() circuit = QuantumCircuit(*self.qregs, name=self.name) # build the circuit qr_state = self.qubits[: self.num_state_qubits] qr_target = self.qubits[self.num_state_qubits] if self.basis == "x": ci...
"""If not already built, build the circuit.""" if self._is_built: return super()._build() circuit = QuantumCircuit(*self.qregs, name=self.name) # build the circuit qr_state = self.qubits[: self.num_state_qubits] qr_target = self.qubits[self.num_stat...
72
1,414
345
1,759
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,300
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/library/arithmetic/multipliers/multiplier.py
94,96
20,102
num_result_qubits
Multiplier
101,102
96,102
class Multiplier(QuantumCircuit): r"""Compute the product of two equally sized qubit registers into a new register. For two input registers :math:`|a\rangle_n`, :math:`|b\rangle_n` with :math:`n` qubits each and an output register with :math:`2n` qubits, a multiplier performs the following operation ....
class Multiplier(QuantumCircuit): r"""Compute the product of two equally sized qubit registers into a new register. For two input registers :math:`|a\rangle_n`, :math:`|b\rangle_n` with :math:`n` qubits each and an output register with :math:`2n` qubits, a multiplier performs the following operation ....
return self._num_result_qubits
"""The number of result qubits to limit the output to. Returns: The number of result qubits. """ return self._num_result_qubits
2
908
12
920
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
30,309
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit
/home/hieuvd/dung_repo/raw/stars_02/Qiskit_qiskit/qiskit/qiskit/circuit/library/data_preparation/initializer.py
78,79
32,105
_define
Initialize
79,85
79,85
class Initialize(Instruction): """Complex amplitude initialization. Class that initializes some flexible collection of qubit registers, implemented by calling the :class:`~.library.StatePreparation` class. Note that ``Initialize`` is an :class:`~.circuit.Instruction` and not a :class:`.Gate` since it ...
class Initialize(Instruction): """Complex amplitude initialization. Class that initializes some flexible collection of qubit registers, implemented by calling the :class:`~.library.StatePreparation` class. Note that ``Initialize`` is an :class:`~.circuit.Instruction` and not a :class:`.Gate` since it ...
q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") initialize_circuit.reset(q) initialize_circuit.append(self._stateprep, q) self.definition = initialize_circuit
q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") initialize_circuit.reset(q) initialize_circuit.append(self._stateprep, q) self.definition = initialize_circuit
14
895
83
978
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...