body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
@abstractmethod
def set(self, U):
'Load new data into existing plot objects.'
pass | 4,344,444,513,218,146,300 | Load new data into existing plot objects. | src/pymor/discretizers/builtin/gui/matplotlib.py | set | TreeerT/pymor | python | @abstractmethod
def set(self, U):
pass |
@abstractmethod
def animate(self, u):
'Load new data into existing plot objects.'
pass | -6,992,738,916,723,379,000 | Load new data into existing plot objects. | src/pymor/discretizers/builtin/gui/matplotlib.py | animate | TreeerT/pymor | python | @abstractmethod
def animate(self, u):
pass |
def read_worldbank(iso3166alpha3):
' Fetches and tidies all ~1500 World Bank indicators\n for a given ISO 3166 alpha 3 code.\n\n For a particular alpha 3 code, this function fetches the entire ZIP\n file for that particular country for all World Bank indicators in a\n wide format where y... | -7,063,378,916,210,146,000 | Fetches and tidies all ~1500 World Bank indicators
for a given ISO 3166 alpha 3 code.
For a particular alpha 3 code, this function fetches the entire ZIP
file for that particular country for all World Bank indicators in a
wide format where years are columns. The dataframe is changed into a
narrow format so that year b... | scripts/world_bank/worldbank.py | read_worldbank | IanCostello/data | python | def read_worldbank(iso3166alpha3):
' Fetches and tidies all ~1500 World Bank indicators\n for a given ISO 3166 alpha 3 code.\n\n For a particular alpha 3 code, this function fetches the entire ZIP\n file for that particular country for all World Bank indicators in a\n wide format where y... |
def build_stat_vars_from_indicator_list(row):
' Generates World Bank StatVar for a row in the indicators dataframe. '
def row_to_constraints(row):
' Helper to generate list of constraints. '
constraints_text = ''
next_constraint = 1
while ((f'p{next_constraint}' in row) and (not... | -7,121,890,781,742,843,000 | Generates World Bank StatVar for a row in the indicators dataframe. | scripts/world_bank/worldbank.py | build_stat_vars_from_indicator_list | IanCostello/data | python | def build_stat_vars_from_indicator_list(row):
' '
def row_to_constraints(row):
' Helper to generate list of constraints. '
constraints_text =
next_constraint = 1
while ((f'p{next_constraint}' in row) and (not pd.isna(row[f'p{next_constraint}']))):
variable = row[f'... |
def group_stat_vars_by_observation_properties(indicator_codes):
' Groups stat vars by their observation schemas.\n\n Groups Stat Vars by their inclusion of StatVar Observation\n properties like measurementMethod or Unit.\n The current template MCF schema does not support optional values in the\... | 1,955,805,183,199,638,800 | Groups stat vars by their observation schemas.
Groups Stat Vars by their inclusion of StatVar Observation
properties like measurementMethod or Unit.
The current template MCF schema does not support optional values in the
CSV so we must place these stat vars into
different template MCFs and CSVs.
Args:
indicator_c... | scripts/world_bank/worldbank.py | group_stat_vars_by_observation_properties | IanCostello/data | python | def group_stat_vars_by_observation_properties(indicator_codes):
' Groups stat vars by their observation schemas.\n\n Groups Stat Vars by their inclusion of StatVar Observation\n properties like measurementMethod or Unit.\n The current template MCF schema does not support optional values in the\... |
def download_indicator_data(worldbank_countries, indicator_codes):
' Downloads World Bank country data for all countries and\n indicators provided.\n\n Retains only the unique indicator codes provided.\n\n Args:\n worldbank_countries: Dataframe with ISO 3166 alpha 3 code for each... | -1,911,059,532,361,748,700 | Downloads World Bank country data for all countries and
indicators provided.
Retains only the unique indicator codes provided.
Args:
worldbank_countries: Dataframe with ISO 3166 alpha 3 code for each
country.
indicator_code: Dataframe with INDICATOR_CODES to include.
Returns:
worldbank_datafr... | scripts/world_bank/worldbank.py | download_indicator_data | IanCostello/data | python | def download_indicator_data(worldbank_countries, indicator_codes):
' Downloads World Bank country data for all countries and\n indicators provided.\n\n Retains only the unique indicator codes provided.\n\n Args:\n worldbank_countries: Dataframe with ISO 3166 alpha 3 code for each... |
def output_csv_and_tmcf_by_grouping(worldbank_dataframe, tmcfs_for_stat_vars, indicator_codes):
' Outputs TMCFs and CSVs for each grouping of stat vars.\n\n Args:\n worldbank_dataframe: Dataframe containing all indicators for all\n countries.\n tmcfs_for_stat_vars: Array ... | 3,036,552,345,292,613,000 | Outputs TMCFs and CSVs for each grouping of stat vars.
Args:
worldbank_dataframe: Dataframe containing all indicators for all
countries.
tmcfs_for_stat_vars: Array of tuples of template MCF,
columns on stat var observations,
indicator codes for that template.
indicator_codes -> Data... | scripts/world_bank/worldbank.py | output_csv_and_tmcf_by_grouping | IanCostello/data | python | def output_csv_and_tmcf_by_grouping(worldbank_dataframe, tmcfs_for_stat_vars, indicator_codes):
' Outputs TMCFs and CSVs for each grouping of stat vars.\n\n Args:\n worldbank_dataframe: Dataframe containing all indicators for all\n countries.\n tmcfs_for_stat_vars: Array ... |
def source_scaling_remap(row, scaling_factor_lookup, existing_stat_var_lookup):
' Scales values by sourceScalingFactor and inputs exisiting stat vars.\n\n First, this function converts all values to per capita. Some measures\n in the World Bank dataset are per thousand or per hundred thousand, but\n ... | -7,367,889,510,659,683,000 | Scales values by sourceScalingFactor and inputs exisiting stat vars.
First, this function converts all values to per capita. Some measures
in the World Bank dataset are per thousand or per hundred thousand, but
we need to scale these to the common denomination format. Secondly,
some statistical variabl... | scripts/world_bank/worldbank.py | source_scaling_remap | IanCostello/data | python | def source_scaling_remap(row, scaling_factor_lookup, existing_stat_var_lookup):
' Scales values by sourceScalingFactor and inputs exisiting stat vars.\n\n First, this function converts all values to per capita. Some measures\n in the World Bank dataset are per thousand or per hundred thousand, but\n ... |
def row_to_constraints(row):
' Helper to generate list of constraints. '
constraints_text = ''
next_constraint = 1
while ((f'p{next_constraint}' in row) and (not pd.isna(row[f'p{next_constraint}']))):
variable = row[f'p{next_constraint}']
constraint = row[f'v{next_constraint}']
c... | -6,597,162,794,003,730,000 | Helper to generate list of constraints. | scripts/world_bank/worldbank.py | row_to_constraints | IanCostello/data | python | def row_to_constraints(row):
' '
constraints_text =
next_constraint = 1
while ((f'p{next_constraint}' in row) and (not pd.isna(row[f'p{next_constraint}']))):
variable = row[f'p{next_constraint}']
constraint = row[f'v{next_constraint}']
constraints_text += f'{variable}: dcs:{con... |
def request_file(url):
'从远端下载文件, 并构建request.FILES中的uploaded file对象返回. \n @param url: 文件url路径, 如http://abc.im/12345.jpg\n \n @return: SimpleUploadedFile object, it is containned by the request.FILES(dictionary-like object) \n '
if (not url):
return
response = requests.get(url)
return... | 4,314,314,294,437,754,000 | 从远端下载文件, 并构建request.FILES中的uploaded file对象返回.
@param url: 文件url路径, 如http://abc.im/12345.jpg
@return: SimpleUploadedFile object, it is containned by the request.FILES(dictionary-like object) | apps/utils/http.py | request_file | dlooto/driver-vision | python | def request_file(url):
'从远端下载文件, 并构建request.FILES中的uploaded file对象返回. \n @param url: 文件url路径, 如http://abc.im/12345.jpg\n \n @return: SimpleUploadedFile object, it is containned by the request.FILES(dictionary-like object) \n '
if (not url):
return
response = requests.get(url)
return... |
def send_request(host, send_url, method='GET', port=80, params={}, timeout=30, headers={'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}):
'发起http请求. 执行结果返回响应字符串\n \n @param: The sample parameters format like following: \n params = {\'token\': \'dF0zeqAPWs\'}\n header... | 1,627,781,333,786,985,000 | 发起http请求. 执行结果返回响应字符串
@param: The sample parameters format like following:
params = {'token': 'dF0zeqAPWs'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
host = 'fir.im'
port = 80
method = 'GET'
send_url = '/api/v2/app/version/541a7131f?token=dF0zeqBMX... | apps/utils/http.py | send_request | dlooto/driver-vision | python | def send_request(host, send_url, method='GET', port=80, params={}, timeout=30, headers={'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}):
'发起http请求. 执行结果返回响应字符串\n \n @param: The sample parameters format like following: \n params = {\'token\': \'dF0zeqAPWs\'}\n header... |
def standard_response(template, req, context):
'返回http Web response'
return render_to_response(template, RequestContext(req, context)) | -2,021,967,324,553,648,600 | 返回http Web response | apps/utils/http.py | standard_response | dlooto/driver-vision | python | def standard_response(template, req, context):
return render_to_response(template, RequestContext(req, context)) |
def ok(data={}):
'data为字典类型数据'
return (JResponse(codes.append('ok', data)) if data else resp('ok')) | 2,627,429,873,032,745,000 | data为字典类型数据 | apps/utils/http.py | ok | dlooto/driver-vision | python | def ok(data={}):
return (JResponse(codes.append('ok', data)) if data else resp('ok')) |
def resp(crr, msg=''):
'返回常量错误码. msg可格式化具有占位符的字符串\n \n params:\n @crr 错误码标识\n '
return JResponse(codes.fmat(crr, msg)) | -288,261,512,890,758,300 | 返回常量错误码. msg可格式化具有占位符的字符串
params:
@crr 错误码标识 | apps/utils/http.py | resp | dlooto/driver-vision | python | def resp(crr, msg=):
'返回常量错误码. msg可格式化具有占位符的字符串\n \n params:\n @crr 错误码标识\n '
return JResponse(codes.fmat(crr, msg)) |
async def send_async_http(session, method, url, *, retries=1, interval=1, wait_factor=2, timeout=30, success_callback=None, fail_callback=None, **kwargs) -> dict:
'\n 发送一个异步请求至某个特定url,实现失败重试\n 每一次失败后会延时一段时间再去重试,延时时间由\n interval和wait_factor决定\n :param session:请求的异步session\n :param method:请求方法\n :pa... | -5,617,060,968,950,471,000 | 发送一个异步请求至某个特定url,实现失败重试
每一次失败后会延时一段时间再去重试,延时时间由
interval和wait_factor决定
:param session:请求的异步session
:param method:请求方法
:param url:请求url
:param retries:失败重试次数
:param interval:失败后的再次异步请求的延时时长
:param wait_factor:每一次失败后延时乘以这个因子,延长重试等待时间,一般1<wf<2,即延时最多2^retries秒
:param timeout:连接超时时长
:param success_callback:成功回调函数
:param fai... | tools/async_tools.py | send_async_http | 01ly/FooProxy | python | async def send_async_http(session, method, url, *, retries=1, interval=1, wait_factor=2, timeout=30, success_callback=None, fail_callback=None, **kwargs) -> dict:
'\n 发送一个异步请求至某个特定url,实现失败重试\n 每一次失败后会延时一段时间再去重试,延时时间由\n interval和wait_factor决定\n :param session:请求的异步session\n :param method:请求方法\n :pa... |
def connect(argv):
'\n connect [connector type] [connector args ...]\n 连接到设备\n 支持的设备类型:\n connect adb [serial or tcpip endpoint]\n '
connector_type = 'adb'
if (len(argv) > 1):
connector_type = argv[1]
connector_args = argv[2:]
else:
connector_args = []
... | 5,385,238,541,063,250,000 | connect [connector type] [connector args ...]
连接到设备
支持的设备类型:
connect adb [serial or tcpip endpoint] | Arknights/shell_next.py | connect | TeemoKill/ArknightsAutoHelper | python | def connect(argv):
'\n connect [connector type] [connector args ...]\n 连接到设备\n 支持的设备类型:\n connect adb [serial or tcpip endpoint]\n '
connector_type = 'adb'
if (len(argv) > 1):
connector_type = argv[1]
connector_args = argv[2:]
else:
connector_args = []
... |
def quick(argv):
'\n quick [+-rR[N]] [n]\n 重复挑战当前画面关卡特定次数或直到理智不足\n +r/-r 是否自动回复理智,最多回复 N 次\n +R/-R 是否使用源石回复理智(需要同时开启 +r)\n '
ops = _parse_opt(argv)
if (len(argv) == 2):
count = int(argv[1])
else:
count = 114514
(helper, context) = _create_helper(show_toggle... | 4,636,756,966,689,924,000 | quick [+-rR[N]] [n]
重复挑战当前画面关卡特定次数或直到理智不足
+r/-r 是否自动回复理智,最多回复 N 次
+R/-R 是否使用源石回复理智(需要同时开启 +r) | Arknights/shell_next.py | quick | TeemoKill/ArknightsAutoHelper | python | def quick(argv):
'\n quick [+-rR[N]] [n]\n 重复挑战当前画面关卡特定次数或直到理智不足\n +r/-r 是否自动回复理智,最多回复 N 次\n +R/-R 是否使用源石回复理智(需要同时开启 +r)\n '
ops = _parse_opt(argv)
if (len(argv) == 2):
count = int(argv[1])
else:
count = 114514
(helper, context) = _create_helper(show_toggle... |
def auto(argv):
'\n auto [+-rR[N]] stage1 count1 [stage2 count2] ...\n 按顺序挑战指定关卡特定次数直到理智不足\n '
ops = _parse_opt(argv)
arglist = argv[1:]
if ((len(arglist) % 2) != 0):
print('usage: auto [+-rR] stage1 count1 [stage2 count2] ...')
return 1
it = iter(arglist)
tasks = [(... | 6,632,307,330,463,694,000 | auto [+-rR[N]] stage1 count1 [stage2 count2] ...
按顺序挑战指定关卡特定次数直到理智不足 | Arknights/shell_next.py | auto | TeemoKill/ArknightsAutoHelper | python | def auto(argv):
'\n auto [+-rR[N]] stage1 count1 [stage2 count2] ...\n 按顺序挑战指定关卡特定次数直到理智不足\n '
ops = _parse_opt(argv)
arglist = argv[1:]
if ((len(arglist) % 2) != 0):
print('usage: auto [+-rR] stage1 count1 [stage2 count2] ...')
return 1
it = iter(arglist)
tasks = [(... |
def collect(argv):
'\n collect\n 收集每日任务和每周任务奖励\n '
(helper, context) = _create_helper()
with context:
helper.clear_task()
return 0 | -1,399,731,280,119,893,800 | collect
收集每日任务和每周任务奖励 | Arknights/shell_next.py | collect | TeemoKill/ArknightsAutoHelper | python | def collect(argv):
'\n collect\n 收集每日任务和每周任务奖励\n '
(helper, context) = _create_helper()
with context:
helper.clear_task()
return 0 |
def recruit(argv):
'\n recruit [tags ...]\n 公开招募识别/计算,不指定标签则从截图中识别\n '
from . import recruit_calc
if (2 <= len(argv) <= 6):
tags = argv[1:]
result = recruit_calc.calculate(tags)
elif (len(argv) == 1):
(helper, context) = _create_helper(use_status_line=False)
... | 8,619,267,370,571,826,000 | recruit [tags ...]
公开招募识别/计算,不指定标签则从截图中识别 | Arknights/shell_next.py | recruit | TeemoKill/ArknightsAutoHelper | python | def recruit(argv):
'\n recruit [tags ...]\n 公开招募识别/计算,不指定标签则从截图中识别\n '
from . import recruit_calc
if (2 <= len(argv) <= 6):
tags = argv[1:]
result = recruit_calc.calculate(tags)
elif (len(argv) == 1):
(helper, context) = _create_helper(use_status_line=False)
... |
def interactive(argv):
'\n interactive\n 进入交互模式,减少按键次数(\n '
import shlex
import traceback
helpcmds(interactive_cmds)
errorlevel = None
try:
import readline
except ImportError:
pass
while True:
try:
if (device is None):
prom... | -7,922,720,041,851,671,000 | interactive
进入交互模式,减少按键次数( | Arknights/shell_next.py | interactive | TeemoKill/ArknightsAutoHelper | python | def interactive(argv):
'\n interactive\n 进入交互模式,减少按键次数(\n '
import shlex
import traceback
helpcmds(interactive_cmds)
errorlevel = None
try:
import readline
except ImportError:
pass
while True:
try:
if (device is None):
prom... |
def help(argv):
'\n help\n 输出本段消息\n '
print(('usage: %s command [command args]' % argv0))
helpcmds(global_cmds) | -3,847,951,780,685,274,600 | help
输出本段消息 | Arknights/shell_next.py | help | TeemoKill/ArknightsAutoHelper | python | def help(argv):
'\n help\n 输出本段消息\n '
print(('usage: %s command [command args]' % argv0))
helpcmds(global_cmds) |
def majority_vote(labels, weight=None):
'Perform majority vote to determine the true label from\n multiple noisy oracles.\n\n Parameters\n ----------\n labels: list\n A list with length=k, which contains the labels provided by\n k noisy oracles.\n\n weight: list, optional (default=None)... | 6,889,896,317,466,734,000 | Perform majority vote to determine the true label from
multiple noisy oracles.
Parameters
----------
labels: list
A list with length=k, which contains the labels provided by
k noisy oracles.
weight: list, optional (default=None)
The weights of each oracle. It should have the same length with
labels.
... | alipy/query_strategy/noisy_oracles.py | majority_vote | Houchaoqun/ALiPy | python | def majority_vote(labels, weight=None):
'Perform majority vote to determine the true label from\n multiple noisy oracles.\n\n Parameters\n ----------\n labels: list\n A list with length=k, which contains the labels provided by\n k noisy oracles.\n\n weight: list, optional (default=None)... |
def get_query_results(selected_instance, oracles, names=None):
'Get the query results from oracles of the selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n oracles: {list, alipy.o... | 4,728,099,483,708,930,000 | Get the query results from oracles of the selected instance.
Parameters
----------
selected_instance: int
The indexes of selected samples. Should be a member of unlabeled set.
oracles: {list, alipy.oracle.Oracles}
An alipy.oracle.Oracle object that contains all the
available oracles or a list of oracles.
... | alipy/query_strategy/noisy_oracles.py | get_query_results | Houchaoqun/ALiPy | python | def get_query_results(selected_instance, oracles, names=None):
'Get the query results from oracles of the selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n oracles: {list, alipy.o... |
def get_majority_vote(selected_instance, oracles, names=None):
'Get the majority vote results of the selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n oracles: {list, alipy.oracle.Oracles}\n A... | 7,810,245,918,018,826,000 | Get the majority vote results of the selected instance.
Parameters
----------
selected_instance: int
The indexes of selected samples. Should be a member of unlabeled set.
oracles: {list, alipy.oracle.Oracles}
An alipy.oracle.Oracle object that contains all the
available oracles or a list of oracles.
E... | alipy/query_strategy/noisy_oracles.py | get_majority_vote | Houchaoqun/ALiPy | python | def get_majority_vote(selected_instance, oracles, names=None):
'Get the majority vote results of the selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n oracles: {list, alipy.oracle.Oracles}\n A... |
def select(self, label_index, unlabel_index, eval_cost=False, model=None, **kwargs):
"Query from oracles. Return the index of selected instance and oracle.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The indexes of labeled samples.\n\n unla... | 5,707,326,584,340,173,000 | Query from oracles. Return the index of selected instance and oracle.
Parameters
----------
label_index: {list, np.ndarray, IndexCollection}
The indexes of labeled samples.
unlabel_index: {list, np.ndarray, IndexCollection}
The indexes of unlabeled samples.
eval_cost: bool, optional (default=False)
To ev... | alipy/query_strategy/noisy_oracles.py | select | Houchaoqun/ALiPy | python | def select(self, label_index, unlabel_index, eval_cost=False, model=None, **kwargs):
"Query from oracles. Return the index of selected instance and oracle.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The indexes of labeled samples.\n\n unla... |
def select_by_prediction_mat(self, label_index, unlabel_index, predict, **kwargs):
'Query from oracles. Return the index of selected instance and oracle.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The indexes of labeled samples.\n\n unlabe... | 2,987,720,386,717,713,000 | Query from oracles. Return the index of selected instance and oracle.
Parameters
----------
label_index: {list, np.ndarray, IndexCollection}
The indexes of labeled samples.
unlabel_index: {list, np.ndarray, IndexCollection}
The indexes of unlabeled samples.
predict: : 2d array, shape [n_samples, n_classes]
... | alipy/query_strategy/noisy_oracles.py | select_by_prediction_mat | Houchaoqun/ALiPy | python | def select_by_prediction_mat(self, label_index, unlabel_index, predict, **kwargs):
'Query from oracles. Return the index of selected instance and oracle.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The indexes of labeled samples.\n\n unlabe... |
def _calc_Q_table(self, label_index, unlabel_index, oracles, pred_unlab, n_neighbors=10, eval_cost=False):
'Query from oracles. Return the Q table and the oracle name/index of each row of Q_table.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The in... | 6,530,858,138,236,620,000 | Query from oracles. Return the Q table and the oracle name/index of each row of Q_table.
Parameters
----------
label_index: {list, np.ndarray, IndexCollection}
The indexes of labeled samples.
unlabel_index: {list, np.ndarray, IndexCollection}
The indexes of unlabeled samples.
oracles: {list, alipy.oracle.Ora... | alipy/query_strategy/noisy_oracles.py | _calc_Q_table | Houchaoqun/ALiPy | python | def _calc_Q_table(self, label_index, unlabel_index, oracles, pred_unlab, n_neighbors=10, eval_cost=False):
'Query from oracles. Return the Q table and the oracle name/index of each row of Q_table.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The in... |
def select(self, label_index, unlabel_index, model=None, **kwargs):
'Select an instance and a batch of oracles to label it.\n The instance is selected by uncertainty, the oracles is\n selected by the difference between their\n labeling results and the majority vote results.\n\n Parameter... | -6,239,752,573,043,427,000 | Select an instance and a batch of oracles to label it.
The instance is selected by uncertainty, the oracles is
selected by the difference between their
labeling results and the majority vote results.
Parameters
----------
label_index: {list, np.ndarray, IndexCollection}
The indexes of labeled samples.
unlabel_ind... | alipy/query_strategy/noisy_oracles.py | select | Houchaoqun/ALiPy | python | def select(self, label_index, unlabel_index, model=None, **kwargs):
'Select an instance and a batch of oracles to label it.\n The instance is selected by uncertainty, the oracles is\n selected by the difference between their\n labeling results and the majority vote results.\n\n Parameter... |
def select_by_prediction_mat(self, label_index, unlabel_index, predict):
'Query from oracles. Return the index of selected instance and oracle.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The indexes of labeled samples.\n\n unlabel_index: {... | -8,976,557,389,727,556,000 | Query from oracles. Return the index of selected instance and oracle.
Parameters
----------
label_index: {list, np.ndarray, IndexCollection}
The indexes of labeled samples.
unlabel_index: {list, np.ndarray, IndexCollection}
The indexes of unlabeled samples.
predict: : 2d array, shape [n_samples, n_classes]
... | alipy/query_strategy/noisy_oracles.py | select_by_prediction_mat | Houchaoqun/ALiPy | python | def select_by_prediction_mat(self, label_index, unlabel_index, predict):
'Query from oracles. Return the index of selected instance and oracle.\n\n Parameters\n ----------\n label_index: {list, np.ndarray, IndexCollection}\n The indexes of labeled samples.\n\n unlabel_index: {... |
def _calc_uia(self, oracle_history, majority_vote_result, alpha=0.05):
'Calculate the UI(a) by providing the labeling history and the majority vote results.\n\n Parameters\n ----------\n oracle_history: dict\n The labeling history of an oracle. The key is the index of instance, the v... | -5,705,311,290,492,422,000 | Calculate the UI(a) by providing the labeling history and the majority vote results.
Parameters
----------
oracle_history: dict
The labeling history of an oracle. The key is the index of instance, the value is the
label given by the oracle.
majority_vote_result: dict
The results of majority vote of instan... | alipy/query_strategy/noisy_oracles.py | _calc_uia | Houchaoqun/ALiPy | python | def _calc_uia(self, oracle_history, majority_vote_result, alpha=0.05):
'Calculate the UI(a) by providing the labeling history and the majority vote results.\n\n Parameters\n ----------\n oracle_history: dict\n The labeling history of an oracle. The key is the index of instance, the v... |
def select_by_given_instance(self, selected_instance):
'Select oracle to query by providing the index of selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n Returns\n -------... | 2,648,065,523,936,558,600 | Select oracle to query by providing the index of selected instance.
Parameters
----------
selected_instance: int
The indexes of selected samples. Should be a member of unlabeled set.
Returns
-------
selected_oracles: list
The selected oracles for querying. | alipy/query_strategy/noisy_oracles.py | select_by_given_instance | Houchaoqun/ALiPy | python | def select_by_given_instance(self, selected_instance):
'Select oracle to query by providing the index of selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n Returns\n -------... |
def select_by_given_instance(self, selected_instance):
'Select oracle to query by providing the index of selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n Returns\n -------... | 3,101,368,587,388,647,400 | Select oracle to query by providing the index of selected instance.
Parameters
----------
selected_instance: int
The indexes of selected samples. Should be a member of unlabeled set.
Returns
-------
oracles_ind: list
The indexes of selected oracles. | alipy/query_strategy/noisy_oracles.py | select_by_given_instance | Houchaoqun/ALiPy | python | def select_by_given_instance(self, selected_instance):
'Select oracle to query by providing the index of selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n Returns\n -------... |
def select_by_given_instance(self, selected_instance):
'Select oracle to query by providing the index of selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n Returns\n -------... | 2,175,907,547,186,365,200 | Select oracle to query by providing the index of selected instance.
Parameters
----------
selected_instance: int
The indexes of selected samples. Should be a member of unlabeled set.
Returns
-------
oracles_ind: list
The indexes of selected oracles. | alipy/query_strategy/noisy_oracles.py | select_by_given_instance | Houchaoqun/ALiPy | python | def select_by_given_instance(self, selected_instance):
'Select oracle to query by providing the index of selected instance.\n\n Parameters\n ----------\n selected_instance: int\n The indexes of selected samples. Should be a member of unlabeled set.\n\n Returns\n -------... |
def run(self, params={}):
'Add label to issue'
issue = self.connection.client.issue(id=params['id'])
if (not issue):
raise Exception(('Error: No issue found with ID: ' + params['id']))
labels = params['label'].split(',')
for label in labels:
if (label not in issue.fields.labels):
... | 4,915,808,299,214,609,000 | Add label to issue | jira/komand_jira/actions/label_issue/action.py | run | xhennessy-r7/insightconnect-plugins | python | def run(self, params={}):
issue = self.connection.client.issue(id=params['id'])
if (not issue):
raise Exception(('Error: No issue found with ID: ' + params['id']))
labels = params['label'].split(',')
for label in labels:
if (label not in issue.fields.labels):
issue.field... |
def normalize_query_parameters(params):
'9.1.1. Normalize Request Parameters'
return '&'.join(map((lambda pair: '='.join([_quote(pair[0]), _quote(pair[1])])), sorted(params.items()))) | 941,568,051,545,711,700 | 9.1.1. Normalize Request Parameters | emailage/signature.py | normalize_query_parameters | bluefish6/Emailage_Python | python | def normalize_query_parameters(params):
return '&'.join(map((lambda pair: '='.join([_quote(pair[0]), _quote(pair[1])])), sorted(params.items()))) |
def concatenate_request_elements(method, url, query):
'9.1.3. Concatenate Request Elements'
return '&'.join(map(_quote, [str(method).upper(), url, query])) | -1,319,764,161,872,008,200 | 9.1.3. Concatenate Request Elements | emailage/signature.py | concatenate_request_elements | bluefish6/Emailage_Python | python | def concatenate_request_elements(method, url, query):
return '&'.join(map(_quote, [str(method).upper(), url, query])) |
def hmac_sha1(base_string, hmac_key):
'9.2. HMAC-SHA1'
hash = hmac.new(b(hmac_key), b(base_string), sha1)
return hash.digest() | 8,651,286,224,927,855,000 | 9.2. HMAC-SHA1 | emailage/signature.py | hmac_sha1 | bluefish6/Emailage_Python | python | def hmac_sha1(base_string, hmac_key):
hash = hmac.new(b(hmac_key), b(base_string), sha1)
return hash.digest() |
def encode(digest):
'9.2.1. Generating Signature'
return base64.b64encode(digest).decode('ascii').rstrip('\n') | 6,410,103,192,144,333,000 | 9.2.1. Generating Signature | emailage/signature.py | encode | bluefish6/Emailage_Python | python | def encode(digest):
return base64.b64encode(digest).decode('ascii').rstrip('\n') |
def add_oauth_entries_to_fields_dict(secret, params, nonce=None, timestamp=None):
" Adds dict entries to the user's params dict which are required for OAuth1.0 signature generation\n\n :param secret: API secret\n :param params: dictionary of values which will be sent in the query\n :param nonce... | 3,161,492,757,002,849,000 | Adds dict entries to the user's params dict which are required for OAuth1.0 signature generation
:param secret: API secret
:param params: dictionary of values which will be sent in the query
:param nonce: (Optional) random string used in signature creation, uuid4() is used if not provided
:param timestamp: (Optional) ... | emailage/signature.py | add_oauth_entries_to_fields_dict | bluefish6/Emailage_Python | python | def add_oauth_entries_to_fields_dict(secret, params, nonce=None, timestamp=None):
" Adds dict entries to the user's params dict which are required for OAuth1.0 signature generation\n\n :param secret: API secret\n :param params: dictionary of values which will be sent in the query\n :param nonce... |
def create(method, url, params, hmac_key):
" Generates the OAuth1.0 signature used as the value for the query string parameter 'oauth_signature'\n \n :param method: HTTP method that will be used to send the request ( 'GET' | 'POST' ); EmailageClient uses GET\n :param url: API domain and endpoint up... | -465,169,348,556,150,140 | Generates the OAuth1.0 signature used as the value for the query string parameter 'oauth_signature'
:param method: HTTP method that will be used to send the request ( 'GET' | 'POST' ); EmailageClient uses GET
:param url: API domain and endpoint up to the ?
:param params: user-provided query string parameters and the O... | emailage/signature.py | create | bluefish6/Emailage_Python | python | def create(method, url, params, hmac_key):
" Generates the OAuth1.0 signature used as the value for the query string parameter 'oauth_signature'\n \n :param method: HTTP method that will be used to send the request ( 'GET' | 'POST' ); EmailageClient uses GET\n :param url: API domain and endpoint up... |
def load_custom_boot9(path: str, dev: bool=False):
'Load keys from a custom ARM9 bootROM path.'
if path:
from pyctr.crypto import CryptoEngine
CryptoEngine(boot9=path, dev=dev) | -6,919,565,763,664,082,000 | Load keys from a custom ARM9 bootROM path. | ninfs/mount/_common.py | load_custom_boot9 | Jhynjhiruu/ninfs | python | def load_custom_boot9(path: str, dev: bool=False):
if path:
from pyctr.crypto import CryptoEngine
CryptoEngine(boot9=path, dev=dev) |
def __repr__(self):
' return tree as JSON serialized dictionary '
return self.pretty_print(self.__dict__) | -4,872,637,371,779,116,000 | return tree as JSON serialized dictionary | gametree_lite.py | __repr__ | deadsmond/gametree | python | def __repr__(self):
' '
return self.pretty_print(self.__dict__) |
@staticmethod
def pretty_print(dictionary: dict):
' return pretty printed dictionary as JSON serialized object '
return json.dumps(dictionary, indent=4) | 5,869,241,633,187,367,000 | return pretty printed dictionary as JSON serialized object | gametree_lite.py | pretty_print | deadsmond/gametree | python | @staticmethod
def pretty_print(dictionary: dict):
' '
return json.dumps(dictionary, indent=4) |
def __init__(self, nodes: dict=None, groups: dict=None, leafs: list=None, players_list: list=None):
'\n GameTree class used to represent game tree:\n\n Attributes\n ----------\n nodes : dict\n dictionary of nodes;\n groups : dict\n dictionary of groups\n ... | -7,397,175,947,897,329,000 | GameTree class used to represent game tree:
Attributes
----------
nodes : dict
dictionary of nodes;
groups : dict
dictionary of groups
leafs : list
list of leafs, calculated on demand
players_list: list
list of players names, indicating which game income from list is connected to which player | gametree_lite.py | __init__ | deadsmond/gametree | python | def __init__(self, nodes: dict=None, groups: dict=None, leafs: list=None, players_list: list=None):
'\n GameTree class used to represent game tree:\n\n Attributes\n ----------\n nodes : dict\n dictionary of nodes;\n groups : dict\n dictionary of groups\n ... |
def add_node(self, node: dict):
"\n add node method. Runs basic validation before adding.\n\n :param dict node: dictionary of node's data\n "
if (node.get('id') is not None):
if (node['id'] in self._nodes):
raise ValueError(('tried to override node %s' % node['id']))
... | 672,232,565,832,253,000 | add node method. Runs basic validation before adding.
:param dict node: dictionary of node's data | gametree_lite.py | add_node | deadsmond/gametree | python | def add_node(self, node: dict):
"\n add node method. Runs basic validation before adding.\n\n :param dict node: dictionary of node's data\n "
if (node.get('id') is not None):
if (node['id'] in self._nodes):
raise ValueError(('tried to override node %s' % node['id']))
... |
def add_vertex(self, id_: str, player: str, parents: dict):
'\n add vertex from simplified function:\n\n :param str id_: id of the node\n :param str player: id of player owning the node\n :param dict parents: dictionary of parents for the node\n '
self.add_node({'id': id_, 'pl... | 3,655,447,033,792,964,600 | add vertex from simplified function:
:param str id_: id of the node
:param str player: id of player owning the node
:param dict parents: dictionary of parents for the node | gametree_lite.py | add_vertex | deadsmond/gametree | python | def add_vertex(self, id_: str, player: str, parents: dict):
'\n add vertex from simplified function:\n\n :param str id_: id of the node\n :param str player: id of player owning the node\n :param dict parents: dictionary of parents for the node\n '
self.add_node({'id': id_, 'pl... |
def add_leaf(self, id_: str, value: list, parents: dict):
"\n add leaf from simplified function:\n\n :param str id_: id of the node\n :param list value: list of node's values\n :param dict parents: dictionary of parents for the node\n "
self.add_node({'id': id_, 'value': value... | 1,990,150,339,781,963,000 | add leaf from simplified function:
:param str id_: id of the node
:param list value: list of node's values
:param dict parents: dictionary of parents for the node | gametree_lite.py | add_leaf | deadsmond/gametree | python | def add_leaf(self, id_: str, value: list, parents: dict):
"\n add leaf from simplified function:\n\n :param str id_: id of the node\n :param list value: list of node's values\n :param dict parents: dictionary of parents for the node\n "
self.add_node({'id': id_, 'value': value... |
def copy_node(self, from_: str, to_: str):
"\n create a copy of node's properties in another node\n\n :param str from_: origin node of properties\n :param str to_: destination node for properties\n "
self._nodes[to_] = dict(self._nodes[from_]) | -6,969,693,781,149,090 | create a copy of node's properties in another node
:param str from_: origin node of properties
:param str to_: destination node for properties | gametree_lite.py | copy_node | deadsmond/gametree | python | def copy_node(self, from_: str, to_: str):
"\n create a copy of node's properties in another node\n\n :param str from_: origin node of properties\n :param str to_: destination node for properties\n "
self._nodes[to_] = dict(self._nodes[from_]) |
def change_node(self, node: dict):
"\n change node method. Changes attributes provided in node dictionary\n\n :param dict node: dictionary of node's data\n "
if (node.get('id') is not None):
if (node['id'] not in self._nodes):
raise ValueError(('tried to change non-exist... | 6,497,729,752,810,320,000 | change node method. Changes attributes provided in node dictionary
:param dict node: dictionary of node's data | gametree_lite.py | change_node | deadsmond/gametree | python | def change_node(self, node: dict):
"\n change node method. Changes attributes provided in node dictionary\n\n :param dict node: dictionary of node's data\n "
if (node.get('id') is not None):
if (node['id'] not in self._nodes):
raise ValueError(('tried to change non-exist... |
def get_parent(self, id_) -> str:
' get id of the parent node '
return list(self._nodes[id_]['parents'].keys())[0] | 3,571,465,201,896,533,500 | get id of the parent node | gametree_lite.py | get_parent | deadsmond/gametree | python | def get_parent(self, id_) -> str:
' '
return list(self._nodes[id_]['parents'].keys())[0] |
def get_player_index(self, id_) -> int:
' return player index from players list order '
return self._players_list.index(self._nodes[id_]['player']) | 1,250,716,915,530,892,800 | return player index from players list order | gametree_lite.py | get_player_index | deadsmond/gametree | python | def get_player_index(self, id_) -> int:
' '
return self._players_list.index(self._nodes[id_]['player']) |
def get_path_to_node(self, id_: str, mode: str='nodes') -> list:
"\n get path from root to the node\n :param str id_: id of the node you want to reach from root\n :param str mode: mode of return type, 'nodes' - make path with nodes id, 'moves' - make path with player choices\n "
path... | -2,872,573,102,666,817,500 | get path from root to the node
:param str id_: id of the node you want to reach from root
:param str mode: mode of return type, 'nodes' - make path with nodes id, 'moves' - make path with player choices | gametree_lite.py | get_path_to_node | deadsmond/gametree | python | def get_path_to_node(self, id_: str, mode: str='nodes') -> list:
"\n get path from root to the node\n :param str id_: id of the node you want to reach from root\n :param str mode: mode of return type, 'nodes' - make path with nodes id, 'moves' - make path with player choices\n "
path... |
@staticmethod
def _get_key(obj: dict, val: str) -> list:
'\n get list of keys with specified value from obj dictionary\n :param dict obj: chosen dictionary\n :param str val: specified value\n '
sublist = [key for (key, value) in obj.items() if (value == val)]
if sublist:
... | 8,235,374,987,499,246,000 | get list of keys with specified value from obj dictionary
:param dict obj: chosen dictionary
:param str val: specified value | gametree_lite.py | _get_key | deadsmond/gametree | python | @staticmethod
def _get_key(obj: dict, val: str) -> list:
'\n get list of keys with specified value from obj dictionary\n :param dict obj: chosen dictionary\n :param str val: specified value\n '
sublist = [key for (key, value) in obj.items() if (value == val)]
if sublist:
... |
def get_tree(self) -> dict:
' return copy of tree nodes structure dict'
return dict(self._nodes) | 8,268,054,770,871,867,000 | return copy of tree nodes structure dict | gametree_lite.py | get_tree | deadsmond/gametree | python | def get_tree(self) -> dict:
' '
return dict(self._nodes) |
def calculate_leafs(self):
' calculate inner list of leafs ids '
self._leafs = [node for node in self._nodes if (not self._nodes[node]['children'])] | -5,249,638,405,223,942,000 | calculate inner list of leafs ids | gametree_lite.py | calculate_leafs | deadsmond/gametree | python | def calculate_leafs(self):
' '
self._leafs = [node for node in self._nodes if (not self._nodes[node]['children'])] |
def get_leafs(self) -> list:
' return list of leafs ids. Will return empty list, if calculate_leafs() has not been called earlier. '
return self._leafs[:] | -8,597,578,595,401,025,000 | return list of leafs ids. Will return empty list, if calculate_leafs() has not been called earlier. | gametree_lite.py | get_leafs | deadsmond/gametree | python | def get_leafs(self) -> list:
' '
return self._leafs[:] |
def set_group(self, id_: str, player: str, group: list):
"\n add list of ids to new group\n :param str id_: id of group\n :param str player: id of player owning the group\n :param list group: list of id's you want to create group with\n "
self._groups[id_] = {'player': player,... | -7,605,189,599,437,389,000 | add list of ids to new group
:param str id_: id of group
:param str player: id of player owning the group
:param list group: list of id's you want to create group with | gametree_lite.py | set_group | deadsmond/gametree | python | def set_group(self, id_: str, player: str, group: list):
"\n add list of ids to new group\n :param str id_: id of group\n :param str player: id of player owning the group\n :param list group: list of id's you want to create group with\n "
self._groups[id_] = {'player': player,... |
def get_groups(self) -> dict:
' return dictionary of groups '
return dict(self._groups) | 3,093,298,729,605,135,000 | return dictionary of groups | gametree_lite.py | get_groups | deadsmond/gametree | python | def get_groups(self) -> dict:
' '
return dict(self._groups) |
def get_groups_of_player(self, player: str) -> list:
" return list of all groups id's where player is the owner "
return [group for group in self._groups if (self._groups[group]['player'] == player)] | 437,090,716,761,561,800 | return list of all groups id's where player is the owner | gametree_lite.py | get_groups_of_player | deadsmond/gametree | python | def get_groups_of_player(self, player: str) -> list:
" "
return [group for group in self._groups if (self._groups[group]['player'] == player)] |
def variable_position_placement_generator(positions):
'\n Use itertools.product to generate a list of tuple with different number of 0 and 1. The length of the tuple is the\n length of the input positions.\n Using itertools.compress, for each output from itertools.product pairing with input positions, we g... | 2,728,138,451,279,051,000 | Use itertools.product to generate a list of tuple with different number of 0 and 1. The length of the tuple is the
length of the input positions.
Using itertools.compress, for each output from itertools.product pairing with input positions, we generate a list of
positions where only those with the same index as 1 would... | sequal/sequence.py | variable_position_placement_generator | bschulzlab/dialib_standalone | python | def variable_position_placement_generator(positions):
'\n Use itertools.product to generate a list of tuple with different number of 0 and 1. The length of the tuple is the\n length of the input positions.\n Using itertools.compress, for each output from itertools.product pairing with input positions, we g... |
def __init__(self, seq, encoder=AminoAcid, mods=None, parse=True, parser_ignore=None, mod_position='right'):
'\n :param mod_position\n Indicate the position of the modifications relative to the base block it is supposed to modify\n :type mod_position: str\n :param mods\n Dictionar... | 2,356,593,637,083,451,000 | :param mod_position
Indicate the position of the modifications relative to the base block it is supposed to modify
:type mod_position: str
:param mods
Dictionary whose keys are the positions within the sequence and values are array of modifications at those
positions
:type mods: dict
:param encoder
Class for encoding o... | sequal/sequence.py | __init__ | bschulzlab/dialib_standalone | python | def __init__(self, seq, encoder=AminoAcid, mods=None, parse=True, parser_ignore=None, mod_position='right'):
'\n :param mod_position\n Indicate the position of the modifications relative to the base block it is supposed to modify\n :type mod_position: str\n :param mods\n Dictionar... |
def sequence_parse(self, current_mod, current_position, mod_position, mods, seq):
'\n :param seq: sequence input\n :param mods: external modification input\n :param mod_position: modification position relative to the modified residue\n :param current_position: current iterating amino aci... | -6,007,742,902,697,778,000 | :param seq: sequence input
:param mods: external modification input
:param mod_position: modification position relative to the modified residue
:param current_position: current iterating amino acid position from the input sequence
:type current_mod: List[Modification] | sequal/sequence.py | sequence_parse | bschulzlab/dialib_standalone | python | def sequence_parse(self, current_mod, current_position, mod_position, mods, seq):
'\n :param seq: sequence input\n :param mods: external modification input\n :param mod_position: modification position relative to the modified residue\n :param current_position: current iterating amino aci... |
def to_stripped_string(self):
'\n Return string of the sequence without any modification annotation\n :return: str\n '
seq = ''
for i in self.seq:
seq += i.value
return seq | 92,417,537,465,720,400 | Return string of the sequence without any modification annotation
:return: str | sequal/sequence.py | to_stripped_string | bschulzlab/dialib_standalone | python | def to_stripped_string(self):
'\n Return string of the sequence without any modification annotation\n :return: str\n '
seq =
for i in self.seq:
seq += i.value
return seq |
def to_string_customize(self, data, annotation_placement='right', block_separator='', annotation_enclose_characters=('[', ']'), individual_annotation_enclose=False, individual_annotation_enclose_characters=('[', ']'), individual_annotation_separator=''):
'\n\n :rtype: str\n :param data: a dictionary w... | 7,458,964,784,928,617,000 | :rtype: str
:param data: a dictionary where the key is the index position of the amino acid residue and the value is a
iterable where containing the item needed to be included into the sequence.
:param annotation_placement: whether the information should be included on the right of the left of the residue
:param block_... | sequal/sequence.py | to_string_customize | bschulzlab/dialib_standalone | python | def to_string_customize(self, data, annotation_placement='right', block_separator=, annotation_enclose_characters=('[', ']'), individual_annotation_enclose=False, individual_annotation_enclose_characters=('[', ']'), individual_annotation_separator=):
'\n\n :rtype: str\n :param data: a dictionary where... |
def __init__(self, seq, variable_mods=None, static_mods=None, used_scenarios=None, parse_mod_position=True, mod_position_dict=None, ignore_position=None):
'\n Generator for creating modified sequences.\n :type used_scenarios: set\n :type static_mods: List[Modification]\n :type variable_m... | 442,156,656,313,768,800 | Generator for creating modified sequences.
:type used_scenarios: set
:type static_mods: List[Modification]
:type variable_mods: List[Modification]
:type seq: str | sequal/sequence.py | __init__ | bschulzlab/dialib_standalone | python | def __init__(self, seq, variable_mods=None, static_mods=None, used_scenarios=None, parse_mod_position=True, mod_position_dict=None, ignore_position=None):
'\n Generator for creating modified sequences.\n :type used_scenarios: set\n :type static_mods: List[Modification]\n :type variable_m... |
def variable_mod_generate_scenarios(self):
'\n Recursively generating all possible position compositions for each variable modification and add them to\n self.variable_map_scenarios dictionary where key is the value attr of the modification while the value is the\n position list\n '
... | -6,510,374,812,757,205,000 | Recursively generating all possible position compositions for each variable modification and add them to
self.variable_map_scenarios dictionary where key is the value attr of the modification while the value is the
position list | sequal/sequence.py | variable_mod_generate_scenarios | bschulzlab/dialib_standalone | python | def variable_mod_generate_scenarios(self):
'\n Recursively generating all possible position compositions for each variable modification and add them to\n self.variable_map_scenarios dictionary where key is the value attr of the modification while the value is the\n position list\n '
... |
def render_generic_exception(exception):
'Log a traceback and return code 500 with a simple JSON\n The CORS header is set as usual. Without this, an error could lead to browsers\n caching a response without the correct CORS header.\n '
current_app.logger.error(f'Exception: {exception}')
current_app... | -1,476,872,618,221,553,700 | Log a traceback and return code 500 with a simple JSON
The CORS header is set as usual. Without this, an error could lead to browsers
caching a response without the correct CORS header. | newapi/ooniapi/views.py | render_generic_exception | hellais/ooni-measurements | python | def render_generic_exception(exception):
'Log a traceback and return code 500 with a simple JSON\n The CORS header is set as usual. Without this, an error could lead to browsers\n caching a response without the correct CORS header.\n '
current_app.logger.error(f'Exception: {exception}')
current_app... |
def pixel_unshuffle(input, downscale_factor):
'\n input: batchSize * c * k*w * k*h\n downscale_factor: k\n batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h\n '
c = input.shape[1]
kernel = torch.zeros(size=[((downscale_factor * downscale_factor) * c), 1, downscale_factor, downscale_factor],... | -4,688,762,636,236,403,000 | input: batchSize * c * k*w * k*h
downscale_factor: k
batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h | src/model/PixelUnShuffle.py | pixel_unshuffle | laowng/GISR | python | def pixel_unshuffle(input, downscale_factor):
'\n input: batchSize * c * k*w * k*h\n downscale_factor: k\n batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h\n '
c = input.shape[1]
kernel = torch.zeros(size=[((downscale_factor * downscale_factor) * c), 1, downscale_factor, downscale_factor],... |
def forward(self, input):
'\n input: batchSize * c * k*w * k*h\n downscale_factor: k\n batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h\n '
return pixel_unshuffle(input, self.downscale_factor) | 4,646,901,910,324,699,000 | input: batchSize * c * k*w * k*h
downscale_factor: k
batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h | src/model/PixelUnShuffle.py | forward | laowng/GISR | python | def forward(self, input):
'\n input: batchSize * c * k*w * k*h\n downscale_factor: k\n batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h\n '
return pixel_unshuffle(input, self.downscale_factor) |
def load_annotations(self, ann_file):
'Load annotation from COCO style annotation file.\n Args:\n ann_file (str): Path of annotation file.\n Returns:\n list[dict]: Annotation info from COCO api.\n '
self.coco = COCO(ann_file)
self.cat_ids = self.coco.get_cat_ids(ca... | -2,126,208,448,530,252,000 | Load annotation from COCO style annotation file.
Args:
ann_file (str): Path of annotation file.
Returns:
list[dict]: Annotation info from COCO api. | mmdet/datasets/coco_car.py | load_annotations | invite-you/mmdetection | python | def load_annotations(self, ann_file):
'Load annotation from COCO style annotation file.\n Args:\n ann_file (str): Path of annotation file.\n Returns:\n list[dict]: Annotation info from COCO api.\n '
self.coco = COCO(ann_file)
self.cat_ids = self.coco.get_cat_ids(ca... |
def get_ann_info(self, idx):
'Get COCO annotation by index.\n Args:\n idx (int): Index of data.\n Returns:\n dict: Annotation info of specified index.\n '
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
ann_info = self.coco... | 3,511,945,127,863,459,000 | Get COCO annotation by index.
Args:
idx (int): Index of data.
Returns:
dict: Annotation info of specified index. | mmdet/datasets/coco_car.py | get_ann_info | invite-you/mmdetection | python | def get_ann_info(self, idx):
'Get COCO annotation by index.\n Args:\n idx (int): Index of data.\n Returns:\n dict: Annotation info of specified index.\n '
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
ann_info = self.coco... |
def get_cat_ids(self, idx):
'Get COCO category ids by index.\n Args:\n idx (int): Index of data.\n Returns:\n list[int]: All categories in the image of specified index.\n '
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
an... | 1,445,273,419,346,334,000 | Get COCO category ids by index.
Args:
idx (int): Index of data.
Returns:
list[int]: All categories in the image of specified index. | mmdet/datasets/coco_car.py | get_cat_ids | invite-you/mmdetection | python | def get_cat_ids(self, idx):
'Get COCO category ids by index.\n Args:\n idx (int): Index of data.\n Returns:\n list[int]: All categories in the image of specified index.\n '
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
an... |
def _filter_imgs(self, min_size=32):
'Filter images too small or without ground truths.'
valid_inds = []
ids_with_ann = set((_['image_id'] for _ in self.coco.anns.values()))
ids_in_cat = set()
for (i, class_id) in enumerate(self.cat_ids):
ids_in_cat |= set(self.coco.cat_img_map[class_id])
... | 988,372,852,360,179,500 | Filter images too small or without ground truths. | mmdet/datasets/coco_car.py | _filter_imgs | invite-you/mmdetection | python | def _filter_imgs(self, min_size=32):
valid_inds = []
ids_with_ann = set((_['image_id'] for _ in self.coco.anns.values()))
ids_in_cat = set()
for (i, class_id) in enumerate(self.cat_ids):
ids_in_cat |= set(self.coco.cat_img_map[class_id])
ids_in_cat &= ids_with_ann
valid_img_ids = []... |
def _parse_ann_info(self, img_info, ann_info):
'Parse bbox and mask annotation.\n Args:\n ann_info (list[dict]): Annotation info of an image.\n with_mask (bool): Whether to parse mask annotations.\n Returns:\n dict: A dict containing the following keys: bboxes, bboxes_... | -1,308,057,760,310,386,200 | Parse bbox and mask annotation.
Args:
ann_info (list[dict]): Annotation info of an image.
with_mask (bool): Whether to parse mask annotations.
Returns:
dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, seg_map. "masks" are raw annotations and not ... | mmdet/datasets/coco_car.py | _parse_ann_info | invite-you/mmdetection | python | def _parse_ann_info(self, img_info, ann_info):
'Parse bbox and mask annotation.\n Args:\n ann_info (list[dict]): Annotation info of an image.\n with_mask (bool): Whether to parse mask annotations.\n Returns:\n dict: A dict containing the following keys: bboxes, bboxes_... |
def xyxy2xywh(self, bbox):
'Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO\n evaluation.\n Args:\n bbox (numpy.ndarray): The bounding boxes, shape (4, ), in\n ``xyxy`` order.\n Returns:\n list[float]: The converted bounding boxes, in ``xywh... | 6,002,676,184,223,694,000 | Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
evaluation.
Args:
bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
``xyxy`` order.
Returns:
list[float]: The converted bounding boxes, in ``xywh`` order. | mmdet/datasets/coco_car.py | xyxy2xywh | invite-you/mmdetection | python | def xyxy2xywh(self, bbox):
'Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO\n evaluation.\n Args:\n bbox (numpy.ndarray): The bounding boxes, shape (4, ), in\n ``xyxy`` order.\n Returns:\n list[float]: The converted bounding boxes, in ``xywh... |
def _proposal2json(self, results):
'Convert proposal results to COCO json style.'
json_results = []
for idx in range(len(self)):
img_id = self.img_ids[idx]
bboxes = results[idx]
for i in range(bboxes.shape[0]):
data = dict()
data['image_id'] = img_id
... | 1,776,314,576,809,435,600 | Convert proposal results to COCO json style. | mmdet/datasets/coco_car.py | _proposal2json | invite-you/mmdetection | python | def _proposal2json(self, results):
json_results = []
for idx in range(len(self)):
img_id = self.img_ids[idx]
bboxes = results[idx]
for i in range(bboxes.shape[0]):
data = dict()
data['image_id'] = img_id
data['bbox'] = self.xyxy2xywh(bboxes[i])
... |
def _det2json(self, results):
'Convert detection results to COCO json style.'
json_results = []
for idx in range(len(self)):
img_id = self.img_ids[idx]
result = results[idx]
for label in range(len(result)):
bboxes = result[label]
for i in range(bboxes.shape[0]... | -8,234,219,059,450,971,000 | Convert detection results to COCO json style. | mmdet/datasets/coco_car.py | _det2json | invite-you/mmdetection | python | def _det2json(self, results):
json_results = []
for idx in range(len(self)):
img_id = self.img_ids[idx]
result = results[idx]
for label in range(len(result)):
bboxes = result[label]
for i in range(bboxes.shape[0]):
data = dict()
... |
def _segm2json(self, results):
'Convert instance segmentation results to COCO json style.'
bbox_json_results = []
segm_json_results = []
for idx in range(len(self)):
img_id = self.img_ids[idx]
(det, seg) = results[idx]
for label in range(len(det)):
bboxes = det[label]... | -3,094,880,850,971,942,400 | Convert instance segmentation results to COCO json style. | mmdet/datasets/coco_car.py | _segm2json | invite-you/mmdetection | python | def _segm2json(self, results):
bbox_json_results = []
segm_json_results = []
for idx in range(len(self)):
img_id = self.img_ids[idx]
(det, seg) = results[idx]
for label in range(len(det)):
bboxes = det[label]
for i in range(bboxes.shape[0]):
... |
def results2json(self, results, outfile_prefix):
'Dump the detection results to a COCO style json file.\n There are 3 types of results: proposals, bbox predictions, mask\n predictions, and they have different data types. This method will\n automatically recognize the type, and dump them to json... | 9,173,968,849,306,380,000 | Dump the detection results to a COCO style json file.
There are 3 types of results: proposals, bbox predictions, mask
predictions, and they have different data types. This method will
automatically recognize the type, and dump them to json files.
Args:
results (list[list | tuple | ndarray]): Testing results of the
... | mmdet/datasets/coco_car.py | results2json | invite-you/mmdetection | python | def results2json(self, results, outfile_prefix):
'Dump the detection results to a COCO style json file.\n There are 3 types of results: proposals, bbox predictions, mask\n predictions, and they have different data types. This method will\n automatically recognize the type, and dump them to json... |
def format_results(self, results, jsonfile_prefix=None, **kwargs):
'Format the results to json (standard format for COCO evaluation).\n Args:\n results (list[tuple | numpy.ndarray]): Testing results of the\n dataset.\n jsonfile_prefix (str | None): The prefix of json file... | 5,435,673,174,381,394,000 | Format the results to json (standard format for COCO evaluation).
Args:
results (list[tuple | numpy.ndarray]): Testing results of the
dataset.
jsonfile_prefix (str | None): The prefix of json files. It includes
the file path and the prefix of filename, e.g., "a/b/prefix".
If not specifie... | mmdet/datasets/coco_car.py | format_results | invite-you/mmdetection | python | def format_results(self, results, jsonfile_prefix=None, **kwargs):
'Format the results to json (standard format for COCO evaluation).\n Args:\n results (list[tuple | numpy.ndarray]): Testing results of the\n dataset.\n jsonfile_prefix (str | None): The prefix of json file... |
def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=None, metric_items=None):
'Evaluation in COCO protocol.\n Args:\n results (list[list | tuple]): Testing results of the dataset.\n metric (str | list[st... | -2,850,738,235,883,896,000 | Evaluation in COCO protocol.
Args:
results (list[list | tuple]): Testing results of the dataset.
metric (str | list[str]): Metrics to be evaluated. Options are
'bbox', 'segm', 'proposal', 'proposal_fast'.
logger (logging.Logger | str | None): Logger used for printing
related information duri... | mmdet/datasets/coco_car.py | evaluate | invite-you/mmdetection | python | def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=None, metric_items=None):
'Evaluation in COCO protocol.\n Args:\n results (list[list | tuple]): Testing results of the dataset.\n metric (str | list[st... |
def _get_and_format(self, tags, key, format, convertfunc):
'\n Gets element with "key" from dict "tags". Converts this data with\n convertfunc and inserts it into the formatstring "format".\n\n If "format" is None, the data is returned without formatting, conversion\n is done.\n\n ... | 2,398,577,797,941,107,000 | Gets element with "key" from dict "tags". Converts this data with
convertfunc and inserts it into the formatstring "format".
If "format" is None, the data is returned without formatting, conversion
is done.
It the key is not in the dict, the empty string is returned. | image_exif/models.py | _get_and_format | svenhertle/django_image_exif | python | def _get_and_format(self, tags, key, format, convertfunc):
'\n Gets element with "key" from dict "tags". Converts this data with\n convertfunc and inserts it into the formatstring "format".\n\n If "format" is None, the data is returned without formatting, conversion\n is done.\n\n ... |
def test_fixture():
'Test Fixtures.'
assert (dir1 and dir2 and ttorrent and wind) | 8,045,601,637,958,376,000 | Test Fixtures. | tests/test_checktab.py | test_fixture | alexpdev/Torrentfile-GUI | python | def test_fixture():
assert (dir1 and dir2 and ttorrent and wind) |
def test_missing_files_check(dir2, ttorrent, wind):
'Test missing files checker proceduire.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
dirpath = Path(dir2)
for item in dirpath.iterdir():
if item.is_file():
os.remove(ite... | -2,974,906,744,892,642,000 | Test missing files checker proceduire. | tests/test_checktab.py | test_missing_files_check | alexpdev/Torrentfile-GUI | python | def test_missing_files_check(dir2, ttorrent, wind):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
dirpath = Path(dir2)
for item in dirpath.iterdir():
if item.is_file():
os.remove(item)
checktab.fileInput.setText(ttorre... |
def test_shorter_files_check(wind, ttorrent, dir2):
'Test missing files checker proceduire.'
(window, _) = wind
checktab = window.central.checkWidget
dirpath = Path(dir2)
window.central.setCurrentWidget(checktab)
def shortenfile(item):
'Shave some data off the end of file.'
temp... | 1,682,717,630,852,873,000 | Test missing files checker proceduire. | tests/test_checktab.py | test_shorter_files_check | alexpdev/Torrentfile-GUI | python | def test_shorter_files_check(wind, ttorrent, dir2):
(window, _) = wind
checktab = window.central.checkWidget
dirpath = Path(dir2)
window.central.setCurrentWidget(checktab)
def shortenfile(item):
'Shave some data off the end of file.'
temp = bytearray((2 ** 19))
with ope... |
def test_check_tab(wind, ttorrent, dir1):
'Test checker procedure.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
checktab.fileInput.setText(ttorrent)
checktab.searchInput.setText(dir1)
checktab.checkButton.click()
assert (checktab.tex... | 283,783,477,430,735,520 | Test checker procedure. | tests/test_checktab.py | test_check_tab | alexpdev/Torrentfile-GUI | python | def test_check_tab(wind, ttorrent, dir1):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
checktab.fileInput.setText(ttorrent)
checktab.searchInput.setText(dir1)
checktab.checkButton.click()
assert (checktab.textEdit.toPlainText() != ) |
def test_check_tab_input1(wind, dir1):
'Test checker procedure.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
checktab.browseButton2.browse(dir1)
assert (checktab.searchInput.text() != '') | -1,956,773,412,232,258,600 | Test checker procedure. | tests/test_checktab.py | test_check_tab_input1 | alexpdev/Torrentfile-GUI | python | def test_check_tab_input1(wind, dir1):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
checktab.browseButton2.browse(dir1)
assert (checktab.searchInput.text() != ) |
def test_check_tab_input_2(wind, dir1):
'Test checker procedure.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
checktab.browseButton1.browse(dir1)
assert (checktab.fileInput.text() != '') | -2,293,029,483,697,940,200 | Test checker procedure. | tests/test_checktab.py | test_check_tab_input_2 | alexpdev/Torrentfile-GUI | python | def test_check_tab_input_2(wind, dir1):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
checktab.browseButton1.browse(dir1)
assert (checktab.fileInput.text() != ) |
def test_check_tab4(wind):
'Test checker procedure again.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
tree_widget = checktab.treeWidget
assert (tree_widget.invisibleRootItem() is not None) | 7,435,339,097,934,807,000 | Test checker procedure again. | tests/test_checktab.py | test_check_tab4 | alexpdev/Torrentfile-GUI | python | def test_check_tab4(wind):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
tree_widget = checktab.treeWidget
assert (tree_widget.invisibleRootItem() is not None) |
def test_clear_logtext(wind):
'Test checker logTextEdit widget function.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
text_edit = checktab.textEdit
text_edit.insertPlainText('sometext')
text_edit.clear_data()
assert (text_edit.toPlai... | 7,770,702,326,506,262,000 | Test checker logTextEdit widget function. | tests/test_checktab.py | test_clear_logtext | alexpdev/Torrentfile-GUI | python | def test_clear_logtext(wind):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
text_edit = checktab.textEdit
text_edit.insertPlainText('sometext')
text_edit.clear_data()
assert (text_edit.toPlainText() == ) |
def test_checktab_tree(wind):
'Check tree item counting functionality.'
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
tree = TreeWidget(parent=checktab)
item = TreePieceItem(type=0, tree=tree)
item.progbar = ProgressBar(parent=tree, size=1... | -3,247,643,926,909,501,000 | Check tree item counting functionality. | tests/test_checktab.py | test_checktab_tree | alexpdev/Torrentfile-GUI | python | def test_checktab_tree(wind):
(window, _) = wind
checktab = window.central.checkWidget
window.central.setCurrentWidget(checktab)
tree = TreeWidget(parent=checktab)
item = TreePieceItem(type=0, tree=tree)
item.progbar = ProgressBar(parent=tree, size=1000000)
item.count(100000000)
ass... |
@pytest.mark.parametrize('size', list(range(18, 20)))
@pytest.mark.parametrize('index', list(range(1, 7, 2)))
@pytest.mark.parametrize('version', [1, 2, 3])
@pytest.mark.parametrize('ext', ['.mkv', '.rar', '.r00', '.mp3'])
def test_singlefile(size, ext, index, version, wind):
'Test the singlefile for create and che... | -7,495,223,836,807,719,000 | Test the singlefile for create and check tabs. | tests/test_checktab.py | test_singlefile | alexpdev/Torrentfile-GUI | python | @pytest.mark.parametrize('size', list(range(18, 20)))
@pytest.mark.parametrize('index', list(range(1, 7, 2)))
@pytest.mark.parametrize('version', [1, 2, 3])
@pytest.mark.parametrize('ext', ['.mkv', '.rar', '.r00', '.mp3'])
def test_singlefile(size, ext, index, version, wind):
(window, _) = wind
createtab =... |
def shortenfile(item):
'Shave some data off the end of file.'
temp = bytearray((2 ** 19))
with open(item, 'rb') as fd:
fd.readinto(temp)
with open(item, 'wb') as fd:
fd.write(temp) | -8,256,249,821,792,937,000 | Shave some data off the end of file. | tests/test_checktab.py | shortenfile | alexpdev/Torrentfile-GUI | python | def shortenfile(item):
temp = bytearray((2 ** 19))
with open(item, 'rb') as fd:
fd.readinto(temp)
with open(item, 'wb') as fd:
fd.write(temp) |
def coro(gen):
'Decorator to mark generator as co-routine.'
@wraps(gen)
def wind_up(*args, **kwargs):
it = gen(*args, **kwargs)
next(it)
return it
return wind_up | 543,768,862,196,839,230 | Decorator to mark generator as co-routine. | kombu/utils/compat.py | coro | CountRedClaw/kombu | python | def coro(gen):
@wraps(gen)
def wind_up(*args, **kwargs):
it = gen(*args, **kwargs)
next(it)
return it
return wind_up |
def detect_environment():
'Detect the current environment: default, eventlet, or gevent.'
global _environment
if (_environment is None):
_environment = _detect_environment()
return _environment | -5,701,659,537,937,548,000 | Detect the current environment: default, eventlet, or gevent. | kombu/utils/compat.py | detect_environment | CountRedClaw/kombu | python | def detect_environment():
global _environment
if (_environment is None):
_environment = _detect_environment()
return _environment |
def entrypoints(namespace):
'Return setuptools entrypoints for namespace.'
if (sys.version_info >= (3, 10)):
entry_points = importlib_metadata.entry_points(group=namespace)
else:
entry_points = importlib_metadata.entry_points().get(namespace, [])
return ((ep, ep.load()) for ep in entry_p... | 3,997,614,384,926,604,000 | Return setuptools entrypoints for namespace. | kombu/utils/compat.py | entrypoints | CountRedClaw/kombu | python | def entrypoints(namespace):
if (sys.version_info >= (3, 10)):
entry_points = importlib_metadata.entry_points(group=namespace)
else:
entry_points = importlib_metadata.entry_points().get(namespace, [])
return ((ep, ep.load()) for ep in entry_points) |
def fileno(f):
'Get fileno from file-like object.'
if isinstance(f, numbers.Integral):
return f
return f.fileno() | 5,161,474,401,131,961,000 | Get fileno from file-like object. | kombu/utils/compat.py | fileno | CountRedClaw/kombu | python | def fileno(f):
if isinstance(f, numbers.Integral):
return f
return f.fileno() |
def maybe_fileno(f):
'Get object fileno, or :const:`None` if not defined.'
try:
return fileno(f)
except FILENO_ERRORS:
pass | 8,165,246,639,734,941,000 | Get object fileno, or :const:`None` if not defined. | kombu/utils/compat.py | maybe_fileno | CountRedClaw/kombu | python | def maybe_fileno(f):
try:
return fileno(f)
except FILENO_ERRORS:
pass |
@contextmanager
def nested(*managers):
'Nest context managers.'
exits = []
vars = []
exc = (None, None, None)
try:
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append... | -6,615,287,256,100,333,000 | Nest context managers. | kombu/utils/compat.py | nested | CountRedClaw/kombu | python | @contextmanager
def nested(*managers):
exits = []
vars = []
exc = (None, None, None)
try:
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
(yiel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.