hexsha
stringlengths 40
40
| size
int64 5
2.06M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
248
| max_stars_repo_name
stringlengths 5
125
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
248
| max_issues_repo_name
stringlengths 5
125
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
248
| max_forks_repo_name
stringlengths 5
125
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
2.06M
| avg_line_length
float64 1
1.02M
| max_line_length
int64 3
1.03M
| alphanum_fraction
float64 0
1
| count_classes
int64 0
1.6M
| score_classes
float64 0
1
| count_generators
int64 0
651k
| score_generators
float64 0
1
| count_decorators
int64 0
990k
| score_decorators
float64 0
1
| count_async_functions
int64 0
235k
| score_async_functions
float64 0
1
| count_documentation
int64 0
1.04M
| score_documentation
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fd89a08e7b302e42c7342a9d210047fac1b9c3fb | 3,399 | py | Python | hasdrubal/visitors/type_var_resolver.py | Armani-T/hasdrubal | 7fac381b866114533e589e964ec7c27adbd1deff | [
"MIT"
]
| 2 | 2021-06-25T15:46:16.000Z | 2022-02-20T22:04:36.000Z | hasdrubal/visitors/type_var_resolver.py | Armani-T/hasdrubal | 7fac381b866114533e589e964ec7c27adbd1deff | [
"MIT"
]
| 42 | 2021-07-06T05:38:23.000Z | 2022-03-04T18:09:30.000Z | hasdrubal/visitors/type_var_resolver.py | Armani-T/hasdrubal | 7fac381b866114533e589e964ec7c27adbd1deff | [
"MIT"
]
| null | null | null | from typing import Container
from asts.typed import Name as TypedName
from asts import base, visitor, types_ as types
PREDEFINED_TYPES: Container[str] = (
",",
"->",
"Bool",
"Float",
"Int",
"List",
"String",
"Unit",
)
def resolve_type_vars(
node: base.ASTNode,
defined_types: Container[str] = PREDEFINED_TYPES,
) -> base.ASTNode:
"""
Convert `TypeName`s in the AST to `TypeVar`s using `defined_types`
to determine which ones should be converted.
Parameters
----------
node: ASTNode
The AST where `TypeName`s will be searched for.
defined_types: Container[str] = PREDEFINED_TYPES
If a `TypeName` is inside this, it will remain a `TypeName`.
Returns
-------
ASTNode
The AST but with the appropriate `TypeName`s converted to
`TypeVar`s.
"""
resolver = TypeVarResolver(defined_types)
return resolver.run(node)
class TypeVarResolver(visitor.BaseASTVisitor[base.ASTNode]):
"""
Convert undefined `TypeName`s into `TypeVar`s using `defined_types`
as a kind of symbol table to check whether a name should remain
a `TypeName` or be converted to a `TypeVar`.
Attributes
----------
defined_types: Container[str]
The identifiers that are known to actually be type names.
"""
def __init__(self, defined_types: Container[str] = PREDEFINED_TYPES) -> None:
self.defined_types: Container[str] = defined_types
def visit_block(self, node: base.Block) -> base.Block:
return base.Block(node.span, [expr.visit(self) for expr in node.body])
def visit_cond(self, node: base.Cond) -> base.Cond:
return base.Cond(
node.span,
node.pred.visit(self),
node.cons.visit(self),
node.else_.visit(self),
)
def visit_define(self, node: base.Define) -> base.Define:
return base.Define(node.span, node.target.visit(self), node.value.visit(self))
def visit_func_call(self, node: base.FuncCall) -> base.FuncCall:
return base.FuncCall(
node.span,
node.caller.visit(self),
node.callee.visit(self),
)
def visit_function(self, node: base.Function) -> base.Function:
return base.Function(node.span, node.param.visit(self), node.body.visit(self))
def visit_name(self, node: base.Name) -> base.Name:
if isinstance(node, TypedName):
return TypedName(node.span, node.type_.visit(self), node.value)
return node
def visit_scalar(self, node: base.Scalar) -> base.Scalar:
return node
def visit_type(self, node: types.Type) -> types.Type:
if isinstance(node, types.TypeApply):
return types.TypeApply(
node.span,
node.caller.visit(self),
node.callee.visit(self),
)
if isinstance(node, types.TypeName) and node.value not in self.defined_types:
return types.TypeVar(node.span, node.value)
if isinstance(node, types.TypeScheme):
return types.TypeScheme(node.actual_type.visit(self), node.bound_types)
return node
def visit_vector(self, node: base.Vector) -> base.Vector:
return base.Vector(
node.span,
node.vec_type,
[element.visit(self) for element in node.elements],
)
| 31.183486 | 86 | 0.626655 | 2,460 | 0.723742 | 0 | 0 | 0 | 0 | 0 | 0 | 857 | 0.252133 |
fd8a5381cdea04589d3919c507d39969d9014954 | 3,533 | py | Python | cdist/plugin.py | acerv/pytest-cdist | 24a3f0987c3bc2821b91374c93d6b1303a7aca81 | [
"MIT"
]
| null | null | null | cdist/plugin.py | acerv/pytest-cdist | 24a3f0987c3bc2821b91374c93d6b1303a7aca81 | [
"MIT"
]
| null | null | null | cdist/plugin.py | acerv/pytest-cdist | 24a3f0987c3bc2821b91374c93d6b1303a7aca81 | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
"""
cdist-plugin implementation.
Author:
Andrea Cervesato <[email protected]>
"""
import pytest
from cdist import __version__
from cdist.redis import RedisResource
from cdist.resource import ResourceError
def pytest_addoption(parser):
"""
Plugin configurations.
"""
parser.addini(
"cdist_hostname",
"cdist resource hostname (default: localhost)",
default="localhost"
)
parser.addini(
"cdist_port",
"cdist resource port (default: 6379)",
default="6379"
)
parser.addini(
"cdist_autolock",
"Enable/Disable configuration automatic lock (default: True)",
default="True"
)
group = parser.getgroup("cdist")
group.addoption(
"--cdist-config",
action="store",
dest="cdist_config",
default="",
help="configuration key name"
)
class Plugin:
"""
cdist plugin definition, handling client and pytest hooks.
"""
def __init__(self):
self._client = None
@staticmethod
def _get_autolock(config):
"""
Return autolock parameter.
"""
autolock = config.getini("cdist_autolock").lower() == "true"
return autolock
def pytest_report_header(self, config):
"""
Create the plugin report to be shown during the session.
"""
config_name = config.option.cdist_config
if not config_name:
return None
# fetch configuration data
hostname = config.getini("cdist_hostname")
port = config.getini("cdist_port")
autolock = self._get_autolock(config)
# create report lines
lines = list()
lines.append("cdist %s -- resource: %s:%s, configuration: %s, autolock: %s" %
(__version__, hostname, port, config_name, autolock))
return lines
def pytest_sessionstart(self, session):
"""
Initialize client, fetch data and update pytest configuration.
"""
config_name = session.config.option.cdist_config
if not config_name:
return None
# fetch data
hostname = session.config.getini("cdist_hostname")
port = session.config.getini("cdist_port")
autolock = self._get_autolock(session.config)
# create client
try:
self._client = RedisResource(hostname=hostname, port=int(port))
if autolock:
self._client.lock(config_name)
# pull configuration
config = self._client.pull(config_name)
except ResourceError as err:
raise pytest.UsageError(err)
# update pytest configuration
for key, value in config.items():
try:
# check if key is available inside pytest configuration
session.config.getini(key)
except ValueError:
continue
session.config._inicache[key] = value
def pytest_sessionfinish(self, session, exitstatus):
"""
Unlock configuration when session finish.
"""
config_name = session.config.option.cdist_config
if not config_name:
return None
autolock = self._get_autolock(session.config)
if autolock:
self._client.unlock(config_name)
def pytest_configure(config):
"""
Print out some session informations.
"""
config.pluginmanager.register(Plugin(), "plugin.cdist")
| 26.765152 | 85 | 0.601472 | 2,462 | 0.696858 | 0 | 0 | 196 | 0.055477 | 0 | 0 | 1,178 | 0.333428 |
fd8a85c0cecb1f0067a9c558a9299006820a9bf0 | 2,851 | py | Python | superironic/utils.py | jimrollenhagen/superironic | 45f8c50a881a0728c3d86e0783f9ee6baa47559d | [
"Apache-2.0"
]
| null | null | null | superironic/utils.py | jimrollenhagen/superironic | 45f8c50a881a0728c3d86e0783f9ee6baa47559d | [
"Apache-2.0"
]
| null | null | null | superironic/utils.py | jimrollenhagen/superironic | 45f8c50a881a0728c3d86e0783f9ee6baa47559d | [
"Apache-2.0"
]
| null | null | null | # Copyright 2015 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from superironic import colors
from superironic import config
def get_envs_in_group(group_name):
"""
Takes a group_name and finds any environments that have a SUPERIRONIC_GROUP
configuration line that matches the group_name.
"""
envs = []
for section in config.ironic_creds.sections():
if (config.ironic_creds.has_option(section, 'SUPERIRONIC_GROUP') and
config.ironic_creds.get(section,
'SUPERIRONIC_GROUP') == group_name):
envs.append(section)
return envs
def is_valid_environment(env):
"""Check if config file contains `env`."""
valid_envs = config.ironic_creds.sections()
return env in valid_envs
def is_valid_group(group_name):
"""
Checks to see if the configuration file contains a SUPERIRONIC_GROUP
configuration option.
"""
valid_groups = []
for section in config.ironic_creds.sections():
if config.ironic_creds.has_option(section, 'SUPERIRONIC_GROUP'):
valid_groups.append(config.ironic_creds.get(section,
'SUPERIRONIC_GROUP'))
valid_groups = list(set(valid_groups))
if group_name in valid_groups:
return True
else:
return False
def print_valid_envs(valid_envs):
"""Prints the available environments."""
print("[%s] Your valid environments are:" %
(colors.gwrap('Found environments')))
print("%r" % valid_envs)
def warn_missing_ironic_args():
"""Warn user about missing Ironic arguments."""
msg = """
[%s] No arguments were provided to pass along to ironic.
The superironic script expects to get commands structured like this:
superironic [environment] [command]
Here are some example commands that may help you get started:
superironic prod node-list
superironic prod node-show
superironic prod port-list
"""
print(msg % colors.rwrap('Missing arguments'))
def rm_prefix(name):
"""
Removes ironic_ os_ ironicclient_ prefix from string.
"""
if name.startswith('ironic_'):
return name[7:]
elif name.startswith('ironicclient_'):
return name[13:]
elif name.startswith('os_'):
return name[3:]
else:
return name
| 30.98913 | 79 | 0.681866 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,522 | 0.533848 |
fd8b4419a03211dab8726d274c1ded97471a7d78 | 1,150 | py | Python | cloudshell/huawei/wdm/cli/huawei_cli_handler.py | QualiSystems/cloudshell-huawei-wdm | be359a6bc81fd1644e3cb2a619b7c296a17a2e68 | [
"Apache-2.0"
]
| null | null | null | cloudshell/huawei/wdm/cli/huawei_cli_handler.py | QualiSystems/cloudshell-huawei-wdm | be359a6bc81fd1644e3cb2a619b7c296a17a2e68 | [
"Apache-2.0"
]
| 1 | 2021-04-11T18:57:18.000Z | 2021-04-11T18:57:18.000Z | cloudshell/huawei/wdm/cli/huawei_cli_handler.py | QualiSystems/cloudshell-huawei-wdm | be359a6bc81fd1644e3cb2a619b7c296a17a2e68 | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
from cloudshell.cli.service.cli_service_impl import CliServiceImpl
from cloudshell.huawei.cli.huawei_cli_handler import HuaweiCli, HuaweiCliHandler
from cloudshell.huawei.wdm.cli.huawei_command_modes import (
WDMConfigCommandMode,
WDMEnableCommandMode,
)
class HuaweiWDMCli(HuaweiCli):
def get_cli_handler(self, resource_config, logger):
return HuaweiWDMCliHandler(self.cli, resource_config, logger)
class HuaweiWDMCliHandler(HuaweiCliHandler):
@property
def default_mode(self):
return self.modes[WDMEnableCommandMode]
@property
def enable_mode(self):
return self.modes[WDMEnableCommandMode]
@property
def config_mode(self):
return self.modes[WDMConfigCommandMode]
def _on_session_start(self, session, logger):
"""Send default commands to configure/clear session outputs."""
cli_service = CliServiceImpl(
session=session, requested_command_mode=self.enable_mode, logger=logger
)
cli_service.send_command(
"screen-length 0 temporary", WDMEnableCommandMode.PROMPT
)
| 30.263158 | 83 | 0.727826 | 838 | 0.728696 | 0 | 0 | 253 | 0.22 | 0 | 0 | 130 | 0.113043 |
fd8b6f3ec4c3956c2a4af1d583d22afb4c1f7e8e | 1,510 | py | Python | pretalx_orcid/migrations/0001_initial.py | pretalx/pretalx-orcid | a10adf5bf5579bd7818db7697d49176114c9714e | [
"Apache-2.0"
]
| 1 | 2020-02-07T12:32:15.000Z | 2020-02-07T12:32:15.000Z | pretalx_orcid/migrations/0001_initial.py | pretalx/pretalx-orcid | a10adf5bf5579bd7818db7697d49176114c9714e | [
"Apache-2.0"
]
| 4 | 2019-11-26T04:02:02.000Z | 2022-03-06T02:06:54.000Z | pretalx_orcid/migrations/0001_initial.py | pretalx/pretalx-orcid | a10adf5bf5579bd7818db7697d49176114c9714e | [
"Apache-2.0"
]
| null | null | null | # Generated by Django 2.2.7 on 2019-11-20 14:10
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="OrcidProfile",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, serialize=False
),
),
("orcid", models.CharField(blank=True, max_length=40, null=True)),
(
"access_token",
models.CharField(blank=True, max_length=40, null=True),
),
(
"refresh_token",
models.CharField(blank=True, max_length=40, null=True),
),
("scope", models.CharField(blank=True, max_length=40, null=True)),
("expires_in", models.CharField(blank=True, max_length=20, null=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="orcid_profile",
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| 31.458333 | 87 | 0.47947 | 1,351 | 0.894702 | 0 | 0 | 0 | 0 | 0 | 0 | 141 | 0.093377 |
fd8bcae4d3f693f9766ffc4188aca7183ade4a41 | 980 | py | Python | python/leetcode/401.py | ParkinWu/leetcode | b31312bdefbb2be795f3459e1a76fbc927cab052 | [
"MIT"
]
| null | null | null | python/leetcode/401.py | ParkinWu/leetcode | b31312bdefbb2be795f3459e1a76fbc927cab052 | [
"MIT"
]
| null | null | null | python/leetcode/401.py | ParkinWu/leetcode | b31312bdefbb2be795f3459e1a76fbc927cab052 | [
"MIT"
]
| null | null | null | # 二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。
#
# 每个 LED 代表一个 0 或 1,最低位在右侧。
#
#
#
# 例如,上面的二进制手表读取 “3:25”。
#
# 给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。
#
# 案例:
#
# 输入: n = 1
# 返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
#
#
# 注意事项:
#
# 输出的顺序没有要求。
# 小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
# 分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。
#
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/binary-watch
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class Solution:
def numOfBin(self, pow: int, n: int) -> [int]:
if n == 0:
return [0]
if pow == 0:
return [1]
if pow <= n:
return []
return list(map(lambda x: x + 2 ** pow, self.numOfBin(pow - 1, n - 1))) + self.numOfBin(pow - 1, n)
def readBinaryWatch(self, num: int) -> List[str]:
pass
if __name__ == '__main__':
s = Solution()
res = s.numOfBin(4, 2)
print(res)
| 19.6 | 107 | 0.542857 | 372 | 0.266094 | 0 | 0 | 0 | 0 | 0 | 0 | 892 | 0.638054 |
fd8bcd859196def3cab1defab94ee20606249351 | 22,340 | py | Python | torchreid/engine/image/classmemoryloss_QA.py | Arindam-1991/deep_reid | ab68d95c2229ef5b832a6a6b614a9b91e4984bd5 | [
"MIT"
]
| 1 | 2021-03-27T17:27:47.000Z | 2021-03-27T17:27:47.000Z | torchreid/engine/image/classmemoryloss_QA.py | Arindam-1991/deep_reid | ab68d95c2229ef5b832a6a6b614a9b91e4984bd5 | [
"MIT"
]
| null | null | null | torchreid/engine/image/classmemoryloss_QA.py | Arindam-1991/deep_reid | ab68d95c2229ef5b832a6a6b614a9b91e4984bd5 | [
"MIT"
]
| null | null | null | from __future__ import division, print_function, absolute_import
import numpy as np
import torch, sys
import os.path as osp
from torchreid import metrics
from torchreid.losses import TripletLoss, CrossEntropyLoss
from torchreid.losses import ClassMemoryLoss
from ..engine import Engine
from ..pretrainer import PreTrainer
# Required for new engine run defination
import time, datetime
from torch import nn
from torchreid.utils import (
MetricMeter, AverageMeter, re_ranking, open_all_layers, Logger,
open_specified_layers, visualize_ranked_results
)
from torch.utils.tensorboard import SummaryWriter
from torchreid.utils.serialization import load_checkpoint, save_checkpoint
class ImageQAConvEngine(Engine):
r"""Triplet-loss engine for image-reid.
Args:
datamanager (DataManager): an instance of ``torchreid.data.ImageDataManager``
or ``torchreid.data.VideoDataManager``.
model (nn.Module): model instance.
optimizer (Optimizer): an Optimizer.
margin (float, optional): margin for triplet loss. Default is 0.3.
weight_t (float, optional): weight for triplet loss. Default is 1.
weight_x (float, optional): weight for softmax loss. Default is 1.
scheduler (LRScheduler, optional): if None, no learning rate decay will be performed.
use_gpu (bool, optional): use gpu. Default is True.
label_smooth (bool, optional): use label smoothing regularizer. Default is True.
Examples::
import torchreid
datamanager = torchreid.data.ImageDataManager(
root='path/to/reid-data',
sources='market1501',
height=256,
width=128,
combineall=False,
batch_size=32,
num_instances=4,
train_sampler='RandomIdentitySampler' # this is important
)
model = torchreid.models.build_model(
name='resnet50',
num_classes=datamanager.num_train_pids,
loss='triplet'
)
model = model.cuda()
optimizer = torchreid.optim.build_optimizer(
model, optim='adam', lr=0.0003
)
scheduler = torchreid.optim.build_lr_scheduler(
optimizer,
lr_scheduler='single_step',
stepsize=20
)
engine = torchreid.engine.ImageTripletEngine(
datamanager, model, optimizer, margin=0.3,
weight_t=0.7, weight_x=1, scheduler=scheduler
)
engine.run(
max_epoch=60,
save_dir='log/resnet50-triplet-market1501',
print_freq=10
)
"""
def __init__(
self,
datamanager,
model,
optimizer,
matcher,
margin = 0.3,
weight_t=1,
weight_clsm=1,
scheduler=None,
use_gpu=True,
label_smooth=True,
mem_batch_size = 16,
):
super(ImageQAConvEngine, self).__init__(datamanager, use_gpu)
self.datamanager = datamanager
self.model = model
self.matcher = matcher
self.optimizer = optimizer
self.scheduler = scheduler
self.register_model('model', model, optimizer, scheduler)
assert weight_t >= 0 and weight_clsm >= 0
assert weight_t + weight_clsm > 0
self.weight_t = weight_t
self.weight_clsm = weight_clsm
self.criterion_t = TripletLoss(margin=margin)
self.criterion_clsmloss = ClassMemoryLoss(self.matcher, datamanager.num_train_pids, mem_batch_size = mem_batch_size)
if self.use_gpu:
self.criterion_clsmloss = self.criterion_clsmloss.cuda()
def save_model(self, epoch, rank1, save_dir):
save_checkpoint(
{
'model': self.model.module.state_dict(),
'criterion': self.criterion_clsmloss.module.state_dict(),
'optim': self.optimizer.state_dict(),
'epoch': epoch + 1,
'rank1': rank1
},
fpath = osp.join(save_dir, self.method_name, self.sub_method_name, 'checkpoint.pth.tar')
)
def pretrain(self, test_only, output_dir):
"""
This function either loads an already trained model or pre-trains a model before actual
training for a better starting point.
"""
if self.resume or test_only:
print('Loading checkpoint...')
if self.resume and (self.resume != 'ori'):
checkpoint = load_checkpoint(self.resume)
else:
checkpoint = load_checkpoint(osp.join(output_dir, self.method_name, self.sub_method_name, 'checkpoint.pth.tar'))
self.model.load_state_dict(checkpoint['model'])
self.criterion_clsmloss.load_state_dict(checkpoint['criterion'])
self.optimizer.load_state_dict(checkpoint['optim'])
start_epoch = checkpoint['epoch']
print("=> Start epoch {} ".format(start_epoch))
elif self.pre_epochs > 0:
pre_tr = PreTrainer(
self.model,
self.criterion_clsmloss,
self.optimizer,
self.datamanager,
self.pre_epochs,
self.pmax_steps,
self.pnum_trials)
result_file = osp.join(output_dir, self.method_name, 'pretrain_metric.txt')
self.model, self.criterion_clsmloss, self.optimizer = pre_tr.train(result_file, self.method_name, self.sub_method_name)
def train(self, print_freq=10, print_epoch=False, fixbase_epoch=0, open_layers=None):
print(".... Calling train defination from new engine run ... !")
losses = MetricMeter()
batch_time = AverageMeter()
data_time = AverageMeter()
info_dict = {} # Dictonary containing all the information (loss, accuracy, lr etc)
if self.weight_t > 0:
losses_t = AverageMeter()
if self.weight_clsm > 0:
losses_clsm = AverageMeter()
precisions = AverageMeter()
self.set_model_mode('train')
self.two_stepped_transfer_learning(
self.epoch, fixbase_epoch, open_layers
)
self.num_batches = len(self.train_loader)
end = time.time()
for self.batch_idx, data in enumerate(self.train_loader):
data_time.update(time.time() - end)
loss_summary = self.forward_backward(data)
batch_time.update(time.time() - end)
losses.update(loss_summary)
if self.weight_t > 0:
losses_t.update(loss_summary['loss_t'], self.targets_sz)
if self.weight_clsm > 0:
losses_clsm.update(loss_summary['loss_clsm'], self.targets_sz)
precisions.update(loss_summary['acc'], self.targets_sz)
if (self.batch_idx + 1) % print_freq == 0:
nb_this_epoch = self.num_batches - (self.batch_idx + 1)
nb_future_epochs = (
self.max_epoch - (self.epoch + 1)
) * self.num_batches
eta_seconds = batch_time.avg * (nb_this_epoch+nb_future_epochs)
eta_str = str(datetime.timedelta(seconds=int(eta_seconds)))
print(
'epoch: [{0}/{1}][{2}/{3}]\t'
'time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'eta {eta}\t'
'{losses}\t'
'lr {lr:.6f}'.format(
self.epoch + 1,
self.max_epoch,
self.batch_idx + 1,
self.num_batches,
batch_time=batch_time,
data_time=data_time,
eta=eta_str,
losses=losses,
lr=self.get_current_lr()
),
end='\r'
)
if self.writer is not None:
n_iter = self.epoch * self.num_batches + self.batch_idx
self.writer.add_scalar('Train/time', batch_time.avg, n_iter)
self.writer.add_scalar('Train/data', data_time.avg, n_iter)
for name, meter in losses.meters.items():
self.writer.add_scalar('Train/' + name, meter.avg, n_iter)
self.writer.add_scalar(
'Train/lr', self.get_current_lr(), n_iter
)
end = time.time()
info_dict['lr'] = list(map(lambda group: group['lr'], self.optimizer.param_groups))
self.update_lr()
# Returing the relevant info in dictionary
if self.weight_t > 0:
info_dict['loss_t_avg'] = losses_t.avg
if self.weight_clsm > 0:
info_dict['loss_clsm_avg'] = losses_clsm.avg
info_dict['prec_avg'] = precisions.avg
return info_dict
def run(
self,
save_dir='log',
max_epoch=0,
start_epoch=0,
print_freq=10, # If print_freq is invalid if print_epoch is set true
print_epoch=False,
fixbase_epoch=0,
open_layers=None,
start_eval=0,
eval_freq=-1,
test_only=False,
dist_metric='euclidean',
train_resume = False,
pre_epochs = 1,
pmax_steps = 2000,
pnum_trials = 10,
acc_thr = 0.6,
enhance_data_aug = False,
method_name = 'QAConv',
sub_method_name = 'res50_layer3',
qbatch_sz = None,
gbatch_sz = None,
normalize_feature=False,
visrank=False,
visrank_topk=10,
use_metric_cuhk03=False,
ranks=[1, 5, 10, 20],
rerank=False
):
r"""A unified pipeline for training and evaluating a model.
Args:
save_dir (str): directory to save model.
max_epoch (int): maximum epoch.
start_epoch (int, optional): starting epoch. Default is 0.
print_freq (int, optional): print_frequency. Default is 10.
fixbase_epoch (int, optional): number of epochs to train ``open_layers`` (new layers)
while keeping base layers frozen. Default is 0. ``fixbase_epoch`` is counted
in ``max_epoch``.
open_layers (str or list, optional): layers (attribute names) open for training.
start_eval (int, optional): from which epoch to start evaluation. Default is 0.
eval_freq (int, optional): evaluation frequency. Default is -1 (meaning evaluation
is only performed at the end of training).
test_only (bool, optional): if True, only runs evaluation on test datasets.
Default is False.
dist_metric (str, optional): distance metric used to compute distance matrix
between query and gallery. Default is "euclidean".
normalize_feature (bool, optional): performs L2 normalization on feature vectors before
computing feature distance. Default is False.
visrank (bool, optional): visualizes ranked results. Default is False. It is recommended to
enable ``visrank`` when ``test_only`` is True. The ranked images will be saved to
"save_dir/visrank_dataset", e.g. "save_dir/visrank_market1501".
visrank_topk (int, optional): top-k ranked images to be visualized. Default is 10.
use_metric_cuhk03 (bool, optional): use single-gallery-shot setting for cuhk03.
Default is False. This should be enabled when using cuhk03 classic split.
ranks (list, optional): cmc ranks to be computed. Default is [1, 5, 10, 20].
rerank (bool, optional): uses person re-ranking (by Zhong et al. CVPR'17).
Default is False. This is only enabled when test_only=True.
"""
self.resume = train_resume
self.pre_epochs = pre_epochs
self.pmax_steps = pmax_steps
self.pnum_trials = pnum_trials
self.acc_thr = acc_thr
self.enhance_data_aug = enhance_data_aug
self.method_name = method_name
self.sub_method_name = sub_method_name
self.qbatch_sz = qbatch_sz
self.gbatch_sz = gbatch_sz
if visrank and not test_only:
raise ValueError(
'visrank can be set to True only if test_only=True'
)
print(".... Running from new engine run defination ... !")
# Building log file and location to save model checkpoint
log_file = osp.join(save_dir, self.method_name, self.sub_method_name, 'pretrain_metric.txt')
sys.stdout = Logger(log_file)
# Pre-training the network for warm-start
self.pretrain(test_only, save_dir) # test_only automatically loads model from checkpoint
self.criterion_clsmloss = nn.DataParallel(self.criterion_clsmloss)
self.model = nn.DataParallel(self.model)
if test_only:
self.test(
dist_metric=dist_metric,
normalize_feature=normalize_feature,
visrank=visrank,
visrank_topk=visrank_topk,
save_dir=save_dir,
use_metric_cuhk03=use_metric_cuhk03,
ranks=ranks,
rerank=rerank
)
return
if self.writer is None:
self.writer = SummaryWriter(log_dir=save_dir)
time_start = time.time()
self.start_epoch = start_epoch
self.max_epoch = max_epoch
print('=> Start training')
for self.epoch in range(self.start_epoch, self.max_epoch):
info_dict = self.train(
print_freq=print_freq,
print_epoch = print_epoch,
fixbase_epoch=fixbase_epoch,
open_layers=open_layers
)
train_time = time.time() - time_start
lr = info_dict['lr']
if print_epoch:
if self.weight_t > 0 and self.weight_clsm > 0:
print(
'* Finished epoch %d at lr=[%g, %g, %g]. Loss_t: %.3f. Loss_clsm: %.3f. Acc: %.2f%%. Training time: %.0f seconds. \n'
% (self.epoch + 1, lr[0], lr[1], lr[2],
info_dict['loss_t_avg'], info_dict['loss_clsm_avg'], info_dict['prec_avg'] * 100, train_time))
elif self.weight_t > 0:
print(
'* Finished epoch %d at lr=[%g, %g, %g]. Loss_t: %.3f. Training time: %.0f seconds. \n'
% (self.epoch + 1, lr[0], lr[1], lr[2], info_dict['loss_t_avg'], train_time))
elif self.weight_clsm > 0:
print(
'* Finished epoch %d at lr=[%g, %g, %g]. Loss_clsm: %.3f. Acc: %.2f%%. Training time: %.0f seconds. \n'
% (self.epoch + 1, lr[0], lr[1], lr[2], info_dict['loss_clsm_avg'], info_dict['prec_avg'] * 100, train_time))
if (self.epoch + 1) >= start_eval \
and eval_freq > 0 \
and (self.epoch+1) % eval_freq == 0 \
and (self.epoch + 1) != self.max_epoch:
rank1 = self.test(
dist_metric=dist_metric,
normalize_feature=normalize_feature,
visrank=visrank,
visrank_topk=visrank_topk,
save_dir=save_dir,
use_metric_cuhk03=use_metric_cuhk03,
ranks=ranks
)
self.save_model(self.epoch, rank1, save_dir)
# Modify transforms and re-initilize train dataloader
if not self.enhance_data_aug and self.epoch < self.max_epoch - 1:
if 'prec_avg' not in info_dict.keys():
self.enhance_data_aug = True
print('Start to Flip and Block only for triplet loss')
self.datamanager.QAConv_train_loader()
elif info_dict['prec_avg'] > self.acc_thr:
self.enhance_data_aug = True
print('\nAcc = %.2f%% > %.2f%%. Start to Flip and Block.\n' % (info_dict['prec_avg']* 100, self.acc_thr *100))
self.datamanager.QAConv_train_loader()
if self.max_epoch > 0:
print('=> Final test')
rank1 = self.test(
dist_metric=dist_metric,
normalize_feature=normalize_feature,
visrank=visrank,
visrank_topk=visrank_topk,
save_dir=save_dir,
use_metric_cuhk03=use_metric_cuhk03,
ranks=ranks
)
self.save_model(self.epoch, rank1, save_dir)
elapsed = round(time.time() - time_start)
elapsed = str(datetime.timedelta(seconds=elapsed))
print('Elapsed {}'.format(elapsed))
if self.writer is not None:
self.writer.close()
# Defining evaluation mechanism
@torch.no_grad()
def _evaluate(
self,
dataset_name='',
query_loader=None,
gallery_loader=None,
dist_metric='euclidean',
normalize_feature=False,
visrank=False,
visrank_topk=10,
save_dir='',
use_metric_cuhk03=False,
ranks=[1, 5, 10, 20],
rerank=False,
):
batch_time = AverageMeter()
def _feature_extraction(data_loader):
f_, pids_, camids_ = [], [], []
for batch_idx, data in enumerate(data_loader):
imgs, pids, camids = self.parse_data_for_eval(data)
if self.use_gpu:
imgs = imgs.cuda()
end = time.time()
features = self.extract_features(imgs)
batch_time.update(time.time() - end)
features = features.data.cpu()
f_.append(features)
pids_.extend(pids)
camids_.extend(camids)
f_ = torch.cat(f_, 0)
pids_ = np.asarray(pids_)
camids_ = np.asarray(camids_)
return f_, pids_, camids_
print('Extracting features from query set ...')
qf, q_pids, q_camids = _feature_extraction(query_loader)
print('Done, obtained {}-by-{} matrix'.format(qf.size(0), qf.size(1)))
print('Extracting features from gallery set ...')
gf, g_pids, g_camids = _feature_extraction(gallery_loader)
print('Done, obtained {}-by-{} matrix'.format(gf.size(0), gf.size(1)))
print('Speed: {:.4f} sec/batch'.format(batch_time.avg))
if normalize_feature:
print('Normalzing features with L2 norm ...')
qf = F.normalize(qf, p=2, dim=1)
gf = F.normalize(gf, p=2, dim=1)
print(
'Computing distance matrix is with metric={} ...'.format('QAConv_kernel')
)
distmat = metrics.pairwise_distance_using_QAmatcher(
self.matcher, qf, gf,
prob_batch_size = self.qbatch_sz,
gal_batch_size = self.gbatch_sz)
distmat = distmat.numpy()
if rerank:
print('Applying person re-ranking ...')
distmat_qq = metrics.pairwise_distance_using_QAmatcher(
self.matcher, qf, qf,
prob_batch_size = self.qbatch_sz,
gal_batch_size = self.qbatch_sz)
distmat_gg = metrics.pairwise_distance_using_QAmatcher(
self.matcher, gf, gf,
prob_batch_size = self.gbatch_sz,
gal_batch_size = self.gbatch_sz)
distmat = re_ranking(distmat, distmat_qq, distmat_gg)
print('Computing CMC and mAP ...')
cmc, mAP = metrics.evaluate_rank(
distmat,
q_pids,
g_pids,
q_camids,
g_camids,
use_metric_cuhk03=use_metric_cuhk03
)
print('** Results **')
print('mAP: {:.1%}'.format(mAP))
print('CMC curve')
for r in ranks:
print('Rank-{:<3}: {:.1%}'.format(r, cmc[r - 1]))
if visrank:
visualize_ranked_results(
distmat,
self.datamanager.fetch_test_loaders(dataset_name),
self.datamanager.data_type,
width=self.datamanager.width,
height=self.datamanager.height,
save_dir=osp.join(save_dir, 'visrank_' + dataset_name),
topk=visrank_topk
)
return cmc[0], mAP
def forward_backward(self, data):
imgs, pids, camids, dsetids = self.parse_data_for_train_DG(data)
if self.use_gpu:
imgs = imgs.cuda()
pids = pids.cuda()
self.targets_sz = pids.size(0)
features = self.model(imgs)
loss = 0
loss_summary = {}
# print("Algorithm is at epoch : {}".format(self.epoch))
if self.weight_t > 0:
loss_t = self.compute_loss(self.criterion_t, features, pids)
loss += self.weight_t * loss_t
loss_summary['loss_t'] = loss_t.item()
if self.weight_clsm > 0:
loss_clsm, acc = self.compute_loss(self.criterion_clsmloss, features, pids)
loss += self.weight_clsm * loss_clsm
loss_summary['loss_clsm'] = loss_clsm.item()
loss_summary['acc'] = acc.item() #metrics.accuracy(outputs, pids)[0].item()
assert loss_summary
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
return loss_summary
| 40.32491 | 159 | 0.555237 | 21,627 | 0.968084 | 0 | 0 | 3,640 | 0.162936 | 0 | 0 | 6,580 | 0.294539 |
fd8c2c7eeb82fbf804fe620863dfe2ae2700ad4d | 337 | py | Python | setup.py | xoolive/cartotools | 2d6217fde9dadcdb860603cd4b33814b99ae451e | [
"MIT"
]
| 3 | 2018-01-09T10:53:24.000Z | 2020-06-04T16:04:52.000Z | setup.py | xoolive/cartotools | 2d6217fde9dadcdb860603cd4b33814b99ae451e | [
"MIT"
]
| 1 | 2018-12-16T13:49:06.000Z | 2019-02-19T20:23:19.000Z | setup.py | xoolive/cartotools | 2d6217fde9dadcdb860603cd4b33814b99ae451e | [
"MIT"
]
| 1 | 2018-01-09T11:00:39.000Z | 2018-01-09T11:00:39.000Z | from setuptools import setup
setup(
name="cartotools",
version="1.2.1",
description="Making cartopy suit my needs",
license="MIT",
packages=[
"cartotools",
"cartotools.crs",
"cartotools.img_tiles",
"cartotools.osm",
],
author="Xavier Olive",
install_requires=['pandas']
)
| 19.823529 | 47 | 0.596439 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 142 | 0.421365 |
fd8d82fd51795634599d592a12414f82293ec386 | 2,623 | py | Python | api/app/tests/weather_models/endpoints/test_models_endpoints.py | bcgov/wps | 71df0de72de9cd656dc9ebf8461ffe47cfb155f6 | [
"Apache-2.0"
]
| 19 | 2020-01-31T21:51:31.000Z | 2022-01-07T14:40:03.000Z | api/app/tests/weather_models/endpoints/test_models_endpoints.py | bcgov/wps | 71df0de72de9cd656dc9ebf8461ffe47cfb155f6 | [
"Apache-2.0"
]
| 1,680 | 2020-01-24T23:25:08.000Z | 2022-03-31T23:50:27.000Z | api/app/tests/weather_models/endpoints/test_models_endpoints.py | bcgov/wps | 71df0de72de9cd656dc9ebf8461ffe47cfb155f6 | [
"Apache-2.0"
]
| 6 | 2020-04-28T22:41:08.000Z | 2021-05-05T18:16:06.000Z | """ Functional testing for /models/* endpoints.
"""
import os
import json
import importlib
import logging
import pytest
from pytest_bdd import scenario, given, then, when
from fastapi.testclient import TestClient
import app.main
from app.tests import load_sqlalchemy_response_from_json
from app.tests import load_json_file
logger = logging.getLogger(__name__)
@pytest.mark.usefixtures("mock_jwt_decode")
@scenario("test_models_endpoints.feature", "Generic model endpoint testing",
example_converters=dict(
codes=json.loads, endpoint=str, crud_mapping=load_json_file(__file__), expected_status_code=int,
expected_response=load_json_file(__file__), notes=str))
def test_model_predictions_summaries_scenario():
""" BDD Scenario for prediction summaries """
def _patch_function(monkeypatch, module_name: str, function_name: str, json_filename: str):
""" Patch module_name.function_name to return de-serialized json_filename """
def mock_get_data(*_):
dirname = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(dirname, json_filename)
return load_sqlalchemy_response_from_json(filename)
monkeypatch.setattr(importlib.import_module(module_name), function_name, mock_get_data)
@given("some explanatory <notes>")
def given_some_notes(notes: str):
""" Send notes to the logger. """
logger.info(notes)
@given("A <crud_mapping>", target_fixture='database')
def given_a_database(monkeypatch, crud_mapping: dict):
""" Mock the sql response """
for item in crud_mapping:
_patch_function(monkeypatch, item['module'], item['function'], item['json'])
return {}
@when("I call <endpoint> with <codes>")
def when_prediction(database: dict, codes: str, endpoint: str):
""" Make call to endpoint """
client = TestClient(app.main.app)
response = client.post(
endpoint, headers={'Authorization': 'Bearer token'}, json={'stations': codes})
if response.status_code == 200:
database['response_json'] = response.json()
database['status_code'] = response.status_code
@then('The <expected_status_code> is matched')
def assert_status_code(database: dict, expected_status_code: str):
""" Assert that the status code is as expected
"""
assert database['status_code'] == int(expected_status_code)
@then('The <expected_response> is matched')
def assert_response(database: dict, expected_response: dict):
""" "Catch all" test that blindly checks the actual json response against an expected response. """
assert database['response_json'] == expected_response
| 34.973333 | 110 | 0.733511 | 0 | 0 | 0 | 0 | 1,769 | 0.674419 | 0 | 0 | 777 | 0.296226 |
fd8e56403a239049d047cb2ae7cdbf57d5c4d0b6 | 3,144 | py | Python | CLE/Module_DeploymentMonitoring/urls.py | CherBoon/Cloudtopus | 41e4b3743d8f5f988373d14937a1ed8dbdf92afb | [
"MIT"
]
| 3 | 2019-03-04T02:55:25.000Z | 2021-02-13T09:00:52.000Z | CLE/Module_DeploymentMonitoring/urls.py | MartinTeo/Cloudtopus | ebcc57cdf10ca2b73343f03abb33a12ab9c6edef | [
"MIT"
]
| 6 | 2019-02-28T08:54:25.000Z | 2022-03-02T14:57:04.000Z | CLE/Module_DeploymentMonitoring/urls.py | MartinTeo/Cloudtopus | ebcc57cdf10ca2b73343f03abb33a12ab9c6edef | [
"MIT"
]
| 2 | 2019-02-28T08:52:15.000Z | 2019-09-24T18:32:01.000Z | from django.contrib import admin
from Module_DeploymentMonitoring import views
from django.urls import path,re_path
urlpatterns = [
path('instructor/ITOperationsLab/setup/awskeys/',views.faculty_Setup_GetAWSKeys,name='itopslab_setup_AWSKeys'),
path('instructor/ITOperationsLab/monitor/',views.faculty_Monitor_Base,name='itopslab_monitor'),
path('student/ITOperationsLab/deploy/',views.student_Deploy_Base,name='itopslab_studeploy'),
path('student/ITOperationsLab/deploy/<str:course_title>/2',views.student_Deploy_Upload,name='itopslab_studeployUpload'),
path('student/ITOperationsLab/monitor/',views.student_Monitor_Base,name='itopslab_stumonitor'),
# For adding deployment packages into system
path('instructor/ITOperationsLab/setup/deployment_package/',views.faculty_Setup_GetGitHubLinks,name='dp_list'),
path('instructor/ITOperationsLab/setup/deployment_package/create/', views.faculty_Setup_AddGitHubLinks, name='dp_create'),
path('instructor/ITOperationsLab/setup/deployment_package/<str:course_title>/<str:pk>/update/', views.faculty_Setup_UpdateGitHubLinks, name='dp_update'),
path('instructor/ITOperationsLab/setup/deployment_package/<str:course_title>/<str:pk>/delete/', views.faculty_Setup_DeleteGitHubLinks, name='dp_delete'),
path('instructor/ITOperationsLab/setup/deployment_package/<str:course_title>/delete/all/', views.faculty_Setup_DeleteAllGitHubLinks, name='dp_delete_all'),
# For retrieving and sharing of AMI
path('instructor/ITOperationsLab/setup/',views.faculty_Setup_Base,name='itopslab_setup'),
path('instructor/ITOperationsLab/setup/ami/get/',views.faculty_Setup_GetAMI,name='itopslab_setup_AMI_get'),
path('instructor/ITOperationsLab/setup/ami/accounts/get/',views.faculty_Setup_GetAMIAccounts,name='itopslab_setup_AMI_Accounts_get'),
path('instructor/ITOperationsLab/setup/ami/accounts/share/',views.faculty_Setup_ShareAMI,name='itopslab_setup_AMI_Accounts_share'),
# For standard student deployment page
path('student/ITOperationsLab/deploy/standard/',views.student_Deploy_Standard_Base,name='itopslab_studeploy_standard'),
path('student/ITOperationsLab/deploy/standard/deployment_package/',views.student_Deploy_Standard_GetDeploymentPackages,name='dp_list_student'),
path('student/ITOperationsLab/deploy/standard/account/',views.student_Deploy_Standard_AddAccount,name='itopslab_studeploy_standard_AddAccount'),
path('student/ITOperationsLab/deploy/standard/server/',views.student_Deploy_Standard_GetIPs,name='server_list'),
path('student/ITOperationsLab/deploy/standard/server/create/',views.student_Deploy_Standard_AddIPs,name='server_create'),
path('student/ITOperationsLab/deploy/standard/server/<str:course_title>/<str:pk>/update/',views.student_Deploy_Standard_UpdateIPs,name='server_update'),
path('student/ITOperationsLab/deploy/standard/server/<str:course_title>/<str:pk>/delete/',views.student_Deploy_Standard_DeleteIPs,name='server_delete'),
path('student/ITOperationsLab/deploy/standard/server/<str:course_title>/delete/all/',views.student_Deploy_Standard_DeleteAllIPs,name='server_delete_all'),
]
| 89.828571 | 159 | 0.818702 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,820 | 0.57888 |
fd8eaa1dd13d7842905f05439abe0c727ac76666 | 2,918 | py | Python | 30-Days-of-Python-master/practice_day_9/alpha_day_9/akash_prank.py | vimm0/python_exercise | 7773d95b4c25b82a9d014f7a814ac83df9ebac17 | [
"MIT"
]
| null | null | null | 30-Days-of-Python-master/practice_day_9/alpha_day_9/akash_prank.py | vimm0/python_exercise | 7773d95b4c25b82a9d014f7a814ac83df9ebac17 | [
"MIT"
]
| null | null | null | 30-Days-of-Python-master/practice_day_9/alpha_day_9/akash_prank.py | vimm0/python_exercise | 7773d95b4c25b82a9d014f7a814ac83df9ebac17 | [
"MIT"
]
| 1 | 2018-01-04T16:27:31.000Z | 2018-01-04T16:27:31.000Z | class Akash():
msg="""
Seems like you are in trouble now. I can feel that...hahaaa
Your name:Akash
Address:Nepalgunj
"""
another="""
I am not really good friend of yours becauase i am going transfer some viruses from the internet.\n
I Know everythings about you??:P.....Press Enter extract virus
"""
last_message = """
#
##
###
####
#####
#######
#######
########
########
#########
##########
############
##############
################
################ #
############## ### Installing viruses....
############## #### GoodByee...!!
############## ##### Computer will turn off in one minute
############## #######
############## ###########
############### #############
################ ##############
################# # ################
################## ## # #################
#################### ### ## #################
################ ######## #################
################ ####### ###################
####################### #####################
##################### ###################
############################################
###########################################
##########################################
########################################
########################################
######################################
######################################
########################## #####
### ################### ##
## ###############
# ## ##########
## ###
###
Ghost Computer ##
Arch Linux #
sudo:vimm0 """
def question_answer(self):
var2=[]
var1 = input("Hello, dear what is your name?: ")
print("Ohh!! {var1} is nice name to have. ".format(var1=var1))
var2 = input(
"Do you want to install virus?")
print(self.msg)
print(self.another)
print(self.last_message)
if __name__=="__main__":
obj=Akash()
obj.question_answer()
| 35.156627 | 119 | 0.186429 | 2,853 | 0.977724 | 0 | 0 | 0 | 0 | 0 | 0 | 2,611 | 0.894791 |
fd93406451b3b5dc2f87a2b2dbd3aa123abc1eb6 | 1,312 | py | Python | mainapp/models/user_alert.py | cyroxx/meine-stadt-transparent | d5a3f03a29a1bb97ce50ac5257d8bbd5208d9218 | [
"MIT"
]
| 34 | 2017-10-04T14:20:41.000Z | 2022-03-11T18:06:48.000Z | mainapp/models/user_alert.py | cyroxx/meine-stadt-transparent | d5a3f03a29a1bb97ce50ac5257d8bbd5208d9218 | [
"MIT"
]
| 588 | 2017-10-14T18:31:17.000Z | 2022-03-16T13:00:30.000Z | mainapp/models/user_alert.py | codeformuenster/meine-stadt-transparent | 1458bc6acad40183908e2b7cc98ef92165d1123a | [
"MIT"
]
| 11 | 2017-11-27T10:12:59.000Z | 2022-02-09T10:27:11.000Z | from django.contrib.auth.models import User
from django.db import models
from mainapp.functions.search import params_to_search_string, search_string_to_params
from mainapp.functions.search_notification_tools import (
params_to_human_string,
params_are_equal,
)
class UserAlert(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
search_string = models.TextField(null=False, blank=False)
created = models.DateTimeField(auto_now_add=True)
last_match = models.DateTimeField(null=True)
def get_search_params(self):
return search_string_to_params(self.search_string)
def set_search_params(self, params: dict):
self.search_string = params_to_search_string(params)
def __str__(self):
return params_to_human_string(self.get_search_params())
@classmethod
def find_user_alert(cls, user, search_params):
alerts = UserAlert.objects.filter(user=user).all()
for alert in alerts:
if params_are_equal(search_params, alert.get_search_params()):
return alert
return None
@classmethod
def user_has_alert(cls, user, search_params):
found = UserAlert.find_user_alert(user, search_params)
if found:
return True
else:
return False
| 32 | 85 | 0.717988 | 1,039 | 0.791921 | 0 | 0 | 481 | 0.366616 | 0 | 0 | 0 | 0 |
fd944074d8e83c269f766de8fed07825db678f3d | 8,123 | py | Python | COT/helpers/tests/test_fatdisk.py | morneaup/cot | 3d4dc7079a33aa0c09216ec339b44f84ab69ff4b | [
"MIT"
]
| 81 | 2015-01-18T22:31:42.000Z | 2022-03-14T12:34:33.000Z | COT/helpers/tests/test_fatdisk.py | morneaup/cot | 3d4dc7079a33aa0c09216ec339b44f84ab69ff4b | [
"MIT"
]
| 67 | 2015-01-05T15:24:39.000Z | 2021-08-16T12:44:58.000Z | COT/helpers/tests/test_fatdisk.py | morneaup/cot | 3d4dc7079a33aa0c09216ec339b44f84ab69ff4b | [
"MIT"
]
| 20 | 2015-07-09T14:20:25.000Z | 2021-09-18T17:59:57.000Z | #!/usr/bin/env python
#
# fatdisk.py - Unit test cases for COT.helpers.fatdisk submodule.
#
# March 2015, Glenn F. Matthews
# Copyright (c) 2014-2017 the COT project developers.
# See the COPYRIGHT.txt file at the top-level directory of this distribution
# and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt.
#
# This file is part of the Common OVF Tool (COT) project.
# It is subject to the license terms in the LICENSE.txt file found in the
# top-level directory of this distribution and at
# https://github.com/glennmatthews/cot/blob/master/LICENSE.txt. No part
# of COT, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE.txt file.
"""Unit test cases for the COT.helpers.fatdisk module."""
import os
import re
from distutils.version import StrictVersion
import mock
from COT.helpers.tests.test_helper import HelperTestCase
from COT.helpers.fatdisk import FatDisk
from COT.helpers import helpers
# pylint: disable=missing-type-doc,missing-param-doc,protected-access
@mock.patch('COT.helpers.fatdisk.FatDisk.download_and_expand_tgz',
side_effect=HelperTestCase.stub_download_and_expand_tgz)
class TestFatDisk(HelperTestCase):
"""Test cases for FatDisk helper class."""
def setUp(self):
"""Test case setup function called automatically prior to each test."""
self.helper = FatDisk()
self.maxDiff = None
super(TestFatDisk, self).setUp()
@mock.patch('COT.helpers.helper.check_output',
return_value="fatdisk, version 1.0.0-beta")
def test_get_version(self, *_):
"""Validate .version getter."""
self.helper._installed = True
self.assertEqual(StrictVersion("1.0.0"), self.helper.version)
@mock.patch('COT.helpers.helper.check_output')
@mock.patch('subprocess.check_call')
def test_install_already_present(self,
mock_check_call,
mock_check_output,
*_):
"""Trying to re-install is a no-op."""
self.helper._installed = True
self.helper.install()
mock_check_output.assert_not_called()
mock_check_call.assert_not_called()
@mock.patch('platform.system', return_value='Linux')
@mock.patch('os.path.isdir', return_value=False)
@mock.patch('os.path.exists', return_value=False)
@mock.patch('os.makedirs', side_effect=OSError)
@mock.patch('distutils.spawn.find_executable', return_value="/foo")
@mock.patch('shutil.copy', return_value=True)
@mock.patch('COT.helpers.helper.check_output', return_value="")
@mock.patch('subprocess.check_call')
def test_install_apt_get(self,
mock_check_call,
mock_check_output,
mock_copy,
*_):
"""Test installation via 'apt-get'."""
self.enable_apt_install()
helpers['dpkg']._installed = True
for name in ['make', 'clang', 'gcc', 'g++']:
helpers[name]._installed = False
self.helper.install()
self.assertSubprocessCalls(
mock_check_output,
[
['dpkg', '-s', 'make'],
['dpkg', '-s', 'gcc'],
])
self.assertSubprocessCalls(
mock_check_call,
[
['apt-get', '-q', 'update'],
['apt-get', '-q', 'install', 'make'],
['apt-get', '-q', 'install', 'gcc'],
['./RUNME'],
['sudo', 'mkdir', '-p', '-m', '755', '/usr/local/bin'],
])
self.assertTrue(re.search("/fatdisk$", mock_copy.call_args[0][0]))
self.assertEqual('/usr/local/bin', mock_copy.call_args[0][1])
self.assertAptUpdated()
# Make sure we don't call apt-get update/install again unnecessarily.
mock_check_output.reset_mock()
mock_check_call.reset_mock()
mock_check_output.return_value = 'install ok installed'
# fakeout!
helpers['make']._installed = False
self.helper._installed = False
os.environ['PREFIX'] = '/opt/local'
os.environ['DESTDIR'] = '/home/cot'
self.helper.install()
self.assertSubprocessCalls(
mock_check_output,
[
['dpkg', '-s', 'make'],
])
self.assertSubprocessCalls(
mock_check_call,
[
['./RUNME'],
['sudo', 'mkdir', '-p', '-m', '755',
'/home/cot/opt/local/bin'],
])
self.assertTrue(re.search("/fatdisk$", mock_copy.call_args[0][0]))
self.assertEqual('/home/cot/opt/local/bin', mock_copy.call_args[0][1])
def test_install_brew(self, *_):
"""Test installation via 'brew'."""
self.brew_install_test(['glennmatthews/fatdisk/fatdisk', '--devel'])
def test_install_port(self, *_):
"""Test installation via 'port'."""
self.port_install_test('fatdisk')
@mock.patch('platform.system', return_value='Linux')
@mock.patch('os.path.isdir', return_value=False)
@mock.patch('os.path.exists', return_value=False)
@mock.patch('os.makedirs', side_effect=OSError)
@mock.patch('distutils.spawn.find_executable', return_value='/foo')
@mock.patch('shutil.copy', return_value=True)
@mock.patch('subprocess.check_call')
def test_install_yum(self,
mock_check_call,
mock_copy,
*_):
"""Test installation via 'yum'."""
self.enable_yum_install()
for name in ['make', 'clang', 'gcc', 'g++']:
helpers[name]._installed = False
self.helper.install()
self.assertSubprocessCalls(
mock_check_call,
[
['yum', '--quiet', 'install', 'make'],
['yum', '--quiet', 'install', 'gcc'],
['./RUNME'],
['sudo', 'mkdir', '-p', '-m', '755', '/usr/local/bin'],
])
self.assertTrue(re.search("/fatdisk$", mock_copy.call_args[0][0]))
self.assertEqual('/usr/local/bin', mock_copy.call_args[0][1])
@mock.patch('platform.system', return_value='Linux')
@mock.patch('distutils.spawn.find_executable', return_value=None)
def test_install_linux_need_make_no_package_manager(self, *_):
"""Linux installation requires yum or apt-get if 'make' missing."""
self.select_package_manager(None)
for name in ['make', 'clang', 'gcc', 'g++']:
helpers[name]._installed = False
with self.assertRaises(NotImplementedError):
self.helper.install()
@staticmethod
def _find_make_only(name):
"""Stub for distutils.spawn.find_executable - only finds 'make'."""
if name == 'make':
return "/bin/make"
else:
return None
@mock.patch('platform.system', return_value='Linux')
@mock.patch('COT.helpers.helper.Helper')
@mock.patch('distutils.spawn.find_executable')
def test_install_linux_need_compiler_no_package_manager(self,
mock_find_exec,
*_):
"""Linux installation requires yum or apt-get if 'gcc' missing."""
self.select_package_manager(None)
for name in ['clang', 'gcc', 'g++']:
helpers[name]._installed = False
mock_find_exec.side_effect = self._find_make_only
with self.assertRaises(NotImplementedError):
self.helper.install()
@mock.patch('platform.system', return_value='Darwin')
@mock.patch('COT.helpers.fatdisk.FatDisk.installable',
new_callable=mock.PropertyMock, return_value=True)
def test_install_helper_mac_no_package_manager(self, *_):
"""Mac installation requires port."""
self.select_package_manager(None)
self.assertRaises(RuntimeError, self.helper.install)
| 40.014778 | 79 | 0.596331 | 6,912 | 0.850917 | 0 | 0 | 7,048 | 0.86766 | 0 | 0 | 2,849 | 0.350732 |
fd969867a45418ad24a3e7bb303872fc31aae097 | 541 | py | Python | scripts/set_left_arm2static_pose.py | birlrobotics/birl_kitting_experiment | 75cf42b6fd187b12e99b0e916c73058f429a556c | [
"BSD-3-Clause"
]
| 2 | 2019-06-03T03:33:50.000Z | 2019-12-30T05:43:34.000Z | scripts/set_left_arm2static_pose.py | birlrobotics/birl_kitting_experiment | 75cf42b6fd187b12e99b0e916c73058f429a556c | [
"BSD-3-Clause"
]
| null | null | null | scripts/set_left_arm2static_pose.py | birlrobotics/birl_kitting_experiment | 75cf42b6fd187b12e99b0e916c73058f429a556c | [
"BSD-3-Clause"
]
| 1 | 2019-12-30T05:43:35.000Z | 2019-12-30T05:43:35.000Z | #!/usr/bin/env python
import baxter_interface
import rospy
if __name__ == '__main__':
rospy.init_node("set_left_arm_py")
names = ['left_e0', 'left_e1', 'left_s0', 'left_s1', 'left_w0', 'left_w1', 'left_w2']
joints = [-0.8022719520640714, 1.7184419776286348, 0.21399031991001521, 0.324436936637765, 2.5862916083748075, -0.5825292041994858, -0.3566505331833587]
combined = zip(names, joints)
command = dict(combined)
left = baxter_interface.Limb('left')
left.move_to_joint_positions(command)
print "Done"
| 28.473684 | 156 | 0.713494 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 123 | 0.227357 |
fd97704e53ec2a3a2b53ad0c5d0eef703c39868d | 4,414 | py | Python | python/SessionCallbackPLSQL.py | synetcom/oracle-db-examples | e995ca265b93c0d6b7da9ad617994288b3a19a2c | [
"Apache-2.0"
]
| 4 | 2019-10-26T06:21:32.000Z | 2021-02-15T15:28:02.000Z | python/SessionCallbackPLSQL.py | synetcom/oracle-db-examples | e995ca265b93c0d6b7da9ad617994288b3a19a2c | [
"Apache-2.0"
]
| null | null | null | python/SessionCallbackPLSQL.py | synetcom/oracle-db-examples | e995ca265b93c0d6b7da9ad617994288b3a19a2c | [
"Apache-2.0"
]
| 5 | 2019-10-26T06:21:31.000Z | 2022-03-10T12:47:13.000Z | #------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# SessionCallbackPLSQL.py
#
# Demonstrate how to use a session callback written in PL/SQL. The callback is
# invoked whenever the tag requested by the application does not match the tag
# associated with the session in the pool. It should be used to set session
# state, so that the application can count on known session state, which allows
# the application to reduce the number of round trips to the database.
#
# The primary advantage to this approach over the equivalent approach shown in
# SessionCallback.py is when DRCP is used, as the callback is invoked on the
# server and no round trip is required to set state.
#
# This script requires cx_Oracle 7.1 and higher.
#------------------------------------------------------------------------------
from __future__ import print_function
import cx_Oracle
import SampleEnv
# create pool with session callback defined
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2,
max=5, increment=1, threaded=True,
sessionCallback="pkg_SessionCallback.TheCallback")
# truncate table logging calls to PL/SQL session callback
conn = pool.acquire()
cursor = conn.cursor()
cursor.execute("truncate table PLSQLSessionCallbacks")
conn.close()
# acquire session without specifying a tag; the callback will not be invoked as
# a result and no session state will be changed
print("(1) acquire session without tag")
conn = pool.acquire()
cursor = conn.cursor()
cursor.execute("select to_char(current_date) from dual")
result, = cursor.fetchone()
print("main(): result is", repr(result))
conn.close()
# acquire session, specifying a tag; since the session returned has no tag,
# the callback will be invoked; session state will be changed and the tag will
# be saved when the connection is closed
print("(2) acquire session with tag")
conn = pool.acquire(tag="NLS_DATE_FORMAT=SIMPLE")
cursor = conn.cursor()
cursor.execute("select to_char(current_date) from dual")
result, = cursor.fetchone()
print("main(): result is", repr(result))
conn.close()
# acquire session, specifying the same tag; since a session exists in the pool
# with this tag, it will be returned and the callback will not be invoked but
# the connection will still have the session state defined previously
print("(3) acquire session with same tag")
conn = pool.acquire(tag="NLS_DATE_FORMAT=SIMPLE")
cursor = conn.cursor()
cursor.execute("select to_char(current_date) from dual")
result, = cursor.fetchone()
print("main(): result is", repr(result))
conn.close()
# acquire session, specifying a different tag; since no session exists in the
# pool with this tag, a new session will be returned and the callback will be
# invoked; session state will be changed and the tag will be saved when the
# connection is closed
print("(4) acquire session with different tag")
conn = pool.acquire(tag="NLS_DATE_FORMAT=FULL;TIME_ZONE=UTC")
cursor = conn.cursor()
cursor.execute("select to_char(current_date) from dual")
result, = cursor.fetchone()
print("main(): result is", repr(result))
conn.close()
# acquire session, specifying a different tag but also specifying that a
# session with any tag can be acquired from the pool; a session with one of the
# previously set tags will be returned and the callback will be invoked;
# session state will be changed and the tag will be saved when the connection
# is closed
print("(4) acquire session with different tag but match any also specified")
conn = pool.acquire(tag="NLS_DATE_FORMAT=FULL;TIME_ZONE=MST", matchanytag=True)
cursor = conn.cursor()
cursor.execute("select to_char(current_date) from dual")
result, = cursor.fetchone()
print("main(): result is", repr(result))
conn.close()
# acquire session and display results from PL/SQL session logs
conn = pool.acquire()
cursor = conn.cursor()
cursor.execute("""
select RequestedTag, ActualTag
from PLSQLSessionCallbacks
order by FixupTimestamp""")
print("(5) PL/SQL session callbacks")
for requestedTag, actualTag in cursor:
print("Requested:", requestedTag, "Actual:", actualTag)
| 41.641509 | 79 | 0.705709 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,173 | 0.718849 |
fd9b3eca720cfbb505d3feb4ca4a2f19b87529e1 | 536 | py | Python | mbrl/env/wrappers/gym_jump_wrapper.py | MaxSobolMark/mbrl-lib | bc8ccfe8a56b58d3ce5bae2c4ccdadd82ecdb594 | [
"MIT"
]
| null | null | null | mbrl/env/wrappers/gym_jump_wrapper.py | MaxSobolMark/mbrl-lib | bc8ccfe8a56b58d3ce5bae2c4ccdadd82ecdb594 | [
"MIT"
]
| null | null | null | mbrl/env/wrappers/gym_jump_wrapper.py | MaxSobolMark/mbrl-lib | bc8ccfe8a56b58d3ce5bae2c4ccdadd82ecdb594 | [
"MIT"
]
| null | null | null | """Reward wrapper that gives rewards for positive change in z axis.
Based on MOPO: https://arxiv.org/abs/2005.13239"""
from gym import Wrapper
class JumpWrapper(Wrapper):
def __init__(self, env):
super(JumpWrapper, self).__init__(env)
self._z_init = self.env.sim.data.qpos[1]
def step(self, action):
observation, reward, done, info = self.env.step(action)
z = self.env.sim.data.qpos[1]
reward = reward + 15 * max(z - self._z_init, 0)
return observation, reward, done, info
| 31.529412 | 67 | 0.654851 | 386 | 0.720149 | 0 | 0 | 0 | 0 | 0 | 0 | 121 | 0.225746 |
fd9b964182281e0d8725c664433f2162b4f057ea | 2,102 | py | Python | img.py | svh2811/Advanced-Lane-Finding | f451f26ef126efcbef711e8c4a14d28d24b08262 | [
"MIT"
]
| null | null | null | img.py | svh2811/Advanced-Lane-Finding | f451f26ef126efcbef711e8c4a14d28d24b08262 | [
"MIT"
]
| null | null | null | img.py | svh2811/Advanced-Lane-Finding | f451f26ef126efcbef711e8c4a14d28d24b08262 | [
"MIT"
]
| null | null | null | import matplotlib.pyplot as plt
import numpy as np
import cv2
from thresholding import *
# list of lists
def plot_images_along_row(images):
fig = plt.figure()
rows = len(images)
cols = len(images[0])
i = 0
for row in range(rows):
for col in range(cols):
a = fig.add_subplot(rows, cols, i+1)
if (len(images[row][col][1].shape) == 2):
imgplot = plt.imshow(images[row][col][1], cmap='gray')
else:
imgplot = plt.imshow(images[row][col][1])
a.set_title(images[row][col][0])
i += 1
plt.show()
plt.close()
img = cv2.imread("challenge_video_frames/02.jpg")
#"""
colorspace1 = cv2.cvtColor(img, cv2.COLOR_BGR2Luv)
channels1 = [
("L", colorspace1[:, :, 0]),
("u", colorspace1[:, :, 1]),
("v", colorspace1[:, :, 2])
]
#"""
"""
colorspace2 = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)
channels2 = [
("L", colorspace2[:, :, 0]),
("a", colorspace2[:, :, 1]),
("b", colorspace2[:, :, 2])
]
colorspace3 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
channels3 = [
("H", colorspace3[:, :, 0]),
("S", colorspace3[:, :, 1]),
("V", colorspace3[:, :, 2])
]
colorspace4 = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
channels4 = [
("H", colorspace4[:, :, 0]),
("L", colorspace4[:, :, 1]),
("S", colorspace4[:, :, 2])
]
"""
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gradx = gradient_thresh(rgb_img, orient="x", sobel_kernel=7, thresh=(8, 16))
grady = gradient_thresh(rgb_img, orient="y", sobel_kernel=3, thresh=(20, 100))
sobel_grads = [
("gray", cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)),
("gX", gradx),
("gY", grady)
]
mag_thresh_img = mag_thresh(rgb_img, sobel_kernel=3, mag_thresh=(20, 200))
mean_gX = cv2.medianBlur(gradx, 5)
dir_thresh_img = dir_threshold(rgb_img, sobel_kernel=3, thresh=(np.pi/2, 2*np.pi/3))
others = [
("Og Img", rgb_img),
("mag", mag_thresh_img),
("mean_gx", mean_gX)
]
plot_images_along_row([others, channels1, sobel_grads])
#plot_images_along_row([channels1, channels2, channels3, channels4])
| 22.602151 | 84 | 0.597526 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 688 | 0.327307 |
fd9c0ebbfa6af60ce30b95d414b6de4fd9d68823 | 479 | py | Python | api/utils/signal_hup.py | AutoCoinDCF/NEW_API | f4abc48fff907a0785372b941afcd67e62eec825 | [
"Apache-2.0"
]
| null | null | null | api/utils/signal_hup.py | AutoCoinDCF/NEW_API | f4abc48fff907a0785372b941afcd67e62eec825 | [
"Apache-2.0"
]
| null | null | null | api/utils/signal_hup.py | AutoCoinDCF/NEW_API | f4abc48fff907a0785372b941afcd67e62eec825 | [
"Apache-2.0"
]
| null | null | null | import signal
import ConfigParser
def get_config():
conf = ConfigParser.ConfigParser()
conf.read("config.cfg")
name = conf.get("test", "name")
print(name)
def update_config(signum, frame):
print("update config")
get_config()
def ctrl_c(signum, frame):
print("input ctrl c")
exit(1)
# 捕获HUP
signal.signal(signal.SIGHUP, update_config)
# 捕获ctrl+c
signal.signal(signal.SIGINT, ctrl_c)
print("test signal")
get_config()
while True:
pass
| 14.96875 | 43 | 0.682672 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 91 | 0.186858 |
fd9c7ab39a034416b3b55dc333af7b177eebd1ee | 5,602 | py | Python | disease_predictor_backend/disease_prediction.py | waizshahid/Disease-Predictor | 2bf2e69631ddbf7ffce0b6c39adcb6816d4208b2 | [
"MIT"
]
| null | null | null | disease_predictor_backend/disease_prediction.py | waizshahid/Disease-Predictor | 2bf2e69631ddbf7ffce0b6c39adcb6816d4208b2 | [
"MIT"
]
| 7 | 2020-09-07T21:31:50.000Z | 2022-02-26T22:28:30.000Z | disease_predictor_backend/disease_prediction.py | waizshahid/Disease-Predictor | 2bf2e69631ddbf7ffce0b6c39adcb6816d4208b2 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import flask
from flask import request, jsonify
import time
import sqlite3
import random
# import the necessary packages
from keras.preprocessing.image import img_to_array
from keras.models import load_model
from keras import backend
from imutils import build_montages
import cv2
import numpy as np
from flask_cors import CORS
import io
app = flask.Flask(__name__)
CORS(app)
conn = sqlite3.connect('database.db')
print("Opened database successfully")
conn.execute('CREATE TABLE IF NOT EXISTS Patients (id INTEGER PRIMARY KEY,firstName TEXT, lastName TEXT, ins_ID TEXT, city TEXT, dob TEXT)')
conn.execute('CREATE TABLE IF NOT EXISTS Spiral (id INTEGER PRIMARY KEY,positive INTEGER, negative INTEGER)')
conn.execute('CREATE TABLE IF NOT EXISTS Wave (id INTEGER PRIMARY KEY,positive INTEGER, negative INTEGER)')
conn.execute('CREATE TABLE IF NOT EXISTS Malaria (id INTEGER PRIMARY KEY,positive INTEGER, negative INTEGER)')
@app.route('/prediction', methods=['POST'])
def api_image():
# Database
print('API CALL')
firstName = request.args['fname']
lastName = request.args['lname']
ins_ID = request.args['ins_ID']
city = request.args['city']
dob = request.args['dob']
model_name = request.args["model"]
photo = request.files['photo']
in_memory_file = io.BytesIO()
photo.save(in_memory_file)
data = np.fromstring(in_memory_file.getvalue(), dtype=np.uint8)
color_image_flag = 1
orig = cv2.imdecode(data, color_image_flag)
model_path = ""
# load the pre-trained network
print("[INFO] loading pre-trained network...")
if model_name in "malaria":
print("Maalaria model loaded")
model_path = "malaria_model.model" # Please enter the path for Malaria model
elif model_name in "spiral":
print("Spiral model loaded")
model_path = "spiral_model.model" # Please enter the path for Spiral model
elif model_name in "wave":
print("Wave model loaded")
model_path = r"wave_model.model" # Please enter the path for wave model
model = load_model(model_path)
# initialize our list of results
results = []
# pre-process our image by converting it from BGR to RGB channel
# ordering (since our Keras mdoel was trained on RGB ordering),
# resize it to 64x64 pixels, and then scale the pixel intensities
# to the range [0, 1]
image = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (48, 48))
image = image.astype("float") / 255.0
# order channel dimensions (channels-first or channels-last)
# depending on our Keras backend, then add a batch dimension to
# the image
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
# make predictions on the input image
pred = model.predict(image)
print("pred: ", pred)
pred = pred.argmax(axis=1)[0]
# an index of zero is the 'parasitized' label while an index of
# one is the 'uninfected' label
label = "UnInfected" if pred == 0 else "Infected"
color = (0, 0, 255) if pred == 0 else (0, 255, 0)
# resize our original input (so we can better visualize it) and
# then draw the label on the image
orig = cv2.resize(orig, (128, 128))
cv2.putText(orig, label, (3, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
color, 2)
# add the output image to our list of results
results.append(orig)
# Use the jsonify function from Flask to convert our list of
# Python dictionaries to the JSON format.
res = {}
with sqlite3.connect("database.db") as con:
cur = con.cursor()
cur.execute('INSERT INTO Patients VALUES(?,?,?,?,?,?)',(None,firstName, lastName, ins_ID, city, dob))
res=cur.execute('SELECT * FROM Patients')
if model_name in "malaria":
if pred == 1:
cur.execute('INSERT INTO Malaria VALUES(?,?,?)',(None,1,0))
else:
cur.execute('INSERT INTO Malaria VALUES(?,?,?)',(None,0,1))
con.commit()
positive = cur.execute('SELECT SUM(positive) FROM Malaria')
positive = positive.fetchall()
negative = cur.execute('SELECT SUM(negative) FROM Malaria')
negative = negative.fetchall()
elif model_name in "spiral":
if pred == 1:
cur.execute('INSERT INTO Spiral VALUES(?,?,?)',(None,1,0))
else:
cur.execute('INSERT INTO Spiral VALUES(?,?,?)',(None,0,1))
con.commit()
positive = cur.execute('SELECT SUM(positive) FROM Spiral')
positive = positive.fetchall()
negative = cur.execute('SELECT SUM(negative) FROM Spiral')
negative = negative.fetchall()
elif model_name in "wave":
if pred == 1:
cur.execute('INSERT INTO Wave VALUES(?,?,?)',(None,1,0))
else:
cur.execute('INSERT INTO Wave VALUES(?,?,?)',(None,0,1))
con.commit()
positive = cur.execute('SELECT SUM(positive) FROM Wave')
positive = positive.fetchall()
negative = cur.execute('SELECT SUM(negative) FROM Wave')
negative = negative.fetchall()
if pred == 1:
res = {"Prediction":"1", "positive":positive, "negative":negative}
print(res)
else:
res = {"Prediction":"0", "positive":positive, "negative":negative}
print(res)
backend.clear_session()
return jsonify(res)
app.run()
# In[ ]:
| 30.950276 | 141 | 0.632453 | 0 | 0 | 0 | 0 | 4,594 | 0.820064 | 0 | 0 | 2,324 | 0.414852 |
fd9d4c56c77881ca620b8d3d69d3ef8f45c56824 | 1,917 | py | Python | core/views.py | georgeo23/fika_backend | bff76f3be8bb4af7499bb17127b96b4d4aca14e1 | [
"MIT"
]
| null | null | null | core/views.py | georgeo23/fika_backend | bff76f3be8bb4af7499bb17127b96b4d4aca14e1 | [
"MIT"
]
| null | null | null | core/views.py | georgeo23/fika_backend | bff76f3be8bb4af7499bb17127b96b4d4aca14e1 | [
"MIT"
]
| null | null | null | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from rest_framework import permissions, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserSerializer, UserSerializerWithToken, MessageSerializer
from core.models import Message
from rest_framework import viewsets
@api_view(['GET'])
def current_user(request):
"""
Determine the current user by their token, and return their data
"""
serializer = UserSerializer(request.user)
return Response(serializer.data)
class UserList(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request):
nameset = User.objects.all()
serializer = UserSerializerWithToken(nameset, many=True)
return Response(serializer.data)
# def get(self, request):
# serializer = UserSerializerWithToken.objects.all()
# return Reponse(serializer.data)
def post(self, request, format=None):
serializer = UserSerializerWithToken(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class MessageSet(APIView):
def post(self, request):
serializer = MessageSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request):
queryset = Message.objects.all()
serializer_class = MessageSerializer(queryset, many=True)
return Response(serializer_class.data)
| 32.491525 | 83 | 0.7277 | 1,231 | 0.642149 | 0 | 0 | 218 | 0.113719 | 0 | 0 | 203 | 0.105895 |
fd9dfebdc3992ce7b8a849f7cc5d3d65ff09d8f0 | 352 | py | Python | src/tweetvalidator/data_processing/__init__.py | JoshuaGRubin/AI-Tweet-Validator | c011b08163cfd322c637c2296dab7ae41a64ae71 | [
"MIT"
]
| 5 | 2019-06-27T02:18:08.000Z | 2020-03-09T22:03:09.000Z | src/tweetvalidator/data_processing/__init__.py | JoshuaGRubin/AI-Tweet-Validator | c011b08163cfd322c637c2296dab7ae41a64ae71 | [
"MIT"
]
| 11 | 2020-01-28T22:50:34.000Z | 2022-02-10T00:31:21.000Z | src/tweetvalidator/data_processing/__init__.py | JoshuaGRubin/AI-Text-Validator | c011b08163cfd322c637c2296dab7ae41a64ae71 | [
"MIT"
]
| 1 | 2020-02-21T03:38:12.000Z | 2020-02-21T03:38:12.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .filter_tweets import filter_tweets_from_directories
from .filter_tweets import filter_tweets_from_files
from .download_tweets import get_tweets_by_user
from .embed_tweets import SentenceEncoder
from .embed_tweets import embed_tweets_from_file
from .embed_tweets import embed_tweets_from_directories
| 39.111111 | 57 | 0.855114 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 45 | 0.127841 |
fd9e5a93435223ef2e9839097575d0e44e5ee1f5 | 2,132 | py | Python | portalsdmz/measureTools/models.py | larc-usp/data-transfer-tester | fd94f120961d6016f58247d31b5d04b2f2b2cd07 | [
"AFL-2.1"
]
| null | null | null | portalsdmz/measureTools/models.py | larc-usp/data-transfer-tester | fd94f120961d6016f58247d31b5d04b2f2b2cd07 | [
"AFL-2.1"
]
| 2 | 2017-12-13T20:57:34.000Z | 2017-12-13T20:57:35.000Z | portalsdmz/measureTools/models.py | larc-usp/data-transfer-tester | fd94f120961d6016f58247d31b5d04b2f2b2cd07 | [
"AFL-2.1"
]
| null | null | null | from django.db import models
from scenarios.models import ScenarioData
# Create your models here.
class scpData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
class gridftpData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
class wgetData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
class iperfData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
class axelData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
class udrData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
class aria2cData(models.Model):
velocidade = models.DecimalField(max_digits=5, decimal_places=1)
scenario = models.ForeignKey(ScenarioData, null=True)
num_teste = models.SmallIntegerField()
descricao_erro = models.TextField(blank=True)
def __unicode__(self):
return str(self.id)
| 31.352941 | 66 | 0.778612 | 2,019 | 0.946998 | 0 | 0 | 0 | 0 | 0 | 0 | 26 | 0.012195 |
fd9eda7f958b9bb9b2b7af7adc0477c17f9fb5fc | 19,230 | py | Python | web/app.py | Luzkan/MessengerNotifier | 462c6b1a9aa0a29a0dd6b5fc77d0677c61962d5d | [
"Linux-OpenIB"
]
| 4 | 2020-06-01T09:01:47.000Z | 2021-04-16T20:07:29.000Z | web/app.py | Luzkan/NotifAyy | 462c6b1a9aa0a29a0dd6b5fc77d0677c61962d5d | [
"Linux-OpenIB"
]
| 20 | 2020-06-05T16:54:36.000Z | 2020-06-09T13:25:59.000Z | web/app.py | Luzkan/MessengerNotifier | 462c6b1a9aa0a29a0dd6b5fc77d0677c61962d5d | [
"Linux-OpenIB"
]
| 2 | 2020-05-07T04:51:00.000Z | 2020-05-08T17:52:55.000Z | import logging
from flask import Flask, render_template, request, redirect, flash, session, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, LoginManager, login_user, logout_user
from datetime import datetime
from passlib.hash import sha256_crypt
import msnotifier.bot.siteMonitor as siteMonitor
import threading
import msnotifier.messenger as messenger
app = Flask(__name__)
app.config['SECRET_KEY'] = 'xDDDDsupresikretKEy'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///notifayy.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Login Handling
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
# User_ID = Primary Key
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# -------------------------
# - Database Structure -
# ALERT TABLE
# +----+-------------+-----------------+-------------------+---------------+---------------+
# | ID | TITLE (str) | PAGE (url) | DATE_ADDED (date) | USER_ID (key) | APPS_ID (key) |
# +----+-------------+-----------------+-------------------+---------------+---------------+
# | 1 | My Site | http://site.com | 07.06.2020 | 2 | 4 |
# | 2 | (...) | (...) | (...) | (...) | (...) |
# +----+-------------+-----------------+-------------------+---------------+---------------+
# > APPS_ID -> Key, which is: Primary Key in APPS Table
# > USER_ID -> Key, which is: Primary Key in USER Table
# APPS TABLE
# +----+----------------+-----------------+------------------+--------------+
# | ID | Discord (bool) | Telegram (bool) | Messenger (bool) | Email (bool) |
# +----+----------------+-----------------+------------------+--------------+
# | 4 | true | false | true | true |
# | 5 | (...) | (...) | (...) | (...) |
# +----+----------------+-----------------+------------------+--------------+
# > ID -> Primary Key, which is: Referenced by ALERTS TABLE (APPS_ID)
# USER TABLE
# +----+----------------+-----------------------+------------------+--------------------+--------------+
# | ID | Email (str) | Passowrd (str hashed) | Discord_Id (int) | Messenger_Id (str) | Logged (int) |
# +----+----------------+-----------------------+------------------+--------------------+--------------+
# | 2 | [email protected] | <hash> | 21842147 | ??? | 1 |
# | 3 | (...) | (...) | (...) | (...) | |
# +----+----------------+-----------------------+------------------+--------------------+--------------+
# > ID -> Primary Key, which is: Referenced by ALERTS TABLE (USER_ID)
# -------------------------------
# - Database Classes Tables -
class Alert(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
page = db.Column(db.String(100), nullable=False)
date_added = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
user_id = db.Column(db.Integer, nullable=False)
apps_id = db.Column(db.Integer, nullable=False)
def __repr__(self):
return f'Alert # {str(self.id)}'
class ChangesForDiscord(db.Model):
id = db.Column(db.Integer, primary_key=True)
alert_id = db.Column(db.Integer, nullable=False)
content = db.Column(db.String(200), nullable=False)
def __repr__(self):
return f'ChangesForDiscord # {str(self.id)}'
class Apps(db.Model):
id = db.Column(db.Integer, primary_key=True)
discord = db.Column(db.Boolean, nullable=False, default=False)
telegram = db.Column(db.Boolean, nullable=False, default=False)
messenger = db.Column(db.Boolean, nullable=False, default=False)
email = db.Column(db.Boolean, nullable=False, default=False)
def __repr__(self):
return f'Apps # {str(self.id)}. Status (d/t/m): ({str(self.discord)}/{str(self.telegram)}/{str(self.messenger)}/{str(self.email)})'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
discord_id = db.Column(db.Integer, nullable=True)
messenger_l = db.Column(db.String(100), nullable=True)
messenger_token = db.Column(db.String(100), nullable=True)
telegram_id = db.Column(db.String(100), nullable=True)
logged = db.Column(db.Integer, nullable=True)
def __repr__(self):
return f'User: {str(self.email)}'
def get_items_for_messaging(id):
a=Alert.query.filter_by(id=id).first()
u=User.query.filter_by(id=a.user_id)
bools=Apps.query.filter_by(id=id)
return [a,u,bools]
def add_to_changes(item):
item=ChangesForDiscord(alert_id=item[0],content=item[1])
db.session.add(item)
db.session.commit()
# --------------------------------
# - Helping Functions for DB -
def get_everything(alert_id):
al=Alert.query.filter_by(id=alert_id).first()
user=User.query.filter_by(id=al.user_id).first()
apps=Apps.query.filter_by(id=al.apps_id).first()
return al, user, apps
def allAlerts():
return Alert.query.all()
class Sending(threading.Thread):
def __init__(self,changes):
threading.Thread.__init__(self)
self.changes =changes
def run(self):
for item in self.changes:
# z itema wyciągamy alert_id i content
content=item[1]
alert_id=item[0]
al, user, apps = get_everything(alert_id)
alertwebpage=al.page
mail=apps.email
msng=apps.messenger
discord=apps.discord
if mail==True:
email=user.email
notifier= messenger.mail_chat()
notifier.log_into(email,"")
notifier.message_myself(content,alertwebpage)
if msng==True:
fblogin=user.fb_login
fbpass=user.fb_passw
notifier= messenger.mail_chat()
notifier.log_into(fblogin,fbpass)
notifier.message_myself(content,alertwebpage)
if discord==True:
add_to_changes(item)
class Detecting(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.alerts=[]
def get_all_alerts(self):
return [(i.id, i.page) for i in allAlerts()]
def delete_alert(self,alert_id):
for alert in self.alerts:
if alert[0]==alert_id:
self.alerts.remove(alert)
return 1
return -1
def add_alert(self,alert_id,adr):
self.alerts.append((alert_id,adr))
def run(self):
self.alerts = self.get_all_alerts()
while(True):
tags = ["h1", "h2", "h3", "p"]
changes=siteMonitor.get_diffs_string_format(siteMonitor.get_diffs(tags,[alert[0] for alert in self.alerts],[alert[1] for alert in self.alerts],16),tags)
if len(changes)!=0:
Sending(changes).start()
o=Detecting()
o.start()
def get_alerts():
# Getting current User ID and retrieving his alerts
cur_user_id = session["_user_id"]
all_alerts = Alert.query.filter_by(user_id=cur_user_id).order_by(Alert.date_added).all()
all_apps = get_apps(all_alerts)
# Adding to Alert Object the booleans for apps through apps_id key
for alert in all_alerts:
alert.messenger = all_apps[alert.id].messenger
alert.discord = all_apps[alert.id].discord
alert.telegram = all_apps[alert.id].telegram
alert.email = all_apps[alert.id].email
return all_alerts
def get_alerts_by_id(discordId: str):
all_alerts = Alert.query.filter_by(user_id=discordId).order_by(Alert.date_added).all()
all_apps = get_apps(all_alerts)
for alert in all_alerts:
alert.discord = all_apps[alert.id].discord
return all_alerts
def get_apps(all_alerts):
all_apps = {}
for alert in all_alerts:
all_apps[alert.id] = Apps.query.get(alert.apps_id)
return all_apps
# ---------------------------------------
# - Helping Functions for Site Walk -
def remember_me_handle():
if "_user_id" in session:
if session["remember_me"]:
app.logger.info('User was logged in - printing his site.')
all_alerts = get_alerts()
return render_template('index.html', alerts=all_alerts, emailuser=session['email'])
else:
app.logger.info('User was not logged in - printing landing page.')
return redirect('/index.html')
else:
return render_template('index.html')
def get_bool(string):
if string == "True" or string == "true":
return True
return False
# -----------------------
# - Main HREF Routes -
@app.route('/register', methods=['GET', 'POST'])
def auth():
app.logger.info('Registration Button pressed.')
if request.method == 'POST':
app.logger.info('Method: POST')
user_email = request.form['email']
user_password = request.form['password']
# If this returns then it means that this user exists
user = User.query.filter_by(email=user_email).first()
# If user doesn't exist, redirect back
if user:
flash('Email address already exists')
app.logger.warning("Email adress already exist in the database.")
return redirect('/')
app.logger.info("Succesfully added new user to database.")
# Hashing the Password
password_hashed = sha256_crypt.hash(user_password)
new_user = User(email=user_email, password=password_hashed)
# Add new user to DB
db.session.add(new_user)
db.session.commit()
flash('Registration went all fine! :3 You can now log in!')
return redirect('/')
else:
app.logger.warning("User somehow didn't use Method: POST.")
flash('Something went wrong with sending the registration informations.')
return redirect('/')
@app.route('/login', methods=['POST'])
def login_post():
app.logger.info('Login Button Pressed.')
if request.method == 'POST':
# Get User Informations from Form
user_email = request.form.get('email')
user_password = request.form.get('password')
remember = request.form.get('remember')
user = User.query.filter_by(email=user_email).first()
# Checking if this user exist (doing this and pass check will throw err, if user is not in db, hence no pass)
if not user:
flash("There's no registered account with given email adress.")
app.logger.warning(" User doesn't exist: " + user_email)
return redirect('/')
# --- Password Check
# Info: I'm printing hashed version, but we actually compare the original string with hashed version in db
pass_check = (sha256_crypt.verify(user_password, user.password))
app.logger.info(f"Result of pass check: {pass_check} - (input: {sha256_crypt.hash(user_password)}, db: {user.password})")
# ---
# Verifying Password
if not user or not pass_check:
flash('Please check your login details and try again.')
app.logger.warning("Wrong Credentials" + user_email)
return redirect('/')
app.logger.info("Succesfully logged in user: " + user_email)
# Remember Me Handling (saving in session and in param)
login_user(user, remember=remember)
session["remember_me"] = True if remember else False
session["email"] = user_email
# Apps Quality of Life display if already defined by user
session["disc"] = user.discord_id
session["mess"] = user.messenger_l
session["tele"] = user.telegram_id
if user.discord_id == None:
session["disc"] = ""
if user.messenger_l == None:
session["mess"] = ""
if user.telegram_id == None:
session["tele"] = ""
# Getting Alerts and loading the page for this user
return redirect('/index.html')
else:
return remember_me_handle()
return redirect('/')
@app.route('/alerts', methods=['GET', 'POST'])
def alerts():
if request.method == 'POST':
app.logger.info('Adding New Alert.')
# Creating App Alert
messenger_bool = get_bool(request.form['messenger'])
telegram_bool = get_bool(request.form['telegram'])
discord_bool = get_bool(request.form['discord'])
email_bool = get_bool(request.form['email'])
new_apps_bool = Apps(discord=discord_bool, telegram=telegram_bool, messenger=messenger_bool, email=email_bool)
# First we add the app alert, then flush to retrieve it's unique ID
db.session.add(new_apps_bool)
db.session.flush()
# Creating new Alert
alert_title = request.form['title']
alert_page = request.form['page']
current_user_id = session["_user_id"]
apps_bools_id = new_apps_bool.id
new_alert = Alert(title=alert_title, page=alert_page, user_id=current_user_id, apps_id=apps_bools_id)
db.session.add(new_alert)
db.session.flush()
o.add_alert(new_alert.id,new_alert.page)
db.session.commit()
return redirect('/index.html')
else:
app.logger.info('Loading Landing Page or User Main Page.')
return remember_me_handle()
# --------------------------------
# - Editing / Deleting Alerts -
@app.route('/alerts/delete/<int:id>')
def delete(id):
app.logger.info(f'Deleting Alert with ID: {id}')
alert = Alert.query.get_or_404(id)
db.session.delete(alert)
o.delete_alert(alert.id)
db.session.commit()
return redirect('/index.html')
# Made the alert editing very smooth - everything is handled from mainpage
@app.route('/alerts/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
app.logger.info(f'Trying to edit Alert with ID: {id}')
# Retrieving the edited Alert from DB
o.delete_alert(id)
alert = Alert.query.get_or_404(id)
apps = Apps.query.get_or_404(alert.apps_id)
if request.method == 'POST':
app.logger.info(f'Editing Alert with ID: {id}')
# Receiving new inputs for this alert
alert.title = request.form['title']
alert.page = request.form['page']
apps.messenger = get_bool(request.form['messenger'])
apps.telegram = get_bool(request.form['telegram'])
apps.discord = get_bool(request.form['discord'])
apps.email = get_bool(request.form['email'])
# Updating the alert in DB
o.add_alert(alert.id, alert.page)
db.session.commit()
app.logger.info(f'Edited Alert with ID: {id}')
return redirect('/index.html')
# -----------------------------------------
# - Linking Discord/Messenger/Telegram -
@app.route('/discord_link', methods=['POST'])
def discord_link():
app.logger.info(f'Trying to link discord id.')
# Retrieving the current User info from DB
user = User.query.get_or_404(session["_user_id"])
if request.method == 'POST':
# Receiving new inputs for this alert
user.discord_id = request.form['discord_id']
session["disc"] = user.discord_id
# Updating the alert in DB
db.session.commit()
app.logger.info(f"Linked Discord for user {session['_user_id']} - id: {user.discord_id}")
return redirect('/index.html')
@app.route('/messenger_link', methods=['POST'])
def messenger_link():
app.logger.info(f'Trying to link messenger credentials.')
user = User.query.get_or_404(session["_user_id"])
if request.method == 'POST':
# Deadline Request Feature
user.messenger_l = request.form['messenger_l']
# It's bad idea to store plain password String in db
# messenger_p variable contains fb password
messenger_p = request.form['messenger_p']
session["mess"] = user.messenger_l
db.session.commit()
app.logger.info(f"Linked Messenger for user {session['_user_id']} - login: {user.messenger_l}")
return redirect('/index.html')
@app.route('/telegram_link', methods=['POST'])
def telegram_link():
app.logger.info(f'Trying to link telegram id.')
user = User.query.get_or_404(session["_user_id"])
if request.method == 'POST':
user.telegram_id = request.form['telegram_id']
session["tele"] = user.telegram_id
db.session.commit()
app.logger.info(f"Linked Telegram for user {session['_user_id']} - id: {user.telegram_id}")
return redirect('/index.html')
# ------------------------------------
# - HREF for Mainpage and Logout -
@app.route('/')
def index():
app.logger.info('Landing Page Visited.')
return remember_me_handle()
@app.route('/index.html', methods=['GET', 'POST'])
def go_home():
all_alerts = get_alerts()
return render_template('index.html', alerts=all_alerts, emailuser=session['email'], discsaved=session["disc"], messsaved=session["mess"], telesaved=session["tele"])
@app.route('/logout', methods=['GET', 'POST'])
def logout():
app.logger.info(f"User is logging out: {session['email']}")
logout_user()
return redirect('/')
@app.route('/changes', methods=['GET'])
def changes():
change = ChangesForDiscord.query.first()
if change is None:
return jsonify({'change': '', 'title': '', 'page': '', 'discid': -1})
db.session.delete(change)
db.session.commit()
alrt = Alert.query.filter_by(id = change.alert_id).first()
usr = User.query.filter_by(id = alrt.user_id).first()
if usr is None:
return jsonify({'change': '', 'title': '', 'page': '', 'discid': -1})
result = jsonify({'change': change.content, 'title': alrt.title, 'page': alrt.page, 'discid': usr.discord_id})
return result
if __name__ == "__main__":
app.run(debug=True)
# ===== Notice Info 04-06-2020
# First of all, password encryption was added, so:
# > pip install passlib (507kb, guys)
#
# Keep in mind that expanding on existing models in DB
# Will caues error due to unexisting columns, so:
# Navigate to ./web (here's the app.py)
# > python
# > from app import db
# > db.reflect()
# > db.drop_all()
# > db.create_all()
# ===== Notice Info 05-06-2020
# To surprass all these annoying false-positive warnings with
# db.* and logger.*, just do this:
# > pip install pylint-flask (10 KB)
# Then in .vscode/settings.json (if you are using vscode), add:
# > "python.linting.pylintArgs": ["--load-plugins", "pylint-flask"]
# ===== Notice Info 06-06-2020
# > app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# ^ This is for the FSADeprecationWarning (adds significant overhead)
# and will be disabled by default in the future anyway
#
# Cleaned up this code a bit, and made it more visual and easy to read
# Added linking functionality for all buttons, so you can do w/e you want
# with them right now. Also added email bool for alerts | 36.768642 | 168 | 0.5974 | 3,596 | 0.18699 | 0 | 0 | 8,851 | 0.460246 | 0 | 0 | 7,479 | 0.388903 |
fd9edbd2527ab031760844081c4c8a7d476ee612 | 2,344 | py | Python | src/tcp/registration/pygame_labeler.py | Iszhanghailun/Traffic_Camera_Pipeline | 4dbd0e993087d46066a780f5345c125f47b28881 | [
"MIT"
]
| 5 | 2019-04-04T17:30:41.000Z | 2021-12-06T15:27:43.000Z | src/tcp/registration/pygame_labeler.py | Iszhanghailun/Traffic_Camera_Pipeline | 4dbd0e993087d46066a780f5345c125f47b28881 | [
"MIT"
]
| 2 | 2018-02-07T06:22:08.000Z | 2020-04-20T06:54:52.000Z | src/tcp/registration/pygame_labeler.py | Iszhanghailun/Traffic_Camera_Pipeline | 4dbd0e993087d46066a780f5345c125f47b28881 | [
"MIT"
]
| 7 | 2018-02-06T23:23:29.000Z | 2020-09-20T14:48:22.000Z | import sys, os
import gym
import gym_urbandriving as uds
import cProfile
import time
import numpy as np
import pickle
import skimage.transform
import cv2
import IPython
import pygame
from random import shuffle
from gym_urbandriving.agents import KeyboardAgent, AccelAgent, NullAgent, TrafficLightAgent#, RRTAgent
from gym_urbandriving.assets import Car, TrafficLight
import colorlover as cl
class PygameLabeler():
def __init__(self,config):
self.config = config
def initalize_simulator(self):
'''
Initializes the simulator
'''
self.vis = uds.PyGameVisualizer((800, 800))
# Create a simple-intersection state, with no agents
self.init_state = uds.state.SimpleIntersectionState(ncars=0, nped=0, traffic_lights=True)
# Create the world environment initialized to the starting state
# Specify the max time the environment will run to 500
# Randomize the environment when env._reset() is called
# Specify what types of agents will control cars and traffic lights
# Use ray for multiagent parallelism
self.env = uds.UrbanDrivingEnv(init_state=self.init_state,
visualizer=self.vis,
max_time=500,
randomize=False,
agent_mappings={Car:NullAgent,
TrafficLight:TrafficLightAgent},
use_ray=False
)
self.env._reset(new_state=self.init_state)
def sim_labeler(self):
'''
Visualize the sperated trajecotries in the simulator and can also visualize the matching images
Parameter
------------
trajectories: list of Trajectory
A list of Trajectory Class
plot_traffic_images: bool
True if the images from the traffic cam should be shown alongside the simulator
'''
self.initalize_simulator()
while True:
values = pygame.mouse.get_pressed()
self.env._render(traffic_trajectories = self.config.registration_points)
if values[0]:
pose = pygame.mouse.get_pos()
return np.array([pose[0],pose[1]])/0.8
| 26.942529 | 103 | 0.610922 | 1,942 | 0.828498 | 0 | 0 | 0 | 0 | 0 | 0 | 748 | 0.319113 |
fd9ef32448c7395440ff57be12cda76c221914ac | 12,319 | py | Python | maccli/service/instance.py | manageacloud/manageacloud-cli | 1b7d9d5239f9e51f97d0377d223db0f58ca0ca7c | [
"MIT"
]
| 6 | 2015-09-21T09:02:04.000Z | 2017-02-08T23:40:18.000Z | maccli/service/instance.py | manageacloud/manageacloud-cli | 1b7d9d5239f9e51f97d0377d223db0f58ca0ca7c | [
"MIT"
]
| 3 | 2015-11-03T01:44:29.000Z | 2016-03-25T08:36:15.000Z | maccli/service/instance.py | manageacloud/manageacloud-cli | 1b7d9d5239f9e51f97d0377d223db0f58ca0ca7c | [
"MIT"
]
| 4 | 2015-07-06T01:46:13.000Z | 2019-01-10T23:08:19.000Z | import os
import tempfile
import time
import urllib
import urllib.parse
import pexpect
import maccli.dao.api_instance
import maccli.helper.cmd
import maccli.helper.simplecache
import maccli.helper.metadata
from maccli.helper.exception import InstanceDoesNotExistException, InstanceNotReadyException
def list_instances(name_or_ids=None):
"""
List available instances in the account
"""
instances = []
instances_raw = maccli.dao.api_instance.get_list()
if name_or_ids is not None:
# if name_or_ids is string, convert to list
if isinstance(name_or_ids, str):
name_or_ids = [name_or_ids]
for instance_raw in instances_raw:
if instance_raw['servername'] in name_or_ids or instance_raw['id'] in name_or_ids:
instances.append(instance_raw)
else:
instances = instances_raw
return instances
def list_by_infrastructure(name, version):
instances = maccli.dao.api_instance.get_list()
filtered_instances = []
for instance in instances:
if 'metadata' in instance and 'infrastructure' in instance['metadata'] and 'name' in instance['metadata'][
'infrastructure']:
infrastructure_name = instance['metadata']['infrastructure']['name']
else:
infrastructure_name = ""
if 'metadata' in instance and 'infrastructure' in instance['metadata'] and 'version' in instance['metadata'][
'infrastructure']:
infrastructure_version = instance['metadata']['infrastructure']['version']
else:
infrastructure_version = ""
if infrastructure_name == name and infrastructure_version == version:
filtered_instances.append(instance)
return filtered_instances
def ssh_command_instance(instance_id, cmd):
rc, stdout, stderr = -1, "", ""
cache_hash = maccli.helper.simplecache.hash_value(cmd)
cache_key = 'ssh_%s_%s' % (instance_id, cache_hash)
cached_value = maccli.helper.simplecache.get(cache_key) # read from cache
if cached_value is not None:
rc = cached_value['rc']
stdout = cached_value['stdout']
stderr = cached_value['stderr']
else:
instance = maccli.dao.api_instance.credentials(instance_id)
# strict host check
ssh_params = ""
if maccli.disable_strict_host_check:
maccli.logger.debug("SSH String Host Checking disabled")
ssh_params = "-o 'StrictHostKeyChecking no'"
if instance is None:
raise InstanceDoesNotExistException(instance_id)
if not (instance['privateKey'] or instance['password']):
raise InstanceNotReadyException(instance_id)
if instance is not None and (instance['privateKey'] or instance['password']):
if instance['privateKey']:
fd, path = tempfile.mkstemp()
try:
with open(path, "wb") as f:
f.write(bytes(instance['privateKey'], encoding='utf8'))
f.close()
# openssh 7.6, it defaults to a new more secure format.
command = "ssh-keygen -f %s -p -N ''" % f.name
maccli.helper.cmd.run(command)
command = "ssh %s %s@%s -i %s %s" % (ssh_params, instance['user'], instance['ip'], f.name, cmd)
rc, stdout, stderr = maccli.helper.cmd.run(command)
finally:
os.close(fd)
os.remove(path)
else:
""" Authentication with password """
command = "ssh %s %s@%s %s" % (ssh_params, instance['user'], instance['ip'], cmd)
child = pexpect.spawn(command)
(rows, cols) = gettermsize()
child.setwinsize(rows, cols) # set the child to the size of the user's term
i = child.expect(['.* password:', "yes/no", '(.*)'], timeout=60)
if i == 0:
child.sendline(instance['password'])
child.expect(pexpect.EOF, timeout=120)
elif i == 1:
child.sendline("yes")
child.expect('.* password:', timeout=60)
child.sendline(instance['password'])
child.expect(pexpect.EOF, timeout=120)
elif i == 2:
child.expect(pexpect.EOF, timeout=120)
output = child.before
while child.isalive():
time.sleep(0.1)
rc = child.exitstatus
# HACK: we do not really capture stderr
if rc:
stdout = ""
stderr = output
else:
stdout = output
stderr = ""
# save cache
if not rc:
cached_value = {
'rc': rc,
'stdout': stdout,
'stderr': stderr
}
maccli.helper.simplecache.set_value(cache_key, cached_value)
return rc, stdout, stderr
def ssh_interactive_instance(instance_id):
"""
ssh to an existing instance for an interactive session
"""
stdout = None
instance = maccli.dao.api_instance.credentials(instance_id)
# strict host check
ssh_params = ""
maccli.logger.debug("maccli.strict_host_check: " + str(maccli.disable_strict_host_check))
if maccli.disable_strict_host_check:
maccli.logger.debug("SSH String Host Checking disabled")
ssh_params = "-o 'StrictHostKeyChecking no'"
if instance is not None:
if instance['privateKey']:
""" Authentication with private key """
fd, path = tempfile.mkstemp()
try:
with open(path, "wb") as f:
f.write(bytes(instance['privateKey'], encoding='utf8'))
f.close()
command = "ssh %s %s@%s -i %s " % (ssh_params, instance['user'], instance['ip'], f.name)
os.system(command)
finally:
os.close(fd)
os.remove(path)
else:
""" Authentication with password """
command = "ssh %s %s@%s" % (ssh_params, instance['user'], instance['ip'])
child = pexpect.spawn(command)
(rows, cols) = gettermsize()
child.setwinsize(rows, cols) # set the child to the size of the user's term
i = child.expect(['.* password:', "yes/no", '[#\$] '], timeout=60)
if i == 0:
child.sendline(instance['password'])
child.interact()
elif i == 1:
child.sendline("yes")
child.expect('.* password:', timeout=60)
child.sendline(instance['password'])
child.interact()
elif i == 2:
child.sendline("\n")
child.interact()
return stdout
def gettermsize():
""" horrible non-portable hack to get the terminal size to transmit
to the child process spawned by pexpect """
(rows, cols) = os.popen("stty size").read().split() # works on Mac OS X, YMMV
rows = int(rows)
cols = int(cols)
return rows, cols
def create_instance(cookbook_tag, bootstrap, deployment, location, servername, provider, release, release_version,
branch, hardware, lifespan,
environments, hd, port, net, metadata=None, applyChanges=True):
"""
List available instances in the account
"""
return maccli.dao.api_instance.create(cookbook_tag, bootstrap, deployment, location, servername, provider, release,
release_version,
branch, hardware, lifespan, environments, hd, port, net, metadata,
applyChanges)
def destroy_instance(instanceid):
"""
Destroy the server
:param servername:
:return:
"""
return maccli.dao.api_instance.destroy(instanceid)
def credentials(servername, session_id):
"""
Gets the server credentials: public ip, username, password and private key
:param instance_id;
:return:
"""
return maccli.dao.api_instance.credentials(servername, session_id)
def facts(instance_id):
"""
Returns facts about the system
:param instance_id;
:return:
"""
return maccli.dao.api_instance.facts(instance_id)
def log(instance_id, follow):
"""
Returns server logs
:param instance_id;
:return:
"""
if follow:
logs = maccli.dao.api_instance.log_follow(instance_id)
else:
logs = maccli.dao.api_instance.log(instance_id)
return logs
def lifespan(instance_id, amount):
"""
Set new instance lifespan
:param instance_id;
:return:
"""
return maccli.dao.api_instance.update(instance_id, amount)
def update_configuration(cookbook_tag, bootstrap, instance_id, new_metadata=None):
"""
Update server configuration with given cookbook
:param cookbook_tag:
:param instance_id:
:return:
"""
return maccli.dao.api_instance.update_configuration(cookbook_tag, bootstrap, instance_id, new_metadata)
def create_instances_for_role(root, infrastructure, roles, infrastructure_key, quiet):
""" Create all the instances for the given tier """
maccli.logger.debug("Processing infrastructure %s" % infrastructure_key)
roles_created = {}
maccli.logger.debug("Type role")
infrastructure_role = infrastructure['role']
role_raw = roles[infrastructure_role]["instance create"]
metadata = maccli.helper.metadata.metadata_instance(root, infrastructure_key, infrastructure_role, role_raw,
infrastructure)
instances = create_tier(role_raw, infrastructure, metadata, quiet)
roles_created[infrastructure_role] = instances
return roles_created
def create_tier(role, infrastructure, metadata, quiet):
"""
Creates the instances that represents a role in a given infrastructure
:param role:
:param infrastructure:
:return:
"""
lifespan = None
try:
lifespan = infrastructure['lifespan']
except KeyError:
pass
hardware = ""
try:
hardware = infrastructure["hardware"]
except KeyError:
pass
environment = maccli.helper.metadata.get_environment(role, infrastructure)
hd = None
try:
hd = role["hd"]
except KeyError:
pass
configuration = None
try:
configuration = role["configuration"]
except KeyError:
pass
bootstrap = None
try:
bootstrap = role["bootstrap bash"]
except KeyError:
pass
port = None
try:
port = infrastructure["port"]
except KeyError:
pass
net = None
try:
net = infrastructure["net"]
except KeyError:
pass
deployment = None
try:
deployment = infrastructure["deployment"]
except KeyError:
pass
release = None
try:
release = infrastructure["release"]
except KeyError:
pass
release_version = None
try:
release_version = infrastructure["release_version"]
except KeyError:
pass
branch = None
try:
branch = infrastructure["branch"]
except KeyError:
pass
provider = None
try:
provider = infrastructure["provider"]
except KeyError:
pass
instances = []
amount = 1
if 'amount' in infrastructure:
amount = infrastructure['amount']
for x in range(0, amount):
instance = maccli.dao.api_instance.create(configuration, bootstrap, deployment,
infrastructure["location"], infrastructure["name"],
provider, release, release_version, branch, hardware, lifespan,
environment, hd, port, net, metadata, False)
instances.append(instance)
maccli.logger.info("Creating instance '%s'" % (instance['id']))
return instances
| 29.973236 | 119 | 0.583976 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,610 | 0.211868 |
fd9f2efde7a1d0ab6cab653c4c31ffe2c9cae398 | 5,741 | py | Python | odmlui/helpers.py | mpsonntag/odml-ui | bd1ba1b5a04e4409d1f5b05fc491411963ded1fd | [
"BSD-3-Clause"
]
| 3 | 2017-03-06T17:00:45.000Z | 2020-05-05T20:59:28.000Z | odmlui/helpers.py | mpsonntag/odml-ui | bd1ba1b5a04e4409d1f5b05fc491411963ded1fd | [
"BSD-3-Clause"
]
| 138 | 2017-02-27T17:08:32.000Z | 2021-02-10T14:06:45.000Z | odmlui/helpers.py | mpsonntag/odml-ui | bd1ba1b5a04e4409d1f5b05fc491411963ded1fd | [
"BSD-3-Clause"
]
| 7 | 2017-03-07T06:39:18.000Z | 2020-04-19T12:54:51.000Z | """
The 'helpers' module provides various helper functions.
"""
import getpass
import json
import os
import subprocess
import sys
from odml import fileio
from odml.dtypes import default_values
from odml.tools.parser_utils import SUPPORTED_PARSERS
from .treemodel import value_model
try: # Python 3
from urllib.parse import urlparse, unquote, urljoin
from urllib.request import pathname2url
except ImportError: # Python 2
from urlparse import urlparse, urljoin
from urllib import unquote, pathname2url
def uri_to_path(uri):
"""
*uri_to_path* parses a uri into a OS specific file path.
:param uri: string containing a uri.
:return: OS specific file path.
"""
net_locator = urlparse(uri).netloc
curr_path = unquote(urlparse(uri).path)
file_path = os.path.join(net_locator, curr_path)
# Windows specific file_path handling
if os.name == "nt" and file_path.startswith("/"):
file_path = file_path[1:]
return file_path
def path_to_uri(path):
"""
Converts a passed *path* to a URI GTK can handle and returns it.
"""
uri = pathname2url(path)
uri = urljoin('file:', uri)
return uri
def get_extension(path):
"""
Returns the upper case file extension of a file
referenced by a passed *path*.
"""
ext = os.path.splitext(path)[1][1:]
ext = ext.upper()
return ext
def get_parser_for_uri(uri):
"""
Sanitize the given path, and also return the
odML parser to be used for the given path.
"""
path = uri_to_path(uri)
parser = get_extension(path)
if parser not in SUPPORTED_PARSERS:
parser = 'XML'
return parser
def get_parser_for_file_type(file_type):
"""
Checks whether a provided file_type is supported by the currently
available odML parsers.
Returns either the identified parser or XML as the fallback parser.
"""
parser = file_type.upper()
if parser not in SUPPORTED_PARSERS:
parser = 'XML'
return parser
def handle_section_import(section):
"""
Augment all properties of an imported section according to odml-ui needs.
:param section: imported odml.BaseSection
"""
for prop in section.properties:
handle_property_import(prop)
# Make sure properties down the rabbit hole are also treated.
for sec in section.sections:
handle_section_import(sec)
def handle_property_import(prop):
"""
Every odml-ui property requires at least one default value according
to its dtype, otherwise the property is currently broken.
Further the properties are augmented with 'pseudo_values' which need to be
initialized and added to each property.
:param prop: imported odml.BaseProperty
"""
if len(prop.values) < 1:
if prop.dtype:
prop.values = [default_values(prop.dtype)]
else:
prop.values = [default_values('string')]
create_pseudo_values([prop])
def create_pseudo_values(odml_properties):
"""
Creates a treemodel.Value for each value in an
odML Property and appends the resulting list
as *pseudo_values* to the passed odML Property.
"""
for prop in odml_properties:
values = prop.values
new_values = []
for index in range(len(values)):
val = value_model.Value(prop, index)
new_values.append(val)
prop.pseudo_values = new_values
def get_conda_root():
"""
Checks for an active Anaconda environment.
:return: Either the root of an active Anaconda environment or an empty string.
"""
# Try identifying conda the easy way
if "CONDA_PREFIX" in os.environ:
return os.environ["CONDA_PREFIX"]
# Try identifying conda the hard way
try:
conda_json = subprocess.check_output("conda info --json",
shell=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as exc:
print("[Info] Conda check: %s" % exc)
return ""
if sys.version_info.major > 2:
conda_json = conda_json.decode("utf-8")
dec = json.JSONDecoder()
try:
root_path = dec.decode(conda_json)['default_prefix']
except ValueError as exc:
print("[Info] Conda check: %s" % exc)
return ""
if sys.version_info.major < 3:
root_path = str(root_path)
return root_path
def run_odmltables(file_uri, save_dir, odml_doc, odmltables_wizard):
"""
Saves an odML document to a provided folder with the file
ending '.odml' in format 'XML' to ensure an odmltables
supported file. It then executes odmltables with the provided wizard
and the created file.
:param file_uri: File URI of the odML document that is handed over to
odmltables.
:param save_dir: Directory where the temporary file is saved to.
:param odml_doc: An odML document.
:param odmltables_wizard: supported values are 'compare', 'convert',
'filter' and 'merge'.
"""
tail = os.path.split(uri_to_path(file_uri))[1]
tmp_file = os.path.join(save_dir, ("%s.odml" % tail))
fileio.save(odml_doc, tmp_file)
try:
subprocess.Popen(['odmltables', '-w', odmltables_wizard, '-f', tmp_file])
except Exception as exc:
print("[Warning] Error running odml-tables: %s" % exc)
def get_username():
"""
:return: Full name or username of the current user
"""
username = getpass.getuser()
try:
# this only works on linux
import pwd
fullname = pwd.getpwnam(username).pw_gecos
if fullname:
username = fullname
except ImportError:
pass
return username.rstrip(",")
| 27.338095 | 82 | 0.659815 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,516 | 0.438251 |
fd9fb12d6a255983397f47fb91d956bce471d4bb | 3,511 | py | Python | mindspore/dataset/transforms/c_transforms.py | Xylonwang/mindspore | ea37dc76f0a8f0b10edd85c2ad545af44552af1e | [
"Apache-2.0"
]
| 1 | 2020-06-17T07:05:45.000Z | 2020-06-17T07:05:45.000Z | mindspore/dataset/transforms/c_transforms.py | Xylonwang/mindspore | ea37dc76f0a8f0b10edd85c2ad545af44552af1e | [
"Apache-2.0"
]
| null | null | null | mindspore/dataset/transforms/c_transforms.py | Xylonwang/mindspore | ea37dc76f0a8f0b10edd85c2ad545af44552af1e | [
"Apache-2.0"
]
| null | null | null | # Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
This module c_transforms provides common operations, including OneHotOp and TypeCast.
"""
import numpy as np
import mindspore._c_dataengine as cde
from .validators import check_num_classes, check_de_type, check_fill_value, check_slice_op
from ..core.datatypes import mstype_to_detype
class OneHot(cde.OneHotOp):
"""
Tensor operation to apply one hot encoding.
Args:
num_classes (int): Number of classes of the label.
"""
@check_num_classes
def __init__(self, num_classes):
self.num_classes = num_classes
super().__init__(num_classes)
class Fill(cde.FillOp):
"""
Tensor operation to create a tensor filled with passed scalar value.
The output tensor will have the same shape and type as the input tensor.
Args:
fill_value (python types (str, int, float, or bool)) : scalar value
to fill created tensor with.
"""
@check_fill_value
def __init__(self, fill_value):
print(fill_value)
super().__init__(cde.Tensor(np.array(fill_value)))
class TypeCast(cde.TypeCastOp):
"""
Tensor operation to cast to a given MindSpore data type.
Args:
data_type (mindspore.dtype): mindspore.dtype to be casted to.
"""
@check_de_type
def __init__(self, data_type):
data_type = mstype_to_detype(data_type)
self.data_type = str(data_type)
super().__init__(data_type)
class Slice(cde.SliceOp):
"""
Slice operation to extract a tensor out using the given n slices.
The functionality of Slice is similar to NumPy indexing feature.
(Currently only rank 1 Tensors are supported)
Args:
*slices: Maximum n number of objects to slice a tensor of rank n.
One object in slices can be one of:
1. int: slice this index only. Negative index is supported.
2. slice object: slice the generated indices from the slice object. Similar to `start:stop:step`.
3. None: slice the whole dimension. Similar to `:` in python indexing.
4. Ellipses ...: slice all dimensions between the two slices.
Examples:
>>> # Data before
>>> # | col |
>>> # +---------+
>>> # | [1,2,3] |
>>> # +---------|
>>> data = data.map(operations=Slice(slice(1,3))) # slice indices 1 and 2 only
>>> # Data after
>>> # | col |
>>> # +------------+
>>> # | [1,2] |
>>> # +------------|
"""
@check_slice_op
def __init__(self, *slices):
dim0 = slices[0]
if isinstance(dim0, int):
dim0 = [dim0]
elif dim0 is None:
dim0 = True
elif isinstance(dim0, slice):
dim0 = (dim0.start, dim0.stop, dim0.step)
elif dim0 is Ellipsis:
dim0 = True
super().__init__(dim0)
| 31.630631 | 111 | 0.621191 | 2,541 | 0.723725 | 0 | 0 | 805 | 0.229279 | 0 | 0 | 2,334 | 0.664768 |
fda32d9ef88615859faf1c308e9468dde8a656a0 | 2,264 | py | Python | cgatpipelines/tools/pipeline_docs/pipeline_rrbs/trackers/rrbsReport.py | kevinrue/cgat-flow | 02b5a1867253c2f6fd6b4f3763e0299115378913 | [
"MIT"
]
| 49 | 2015-04-13T16:49:25.000Z | 2022-03-29T10:29:14.000Z | cgatpipelines/tools/pipeline_docs/pipeline_rrbs/trackers/rrbsReport.py | kevinrue/cgat-flow | 02b5a1867253c2f6fd6b4f3763e0299115378913 | [
"MIT"
]
| 252 | 2015-04-08T13:23:34.000Z | 2019-03-18T21:51:29.000Z | cgatpipelines/tools/pipeline_docs/pipeline_rrbs/trackers/rrbsReport.py | kevinrue/cgat-flow | 02b5a1867253c2f6fd6b4f3763e0299115378913 | [
"MIT"
]
| 22 | 2015-05-21T00:37:52.000Z | 2019-09-25T05:04:27.000Z | import re
from CGATReport.Tracker import *
from CGATReport.Utils import PARAMS as P
# get from config file
UCSC_DATABASE = "hg19"
EXPORTDIR = "export"
###################################################################
###################################################################
###################################################################
###################################################################
# Run configuration script
EXPORTDIR = P.get('exome_exportdir', P.get('exportdir', 'export'))
DATADIR = P.get('exome_datadir', P.get('datadir', '.'))
DATABASE = P.get('exome_backend', P.get('sql_backend', 'sqlite:///./csvdb'))
TRACKS = ['WTCHG_10997_01', 'WTCHG_10997_02']
###########################################################################
def splitLocus(locus):
if ".." in locus:
contig, start, end = re.match("(\S+):(\d+)\.\.(\d+)", locus).groups()
elif "-" in locus:
contig, start, end = re.match("(\S+):(\d+)\-(\d+)", locus).groups()
return contig, int(start), int(end)
def linkToUCSC(contig, start, end):
'''build URL for UCSC.'''
ucsc_database = UCSC_DATABASE
link = "`%(contig)s:%(start)i..%(end)i <http://genome.ucsc.edu/cgi-bin/hgTracks?db=%(ucsc_database)s&position=%(contig)s:%(start)i..%(end)i>`_" \
% locals()
return link
###########################################################################
class RrbsTracker(TrackerSQL):
'''Define convenience tracks for plots'''
def __init__(self, *args, **kwargs):
TrackerSQL.__init__(self, *args, backend=DATABASE, **kwargs)
class SingleTableHistogram(TrackerSQL):
columns = None
table = None
group_by = None
def __init__(self, *args, **kwargs):
TrackerSQL.__init__(self, *args, **kwargs)
def __call__(self, track, slice=None):
data = self.getAll("SELECT %(group_by)s, %(columns)s FROM %(table)s")
return data
class imagesTracker(TrackerImages):
'''Convience Tracker for globbing images for gallery plot'''
def __init__(self, *args, **kwargs):
Tracker.__init__(self, *args, **kwargs)
if "glob" not in kwargs:
raise ValueError("TrackerImages requires a:glob: parameter")
self.glob = kwargs["glob"]
| 31.444444 | 149 | 0.518993 | 849 | 0.375 | 0 | 0 | 0 | 0 | 0 | 0 | 1,036 | 0.457597 |
fda439b250b37d77743740f40f14e6a0ae152586 | 512 | py | Python | leetcode/python/985_sum_of_even_number_after_queries.py | VVKot/leetcode-solutions | 7d6e599b223d89a7861929190be715d3b3604fa4 | [
"MIT"
]
| 4 | 2019-04-22T11:57:36.000Z | 2019-10-29T09:12:56.000Z | leetcode/python/985_sum_of_even_number_after_queries.py | VVKot/coding-competitions | 7d6e599b223d89a7861929190be715d3b3604fa4 | [
"MIT"
]
| null | null | null | leetcode/python/985_sum_of_even_number_after_queries.py | VVKot/coding-competitions | 7d6e599b223d89a7861929190be715d3b3604fa4 | [
"MIT"
]
| null | null | null | from typing import List
class Solution:
def sumEvenAfterQueries(self,
A: List[int],
queries: List[List[int]]) -> List[int]:
even_sum = sum(num for num in A if not num & 1)
result = []
for val, idx in queries:
if not A[idx] & 1:
even_sum -= A[idx]
A[idx] += val
if not A[idx] & 1:
even_sum += A[idx]
result.append(even_sum)
return result
| 26.947368 | 67 | 0.451172 | 485 | 0.947266 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
fda4de20d32afa6769144964f3e6cd00599e20ed | 7,400 | py | Python | data.py | MicBrain/Laziness-Finder | 42f0a8c21ca80f81c540914b7fbe7d0491b5452b | [
"MIT"
]
| 3 | 2015-01-06T19:58:47.000Z | 2015-06-08T19:47:11.000Z | data.py | MicBrain/Laziness-Finder | 42f0a8c21ca80f81c540914b7fbe7d0491b5452b | [
"MIT"
]
| null | null | null | data.py | MicBrain/Laziness-Finder | 42f0a8c21ca80f81c540914b7fbe7d0491b5452b | [
"MIT"
]
| null | null | null | import csv
# Finding States' Laziness Rankings: #
dataDict = {}
with open('data.csv', 'rU') as csvfile:
dataReader = csv.reader(csvfile, delimiter=',')
for row in dataReader:
state = row[0]
row.pop(0)
dataDict[state] = row
projectedmeans = []
with open('rafadata.csv', 'rb') as csvfile:
dataReader = csv.reader(csvfile, delimiter=',')
for row in dataReader:
projectedmeans.append(row[0])
gdps = []
with open('gdp data.csv', 'rb') as csvfile:
dataReader = csv.reader(csvfile, delimiter=',')
for row in dataReader:
for letter in row[1]:
if letter == ',':
row[1].remove(letter)
gdps.append((row[0], float(row[1])))
gdps.sort(key=lambda x: x[0])
obesitylevels = []
with open('Obesity data.csv', 'rb') as csvfile:
dataReader = csv.reader(csvfile, delimiter=',')
for row in dataReader:
for letter in row[1]:
if letter == ',':
row[1].remove(letter)
obesitylevels.append((row[0], float(row[1])))
educationlevels = []
with open('education data.csv', 'rb') as csvfile:
dataReader = csv.reader(csvfile, delimiter=',')
for row in dataReader:
for letter in row[1]:
if letter == ',':
row[1].remove(letter)
educationlevels.append((row[0], float(row[1])))
educationlevels.sort(key=lambda x: x[0])
projectedmeans = map(float, projectedmeans)
meanlist = []
for i in dataDict:
i = [i]
meanlist.append(i)
index = 0
while index < 50:
meanlist[index].append(projectedmeans[index])
index +=1
# Add relevant information #
meanlist.sort(key=lambda x: x[0])
index = 0
while index<50:
meanlist[index].append(gdps[index][1])
meanlist[index].append(obesitylevels[index][1])
meanlist[index].append(educationlevels[index][1])
index +=1
meanlist.sort(key=lambda x: x[1], reverse= True)
# Adding rank to each state#
index = 0
rank = 10
n = 0
go = True
while go:
for i in range(0,5):
meanlist[index].insert(0, rank)
index +=1
rank -=1
if rank ==0:
go = False
#Finding your laziness ranking: #
answers = []
import os
os.system('clear')
print("Laziness Ranker Version 1.0")
print
print("Question 1")
print
print("Which of the following activities is your favorite?")
print
print("A. Going rock climbing.")
print("B. Gardening")
print("C. Hanging out with friends")
print("D. Playing GTA V")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 2")
print
print("If you saw a baby drowning in a pool, what would you do FIRST?")
print
print("A. Jump in immediately to save it.")
print("B. Make sure no one else is already diving in before saving it.")
print("C. Call 911")
print("D. Slowly put down your sweaty cheesburger and wipe the ketchup from your fingers before applying sun lotion to make sure you don't get burnt whilst saving the poor kid")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 3")
print
print("What is the reminder of 47/2?")
print
print("A. 1")
print("B. 47")
print("C. Can I phone a friend?")
print("D. I'm skipping this question.")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 4")
print
print("What's your favorite movie?")
print
print("A. Donnie Darko")
print("B. Inception")
print("C. The Avengers")
print("D. Anything with Adam Sandler.")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 5")
print
print("Approximately how much of your leisure time is spent doing physical activity?")
print
print("A. 80%")
print("B. 50%")
print("C. 30%")
print("D. 10%")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 6")
print
print("What would you do if someone ran by and snatched your purse/wallet?")
print
print("A. Trip the basterd.")
print("B. Run after the stealer.")
print("C. Call 911")
print("D. 'Eh. Wasn't that great of a wallet anyway.'")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 7")
print
print("What is your favorite nightly activity?")
print
print("A. Krav Maga.")
print("B. Taking the dog for a walk")
print("C. Watching TV")
print("D. Watching cat videos on Youtube")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 8")
print
print("Which item is closest to you at your desk in your room?")
print
print("A. Treadmill")
print("B. Stress ball")
print("C. Potato chips")
print("D. Everything is way too far away for my arm to reach.")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 9")
print
print("What's your favorite animal?")
print
print("A. Freakin' Tigers")
print("B. Hawks")
print("C. Turtles")
print("D. Sloths")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
os.system('clear')
print
print("Question 10")
print
print("Why are we here?")
print
print("A. To understand our world, and help each other out at the same time")
print("B. To eat and mate.")
print("C. It's way too early in the morning for this type of question.")
print("D. It's way too late in the evening for this type of question.")
print
answer = raw_input("Please enter the letter of your answer here: ").lower()
answers.append(answer)
def score(inputlist):
total = 0
for i in inputlist:
if i=='a':
total += 4
elif i =='b':
total += 3
elif i =='c':
total += 2
elif i =='d':
total += 1
return total
def rank(score):
if score<=13:
return 10
elif score>13 and score<=16:
return 9
elif score>16 and score<=19:
return 8
elif score>19 and score<=22:
return 7
elif score>22 and score<=25:
return 6
elif score>25 and score<=28:
return 5
elif score>28 and score<=31:
return 4
elif score>31 and score<=34:
return 3
elif score>34 and score<=37:
return 2
elif score>37:
return 1
rank = rank(score(answers))
# Matching you with a group of states #
def correctstate(somelist):
if somelist[0]==rank:
return True
else:
return False
yourstates1 = filter(correctstate, meanlist)
yourstates = []
index = 0
while index<len(yourstates1):
yourstates.append(yourstates1[index])
index +=1
def returnstates(listvalues, index):
print
print listvalues[index][1]
print
print("GDP per Capita: $" + str(listvalues[index][3]))
print("Obesity percentage: " + str(listvalues[index][4]) + "%")
print("Education ranking (out of 100): " + str(listvalues[index][5]))
os.system('clear')
print("Based on your level of physical activity, we suggest you move to one of these states:")
print
returnstates(yourstates, 0)
returnstates(yourstates, 1)
returnstates(yourstates, 2)
returnstates(yourstates, 3)
returnstates(yourstates, 4) | 24.749164 | 177 | 0.672973 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,766 | 0.373784 |
fda704c8c3598728280ac25d245978289f33459f | 1,540 | py | Python | camera/start.py | IbrahimAhmad65/pythonApp | 76c6e2a6de48d34b034bfc0e045cc345b90bf45c | [
"MIT"
]
| null | null | null | camera/start.py | IbrahimAhmad65/pythonApp | 76c6e2a6de48d34b034bfc0e045cc345b90bf45c | [
"MIT"
]
| null | null | null | camera/start.py | IbrahimAhmad65/pythonApp | 76c6e2a6de48d34b034bfc0e045cc345b90bf45c | [
"MIT"
]
| null | null | null | #/bin/python3
import numpy as np
from PIL import Image
def processbad(array):
#arr = np.zeros([array.size(),array[0].size(),array[0][0].size])
arr = np.zeros([int(np.size(array)/8),
int(np.size(array[0])/8),3],
dtype=np.byte)
# print (arr)
counter = 0
count = 0
for i in array:
for b in i:
array[counter][count][0] = b[0]
array[counter][count][1] = b[1]
array[counter][count][2] = b[2]
count +=1
counter +=1
image = Image.fromarray(arr)
return image
def process(img, red, green, blue):
array = np.array(img)# [widthxheightxpixels]
r = array[:,:,0]
g = array[:,:,1]
b = array[:,:,2]
return np.logical_and(np.logical_not(np.ma.masked_equal(r, red).mask), np.logical_and(np.logical_not(np.ma.masked_equal(b, blue).mask), (np.logical_not(np.ma.masked_equal(g, green).mask))))
#return np.ma.masked_equal(r,0)
counter = 0
count = 0
for i in array:
for b in i:
if(b[0] < 1 and b[1] < 1 and b[2] < 1):
array[counter][count] = [255,255,255,255]
#print(b)
else:
array[counter][count] = [0,0,0,255]
count +=1
counter +=1
count = 0
image = Image.fromarray(array)
return image
img = Image.open('checker.png')
#array = 255 - array
#invimg = Image.fromarray(array)
#invimg.save('testgrey-inverted.png')
img = Image.fromarray(process(img,0,0,0))
img.save("newchecker.png")
| 26.101695 | 193 | 0.555844 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 275 | 0.178571 |
fda7b7ab5e740804c9088eb3b79d539461e5afae | 1,290 | py | Python | esque/cli/commands/edit/topic.py | real-digital/esque | 0b779fc308ce8bce45c1903f36c33664b2e832e7 | [
"MIT"
]
| 29 | 2019-05-10T21:12:38.000Z | 2021-08-24T08:09:49.000Z | esque/cli/commands/edit/topic.py | real-digital/esque | 0b779fc308ce8bce45c1903f36c33664b2e832e7 | [
"MIT"
]
| 103 | 2019-05-17T07:21:41.000Z | 2021-12-02T08:29:00.000Z | esque/cli/commands/edit/topic.py | real-digital/esque | 0b779fc308ce8bce45c1903f36c33664b2e832e7 | [
"MIT"
]
| 2 | 2019-05-28T06:45:14.000Z | 2019-11-21T00:33:15.000Z | import click
from esque import validation
from esque.cli.autocomplete import list_topics
from esque.cli.helpers import edit_yaml, ensure_approval
from esque.cli.options import State, default_options
from esque.cli.output import pretty_topic_diffs
from esque.resources.topic import copy_to_local
@click.command("topic")
@click.argument("topic-name", required=True, autocompletion=list_topics)
@default_options
def edit_topic(state: State, topic_name: str):
"""Edit a topic.
Open the topic's configuration in the default editor. If the user saves upon exiting the editor,
all the given changes will be applied to the topic.
"""
controller = state.cluster.topic_controller
topic = state.cluster.topic_controller.get_cluster_topic(topic_name)
_, new_conf = edit_yaml(topic.to_yaml(only_editable=True), validator=validation.validate_editable_topic_config)
local_topic = copy_to_local(topic)
local_topic.update_from_dict(new_conf)
diff = controller.diff_with_cluster(local_topic)
if not diff.has_changes:
click.echo("Nothing changed.")
return
click.echo(pretty_topic_diffs({topic_name: diff}))
if ensure_approval("Are you sure?"):
controller.alter_configs([local_topic])
else:
click.echo("Canceled!")
| 34.864865 | 115 | 0.762016 | 0 | 0 | 0 | 0 | 991 | 0.768217 | 0 | 0 | 245 | 0.189922 |
fda80efdae2846a2b9845cad8f9cce0c191ea1d2 | 134 | py | Python | euporie/__main__.py | joouha/euporie | 7f1cf9a3b4061b662c1e56b16a3a8883bd50e315 | [
"MIT"
]
| 505 | 2021-05-08T22:52:19.000Z | 2022-03-31T15:52:43.000Z | euporie/__main__.py | joouha/euporie | 7f1cf9a3b4061b662c1e56b16a3a8883bd50e315 | [
"MIT"
]
| 19 | 2021-05-09T09:06:40.000Z | 2022-03-26T14:49:35.000Z | euporie/__main__.py | joouha/euporie | 7f1cf9a3b4061b662c1e56b16a3a8883bd50e315 | [
"MIT"
]
| 16 | 2021-05-09T00:07:14.000Z | 2022-03-28T09:16:11.000Z | # -*- coding: utf-8 -*-
"""Main entry point into euporie."""
from euporie.app import App
if __name__ == "__main__":
App.launch()
| 19.142857 | 36 | 0.634328 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 69 | 0.514925 |
fda8d40081b9fb4ec44129fb7abfaa7410ce0508 | 9,535 | py | Python | robocorp-python-ls-core/src/robocorp_ls_core/pluginmanager.py | anton264/robotframework-lsp | 6f8f89b88ec56b767f6d5e9cf0d3fb58847e5844 | [
"ECL-2.0",
"Apache-2.0"
]
| 92 | 2020-01-22T22:15:29.000Z | 2022-03-31T05:19:16.000Z | robocorp-python-ls-core/src/robocorp_ls_core/pluginmanager.py | anton264/robotframework-lsp | 6f8f89b88ec56b767f6d5e9cf0d3fb58847e5844 | [
"ECL-2.0",
"Apache-2.0"
]
| 604 | 2020-01-25T17:13:27.000Z | 2022-03-31T18:58:24.000Z | robocorp-python-ls-core/src/robocorp_ls_core/pluginmanager.py | anton264/robotframework-lsp | 6f8f89b88ec56b767f6d5e9cf0d3fb58847e5844 | [
"ECL-2.0",
"Apache-2.0"
]
| 39 | 2020-02-06T00:38:06.000Z | 2022-03-15T06:14:19.000Z | # Original work Copyright 2018 Brainwy Software Ltda (Dual Licensed: LGPL / Apache 2.0)
# From https://github.com/fabioz/pyvmmonitor-core
# See ThirdPartyNotices.txt in the project root for license information.
# All modifications Copyright (c) Robocorp Technologies Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Defines a PluginManager (which doesn't really have plugins, only a registry of extension points
and implementations for such extension points).
To use, create the extension points you want (any class starting with 'EP') and register
implementations for those.
I.e.:
pm = PluginManager()
pm.register(EPFoo, FooImpl, keep_instance=True)
pm.register(EPBar, BarImpl, keep_instance=False)
Then, later, to use it, it's possible to ask for instances through the PluginManager API:
foo_instances = pm.get_implementations(EPFoo) # Each time this is called, new
# foo_instances will be created
bar_instance = pm.get_instance(EPBar) # Each time this is called, the same bar_instance is returned.
Alternatively, it's possible to use a decorator to use a dependency injection pattern -- i.e.:
don't call me, I'll call you ;)
@inject(foo_instance=EPFoo, bar_instances=[EPBar])
def m1(foo_instance, bar_instances, pm):
for bar in bar_instances:
...
foo_instance.foo
"""
import functools
from pathlib import Path
from typing import TypeVar, Any, Dict, Type, Tuple, Optional, Union
def execfile(file, glob=None, loc=None):
import tokenize
with tokenize.open(file) as stream:
contents = stream.read()
exec(compile(contents + "\n", file, "exec"), glob, loc)
class NotInstanceError(RuntimeError):
pass
class NotRegisteredError(RuntimeError):
pass
class InstanceAlreadyRegisteredError(RuntimeError):
pass
T = TypeVar("T")
class PluginManager(object):
"""
This is a manager of plugins (which we refer to extension points and implementations).
Mostly, we have a number of EPs (Extension Points) and implementations may be registered
for those extension points.
The PluginManager is able to provide implementations (through #get_implementations) which are
not kept on being tracked and a special concept which keeps an instance alive for an extension
(through #get_instance).
"""
def __init__(self) -> None:
self._ep_to_impls: Dict[Type, list] = {}
self._ep_to_instance_impls: Dict[Tuple[Type, Optional[str]], list] = {}
self._ep_to_context_to_instance: Dict[Type, dict] = {}
self._name_to_ep: Dict[str, Type] = {}
self.exited = False
def load_plugins_from(self, directory: Path) -> int:
found_files_with_plugins = 0
filepath: Path
for filepath in directory.iterdir():
if filepath.is_file() and filepath.name.endswith(".py"):
namespace: dict = {"__file__": str(filepath)}
execfile(str(filepath), glob=namespace, loc=namespace)
register_plugins = namespace.get("register_plugins")
if register_plugins is not None:
found_files_with_plugins += 1
register_plugins(self)
return found_files_with_plugins
# This should be:
# def get_implementations(self, ep: Type[T]) -> List[T]:
# But isn't due to: https://github.com/python/mypy/issues/5374
def get_implementations(self, ep: Union[Type, str]) -> list:
assert not self.exited
if isinstance(ep, str):
ep = self._name_to_ep[ep]
impls = self._ep_to_impls.get(ep, [])
ret = []
for class_, kwargs in impls:
instance = class_(**kwargs)
ret.append(instance)
return ret
def register(
self,
ep: Type,
impl,
kwargs: Optional[dict] = None,
context: Optional[str] = None,
keep_instance: bool = False,
):
"""
:param ep:
:param str impl:
This is the full path to the class implementation.
:param kwargs:
:param context:
If keep_instance is True, it's possible to register it for a given
context.
:param keep_instance:
If True, it'll be only available through pm.get_instance and the
instance will be kept for further calls.
If False, it'll only be available through get_implementations.
"""
if kwargs is None:
kwargs = {}
assert not self.exited
if isinstance(ep, str):
raise ValueError("Expected the actual EP class to be passed.")
self._name_to_ep[ep.__name__] = ep
if keep_instance:
ep_to_instance_impls = self._ep_to_instance_impls
impls = ep_to_instance_impls.get((ep, context))
if impls is None:
impls = ep_to_instance_impls[(ep, context)] = []
else:
raise InstanceAlreadyRegisteredError(
"Unable to override when instance is kept and an implementation "
"is already registered."
)
else:
ep_to_impl = self._ep_to_impls
impls = ep_to_impl.get(ep)
if impls is None:
impls = ep_to_impl[ep] = []
impls.append((impl, kwargs))
def set_instance(self, ep: Type, instance, context=None) -> None:
if isinstance(ep, str):
raise ValueError("Expected the actual EP class to be passed.")
self._name_to_ep[ep.__name__] = ep
instances = self._ep_to_context_to_instance.get(ep)
if instances is None:
instances = self._ep_to_context_to_instance[ep] = {}
instances[context] = instance
def iter_existing_instances(self, ep: Union[Type, str]):
if isinstance(ep, str):
ep = self._name_to_ep[ep]
return self._ep_to_context_to_instance[ep].values()
def has_instance(self, ep: Union[Type, str], context=None):
if isinstance(ep, str):
ep_cls = self._name_to_ep.get(ep)
if ep_cls is None:
return False
try:
self.get_instance(ep, context)
return True
except NotRegisteredError:
return False
# This should be:
# def get_instance(self, ep: Type[T], context=None) -> T:
# But isn't due to: https://github.com/python/mypy/issues/5374
def get_instance(self, ep: Union[Type, str], context: Optional[str] = None) -> Any:
"""
Creates an instance in this plugin manager: Meaning that whenever a new EP is asked in
the same context it'll receive the same instance created previously (and it'll be
kept alive in the plugin manager).
"""
if self.exited:
raise AssertionError("PluginManager already exited")
if isinstance(ep, str):
ep = self._name_to_ep[ep]
try:
return self._ep_to_context_to_instance[ep][context]
except KeyError:
try:
impls = self._ep_to_instance_impls[(ep, context)]
except KeyError:
found = False
if context is not None:
found = True
try:
impls = self._ep_to_instance_impls[(ep, None)]
except KeyError:
found = False
if not found:
if ep in self._ep_to_impls:
# Registered but not a kept instance.
raise NotInstanceError()
else:
# Not registered at all.
raise NotRegisteredError()
assert len(impls) == 1
class_, kwargs = impls[0]
instances = self._ep_to_context_to_instance.get(ep)
if instances is None:
instances = self._ep_to_context_to_instance[ep] = {}
ret = instances[context] = class_(**kwargs)
return ret
__getitem__ = get_instance
def exit(self):
self.exited = True
self._ep_to_context_to_instance.clear()
self._ep_to_impls.clear()
def inject(**inject_kwargs):
def decorator(func):
@functools.wraps(func)
def inject_dec(*args, **kwargs):
pm = kwargs.get("pm")
if pm is None:
raise AssertionError(
"pm argument with PluginManager not passed (required for @inject)."
)
for key, val in inject_kwargs.items():
if key not in kwargs:
if val.__class__ is list:
kwargs[key] = pm.get_implementations(val[0])
else:
kwargs[key] = pm.get_instance(val)
return func(*args, **kwargs)
return inject_dec
return decorator
| 35.446097 | 100 | 0.607971 | 6,562 | 0.688201 | 0 | 0 | 599 | 0.062821 | 0 | 0 | 3,759 | 0.394232 |
fdaa4e938b8821b9a6f605b0dbe6cbeea3d62940 | 25 | py | Python | version.py | vignesh1793/gmail_reader | 8bcf8dbc4e839e8eb736c1ae2fef9fd4f9f77ded | [
"MIT"
]
| 1 | 2020-07-29T03:35:26.000Z | 2020-07-29T03:35:26.000Z | version.py | thevickypedia/gmail_reader | 8bcf8dbc4e839e8eb736c1ae2fef9fd4f9f77ded | [
"MIT"
]
| null | null | null | version.py | thevickypedia/gmail_reader | 8bcf8dbc4e839e8eb736c1ae2fef9fd4f9f77ded | [
"MIT"
]
| null | null | null | version_info = (0, 5, 2)
| 12.5 | 24 | 0.6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
fdab78fe2c0240156557e76473319683d8e4d96e | 291 | py | Python | hippynn/interfaces/__init__.py | tautomer/hippynn | df4504a5ea4680cfc61f490984dcddeac7ed99ee | [
"BSD-3-Clause"
]
| 21 | 2021-11-17T00:56:35.000Z | 2022-03-22T05:57:11.000Z | hippynn/interfaces/__init__.py | tautomer/hippynn | df4504a5ea4680cfc61f490984dcddeac7ed99ee | [
"BSD-3-Clause"
]
| 4 | 2021-12-17T16:16:53.000Z | 2022-03-16T23:50:38.000Z | hippynn/interfaces/__init__.py | tautomer/hippynn | df4504a5ea4680cfc61f490984dcddeac7ed99ee | [
"BSD-3-Clause"
]
| 6 | 2021-11-30T21:09:31.000Z | 2022-03-18T07:07:32.000Z | """
``hippynn`` currently has interfaces to the following other codes:
1. ``ase`` for atomic simulation
2. ``pyseqm`` for combined ML-seqm models
3. ``schnetpack`` for usage of schnet models in ``hippynn``.
This subpackage is not available by default; you must import it explicitly.
"""
| 24.25 | 75 | 0.721649 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 290 | 0.996564 |
fdac411261e3837a075f2bf9d23c9a72e80c187a | 459 | py | Python | code/data_owner_1/get_connection.py | ClarkYan/msc-thesis | c4fbd901c2664aa7140e5e82fb322ed0f578761a | [
"Apache-2.0"
]
| 7 | 2017-11-05T08:22:51.000Z | 2021-09-14T19:34:30.000Z | code/data_owner_1/get_connection.py | ClarkYan/msc-thesis | c4fbd901c2664aa7140e5e82fb322ed0f578761a | [
"Apache-2.0"
]
| 1 | 2021-02-27T07:24:50.000Z | 2021-04-24T03:29:12.000Z | code/data_owner_1/get_connection.py | ClarkYan/msc-thesis | c4fbd901c2664aa7140e5e82fb322ed0f578761a | [
"Apache-2.0"
]
| 3 | 2019-04-15T03:22:22.000Z | 2022-03-12T11:27:39.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Author: ClarkYAN -*-
import requests
def set_up_connection(url, sender):
# files = {'dataset': open(filename, 'rb')}
user_info = {'name': sender}
r = requests.post(url, data=user_info, headers={'Connection': 'close'})
if r.text == "success":
conn_result = sender, "connect to the cloud"
else:
conn_result = sender, "cannot connect to the cloud"
return conn_result
| 27 | 75 | 0.625272 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 198 | 0.431373 |
fdad3ab7cf57f8eea008adff9a2f0ea59bd908a4 | 1,553 | py | Python | signup_instagram.py | cnfreitax/all_scrapers | 35597cd3845c64b589cb2937ea7ea70ea4cd3286 | [
"Apache-2.0"
]
| null | null | null | signup_instagram.py | cnfreitax/all_scrapers | 35597cd3845c64b589cb2937ea7ea70ea4cd3286 | [
"Apache-2.0"
]
| null | null | null | signup_instagram.py | cnfreitax/all_scrapers | 35597cd3845c64b589cb2937ea7ea70ea4cd3286 | [
"Apache-2.0"
]
| null | null | null | """
use of script to create the login method
use a fake account!
"""
from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup as bs
class Login:
def __init__(self, email, password, idPage):
self.browser = webdriver.Chrome('/home/ekoar/chromedriver')
self.email = email
self.password = password
self.idPage = idPage
def signup(self, url):
self.browser.get(url)
sleep(0.5)
emailInput = self.browser.find_element_by_xpath('//input[@class = "_2hvTZ pexuQ zyHYP"]')
passwordInput = self.browser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[3]/div/label/input')
emailInput.send_keys(self.email)
sleep(0.2)
passwordInput.send_keys(self.password)
button = self.browser.find_element_by_xpath('//button[@class = "sqdOP L3NKy y3zKF "]').click()
sleep(4)
buttonpu = self.browser.find_element_by_xpath('//button[@class = "aOOlW HoLwm "]').click()
def searchPage(self):
buttonFind = self.browser.find_element_by_xpath('//input[@class = "XTCLo x3qfX "]')
buttonFind.send_keys(self.idPage)
sleep(0.9)
resultSearch = self.browser.find_element_by_xpath('//a[@class = "yCE8d "]').click()
def scraper(self):
lista_links = []
bsObj = bs(self.browser.page_source, 'html.parser')
sleep(3)
publicacoes = bsObj.find_all('div', {'class':'Nnq7C weEfm'})
lista_links.append(publicacoes)
| 35.295455 | 151 | 0.647778 | 1,391 | 0.895686 | 0 | 0 | 0 | 0 | 0 | 0 | 407 | 0.262073 |
fdad5082e78e4cecb0dc06f0019827b83dac2415 | 4,699 | py | Python | ntee/utils/model_reader.py | AdityaAS/PyTorch_NTEE | a1dc5cc6cd22fc9de3f054fa35f50b975bae75ce | [
"MIT"
]
| 1 | 2019-01-15T11:21:08.000Z | 2019-01-15T11:21:08.000Z | ntee/utils/model_reader.py | AdityaAS/PyTorch_NTEE | a1dc5cc6cd22fc9de3f054fa35f50b975bae75ce | [
"MIT"
]
| null | null | null | ntee/utils/model_reader.py | AdityaAS/PyTorch_NTEE | a1dc5cc6cd22fc9de3f054fa35f50b975bae75ce | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
import joblib
import torch
import numpy as np
from ntee.utils.my_tokenizer import RegexpTokenizer
from ntee.utils.vocab_joint import JointVocab
from ntee.utils.vocab import Vocab
class ModelReader(object):
def __init__(self, model_file):
model = joblib.load(model_file, mmap_mode='r')
self._word_embedding = model['word_embedding']
self._entity_embedding = model['entity_embedding']
self._W = model.get('W')
self._b = model.get('b')
self._vocab = model.get('vocab')
self._tokenizer = RegexpTokenizer()
@property
def vocab(self):
return self._vocab
@property
def word_embedding(self):
return self._word_embedding
@property
def entity_embedding(self):
return self._entity_embedding
@property
def W(self):
return self._W
@property
def b(self):
return self._b
def get_word_vector(self, word, default=None):
index = self._vocab.get_word_index(word)
if index:
return self.word_embedding[index]
else:
return default
def get_entity_vector(self, title, default=None):
index = self._vocab.get_entity_index(title)
if index:
return self.entity_embedding[index]
else:
return default
def get_text_vector(self, text):
vectors = [self.get_word_vector(t.text.lower())
for t in self._tokenizer.tokenize(text)]
vectors = [v for v in vectors if v is not None]
if not vectors:
return None
ret = np.mean(vectors, axis=0)
ret = np.dot(ret, self._W)
ret += self._b
ret /= np.linalg.norm(ret, 2)
return ret
class PyTorchModelReader(object):
def __init__(self, model_file, vocab_file, modelname, cpuflag=False):
model = torch.load(model_file)
if cpuflag: #CPU Tensors
self._word_embedding = model['word_embedding.weight'].cpu()
self._entity_embedding = model['entity_embedding.weight'].cpu()
if modelname.lower() == 'ntee':
self._vocab = Vocab.load(vocab_file)
else:
self._relation_embedding = model['relation_embedding.weight'].cpu()
self._vocab = JointVocab.load(vocab_file)
self._W = model.get('W').cpu()
self._b = model.get('b').cpu()
else: #GPU Tensors
self._word_embedding = model['word_embedding.weight']
self._entity_embedding = model['entity_embedding.weight']
if modelname.lower() == 'ntee':
self._vocab = Vocab.load(vocab_file)
else:
self._relation_embedding = model['relation_embedding.weight']
self._vocab = JointVocab.load(vocab_file)
self._W = model.get('W')
self._b = model.get('b')
self._tokenizer = RegexpTokenizer()
@property
def vocab(self):
return self._vocab
@property
def word_embedding(self):
return self._word_embedding
@property
def entity_embedding(self):
return self._entity_embedding
@property
def relation_embedding(self):
return self._relation_embedding
@property
def W(self):
return self._W
@property
def b(self):
return self._b
def get_word_vector(self, word, default=None):
index = self._vocab.get_word_index(word)
if index:
return self.word_embedding[index]
else:
return default
def get_entity_vector(self, title, default=None):
index = self._vocab.get_entity_index(title)
if index:
return self.entity_embedding[index]
else:
return default
def get_text_vector(self, text):
vectors = [self.get_word_vector(t.text.lower())
for t in self._tokenizer.tokenize(text)]
vectors = [v for v in vectors if v is not None]
# vectors_numpy = [v.cpu().numpy() for v in vectors if v is not None]
# ret_numpy = np.mean(vectors_numpy, axis=0)
# ret_numpy = np.dot(ret_numpy, self._W.cpu().numpy())
# ret_numpy += self._b.cpu().numpy()
# ret_numpy /= np.linalg.norm(ret_numpy, 2)
# return ret_numpy
if not vectors:
return None
ret = torch.zeros(vectors[0].shape)
for v in vectors:
ret += v
ret = ret / len(vectors)
ret = torch.matmul(ret, self._W)
ret += self._b
ret /= torch.norm(ret, 2)
return ret
| 27.970238 | 83 | 0.589062 | 4,491 | 0.955735 | 0 | 0 | 701 | 0.149181 | 0 | 0 | 535 | 0.113854 |
fdae4d589a0bfe5706d084ebb885895cfa2070d3 | 1,479 | py | Python | setup.py | polishmatt/sputr | 7611d40090c8115dff69912725efc506414ac47a | [
"MIT"
]
| 1 | 2017-02-13T23:09:18.000Z | 2017-02-13T23:09:18.000Z | setup.py | polishmatt/sputr | 7611d40090c8115dff69912725efc506414ac47a | [
"MIT"
]
| 6 | 2017-02-18T20:14:32.000Z | 2017-09-27T19:07:06.000Z | setup.py | polishmatt/sputr | 7611d40090c8115dff69912725efc506414ac47a | [
"MIT"
]
| null | null | null | from setuptools import setup
import importlib
version = importlib.import_module('sputr.config').version
setup(
name='sputr',
version=version,
description='Simple Python Unit Test Runner',
long_description="An intuitive command line and Python package interface for Python's unit testing framework.",
author='Matt Wisniewski',
author_email='[email protected]',
license='MIT',
url='https://github.com/polishmatt/sputr',
keywords=['testing'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
platforms=['unix','linux'],
packages=[
'sputr'
],
install_requires=[
'click==6.7'
],
entry_points={
'console_scripts': [
'sputr = sputr.cli:cli'
],
},
)
| 31.468085 | 115 | 0.597025 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 896 | 0.605815 |
fdb047a38cb8eadeccbc08314dec72d4acb12c4f | 1,820 | py | Python | tools/malloc-exp/plot-histogram.py | scottviteri/verified-betrfs | 7af56c8acd943880cb19ba16d146c6a206101d9b | [
"BSD-2-Clause"
]
| 15 | 2021-05-11T09:19:12.000Z | 2022-03-14T10:39:05.000Z | tools/malloc-exp/plot-histogram.py | scottviteri/verified-betrfs | 7af56c8acd943880cb19ba16d146c6a206101d9b | [
"BSD-2-Clause"
]
| 3 | 2021-06-07T21:45:13.000Z | 2021-11-29T23:19:59.000Z | tools/malloc-exp/plot-histogram.py | scottviteri/verified-betrfs | 7af56c8acd943880cb19ba16d146c6a206101d9b | [
"BSD-2-Clause"
]
| 7 | 2021-05-11T17:08:04.000Z | 2022-02-23T07:19:36.000Z | #!/usr/bin/env python3
# Copyright 2018-2021 VMware, Inc., Microsoft Inc., Carnegie Mellon University, ETH Zurich, and University of Washington
# SPDX-License-Identifier: BSD-2-Clause
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import re
#import json
def parse_one_histogram(line):
#return json.loads(line)
assert line[0] == "{"
assert line[-2:] == "}\n"
line = line[1:-2]
pairs = line.split(",")[:-1]
histo = {}
for pair in pairs:
size,count = map(int, pair.split(":"))
if count>0:
histo[size] = count
return histo
def cdf(histo, by_size):
sizes = list(histo.keys())
sizes.sort()
xs = []
ys = []
accum = 0
for size in sizes:
count = histo[size]
accum += count * size if by_size else count
xs.append(size)
ys.append(accum)
#print(xs)
# normalize ys to 0..1
ys = [y/float(accum) for y in ys]
#print(ys)
return xs, ys
def parse():
t = 0
proc_heap = {}
malloc_total = {}
histos = {}
for line in open("malloc-exp/histograms", "r").readlines():
if line.startswith("proc-heap"):
fields = line.split()
proc_heap[t] = int(fields[1])
malloc_total[t] = int(fields[3])
t += 1
if line.startswith("{"):
histos[t] = parse_one_histogram(line)
max_histo_t = max(histos.keys())
print(max_histo_t)
max_histo = histos[max_histo_t]
print(max_histo)
# accumulate the CDF
line, = plt.plot(*cdf(max_histo, True))
line.set_label("by size")
line, = plt.plot(*cdf(max_histo, False))
line.set_label("by allocation count")
plt.xscale("log")
plt.legend()
plt.savefig("malloc-exp/size-cdf.png")
#plt.show()
parse()
| 24.594595 | 120 | 0.581868 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 404 | 0.221978 |
fdb1f945768c5695ac9336664448e0864ebfec52 | 4,587 | py | Python | oy/models/mixins/polymorphic_prop.py | mush42/oy-cms | 66f2490be7eab9a692a68bb635099ba21d5944ae | [
"MIT"
]
| 5 | 2019-02-12T08:54:46.000Z | 2021-03-15T09:22:44.000Z | oy/models/mixins/polymorphic_prop.py | mush42/oy-cms | 66f2490be7eab9a692a68bb635099ba21d5944ae | [
"MIT"
]
| 2 | 2020-04-30T01:27:08.000Z | 2020-07-16T18:04:16.000Z | oy/models/mixins/polymorphic_prop.py | mush42/oy-cms | 66f2490be7eab9a692a68bb635099ba21d5944ae | [
"MIT"
]
| 3 | 2019-10-16T05:53:31.000Z | 2021-10-11T09:37:16.000Z | # -*- coding: utf-8 -*-
"""
oy.models.mixins.polymorphic_prop
~~~~~~~~~~
Provides helper mixin classes for special sqlalchemy models
:copyright: (c) 2018 by Musharraf Omer.
:license: MIT, see LICENSE for more details.
"""
import sqlalchemy.types as types
from sqlalchemy import literal_column, event
from sqlalchemy.orm.interfaces import PropComparator
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.declarative import declared_attr
from oy.boot.sqla import db
class ProxiedDictMixin(object):
"""Adds obj[key] access to a mapped class.
This class basically proxies dictionary access to an attribute
called ``_proxied``. The class which inherits this class
should have an attribute called ``_proxied`` which points to a dictionary.
"""
def __len__(self):
return len(self._proxied)
def __iter__(self):
return iter(self._proxied)
def __getitem__(self, key):
return self._proxied[key]
def __contains__(self, key):
return key in self._proxied
def get(self, key):
return self._proxied.get(key)
def __setitem__(self, key, value):
self._proxied[key] = value
def __delitem__(self, key):
del self._proxied[key]
class ImmutableProxiedDictMixin(ProxiedDictMixin):
"""Like :class:`ProxiedDictMixin` but disables the addition of
new keys and deletion of existing ones
"""
def __setitem__(self, key, value):
if key not in self._proxied:
raise AttributeError("Cann't Set Attribute")
self._proxied[key] = value
def __delitem__(self, key):
raise AttributeError("Deleting is not allowed")
class PolymorphicVerticalProperty(object):
"""A key/value pair with polymorphic value storage.
The class which is mapped should indicate typing information
within the "info" dictionary of mapped Column objects.
"""
def __init__(self, key=None, value=None):
self.key = key
self.value = value
@hybrid_property
def value(self):
fieldname, discriminator = self.type_map[self.type]
if fieldname is None:
return None
else:
return getattr(self, fieldname)
@value.setter
def value(self, value):
py_type = type(value)
fieldname, discriminator = self.type_map[py_type]
self.type = discriminator
if fieldname is not None:
setattr(self, fieldname, value)
@value.deleter
def value(self):
self._set_value(None)
@value.comparator
class value(PropComparator):
"""A comparator for .value, builds a polymorphic comparison via CASE.
"""
def __init__(self, cls):
self.cls = cls
def _case(self):
pairs = set(self.cls.type_map.values())
whens = [
(
literal_column("'%s'" % discriminator),
cast(getattr(self.cls, attribute), String),
)
for attribute, discriminator in pairs
if attribute is not None
]
return case(whens, self.cls.type, null())
def __eq__(self, other):
return self._case() == cast(other, String)
def __ne__(self, other):
return self._case() != cast(other, String)
def __repr__(self):
return "<%s %r>" % (self.__class__.__name__, self.value)
@event.listens_for(PolymorphicVerticalProperty, "mapper_configured", propagate=True)
def on_new_class(mapper, cls_):
"""Look for Column objects with type info in them, and work up
a lookup table.
"""
info_dict = {}
info_dict[type(None)] = (None, "none")
info_dict["none"] = (None, "none")
for k in mapper.c.keys():
col = mapper.c[k]
if "type" in col.info:
python_type, discriminator = col.info["type"]
if type(python_type) in (list, tuple):
for pty in python_type:
info_dict[pty] = (k, discriminator)
else:
info_dict[python_type] = (k, discriminator)
info_dict[discriminator] = (k, discriminator)
cls_.type_map = info_dict
class DynamicProp(PolymorphicVerticalProperty):
key = db.Column(db.String(128), nullable=False)
type = db.Column(db.String(64))
int_value = db.Column(db.Integer, info={"type": (int, "integer")})
str_value = db.Column(db.Unicode(5120), info={"type": (str, "string")})
bool_value = db.Column(db.Boolean, info={"type": (bool, "boolean")})
| 29.785714 | 84 | 0.625681 | 3,294 | 0.718116 | 0 | 0 | 2,089 | 0.455417 | 0 | 0 | 1,126 | 0.245476 |
fdb2d4c9f5001e0fbebe90b3cb11e75763d20dd3 | 1,735 | py | Python | tests/extensions/aria_extension_tosca/conftest.py | tnadeau/incubator-ariatosca | de32028783969bc980144afa3c91061c7236459c | [
"Apache-2.0"
]
| null | null | null | tests/extensions/aria_extension_tosca/conftest.py | tnadeau/incubator-ariatosca | de32028783969bc980144afa3c91061c7236459c | [
"Apache-2.0"
]
| null | null | null | tests/extensions/aria_extension_tosca/conftest.py | tnadeau/incubator-ariatosca | de32028783969bc980144afa3c91061c7236459c | [
"Apache-2.0"
]
| 1 | 2020-06-16T15:13:06.000Z | 2020-06-16T15:13:06.000Z | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
PyTest configuration module.
Add support for a "--tosca-parser" CLI option.
For more information on PyTest hooks, see the `PyTest documentation
<https://docs.pytest.org/en/latest/writing_plugins.html#pytest-hook-reference>`__.
"""
import pytest
from ...mechanisms.parsing.aria import AriaParser
def pytest_addoption(parser):
parser.addoption('--tosca-parser', action='store', default='aria', help='TOSCA parser')
def pytest_report_header(config):
tosca_parser = config.getoption('--tosca-parser')
return 'tosca-parser: {0}'.format(tosca_parser)
@pytest.fixture(scope='session')
def parser(request):
tosca_parser = request.config.getoption('--tosca-parser')
verbose = request.config.getoption('verbose') > 0
if tosca_parser == 'aria':
with AriaParser() as p:
p.verbose = verbose
yield p
else:
pytest.fail('configured tosca-parser not supported: {0}'.format(tosca_parser))
| 35.408163 | 91 | 0.736023 | 0 | 0 | 348 | 0.200576 | 381 | 0.219597 | 0 | 0 | 1,165 | 0.67147 |
fdb6180fad4a97a9bd7fd4c10c96bb8a853e03d5 | 5,487 | py | Python | tests/test_project.py | eruber/py_project_template | f0b12ab603e1277943f0323cbd0d8fb86fd04861 | [
"MIT"
]
| null | null | null | tests/test_project.py | eruber/py_project_template | f0b12ab603e1277943f0323cbd0d8fb86fd04861 | [
"MIT"
]
| null | null | null | tests/test_project.py | eruber/py_project_template | f0b12ab603e1277943f0323cbd0d8fb86fd04861 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test Project Template
The code below is derived from several locations:
REFERENCES:
REF1: https://docs.pytest.org/en/latest/contents.html
REF2: https://github.com/hackebrot/pytest-cookies
LOCATIONS
LOC1: https://github.com/audreyr/cookiecutter-pypackage
LOC2: https://github.com/mdklatt/cookiecutter-python-app
LOC3: https://github.com/Springerle/py-generic-project
"""
# ----------------------------------------------------------------------------
# Python Standard Library Imports (one per line)
# ----------------------------------------------------------------------------
import sys
import shlex
import os
import sys
import subprocess
# import yaml
import datetime
from contextlib import contextmanager
if sys.version_info > (3, 2):
import io
import os
else:
raise "Use Python 3.3 or higher"
# ----------------------------------------------------------------------------
# External Third Party Python Module Imports (one per line)
# ----------------------------------------------------------------------------
from cookiecutter.utils import rmtree
# from click.testing import CliRunner
# ----------------------------------------------------------------------------
# Project Specific Module Imports (one per line)
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
__author__ = 'E.R. Uber ([email protected])'
__license__ = 'MIT'
__copyright__ = "Copyright (C) 2017 by E.R. Uber"
# ----------------------------------------------------------------------------
# Module Global & Constant Definitions
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Test Support...
# ----------------------------------------------------------------------------
# [LOC1]
@contextmanager
def inside_dir(dirpath):
"""
Execute code from inside the given directory
:param dirpath: String, path of the directory the command is being run.
"""
old_path = os.getcwd()
try:
os.chdir(dirpath)
yield
finally:
os.chdir(old_path)
# [LOC1]
@contextmanager
def bake_in_temp_dir(cookies, *args, **kwargs):
"""
Delete the temporal directory that is created when executing the tests
:param cookies: pytest_cookies.Cookies, cookie to be baked and its temporal files will be removed
"""
result = cookies.bake(*args, **kwargs)
try:
yield result
finally:
rmtree(str(result.project))
# [LOC1]
def run_inside_dir(command, dirpath):
"""
Run a command from inside a given directory, returning the exit status
:param command: Command that will be executed
:param dirpath: String, path of the directory the command is being run.
"""
with inside_dir(dirpath):
return subprocess.check_call(shlex.split(command))
# [LOC1]
def check_output_inside_dir(command, dirpath):
"Run a command from inside a given directory, returning the command output"
with inside_dir(dirpath):
return subprocess.check_output(shlex.split(command))
# [LOC1]
def project_info(result):
"""Get toplevel dir, project_slug, and project dir from baked cookies"""
project_path = str(result.project)
project_slug = os.path.split(project_path)[-1]
project_dir = os.path.join(project_path, project_slug)
return project_path, project_slug, project_dir
# ----------------------------------------------------------------------------
# Tests...
# ----------------------------------------------------------------------------
# [LOC1]
def test_year_compute_in_license_file(cookies):
with bake_in_temp_dir(cookies) as result:
license_file_path = result.project.join('LICENSE')
now = datetime.datetime.now()
assert str(now.year) in license_file_path.read()
# [LOC1]
# ["MIT", "BSD3", "ISC", "Apache2", "GNU-GPL-v3", "Not open source"]
def test_bake_selecting_license(cookies):
license_strings = {
'MIT': 'MIT License',
'BSD3': 'Redistributions of source code must retain the above copyright notice, this',
'ISC': 'ISC License',
'Apache2': 'Licensed under the Apache License, Version 2.0',
'GNU-GPL-v3': 'GNU GENERAL PUBLIC LICENSE',
}
for license, target_string in license_strings.items():
with bake_in_temp_dir(cookies, extra_context={'license': license}) as result:
assert target_string in result.project.join('LICENSE').read()
# NEED TO ADD a project setup.py file for this to pass
# already have a template setup.py file, but this one is for
# the project
assert license in result.project.join('setup.py').read()
def test_bake_project(cookies):
result = cookies.bake(extra_context={'project_name': 'TestProject'})
# p, s, d = project_info(result)
# print(f"Project Path: {p}")
# print(f"Project Slug: {s}")
# print(f" Project Dir: {d}")
if result.trace_back:
print(result.trace_back_stack)
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == 'python-testproject'
assert result.project.isdir()
# ----------------------------------------------------------------------------
if __name__ == "__main__":
pass
| 32.467456 | 101 | 0.546382 | 0 | 0 | 643 | 0.117186 | 675 | 0.123018 | 0 | 0 | 3,288 | 0.599235 |
fdbbcdb74fb497d41cae48ac2a6300801085c4fc | 2,053 | py | Python | tag.py | tom-choi/NLPforPIXIV | 77e905793c792ec97f196a4da7144456018577c7 | [
"MIT"
]
| 1 | 2022-03-18T09:10:59.000Z | 2022-03-18T09:10:59.000Z | tag.py | tom-choi/NLPforPIXIV | 77e905793c792ec97f196a4da7144456018577c7 | [
"MIT"
]
| null | null | null | tag.py | tom-choi/NLPforPIXIV | 77e905793c792ec97f196a4da7144456018577c7 | [
"MIT"
]
| null | null | null | import json
from msilib.schema import Directory
import pandas as pd
import csv
with open('./result-#succubus Drawings, Best Fan Art on pixiv, Japan-1647491083659.json', 'r',encoding="utf-8") as f:
data = json.load(f)
Tags_Directory = {}
print(f"已經捕捉到{len(data)}條信息,準備將tag新增到字典……")
n = len(data)
for i in range(0,n):
#print(f"idNum:{data[i]['idNum']} tag數量:{len(data[i]['tagsWithTransl'])}")
for j in range(0,len(data[i]['tagsWithTransl'])):
if (data[i]['tagsWithTransl'][j] in Tags_Directory):
Tags_Directory[data[i]['tagsWithTransl'][j]] += 1
else:
Tags_Directory[data[i]['tagsWithTransl'][j]] = 1
# print(f"Tags_Directory 字典收錄了以下tags: ")
# for key in Tags_Directory.keys():
# print(f"{key} : {Tags_Directory[key]}")
pd_Tags_Directory = []
pd_Tags_Directory_ID = {}
i = 0
print("製作字典序……")
for key in Tags_Directory.keys():
pd_Tags_Directory.append(key)
pd_Tags_Directory_ID[key] = i
i += 1
with open('./pd_Tags_Directory_ID.json', 'w+',encoding="utf-8") as f:
json.dump(pd_Tags_Directory_ID,f)
print(f"字典序完成(一共 {len(Tags_Directory)} 個tags)")
# for i in range(0,n):
# for j in range(0,len(data[i]['tagsWithTransl'])):
# if (data[i]['tagsWithTransl'][j] in Tags_Directory):
# Tags_Directory[data[i]['tagsWithTransl'][j]] += 1
# else:
# Tags_Directory[data[i]['tagsWithTransl'][j]] = 1
# k = 0
# times = 1
# print(f"進程:統計Tags二元組…… ({k}/{n})")
# Count_Tags = {"kEySSS": pd_Tags_Directory}
# for key in pd_Tags_Directory_ID:
# Count_Tag = [0 for _ in range(len(pd_Tags_Directory_ID))]
# for i in range(0,n):
# if (key not in data[i]['tagsWithTransl']):
# continue
# else:
# for j in range(0,len(data[i]['tagsWithTransl'])):
# Count_Tag[pd_Tags_Directory_ID[data[i]['tagsWithTransl'][j]]] += 1
# Count_Tags[key] = Count_Tag
# k += 1
# if (k % (n//100) == 0):
# print(f"進程:統計Tags二元組…… ({k}/{n}) 已完成{times}%")
# times += 1
# print(f"統計完成!準備輸出excel檔案")
# #print(pd_Tags_Directory)
# df = pd.DataFrame(Count_Tags)
# df.to_csv('trainning.csv')
# print(df)
| 33.112903 | 117 | 0.649781 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,560 | 0.708769 |
fdbd3757fbcb05b2b219ad506437967a7305ef32 | 3,583 | py | Python | event_handlers/voyager_event_handler.py | bigpizza/VoyagerTelegramBot | 8b1e3cbebe9041b0ca341ce4d5d9835f5e12b4d9 | [
"MIT"
]
| null | null | null | event_handlers/voyager_event_handler.py | bigpizza/VoyagerTelegramBot | 8b1e3cbebe9041b0ca341ce4d5d9835f5e12b4d9 | [
"MIT"
]
| null | null | null | event_handlers/voyager_event_handler.py | bigpizza/VoyagerTelegramBot | 8b1e3cbebe9041b0ca341ce4d5d9835f5e12b4d9 | [
"MIT"
]
| null | null | null | from abc import abstractmethod
from typing import Dict, Tuple
from curse_manager import CursesManager
from telegram import TelegramBot
class VoyagerEventHandler:
"""
A base class for all event handlers to inherit from.
To handle an incoming event from voyager application server, Most important method is the 'handle_event' method.
"""
def __init__(self, config,
telegram_bot: TelegramBot,
handler_name: str = 'DefaultHandler',
curses_manager: CursesManager = None):
self.name = handler_name
self.config = config
self.telegram_bot = telegram_bot
self.curses_manager = curses_manager
def interested_event_names(self):
"""
:return: List of event names this event_handler wants to process.
"""
return []
def interested_event_name(self):
"""
:return: An event name this event_handler wants to process.
"""
return None
def interested_in_all_events(self):
"""
:return: A boolean indicating whether this event handler wants to process all possible events.
"""
return False
def get_name(self):
"""
:return: The name of this event_handler
"""
return self.name
def send_text_message(self, message: str):
"""
Send plain text message to Telegram, and print out error message
:param message: The text that need to be sent to Telegram
"""
if self.telegram_bot:
status, info_dict = self.telegram_bot.send_text_message(message)
if status == 'ERROR':
print(
f'\n[ERROR - {self.get_name()} - Text Message]'
f'[{info_dict["error_code"]}]'
f'[{info_dict["description"]}]')
else:
print(f'\n[ERROR - {self.get_name()} - Telegram Bot]')
def send_image_message(self, base64_img: bytes = None, image_fn: str = '', msg_text: str = '',
as_doc: bool = True) -> Tuple[str or None, str or None]:
"""
Send image message to Telegram, and print out error message
:param base64_img: image data that encoded as base64
:param image_fn: the file name of the image
:param msg_text: image capture in string format
:param as_doc: if the image should be sent as document (for larger image file)
:return: Tuple of chat_id and message_id to check status
"""
if self.telegram_bot:
status, info_dict = self.telegram_bot.send_image_message(base64_img, image_fn, msg_text, as_doc)
if status == 'ERROR':
print(
f'\n[ERROR - {self.get_name()} - Text Message]'
f'[{info_dict["error_code"]}]'
f'[{info_dict["description"]}]')
elif status == 'OK':
return str(info_dict['chat_id']), str(info_dict['message_id'])
else:
print(f'\n[ERROR - {self.get_name()} - Telegram Bot]')
return None, None
@abstractmethod
def handle_event(self, event_name: str, message: Dict):
"""
Processes the incoming event + message. Note: a single message might be
processed by multiple event handlers. Don't modify the message dict.
:param event_name: The event name in string format.
:param message: A dictionary containing all messages
:return: Nothing
"""
print('handling event', event_name, message)
| 36.191919 | 116 | 0.597823 | 3,444 | 0.961206 | 0 | 0 | 455 | 0.126989 | 0 | 0 | 1,800 | 0.502372 |
fdbd68dd1e0a0ba0978c1bd0880d05f492ec5829 | 3,063 | py | Python | fluentcms_bootstrap_grid/content_plugins.py | edoburu/fluentcms-bootstrap-grid | 67a8255e34e22284eeb05c04517671311305d370 | [
"Apache-2.0"
]
| null | null | null | fluentcms_bootstrap_grid/content_plugins.py | edoburu/fluentcms-bootstrap-grid | 67a8255e34e22284eeb05c04517671311305d370 | [
"Apache-2.0"
]
| null | null | null | fluentcms_bootstrap_grid/content_plugins.py | edoburu/fluentcms-bootstrap-grid | 67a8255e34e22284eeb05c04517671311305d370 | [
"Apache-2.0"
]
| null | null | null | from django import forms
from django.utils.encoding import force_text
from django.utils.translation import pgettext, ugettext_lazy as _
from fluent_contents.extensions import ContainerPlugin, plugin_pool, ContentItemForm
from . import appsettings
from .models import BootstrapRow, BootstrapColumn
GRID_COLUMNS = appsettings.FLUENTCMS_BOOTSTRAP_GRID_COLUMNS
def _get_size_choices():
choices = [('', '----')]
for i in range(1, GRID_COLUMNS + 1):
title = '{0} / {1}'.format(i, GRID_COLUMNS)
choices.append((i, title))
return choices
SIZE_CHOICES = _get_size_choices()
OFFSET_CHOICES = [('', '----')] + [(i, force_text(i)) for i in range(1, GRID_COLUMNS + 1)]
size_widget = forms.Select(choices=SIZE_CHOICES)
offset_widget = forms.Select(choices=OFFSET_CHOICES)
push_widget = forms.Select(choices=OFFSET_CHOICES)
@plugin_pool.register
class BootstrapRowPlugin(ContainerPlugin):
"""
Row plugin
"""
model = BootstrapRow
render_template = 'fluentcms_bootstrap_grid/row.html'
empty_children_message = _("Add a new column here.")
class BootstrapColumnForm(ContentItemForm):
"""
Custom form for the bootstrap column
"""
def __init__(self, *args, **kwargs):
super(BootstrapColumnForm, self).__init__(*args, **kwargs)
for size in appsettings.FLUENTCMS_BOOTSTRAP_GRID_SIZES:
col = self.fields['col_{0}'.format(size)]
offset = self.fields['col_{0}_offset'.format(size)]
push = self.fields['col_{0}_push'.format(size)]
col.label = appsettings.FLUENTCMS_BOOTSTRAP_GRID_TITLES[size]
offset.label = pgettext("bootstrap-grid", u"Offset")
push.label = pgettext("bootstrap-grid", u"Push")
@plugin_pool.register
class BootstrapColumnPlugin(ContainerPlugin):
"""
Column plugin
"""
model = BootstrapColumn
form = BootstrapColumnForm
render_template = 'fluentcms_bootstrap_grid/column.html'
allowed_parent_types = (BootstrapRowPlugin,)
formfield_overrides = {
'col_xs': {'widget': size_widget},
'col_sm': {'widget': size_widget},
'col_md': {'widget': size_widget},
'col_lg': {'widget': size_widget},
'col_xs_offset': {'widget': offset_widget},
'col_sm_offset': {'widget': offset_widget},
'col_md_offset': {'widget': offset_widget},
'col_lg_offset': {'widget': offset_widget},
'col_xs_push': {'widget': push_widget},
'col_sm_push': {'widget': push_widget},
'col_md_push': {'widget': push_widget},
'col_lg_push': {'widget': push_widget},
}
fieldsets = (
(None, {
'fields': (
('col_xs', 'col_xs_offset', 'col_xs_push'),
('col_sm', 'col_sm_offset', 'col_sm_push'),
('col_md', 'col_md_offset', 'col_md_push'),
('col_lg', 'col_lg_offset', 'col_lg_push'),
),
}),
)
class Media:
css = {
'all': ('admin/fluentcms_bootstrap_grid/grid_admin.css',),
}
| 32.935484 | 90 | 0.642507 | 2,167 | 0.707476 | 0 | 0 | 1,559 | 0.508978 | 0 | 0 | 762 | 0.248776 |
fdbd9c9ab6b561ed49a22efac24abb031c9653d8 | 8,083 | py | Python | study.py | Yougeeg/zhihuiguo | 21cfa4210b011e0fbc200774b88e570d21e30ab2 | [
"MIT"
]
| null | null | null | study.py | Yougeeg/zhihuiguo | 21cfa4210b011e0fbc200774b88e570d21e30ab2 | [
"MIT"
]
| null | null | null | study.py | Yougeeg/zhihuiguo | 21cfa4210b011e0fbc200774b88e570d21e30ab2 | [
"MIT"
]
| 2 | 2017-11-04T08:46:04.000Z | 2018-09-12T08:16:44.000Z | import logging
import json
from datetime import datetime, timedelta
from getpass import getpass
import uuid
import requests
from Cryptodome.PublicKey import RSA
import utils
NONE, SIGN, TICKET = 0, 1, 2
SERVER = 'https://appstudentapi.zhihuishu.com'
SSL_VERIFY = True
TAKE_EXAMS = True
SKIP_FINAL_EXAM = False
EXAM_AUTO_SUBMIT = True
def post(head, url, data, raw=False):
timestamp = str(int(datetime.now().timestamp() * 1000))
s.headers.update({'Timestamp': timestamp})
if head == SIGN:
s.headers.update({'App-Signature': utils.md5_digest(app_key + timestamp + secret)})
elif head == TICKET:
s.headers.update({'App-Ticket': ticket})
r = s.post(SERVER + url, data=data, verify=SSL_VERIFY)
if raw is True:
return r.text
return r.json()['rt']
def login():
account = input(u'账号(手机):')
password = getpass(prompt=u'密码:')
assert account or password
p = {'appkey': app_key}
global ticket
ticket = post(NONE, '/api/ticket', p)
p = {'platform': 'android', 'm': account, 'appkey': app_key, 'p': password, 'client': 'student',
'version': '2.8.9'}
d = post(TICKET, '/api/login', p)
u = d['userId']
se = d['secret']
s.headers.clear()
p = {'type': 3, 'userId': u, 'secretStr': utils.rsa_encrypt(rsa_key, u), 'versionKey': 1}
d = post(SIGN, '/appstudent/student/user/getUserInfoAndAuthentication', p)
ai = json.loads(utils.rsa_decrypt(rsa_key, d['authInfo']))
ui = json.loads(utils.rsa_decrypt(rsa_key, d['userInfo']))
logger.info(ai)
logger.info(ui)
n = ui['realName']
logger.info(f'{u} {n}')
with open('userinfo.py', 'w+', encoding='utf-8') as f:
f.writelines(f'USER = {u}\n')
f.writelines(f'NAME = "{n}"\n')
f.writelines(f'SECRET = "{se}"')
logger.info('Login OK.')
return u, n, se
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO)
logger = logging.getLogger()
logger.info('I love studying! Study makes me happy!')
rsa_key = RSA.import_key(open('key.pem', 'r').read())
app_key = utils.md5_digest(str(uuid.uuid4()).replace('-', ''))
s = requests.Session()
s.headers.update({
'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.1.1; Nexus 5X Build/NOF27B',
'Accept-Encoding': 'gzip',
'App-Key': app_key})
secret = ''
ticket = ''
try:
import userinfo
user = userinfo.USER
name = userinfo.NAME
secret = userinfo.SECRET
if input(f'Current user:{user} {name}:[y/n]') != 'y':
user, name, secret = login()
except:
user, name, secret = login()
SERVER += '/appstudent'
p = {'userId': user}
d = post(SIGN, '/student/tutorial/getStudyingCourses', p)
course_id, recruit_id, link_course_id = 0, 0, 0
if d is None:
logger.info('No studying courses.')
exit()
for course in d:
if input(course['courseName'] + ':[y/n]') == 'y':
course_id = course['courseId']
recruit_id = course['recruitId']
link_course_id = course['linkCourseId']
break
if course_id == 0:
exit()
def save_record(dic, chapter_id, lesson_id):
if dic['studiedLessonDto'] is not None and dic['studiedLessonDto']['watchState'] == 1:
return
p = {'deviceId': app_key, 'userId': user, 'versionKey': 1}
rt = post(SIGN, '/student/tutorial/getSaveLearningRecordToken', p)
token = utils.rsa_decrypt(rsa_key, rt)
video_time = dic['videoSec']
chapter_id = chapter_id or dic['chapterId']
j = {'lessonId': lesson_id, 'learnTime': str(timedelta(seconds=video_time)), 'userId': user,
'personalCourseId': link_course_id, 'recruitId': recruit_id, 'chapterId': chapter_id, 'sourseType': 3,
'playTimes': video_time, 'videoId': dic['videoId'], 'token': token, 'deviceId': app_key}
if lesson_id is None:
j['lessonId'] = dic['id']
else:
j['lessonVideoId'] = dic['id']
json_str = json.dumps(j, sort_keys=True, separators=(',', ':'))
p = {'jsonStr': json_str, 'secretStr': utils.rsa_encrypt(rsa_key, json_str), 'versionKey': 1}
rt = post(SIGN, '/student/tutorial/saveLearningRecordByToken', p)
logger.info(dic['name'] + rt)
p = {'recruitId': recruit_id, 'courseId': course_id, 'userId': user}
chapter_list = post(SIGN, '/appserver/student/getCourseInfo', p)['chapterList']
for chapter in chapter_list:
for lesson in chapter['lessonList']:
if lesson['sectionList'] is not None:
for section in lesson['sectionList']:
save_record(section, lesson['chapterId'], lesson['id'])
else:
save_record(lesson, None, None)
logger.info('Videos done.')
if TAKE_EXAMS is False:
exit()
p = {'mobileType': 2, 'recruitId': recruit_id, 'courseId': course_id, 'page': 1, 'userId': user, 'examType': 1,
'schoolId': -1, 'pageSize': 20} # examType=2 is for finished exams
exam_list = post(SIGN, '/appserver/exam/findAllExamInfo', p)['stuExamDtoList']
for exam in exam_list:
logger.info(exam['examInfoDto']['name'])
exam_type = exam['examInfoDto']['type']
if exam_type == 2: # Final exams
if SKIP_FINAL_EXAM is True:
logger.info('Skipped final exam.')
continue
exam_id = exam['examInfoDto']['examId']
student_exam_id = exam['studentExamInfoDto']['id']
question_ids = []
p = {'userId': user}
rt = post(SIGN, '/student/exam/canIntoExam', p)
if rt != 1:
logger.info('Cannot into exam.')
continue
p = {'recruitId': recruit_id, 'examId': exam_id, 'isSubmit': 0, 'studentExamId': student_exam_id,
'type': exam_type, 'userId': user}
ids = post(SIGN, '/student/exam/examQuestionIdListByCache', p)['examList']
p.pop('isSubmit')
p.pop('type')
for exam_question in ids:
question_ids.append(str(exam_question['questionId']))
p['questionIds'] = question_ids
questions = post(SIGN, '/student/exam/questionInfos', p)
for question_id in question_ids:
question = questions[question_id]
logger.info(question['firstname'])
if question['questionTypeName'] == '多选题' or '单选题':
answer = question['realAnswer'].split(',')
else:
EXAM_AUTO_SUBMIT = False
continue
pa = [{'deviceType': '1', 'examId': str(exam_id), 'userId': str(user), 'stuExamId': str(student_exam_id),
'questionId': str(question_id), 'recruitId': str(recruit_id), 'answerIds': answer, 'dataIds': []}]
json_str = json.dumps(pa, separators=(',', ':'))
pb = {'mobileType': 2, 'jsonStr': json_str,
'secretStr': utils.rsa_encrypt(rsa_key, json_str),
'versionKey': 1}
rt = post(SIGN, '/student/exam/saveExamAnswer', pb)
logger.info(rt[0]['messages'])
if not EXAM_AUTO_SUBMIT:
continue
pa = {'deviceType': '1', 'userId': str(user), 'stuExamId': str(student_exam_id), 'recruitId': recruit_id,
'examId': str(exam_id), 'questionIds': question_ids, 'remainingTime': '0',
'achieveCount': str(question_ids.__len__())}
json_str = json.dumps(pa, separators=(',', ':'))
pb = {'mobileType': 2, 'recruitId': recruit_id, 'examId': str(exam_id), 'userId': user, 'jsonStr': json_str,
'secretStr': utils.rsa_encrypt(rsa_key, json_str), 'type': exam_type, 'versionKey': 1}
raw = post(SIGN, '/student/exam/submitExamInfo', pb, raw=True)
rt = json.loads(raw.replace('"{', '{').replace('}"', '}').replace('\\', ''))['rt']
logger.info(f'{rt["messages"]} Score: {rt["errorInfo"]["score"]}')
logger.info('Exams done.')
| 39.237864 | 117 | 0.588767 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,423 | 0.298878 |
fdbe327728712dcbbd59d238061b617718c7c9a0 | 244 | py | Python | autogl/module/feature/_base_feature_engineer/__init__.py | dedsec-9/AutoGL | 487f2b2f798b9b1363ad5dc100fb410b12222e06 | [
"MIT"
]
| null | null | null | autogl/module/feature/_base_feature_engineer/__init__.py | dedsec-9/AutoGL | 487f2b2f798b9b1363ad5dc100fb410b12222e06 | [
"MIT"
]
| null | null | null | autogl/module/feature/_base_feature_engineer/__init__.py | dedsec-9/AutoGL | 487f2b2f798b9b1363ad5dc100fb410b12222e06 | [
"MIT"
]
| null | null | null | import autogl
if autogl.backend.DependentBackend.is_dgl():
from ._base_feature_engineer_dgl import BaseFeatureEngineer
else:
from ._base_feature_engineer_pyg import BaseFeatureEngineer
class BaseFeature(BaseFeatureEngineer):
...
| 22.181818 | 63 | 0.811475 | 47 | 0.192623 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
fdc0b230d2a0f01f084eb9ceb1e8ca8a841fb58f | 1,440 | py | Python | python/controllers/ner_annotation_api.py | barkavi87/anuvaad-corpus | 9ea832f4228f61a7d4998205976629ea4b7c3d70 | [
"MIT"
]
| 2 | 2019-12-20T08:58:10.000Z | 2020-05-15T14:17:43.000Z | python/controllers/ner_annotation_api.py | barkavi87/anuvaad-corpus | 9ea832f4228f61a7d4998205976629ea4b7c3d70 | [
"MIT"
]
| 73 | 2019-08-12T16:17:33.000Z | 2022-01-13T01:24:38.000Z | python/controllers/ner_annotation_api.py | barkavi87/anuvaad-corpus | 9ea832f4228f61a7d4998205976629ea4b7c3d70 | [
"MIT"
]
| 1 | 2020-08-24T09:51:46.000Z | 2020-08-24T09:51:46.000Z | import os
import urllib.request
from flask import Flask, request, redirect, render_template, jsonify
from flask import Blueprint, request, current_app as app
from controllers.sc_judgment_header_ner_eval import SC_ner_annotation
import json
from models.response import CustomResponse
from models.status import Status
ner_annotation_api = Blueprint('ner_annotation_api', __name__)
@ner_annotation_api.route('/ner', methods = ['POST'])
def ner_sentences():
data = request.get_json()
if 'sentences' not in data or data['sentences'] is None or not isinstance(data['sentences'],list):
res = CustomResponse(
Status.ERR_GLOBAL_MISSING_PARAMETERS.value, None)
return res.getres(), Status.ERR_GLOBAL_MISSING_PARAMETERS.value['http']['status']
else:
output_ner = list()
for text in data['sentences']:
mix_model_dir = os.getcwd()+'/upload/models/exp_1_mix/'
model_dir_order = os.getcwd()+'/upload/models/exp_1_order/'
model_dir_judgment = os.getcwd()+'/upload/models/exp_1_judgement/'
result_ner = SC_ner_annotation(model_dir_judgment, model_dir_order, mix_model_dir, text).main()
if result_ner is None or mix_model_dir is None:
return "something went wrong"
else:
output_ner.append(result_ner)
res = CustomResponse(Status.SUCCESS.value, output_ner)
return res.getres()
| 43.636364 | 107 | 0.702083 | 0 | 0 | 0 | 0 | 1,057 | 0.734028 | 0 | 0 | 201 | 0.139583 |
fdc1c97e35e98b3788187bd4a1997c5b2842cc3b | 4,594 | py | Python | HandGenerator/HandGenerator.py | VASST/SlicerLeapMotion | d20215fb657eb5c972d1fe380bdf2d0479796c93 | [
"MIT"
]
| null | null | null | HandGenerator/HandGenerator.py | VASST/SlicerLeapMotion | d20215fb657eb5c972d1fe380bdf2d0479796c93 | [
"MIT"
]
| 2 | 2019-09-06T16:06:20.000Z | 2020-02-16T17:15:28.000Z | HandGenerator/HandGenerator.py | VASST/SlicerLeapMotion | d20215fb657eb5c972d1fe380bdf2d0479796c93 | [
"MIT"
]
| 1 | 2020-01-14T17:49:31.000Z | 2020-01-14T17:49:31.000Z | import sys
import os
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
import numpy as np
#
# HandGenerator
#
class HandGenerator(ScriptedLoadableModule):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "Hand Generator"
self.parent.categories = ["IGT"]
self.parent.dependencies = ["OpenIGTLinkIF"]
self.parent.contributors = ["Leah Groves (Robarts Research Institute), Thomas Morphew (Robarts Research Institute)"]
self.parent.helpText = """This module creates a number of models (cylinders and spheres), and parents new transforms to those models in order to mimic the human hand. These transforms are then driven by the Leap Motion device."""
self.parent.helpText += self.getDefaultModuleDocumentationLink()
self.parent.acknowledgementText = """Thanks to the VASST Lab for its support."""
#
# HandGeneratorWidget
#
class HandGeneratorWidget(ScriptedLoadableModuleWidget):
def __init__(self, parent=None):
ScriptedLoadableModuleWidget.__init__(self, parent)
self.connectorNode = None
self.generated = False
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
self.parametersCollapsibleButton = ctk.ctkCollapsibleButton()
self.parametersCollapsibleButton.text = "Actions"
self.layout.addWidget(self.parametersCollapsibleButton)
self.parametersFormLayout = qt.QFormLayout(self.parametersCollapsibleButton)
self.connectButton = qt.QPushButton()
self.connectButton.setDefault(False)
self.connectButton.text = "Click to connect"
self.parametersFormLayout.addWidget(self.connectButton)
self.pathText = qt.QLabel("Please place hands within view")
self.parametersFormLayout.addRow(self.pathText)
self.layout.addStretch(1)
self.generateButton = qt.QPushButton()
self.generateButton.setDefault(False)
self.generateButton.text = "Generate Hands"
self.parametersFormLayout.addWidget(self.generateButton)
self.connectButton.connect('clicked(bool)', self.onConnectButtonClicked)
self.generateButton.connect('clicked(bool)', self.generateCylinders)
self.layout.addStretch(1)
def onConnectButtonClicked(self):
if self.connectorNode is not None:
self.connectorNode = None
self.connectCheck = 1
self.connectButton.text = 'Click to connect'
else:
self.connectorNode = slicer.vtkMRMLIGTLConnectorNode()
slicer.mrmlScene.AddNode(self.connectorNode)
self.connectorNode.SetTypeClient('localhost', 18944)
self.connectorNode.Start()
self.connectCheck = 0
self.connectButton.text = 'Connected'
def generateCylinders(self):
if self.generated == False:
nodes = slicer.util.getNodesByClass('vtkMRMLLinearTransformNode')
l = slicer.modules.createmodels.logic()
# TODO: Make sure to render the palm as well!
for i in range (0, len(nodes)):
if 'Left' in nodes[i].GetName() or 'Right' in nodes[i].GetName():
if 'Dis' in nodes[i].GetName() or 'Int' in nodes[i].GetName() or 'Prox' in nodes[i].GetName() or 'Meta' in nodes[i].GetName():
# This is a temporary solution, idealy the Plus server and Leap Motion can scan the actual sizes
# This is also subject to change for different model types that look more like a hand.
if 'Dis' in nodes[i].GetName():
length = 16
radiusMm = 1.5
elif 'Int' in nodes[i].GetName():
length = 20
radiusMm = 1.5
elif 'Prox' in nodes[i].GetName():
length = 28
radiusMm = 1.5
elif 'Meta' in nodes[i].GetName():
length = 50
radiusMm = 3
cylinder = l.CreateCylinder(length, radiusMm)
cylinder.SetAndObserveTransformNodeID(nodes[i].GetID())
cylinder.SetName('LHG_Cyl_'+nodes[i].GetName())
self.generated = True
else:
nodes = slicer.util.getNodesByClass('vtkMRMLLinearTransformNode')
models = slicer.util.getNodesByClass('vtkMRMLModelNode')
n = 0
mat = vtk.vtkMatrix4x4()
l = slicer.modules.createmodels.logic()
for j in range(0, len(models)):
if 'LHG_' in models[j].GetName():
slicer.mrmlScene.RemoveNode(models[j])
for i in range (0, len(nodes)):
if 'LHG_Zshift' in nodes[i].GetName():
slicer.mrmlScene.RemoveNode(nodes[i])
self.generated = False
self.generateCylinders() | 38.932203 | 233 | 0.680888 | 4,401 | 0.957989 | 0 | 0 | 0 | 0 | 0 | 0 | 946 | 0.205921 |
fdc27871983c6fc23e23bf1a61087b70dff46dd6 | 238 | py | Python | test_api/movies/urls.py | xm4dn355x/drf_test | efdc38afa51d259fcb5781c9f8cc52f93e2fd81b | [
"MIT"
]
| null | null | null | test_api/movies/urls.py | xm4dn355x/drf_test | efdc38afa51d259fcb5781c9f8cc52f93e2fd81b | [
"MIT"
]
| null | null | null | test_api/movies/urls.py | xm4dn355x/drf_test | efdc38afa51d259fcb5781c9f8cc52f93e2fd81b | [
"MIT"
]
| null | null | null | from django.urls import path
from . import views
urlpatterns = [
path('movie/', views.MovieListView.as_view()),
path('movie/<int:pk>/', views.MovieDetailView.as_view()),
path('review/', views.ReviewCreateView.as_view()),
]
| 21.636364 | 61 | 0.684874 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 34 | 0.142857 |
fdc29b2d1755fa39792e6b6765f17fb3cfeeb9de | 1,166 | py | Python | commlib/utils.py | robotics-4-all/commlib-py | 9d56e0a2e13410feac0e10d9866a1c4a60ade2c7 | [
"MIT"
]
| 1 | 2021-06-09T09:32:53.000Z | 2021-06-09T09:32:53.000Z | commlib/utils.py | robotics-4-all/commlib-py | 9d56e0a2e13410feac0e10d9866a1c4a60ade2c7 | [
"MIT"
]
| 7 | 2022-03-10T23:57:25.000Z | 2022-03-13T19:12:54.000Z | commlib/utils.py | robotics-4-all/commlib-py | 9d56e0a2e13410feac0e10d9866a1c4a60ade2c7 | [
"MIT"
]
| 1 | 2021-06-07T16:25:05.000Z | 2021-06-07T16:25:05.000Z | import re
import uuid
import time
from typing import (Any, Callable, Dict, List, Optional, Tuple, Type,
TypeVar, Union, Text)
def camelcase_to_snakecase(_str: str) -> str:
"""camelcase_to_snakecase.
Transform a camelcase string to snakecase
Args:
_str (str): String to apply transformation.
Returns:
str: Transformed string
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', _str)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def gen_timestamp() -> int:
"""gen_timestamp.
Generate a timestamp.
Args:
Returns:
int: Timestamp in integer representation. User `str()` to
transform to string.
"""
return int(1.0 * (time.time() + 0.5) * 1000)
def gen_random_id() -> str:
"""gen_random_id.
Generates a random unique id, using the uuid library.
Args:
Returns:
str: String representation of the random unique id
"""
return str(uuid.uuid4()).replace('-', '')
class Rate:
def __init__(self, hz: int):
self._hz = hz
self._tsleep = 1.0 / hz
def sleep(self):
time.sleep(self._tsleep)
| 21.2 | 69 | 0.588336 | 153 | 0.131218 | 0 | 0 | 0 | 0 | 0 | 0 | 590 | 0.506003 |
fdc3fc24cea107cba4ab6159b29d6bd76397bdc9 | 434 | py | Python | Pratical/Class02/metodo_da_bissecao.py | JoaoCostaIFG/MNUM | 6e042d8a6f64feb9eae9c79afec2fbab51f46fbd | [
"MIT"
]
| 1 | 2019-12-07T10:34:30.000Z | 2019-12-07T10:34:30.000Z | Pratical/Class02/metodo_da_bissecao.py | JoaoCostaIFG/MNUM | 6e042d8a6f64feb9eae9c79afec2fbab51f46fbd | [
"MIT"
]
| null | null | null | Pratical/Class02/metodo_da_bissecao.py | JoaoCostaIFG/MNUM | 6e042d8a6f64feb9eae9c79afec2fbab51f46fbd | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
# Pesquisa binaria
# Read
num = int(input("Number to find the sqrt of? "))
index = 0
step = num / 2
prox = True
while abs(index * index - num) > 1e-10:
if (prox):
index += step
else:
index -= step
step = step / 2
if (index * index) < num:
prox = True
else:
prox = False
print("Result: [", index - 2 * step, ", ", index, "] with percision of +/-", step)
| 17.36 | 82 | 0.534562 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 116 | 0.267281 |
fdc4efcf38d739230cb577df9971b45dd3d12756 | 2,625 | py | Python | final/NerualNetworks/utils/MakeData.py | XuYi-fei/HUST-EIC-MathematicalModeling | 73797bdba17d4f759be3a39603b42be081a98e5c | [
"MIT"
]
| 1 | 2021-05-04T12:29:21.000Z | 2021-05-04T12:29:21.000Z | final/NerualNetworks/utils/MakeData.py | XuYi-fei/HUST-EIC-MathematicalModeling | 73797bdba17d4f759be3a39603b42be081a98e5c | [
"MIT"
]
| null | null | null | final/NerualNetworks/utils/MakeData.py | XuYi-fei/HUST-EIC-MathematicalModeling | 73797bdba17d4f759be3a39603b42be081a98e5c | [
"MIT"
]
| null | null | null | import pandas as pd
import os
import random
class MakeDataset():
def __init__(self, known=30, predict=7, ratio=0.4, path=None):
# ratio means the valid/(train + valid)
assert path is not None, "The path is invalid"
self.df = pd.read_excel(path)
self.columns = self.df.columns
self.knownLength = known
self.ratio = ratio
self.predictLength = predict
self.data_length = len(self.df.values[0]) - 3
# self.datasets: {known data: predict data}
self.datasets = {}
self.train_dataset = []
self.val_dataset = []
self.begin_index = self.data_length % (known + predict) + 3
self.keys = []
self.process()
self.splitDataset()
def process(self):
# self.maxData = 0
# self.minData = 0
maxData = 0
minData = 0
for index, row in self.df.iterrows():
data = list(row[self.begin_index:])
while len(data) >= self.knownLength + self.predictLength:
maxData = 1 if max(data[-(self.predictLength + self.knownLength):-self.predictLength]) * 1.5 == 0 else max(data[-(self.predictLength + self.knownLength):-self.predictLength]) * 1.5
self.datasets[str(data[-(self.predictLength + self.knownLength):-self.predictLength])] = str([(data[-self.predictLength:]), maxData])
# data = data[:-(self.predictLength+self.knownLength)]
data = data[:-1]
return
def splitDataset(self):
writer_train = open('../Data/train2.txt', 'w')
writer_val = open('../Data/val2.txt', 'w')
for index, (k,v) in enumerate(self.datasets.items()):
k, v = eval(k), eval(v)
k = str([i / v[1] for i in k])
v[0] = str([i / v[1] for i in v[0]])
if random.random() > self.ratio:
writer_train.write(k)
writer_train.write('#')
writer_train.write(v[0])
writer_train.write('#')
writer_train.write(str(v[1]))
writer_train.write('\n')
else:
writer_val.write(k)
writer_val.write('#')
writer_val.write(v[0])
writer_val.write('#')
writer_val.write(str(v[1]))
writer_val.write('\n')
writer_val.close()
writer_train.close()
return
if __name__ == '__main__':
data = MakeDataset(path=r'D:\GitRepos\EIC\MathmaticalModeling\HUST-EIC-MathematicalModeling\final\NerualNetworks\Data\Preprocessed_original.xlsx')
| 34.090909 | 196 | 0.55619 | 2,391 | 0.910857 | 0 | 0 | 0 | 0 | 0 | 0 | 388 | 0.14781 |
fdc5979ebdcfef679c432bdc3659a7c209d59706 | 326 | py | Python | chapter06/example612.py | yozw/lio-files | e036bc868207ec045a804495fc40cf3a48e37d6d | [
"MIT"
]
| null | null | null | chapter06/example612.py | yozw/lio-files | e036bc868207ec045a804495fc40cf3a48e37d6d | [
"MIT"
]
| null | null | null | chapter06/example612.py | yozw/lio-files | e036bc868207ec045a804495fc40cf3a48e37d6d | [
"MIT"
]
| null | null | null | from math import sqrt
from numpy import matrix
from intpm import intpm
A = matrix([[1, 0, 1, 0], [0, 1, 0, 1]])
b = matrix([1, 1]).T
c = matrix([-1, -2, 0, 0]).T
mu = 100
x1 = 0.5 * (-2 * mu + 1 + sqrt(1 + 4*mu*mu))
x2 = 0.5 * (-mu + 1 + sqrt(1 + mu * mu))
x0 = matrix([x1, x2, 1 - x1, 1 - x2]).T
intpm(A, b, c, x0, mu)
| 18.111111 | 44 | 0.509202 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
fdc8a16130fbd3365668c8adfa036d8311ee21c2 | 2,205 | py | Python | DataBase/Postgres/PostgresTest.py | InverseLina/python-practice | 496d2020916d8096a32131cdedd25a4da7b7735e | [
"Apache-2.0"
]
| null | null | null | DataBase/Postgres/PostgresTest.py | InverseLina/python-practice | 496d2020916d8096a32131cdedd25a4da7b7735e | [
"Apache-2.0"
]
| null | null | null | DataBase/Postgres/PostgresTest.py | InverseLina/python-practice | 496d2020916d8096a32131cdedd25a4da7b7735e | [
"Apache-2.0"
]
| null | null | null | import psycopg2
# encoding=utf-8
__author__ = 'Hinsteny'
def get_conn():
conn = psycopg2.connect(database="hello_db", user="hinsteny", password="welcome", host="127.0.0.1", port="5432")
return conn
def create_table(conn):
cur = conn.cursor()
cur.execute('''CREATE TABLE if not exists COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
conn.commit()
conn.close()
def insert_data(conn):
cur = conn.cursor()
# cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
# VALUES (1, 'Paul', 32, 'California', 20000.00 )")
#
# cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
# VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
#
# cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
# VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )")
#
# cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
# VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )")
# conn.commit()
print("Records created successfully")
conn.close()
def select_data(conn):
'''
:param conn:
:return:
'''
cur = conn.cursor()
cur.execute("SELECT id, name, address, salary from COMPANY ORDER BY id ASC;")
rows = cur.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3], "\n")
print("Operation done successfully")
conn.close()
pass
def update_data(conn):
cur = conn.cursor()
cur.execute("UPDATE COMPANY set SALARY = 50000.00 where ID=1;")
conn.commit()
conn.close()
select_data(get_conn())
pass
def delete_data(conn):
cur = conn.cursor()
cur.execute("DELETE from COMPANY where ID=4;")
conn.commit()
conn.close()
select_data(get_conn())
pass
# Do test
if __name__ == "__main__":
create_table(get_conn())
insert_data(get_conn())
select_data(get_conn())
update_data(get_conn())
delete_data(get_conn())
pass
| 24.230769 | 116 | 0.579592 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,120 | 0.507937 |
fdc9a425f145a01bd193481bd02f81259f33f97c | 21,351 | py | Python | pysnmp/DHCP-Server-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
]
| 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/DHCP-Server-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
]
| 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/DHCP-Server-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
]
| 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module DHCP-Server-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DHCP-SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:31:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint")
dlink_common_mgmt, = mibBuilder.importSymbols("DLINK-ID-REC-MIB", "dlink-common-mgmt")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, ModuleIdentity, Counter32, Counter64, ObjectIdentity, MibIdentifier, IpAddress, NotificationType, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Integer32, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "ModuleIdentity", "Counter32", "Counter64", "ObjectIdentity", "MibIdentifier", "IpAddress", "NotificationType", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Integer32", "iso", "TimeTicks")
TextualConvention, RowStatus, MacAddress, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "MacAddress", "DisplayString")
swDHCPServerMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 12, 38))
if mibBuilder.loadTexts: swDHCPServerMIB.setLastUpdated('200706080000Z')
if mibBuilder.loadTexts: swDHCPServerMIB.setOrganization('D-Link Crop.')
swDHCPServerCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 38, 1))
swDHCPServerInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 38, 2))
swDHCPServerMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 38, 3))
swDHCPServerPoolMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2))
swDHCPServerBindingMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4))
swDHCPServerState = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 38, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerState.setStatus('current')
swDHCPServerPingPktNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 38, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPingPktNumber.setStatus('current')
swDHCPServerPingTimeOut = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 38, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 2000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPingTimeOut.setStatus('current')
swDHCPServerExcludedAddressTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 1), )
if mibBuilder.loadTexts: swDHCPServerExcludedAddressTable.setStatus('current')
swDHCPServerExcludedAddressEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 1, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerExcludedAddressBegin"), (0, "DHCP-Server-MIB", "swDHCPServerExcludedAddressEnd"))
if mibBuilder.loadTexts: swDHCPServerExcludedAddressEntry.setStatus('current')
swDHCPServerExcludedAddressBegin = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerExcludedAddressBegin.setStatus('current')
swDHCPServerExcludedAddressEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 1, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerExcludedAddressEnd.setStatus('current')
swDHCPServerExcludedAddressStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerExcludedAddressStatus.setStatus('current')
swDHCPServerPoolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1), )
if mibBuilder.loadTexts: swDHCPServerPoolTable.setStatus('current')
swDHCPServerPoolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerPoolName"))
if mibBuilder.loadTexts: swDHCPServerPoolEntry.setStatus('current')
swDHCPServerPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerPoolName.setStatus('current')
swDHCPServerPoolNetworkAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolNetworkAddress.setStatus('current')
swDHCPServerPoolNetworkAddressMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolNetworkAddressMask.setStatus('current')
swDHCPServerPoolDomainName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolDomainName.setStatus('current')
swDHCPServerPoolNetBIOSNodeType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("broadcast", 1), ("peer-to-peer", 2), ("mixed", 3), ("hybid", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolNetBIOSNodeType.setStatus('current')
swDHCPServerPoolLeaseState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("predefined", 1), ("infinite", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolLeaseState.setStatus('current')
swDHCPServerPoolLeaseDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 365))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolLeaseDay.setStatus('current')
swDHCPServerPoolLeaseHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolLeaseHour.setStatus('current')
swDHCPServerPoolLeaseMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolLeaseMinute.setStatus('current')
swDHCPServerPoolBootFile = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolBootFile.setStatus('current')
swDHCPServerPoolNextServer = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 11), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerPoolNextServer.setStatus('current')
swDHCPServerPoolStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 1, 1, 12), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerPoolStatus.setStatus('current')
swDHCPServerDNSServerAddressTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 2), )
if mibBuilder.loadTexts: swDHCPServerDNSServerAddressTable.setStatus('current')
swDHCPServerDNSServerAddressEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 2, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerDNSServerPoolName"), (0, "DHCP-Server-MIB", "swDHCPServerDNSServerAddressIndex"))
if mibBuilder.loadTexts: swDHCPServerDNSServerAddressEntry.setStatus('current')
swDHCPServerDNSServerPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerDNSServerPoolName.setStatus('current')
swDHCPServerDNSServerAddressIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerDNSServerAddressIndex.setStatus('current')
swDHCPServerDNSServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 2, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerDNSServerAddress.setStatus('current')
swDHCPServerDNSServerAddressStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 2, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerDNSServerAddressStatus.setStatus('current')
swDHCPServerNetBIOSNameServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 3), )
if mibBuilder.loadTexts: swDHCPServerNetBIOSNameServerTable.setStatus('current')
swDHCPServerNetBIOSNameServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 3, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerNetBIOSNameServerPoolName"), (0, "DHCP-Server-MIB", "swDHCPServerNetBIOSNameServerIndex"))
if mibBuilder.loadTexts: swDHCPServerNetBIOSNameServerEntry.setStatus('current')
swDHCPServerNetBIOSNameServerPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 3, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerNetBIOSNameServerPoolName.setStatus('current')
swDHCPServerNetBIOSNameServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 3, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerNetBIOSNameServerIndex.setStatus('current')
swDHCPServerNetBIOSNameServer = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 3, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerNetBIOSNameServer.setStatus('current')
swDHCPServerNetBIOSNameServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerNetBIOSNameServerStatus.setStatus('current')
swDHCPServerDefaultRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 4), )
if mibBuilder.loadTexts: swDHCPServerDefaultRouterTable.setStatus('current')
swDHCPServerDefaultRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 4, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerDefaultRouterPoolName"), (0, "DHCP-Server-MIB", "swDHCPServerDefaultRouterIndex"))
if mibBuilder.loadTexts: swDHCPServerDefaultRouterEntry.setStatus('current')
swDHCPServerDefaultRouterPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 4, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerDefaultRouterPoolName.setStatus('current')
swDHCPServerDefaultRouterIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 4, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerDefaultRouterIndex.setStatus('current')
swDHCPServerDefaultRouter = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 4, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerDefaultRouter.setStatus('current')
swDHCPServerDefaultRouterStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 2, 4, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerDefaultRouterStatus.setStatus('current')
swDHCPServerManualBindingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3), )
if mibBuilder.loadTexts: swDHCPServerManualBindingTable.setStatus('current')
swDHCPServerManualBindingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerManualBindingPoolName"), (0, "DHCP-Server-MIB", "swDHCPServerManualBindingIpAddress"))
if mibBuilder.loadTexts: swDHCPServerManualBindingEntry.setStatus('current')
swDHCPServerManualBindingPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerManualBindingPoolName.setStatus('current')
swDHCPServerManualBindingIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerManualBindingIpAddress.setStatus('current')
swDHCPServerManualBindingHardwareAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3, 1, 3), MacAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerManualBindingHardwareAddress.setStatus('current')
swDHCPServerManualBindingType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("ethernet", 1), ("ieee802", 2), ("both", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerManualBindingType.setStatus('current')
swDHCPServerManualBindingStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 3, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swDHCPServerManualBindingStatus.setStatus('current')
swDHCPServerBindingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4), )
if mibBuilder.loadTexts: swDHCPServerBindingTable.setStatus('current')
swDHCPServerBindingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerBindingPoolName"), (0, "DHCP-Server-MIB", "swDHCPServerBindingIpAddress"))
if mibBuilder.loadTexts: swDHCPServerBindingEntry.setStatus('current')
swDHCPServerBindingPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerBindingPoolName.setStatus('current')
swDHCPServerBindingIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerBindingIpAddress.setStatus('current')
swDHCPServerBindingHardwareAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 3), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerBindingHardwareAddress.setStatus('current')
swDHCPServerBindingType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ethernet", 1), ("iee802", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerBindingType.setStatus('current')
swDHCPServerBindingStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("automatic", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerBindingStatus.setStatus('current')
swDHCPServerBindingLifeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerBindingLifeTime.setStatus('current')
swDHCPServerBindingClearState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 4, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("start", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerBindingClearState.setStatus('current')
swDHCPServerConflictIPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 5), )
if mibBuilder.loadTexts: swDHCPServerConflictIPTable.setStatus('current')
swDHCPServerConflictIPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 5, 1), ).setIndexNames((0, "DHCP-Server-MIB", "swDHCPServerConflictIPIPAddress"))
if mibBuilder.loadTexts: swDHCPServerConflictIPEntry.setStatus('current')
swDHCPServerConflictIPIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 5, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerConflictIPIPAddress.setStatus('current')
swDHCPServerConflictIPDetectionMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ping", 1), ("gratuitous-arp", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerConflictIPDetectionMethod.setStatus('current')
swDHCPServerConflictIPDetectionTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 5, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swDHCPServerConflictIPDetectionTime.setStatus('current')
swDHCPServerConflictIPClearState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 38, 3, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("start", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swDHCPServerConflictIPClearState.setStatus('current')
mibBuilder.exportSymbols("DHCP-Server-MIB", swDHCPServerPoolName=swDHCPServerPoolName, swDHCPServerExcludedAddressEntry=swDHCPServerExcludedAddressEntry, swDHCPServerExcludedAddressEnd=swDHCPServerExcludedAddressEnd, swDHCPServerBindingMgmt=swDHCPServerBindingMgmt, swDHCPServerNetBIOSNameServerIndex=swDHCPServerNetBIOSNameServerIndex, swDHCPServerPoolTable=swDHCPServerPoolTable, swDHCPServerDefaultRouterStatus=swDHCPServerDefaultRouterStatus, swDHCPServerPoolNetBIOSNodeType=swDHCPServerPoolNetBIOSNodeType, swDHCPServerPoolLeaseState=swDHCPServerPoolLeaseState, swDHCPServerDefaultRouterTable=swDHCPServerDefaultRouterTable, swDHCPServerManualBindingTable=swDHCPServerManualBindingTable, swDHCPServerBindingLifeTime=swDHCPServerBindingLifeTime, swDHCPServerManualBindingType=swDHCPServerManualBindingType, swDHCPServerDNSServerAddress=swDHCPServerDNSServerAddress, swDHCPServerDefaultRouterIndex=swDHCPServerDefaultRouterIndex, swDHCPServerConflictIPTable=swDHCPServerConflictIPTable, swDHCPServerBindingPoolName=swDHCPServerBindingPoolName, swDHCPServerPingTimeOut=swDHCPServerPingTimeOut, swDHCPServerExcludedAddressBegin=swDHCPServerExcludedAddressBegin, swDHCPServerPoolMgmt=swDHCPServerPoolMgmt, swDHCPServerNetBIOSNameServerTable=swDHCPServerNetBIOSNameServerTable, swDHCPServerConflictIPDetectionMethod=swDHCPServerConflictIPDetectionMethod, swDHCPServerNetBIOSNameServerEntry=swDHCPServerNetBIOSNameServerEntry, swDHCPServerExcludedAddressTable=swDHCPServerExcludedAddressTable, swDHCPServerPoolNetworkAddressMask=swDHCPServerPoolNetworkAddressMask, swDHCPServerDNSServerAddressTable=swDHCPServerDNSServerAddressTable, swDHCPServerExcludedAddressStatus=swDHCPServerExcludedAddressStatus, swDHCPServerPingPktNumber=swDHCPServerPingPktNumber, swDHCPServerMgmt=swDHCPServerMgmt, swDHCPServerNetBIOSNameServerPoolName=swDHCPServerNetBIOSNameServerPoolName, swDHCPServerDefaultRouterEntry=swDHCPServerDefaultRouterEntry, swDHCPServerBindingEntry=swDHCPServerBindingEntry, swDHCPServerManualBindingPoolName=swDHCPServerManualBindingPoolName, swDHCPServerDefaultRouter=swDHCPServerDefaultRouter, swDHCPServerManualBindingHardwareAddress=swDHCPServerManualBindingHardwareAddress, swDHCPServerPoolLeaseMinute=swDHCPServerPoolLeaseMinute, swDHCPServerBindingType=swDHCPServerBindingType, swDHCPServerBindingClearState=swDHCPServerBindingClearState, swDHCPServerDNSServerPoolName=swDHCPServerDNSServerPoolName, swDHCPServerManualBindingIpAddress=swDHCPServerManualBindingIpAddress, swDHCPServerBindingHardwareAddress=swDHCPServerBindingHardwareAddress, swDHCPServerConflictIPEntry=swDHCPServerConflictIPEntry, swDHCPServerInfo=swDHCPServerInfo, swDHCPServerState=swDHCPServerState, PYSNMP_MODULE_ID=swDHCPServerMIB, swDHCPServerCtrl=swDHCPServerCtrl, swDHCPServerPoolLeaseHour=swDHCPServerPoolLeaseHour, swDHCPServerDNSServerAddressEntry=swDHCPServerDNSServerAddressEntry, swDHCPServerNetBIOSNameServer=swDHCPServerNetBIOSNameServer, swDHCPServerBindingIpAddress=swDHCPServerBindingIpAddress, swDHCPServerBindingStatus=swDHCPServerBindingStatus, swDHCPServerPoolBootFile=swDHCPServerPoolBootFile, swDHCPServerPoolStatus=swDHCPServerPoolStatus, swDHCPServerPoolDomainName=swDHCPServerPoolDomainName, swDHCPServerManualBindingEntry=swDHCPServerManualBindingEntry, swDHCPServerConflictIPClearState=swDHCPServerConflictIPClearState, swDHCPServerBindingTable=swDHCPServerBindingTable, swDHCPServerManualBindingStatus=swDHCPServerManualBindingStatus, swDHCPServerMIB=swDHCPServerMIB, swDHCPServerPoolNextServer=swDHCPServerPoolNextServer, swDHCPServerConflictIPIPAddress=swDHCPServerConflictIPIPAddress, swDHCPServerNetBIOSNameServerStatus=swDHCPServerNetBIOSNameServerStatus, swDHCPServerDNSServerAddressStatus=swDHCPServerDNSServerAddressStatus, swDHCPServerDefaultRouterPoolName=swDHCPServerDefaultRouterPoolName, swDHCPServerPoolEntry=swDHCPServerPoolEntry, swDHCPServerPoolNetworkAddress=swDHCPServerPoolNetworkAddress, swDHCPServerPoolLeaseDay=swDHCPServerPoolLeaseDay, swDHCPServerConflictIPDetectionTime=swDHCPServerConflictIPDetectionTime, swDHCPServerDNSServerAddressIndex=swDHCPServerDNSServerAddressIndex)
| 144.263514 | 4,113 | 0.793405 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,890 | 0.135357 |
fdcd1b4c925a7d033b9a81f8136657b169b6bcf9 | 1,603 | py | Python | example_convert_dataset.py | fadamsyah/cv_utils | 487fc65fe4a71f05dd03df31cde21d866968c0b4 | [
"MIT"
]
| null | null | null | example_convert_dataset.py | fadamsyah/cv_utils | 487fc65fe4a71f05dd03df31cde21d866968c0b4 | [
"MIT"
]
| 1 | 2021-11-01T06:10:29.000Z | 2021-11-09T12:47:48.000Z | example_convert_dataset.py | fadamsyah/cv_utils | 487fc65fe4a71f05dd03df31cde21d866968c0b4 | [
"MIT"
]
| null | null | null | from cv_utils.object_detection.dataset.converter import coco_to_yolo
from cv_utils.object_detection.dataset.converter import yolo_to_coco
''' COCO --> YOLO
This code uses the ultralytics/yolov5 format.
The converted dataset will be saved as follow:
- {output_folder}
- images
- {output_set_name}
- {image_1}
- {image_2}
- ...
- labels
- {output_set_name}
- {image_1}
- {image_2}
- ...
- classes.txt
'''
for set_name in ["train", "test", "val"]:
coco_to_yolo(
coco_annotation_path = f"demo/dataset/fasciola_ori/annotations/instances_{set_name}.json",
coco_image_dir = f"demo/dataset/fasciola_ori/{set_name}",
output_image_dir = f"demo/dataset/fasciola_yolo/images/{set_name}",
output_label_dir = f"demo/dataset/fasciola_yolo/labels/{set_name}",
output_category_path = f"demo/dataset/fasciola_yolo/classes.txt"
)
'''YOLO --> COCO
This code uses the ultralytics/yolov5 format:
- {yolo_image_dir}
- {image_1}
- {image_2}
- ...
- {yolo_label_dir}
- {image_1}
- {image_2}
- ...
'''
for set_name in ["train", "test", "val"]:
yolo_to_coco(
yolo_image_dir = f"demo/dataset/fasciola_yolo/images/{set_name}",
yolo_label_dir = f"demo/dataset/fasciola_yolo/labels/{set_name}",
yolo_class_file = "demo/dataset/fasciola_yolo/classes.txt",
coco_image_dir = f"demo/dataset/fasciola_coco/{set_name}",
coco_annotation_path = f"demo/dataset/fasciola_coco/annotations/instances_{set_name}.json"
) | 32.714286 | 98 | 0.651903 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,069 | 0.666875 |
fdcf6f1f635a8225a76ad32f552e3db603ad1c14 | 2,369 | py | Python | jobs/api/models/keyword.py | gitdaniel228/jobSearch | 5dc1c69a3750f92ca0bcd378dfdc500143204a5a | [
"MIT"
]
| null | null | null | jobs/api/models/keyword.py | gitdaniel228/jobSearch | 5dc1c69a3750f92ca0bcd378dfdc500143204a5a | [
"MIT"
]
| null | null | null | jobs/api/models/keyword.py | gitdaniel228/jobSearch | 5dc1c69a3750f92ca0bcd378dfdc500143204a5a | [
"MIT"
]
| null | null | null | from django.db import models
from django.contrib import admin
from .country import Country
from .filter import Filter
from .setting import Setting
from .site import Site
class Keyword(models.Model):
site = models.ForeignKey('Site')
phrase = models.CharField(max_length=50)
feed_url = models.CharField(
max_length=255, blank=True, default='', help_text='for Upwork')
countries = models.ManyToManyField('Country')
class Meta:
app_label = 'api'
def __str__(self):
return self.phrase
def save(self, *args, **kwargs):
"""For Indeed: automatically adds Keyword-Country relation."""
init = False
if not self.pk:
init = True
super(Keyword, self).save(*args, **kwargs)
if init and self.site.code == 'Indeed':
sobj = Setting.objects.get(code='countries')
l = sobj.value.strip().split(',')
l = [x.strip() for x in l]
for co in l:
try:
c = Country.objects.get(code=co)
except Country.DoesNotExist:
continue
self.countries.add(c)
@staticmethod
def get_keywords(site_id):
table = Site.get_job_table(site_id)
query = 'SELECT COUNT(*) from {} WHERE keyword_id=api_keyword.id AND \
is_viewed=0 AND is_deleted=0 AND is_processed=1'
# Upwork
if site_id == 2:
avh = int(Filter.objects.get(code='avh').value)
budget = int(Filter.objects.get(code='budget').value)
spent = int(Filter.objects.get(code='spent').value)
query += ' AND (avg_hour_price=0 OR avg_hour_price>={})'.format(
avh)
query += ' AND (budget=0 OR budget>={})'.format(budget)
query += ' AND total_spent>={}'.format(spent)
query = query.format(table)
qs = Keyword.objects.filter(site_id=site_id)
qs = qs.extra(select={'quantity_nv_jobs': query})
qs = qs.values('id', 'phrase', 'site_id', 'quantity_nv_jobs')
return list(qs)
class CountryInline(admin.TabularInline):
model = Keyword.countries.through
@admin.register(Keyword)
class KeywordAdmin(admin.ModelAdmin):
inlines = [
CountryInline,
]
exclude = ('countries',)
list_display = ('site', 'phrase', 'feed_url')
| 31.171053 | 78 | 0.594344 | 2,164 | 0.913466 | 0 | 0 | 1,114 | 0.470241 | 0 | 0 | 461 | 0.194597 |
fdd4d7c9ea8afe2d857b858645122b0c43587a2f | 4,262 | py | Python | test/units/plugins/inventory/test_script.py | Container-Projects/ansible-provider-docs | 100b695b0b0c4d8d08af362069557ffc735d0d7e | [
"PSF-2.0",
"BSD-2-Clause",
"MIT"
]
| 37 | 2017-08-15T15:02:43.000Z | 2021-07-23T03:44:31.000Z | test/units/plugins/inventory/test_script.py | Container-Projects/ansible-provider-docs | 100b695b0b0c4d8d08af362069557ffc735d0d7e | [
"PSF-2.0",
"BSD-2-Clause",
"MIT"
]
| 12 | 2018-01-10T05:25:25.000Z | 2021-11-28T06:55:48.000Z | test/units/plugins/inventory/test_script.py | Container-Projects/ansible-provider-docs | 100b695b0b0c4d8d08af362069557ffc735d0d7e | [
"PSF-2.0",
"BSD-2-Clause",
"MIT"
]
| 49 | 2017-08-15T09:52:13.000Z | 2022-03-21T17:11:54.000Z | # -*- coding: utf-8 -*-
# Copyright 2017 Chris Meyers <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.loader import PluginLoader
from ansible.compat.tests import mock
from ansible.compat.tests import unittest
from ansible.module_utils._text import to_bytes, to_native
class TestInventoryModule(unittest.TestCase):
def setUp(self):
class Inventory():
cache = dict()
class PopenResult():
returncode = 0
stdout = b""
stderr = b""
def communicate(self):
return (self.stdout, self.stderr)
self.popen_result = PopenResult()
self.inventory = Inventory()
self.loader = mock.MagicMock()
self.loader.load = mock.MagicMock()
inv_loader = PluginLoader('InventoryModule', 'ansible.plugins.inventory', C.DEFAULT_INVENTORY_PLUGIN_PATH, 'inventory_plugins')
self.inventory_module = inv_loader.get('script')
self.inventory_module.set_options()
def register_patch(name):
patcher = mock.patch(name)
self.addCleanup(patcher.stop)
return patcher.start()
self.popen = register_patch('subprocess.Popen')
self.popen.return_value = self.popen_result
self.BaseInventoryPlugin = register_patch('ansible.plugins.inventory.BaseInventoryPlugin')
self.BaseInventoryPlugin.get_cache_prefix.return_value = 'abc123'
def test_parse_subprocess_path_not_found_fail(self):
self.popen.side_effect = OSError("dummy text")
with pytest.raises(AnsibleError) as e:
self.inventory_module.parse(self.inventory, self.loader, '/foo/bar/foobar.py')
assert e.value.message == "problem running /foo/bar/foobar.py --list (dummy text)"
def test_parse_subprocess_err_code_fail(self):
self.popen_result.stdout = to_bytes(u"fooébar", errors='surrogate_escape')
self.popen_result.stderr = to_bytes(u"dummyédata")
self.popen_result.returncode = 1
with pytest.raises(AnsibleError) as e:
self.inventory_module.parse(self.inventory, self.loader, '/foo/bar/foobar.py')
assert e.value.message == to_native("Inventory script (/foo/bar/foobar.py) had an execution error: "
"dummyédata\n ")
def test_parse_utf8_fail(self):
self.popen_result.returncode = 0
self.popen_result.stderr = to_bytes("dummyédata")
self.loader.load.side_effect = TypeError('obj must be string')
with pytest.raises(AnsibleError) as e:
self.inventory_module.parse(self.inventory, self.loader, '/foo/bar/foobar.py')
assert e.value.message == to_native("failed to parse executable inventory script results from "
"/foo/bar/foobar.py: obj must be string\ndummyédata\n")
def test_parse_dict_fail(self):
self.popen_result.returncode = 0
self.popen_result.stderr = to_bytes("dummyédata")
self.loader.load.return_value = 'i am not a dict'
with pytest.raises(AnsibleError) as e:
self.inventory_module.parse(self.inventory, self.loader, '/foo/bar/foobar.py')
assert e.value.message == to_native("failed to parse executable inventory script results from "
"/foo/bar/foobar.py: needs to be a json dict\ndummyédata\n")
| 40.207547 | 135 | 0.680432 | 3,137 | 0.734833 | 0 | 0 | 0 | 0 | 0 | 0 | 1,460 | 0.342 |
fdd740c29776fedc99f0ae3abe771a8f8e0fe2b3 | 2,781 | py | Python | app/routes.py | volvo007/flask_microblog | b826bcaa4fec6703a66f757e39fdf1fcced031f9 | [
"Apache-2.0"
]
| null | null | null | app/routes.py | volvo007/flask_microblog | b826bcaa4fec6703a66f757e39fdf1fcced031f9 | [
"Apache-2.0"
]
| null | null | null | app/routes.py | volvo007/flask_microblog | b826bcaa4fec6703a66f757e39fdf1fcced031f9 | [
"Apache-2.0"
]
| null | null | null | import time
from flask import render_template, flash, redirect, url_for
from flask.globals import request
from flask_login.utils import logout_user
from werkzeug.urls import url_parse
# from flask.helpers import flash # 闪动消息
from app import app, db # 第二个 app 是 init文件里的app 对象
from app.forms import LoginForm, RegistrationForm
from flask_login import current_user, login_user, login_required
from app.models import User
@app.route('/')
@app.route('/index')
@login_required # 登录保护只需要加一个装饰器,加了这个的,都必须登录才能访问
def index():
# user = {'username': 'Miguel'}
posts = [
{
'author': {'username': 'John'},
'body': 'b day'
},
{
'author': {'username': 'Lucy'},
'body': 'bbb day'
}
]
return render_template('index.html', title='Home', posts=posts)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated: # login 模块会默认创建一个用户为 current_user
return redirect(url_for('index')) # 如果登录成功,会被跳转到主页
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first() # 数据库查询用户
# 这里查询用户,或者没有,或者密码不对
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
# remember_me 用 cookie 保留登录状态
login_user(user, remember=form.remember_me.data)
# 虽然没有登录的用户会重定向到 login,不过会包含三种情况
# 1. 登录url没有 next 参数,则重定向到 /login
# 2. 登录url包含 next 设置为相对路径的参数,则重定向到该url
# 3. 登录url包含 next 设置为包含域名的完整 url 的参数,则重定向到 /index
# 这是为了保证,重定向只发生在站内,不会导向恶意网站
# 为了只发生1,2,要调用 werkzeug 的 url_parse 解析
# 举例,如果登录失败,会出现 login?next=%2Findex ,%2F 是 / 字符,也就是重定向到 index
# 不过因为没有登录,所以这个行为会被接着重定向回 login
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return redirect(url_for('index'))
return render_template('login.html', title='Sing In', form=form)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congrates, you now registered a new user')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form) | 37.08 | 82 | 0.647609 | 0 | 0 | 0 | 0 | 2,860 | 0.862745 | 0 | 0 | 1,408 | 0.424736 |
fdda757521b551e07a7f4e98103818cc6dd32745 | 10,501 | py | Python | asr_deepspeech/modules/deepspeech.py | shangdibufashi/ASRDeepSpeech | f11134abb79e98062fbc25fab99ca4cf675e538b | [
"MIT"
]
| 44 | 2020-03-03T13:05:57.000Z | 2022-03-24T03:42:31.000Z | asr_deepspeech/modules/deepspeech.py | shangdibufashi/ASRDeepSpeech | f11134abb79e98062fbc25fab99ca4cf675e538b | [
"MIT"
]
| 6 | 2020-12-15T10:58:19.000Z | 2021-10-12T01:59:17.000Z | asr_deepspeech/modules/deepspeech.py | shangdibufashi/ASRDeepSpeech | f11134abb79e98062fbc25fab99ca4cf675e538b | [
"MIT"
]
| 13 | 2020-05-20T06:42:20.000Z | 2022-03-24T03:42:31.000Z | import math
from collections import OrderedDict
import json
from asr_deepspeech.decoders import GreedyDecoder
import os
from ascii_graph import Pyasciigraph
from asr_deepspeech.data.loaders import AudioDataLoader
from asr_deepspeech.data.samplers import BucketingSampler
from .blocks import *
from asr_deepspeech.data.dataset import SpectrogramDataset
from argparse import Namespace
from zakuro import hub
class DeepSpeech(nn.Module):
def __init__(self,
audio_conf,
decoder,
id="asr",
label_path=None,
labels=None,
rnn_type="nn.LSTM",
rnn_hidden_size=768,
rnn_hidden_layers=5,
bidirectional=True,
context=20,
version='0.0.1',
model_path=None,
):
super(DeepSpeech, self).__init__()
labels = json.load(open(label_path, "r")) if labels is None else labels
self.version = version
self.id =id
self.decoder, self.audio_conf = decoder, audio_conf
self.context = context
self.rnn_hidden_size = rnn_hidden_size
self.rnn_hidden_layers = rnn_hidden_layers
self.rnn_type = eval(rnn_type)
self.labels = labels
self.bidirectional = bidirectional
self.sample_rate = self.audio_conf.sample_rate
self.window_size = self.audio_conf.window_size
self.num_classes = len(self.labels)
self.model_path = model_path
self.build_network()
self.decoder = GreedyDecoder(self.labels)
try:
assert model_path is not None
assert os.path.exists(model_path)
print(f"{self.id}>> Loading {model_path}")
ckpt = Namespace(**torch.load(model_path))
self.load_state_dict(ckpt.state_dict)
except:
pass
def build_network(self):
self.conv = MaskConv(nn.Sequential(
nn.Conv2d(1, 32, kernel_size=(41, 11), stride=(2, 2), padding=(20, 5)),
nn.BatchNorm2d(32),
nn.Hardtanh(0, 20, inplace=True),
nn.Conv2d(32, 32, kernel_size=(21, 11), stride=(2, 1), padding=(10, 5)),
nn.BatchNorm2d(32),
nn.Hardtanh(0, 20, inplace=True)
))
# Based on above convolutions and spectrogram size using conv formula (W - F + 2P)/ S+1
rnn_input_size = int(math.floor((self.sample_rate * self.window_size) / 2) + 1)
rnn_input_size = int(math.floor(rnn_input_size + 2 * 20 - 41) / 2 + 1)
rnn_input_size = int(math.floor(rnn_input_size + 2 * 10 - 21) / 2 + 1)
rnn_input_size *= 32
rnns = []
rnn = BatchRNN(input_size=rnn_input_size,
hidden_size=self.rnn_hidden_size,
rnn_type=self.rnn_type,
bidirectional=self.bidirectional,
batch_norm=False)
rnns.append(('0', rnn))
for x in range(self.rnn_hidden_layers - 1):
rnn = BatchRNN(input_size=self.rnn_hidden_size,
hidden_size=self.rnn_hidden_size,
rnn_type=self.rnn_type,
bidirectional=self.bidirectional)
rnns.append(('%d' % (x + 1), rnn))
self.rnns = nn.Sequential(OrderedDict(rnns))
self.lookahead = nn.Sequential(
# consider adding batch norm?
Lookahead(self.rnn_hidden_size,
context=self.context),
nn.Hardtanh(0, 20, inplace=True)
) if not self.bidirectional else None
fully_connected = nn.Sequential(
nn.BatchNorm1d(self.rnn_hidden_size),
nn.Linear(self.rnn_hidden_size, self.num_classes, bias=False)
)
self.fc = nn.Sequential(
SequenceWise(fully_connected),
)
self.inference_softmax = InferenceBatchSoftmax()
def forward(self, x, lengths):
lengths = lengths.cpu().int()
output_lengths = self.get_seq_lens(lengths)
x, _ = self.conv(x, output_lengths)
sizes = x.size()
x = x.view(sizes[0], sizes[1] * sizes[2], sizes[3]) # Collapse feature dimension
x = x.transpose(1, 2).transpose(0, 1).contiguous() # TxNxH
for rnn in self.rnns:
x = rnn(x, output_lengths)
if not self.bidirectional: # no need for lookahead layer in bidirectional
x = self.lookahead(x)
x = self.fc(x)
x = x.transpose(0, 1)
# identity in training mode, softmax in eval mode
x = self.inference_softmax(x)
return x, output_lengths
def get_loader(self, manifest, batch_size, num_workers):
dataset = SpectrogramDataset(audio_conf=self.audio_conf,
manifest_filepath=manifest,
labels=self.labels,
normalize=True,
spec_augment=self.audio_conf.spec_augment)
sampler = BucketingSampler(dataset,
batch_size=batch_size)
loader = AudioDataLoader(dataset,
num_workers=num_workers,
batch_sampler=sampler)
sampler.shuffle()
return loader, sampler
def __call__(self,
loader = None,
manifest=None,
batch_size=None,
cuda=True,
num_workers=32,
dist=None,
verbose=False,
half=False,
output_file=None,
main_proc=True,
restart_from=None):
with torch.no_grad():
if loader is None:
loader, sampler = self.get_loader(manifest=manifest,
batch_size=batch_size,
num_workers=num_workers)
if restart_from is not None:
hub.restart_from(self, restart_from)
device = "cuda"if cuda else "cpu"
decoder = self.decoder
target_decoder = self.decoder
self.eval()
self.to(device)
total_cer, total_wer, num_tokens, num_chars = 0, 0, 0, 0
output_data = []
min_str, max_str, last_str, min_cer, max_cer = "", "", "", 100, 0
hcers = dict([(k, 1) for k in range(10)])
for i, (data) in enumerate(loader):
inputs, targets, input_percentages, target_sizes = data
input_sizes = input_percentages.mul_(int(inputs.size(3))).int()
inputs = inputs.to(device)
if half:
inputs = inputs.half()
# unflatten targets
split_targets = []
offset = 0
for size in target_sizes:
split_targets.append(targets[offset:offset + size])
offset += size
out, output_sizes = self.forward(inputs, input_sizes)
decoded_output, _ = decoder.decode(out, output_sizes)
target_strings = target_decoder.convert_to_strings(split_targets)
if output_file is not None:
# add output to data array, and continue
output_data.append((out.detach().cpu().numpy(), output_sizes.numpy(), target_strings))
for x in range(len(target_strings)):
transcript, reference = decoded_output[x][0], target_strings[x][0]
wer_inst = decoder.wer(transcript, reference)
cer_inst = decoder.cer(transcript, reference)
total_wer += wer_inst
total_cer += cer_inst
num_tokens += len(reference.split())
num_chars += len(reference.replace(' ', ''))
wer_inst = float(wer_inst) / len(reference.split())
cer_inst = float(cer_inst) / len(reference.replace(' ', ''))
wer_inst = wer_inst * 100
cer_inst = cer_inst * 100
wer_inst = min(wer_inst, 100)
cer_inst = min(cer_inst, 100)
hcers[min(int(cer_inst//10), 9)]+=1
last_str = f"Ref:{reference.lower()}" \
f"\nHyp:{transcript.lower()}" \
f"\nWER:{wer_inst} " \
f"- CER:{cer_inst}"
if cer_inst < min_cer:
min_cer = cer_inst
min_str = last_str
if cer_inst > max_cer:
max_cer = cer_inst
max_str = last_str
print(last_str) if verbose else None
wer = float(total_wer) / num_tokens
cer = float(total_cer) / num_chars
cers = [(f'{k*10}-{(k*10) + 10}', v-1) for k, v in hcers.items()]
graph = Pyasciigraph()
asciihistogram = "\n|".join(graph.graph('CER histogram', cers))
if main_proc and output_file is not None:
with open(output_file, "w") as f:
f.write("\n".join([
f"================= {wer*100:.2f}/{cer*100:.2f} =================",
"----- BEST -----",
min_str,
"----- LAST -----",
last_str,
"----- WORST -----",
max_str,
asciihistogram,
"=============================================\n"
]))
return wer * 100, cer * 100, output_data
def get_seq_lens(self, input_length):
"""
Given a 1D Tensor or Variable containing integer sequence lengths, return a 1D tensor or variable
containing the size sequences that will be output by the network.
:param input_length: 1D Tensor
:return: 1D Tensor scaled by model
"""
seq_len = input_length
for m in self.conv.modules():
if type(m) == nn.modules.conv.Conv2d:
seq_len = ((seq_len + 2 * m.padding[1] - m.dilation[1] * (m.kernel_size[1] - 1) - 1) / m.stride[1] + 1)
return seq_len.int()
| 42.172691 | 119 | 0.517475 | 10,093 | 0.961147 | 0 | 0 | 0 | 0 | 0 | 0 | 990 | 0.094277 |
fddb07c49fca7dc8739e0a7542a2263412a966ed | 179 | py | Python | ao2j/lt1300/046/B.py | neshdev/competitive-prog | f406a85d62e83c3dbd3ad41f42ae121ebefd0fda | [
"MIT"
]
| null | null | null | ao2j/lt1300/046/B.py | neshdev/competitive-prog | f406a85d62e83c3dbd3ad41f42ae121ebefd0fda | [
"MIT"
]
| null | null | null | ao2j/lt1300/046/B.py | neshdev/competitive-prog | f406a85d62e83c3dbd3ad41f42ae121ebefd0fda | [
"MIT"
]
| null | null | null | n,k = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
arr.sort()
total = 0
for i in range(k):
if arr[i] < 0:
total += -arr[i]
print(total)
| 16.272727 | 39 | 0.536313 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
fddb0cd219604b7758190e6bb17c4dc60b79a754 | 1,099 | py | Python | Scripts/simulation/ensemble/ensemble_interactions.py | velocist/TS4CheatsInfo | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | [
"Apache-2.0"
]
| null | null | null | Scripts/simulation/ensemble/ensemble_interactions.py | velocist/TS4CheatsInfo | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | [
"Apache-2.0"
]
| null | null | null | Scripts/simulation/ensemble/ensemble_interactions.py | velocist/TS4CheatsInfo | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | [
"Apache-2.0"
]
| null | null | null | # uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\ensemble\ensemble_interactions.py
# Compiled at: 2016-07-13 03:28:12
# Size of source mod 2**32: 1070 bytes
from objects.base_interactions import ProxyInteraction
from sims4.utils import classproperty, flexmethod
class EnsembleConstraintProxyInteraction(ProxyInteraction):
INSTANCE_SUBCLASSES_ONLY = True
@classproperty
def proxy_name(cls):
return '[Ensemble]'
@classmethod
def generate(cls, proxied_affordance, ensemble):
result = super().generate(proxied_affordance)
result.ensemble = ensemble
return result
@flexmethod
def _constraint_gen(cls, inst, *args, **kwargs):
inst_or_cls = inst if inst is not None else cls
for constraint in (super(__class__, inst_or_cls)._constraint_gen)(*args, **kwargs):
yield constraint
yield inst_or_cls.ensemble.get_center_of_mass_constraint() | 37.896552 | 107 | 0.724295 | 665 | 0.605096 | 293 | 0.266606 | 552 | 0.502275 | 0 | 0 | 334 | 0.303913 |
fddc8823ffb3b416234d50c4b32a14d5668ecba6 | 1,663 | py | Python | icmpv6socket/__init__.py | TheDiveO/icmpv6-socket | fe3ee52e6793e3739975aea87e2b6511be96fa12 | [
"Apache-2.0"
]
| null | null | null | icmpv6socket/__init__.py | TheDiveO/icmpv6-socket | fe3ee52e6793e3739975aea87e2b6511be96fa12 | [
"Apache-2.0"
]
| null | null | null | icmpv6socket/__init__.py | TheDiveO/icmpv6-socket | fe3ee52e6793e3739975aea87e2b6511be96fa12 | [
"Apache-2.0"
]
| null | null | null |
import socket
from typing import Optional, List
__version__ = '0.1.0'
class ICMPv6Socket(socket.socket):
# From https://elixir.bootlin.com/linux/v4.18/source/include/linux/socket.h#L312
SOL_ICMPV6 = 58 # type: int
# From https://elixir.bootlin.com/linux/v4.18/source/include/uapi/linux/icmpv6.h#L139
ICMPV6_FILTER = 1 # type: int
# From ... yeah, not in the Linux kernel header files?!
ICMPV6_ROUTER_SOL = 133 # type: int
ICMPV6_ROUTER_ADV = 134 # type: int
def __init__(self, message_types: Optional[List[int]] = None) \
-> None:
"""Initializes an ICMPv6 socket. There isn't much argument here,
it seems, unless you want to receive only certain ICMPv6 message
types.
:arg message_types: optional list of ICMPv6 message types (int).
Defaults to None.
"""
super(ICMPv6Socket, self).__init__(socket.AF_INET6,
socket.SOCK_RAW,
socket.IPPROTO_ICMPV6)
self._filter_mask = bytearray(b'\x00' * 32) # type: bytes
self.accept_type(message_types)
def accept_type(self, message_types: List[int]):
# Please note that with the ICMPv6 filtering socket option
# a "1" actually means to filter out(!), while "0" means to
# let it pass to the socket. Crooked logic.
self._filter_mask = bytearray(b'\xff' * 32)
for msg_type in message_types:
self._filter_mask[msg_type >> 3] &= ~(1 << (msg_type & 7))
self.setsockopt(self.SOL_ICMPV6, self.ICMPV6_FILTER,
self._filter_mask)
| 36.955556 | 89 | 0.615755 | 1,586 | 0.953698 | 0 | 0 | 0 | 0 | 0 | 0 | 724 | 0.435358 |
fddd39b69360c06e6b24844fb2887dcd6cf29f89 | 603 | py | Python | game/pkchess/res/map.py | RaenonX/Jelly-Bot-API | c7da1e91783dce3a2b71b955b3a22b68db9056cf | [
"MIT"
]
| 5 | 2020-08-26T20:12:00.000Z | 2020-12-11T16:39:22.000Z | game/pkchess/res/map.py | RaenonX/Jelly-Bot | c7da1e91783dce3a2b71b955b3a22b68db9056cf | [
"MIT"
]
| 234 | 2019-12-14T03:45:19.000Z | 2020-08-26T18:55:19.000Z | game/pkchess/res/map.py | RaenonX/Jelly-Bot-API | c7da1e91783dce3a2b71b955b3a22b68db9056cf | [
"MIT"
]
| 2 | 2019-10-23T15:21:15.000Z | 2020-05-22T09:35:55.000Z | """Game map resource manager."""
__all__ = ("get_map_template",)
_cache = {}
def get_map_template(name: str):
"""
Get a map template by its ``name``.
Returns ``None`` if not found.
Loaded :class:`MapTemplate` will be cached until the application exits.
:param name: name of the map template.
:return: map template object if found
"""
if name not in _cache:
# On-demand import & avoid circular import
from game.pkchess.map import MapTemplate
_cache[name] = MapTemplate.load_from_file(f"game/pkchess/res/map/{name}")
return _cache[name]
| 24.12 | 81 | 0.658375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 372 | 0.616915 |
fddd3e193fe076cab7c0cf9457a9b99d97220113 | 248 | py | Python | example/main_01.py | janothan/Evaluation-Framework | e53847bc352f657953933e1d7c97b68ac890c852 | [
"Apache-2.0"
]
| 5 | 2020-02-12T13:11:14.000Z | 2021-01-28T12:45:22.000Z | example/main_01.py | charyeezy/Evaluation-Framework | ddfd4ea654a3d7d2abd58f062ec98a8a736f8f51 | [
"Apache-2.0"
]
| 9 | 2019-07-29T17:45:30.000Z | 2022-03-17T12:24:47.000Z | example/main_01.py | charyeezy/Evaluation-Framework | ddfd4ea654a3d7d2abd58f062ec98a8a736f8f51 | [
"Apache-2.0"
]
| 7 | 2020-02-12T13:22:49.000Z | 2021-11-29T01:08:50.000Z | from evaluation_framework.manager import FrameworkManager
if __name__ == "__main__":
evaluation_manager = FrameworkManager()
evaluation_manager.evaluate(
"objectFrequencyS.h5", vector_file_format="hdf5", debugging_mode=False
)
| 31 | 78 | 0.766129 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 37 | 0.149194 |
fddd8f9fba011d6c4a116c9eb70ffe36d73e109e | 7,127 | py | Python | public_data/views.py | danamlewis/open-humans | 9b08310cf151f49032b66ddd005bbd47d466cc4e | [
"MIT"
]
| 57 | 2016-09-01T21:55:52.000Z | 2022-03-27T22:15:32.000Z | public_data/views.py | danamlewis/open-humans | 9b08310cf151f49032b66ddd005bbd47d466cc4e | [
"MIT"
]
| 464 | 2015-03-23T18:08:28.000Z | 2016-08-25T04:57:36.000Z | public_data/views.py | danamlewis/open-humans | 9b08310cf151f49032b66ddd005bbd47d466cc4e | [
"MIT"
]
| 25 | 2017-01-24T16:23:27.000Z | 2021-11-07T01:51:42.000Z | from django.conf import settings
from django.contrib import messages as django_messages
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_POST
from django.views.generic.base import RedirectView, TemplateView
from django.views.generic.edit import CreateView, FormView
from raven.contrib.django.raven_compat.models import client as raven_client
from common.mixins import PrivateMixin
from common.utils import get_source_labels
from private_sharing.models import (
ActivityFeed,
DataRequestProject,
DataRequestProjectMember,
id_label_to_project,
)
from .forms import ConsentForm
from .models import PublicDataAccess, WithdrawalFeedback
class QuizView(PrivateMixin, TemplateView):
"""
Modification of TemplateView that accepts and requires POST.
This prevents users from jumping to the quiz link without going through
the informed consent pages.
"""
template_name = "public_data/quiz.html"
@method_decorator(require_POST)
def dispatch(self, *args, **kwargs):
return super(QuizView, self).dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
return self.get(*args, **kwargs)
class ConsentView(PrivateMixin, FormView):
"""
Modification of FormView that walks through the informed consent content.
Stepping through the form is triggered by POST requests containing new
values in the 'section' field. If this field is present, the view overrides
form data processing.
"""
template_name = "public_data/consent.html"
form_class = ConsentForm
success_url = reverse_lazy("home")
def get(self, request, *args, **kwargs):
"""Customized to allow additional context."""
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form, **kwargs))
def form_invalid(self, form):
"""
Customized to add final section marker when reloading.
"""
return self.render_to_response(self.get_context_data(form=form, section=6))
def post(self, request, *args, **kwargs):
"""
Customized to convert a POST with 'section' into GET request.
"""
if "section" in request.POST:
kwargs["section"] = int(request.POST["section"])
self.request.method = "GET"
return self.get(request, *args, **kwargs)
else:
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
"""
If the form is valid, redirect to the supplied URL.
"""
participant = self.request.user.member.public_data_participant
participant.enrolled = True
participant.save()
django_messages.success(
self.request,
("Thank you! The public data sharing " "feature is now activated."),
)
return super(ConsentView, self).form_valid(form)
class ToggleSharingView(PrivateMixin, RedirectView):
"""
Toggle the specified data_file to the specified value of public.
"""
permanent = False
url = reverse_lazy("my-member-data")
def get_redirect_url(self):
if "next" in self.request.POST:
return self.request.POST["next"]
else:
return super(ToggleSharingView, self).get_redirect_url()
def toggle_data(self, user, source, public):
if source not in get_source_labels() and not source.startswith(
"direct-sharing-"
):
error_msg = (
"Public sharing toggle attempted for "
'unexpected source "{}"'.format(source)
)
django_messages.error(self.request, error_msg)
if not settings.TESTING:
raven_client.captureMessage(error_msg)
return
project = id_label_to_project(source)
project_membership = DataRequestProjectMember.objects.get(
member=user.member, project=project
)
participant = user.member.public_data_participant
access, _ = PublicDataAccess.objects.get_or_create(
participant=participant, project_membership=project_membership
)
access.is_public = False
if public == "True":
if not project.no_public_data:
access.is_public = True
access.save()
if (
project.approved
and not ActivityFeed.objects.filter(
member=user.member, project=project, action="publicly-shared"
).exists()
):
event = ActivityFeed(
member=user.member, project=project, action="publicly-shared"
)
event.save()
def post(self, request, *args, **kwargs):
"""
Toggle public sharing status of a dataset.
"""
if "source" in request.POST and "public" in request.POST:
public = request.POST["public"]
source = request.POST["source"]
if public not in ["True", "False"]:
raise ValueError("'public' must be 'True' or 'False'")
self.toggle_data(request.user, source, public)
else:
raise ValueError("'public' and 'source' must be specified")
return super(ToggleSharingView, self).post(request, *args, **kwargs)
class WithdrawView(PrivateMixin, CreateView):
"""
A form that withdraws the user from the study on POST.
"""
template_name = "public_data/withdraw.html"
model = WithdrawalFeedback
fields = ["feedback"]
success_url = reverse_lazy("public-data:home")
def form_valid(self, form):
"""
If the form is valid, redirect to the supplied URL.
"""
participant = self.request.user.member.public_data_participant
participant.enrolled = False
participant.save()
django_messages.success(
self.request,
(
"You have successfully deactivated public data sharing and marked "
"your files as private."
),
)
form.instance.member = self.request.user.member
return super(WithdrawView, self).form_valid(form)
class HomeView(TemplateView):
"""
Provide this page's URL as the next URL for login or signup.
"""
template_name = "public_data/home.html"
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
projects = DataRequestProject.objects.filter(
approved=True, active=True
).order_by("name")
context.update({"projects": projects, "next": reverse_lazy("public-data:home")})
return context
class ActivateOverviewView(PrivateMixin, TemplateView):
"""
Apply PrivateMixin
"""
template_name = "public_data/overview.html"
| 30.852814 | 88 | 0.638698 | 6,368 | 0.893504 | 0 | 0 | 135 | 0.018942 | 0 | 0 | 1,796 | 0.251999 |
fddf95ac612e69b154ea7fc28a7e99daf0730fea | 685 | py | Python | UserAlgorithm.py | Anirudhsfc/RunTimeAlgo | eb0fb706b4c738bad603327a94c9724e3dfe8fee | [
"MIT"
]
| 1 | 2019-09-03T08:28:26.000Z | 2019-09-03T08:28:26.000Z | UserAlgorithm.py | Anirudhsfc/RunTimeAlgo | eb0fb706b4c738bad603327a94c9724e3dfe8fee | [
"MIT"
]
| null | null | null | UserAlgorithm.py | Anirudhsfc/RunTimeAlgo | eb0fb706b4c738bad603327a94c9724e3dfe8fee | [
"MIT"
]
| null | null | null | from MakeYourOwnGraph import * #user needs to import this line
def F1(x,y):
if x<=2:
return 1
else:
return F1(x-1,y)+F1(x-2,y)
GraphOfMyAlgo(F1,2,[1,30,2,31]) #user needs to execute this line in his or her algorithm where the first argument is the name of the Algorithm Function, here F1
#the Second argument is the number of arguments that the algorithm of the user inputs
#the third argument is an array of ranges, namely beginning value of range, ending value of range_for_first_argument, beginning value of range_for_second_argument, ending value of range_for_second_argument and so on | 52.692308 | 247 | 0.681752 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 459 | 0.670073 |
fde563740923e926b86419c22eb43be2e6e526e1 | 38 | py | Python | robopilot/pipeline/__init__.py | robotory/robopilot | e10207b66d06e5d169f890d1d7e57d971ca1eb5d | [
"MIT"
]
| null | null | null | robopilot/pipeline/__init__.py | robotory/robopilot | e10207b66d06e5d169f890d1d7e57d971ca1eb5d | [
"MIT"
]
| null | null | null | robopilot/pipeline/__init__.py | robotory/robopilot | e10207b66d06e5d169f890d1d7e57d971ca1eb5d | [
"MIT"
]
| null | null | null | # The new robopilot training pipeline. | 38 | 38 | 0.815789 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 38 | 1 |
fde56cf34b5e2c673b4f1db2a825702a705cb407 | 1,257 | py | Python | dsRenamingTool/dialogBase.py | S0nic014/dsRenamingTool | 97efcd660af820ab6b5f1918222ba31a95d47788 | [
"MIT"
]
| 2 | 2020-07-15T16:59:31.000Z | 2021-08-17T14:04:15.000Z | dsRenamingTool/dialogBase.py | S0nic014/dsRenamingTool | 97efcd660af820ab6b5f1918222ba31a95d47788 | [
"MIT"
]
| null | null | null | dsRenamingTool/dialogBase.py | S0nic014/dsRenamingTool | 97efcd660af820ab6b5f1918222ba31a95d47788 | [
"MIT"
]
| null | null | null | import sys
from PySide2 import QtCore
from PySide2 import QtWidgets
from shiboken2 import wrapInstance
import maya.OpenMayaUI as omui
def mayaMainWindow():
"""
Get maya main window as QWidget
:return: Maya main window as QWidget
:rtype: PySide2.QtWidgets.QWidget
"""
mainWindowPtr = omui.MQtUtil.mainWindow()
if mainWindowPtr:
if sys.version_info[0] < 3:
return wrapInstance(long(mainWindowPtr), QtWidgets.QWidget) # noqa: F821
else:
return wrapInstance(int(mainWindowPtr), QtWidgets.QWidget)
else:
mayaMainWindow()
class _modalDialog(QtWidgets.QDialog):
def __init__(self, parent=mayaMainWindow()):
super(_modalDialog, self).__init__(parent)
# Disable question mark for windows
self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)
# MacOSX window stay on top
self.setProperty("saveWindowPref", True)
self.createActions()
self.createWidgets()
self.createLayouts()
self.createConnections()
def createActions(self):
pass
def createWidgets(self):
pass
def createLayouts(self):
pass
def createConnections(self):
pass
| 24.647059 | 87 | 0.668258 | 654 | 0.520286 | 0 | 0 | 0 | 0 | 0 | 0 | 217 | 0.172633 |
fde68e690db6e169850d5ee88a2ba6ad82e43a9a | 853 | py | Python | beyondtheadmin/invoices/templatetags/fullurl.py | gfavre/invoice-manager | 2a1db22edd51b461c090282c6fc1f290f3265379 | [
"MIT"
]
| 1 | 2021-11-27T06:40:34.000Z | 2021-11-27T06:40:34.000Z | beyondtheadmin/invoices/templatetags/fullurl.py | gfavre/invoice-manager | 2a1db22edd51b461c090282c6fc1f290f3265379 | [
"MIT"
]
| 2 | 2021-05-13T04:50:50.000Z | 2022-02-28T21:06:24.000Z | beyondtheadmin/invoices/templatetags/fullurl.py | gfavre/invoice-manager | 2a1db22edd51b461c090282c6fc1f290f3265379 | [
"MIT"
]
| null | null | null | import math
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def buildfullurl(context, url):
"""Converts relative URL to absolute.
For example:
{% buildfullurl article.get_absolute_url %}
or:
{% buildfullurl "/custom-url/" %}
"""
return context.request.build_absolute_uri(url)
@register.filter(is_safe=True, )
def add_domain(value):
try:
number = float(value)
frac, integer = math.modf(number)
if frac:
return mark_safe('CHF <span class="value">{:1,.2f}</span>'.format(number).replace(',', "'"))
else:
return mark_safe('CHF <span class="value">{:1,.0f}.-</span>'.format(number).replace(',', "'"))
except (ValueError, TypeError):
return value
| 26.65625 | 106 | 0.637749 | 0 | 0 | 0 | 0 | 728 | 0.853458 | 0 | 0 | 260 | 0.304807 |
fde73e6cb304ab68d07ceb772b316e170a4014cb | 967 | py | Python | big_o_project/Task4.py | CTylerD/Data-Structures-Algorithms-Projects | e72248a6433c0242003edf404a715d9f53e3792d | [
"MIT"
]
| null | null | null | big_o_project/Task4.py | CTylerD/Data-Structures-Algorithms-Projects | e72248a6433c0242003edf404a715d9f53e3792d | [
"MIT"
]
| null | null | null | big_o_project/Task4.py | CTylerD/Data-Structures-Algorithms-Projects | e72248a6433c0242003edf404a715d9f53e3792d | [
"MIT"
]
| null | null | null | import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
def create_lists_of_users():
outgoing_callers = set()
not_telemarketers = set()
for idx, call in enumerate(calls):
outgoing_callers.add(calls[idx][0])
not_telemarketers.add(calls[idx][1])
for idx, text in enumerate(texts):
not_telemarketers.add(texts[idx][0])
not_telemarketers.add(texts[idx][1])
find_telemarketers(outgoing_callers, not_telemarketers)
def find_telemarketers(out_calls, not_telemarketers):
potential_telemarketers = out_calls.difference(not_telemarketers)
print_results(potential_telemarketers)
def print_results(potential_telemarketers):
print("These numbers could be telemarketers:")
for number in sorted(potential_telemarketers):
print(number, sep="\n")
create_lists_of_users()
| 26.861111 | 69 | 0.709411 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 71 | 0.073423 |
fde75eeec45ccf538859617be8047b6998c73dee | 971 | py | Python | codingstars/platinum3/subarray-sum2.py | yehyunchoi/Algorithm | 35e32159ee13b46b30b543fa79ab6e81d6719f13 | [
"MIT"
]
| null | null | null | codingstars/platinum3/subarray-sum2.py | yehyunchoi/Algorithm | 35e32159ee13b46b30b543fa79ab6e81d6719f13 | [
"MIT"
]
| null | null | null | codingstars/platinum3/subarray-sum2.py | yehyunchoi/Algorithm | 35e32159ee13b46b30b543fa79ab6e81d6719f13 | [
"MIT"
]
| null | null | null | """
[1,2,3,4]의 부분 배열은 다음과 같이 16개가 있습니다.
[]
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 4]
[1, 3]
[1, 3, 4]
[1, 4]
[2]
[2, 3]
[2, 3, 4]
[2, 4]
[3]
[3, 4]
[4]
처음에 있는 blank list([])의 값을 0으로 계산하면
모든 부분 배열의 합(subarray sum)은 80입니다.
숫자로 된 배열을 입력 받아서,
부분 배열의 합을 구하여 보세요.
Input
숫자로 된 배열이 입력됩니다.
숫자는 정수입니다.
Output
부분 배열의 합을 출력합니다.
Sample Input 1
3 26 -14 12 4 -2
Sample Output 1
928
"""
def subarraySum(i=0, s=[]):
global total
total += sum(s)
if (i > n):
return
# duplicate check is here now (i, n); instead of checking duplicate, just skip the index
for k in range(i, n):
subarraySum(k+1, s+[arr[k]])
######################
# sorting step makes it very hard when it comes to computation time.
# infact, it wasn't the sorting -- it was the range(n) --> range(i, n) that made a difference
# different approach:
# just sum it as you iterate
arr = list(map(int, input().split()))
n = len(arr)
total = 0
subarraySum()
print(total) | 15.412698 | 93 | 0.582904 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 902 | 0.770282 |
fde7b9b224da23bd030fbd50ece0e5433d5c208e | 1,683 | py | Python | fastalite/__main__.py | nhoffman/fastalite | 2571c126976f26c8ca06401586559f288245ca8d | [
"MIT"
]
| 2 | 2017-02-16T14:30:18.000Z | 2019-10-03T19:20:57.000Z | fastalite/__main__.py | nhoffman/fastalite | 2571c126976f26c8ca06401586559f288245ca8d | [
"MIT"
]
| 4 | 2017-06-30T14:05:08.000Z | 2022-02-17T00:03:28.000Z | fastalite/__main__.py | nhoffman/fastalite | 2571c126976f26c8ca06401586559f288245ca8d | [
"MIT"
]
| null | null | null | """Command line interface to the fastlite package
"""
import sys
import argparse
from .fastalite import fastalite, fastqlite, Opener
from . import __version__
def count(seqs, fname):
i = 1
for i, seq in enumerate(seqs, 1):
pass
print(('{}\t{}'.format(fname, i)))
def names(seqs, fname):
for seq in seqs:
print(('{}\t{}'.format(fname, seq.id)))
def lengths(seqs, fname):
for seq in seqs:
print(('{}\t{}\t{}'.format(fname, seq.id, len(seq.seq))))
def main(arguments):
actions = {'count': count, 'names': names, 'lengths': lengths}
parser = argparse.ArgumentParser(
prog='fastalite', description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('action', choices=list(actions.keys()),
help="Action to perform")
parser.add_argument('infiles', help="Input file", nargs='+',
metavar='infile.{fasta,fastq}[{.gz,.bz2}]',
type=Opener('r'))
parser.add_argument('-V', '--version', action='version',
version=__version__,
help='Print the version number and exit')
args = parser.parse_args(arguments)
for infile in args.infiles:
with infile as f:
readfun = fastalite if 'fasta' in f.name else fastqlite
seqs = readfun(f)
try:
fun = actions[args.action]
fun(seqs, infile.name)
except ValueError as err:
sys.stderr.write('Error: {}\n'.format(str(err)))
return 1
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| 28.525424 | 67 | 0.572193 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 293 | 0.174094 |
fde8def0c521fe98b37b37c32684b2ac7afe4bd0 | 142 | py | Python | music/class_/audioa/_mode/major.py | jedhsu/music | dea68c4a82296cd4910e786f533b2cbf861377c3 | [
"MIT"
]
| null | null | null | music/class_/audioa/_mode/major.py | jedhsu/music | dea68c4a82296cd4910e786f533b2cbf861377c3 | [
"MIT"
]
| null | null | null | music/class_/audioa/_mode/major.py | jedhsu/music | dea68c4a82296cd4910e786f533b2cbf861377c3 | [
"MIT"
]
| null | null | null | """
*Major Key*
"""
from abc import ABCMeta
from ._key import ModedKey
class MajorKey(
ModedKey,
):
__metaclass__ = ABCMeta
| 8.875 | 27 | 0.640845 | 60 | 0.422535 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0.176056 |
fdeadae2e6055ffb652fbc50ce8253522e83b82c | 151 | py | Python | bb_clients/__init__.py | voglster/ims_client | 34021dd81fcc0196eb2fb23820571b766a50aaa7 | [
"MIT"
]
| null | null | null | bb_clients/__init__.py | voglster/ims_client | 34021dd81fcc0196eb2fb23820571b766a50aaa7 | [
"MIT"
]
| null | null | null | bb_clients/__init__.py | voglster/ims_client | 34021dd81fcc0196eb2fb23820571b766a50aaa7 | [
"MIT"
]
| null | null | null | """Simple python clients for the Gravitate BestBuy Services"""
__version__ = "0.1.18"
from .fc import get_fc_service
from .ims import get_ims_service
| 25.166667 | 62 | 0.781457 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 0.463576 |
fdeb572c08b15704dfb038c3b7db65f44b06027a | 9,482 | py | Python | RpgPiratesAndFishers/Individual.py | LucasRR94/RPG_Pirates_and_Fishers | 75bbb57e916f7a878de34676b1d988e5d2506121 | [
"Apache-2.0"
]
| null | null | null | RpgPiratesAndFishers/Individual.py | LucasRR94/RPG_Pirates_and_Fishers | 75bbb57e916f7a878de34676b1d988e5d2506121 | [
"Apache-2.0"
]
| null | null | null | RpgPiratesAndFishers/Individual.py | LucasRR94/RPG_Pirates_and_Fishers | 75bbb57e916f7a878de34676b1d988e5d2506121 | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from libGamePiratesAndFishers import assertIfIsWeelFormat,makeSureThatIsnumberLimited
class Individual(object):
"""
This class Define object type Individual, it is a base for object used for being the base
of fishers, and is used for enemies in application.
"""
def __init__(self,name,health,attack,defense):
"""
Initializing the class Individual, it's the constructor, assigned
the name and three attributes used for create fishers and enemies.
@param name : (string) constains the name of Individual
@param health : (int) attribute for the class represent the health of the individual, 0..100
@param attack : (int) attribute for the class represent the attack of the individual, 0...100
@param defense : (int) attribute for the class represent the defense of the individual,0...100
@return : None
"""
self.name = assertIfIsWeelFormat(name)
self.health = makeSureThatIsnumberLimited(health,100)
if(self.health == 0):
self.health = 1
self.attack = makeSureThatIsnumberLimited(attack,100)
self.defense = makeSureThatIsnumberLimited(defense,100)
def __del__(self):
"""
it's destructor from the class, cleaning all the attributes
@param none :
@return : None
"""
self.name = ''
self.health = None
self.attack = None
self.defense = None
def getName(self):
"""
it's return an attribute of the class call Name, that represent the name of the individual in game
@param none:
@return : (string) return a attribute name of the object
"""
return self.name
def getHealth(self):
"""
it's return an attribute of the class that represent the health of the individual in the game
@param none:
@return : (int) return a attribute that is the health, between 0 ... 100
"""
return self.health
def getValueDefense(self):
"""
it's return an attribute of the class that represent the defense of the individual in the game
@param none:
@return : (int) return a attribute that is the defense, between 0 ... 100
"""
return self.defense
def getValueAttack(self):
"""
it's return an attribute of the class that represent the attack of the individual in the game
@param none:
@return : (int) return a attribute that is the attack, between 0 ... 100
"""
return self.attack
def __setAttack(self,attack):
"""
it's seting an attribute of the class, the attribute named attack
@param attack:(int) a integer between 0..100, that will be sum in the attribute
@return None :
"""
self.attack = attack
def __setDefense(self,defense):
"""
it's seting an attribute of the class, the attribute named defense
@param defense:(int) a integer between 0..100, that will be sum in the attribute
@return None :
"""
self.defense = defense
def __setHealth(self,health):
"""
it's seting an attribute of the class, the attribute named health
@param health:(int) a integer between 0..100, that will replace the attribute
@return None :
"""
if(health == 0):
self.__del__()
else:
self.health = health
def __changeAttackOrDefense(self,newvalue,option):
"""
it's change the attribute attack or defense by other number, when the player want exchange the weapon
or the defense
when option is : 1 --> attack
: 2 --> defense
@param newvalue:(int) a integer between 0..100, that will replace the attribute
@return oldavalue :(int or tuple) integer that represent the old capacity of attack or defense,
or None plus a message of error
"""
answer = None
if(type(newvalue) is int):
newnumb = newvalue
if(newnumb > 100):
newnumb = 100
if(newnumb < 0):
newnumb = 0
if((type(option) is int)):
if(option >=1 and option <= 2):
if(option == 1):
answer = self.getValueAttack()
self.__setAttack(newnumb) # change the values
return answer
else:
answer = self.getValueDefense()
self.__setDefense(newnumb) # change the values
return answer
else:
resptuple = (None,"error, this is not an supported option")
answer = resptuple
else:
resptuple = (None,"error, this is not an supported option")
answer = resptuple
if(type(newvalue) is str): # try to make conversion between str -> int
try:
newnumb = int(newvalue)
except ValueError:
resptuple = (None,"error, this is not an supported type")
answer = resptuple
else:
if(newnumb > 100):
newnumb = 100
if(newnumb < 0):
newnumb = 0
if((type(option) is int)):
if(option >=1 and option <= 2):
if(option == 1):
answer = self.getValueAttack()
self.__setAttack(newnumb) # change the values
return answer
else:
answer = self.getValueDefense()
self.__setDefense(newnumb) # change the values
return answer
else:
resptuple = (None,"error, this is not an supported option")
answer = resptuple
else:
resptuple = (None,"error, this is not an supported option")
answer = resptuple
finally:
return answer
else:
resptuple = (None,"error, this is not an supported type")
return resptuple
def usingMedkit(self, valuehealth):
"""
it's adding one medkit in health.If the health is on max, it's discarded, and maintaining health in 100
@param valuehealth:(int) a integer between 0..100, that will added in health attribute
@return (int): return 1 , when sucessfull use, 0 when it's not possible the use of medkit
"""
if(type(valuehealth) is int):
newnumb = valuehealth
if(newnumb > 100):
newnumb = 100
if(newnumb < 0):
newnumb = 0
backuphealth = self.getHealth()
updatevalue = newnumb + backuphealth
if(updatevalue >= 100):
self.__setHealth(100)
return 1
elif(newnumb == 0):
return 1
else:
self.__setHealth(updatevalue)
return 1
if(type(valuehealth) is str):
try:
newnumb = int(valuehealth)
except ValueError:
answer = 0
else:
if(newnumb > 100):
newnumb = 100
if(newnumb < 0):
newnumb = 0
backuphealth = self.getHealth()
updatevalue = newnumb + backuphealth
if(updatevalue>=100):
self.__setHealth(100)
answer = 1
elif(newnumb == 0):
answer= 1
else:
self.__setHealth(updatevalue)
answer = 1
finally:
return answer
else:
return 0
def changeAttack(self,newAttack):
"""
it's change the attribute attack,calling the methodchangeAttackOrDefense with the appropriated
parameters
@param newattack:(int) a integer between 0..100, that will replace the attribute
@return oldavalue :(int or tuple) integer that represent the old capacity of attack,
or None plus a message of error
"""
return self.__changeAttackOrDefense(newAttack,1)
def changeDefense(self,newDefense):
"""
it's change the attribute defense,calling the methodchangeAttackOrDefense with the appropriated
parameters
@param newDefense:(int) a integer between 0..100, that will replace the attribute
@return oldavalue :(int or tuple) integer that represent the old capacity of defense,
or None plus a message of error
"""
return self.__changeAttackOrDefense(newDefense,2)
def getDamage(self, valuehit):
"""
it's repass the hit's from enemy, that means check values of health and defense,
updating the values of this two attributes
@param valuehit:(int) a integer between 0..100, that represent the value of an attack that need to be passed to defense and health
@return int: 1 is value hit was correcty repass , 0 if is not.
"""
if(type(valuehit) is str or type(valuehit) is int):
newnumb = valuehit
if(type(valuehit) is str):
try:
newnumb = int(valuehit)
except ValueError:
answer = 0
return answer
if(newnumb < 0): # no hit
newnumb = 0
return 1
defenseBackup = self.getValueDefense()
healthbackup = self.getHealth()
if(defenseBackup == healthbackup == None): #death
self.__del__()
return 1
if(defenseBackup == None):
defensevalue = 0
if(defenseBackup != None):
defensevalue = newnumb - defenseBackup
if(healthbackup == None):
healthbackup = 0
totaldefenseandhealth = defensevalue + healthbackup
if((self.getHealth() + self.getValueDefense()) <= newnumb): #death
self.__del__()
return 1
if(self.getValueDefense() > newnumb):
self.__setDefense(defenseBackup - newnumb)
return 1
elif(self.getValueDefense() <= newnumb):
self.__setDefense(0)
if(newnumb >= (defenseBackup + self.getHealth())):
print("Here")
self.__del__()
return 1
else: # keep live without defense
#newdefinitionattributehealth = healthbackup - defensevalue
self.__setHealth(healthbackup+defenseBackup- newnumb)
return 1
else:
return 0
def getDetail(self):
"""
it's getting the attributes of the class, providing a report of the object
@param None:
@return (string) : getting an report of the attributes of the object
"""
resposta = "\n#########################################################\n"+"Name of individual :" + self.getName() + "\n Health of individual:" + str(self.getHealth())+"\nAttack of individual:"+str(self.getValueAttack())+"\nDefense of individual:"+str(self.getValueDefense())+"\n#########################################################\n"
return resposta | 25.489247 | 341 | 0.665999 | 9,351 | 0.986184 | 0 | 0 | 0 | 0 | 0 | 0 | 4,720 | 0.497785 |
fdedc1899cf1d0a458c3cd2aa54431d61028feb7 | 1,544 | py | Python | 08_apples_and_bananas/apples.py | FabrizioPe/tiny_python_projects | e130d55d36cac43496a8ad482b6159234b5122f3 | [
"MIT"
]
| null | null | null | 08_apples_and_bananas/apples.py | FabrizioPe/tiny_python_projects | e130d55d36cac43496a8ad482b6159234b5122f3 | [
"MIT"
]
| null | null | null | 08_apples_and_bananas/apples.py | FabrizioPe/tiny_python_projects | e130d55d36cac43496a8ad482b6159234b5122f3 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
"""
Author : FabrizioPe
Date : 2021-02-10
Purpose: Find and replace vowels in a given text
"""
import argparse
import os
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Apples and bananas',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('str',
metavar='str',
help='Input text or file')
parser.add_argument('-v',
'--vowel',
help='The vowel to substitute',
metavar='str',
choices='aeiou',
type=str,
default='a')
args = parser.parse_args()
# but will this file remain open?
if os.path.isfile(args.str):
args.str = open(args.str).read().rstrip()
return args
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
text = args.str
vowel = args.vowel
table = {'a': vowel, 'e': vowel, 'i': vowel, 'o': vowel, 'u': vowel,
'A': vowel.upper(), 'E': vowel.upper(), 'I': vowel.upper(),
'O': vowel.upper(), 'U': vowel.upper()}
# apply the transformation defined in the table, to the input text
print(text.translate(str.maketrans(table)))
# --------------------------------------------------
if __name__ == '__main__':
main()
| 26.169492 | 72 | 0.483808 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 576 | 0.373057 |
fdedd48ecc2cd5713a5620f6663699573feeb1b9 | 1,434 | py | Python | utils.py | gabrs-sousa/brasil-rugby-ranking | 78b8f6b466e688f507cb9d97dbbb80442f3c67de | [
"MIT"
]
| 1 | 2020-05-30T03:34:31.000Z | 2020-05-30T03:34:31.000Z | utils.py | gabrs-sousa/brasil-rugby-ranking | 78b8f6b466e688f507cb9d97dbbb80442f3c67de | [
"MIT"
]
| null | null | null | utils.py | gabrs-sousa/brasil-rugby-ranking | 78b8f6b466e688f507cb9d97dbbb80442f3c67de | [
"MIT"
]
| null | null | null | import pandas as pd
from openpyxl import worksheet
def map_team_names(names_sheet: worksheet, games_sheet: worksheet):
mapped_names = []
missing_names = set()
names_last_row = names_sheet.max_row
for row in range(1, names_last_row):
team_name = names_sheet.cell(row, 1).value
if team_name:
mapped_names.append(team_name.upper())
games_last_row = games_sheet.max_row
for row in range(2, games_last_row):
visitor = games_sheet.cell(row, 7).value
home = games_sheet.cell(row, 12).value
if home and home.upper() not in mapped_names:
missing_names.add(home)
if visitor and visitor.upper() not in mapped_names:
missing_names.add(visitor)
if missing_names:
return missing_names
else:
return False
def format_name(name: str) -> str:
"""
Limpa espaços antes e depois da palavra
Nome em caps lock para evitar case sensitive
"""
name = name.strip()
name = name.upper()
return name
def export_output_file(teams: dict, output_file_name: str):
ranking_df = pd.DataFrame(teams)
ranking_df = ranking_df.transpose()
ranking_df = ranking_df.sort_values('points', ascending=False)
ranking_df = ranking_df[ranking_df['total_games'] > 0].dropna()
ranking_df.to_excel(output_file_name)
print(f'Workbook "{output_file_name}" has been created successfully!')
| 28.117647 | 74 | 0.679916 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 189 | 0.131707 |
fdee1b940008dee7fb0abcb8d4fb0eaf97c8d578 | 8,889 | py | Python | mainapp/views.py | AHTOH2001/OOP_4_term | c9b0f64f3507486e0670cc95d7252862b673d845 | [
"MIT"
]
| null | null | null | mainapp/views.py | AHTOH2001/OOP_4_term | c9b0f64f3507486e0670cc95d7252862b673d845 | [
"MIT"
]
| null | null | null | mainapp/views.py | AHTOH2001/OOP_4_term | c9b0f64f3507486e0670cc95d7252862b673d845 | [
"MIT"
]
| null | null | null | from django.core.mail import send_mail
from django.http import Http404
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User
from django.utils.datastructures import MultiValueDictKeyError
from django.utils import timezone
from django.contrib.auth import login, logout
from django import urls
import copy
# from django.contrib.auth.hashers import make_password, check_password, is_password_usable
# from datetime import datetime
from django.views.generic import DetailView
from CheekLit import settings
from .utils import get_code, is_administrator, should_show_price
from .models import Client, Book, Author, Genre, Basket, Status, SliderImages
from .forms import ClientRegisterForm, ClientAuthorizationForm
from .settings import time_for_registration
def home(request):
books = Book.objects.filter(status=True).order_by('-amount')
slider_images = SliderImages.objects.filter(status=True)
# return render(request, 'home.html', {'books': books, 'is_administrator': is_administrator(request.user)})
return render(request, 'home.html',
{'books': books, 'genres': Genre.objects.all(), 'authors': Author.objects.all(),
'slider_images': slider_images})
def book_detail(request, slug):
current_book = Book.objects.get(slug=slug)
if request.method == 'POST':
if 'add_to_basket' in request.GET:
if is_administrator(request.user):
raise Http404('Administration does not have a basket')
client = request.user.client_set.get()
current_basket, is_created = client.baskets.get_or_create(status=Status.IN_PROCESS)
if should_show_price(request.user):
current_basket.books.add(current_book)
messages.success(request, 'Книга успешно добавлена в корзину')
return render(request, 'book_detail.html', {'book': current_book})
# return super(BookDetailView, self).get(request, *args, **kwargs)
# class BookDetailView(DetailView):
# queryset = Book.objects.all()
# model = Book
# context_object_name = 'book'
# template_name = 'book_detail.html'
# slug_url_kwarg = 'slug'
#
# def post(self, request, *args, **kwargs):
# pass
# # context = super().get_context_data(object=self.object)
# # return super().render_to_response(context)
class AuthorDetailView(DetailView):
queryset = Author.objects.all()
model = Author
context_object_name = 'author'
template_name = 'author_detail.html'
slug_url_kwarg = 'slug'
class GenreDetailView(DetailView):
queryset = Genre.objects.all()
model = Genre
context_object_name = 'genre'
template_name = 'genre_detail.html'
slug_url_kwarg = 'slug'
def register(request):
if request.method == 'POST':
form = ClientRegisterForm(data=request.POST)
if form.is_valid():
client, raw_pass = form.save()
confirmation_url = request.META["HTTP_HOST"] + urls.reverse(
register_complete) + f'?login={client.user.email}&code={get_code(client.user.email, "abs", 20)}'
email_message = f'''Здравствуйте, уважаемый {client.user.last_name} {client.user.first_name}!
Вы в одном шаге от завершения регистрации в интернет библиотеке CheekLit.
Ваши данные для авторизации в системе:
Логин: {client.user.email}
Пароль: {raw_pass}
Внимание! Вы должны подтвердить регистрационные данные!
Для подтверждения достаточно перейти по следующей ссылке:
{confirmation_url}
Если Вы действительно желаете подтвердить регистрацию, пожалуйста, сделайте это до {(timezone.localtime() + time_for_registration).strftime('%H:%M %d.%m.%Y')}. В противном случае Ваши регистрационные данные будут удалены из системы.
С уважением, администрация интернет библиотеки CheekLit'''
send_mail(
f'Подтверждение регистрации на сайте {request.META["HTTP_HOST"]}',
email_message,
'[email protected]',
[client.user.email],
fail_silently=False,
)
messages.success(request, 'Пользователь успешно создан, проверьте почту и подтвердите регистрацию')
return redirect('home')
else:
messages.error(request, 'Некоторые данные введены неверно')
else:
form = ClientRegisterForm()
return render(request, 'register.html',
{'form': form, 'genres': Genre.objects.all(), 'authors': Author.objects.all()})
def register_complete(request):
try:
email = request.GET['login']
code = request.GET['code'].replace(' ', '+')
if get_code(email, 'abs', 20) == code:
# Delete outdated clients
User.objects.filter(date_joined__lt=timezone.localtime() - time_for_registration,
is_active=False, is_staff=False, is_superuser=False).delete()
try:
if User.objects.get(email=email).is_active is True:
messages.warning(request, 'Пользователь уже подтверждён')
else:
messages.success(request, 'Пользователь успешно подтверждён, осталось только авторизоваться')
User.objects.filter(email=email).update(is_active=True)
return redirect('authorize')
except User.DoesNotExist:
messages.error(request, 'По всей видимости ссылка регистрации просрочена')
else:
messages.error(request, f'Параметр code неверный')
except MultiValueDictKeyError as e:
messages.error(request, f'Пропущен параметр {e.args}')
return redirect('home')
def authorize(request):
if request.method == 'POST':
form = ClientAuthorizationForm(data=request.POST)
if form.is_valid():
client = form.get_user()
login(request, client)
messages.success(request, f'Добро пожаловать, {client.last_name} {client.first_name}')
return redirect('home')
else:
messages.error(request, 'Некоторые данные введены неверно')
else:
form = ClientAuthorizationForm()
return render(request, 'authorize.html',
{'form': form, 'genres': Genre.objects.all(), 'authors': Author.objects.all()})
def client_logout(request):
logout(request)
return redirect('home')
def useful_information(request):
return render(request, 'useful_information.html')
def about_us(request):
return render(request, 'about_us.html')
def contact(request):
return render(request, 'contact.html')
def basket(request):
if request.user.is_authenticated:
if is_administrator(request.user):
raise Http404('Administration does not have a basket')
client = request.user.client_set.get()
current_basket, is_created = client.baskets.get_or_create(status=Status.IN_PROCESS)
if not should_show_price(request.user):
current_basket.books.clear()
if request.method == 'POST':
if 'delete_book' in request.GET:
current_basket.books.remove(request.GET['delete_book'])
if 'clear' in request.GET:
saved_basket = copy.copy(current_basket)
saved_basket.status = Status.ABANDONED
Basket.objects.filter(client=client, status=Status.ABANDONED).delete()
saved_basket.save()
client.baskets.add(saved_basket)
current_basket.books.clear()
# client.baskets.create(status=Status.ABANDONED, )
if 'restore' in request.GET:
try:
client.baskets.get(status=Status.ABANDONED)
except Basket.DoesNotExist:
raise Http404('Not found abandoned basket')
client.baskets.filter(status=Status.IN_PROCESS).delete()
client.baskets.filter(status=Status.ABANDONED).update(status=Status.IN_PROCESS)
current_basket = client.baskets.get(status=Status.IN_PROCESS)
return render(request, 'basket.html', {'BookModel': Book, 'books_in_basket': current_basket.books.all()})
else:
raise Http404('User is not authenticated')
def order(request):
if request.user.is_authenticated and should_show_price(request.user):
if is_administrator(request.user):
raise Http404('Administration does not have a basket')
client = request.user.client_set.get()
current_basket, is_created = client.baskets.get_or_create(status=Status.IN_PROCESS)
current_basket.status = Status.ON_HANDS
current_basket.date_of_taking = timezone.now()
current_basket.save()
return render(request, 'order.html')
else:
raise Http404('User is not authenticated')
| 39.15859 | 232 | 0.664867 | 383 | 0.039763 | 0 | 0 | 0 | 0 | 0 | 0 | 3,433 | 0.356416 |
fdef583937c7416dc3c1150c9fa7843d7266de92 | 1,941 | py | Python | extra/old-fix-midroll.py | FrederikBanke/critrolesync.github.io | ca09fff7541014d81472d687e48ecd5587cc15ff | [
"MIT"
]
| 5 | 2020-06-29T13:39:07.000Z | 2022-02-07T00:43:55.000Z | extra/old-fix-midroll.py | FrederikBanke/critrolesync.github.io | ca09fff7541014d81472d687e48ecd5587cc15ff | [
"MIT"
]
| 11 | 2020-06-28T09:45:38.000Z | 2022-03-30T17:56:35.000Z | extra/old-fix-midroll.py | FrederikBanke/critrolesync.github.io | ca09fff7541014d81472d687e48ecd5587cc15ff | [
"MIT"
]
| 5 | 2020-06-29T21:17:13.000Z | 2021-09-08T06:34:32.000Z | def str2sec(string):
if len(string.split(':')) == 3:
hours, mins, secs = map(int, string.split(':'))
elif len(string.split(':')) == 2:
mins, secs = map(int, string.split(':'))
hours = 0
else:
raise ValueError('string must have the form [hh:]mm:ss : ' + str(string))
seconds = 3600*hours + 60*mins + secs
return seconds
def sec2str(seconds, format=None):
if seconds < 0:
raise ValueError('seconds must be nonnegative: ' + str(seconds))
mins, secs = divmod(seconds, 60)
hours, mins = divmod(mins, 60)
if format == 'youtube':
string = '%dh%02dm%02ds' % (hours, mins, secs)
else:
string = '%d:%02d:%02d' % (hours, mins, secs)
return string
def fixAnchorMidroll(newAdDuration=61, oldAdDuration=0):
'''For fixing issue #8: https://github.com/critrolesync/critrolesync.github.io/issues/8'''
anchor_podcast_episodes = data[1]['episodes'][19:]
for ep in anchor_podcast_episodes:
if 'timestampsBitrate' in ep:
# need to adjust for new bitrate
bitrateRatio = 128/127.7
else:
# do need to adjust for bitrate
bitrateRatio = 1
print(ep['id'])
print()
print(' "timestamps": [')
for i, (youtube, podcast, comment) in enumerate(ep['timestamps']):
if i<2: # before break
podcast_new = sec2str(str2sec(podcast)*bitrateRatio)
else: # after break
podcast_new = sec2str((str2sec(podcast)-oldAdDuration+newAdDuration)*bitrateRatio)
if i<len(ep['timestamps'])-1: # include final comma
print(f' ["{youtube}", "{podcast_new}", "{comment}"],')
else: # no final comma
print(f' ["{youtube}", "{podcast_new}", "{comment}"]')
print(' ]')
print()
print()
| 37.326923 | 98 | 0.548171 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 581 | 0.29933 |
fdf00539d71fcfd43067729f990a71a6b54c1f86 | 415 | py | Python | 102-neopixel.d/main.py | wa1tnr/cpx-basic-studies | 772d38803bc2394980d81cea7873a4bc027dfb9f | [
"MIT"
]
| null | null | null | 102-neopixel.d/main.py | wa1tnr/cpx-basic-studies | 772d38803bc2394980d81cea7873a4bc027dfb9f | [
"MIT"
]
| null | null | null | 102-neopixel.d/main.py | wa1tnr/cpx-basic-studies | 772d38803bc2394980d81cea7873a4bc027dfb9f | [
"MIT"
]
| null | null | null | # Adafruit CircuitPython 2.2.0
# Adafruit CircuitPlayground Express
import board ; import neopixel; import time
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.2)
pixels.fill((0,0,0))
pixels.show()
def blue():
pixels.fill((0,0,22))
def magenta():
pixels.fill((22,0,22))
blue(); pixels.show(); time.sleep(0.7);
magenta(); pixels.show(); time.sleep(1.4);
pixels.fill((0,0,0)); pixels.show()
| 23.055556 | 61 | 0.684337 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 66 | 0.159036 |
fdf08b92d38f1c12ce10c7842c25d8f96a214534 | 385 | py | Python | indent/migrations/0003_indentmaster_note.py | yvsreenivas/inventory2 | b92c03a398cb9831fa7a727a9a3287bdd9b17cd4 | [
"MIT"
]
| null | null | null | indent/migrations/0003_indentmaster_note.py | yvsreenivas/inventory2 | b92c03a398cb9831fa7a727a9a3287bdd9b17cd4 | [
"MIT"
]
| null | null | null | indent/migrations/0003_indentmaster_note.py | yvsreenivas/inventory2 | b92c03a398cb9831fa7a727a9a3287bdd9b17cd4 | [
"MIT"
]
| null | null | null | # Generated by Django 2.1.15 on 2021-03-15 15:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('indent', '0002_auto_20210314_2324'),
]
operations = [
migrations.AddField(
model_name='indentmaster',
name='note',
field=models.TextField(blank=True),
),
]
| 20.263158 | 48 | 0.597403 | 291 | 0.755844 | 0 | 0 | 0 | 0 | 0 | 0 | 101 | 0.262338 |
fdf18580611d8972ffb45869d74bebdda505d879 | 2,310 | py | Python | Ass2/lotka-volterra.py | Scoudem/modsim | a65da4a29a82ac495367278ec694a28432b30c0d | [
"Apache-2.0"
]
| null | null | null | Ass2/lotka-volterra.py | Scoudem/modsim | a65da4a29a82ac495367278ec694a28432b30c0d | [
"Apache-2.0"
]
| null | null | null | Ass2/lotka-volterra.py | Scoudem/modsim | a65da4a29a82ac495367278ec694a28432b30c0d | [
"Apache-2.0"
]
| null | null | null | '''
File: lotka-volterra.py
Authors:
- Sjoerd Wenker, 10617558
- Tristan van Vaalen, 10551832
Contains a Lotka-Volterra Model which is simulated using the RK4 method.
'''
from integration import RungeKutta4
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
'''
Method that simulates a Lotka-Volterra Model using RK4 for the given
functions with a list containing sets of startvalues and a list of timesteps
This will show a window for each of the timesteps
'''
def lotke_volterra(functions, startvalues, dts, generations):
for dt in dts:
objects = []
for startvalue in startvalues:
objects.append(RungeKutta4(functions, 0, startvalue, stepsize=dt))
for m in objects:
m.generate_n(generations)
fig = plt.gcf()
title = 'Lotka-Volterra with dt:{} ({} timesteps)'.format(dt, generations)
fig.suptitle(title, fontsize="x-large")
olen = len(objects)
''' Make plots for each set of startvalues '''
for i, m in enumerate(objects):
ax = plt.subplot(2, olen, i + 1)
x = startvalues[i][0]
y = startvalues[i][1]
ax.set_title("Startvalues: x:{} y:{}".format(x, y))
''' Plot values '''
values = m.get_y_values()
ax.plot(m.get_t_values(), values[0, :], label="x")
ax.plot(m.get_t_values(), values[1, :], label="y")
ax.legend(loc='best')
''' Make scatter plot '''
ax = plt.subplot(2, olen, olen + i + 1)
ax.scatter(values[0, :], values[1, :])
plt.show()
plt.close()
''' Main execution '''
if __name__ == '__main__':
startvalues = [[11, 49], [1, 10], [15, 26]]
dt = [1, 0.1, 0.05, 0.01, 0.005, 0.001]
generations = 10000
functions = [
lambda (t, x, y): -0.5 * x + 0.01 * x * y,
lambda (t, x, y): y - 0.1 * x * y
]
lotke_volterra(functions, startvalues, dt, generations)
'''
Calculations for stable point:
x' = -a * x + c * d * x * y
y' = b * y - d * x * y
a = 0.5, b = 1,c = 0.1 and d = 0.1.
x' = -0.5 * x + 0.01 * x * y
y' = y - 0.1 * x * y
Stable:
x'=0 y'=0 x!=0 y!=0
-0.5 * x + 0.01 * x * y = 0
-0.5 + 0.01 * y = 0
0.01y = 0.5
y = 50
y - 0.1 * x * y = 0
1 - 0.1x = 0
0.1x = 1
x = 10
''' | 26.860465 | 82 | 0.558009 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 909 | 0.393506 |
fdf306a6233eb15d853aa05d6d7553accacc2060 | 3,717 | py | Python | harmoni_detectors/harmoni_stt/test/test_deepspeech.py | interaction-lab/HARMONI | 9c88019601a983a1739744919a95247a997d3bb1 | [
"MIT"
]
| 7 | 2020-09-02T06:31:21.000Z | 2022-02-18T21:16:44.000Z | harmoni_detectors/harmoni_stt/test/test_deepspeech.py | micolspitale93/HARMONI | cf6a13fb85e3efb4e421dbfd4555359c0a04acaa | [
"MIT"
]
| 61 | 2020-05-15T16:46:32.000Z | 2021-07-28T17:44:49.000Z | harmoni_detectors/harmoni_stt/test/test_deepspeech.py | micolspitale93/HARMONI | cf6a13fb85e3efb4e421dbfd4555359c0a04acaa | [
"MIT"
]
| 3 | 2020-10-05T23:01:29.000Z | 2022-03-02T11:53:34.000Z | #!/usr/bin/env python3
# Common Imports
import io
import rospy
import sys
import unittest
# Specific Imports
import time
import wave
from harmoni_common_lib.action_client import HarmoniActionClient
from harmoni_common_lib.constants import ActionType, DetectorNameSpace, SensorNameSpace, State
from audio_common_msgs.msg import AudioData
from std_msgs.msg import String
PKG = "test_harmoni_stt"
class TestDeepSpeech_Common(unittest.TestCase):
def setUp(self):
self.feedback = State.INIT
self.result = False
self.test_file = rospy.get_param("test_deepspeech_input")
rospy.init_node("test_deepspeech", log_level=rospy.INFO)
self.rate = rospy.Rate(20)
self.output_sub = rospy.Subscriber(
"/harmoni/detecting/stt/default", String, self._detecting_callback
)
# provide mock microphone
self.audio_pub = rospy.Publisher(
SensorNameSpace.microphone.value
+ rospy.get_param("stt/default_param/subscriber_id"),
AudioData,
queue_size=10,
)
rospy.Subscriber(
DetectorNameSpace.stt.value + "stt_default",
String,
self.text_received_callback,
)
# startup stt node
self.server = "stt_default"
self.client = HarmoniActionClient(self.server)
self.client.setup_client(
self.server, self._result_callback, self._feedback_callback, wait=True
)
rospy.loginfo("TestDeepSpeech: Turning ON stt server")
self.client.send_goal(
action_goal=ActionType.ON, optional_data="Setup", wait=False
)
rospy.loginfo("TestDeepSpeech: Started up. waiting for DeepSpeech startup")
time.sleep(5)
rospy.loginfo("TestDeepSpeech: publishing audio")
chunk_size = 1024
wf = wave.open(self.test_file)
# read data (based on the chunk size)
index = 0
audio_length = wf.getnframes()
while index+chunk_size < audio_length:
data = wf.readframes(chunk_size)
self.audio_pub.publish(data)
index = index+chunk_size
time.sleep(0.2)
rospy.loginfo(
f"TestDeepSpeech: audio subscribed to by #{self.output_sub.get_num_connections()} connections."
)
def _feedback_callback(self, data):
rospy.loginfo(f"TestDeepSpeech: Feedback: {data}")
self.feedback = data["state"]
def _status_callback(self, data):
rospy.loginfo(f"TestDeepSpeech: Status: {data}")
self.result = True
def _result_callback(self, data):
rospy.loginfo(f"TestDeepSpeech: Result: {data}")
self.result = True
def text_received_callback(self, data):
rospy.loginfo(f"TestDeepSpeech: Text back: {data}")
self.result = True
def _detecting_callback(self, data):
rospy.loginfo(f"TestDeepSpeech: Detecting: {data}")
self.result = True
class TestDeepSpeech_Valid(TestDeepSpeech_Common):
def test_IO(self):
rospy.loginfo(
"TestDeepSpeech[TEST]: basic IO test to ensure data "
+ "('hello' audio) is received and responded to. Waiting for transcription..."
)
while not rospy.is_shutdown() and not self.result:
self.rate.sleep()
assert self.result
def main():
# TODO combine validity tests into test suite so that setup doesn't have to run over and over.
import rostest
rospy.loginfo("test_deepspeech started")
rospy.loginfo("TestDeepSpeech: sys.argv: %s" % str(sys.argv))
rostest.rosrun(PKG, "test_deepspeech", TestDeepSpeech_Valid, sys.argv)
if __name__ == "__main__":
main()
| 31.235294 | 107 | 0.65456 | 2,954 | 0.794727 | 0 | 0 | 0 | 0 | 0 | 0 | 1,005 | 0.270379 |
fdf47c8f7eacc32cfd98b13ee0730f15d82165c5 | 2,196 | py | Python | smoked/management/commands/smoked.py | martinsvoboda/django-smoked | 42b64fff23a37e3df42f8fc54535ea496dd27d84 | [
"MIT"
]
| 6 | 2015-01-14T12:02:58.000Z | 2021-08-17T23:18:56.000Z | smoked/management/commands/smoked.py | martinsvoboda/django-smoked | 42b64fff23a37e3df42f8fc54535ea496dd27d84 | [
"MIT"
]
| 7 | 2015-01-24T11:36:07.000Z | 2015-01-26T04:55:31.000Z | smoked/management/commands/smoked.py | martinsvoboda/django-smoked | 42b64fff23a37e3df42f8fc54535ea496dd27d84 | [
"MIT"
]
| 1 | 2015-01-25T20:48:06.000Z | 2015-01-25T20:48:06.000Z | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from optparse import make_option
import time
from django import VERSION
from django.core.management.base import NoArgsCommand
from smoked import default_registry
from smoked.runner import run_tests
stats_msg = """
Results
=======
Total: {total}
Success: {success}
Failure: {failure}
--------
Time: {time:.1f}s
"""
class Command(NoArgsCommand):
help = 'Run all registered smoke tests'
option_list = NoArgsCommand.option_list + (
make_option(
'-n', '--dry-run', dest='dry_run',
action='store_true', default=False,
help="Only collect test, don't execute them."),
)
def handle_noargs(self, **options):
verbosity = int(options.get('verbosity', 1))
start_time = time.time()
if options.get('dry_run'):
count = len(default_registry.tests)
if verbosity:
self.log('{0} smoke test(s) could be run'.format(count))
else:
self.log(str(count))
return
success = failure = 0
for result in run_tests():
positive = 'error' not in result
if positive:
success += 1
else:
failure += 1
if verbosity > 1:
output = 'Success' if positive else 'Fail!'
self.log('{0}... {1}'.format(result['name'], output))
if not positive:
self.log(str(result['error']))
else:
output = '.' if positive else 'F'
self.log(output, ending='')
stats = {
'total': success + failure,
'success': success,
'failure': failure,
'time': time.time() - start_time
}
if verbosity:
self.log(stats_msg.format(**stats))
else:
self.log('') # print out new line after dots
def log(self, msg='', ending='\n'):
# Backward compatability with Dj1.4
if VERSION[1] == 4:
self.stdout.write(msg + ending)
else:
self.stdout.write(msg, ending=ending)
| 27.45 | 72 | 0.539617 | 1,803 | 0.821038 | 0 | 0 | 0 | 0 | 0 | 0 | 439 | 0.199909 |
fdf91475384cb8118e074e63142b83edc4f4d2bd | 1,735 | py | Python | Data Science With Python/07-cleaning-data-in-python/4-cleaning-data-for-analysis/10-testing-your-data-with-asserts.py | aimanahmedmoin1997/DataCamp | c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d | [
"MIT"
]
| 5 | 2021-02-03T14:36:58.000Z | 2022-01-01T10:29:26.000Z | Data Science With Python/07-cleaning-data-in-python/4-cleaning-data-for-analysis/10-testing-your-data-with-asserts.py | aimanahmedmoin1997/DataCamp | c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d | [
"MIT"
]
| null | null | null | Data Science With Python/07-cleaning-data-in-python/4-cleaning-data-for-analysis/10-testing-your-data-with-asserts.py | aimanahmedmoin1997/DataCamp | c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d | [
"MIT"
]
| 7 | 2018-11-06T17:43:31.000Z | 2020-11-07T21:08:16.000Z | '''
Testing your data with asserts
Here, you'll practice writing assert statements using the Ebola dataset from previous chapters to programmatically check for missing values and to confirm that all values are positive. The dataset has been pre-loaded into a DataFrame called ebola.
In the video, you saw Dan use the .all() method together with the .notnull() DataFrame method to check for missing values in a column. The .all() method returns True if all values are True. When used on a DataFrame, it returns a Series of Booleans - one for each column in the DataFrame. So if you are using it on a DataFrame, like in this exercise, you need to chain another .all() method so that you return only one True or False value. When using these within an assert statement, nothing will be returned if the assert statement is true: This is how you can confirm that the data you are checking are valid.
Note: You can use pd.notnull(df) as an alternative to df.notnull().
INSTRUCTIONS
100XP
INSTRUCTIONS
100XP
-Write an assert statement to confirm that there are no missing values in ebola.
-Use the pd.notnull() function on ebola (or the .notnull() method of ebola) and chain two .all() methods (that is, .all().all()). The first .all() method will return a True or False for each column, while the second .all() method will return a single True or False.
-Write an assert statement to confirm that all values in ebola are greater than or equal to 0.
-Chain two all() methods to the Boolean condition (ebola >= 0).
'''
import pandas as pd
ebola = pd.read_csv('../_datasets/ebola.csv')
# Assert that there are no missing values
assert ebola.notnull().all().all()
# Assert that all values are >= 0
assert (ebola >= 0).all().all()
| 61.964286 | 611 | 0.756196 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,620 | 0.933718 |
fdfa15c5c9e42a9b497c846a1dd12bc7ab7f4c76 | 623 | py | Python | code/waldo/conf/guisettings.py | amarallab/waldo | e38d23d9474a0bcb7a94e685545edb0115b12af4 | [
"MIT"
]
| null | null | null | code/waldo/conf/guisettings.py | amarallab/waldo | e38d23d9474a0bcb7a94e685545edb0115b12af4 | [
"MIT"
]
| null | null | null | code/waldo/conf/guisettings.py | amarallab/waldo | e38d23d9474a0bcb7a94e685545edb0115b12af4 | [
"MIT"
]
| null | null | null | COLLIDER_SUITE_OFFSHOOT_RANGE = (0, 100)
COLLIDER_SUITE_SPLIT_ABS_RANGE = (0, 10)
COLLIDER_SUITE_SPLIT_REL_RANGE = (-1, 1, 2)
COLLIDER_SUITE_ASSIMILATE_SIZE_RANGE = (0, 10)
TAPE_FRAME_SEARCH_LIMIT_RANGE = (1, 100000)
TAPE_PIXEL_SEARCH_LIMIT_RANGE = (1, 1000000)
DEFAULT_CALIBRATION_ENCLOSURE_SIZE_RANGE = (0, 1000)
COLLISION_PIXEL_OVERLAP_MARGIN_RANGE = (1, 2000)
SCORE_CONTRAST_RADIO_RANGE = (1.0, 5.0)
SCORE_CONTRAST_DIFF_RANGE = (-0.2, 0.2)
SCORE_GOOD_FRACTION_RANGE = (0.0, 1.1)
SCORE_ACCURACY_RANGE = (0.0, 1.1)
SCORE_COVERAGE_RANGE = (0.0, 1.1)
ROI_BORDER_OFFSET_RANGE = (0, 200)
ROI_CORNER_OFFSET_RANGE = (0, 200) | 34.611111 | 52 | 0.781701 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
fdfb52a6d5dc1287a0b5c4d900e03718e519b19a | 6,084 | py | Python | aiospotipy/me.py | sizumita/aiospotipy | 3c542ca90559abde2e35268b4eedfdbbef1dab34 | [
"MIT"
]
| 3 | 2019-03-09T14:53:46.000Z | 2020-06-03T12:50:33.000Z | aiospotipy/me.py | sizumita/aiospotipy | 3c542ca90559abde2e35268b4eedfdbbef1dab34 | [
"MIT"
]
| null | null | null | aiospotipy/me.py | sizumita/aiospotipy | 3c542ca90559abde2e35268b4eedfdbbef1dab34 | [
"MIT"
]
| 1 | 2019-03-09T08:26:46.000Z | 2019-03-09T08:26:46.000Z | from ._http import (HTTPClient,
get_id,
Route,
GET,
PUT,
DELETE,
)
import asyncio
class Me:
def __init__(self, _http: HTTPClient):
self.http = _http
self.request = _http.request
self.timeout = _http.timeout
self.loop = _http.loop
async def user(self):
"""|coro|
Get detailed profile information about the current user.
An alias for the 'current_user' method.
"""
r = Route(GET, '/me/')
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def playlists(self, limit=50, offset=0):
"""|coro|
Get current user playlists without required getting his profile
Parameters:
- limit - the number of items to return
- offset - the index of the first item to return
"""
r = Route(GET, "/me/playlists", limit=limit, offset=offset)
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def albums(self, limit=20, offset=0):
"""|coro|
Gets a list of the albums saved in the current authorized user's
"Your Music" library
Parameters:
- limit - the number of albums to returnx
- offset - the index of the first album to return
"""
r = Route(GET,
'/me/albums',
limit=limit, offset=offset)
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def tracks(self, limit=20, offset=0):
"""|coro|
Gets a list of the tracks saved in the current authorized user's
"Your Music" library
Parameters:
- limit - the number of tracks to return
- offset - the index of the first track to return
"""
r = Route(GET,
'/me/tracks',
limit=limit, offset=offset)
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def followed_artists(self, limit=20, after=None):
"""|coro|
Gets a list of the artists followed by the current authorized user
Parameters:
- limit - the number of tracks to return
- after - ghe last artist ID retrieved from the previous request
"""
r = Route(GET,
'/me/following',
type='artist', limit=limit, after=after)
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def delete_tracks(self, tracks=None):
"""|coro|
Remove one or more tracks from the current user's
"Your Music" library.
Parameters:
- tracks - a list of track URIs, URLs or IDs
"""
track_list = []
if tracks:
track_list = [get_id('track', t) for t in tracks]
r = Route(DELETE,
'/me/tracks/?ids=' + ','.join(track_list))
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def contains_tracks(self, tracks=None):
"""|coro|
Check if one or more tracks is already saved in
the current Spotify user’s “Your Music” library.
Parameters:
- tracks - a list of track URIs, URLs or IDs
"""
track_list = []
if tracks is not None:
track_list = [get_id('track', t) for t in tracks]
r = Route(GET,
'/me/tracks/contains?ids=' + ','.join(track_list))
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def add_tracks(self, tracks=None):
"""|coro|
Add one or more tracks to the current user's
"Your Music" library.
Parameters:
- tracks - a list of track URIs, URLs or IDs
"""
track_list = []
if tracks is not None:
track_list = [get_id('track', t) for t in tracks]
r = Route(PUT,
'/me/tracks/?ids=' + ','.join(track_list))
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def top_artists(self, limit=20, offset=0, time_range='medium_term'):
"""|coro|
Get the current user's top artists
Parameters:
- limit - the number of entities to return
- offset - the index of the first entity to return
- time_range - Over what time frame are the affinities computed
Valid-values: short_term, medium_term, long_term
"""
r = Route(GET,
'/me/top/artists',
time_range=time_range, limit=limit, offset=offset)
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def my_top_tracks(self, limit=20, offset=0, time_range='medium_term'):
"""|coro|
Get the current user's top tracks
Parameters:
- limit - the number of entities to return
- offset - the index of the first entity to return
- time_range - Over what time frame are the affinities computed
Valid-values: short_term, medium_term, long_term
"""
r = Route(GET,
'/me/top/tracks',
time_range=time_range, limit=limit, offset=offset)
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop)
async def add_albums(self, albums=None):
"""|coro|
Add one or more albums to the current user's
"Your Music" library.
Parameters:
- albums - a list of album URIs, URLs or IDs
"""
if albums is None:
albums = []
alist = [get_id('album', a) for a in albums]
r = Route(PUT,
'/me/albums?ids=' + ','.join(alist))
return await asyncio.wait_for(self.request(r), self.timeout, loop=self.loop) | 34.568182 | 84 | 0.561473 | 5,886 | 0.966502 | 0 | 0 | 0 | 0 | 5,637 | 0.925616 | 2,856 | 0.468966 |
fdfb78f1a782871b71fcd4058e86788874102e55 | 582 | py | Python | iiif_prezi3/loader.py | rbturnbull/iiif-prezi3 | 0e66bc41438772c75e064c20964ed01aff1f3709 | [
"Apache-2.0"
]
| null | null | null | iiif_prezi3/loader.py | rbturnbull/iiif-prezi3 | 0e66bc41438772c75e064c20964ed01aff1f3709 | [
"Apache-2.0"
]
| null | null | null | iiif_prezi3/loader.py | rbturnbull/iiif-prezi3 | 0e66bc41438772c75e064c20964ed01aff1f3709 | [
"Apache-2.0"
]
| null | null | null | import json
def load_extensions_from_json():
try:
extensions = json.load(open("extensions.json"))
except FileNotFoundError:
return
for ext in extensions:
__import__(f"iiif_prezi3.extensions.{ext}")
def load_extension(path):
pass
def monkeypatch_schema(schema_class, patch_classes):
schema_bases = list(schema_class.__bases__)
if type(patch_classes) == list:
for c in patch_classes:
schema_bases.append(c)
else:
schema_bases.append(patch_classes)
schema_class.__bases__ = tuple(schema_bases)
| 22.384615 | 55 | 0.689003 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 48 | 0.082474 |
fdfc80e749f6ee439afc826e7feee5425163a88f | 1,237 | py | Python | android_store_service/utils/config_utils.py | gpiress/android-store-service | da81c7e79a345d790f5e744fc8fdfae0e6941765 | [
"Apache-2.0"
]
| 5 | 2020-12-10T14:05:04.000Z | 2020-12-18T09:04:35.000Z | android_store_service/utils/config_utils.py | gpiress/android-store-service | da81c7e79a345d790f5e744fc8fdfae0e6941765 | [
"Apache-2.0"
]
| 4 | 2020-12-15T12:34:51.000Z | 2021-06-28T14:04:34.000Z | android_store_service/utils/config_utils.py | gpiress/android-store-service | da81c7e79a345d790f5e744fc8fdfae0e6941765 | [
"Apache-2.0"
]
| 5 | 2020-12-15T12:10:22.000Z | 2022-03-18T20:06:38.000Z | # Copyright 2019 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from flask import current_app
def read_file(conf_path):
with open(str(conf_path), "r") as _file:
return _file.read()
def get_secret(secret, path=None):
if not path:
path = current_app.config.get("SECRETS_PATH")
file_path = f"{path}/{secret}"
if not secret_exists(secret, path=path):
raise FileNotFoundError(f"Secret {secret} does not exist at {file_path}")
return read_file(file_path)
def secret_exists(secret, path=None):
if not path:
path = current_app.config.get("SECRETS_PATH")
file_path = f"{path}/{secret}"
if os.path.exists(file_path):
return True
return False
| 29.452381 | 81 | 0.712207 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 676 | 0.546483 |
fdfd3606a932554deb9481786f567a3095afa229 | 395 | py | Python | blog/migrations/0015_auto_20190810_1404.py | vishnu-chalil/sharecontent | bda2cb6db0ffc38f582829abfced163e8a6eafdb | [
"Apache-2.0"
]
| null | null | null | blog/migrations/0015_auto_20190810_1404.py | vishnu-chalil/sharecontent | bda2cb6db0ffc38f582829abfced163e8a6eafdb | [
"Apache-2.0"
]
| 7 | 2020-02-12T01:20:22.000Z | 2021-06-10T18:39:59.000Z | blog/migrations/0015_auto_20190810_1404.py | vishnu-chalil/sharecontent | bda2cb6db0ffc38f582829abfced163e8a6eafdb | [
"Apache-2.0"
]
| null | null | null | # Generated by Django 2.2.4 on 2019-08-10 14:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_post_imgdata'),
]
operations = [
migrations.AlterField(
model_name='post',
name='imgdata',
field=models.ImageField(blank=True, upload_to='content'),
),
]
| 20.789474 | 69 | 0.594937 | 302 | 0.764557 | 0 | 0 | 0 | 0 | 0 | 0 | 96 | 0.243038 |
a90000a60889fa2e13612a2352497c1c01e09cb6 | 71,385 | py | Python | DeSu2SE.py | XxArcaiCxX/Devil-Survivor-2-Record-Breaker-Save-Editor | 872717f66f1d9045d48f8d4c2621a925ee4e2817 | [
"MIT"
]
| null | null | null | DeSu2SE.py | XxArcaiCxX/Devil-Survivor-2-Record-Breaker-Save-Editor | 872717f66f1d9045d48f8d4c2621a925ee4e2817 | [
"MIT"
]
| null | null | null | DeSu2SE.py | XxArcaiCxX/Devil-Survivor-2-Record-Breaker-Save-Editor | 872717f66f1d9045d48f8d4c2621a925ee4e2817 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
import os
import sys
print_n = sys.stdout.write
STAT_TXT = ("ST", "MA", "VI", "AG")
# Characters
CHAR_OFFSET = "0x24"
CHAR_ID = ("0x75", 2)
CHAR_LVL = ("0x79", 1)
CHAR_EXP = ("0x7C", 2)
CHAR_HP = ("0x82", 2)
CHAR_MP = ("0x84", 2)
CHAR_ST = ("0x7E", 1)
CHAR_MA = ("0x7F", 1)
CHAR_VI = ("0x80", 1)
CHAR_AG = ("0x81", 1)
CHAR_CMD1 = ("0x86", 1)
CHAR_CMD2 = ("0x87", 1)
CHAR_CMD3 = ("0x88", 1)
CHAR_PAS1 = ("0x89", 1)
CHAR_PAS2 = ("0x8A", 1)
CHAR_PAS3 = ("0x8B", 1)
CHAR_RAC = ("0x8C", 1)
CHAR_MOV = ("0x9F", 1)
# Miscellaneous
MISC_MACCA = ("0x6C4", 4)
# Demons
DE_NUM_MAX = 27
DE_OFFSET = "0x20"
DE_ID = ("0x2B6", 2)
DE_LVL = ("0x2B9", 1)
DE_EXP = ("0x2BC", 2)
DE_HP = ("0x2C2", 2)
DE_MP = ("0x2C4", 2)
DE_ST = ("0x2BE", 1)
DE_MA = ("0x2BF", 1)
DE_VI = ("0x2C0", 1)
DE_AG = ("0x2C1", 1)
DE_CMD1 = ("0x2C6", 1)
DE_CMD2 = ("0x2C7", 1)
DE_CMD3 = ("0x2C8", 1)
DE_PAS1 = ("0x2C9", 1)
DE_PAS2 = ("0x2CA", 1)
DE_PAS3 = ("0x2CB", 1)
DE_RAC = ("0x2CC", 1)
# Skill Information
CMD_IDS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47', '48', '49',
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59',
'60', '61', '62', '63', '64', '65', '66', '67', '68', '69',
'70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
'80', '81', '82', '83', '84', '85', '86', '87', '88', '89',
'90', '91', '92', '93', '94', '95', '96', '97', '98', '99',
'100', '101', '102', '103', '104', '105', '106', '107', '108', '109',
'110', '111', '112', '113', '114', '115', '116', '117', '118', '119',
'120', '121', '122', '123', '124', '125', '126', '127', '128', '129',
'130', '131', '132', '133', '134', '135', '136', '137', '138', '139',
'140', '141', '142', '143', '144', '145', '146', '147', '148', '149',
'150', '151', '152', '153', '154', '155', '156', '157', '158', '159',
'160', '161', '162', '163', '164', '165', '166', '167', '168', '169',
'170', '171', '172')
PAS_IDS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47', '48', '49',
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59',
'60', '61', '62', '63', '64', '65', '66', '67', '68', '69',
'70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
'80', '81', '82', '83', '84', '85', '86', '87', '88', '89',
'90', '91', '92', '93', '94', '95', '96', '97', '98', '99',
'100', '101', '102', '103', '104', '105', '106', '107')
AUTO_IDS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39')
RAC_IDS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47', '48', '49',
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59',
'60', '61', '62', '63', '64', '65', '66', '67', '68', '69',
'70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
'80', '81', '82', '83', '84', '85', '86', '87', '88', '89',
'90', '91', '92', '93', '94', '95', '96', '97', '98', '99',
'100', '101', '102', '103', '104', '105', '106', '107', '108', '109')
DEMON_IDS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19',
'20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47', '48', '49',
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59',
'60', '61', '62', '63', '64', '65', '66', '67', '68', '69',
'70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
'80', '81', '82', '83', '84', '85', '86', '87', '88', '89',
'90', '91', '92', '93', '94', '95', '96', '97', '98', '99',
'100', '101', '102', '103', '104', '105', '106', '107', '108', '109',
'110', '111', '112', '113', '114', '115', '116', '117', '118', '119',
'120', '121', '122', '123', '124', '125', '126', '127', '128', '129',
'130', '131', '132', '133', '134', '135', '136', '137', '138', '139',
'140', '141', '142', '143', '144', '145', '146', '147', '148', '149',
'150', '151', '152', '153', '154', '155', '156', '157', '158', '159',
'160', '161', '162', '163', '164', '165', '166', '167', '168', '169',
'170', '171', '172', '173', '174', '175', '176', '177', '178', '179',
'180', '181', '182', '183', '184', '185', '186', '187', '188', '189',
'190', '191', '192', '193', '194', '195', '196', '197', '198', '199',
'200', '201', '202', '203', '204', '205', '206', '207', '208', '209',
'210', '211', '212', '213', '214', '215', '216', '217', '218', '219',
'220', '221', '222', '223', '224', '225', '226', '227', '228', '229',
'230', '231', '232', '233', '234', '235', '236', '237', '238', '239',
'240', '241', '242', '243', '244', '245', '246', '247', '248', '249',
'250', '251', '252', '253', '254', '255', '256', '257', '258', '259',
'260', '261', '262', '263', '264', '265', '266', '267', '268', '269',
'270', '271', '272', '273', '274', '275', '276', '277', '278', '279',
'280', '281', '282', '283', '284', '285', '286', '287', '288', '289',
'290', '291', '292', '293', '294', '295', '296', '297', '298', '299',
'300', '301', '302', '303', '304', '305', '306', '307', '308', '309',
'310', '311', '312', '313', '314', '315', '316', '317', '318', '319',
'320', '321', '322', '323', '324', '325', '326', '327', '328', '329',
'330', '331', '332', '333', '334', '335', '336', '337', '338', '339',
'340', '341', '342', '343', '344', '345', '346', '347', '348', '349',
'350', '351', '352', '353', '354', '355', '356', '357', '358', '359',
'360', '361', '362', '363', '364', '365', '366', '367', '368', '369',
'370', '371', '372', '373', '374', '375', '376', '377', '378', '379',
'380', '381', '382', '383', '384', '385', '386', '387', '388', '389',
'390', '391', '392', "65535")
# DONE
CMD_SKILLS = {
"0": "None",
"1": "Attack",
"2": "Agi",
"3": "Agidyne",
"4": "Maragi",
"5": "Maragidyne",
"6": "Bufu",
"7": "Bufudyne",
"8": "Mabufu",
"9": "Mabufudyne",
"10": "Zio",
"11": "Ziodyne",
"12": "Mazio",
"13": "Maziodyne",
"14": "Zan",
"15": "Zandyne",
"16": "Mazan",
"17": "Mazandyne",
"18": "Megido",
"19": "Megidolaon",
"20": "Fire Dance",
"21": "Ice Dance",
"22": "Elec Dance",
"23": "Force Dance",
"24": "Holy Dance",
"25": "Drain",
"26": "Judgement",
"27": "Petra Eyes",
"28": "Mute Eyes",
"29": "Paral Eyes",
"30": "Death Call",
"31": "Power Hit",
"32": "Berserk",
"33": "Mighty Hit",
"34": "Anger Hit",
"35": "Brutal Hit",
"36": "Hassohappa",
"37": "Deathbound",
"38": "Weak Kill",
"39": "Desperation",
"40": "Makajamon",
"41": "Gigajama",
"42": "Diajama",
"43": "Makarakarn",
"44": "Tetrakarn",
"45": "Might Call",
"46": "Shield All",
"47": "Taunt",
"48": "Dia",
"49": "Diarahan",
"50": "Media",
"51": "Mediarahan",
"52": "Amrita",
"53": "Prayer",
"54": "Recarm",
"55": "Samerecarm",
"56": "Gunfire",
"57": "Guard",
"58": "Devil's Fuge",
"59": "Vampiric Mist",
"60": "Lost Flame",
"61": "Spawn",
"62": "Fire of Sodom",
"63": "Purging Light",
"64": "Babylon",
"65": "Megidoladyne",
"66": "Piercing Hit",
"67": "Multi-Hit",
"68": "Holy Strike",
"69": "Power Charge",
"70": "Sexy Gaze",
"71": "Marin Karin",
"72": "Extra Cancel",
"73": "Assassinate",
"74": "Fatal Strike",
"75": "Diarama",
"76": "Nigayomogi",
"77": "Recarmloss",
"78": "Mow Down",
"79": "Snipe",
"80": "Life Drain",
"81": "Multi-strike",
"82": "Inferno",
"83": "Escape",
"84": "Remain",
"85": "Double Strike",
"86": "Binary Fire",
"87": "Heat Charge",
"88": "N/A",
"89": "Marked Wing",
"90": "Eject Shot",
"91": "Circumpolarity",
"92": "N/A",
"93": "N/A",
"94": "Hacking",
"95": "Dark Tunder",
"96": "Diastrophism",
"97": "Regenerate",
"98": "Ultimate Hit",
"99": "Twin Ultimate",
"100": "Swallow",
"101": "N/A",
"102": "Binary Fire",
"103": "Circumpolarity",
"104": "Alkaid",
"105": "Areadbhar",
"106": "Dark Thunder",
"107": "Regenerate",
"108": "Supernova",
"109": "Power Up",
"110": "Ominous Star",
"111": "Heaven Wrath",
"112": "Cepheid",
"113": "Unheard Prayer",
"114": "Steal Macca",
"115": "Barrage Strike",
"116": "Heaven Wrath",
"117": "Necromancy",
"118": "Gomorrah Fire",
"119": "Vitality Drain",
"120": "Die for Me!",
"121": "Ruinous Wind",
"122": "Star Pressure",
"123": "Ruinous Wind",
"124": "Diastrophism",
"125": "Final Hit",
"126": "Dream Eater",
"127": "Demon Dance",
"128": "Roche Lobe",
"129": "Darkness Blade",
"130": "Defense Knife",
"131": "Carney",
"132": "Then, die!",
"133": "Don't Hurt Me",
"134": "Wanna Beating?",
"135": "Shadow Scythe",
"136": "No Killing...",
"137": "Shadow Shield",
"138": "Nemean Roar",
"139": "Wider-Radius",
"140": "Spica Spear",
"141": "Memory-Sharing",
"142": "Frozen Pillar",
"143": "Vicarious Spell",
"144": "Vicarious Doll",
"145": "Quaser",
"146": "Life Plower",
"147": "Asterion",
"148": "Partial Blast",
"149": "Vrano=Metria",
"150": "Megidoladyne",
"151": "Darkness Blade(Phys)",
"152": "Darkness Blade(Fire)",
"153": "Darkness Blade(Ice)",
"154": "Darkness Blade(Elec)",
"155": "Darkness Blade(Force)",
"156": "Then, die!(Phys)",
"157": "Then, die!(Phys)",
"158": "Then, die!(Phys)",
"159": "Then, die!(Almighty)",
"160": "Lion's Armor",
"161": "Ley Line True",
"162": "Life Plower True",
"163": "Beheadal",
"164": "Primal Fire",
"165": "Gravity Anomaly",
"166": "Orogin Selection",
"167": "Earthly Stars",
"168": "Master of Life",
"169": "Heavenly Rule",
"170": "Fringer's Brand",
"171": "Flaming Fanfare",
"172": "Ley Line"
}
# DONE
PAS_SKILLS = {
"0": "None",
"1": "+Mute",
"2": "+Poison",
"3": "+Paralyze",
"4": "+Stone",
"5": "Life Bonus",
"6": "Mana Bonus",
"7": "Life Surge",
"8": "Mana Surge",
"9": "Hero Aid",
"10": "Ares Aid",
"11": "Drain Hit",
"12": "Attack All",
"13": "Counter",
"14": "Retaliate",
"15": "Avenge",
"16": "Phys Boost",
"17": "Phys Amp",
"18": "Fire Boost",
"19": "Fire Amp",
"20": "Ice Boost",
"21": "Ice Amp",
"22": "Elec Boost",
"23": "Elec Amp",
"24": "Force Boost",
"25": "Force Amp",
"26": "Anti-Phys",
"27": "Anti-Fire",
"28": "Anti-Ice",
"29": "Anti-Elec",
"30": "Anti-Force",
"31": "Anti-Curse",
"32": "Anti-Most",
"33": "Anti-All",
"34": "Null Phys",
"35": "Null Fire",
"36": "Null Ice",
"37": "Null Elec",
"38": "Null Force",
"39": "Null Curse",
"40": "Phys Drain",
"41": "Fire Drain",
"42": "Ice Drain",
"43": "Elec Drain",
"44": "Force Drain",
"45": "Phys Repel",
"46": "Fire Repel",
"47": "Ice Repel",
"48": "Elec Repel",
"49": "Force Repel",
"50": "Watchful",
"51": "Endure",
"52": "Life Aid",
"53": "Life Lift",
"54": "Mana Aid",
"55": "Victory Cry",
"56": "Pierce",
"57": "Race-O",
"58": "Race-D",
"59": "Dual Shadow",
"60": "Extra One",
"61": "Leader Soul",
"62": "Knight Soul",
"63": "Paladin Soul",
"64": "Hero Soul",
"65": "Beast Eye",
"66": "Dragon Eye",
"67": "Crit Up",
"68": "Dodge",
"69": "MoneyBags",
"70": "Quick Move",
"71": "Vigilant",
"72": "Grimoire",
"73": "Double Strike",
"74": "Perserve Extra",
"75": "Anti-Element",
"76": "+Forget",
"77": "Extra Bonus",
"78": "Swift Step",
"79": "Life Stream",
"80": "Mana Stream",
"81": "Ultimate Hit",
"82": "Anti-Almighty",
"83": "Phys Up",
"84": "Pacify Human",
"85": "Dragon Power",
"86": "True Dragon",
"87": "Final Dragon",
"88": "Heavenly Gift",
"89": "Chaos Stir",
"90": "Undead",
"91": "Hidden Strength",
"92": "Holy Blessing",
"93": "Exchange",
"94": "Extra Zero",
"95": "Spirit Gain",
"96": "Hit Rate Gain",
"97": "Quick Wit",
"98": "Parkour",
"99": "Hitori Nabe",
"100": "Ikebukuro King",
"101": "Immortal Barman",
"102": "Defenseless",
"103": "Coiste Bodhar",
"104": "Dark Courier",
"105": "Massive Shadow",
"106": "Hound Eyes",
"107": "Fighting Doll",
}
# DONE
RAC_SKILLS = {
"0": "None",
"1": "Affection",
"2": "Awakening",
"3": "Chaos Wave",
"4": "Constrict",
"5": "Evil Wave",
"6": "Blood Wine",
"7": "Flight",
"8": "Sacrifice",
"9": "Switch",
"10": "Animal Leg",
"11": "Devil Speed",
"12": "Phantasm",
"13": "Glamour",
"14": "Tyranny",
"15": "Double Up",
"16": "Aggravate",
"17": "Bind",
"18": "Devotion",
"19": "Long Range",
"20": "Immortal",
"21": "Evil Flame",
"22": "Hot Flower",
"23": "Dark Hand",
"24": "Violent God",
"25": "King's Gate",
"26": "King's Gate",
"27": "Fiend",
"28": "Four Devas",
"29": "Dark Finger",
"30": "Asura Karma",
"31": "Ghost Wounds",
"32": "Hero's Mark",
"33": "Uncanny Form",
"34": "Asura Destiny",
"35": "Goddess Grace",
"36": "Enlightenment",
"37": "Chaos Breath",
"38": "Dragon Bind",
"39": "Evil Flow",
"40": "Angel Stigma",
"41": "Winged Flight",
"42": "Fallen's Mark",
"43": "Warp Step",
"44": "Free Leap",
"45": "Devil Flash",
"46": "True Phantasm",
"47": "Fairy Dust",
"48": "Blood Treaty",
"49": "Matchless",
"50": "Agitate",
"51": "Evil Bind",
"52": "Mother's Love",
"53": "Possesion",
"54": "Hero's Proof",
"55": "Unearthy Form",
"56": "Dubhe Proof",
"57": "Merak Proof",
"58": "Phecda Proof",
"59": "Megrez Proof",
"60": "Alioth Proof",
"61": "Mizar Proof",
"62": "Alkaid Proof",
"63": "Polaris Proof",
"64": "Alcor Proof",
"65": "Alcor Warrant",
"66": "Merak Envoy",
"67": "Phecda Clone",
"68": "Megrez Bud",
"69": "Alioth Shot",
"70": "Alkaid Bud",
"71": "Alkaid Spawn",
"72": "Alkaid Spawn",
"73": "Alkaid Spawn",
"74": "Alkaid Spawn",
"75": "Polaris Proof",
"76": "Polaris Proof",
"77": "Heaven Throne",
"78": "Dragon Shard",
"79": "Lugh Blessing",
"80": "Heaven Shield",
"81": "Bounty Shield",
"82": "Heaven Spear",
"83": "Bounty Spear",
"84": "Temptation",
"85": "Mizar Proof",
"86": "Mizar Proof",
"87": "Star's Gate",
"88": "Shinjuku Intel",
"89": "Fighting Doll",
"90": "Headless Rider",
"91": "Leonid Five",
"92": "Spica Sign",
"93": "Spica Sign",
"94": "Shiki-Ouji",
"95": "Arcturus Sign",
"96": "Miyako",
"97": "Cor Caroli Sign",
"98": "Cor Caroli Half",
"99": "Agent of Order",
"100": "Universal Law",
"101": "Factor of Heat",
"102": "Factor of Power",
"103": "Factor of Space",
"104": "Factor of Time",
"105": "???",
"106": "Program: Joy",
"107": "Program: Ultra",
"108": "Fangs of Order",
"109": "Gate of Order"
}
# DONE
AUTO_SKILLS = {
"0": "None",
"1": "Blitzkrieg",
"2": "Hustle",
"3": "Fortify",
"4": "Barrier",
"5": "Wall",
"6": "Full Might",
"7": "Ban Phys",
"8": "Ban Fire",
"9": "Ban Ice",
"10": "Ban Elec",
"11": "Ban Force",
"12": "Ban Curse",
"13": "Rage Soul",
"14": "Grace",
"15": "Marksman",
"16": "Tailwind",
"17": "Magic Yin",
"18": "Battle Aura",
"19": "Revive",
"20": "Magic Yang",
"21": "Healing",
"22": "Alter Pain",
"23": "Weaken",
"24": "Debilitate",
"25": "Health Save",
"26": "Strengthen",
"27": "Grimoire +",
"28": "Desperation",
"29": "Rejuvenate",
"30": "Null Auto",
"31": "Pierce +",
"32": "Endure +",
"33": "Neurotoxin",
"34": "Temptation",
"35": "Shield All EX",
"36": "Dual Shadow EX",
"37": "Kinetic Vision",
"38": "Magnet Barrier",
"39": "Distortion",
}
# Character ID's
ALL_CHARS = {
"0": "MC",
"400": "Fumi",
"300": "Yamato",
"900": "Keita",
"800": "Makoto",
"700": "Jungo",
"a00": "Airi",
"b00": "Joe",
"600": "Otome",
"500": "Daichi",
"c00": "Hinako",
"200": "Io",
"100": "Ronaldo",
"d00": "Alcor"
}
# Demon Information
ALL_DEMONS = {
"0": "Human MC",
"1": "Human Ronaldo",
"2": "Human Io",
"3": "Human Yamato",
"4": "Human Fumi",
"5": "Human Daichi",
"6": "Human Otome",
"7": "Human Jungo",
"8": "Human Makoto",
"9": "Human Keita",
"10": "Human Airi",
"11": "Human Joe",
"12": "Human Hinako",
"13": "Human Alcor",
"14": "Omega Tonatiuh",
"15": "Omega Chernobog",
"16": "Omega Wu Kong",
"17": "Omega Susano-o",
"18": "Omega Kartikeya",
"19": "Omega Shiva",
"20": "Megami Hathor",
"21": "Megami Sarasvati",
"22": "Megami Kikuri-hime",
"23": "Megami Brigid",
"24": "Megami Scathach",
"25": "Megami Laksmi",
"26": "Megami Norn",
"27": "Megami Isis",
"28": "Megami Amaterasu",
"29": "Deity Mahakala",
"30": "Deity Thor",
"31": "Deity Arahabaki",
"32": "Deity Odin",
"33": "Deity Yama",
"34": "Deity Lugh",
"35": "Deity Baal",
"36": "Deity Asura",
"37": "Vile Orcus",
"38": "Vile Pazuzu",
"39": "Vile Abaddon",
"40": "Vile Tao Tie",
"41": "Vile Arioch",
"42": "Vile Tezcatlipoca",
"43": "Vile Nyarlathotep",
"44": "Snake Makara",
"45": "Snake Nozuchi",
"46": "Snake Pendragon",
"47": "Snake Gui Xian",
"48": "Snake Quetzacoatl",
"49": "Snake Seiyuu",
"50": "Snake Orochi",
"51": "Snake Ananta",
"52": "Snake Hoyau Kamui",
"53": "Dragon Toubyou",
"54": "Dragon Bai Suzhen",
"55": "Dragon Basilisk",
"56": "Dragon Ym",
"57": "Dragon Python",
"58": "Dragon Culebre",
"59": "Dragon Vritra",
"60": "Dragon Vasuki",
"61": "Divine Holy Ghost",
"62": "Divine Angel",
"63": "Divine Power",
"64": "Divine Lailah",
"65": "Divine Aniel",
"66": "Divine Kazfiel",
"67": "Divine Remiel",
"68": "Divine Metatron",
"69": "Avian Itsumade",
"70": "Avian Moh Shuvuu",
"71": "Avian Hamsa",
"72": "Avian Suparna",
"73": "Avian Vidofnir",
"74": "Avian Badb Catha",
"75": "Avian Anzu",
"76": "Avian Feng Huang",
"77": "Avian Garuda",
"78": "Fallen Gagyson",
"79": "Fallen Abraxas",
"80": "Fallen Flauros",
"81": "Fallen Nisroc",
"82": "Fallen Orobas",
"83": "Fallen Decarabia",
"84": "Fallen Nebiros",
"85": "Fallen Agares",
"86": "Fallen Murmur",
"87": "Avatar Heqet",
"88": "Avatar Kamapua'a",
"89": "Avatar Shiisaa",
"90": "Avatar Bai Ze",
"91": "Avatar Baihu",
"92": "Avatar Airavata",
"93": "Avatar Ukano Mitama",
"94": "Avatar Barong",
"95": "Avatar Anubis",
"96": "Beast Kabuso",
"97": "Beast Hairy Jack",
"98": "Beast Nekomata",
"99": "Beast Cait Sith",
"100": "Beast Nue",
"101": "Beast Orthrus",
"102": "Beast Myrmecolion",
"103": "Beast Cerberus",
"104": "Beast Fenrir",
"105": "Wilder Hare of Inaba",
"106": "Wilder Waira",
"107": "Wilder Garm",
"108": "Wilder Afanc",
"109": "Wilder Mothman",
"110": "Wilder Taown",
"111": "Wilder Behemoth",
"112": "Wilder Ammut",
"113": "Genma Tam Lin",
"114": "Genma Jambavan",
"115": "Genma Tlaloc",
"116": "Genma Ictinike",
"117": "Genma Hanuman",
"118": "Genma Cu Chulainn",
"119": "Genma Kresnik",
"120": "Genma Ganesha",
"121": "Genma Heimdal",
"122": "Fairy Pixie",
"123": "Fairy Knocker",
"124": "Fairy Kijimunaa",
"125": "Fairy Jack Frost",
"126": "Fairy Pyro Jack",
"127": "Fairy Silky",
"128": "Fairy Lorelei",
"129": "Fairy Vivian",
"130": "Fairy Titania",
"131": "Fairy Oberon",
"132": "Tyrant King Frost",
"133": "Tyrant Moloch",
"134": "Tyrant Hecate",
"135": "Tyrant Tzizimitl",
"136": "Tyrant Astaroth",
"137": "Tyrant Mot",
"138": "Tyrant Loki",
"139": "Tyrant Lucifer",
"140": "Kishin Ubelluris",
"141": "Kishin Nalagiri",
"142": "Hitokotonusi",
"143": "Kishin Take-Mikazuchi",
"144": "Kishin Zouchouten",
"145": "Kishin Jikokuten",
"146": "Kishin Koumokuten",
"147": "Kishin Bishamonten",
"148": "Kishin Zaou Gongen",
"149": "Touki Kobold",
"150": "Touki Bilwis",
"151": "Touki Gozuki",
"152": "Touki Mezuki",
"153": "Touki Ikusa",
"154": "Touki Lham Dearg",
"155": "Touki Berserker",
"156": "Touki Yaksa",
"157": "Touki Nata Taishi",
"158": "Touki Oumitsunu",
"159": "Jaki Obariyon",
"160": "Jaki Ogre",
"161": "Jaki Mokoi",
"162": "Jaki Ogun",
"163": "Jaki Wendigo",
"164": "Jaki Legion",
"165": "Jaki Rakshasa",
"166": "Jaki Girimehkala",
"167": "Jaki Grendel",
"168": "Jaki Black Frost",
"169": "Femme Kikimora",
"170": "Femme Lilim",
"171": "Femme Yuki Jyorou",
"172": "Femme Leanan Sidhe",
"173": "Femme Peri",
"174": "Femme Hariti",
"175": "Femme Rangda",
"176": "Femme Kali",
"177": "Femme Lilith",
"178": "Ghost Poltergeist",
"179": "Ghost Agathion",
"180": "Ghost Tenon Cut",
"181": "Ghost Kumbhanda",
"182": "Ghost Loa",
"183": "Ghost Pisaca",
"184": "Ghost Kudlak",
"185": "Ghost Purple Mirror",
"186": "Fiend Biliken",
"187": "Fiend Ghost Q ",
"188": "Fiend Sage of Time",
"189": "Fiend Alice",
"190": "Fiend Trumpeter",
"191": "Hero Neko Shogun",
"192": "Hero Hagen",
"193": "Hero Jeanne d'Arc",
"194": "Hero Yoshitsune",
"195": "Hero Guan Yu",
"196": "Element Flaemis",
"197": "Element Aquans",
"198": "Element Aeros",
"199": "Element Erthys",
"200": "Mitama Ara Mitama",
"201": "Mitama Nigi Mitama",
"202": "Mitama Kusi Mitama",
"203": "Mitama Saki Mitama",
"204": "Fallen Satan",
"205": "Fallen Beelzebub",
"206": "Fallen Belial",
"207": "Divine Sariel",
"208": "Divine Anael",
"209": "Human Atsuro",
"210": "Human Yuzu",
"211": "Dragon Asp",
"212": "Avatar Apis",
"213": "Avatar Pabilsag",
"214": "Wilder Sleipnir",
"215": "Wilder Xiezhai",
"216": "Genma Kangiten",
"217": "Vile Baphomet",
"218": "Famme Anat",
"219": "Megami Pallas Athena",
"220": "Deity Mithra",
"221": "Deity Osiris",
"222": "Snake Gucumatz",
"223": "Avian Da Peng",
"224": "Kishin Ometeotl",
"225": "Genma Jarilo",
"226": "Human Miyako",
"227": "Fallen Botis",
"228": "Human JP's Member",
"229": "Human Salaryman(1)",
"230": "Human Salaryman(2)",
"231": "Human Salaryman(3)",
"232": "Fallen Samael",
"233": "Human Office Lady(1)",
"234": "Human Office Lady(2)",
"235": "Human Office Lady(3)",
"236": "Human Punk(1)",
"237": "Human Punk(2)",
"238": "Human Punk(3)",
"239": "Human Yakuza(1)",
"240": "Human Yakuza(2)",
"241": "Device Module",
"242": "Human Policeman",
"243": "Human JP's Member(F)",
"244": "Human JP's Member(M)",
"245": "Human Young Man(?)",
"246": "Human Old Woman(?)",
"247": "Human Worker",
"248": "Human Student",
"249": "Human Young man",
"250": "Human Buffer(1)",
"251": "Human Buffer(2)",
"252": "Human JP'S Agent(?)",
"253": "Human JP'S Agent(?)",
"254": "Human JP'S Agent(?)",
"255": "Human JP'S Agent(?)",
"256": "Human ?",
"257": "Fallen Bifrons",
"258": "Fallen Barbatos",
"259": "Femme Dzelarhons",
"260": "Genma Kama",
"261": "Megami Parvati",
"262": "Femme Ixtab",
"263": "Tyrant Balor",
"264": "Tyrant Negral",
"265": "Deity Inti",
"266": "Deity Alilat",
"267": "Omega Beji-Weng",
"268": "Deity Lord Nan Dou",
"269": "Hero Masakado",
"270": "Megami Ishtar",
"271": "Megami Black Maria",
"272": "Snake Yurlungr",
"273": "Dragon Fafnir",
"274": "Divine Sraosha",
"275": "Avian Rukh",
"276": "Avian Kau",
"277": "Beast Cbracan",
"278": "Beast Catoblepas",
"279": "Genma Roitschaggata",
"280": "Fairy Spriggan",
"281": "Fairy Troll",
"282": "Tyrant Lucifuge",
"283": "Kishin Okuninushi",
"284": "Touki Dokkaebi",
"285": "Touki Ongyo-Ki",
"286": "Jaki Macabre",
"287": "Femme Jahi",
"288": "Divine Sandalphon",
"289": "Snake Kohruy",
"290": "Exotic Izaya",
"291": "Exotic Celty",
"292": "Exotic Shizuo",
"293": "Touki Momunofu",
"294": "Tyrant Lucifer Frost",
"295": "(Crashes GUI)",
"296": "Hero Frost Five",
"297": "Hero Milk-Kin Frost",
"298": "Hero Strawberry Fost",
"299": "Fairy Lemon Frost",
"300": "Fairy Melon Frost",
"301": "Fairy B. Hawaii Frost",
"302": "Touki Titan",
"303": "Omega Dyonisus",
"304": "Omega Aramisaki",
"305": "Jaki Shiki-Ouji",
"306": "Feeme Xi Wangmu",
"307": "Divine Dominion",
"308": "Fiend Mother Harlot",
"309": "Fiend Dantalian",
"310": "Vile Seth",
"311": "Jaki Shinigami",
"312": "Bel Belberith",
"313": "Bel Jezebel",
"314": "Bel Beldr",
"315": "Maggot Maggot",
"316": "Star Dubhe",
"317": "Star Merak",
"318": "Star Phecda",
"319": "Star Megrez",
"320": "Star Alioth Core",
"321": "Star Mizar",
"322": "Star Benetnasch",
"323": "Star Alcor",
"324": "Star Polaris",
"325": "Star Merak Missile",
"326": "Star Phecda(WK MAG)",
"327": "Star Phecda(WK PHYS)",
"328": "Star Megrez(Empty)",
"329": "Star Alioth (Poison)",
"330": "Energy LayLine Dragon",
"331": "Star Dubhe",
"332": "Star Dunhe(weak)",
"333": "Star Mizar",
"334": "Star Mizar",
"335": "Star Tentacle",
"336": "Star Tentacle",
"337": "Star Tentacle",
"338": "Star Tentacle",
"339": "Star Tentacle",
"340": "Star Tentacle",
"341": "Star Benetnasch(dubhe)",
"342": "Star Benetnasch(merak)",
"343": "Star Benetnasch(phecda)",
"344": "Star Benetnasch(Alioth)",
"345": "Star Benetnasch",
"346": "Star Alcor",
"347": "Star Polaris A",
"348": "Star Polaris Ab",
"349": "Star Polaris B",
"350": "Human Tall Woman",
"351": "Device Tico",
"352": "Device Tico",
"353": "Human Daichi",
"354": "Human Io",
"355": "Human Io",
"356": "Human MC",
"357": "Human SDF Captain",
"358": "Human SDF Member",
"359": "Human Fireman",
"360": "Deity Io",
"361": "Star Guardian",
"362": "Star Guardian",
"363": "Star Guardian",
"364": "Star Guardian",
"365": "Star Guardian",
"366": "Star Guardian",
"367": "Star Guardian",
"368": "Human Salaryman(1)",
"369": "Human Punk(1)",
"370": "Human Student(1)",
"371": "Human Student(2)",
"372": "Human Young Man(1)",
"373": "Human Young Man(2)",
"374": "Human Salaryman(2)",
"375": "Human Salaryman(3)",
"376": "Human Punk(2)",
"377": "Human Punk(3)",
"378": "Human Kitten",
"379": "Human @",
"380": "Human Ronaldo*",
"381": "Human Io*",
"382": "Human Yamato*",
"383": "Human Fumi*",
"384": "Human Daichi*",
"385": "Human Otome*",
"386": "Human Jungo*",
"387": "Human Makoto*",
"388": "Human Keita*",
"389": "Human Airi*",
"390": "Human Joe*",
"391": "Human Hinako*",
"392": "Human Alcor*",
"65535": "Empty"
}
class mytestapp(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self, parent)
self.parent = parent
self.minsize(400, 100)
self.title("Devil Survivor 2 Record Breaker Save Editor")
self.bind(sequence="<Escape>", func=lambda x: self.quit())
self.resizable(width="False", height="False")
self.grid()
self.initVars()
self.processLists()
self.createWidgets()
# x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
# y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
# self.geometry("+%d+%d" % (x, y))
# self.initialSetup()
def initVars(self):
self.saveFilePath = None
self.saveFileDir = None
self.saveFileName = None
self.save_bytes = None
self.charValues = {}
self.curChar = {}
self.curDemon = {}
self.charNameList = []
self.demonNameList = []
self.charList = []
self.demonList = []
self.vcmd = (self.register(self.validate_int), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
def processLists(self):
skillIDNameList = []
# max_width = 0
for val in CMD_IDS:
if val in CMD_SKILLS:
# tmp_str = val + " - " + ALL_SKILLS[val][0]
# if len(tmp_str) > max_width:
# max_width = len(tmp_str)
skillIDNameList.append(val + " - " + CMD_SKILLS[val])
else:
skillIDNameList.append(val + " - None")
self.skillIDNameList = skillIDNameList
# self.skillIDNameWidth = max_width
def createWidgets(self):
# Menu bar
menubar = tk.Menu(self)
submenu1 = tk.Menu(menubar, tearoff=0)
submenu1.add_command(label="Open Save File", underline=0, command=self.openFileChooser)
submenu1.add_command(label="Save Changes", underline=0, command=self.saveChanges)
submenu1.add_separator()
submenu1.add_command(label="Exit", underline=0, command=self.exitApp)
menubar.add_cascade(label="File", underline=0, menu=submenu1)
menubar.add_separator()
# submenu2 = tk.Menu(menubar, tearoff=0)
# submenu2.add_command(label="Compare difference(s)", command=self.>Diff)
# menubar.add_cascade(label="Compare", menu=submenu2)
menubar.add_command(label="About", command=self.aboutCreator)
menubar.add_command(label="Help", command=self.help)
self.config(menu=menubar)
# Main content frame
mainFrame = tk.Frame(self)
mainFrame.grid(column=0, row=0, padx=10, pady=10, sticky="EW")
self.mainFrame = mainFrame
# Frame for folder paths
folderpathFrame = tk.Frame(mainFrame)
folderpathFrame.grid(column=0, row=1, sticky="EW")
folderpathFrame.grid_columnconfigure(1, weight=1)
tk.Label(folderpathFrame, text="Save file: ").grid(column=0, row=1, sticky="W")
self.saveFilePathTxt = tk.StringVar()
tk.Entry(
folderpathFrame, textvariable=self.saveFilePathTxt, state='readonly', width=80
).grid(column=1, row=1, sticky="EW", padx="5 0")
# Frame for tab buttons
tabButtonsFrame = tk.Frame(mainFrame)
tabButtonsFrame.grid(column=0, row=2, pady="20 0", sticky="EW")
self.tab1Button = tk.Button(
tabButtonsFrame, text="Characters", relief="sunken", state="disabled",
command=lambda: self.changeTab(self.tab1Frame, self.tab1Button)
)
self.tab1Button.grid(column=0, row=0, sticky="W")
self.tab2Button = tk.Button(
tabButtonsFrame, text="Demons",
command=lambda: self.changeTab(self.tab2Frame, self.tab2Button)
)
self.tab2Button.grid(column=1, row=0, sticky="W")
# Frame for tab frames
tabFramesFrame = tk.Frame(mainFrame)
tabFramesFrame.grid(column=0, row=3, sticky="EW")
tabFramesFrame.columnconfigure(0, weight=1)
# Frame for 1st tab
tab1Frame = tk.Frame(tabFramesFrame, bd="2", relief="sunken", padx="10", pady="10")
self.tab1Frame = tab1Frame
tab1Frame.grid(column=0, row=0, sticky="EW")
# Top inner frame for 1st tab
tab1TopFrame = tk.Frame(tab1Frame)
tab1TopFrame.grid(column=0, row=0, columnspan=2, sticky="NW")
# Top left inner frame for 1st tab
tab1TopLFrame = tk.Frame(tab1TopFrame)
tab1TopLFrame.grid(column=0, row=0, sticky="NW")
tab1ComboLabel = tk.Label(tab1TopLFrame, text="Select Character")
tab1ComboLabel.grid(column=1, row=0)
# ComboBox
tab1ComboBox = ttk.Combobox(tab1TopLFrame, values=self.charNameList)
print(self.charNameList)
tab1ComboBox.grid(column=2, row=0, padx=10, pady=10)
def changeCharacter(*args):
name = tab1ComboBox.get()
def get_key(val):
for char_info in self.charList:
for key, value in char_info.items():
if val == value:
return char_info
self.curChar = get_key(name)
print(self.curChar)
tab1txtbLVL.delete(0, 5)
tab1txtbLVL.insert(0, self.curChar["level"])
tab1txtbEXP.delete(0, 5)
tab1txtbEXP.insert(0, self.curChar["exp"])
tab1txtbHP.delete(0, 5)
tab1txtbHP.insert(0, self.curChar["hp"])
tab1txtbMP.delete(0, 5)
tab1txtbMP.insert(0, self.curChar["mp"])
tab1txtbST.delete(0, 5)
tab1txtbST.insert(0, self.curChar["st"])
tab1txtbMA.delete(0, 5)
tab1txtbMA.insert(0, self.curChar["ma"])
tab1txtbVI.delete(0, 5)
tab1txtbVI.insert(0, self.curChar["vi"])
tab1txtbAG.delete(0, 5)
tab1txtbAG.insert(0, self.curChar["ag"])
tab1txtbCMD1.delete(0, 5)
tab1txtbCMD1.insert(0, self.curChar["cmd1"])
tab1txtbCMD2.delete(0, 5)
tab1txtbCMD2.insert(0, self.curChar["cmd2"])
tab1txtbCMD3.delete(0, 5)
tab1txtbCMD3.insert(0, self.curChar["cmd3"])
tab1txtbPAS1.delete(0, 5)
tab1txtbPAS1.insert(0, self.curChar["pas1"])
tab1txtbPAS2.delete(0, 5)
tab1txtbPAS2.insert(0, self.curChar["pas2"])
tab1txtbPAS3.delete(0, 5)
tab1txtbPAS3.insert(0, self.curChar["pas3"])
tab1txtbRAC.delete(0, 5)
tab1txtbRAC.insert(0, self.curChar["rac"])
tab1txtbMOV.delete(0, 5)
tab1txtbMOV.insert(0, self.curChar["mov"])
tab1ComboBox.bind("<<ComboboxSelected>>", changeCharacter)
# Labels
tab1LVL = tk.Label(tab1TopLFrame, text="Level:", padx=50)
tab1LVL.grid(column=0, row=1)
tab1EXP = tk.Label(tab1TopLFrame, text="Experience:")
tab1EXP.grid(column=0, row=2)
tab1HP = tk.Label(tab1TopLFrame, text="Health:")
tab1HP.grid(column=0, row=3)
tab1MP = tk.Label(tab1TopLFrame, text="Mana:")
tab1MP.grid(column=0, row=4)
tab1ST = tk.Label(tab1TopLFrame, text="Strength:")
tab1ST.grid(column=0, row=5)
tab1MA = tk.Label(tab1TopLFrame, text="Magic:")
tab1MA.grid(column=0, row=6)
tab1VI = tk.Label(tab1TopLFrame, text="Vitality:")
tab1VI.grid(column=0, row=7)
tab1AG = tk.Label(tab1TopLFrame, text="Agility:")
tab1AG.grid(column=0, row=8)
tab1CMD1 = tk.Label(tab1TopLFrame, text="Command 1:")
tab1CMD1.grid(column=2, row=1)
tab1CMD2 = tk.Label(tab1TopLFrame, text="Command 2:")
tab1CMD2.grid(column=2, row=2)
tab1CMD3 = tk.Label(tab1TopLFrame, text="Command 3:")
tab1CMD3.grid(column=2, row=3)
tab1PAS1 = tk.Label(tab1TopLFrame, text="Passive 1:")
tab1PAS1.grid(column=2, row=4)
tab1PAS2 = tk.Label(tab1TopLFrame, text="Passive 2:")
tab1PAS2.grid(column=2, row=5)
tab1PAS3 = tk.Label(tab1TopLFrame, text="Passive 3:")
tab1PAS3.grid(column=2, row=6)
tab1RAC = tk.Label(tab1TopLFrame, text="Automatic:")
tab1RAC.grid(column=2, row=7)
tab1MOV = tk.Label(tab1TopLFrame, text="Move:")
tab1MOV.grid(column=2, row=8)
# Text Boxes
tab1txtbLVL = tk.Entry(tab1TopLFrame)
tab1txtbLVL.grid(column=1, row=1)
tab1txtbEXP = tk.Entry(tab1TopLFrame)
tab1txtbEXP.grid(column=1, row=2)
tab1txtbHP = tk.Entry(tab1TopLFrame)
tab1txtbHP.grid(column=1, row=3)
tab1txtbMP = tk.Entry(tab1TopLFrame)
tab1txtbMP.grid(column=1, row=4)
tab1txtbST = tk.Entry(tab1TopLFrame)
tab1txtbST.grid(column=1, row=5)
tab1txtbMA = tk.Entry(tab1TopLFrame)
tab1txtbMA.grid(column=1, row=6)
tab1txtbVI = tk.Entry(tab1TopLFrame)
tab1txtbVI.grid(column=1, row=7)
tab1txtbAG = tk.Entry(tab1TopLFrame)
tab1txtbAG.grid(column=1, row=8)
tab1txtbCMD1 = tk.Entry(tab1TopLFrame)
tab1txtbCMD1.grid(column=3, row=1)
tab1txtbCMD2 = tk.Entry(tab1TopLFrame)
tab1txtbCMD2.grid(column=3, row=2)
tab1txtbCMD3 = tk.Entry(tab1TopLFrame)
tab1txtbCMD3.grid(column=3, row=3)
tab1txtbPAS1 = tk.Entry(tab1TopLFrame)
tab1txtbPAS1.grid(column=3, row=4)
tab1txtbPAS2 = tk.Entry(tab1TopLFrame)
tab1txtbPAS2.grid(column=3, row=5)
tab1txtbPAS3 = tk.Entry(tab1TopLFrame)
tab1txtbPAS3.grid(column=3, row=6)
tab1txtbRAC = tk.Entry(tab1TopLFrame)
tab1txtbRAC.grid(column=3, row=7)
tab1txtbMOV = tk.Entry(tab1TopLFrame)
tab1txtbMOV.grid(column=3, row=8)
tab1emptylabel = tk.Label(tab1TopLFrame, text=" ")
tab1emptylabel.grid(column=0, row=9)
# Skill Frame
tab1SkillFrame = tk.Frame(tab1TopLFrame, bd="2", relief="sunken")
tab1SkillFrame.grid(column=0, row=11, columnspan=4)
# Skill Labels
tab1CMD1label = tk.Label(tab1SkillFrame, text="Command")
tab1CMD1label.grid(column=0, row=0)
tab1CMD2label = tk.Label(tab1SkillFrame, text="Passive")
tab1CMD2label.grid(column=1, row=0)
tab1CMD3label = tk.Label(tab1SkillFrame, text="Automatic")
tab1CMD3label.grid(column=2, row=0)
# Listboxes
tab1ListBoxCMD = tk.Listbox(tab1SkillFrame)
for i in range(0, len(CMD_IDS)):
tab1ListBoxCMD.insert(i, " " + str(CMD_IDS[i]) + " - " + str(CMD_SKILLS[CMD_IDS[i]]))
tab1ListBoxCMD.grid(column=0, row=1)
tab1ListBoxPAS = tk.Listbox(tab1SkillFrame)
for i in range(0, len(PAS_IDS)):
tab1ListBoxPAS.insert(i, " " + str(PAS_IDS[i]) + " - " + str(PAS_SKILLS[PAS_IDS[i]]))
tab1ListBoxPAS.grid(column=1, row=1)
tab1ListBoxAUT = tk.Listbox(tab1SkillFrame)
for i in range(0, len(AUTO_IDS)):
tab1ListBoxAUT.insert(i, " " + str(AUTO_IDS[i]) + " - " + str(AUTO_SKILLS[AUTO_IDS[i]]))
tab1ListBoxAUT.grid(column=2, row=1)
# Save Characters Changes
def applyCharChange(*args):
print("\n BEFORE APPLY \n " + str(self.charList))
name = tab1ComboBox.get()
if self.curChar != {}:
def get_key(val):
i = -1
for char_info in self.charList:
i = i + 1
for key, value in char_info.items():
if val == value:
return i, char_info
index, self.cur_char = get_key(name)
# put textbox values in global variable
self.curChar["level"] = tab1txtbLVL.get()
self.curChar["exp"] = tab1txtbEXP.get()
self.curChar["hp"] = tab1txtbHP.get()
self.curChar["mp"] = tab1txtbMP.get()
self.curChar["st"] = tab1txtbST.get()
self.curChar["ma"] = tab1txtbMA.get()
self.curChar["vi"] = tab1txtbVI.get()
self.curChar["ag"] = tab1txtbAG.get()
self.curChar["cmd1"] = tab1txtbCMD1.get()
self.curChar["cmd2"] = tab1txtbCMD2.get()
self.curChar["cmd3"] = tab1txtbCMD3.get()
self.curChar["pas1"] = tab1txtbPAS1.get()
self.curChar["pas2"] = tab1txtbPAS2.get()
self.curChar["pas3"] = tab1txtbPAS3.get()
self.curChar["rac"] = tab1txtbRAC.get()
self.curChar["mov"] = tab1txtbMOV.get()
print("\n AFTER APPLY \n " + str(self.charList))
# put char_info back on list
self.charList[index] = self.curChar
# Bottom Frame
tab1BtmFrame = tk.Frame(tab1Frame, bd="2", relief="sunken")
tab1BtmFrame.grid(column=0, row=2, columnspan=2, sticky="EW", pady="20 0")
tab1BtmFrame.columnconfigure(0, weight=1)
tk.Button(
tab1BtmFrame, text="Apply", command=applyCharChange
).grid(column=0, row=0, sticky="EW")
# Frame for 2nd tab
tab2Frame = tk.Frame(tabFramesFrame, bd="2", relief="sunken", padx="10", pady="10")
self.tab2Frame = tab2Frame
tab2Frame.grid(column=0, row=0, sticky="EW")
# Top inner frame for 2nd tab
tab2TopFrame = tk.Frame(tab2Frame)
tab2TopFrame.grid(column=0, row=0, columnspan=2, sticky="NW")
# Top left inner frame for 2nd tab
tab2TopLFrame = tk.Frame(tab2TopFrame)
tab2TopLFrame.grid(column=0, row=0, sticky="NW")
tab2ComboLabel = tk.Label(tab2TopLFrame, text="Select Demon")
tab2ComboLabel.grid(column=1, row=0)
# 2nd ComboBox
tab2ComboBox = ttk.Combobox(tab2TopLFrame, values=self.demonNameList)
print(self.demonNameList)
tab2ComboBox.grid(column=2, row=0, padx=10, pady=10)
def changeDemon(*args):
index = tab2ComboBox.current()
self.curDemon = self.demonList[index]
print(self.curDemon)
tab2txtbLVL.delete(0, 5)
tab2txtbLVL.insert(0, self.curDemon["level"])
tab2txtbEXP.delete(0, 5)
tab2txtbEXP.insert(0, self.curDemon["exp"])
tab2txtbHP.delete(0, 5)
tab2txtbHP.insert(0, self.curDemon["hp"])
tab2txtbMP.delete(0, 5)
tab2txtbMP.insert(0, self.curDemon["mp"])
tab2txtbST.delete(0, 5)
tab2txtbST.insert(0, self.curDemon["st"])
tab2txtbMA.delete(0, 5)
tab2txtbMA.insert(0, self.curDemon["ma"])
tab2txtbVI.delete(0, 5)
tab2txtbVI.insert(0, self.curDemon["vi"])
tab2txtbAG.delete(0, 5)
tab2txtbAG.insert(0, self.curDemon["ag"])
tab2txtbCMD1.delete(0, 5)
tab2txtbCMD1.insert(0, self.curDemon["cmd1"])
tab2txtbCMD2.delete(0, 5)
tab2txtbCMD2.insert(0, self.curDemon["cmd2"])
tab2txtbCMD3.delete(0, 5)
tab2txtbCMD3.insert(0, self.curDemon["cmd3"])
tab2txtbPAS1.delete(0, 5)
tab2txtbPAS1.insert(0, self.curDemon["pas1"])
tab2txtbPAS2.delete(0, 5)
tab2txtbPAS2.insert(0, self.curDemon["pas2"])
tab2txtbPAS3.delete(0, 5)
tab2txtbPAS3.insert(0, self.curDemon["pas3"])
tab2txtbRAC.delete(0, 5)
tab2txtbRAC.insert(0, self.curDemon["rac"])
tab2txtbID.delete(0, 5)
tab2txtbID.insert(0, self.curDemon["id"])
tab2ComboBox.bind("<<ComboboxSelected>>", changeDemon)
# Labels
tab2LVL = tk.Label(tab2TopLFrame, text="Level:", padx=50)
tab2LVL.grid(column=0, row=1)
tab2EXP = tk.Label(tab2TopLFrame, text="Experience:")
tab2EXP.grid(column=0, row=2)
tab2HP = tk.Label(tab2TopLFrame, text="Health:")
tab2HP.grid(column=0, row=3)
tab2MP = tk.Label(tab2TopLFrame, text="Mana:")
tab2MP.grid(column=0, row=4)
tab2ST = tk.Label(tab2TopLFrame, text="Strength:")
tab2ST.grid(column=0, row=5)
tab2MA = tk.Label(tab2TopLFrame, text="Magic:")
tab2MA.grid(column=0, row=6)
tab2VI = tk.Label(tab2TopLFrame, text="Vitality:")
tab2VI.grid(column=0, row=7)
tab2AG = tk.Label(tab2TopLFrame, text="Agility:")
tab2AG.grid(column=0, row=8)
tab2CMD1 = tk.Label(tab2TopLFrame, text="Command 1:")
tab2CMD1.grid(column=2, row=1)
tab2CMD2 = tk.Label(tab2TopLFrame, text="Command 2:")
tab2CMD2.grid(column=2, row=2)
tab2CMD3 = tk.Label(tab2TopLFrame, text="Command 3:")
tab2CMD3.grid(column=2, row=3)
tab2PAS1 = tk.Label(tab2TopLFrame, text="Passive 1:")
tab2PAS1.grid(column=2, row=4)
tab2PAS2 = tk.Label(tab2TopLFrame, text="Passive 2:")
tab2PAS2.grid(column=2, row=5)
tab2PAS3 = tk.Label(tab2TopLFrame, text="Passive 3:")
tab2PAS3.grid(column=2, row=6)
tab2RAC = tk.Label(tab2TopLFrame, text="Racial:")
tab2RAC.grid(column=2, row=7)
tab2ID = tk.Label(tab2TopLFrame, text="Id:")
tab2ID.grid(column=2, row=8)
# Text Boxes
tab2txtbLVL = tk.Entry(tab2TopLFrame)
tab2txtbLVL.grid(column=1, row=1)
tab2txtbEXP = tk.Entry(tab2TopLFrame)
tab2txtbEXP.grid(column=1, row=2)
tab2txtbHP = tk.Entry(tab2TopLFrame)
tab2txtbHP.grid(column=1, row=3)
tab2txtbMP = tk.Entry(tab2TopLFrame)
tab2txtbMP.grid(column=1, row=4)
tab2txtbST = tk.Entry(tab2TopLFrame)
tab2txtbST.grid(column=1, row=5)
tab2txtbMA = tk.Entry(tab2TopLFrame)
tab2txtbMA.grid(column=1, row=6)
tab2txtbVI = tk.Entry(tab2TopLFrame)
tab2txtbVI.grid(column=1, row=7)
tab2txtbAG = tk.Entry(tab2TopLFrame)
tab2txtbAG.grid(column=1, row=8)
tab2txtbCMD1 = tk.Entry(tab2TopLFrame)
tab2txtbCMD1.grid(column=3, row=1)
tab2txtbCMD2 = tk.Entry(tab2TopLFrame)
tab2txtbCMD2.grid(column=3, row=2)
tab2txtbCMD3 = tk.Entry(tab2TopLFrame)
tab2txtbCMD3.grid(column=3, row=3)
tab2txtbPAS1 = tk.Entry(tab2TopLFrame)
tab2txtbPAS1.grid(column=3, row=4)
tab2txtbPAS2 = tk.Entry(tab2TopLFrame)
tab2txtbPAS2.grid(column=3, row=5)
tab2txtbPAS3 = tk.Entry(tab2TopLFrame)
tab2txtbPAS3.grid(column=3, row=6)
tab2txtbRAC = tk.Entry(tab2TopLFrame)
tab2txtbRAC.grid(column=3, row=7)
tab2txtbID = tk.Entry(tab2TopLFrame)
tab2txtbID.grid(column=3, row=8)
tab2emptylabel = tk.Label(tab2TopLFrame, text=" ")
tab2emptylabel.grid(column=0, row=9)
# Skill Frame
tab2SkillFrame = tk.Frame(tab2TopLFrame, bd="2", relief="sunken")
tab2SkillFrame.grid(column=0, row=11, columnspan=4)
# Skill Labels
tab2CMD1label = tk.Label(tab2SkillFrame, text="Command")
tab2CMD1label.grid(column=0, row=0)
tab2CMD2label = tk.Label(tab2SkillFrame, text="Passive")
tab2CMD2label.grid(column=1, row=0)
tab2CMD3label = tk.Label(tab2SkillFrame, text="Racial")
tab2CMD3label.grid(column=2, row=0)
tab2IDlabel = tk.Label(tab2SkillFrame, text="Demon ID")
tab2IDlabel.grid(column=3, row=0)
# Listboxes
tab2ListBoxCMD = tk.Listbox(tab2SkillFrame)
for i in range(0, len(CMD_IDS)):
tab2ListBoxCMD.insert(i, " " + str(CMD_IDS[i]) + " - " + str(CMD_SKILLS[CMD_IDS[i]]))
tab2ListBoxCMD.grid(column=0, row=1)
tab2ListBoxPAS = tk.Listbox(tab2SkillFrame)
for i in range(0, len(PAS_IDS)):
tab2ListBoxPAS.insert(i, " " + str(PAS_IDS[i]) + " - " + str(PAS_SKILLS[PAS_IDS[i]]))
tab2ListBoxPAS.grid(column=1, row=1)
tab2ListBoxRAC = tk.Listbox(tab2SkillFrame)
for i in range(0, len(RAC_IDS)):
tab2ListBoxRAC.insert(i, " " + str(RAC_IDS[i]) + " - " + str(RAC_SKILLS[RAC_IDS[i]]))
tab2ListBoxRAC.grid(column=2, row=1)
tab2ListBoxID = tk.Listbox(tab2SkillFrame, width=23)
for i in range(0, len(DEMON_IDS)):
tab2ListBoxID.insert(i, " " + str(DEMON_IDS[i]) + " - " + str(ALL_DEMONS[DEMON_IDS[i]]))
tab2ListBoxID.grid(column=3, row=1)
# Save Characters Changes
def applyDemonChange(*args):
print("\n BEFORE APPLY \n " + str(self.demonList))
if self.curDemon != {}:
index = tab2ComboBox.current()
self.curDemon = self.demonList[index]
# put textbox values in global variable
self.curDemon["level"] = tab2txtbLVL.get()
self.curDemon["exp"] = tab2txtbEXP.get()
self.curDemon["hp"] = tab2txtbHP.get()
self.curDemon["mp"] = tab2txtbMP.get()
self.curDemon["st"] = tab2txtbST.get()
self.curDemon["ma"] = tab2txtbMA.get()
self.curDemon["vi"] = tab2txtbVI.get()
self.curDemon["ag"] = tab2txtbAG.get()
self.curDemon["cmd1"] = tab2txtbCMD1.get()
self.curDemon["cmd2"] = tab2txtbCMD2.get()
self.curDemon["cmd3"] = tab2txtbCMD3.get()
self.curDemon["pas1"] = tab2txtbPAS1.get()
self.curDemon["pas2"] = tab2txtbPAS2.get()
self.curDemon["pas3"] = tab2txtbPAS3.get()
self.curDemon["rac"] = tab2txtbRAC.get()
self.curDemon["id"] = tab2txtbID.get()
print("\n AFTER APPLY \n " + str(self.demonList))
# put char_info back on list
self.demonList[index] = self.curDemon
# Bottom Frame
tab2BtmFrame = tk.Frame(tab2Frame, bd="2", relief="sunken")
tab2BtmFrame.grid(column=0, row=2, columnspan=2, sticky="EW", pady="20 0")
tab2BtmFrame.columnconfigure(0, weight=1)
tk.Button(
tab2BtmFrame, text="Apply", command=applyDemonChange
).grid(column=0, row=0, sticky="EW")
# Hide the other tabs, only show first tab
self.tabShown = self.tab1Frame
self.tabButton = self.tab1Button
self.tab2Frame.grid_remove()
def validate_int(self, action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if action == "0":
return True
try:
int(value_if_allowed)
return True
except ValueError:
return False
def processSaveFile(self):
with open(self.saveFilePath, 'rb') as fh:
self.save_bytes = bytearray(fh.read())
if self.save_bytes is not None:
# For 1st Tab (Main Character)
del self.charList[:]
for x in range(0, 13):
c_start_add = int(CHAR_OFFSET, 16) * x
c_id_add = c_start_add + int(CHAR_ID[0], 16)
char_id = self.getHexStr(self.save_bytes, c_id_add, CHAR_ID[1], add_is_dec=True)
print(char_id)
if char_id in ALL_CHARS:
c_id_add = c_start_add + int(CHAR_ID[0], 16)
c_lvl_add = c_start_add + int(CHAR_LVL[0], 16)
c_exp_add = c_start_add + int(CHAR_EXP[0], 16)
c_hp_add = c_start_add + int(CHAR_HP[0], 16)
c_mp_add = c_start_add + int(CHAR_MP[0], 16)
c_st_add = c_start_add + int(CHAR_ST[0], 16)
c_ma_add = c_start_add + int(CHAR_MA[0], 16)
c_vi_add = c_start_add + int(CHAR_VI[0], 16)
c_ag_add = c_start_add + int(CHAR_AG[0], 16)
c_cmd1_add = c_start_add + int(CHAR_CMD1[0], 16)
c_cmd2_add = c_start_add + int(CHAR_CMD2[0], 16)
c_cmd3_add = c_start_add + int(CHAR_CMD3[0], 16)
c_pas1_add = c_start_add + int(CHAR_PAS1[0], 16)
c_pas2_add = c_start_add + int(CHAR_PAS2[0], 16)
c_pas3_add = c_start_add + int(CHAR_PAS3[0], 16)
c_rac_add = c_start_add + int(CHAR_RAC[0], 16)
c_mov_add = c_start_add + int(CHAR_MOV[0], 16)
char_info = ALL_CHARS[char_id]
c_info = {
"start_add": c_start_add,
"name": char_info,
"id": int(self.getHexStr(self.save_bytes, c_id_add, CHAR_ID[1], add_is_dec=True), 16),
"level": int(self.getHexStr(self.save_bytes, c_lvl_add, CHAR_LVL[1], add_is_dec=True), 16),
"exp": int(self.getHexStr(self.save_bytes, c_exp_add, CHAR_EXP[1], add_is_dec=True), 16),
"hp": int(self.getHexStr(self.save_bytes, c_hp_add, CHAR_HP[1], add_is_dec=True), 16),
"mp": int(self.getHexStr(self.save_bytes, c_mp_add, CHAR_MP[1], add_is_dec=True), 16),
"st": int(self.getHexStr(self.save_bytes, c_st_add, CHAR_ST[1], add_is_dec=True), 16),
"ma": int(self.getHexStr(self.save_bytes, c_ma_add, CHAR_MA[1], add_is_dec=True), 16),
"vi": int(self.getHexStr(self.save_bytes, c_vi_add, CHAR_VI[1], add_is_dec=True), 16),
"ag": int(self.getHexStr(self.save_bytes, c_ag_add, CHAR_AG[1], add_is_dec=True), 16),
"cmd1": int(self.getHexStr(self.save_bytes, c_cmd1_add, CHAR_CMD1[1], add_is_dec=True), 16),
"cmd2": int(self.getHexStr(self.save_bytes, c_cmd2_add, CHAR_CMD2[1], add_is_dec=True), 16),
"cmd3": int(self.getHexStr(self.save_bytes, c_cmd3_add, CHAR_CMD3[1], add_is_dec=True), 16),
"pas1": int(self.getHexStr(self.save_bytes, c_pas1_add, CHAR_PAS1[1], add_is_dec=True), 16),
"pas2": int(self.getHexStr(self.save_bytes, c_pas2_add, CHAR_PAS2[1], add_is_dec=True), 16),
"pas3": int(self.getHexStr(self.save_bytes, c_pas3_add, CHAR_PAS3[1], add_is_dec=True), 16),
"rac": int(self.getHexStr(self.save_bytes, c_rac_add, CHAR_RAC[1], add_is_dec=True), 16),
"mov": int(self.getHexStr(self.save_bytes, c_mov_add, CHAR_MOV[1], add_is_dec=True), 16),
}
self.charList.append(c_info)
self.charNameList.append(char_info)
print("Start Address: %x, Char ID: %s, Name: %s." % (c_info["start_add"], char_id, char_info))
# For 2nd Tab (Demons)
del self.demonList[:]
for x in range(0, DE_NUM_MAX):
d_start_add = int(DE_OFFSET, 16) * x
d_id_add = d_start_add + int(DE_ID[0], 16)
demon_id = self.getHexStr(self.save_bytes, d_id_add, DE_ID[1], add_is_dec=True)
if True:
d_id_add = d_start_add + int(DE_ID[0], 16)
d_lvl_add = d_start_add + int(DE_LVL[0], 16)
d_exp_add = d_start_add + int(DE_EXP[0], 16)
d_hp_add = d_start_add + int(DE_HP[0], 16)
d_mp_add = d_start_add + int(DE_MP[0], 16)
d_st_add = d_start_add + int(DE_ST[0], 16)
d_ma_add = d_start_add + int(DE_MA[0], 16)
d_vi_add = d_start_add + int(DE_VI[0], 16)
d_ag_add = d_start_add + int(DE_AG[0], 16)
d_cmd1_add = d_start_add + int(DE_CMD1[0], 16)
d_cmd2_add = d_start_add + int(DE_CMD2[0], 16)
d_cmd3_add = d_start_add + int(DE_CMD3[0], 16)
d_pas1_add = d_start_add + int(DE_PAS1[0], 16)
d_pas2_add = d_start_add + int(DE_PAS2[0], 16)
d_pas3_add = d_start_add + int(DE_PAS3[0], 16)
d_rac_add = d_start_add + int(DE_RAC[0], 16)
demon_id = int(self.getHexStr(self.save_bytes, d_id_add, DE_ID[1], add_is_dec=True), 16)
print(demon_id)
demon_info = ALL_DEMONS[str(demon_id)]
d_info = {
"start_add": d_start_add,
"name": demon_info,
"id": int(self.getHexStr(self.save_bytes, d_id_add, DE_ID[1], add_is_dec=True), 16),
"level": int(self.getHexStr(self.save_bytes, d_lvl_add, DE_LVL[1], add_is_dec=True), 16),
"exp": int(self.getHexStr(self.save_bytes, d_exp_add, DE_EXP[1], add_is_dec=True), 16),
"hp": int(self.getHexStr(self.save_bytes, d_hp_add, DE_HP[1], add_is_dec=True), 16),
"mp": int(self.getHexStr(self.save_bytes, d_mp_add, DE_MP[1], add_is_dec=True), 16),
"st": int(self.getHexStr(self.save_bytes, d_st_add, DE_ST[1], add_is_dec=True), 16),
"ma": int(self.getHexStr(self.save_bytes, d_ma_add, DE_MA[1], add_is_dec=True), 16),
"vi": int(self.getHexStr(self.save_bytes, d_vi_add, DE_VI[1], add_is_dec=True), 16),
"ag": int(self.getHexStr(self.save_bytes, d_ag_add, DE_AG[1], add_is_dec=True), 16),
"cmd1": int(self.getHexStr(self.save_bytes, d_cmd1_add, DE_CMD1[1], add_is_dec=True), 16),
"cmd2": int(self.getHexStr(self.save_bytes, d_cmd2_add, DE_CMD2[1], add_is_dec=True), 16),
"cmd3": int(self.getHexStr(self.save_bytes, d_cmd3_add, DE_CMD3[1], add_is_dec=True), 16),
"pas1": int(self.getHexStr(self.save_bytes, d_pas1_add, DE_PAS1[1], add_is_dec=True), 16),
"pas2": int(self.getHexStr(self.save_bytes, d_pas2_add, DE_PAS2[1], add_is_dec=True), 16),
"pas3": int(self.getHexStr(self.save_bytes, d_pas3_add, DE_PAS3[1], add_is_dec=True), 16),
"rac": int(self.getHexStr(self.save_bytes, d_rac_add, DE_RAC[1], add_is_dec=True), 16),
}
self.demonList.append(d_info)
self.demonNameList.append(demon_info)
print("Start Address: %x, Demon ID: %s." % (d_start_add, demon_id))
def changeTab(self, tab_to_show, tab_button):
if self.tabShown is tab_to_show:
return
self.tabShown.grid_remove()
tab_to_show.grid()
self.tabButton.config(state="normal", relief="raised")
tab_button.config(state="disabled", relief="sunken")
self.tabButton = tab_button
self.tabShown = tab_to_show
def writeHexBytes(self, byte_arr, hex_str, start_add, num_bytes, skip_bytes=None, add_is_dec=False):
hex_str = hex_str.zfill(num_bytes * 2)
hex_bytes = [hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]
hex_bytes.reverse()
if add_is_dec:
curr_add = start_add
else:
curr_add = int(start_add, 16)
if skip_bytes:
curr_add += skip_bytes
for val in hex_bytes:
# print("old: %d, new: %d" % (byte_arr[curr_add], int(val, 16)))
byte_arr[curr_add] = int(val, 16)
curr_add += 1
def getHexStr(self, byte_arr, start_add, num_bytes, skip_bytes=None, add_is_dec=False):
hex_str = ""
if add_is_dec:
curr_add = start_add
else:
curr_add = int(start_add, 16)
if skip_bytes:
curr_add += skip_bytes
while num_bytes > 0:
hex_str = format(byte_arr[curr_add], '02x') + hex_str
num_bytes -= 1
curr_add += 1
hex_str = hex_str.lstrip("0")
return hex_str if hex_str else "0"
# Menu Functions
def openFileChooser(self):
sel_file = filedialog.askopenfilenames(parent=self, initialdir=os.path.dirname(os.path.realpath(sys.argv[0])),
filetypes=(("Save files", "*.dat"), ("All files", "*.*")))
if sel_file:
sel_file = sel_file[0]
# print(sel_file)
if os.path.isfile(sel_file):
self.saveFilePathTxt.set(sel_file)
self.saveFilePath = sel_file
self.saveFileDir = os.path.dirname(sel_file)
self.saveFileName = os.path.basename(sel_file)
print(self.saveFileName)
self.processSaveFile()
self.createWidgets()
def saveCharChanges(self):
if self.save_bytes:
for char in self.charList:
# Level
tmp_val = format(int(char["level"]), "x")
c_lvl_write = char["start_add"] + int(CHAR_LVL[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_lvl_write, CHAR_LVL[1], add_is_dec=True)
# EXP
tmp_val = format(int(char["exp"]), "x")
c_exp_write = char["start_add"] + int(CHAR_EXP[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_exp_write, CHAR_EXP[1], add_is_dec=True)
# hp
tmp_val = format(int(char["hp"]), "x")
c_hp_write = char["start_add"] + int(CHAR_HP[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_hp_write, CHAR_HP[1], add_is_dec=True)
# MP
tmp_val = format(int(char["mp"]), "x")
c_mp_write = char["start_add"] + int(CHAR_MP[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_mp_write, CHAR_MP[1], add_is_dec=True)
# ST
tmp_val = format(int(char["st"]), "x")
c_st_write = char["start_add"] + int(CHAR_ST[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_st_write, CHAR_ST[1], add_is_dec=True)
# MA
tmp_val = format(int(char["ma"]), "x")
c_ma_write = char["start_add"] + int(CHAR_MA[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_ma_write, CHAR_MA[1], add_is_dec=True)
# VI
tmp_val = format(int(char["vi"]), "x")
c_vi_write = char["start_add"] + int(CHAR_VI[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_vi_write, CHAR_VI[1], add_is_dec=True)
# AG
tmp_val = format(int(char["ag"]), "x")
c_ag_write = char["start_add"] + int(CHAR_AG[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_ag_write, CHAR_AG[1], add_is_dec=True)
# CMD1
tmp_val = format(int(char["cmd1"]), "x")
c_cmd1_write = char["start_add"] + int(CHAR_CMD1[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_cmd1_write, CHAR_CMD1[1], add_is_dec=True)
# CMD2
tmp_val = format(int(char["cmd2"]), "x")
c_cmd2_write = char["start_add"] + int(CHAR_CMD2[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_cmd2_write, CHAR_CMD2[1], add_is_dec=True)
# CMD3
tmp_val = format(int(char["cmd3"]), "x")
c_cmd3_write = char["start_add"] + int(CHAR_CMD3[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_cmd3_write, CHAR_CMD3[1], add_is_dec=True)
# PAS1
tmp_val = format(int(char["pas1"]), "x")
c_pas1_write = char["start_add"] + int(CHAR_PAS1[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_pas1_write, CHAR_PAS1[1], add_is_dec=True)
# PAS2
tmp_val = format(int(char["pas2"]), "x")
c_pas2_write = char["start_add"] + int(CHAR_PAS2[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_pas2_write, CHAR_PAS2[1], add_is_dec=True)
# PAS3
tmp_val = format(int(char["pas3"]), "x")
c_pas3_write = char["start_add"] + int(CHAR_PAS3[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_pas3_write, CHAR_PAS3[1], add_is_dec=True)
# RAC
tmp_val = format(int(char["rac"]), "x")
c_rac_write = char["start_add"] + int(CHAR_RAC[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_rac_write, CHAR_RAC[1], add_is_dec=True)
# MOV
tmp_val = format(int(char["mov"]), "x")
c_mov_write = char["start_add"] + int(CHAR_MOV[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, c_mov_write, CHAR_MOV[1], add_is_dec=True)
return
def saveDemonChanges(self):
if self.save_bytes:
for demon in self.demonList:
# ID
tmp_val = format(int(demon["id"]), "x")
d_id_write = demon["start_add"] + int(DE_ID[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_id_write, DE_ID[1], add_is_dec=True)
# Level
tmp_val = format(int(demon["level"]), "x")
d_lvl_write = demon["start_add"] + int(DE_LVL[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_lvl_write, DE_LVL[1], add_is_dec=True)
# EXP
tmp_val = format(int(demon["exp"]), "x")
d_exp_write = demon["start_add"] + int(DE_EXP[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_exp_write, DE_EXP[1], add_is_dec=True)
# HP
tmp_val = format(int(demon["hp"]), "x")
d_hp_write = demon["start_add"] + int(DE_HP[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_hp_write, DE_HP[1], add_is_dec=True)
# MP
tmp_val = format(int(demon["mp"]), "x")
d_mp_write = demon["start_add"] + int(DE_MP[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_mp_write, DE_MP[1], add_is_dec=True)
# ST
tmp_val = format(int(demon["st"]), "x")
d_st_write = demon["start_add"] + int(DE_ST[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_st_write, DE_ST[1], add_is_dec=True)
# MA
tmp_val = format(int(demon["ma"]), "x")
d_ma_write = demon["start_add"] + int(DE_MA[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_ma_write, DE_MA[1], add_is_dec=True)
# VI
tmp_val = format(int(demon["vi"]), "x")
d_vi_write = demon["start_add"] + int(DE_VI[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_vi_write, DE_VI[1], add_is_dec=True)
# AG
tmp_val = format(int(demon["ag"]), "x")
d_ag_write = demon["start_add"] + int(DE_AG[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_ag_write, DE_AG[1], add_is_dec=True)
# CMD1
tmp_val = format(int(demon["cmd1"]), "x")
d_cmd1_write = demon["start_add"] + int(DE_CMD1[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_cmd1_write, DE_CMD1[1], add_is_dec=True)
# CMD2
tmp_val = format(int(demon["cmd2"]), "x")
d_cmd2_write = demon["start_add"] + int(DE_CMD2[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_cmd2_write, DE_CMD2[1], add_is_dec=True)
# CMD3
tmp_val = format(int(demon["cmd3"]), "x")
d_cmd3_write = demon["start_add"] + int(DE_CMD3[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_cmd3_write, DE_CMD3[1], add_is_dec=True)
# PAS1
tmp_val = format(int(demon["pas1"]), "x")
d_pas1_write = demon["start_add"] + int(DE_PAS1[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_pas1_write, DE_PAS1[1], add_is_dec=True)
# PAS2
tmp_val = format(int(demon["pas2"]), "x")
d_pas2_write = demon["start_add"] + int(DE_PAS2[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_pas2_write, DE_PAS2[1], add_is_dec=True)
# PAS3
tmp_val = format(int(demon["pas3"]), "x")
d_pas3_write = demon["start_add"] + int(DE_PAS3[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_pas3_write, DE_PAS3[1], add_is_dec=True)
# RAC
tmp_val = format(int(demon["rac"]), "x")
d_rac_write = demon["start_add"] + int(DE_RAC[0], 16)
self.writeHexBytes(self.save_bytes, tmp_val, d_rac_write, DE_RAC[1], add_is_dec=True)
return
def saveChanges(self):
if self.saveFilePath and os.path.isdir(self.saveFileDir):
self.saveCharChanges()
self.saveDemonChanges()
edited_dir = os.path.join(self.saveFileDir, "Edited")
if not os.path.isdir(edited_dir):
os.mkdir(edited_dir)
with open(os.path.join(edited_dir, self.saveFileName), 'wb') as fh:
fh.write(self.save_bytes)
def exitApp(self):
self.quit()
def aboutCreator(self):
tk.messagebox.showinfo("About This", "Made by XxArcaiCxX" +
"\n\nCredits to:" +
"\nwaynelimt (GitHub) - SMT IV Save Editor from which this Editor was adapted from")
def help(self):
tk.messagebox.showinfo("Help", "Just don't be stupid lol")
if __name__ == "__main__":
app = mytestapp(None)
app.mainloop()
| 38.255627 | 118 | 0.525867 | 41,800 | 0.585557 | 0 | 0 | 0 | 0 | 0 | 0 | 23,255 | 0.325769 |
a900d8dec7fd37ab4adca645a03f1689e7145bd6 | 6,692 | py | Python | tutorials/examples/interp_plot.py | ReynLieu/tf-pwa | f354b5036bc8c37ffba95849de5ec3367934eef8 | [
"MIT"
]
| 4 | 2021-05-10T15:17:24.000Z | 2021-08-16T07:40:06.000Z | tutorials/examples/interp_plot.py | ReynLieu/tf-pwa | f354b5036bc8c37ffba95849de5ec3367934eef8 | [
"MIT"
]
| 45 | 2020-10-24T08:26:19.000Z | 2022-03-20T06:14:58.000Z | tutorials/examples/interp_plot.py | ReynLieu/tf-pwa | f354b5036bc8c37ffba95849de5ec3367934eef8 | [
"MIT"
]
| 8 | 2020-10-24T06:41:06.000Z | 2022-01-03T01:29:49.000Z | import json
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
import yaml
from mpl_toolkits.mplot3d.axes3d import Axes3D
from scipy.interpolate import interp1d
from tf_pwa.config_loader import ConfigLoader
from tf_pwa.experimental.extra_amp import spline_matrix
# import mplhep
# plt.style.use(mplhep.style.LHCb)
def vialid_name(s):
return s.replace("+", ".")
def polar_err(r, phi, r_e, phi_e):
"""polar errors for r and phi"""
# print(r, phi, r_e, phi_e)
dxdr = np.cos(phi)
dxdphi = r * np.sin(phi)
dydr = np.sin(phi)
dydphi = -r * np.cos(phi)
x_e = np.sqrt((dxdr * r_e) ** 2 + (dxdphi * phi_e) ** 2)
y_e = np.sqrt((dydr * r_e) ** 2 + (dydphi * phi_e) ** 2)
# print(x_e, y_e)
return x_e, y_e
def dalitz_weight(s12, m0, m1, m2, m3):
"""phase space weight in dalitz plot"""
m12 = np.sqrt(s12)
m12 = np.where(m12 > (m1 + m2), m12, m1 + m2)
m12 = np.where(m12 < (m0 - m3), m12, m0 - m3)
# if(mz < (m_d+m_pi)) return 0;
# if(mz > (m_b-m_pi)) return 0;
E2st = 0.5 * (m12 * m12 - m1 * m1 + m2 * m2) / m12
E3st = 0.5 * (m0 * m0 - m12 * m12 - m3 * m3) / m12
p2st2 = E2st * E2st - m2 * m2
p3st2 = E3st * E3st - m3 * m3
p2st = np.sqrt(np.where(p2st2 > 0, p2st2, 0))
p3st = np.sqrt(np.where(p3st2 > 0, p3st2, 0))
return p2st * p3st
def load_params(
config_file="config.yml", params="final_params.json", res="li(1+)S"
):
with open(params) as f:
final_params = json.load(f)
val = final_params["value"]
err = final_params["error"]
with open(config_file) as f:
config = yaml.safe_load(f)
xi = config["particle"][res].get("points", None)
if xi is None:
m_max = config["particle"][res].get("m_max", None)
m_min = config["particle"][res].get("m_min", None)
N = config["particle"][res].get("interp_N", None)
dx = (m_max - m_min) / (N - 1)
xi = [m_min + dx * i for i in range(N)]
N = len(xi)
head = "{}_point".format(vialid_name(res))
r = np.array(
[0] + [val["{}_{}r".format(head, i)] for i in range(N - 2)] + [0]
)
phi = np.array(
[0] + [val["{}_{}i".format(head, i)] for i in range(N - 2)] + [0]
)
r_e = np.array(
[0, 0]
+ [
err.get("{}_{}r".format(head, i), r[i] * 0.1)
for i in range(1, N - 2)
]
+ [0]
)
phi_e = np.array(
[0, 0]
+ [
err.get("{}_{}i".format(head, i), phi[i] * 0.1)
for i in range(1, N - 2)
]
+ [0]
)
return np.array(xi), r, phi, r_e, phi_e
def trans_r2xy(r, phi, r_e, phi_e):
"""r,phi -> x,y """
x = np.array(r) * np.cos(phi)
y = np.array(r) * np.sin(phi)
err = np.array(
[polar_err(i, j, k, l) for i, j, k, l in zip(r, phi, r_e, phi_e)]
)
return x, y, err[:, 0], err[:, 1]
def plot_x_y(name, x, y, x_i, y_i, xlabel, ylabel, ylim=(None, None)):
"""plot x vs y"""
plt.clf()
plt.plot(x, y)
plt.scatter(x_i, y_i)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.ylim(ylim)
plt.savefig(name)
def plot_phi(name, m, phi, m_i, phi_i):
""" plot phi and gradient of phi"""
grad = phi[2:] - phi[:-2]
mask = (phi < 3) & (phi > -3)
grad_max = np.mean(np.abs(grad))
# grad_max = np.max(grad[mask[1:-1]])
(idx,) = signal.argrelextrema(grad, np.less)
plt.clf()
# plt.plot(m, pq/np.max(pq))# np.sqrt(x_new**2+y_new**2)**2)
plt.plot(m[1:-1], grad / grad_max, label="$\\Delta \\phi$ ")
plt.plot(m, phi, label="$\\phi$") # np.sqrt(x_new**2+y_new**2)**2)
m_delta = m[idx + 1]
print("min Delta phi in mass:", m_delta)
plt.scatter(m_delta, [-np.pi] * len(m_delta))
plt.scatter(m_i, phi_i, label="points")
plt.xlabel("mass")
plt.ylabel("$\\phi$")
plt.ylim((-np.pi, np.pi))
plt.legend()
plt.savefig(name)
def plot_x_y_err(name, x, y, x_e, y_e):
"""plot eror bar of x y"""
plt.clf()
plt.errorbar(x, y, xerr=x_e, yerr=y_e)
plt.xlabel("real R(m)")
plt.ylabel("imag R(m)")
plt.savefig(name)
def plot3d_m_x_y(name, m, x, y):
fig = plt.figure()
axes3d = Axes3D(fig)
axes3d.plot(m, x, y)
axes3d.set_xlabel("m")
axes3d.set_ylabel("real R(m)")
axes3d.set_zlabel("imag R(m)")
def update(frame):
axes3d.view_init(elev=30, azim=frame)
return None
anim = animation.FuncAnimation(
fig, update, interval=10, frames=range(0, 360, 10)
)
anim.save(name, writer="imagemagick")
def plot_all(
res="MI(1+)S",
config_file="config.yml",
params="final_params.json",
prefix="figure/",
):
"""plot all figure"""
config = ConfigLoader(config_file)
config.set_params(params)
particle = config.get_decay().get_particle(res)
mi, r, phi_i, r_e, phi_e = load_params(config_file, params, res)
x, y, x_e, y_e = trans_r2xy(r, phi_i, r_e, phi_e)
m = np.linspace(mi[0], mi[-1], 1000)
M_Kpm = 0.49368
M_Dpm = 1.86961
M_Dstar0 = 2.00685
M_Bpm = 5.27926
# x_new = interp1d(xi, x, "cubic")(m)
# y_new = interp1d(xi, y, "cubic")(m)
rm_new = particle.interp(m).numpy()
x_new, y_new = rm_new.real, rm_new.imag
pq = dalitz_weight(m * m, M_Bpm, M_Dstar0, M_Dpm, M_Kpm)
pq_i = dalitz_weight(mi * mi, M_Bpm, M_Dstar0, M_Dpm, M_Kpm)
phi = np.arctan2(y_new, x_new)
r2 = x_new * x_new + y_new * y_new
plot_phi(f"{prefix}phi.png", m, phi, mi, np.arctan2(y, x))
plot_x_y(
f"{prefix}r2.png",
m,
r2,
mi,
r * r,
"mass",
"$|R(m)|^2$",
ylim=(0, None),
)
plot_x_y(f"{prefix}x_y.png", x_new, y_new, x, y, "real R(m)", "imag R(m)")
plot_x_y_err(
f"{prefix}x_y_err.png", x[1:-1], y[1:-1], x_e[1:-1], y_e[1:-1]
)
plot_x_y(
f"{prefix}r2_pq.png",
m,
r2 * pq,
mi,
r * r * pq_i,
"mass",
"$|R(m)|^2 p \cdot q$",
ylim=(0, None),
)
plot3d_m_x_y(f"{prefix}m_r.gif", m, x_new, y_new)
def main():
import argparse
parser = argparse.ArgumentParser(description="plot interpolation")
parser.add_argument("particle", type=str)
parser.add_argument("-c", "--config", default="config.yml", dest="config")
parser.add_argument(
"-i", "--params", default="final_params.json", dest="params"
)
parser.add_argument("-p", "--prefix", default="figure/", dest="prefix")
results = parser.parse_args()
plot_all(results.particle, results.config, results.params, results.prefix)
if __name__ == "__main__":
main()
| 27.539095 | 78 | 0.558876 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,231 | 0.183951 |
a902196e210ce0c9d3fc255989473f3fdb1ab785 | 3,316 | py | Python | scripts/val_step_images_pull.py | neuroailab/curiosity_deprecated | 65f7cde13b07cdac52eed39535a94e7544c396b8 | [
"Apache-2.0"
]
| null | null | null | scripts/val_step_images_pull.py | neuroailab/curiosity_deprecated | 65f7cde13b07cdac52eed39535a94e7544c396b8 | [
"Apache-2.0"
]
| 2 | 2017-11-18T00:53:33.000Z | 2017-11-18T00:53:40.000Z | scripts/val_step_images_pull.py | neuroailab/curiosity_deprecated | 65f7cde13b07cdac52eed39535a94e7544c396b8 | [
"Apache-2.0"
]
| null | null | null | '''
A script for accessing visualization data (saving images at validation steps during training) and saving them to a local directory.
'''
import pymongo as pm
import pickle
import os
import gridfs
import cPickle
import numpy as np
from PIL import Image
dbname = 'future_pred_test'
collname = 'asymmetric'
port = 27017
exp_id = '3_3'
save_loc = '/home/nhaber/really_temp'
save_fn = os.path.join(save_loc, exp_id + '.p')
target_name = 'valid0'
one_channel_softmax = True
conn = pm.MongoClient(port = 27017)
coll = conn[dbname][collname + '.files']
print('experiments')
print(coll.distinct('exp_id'))
cur = coll.find({'exp_id' : exp_id})
q = {'exp_id' : exp_id, 'validation_results' : {'$exists' : True}}
val_steps = coll.find(q)
val_count = val_steps.count()
print('num val steps so far')
print(val_count)
saved_data = {}
def convert_to_viz(np_arr):
'''I did a silly thing and saved discretized-loss predictions as if they were image predictions.
This recovers and converts to an ok visualization.'''
my_shape = np_arr.shape
num_classes = np_arr.shape[-1]
#I fixed things so that it saves the prediction not converted to 255
if np_arr.dtype == 'float32':
exp_arr = np.exp(np_arr)
else:
exp_arr = np.exp(np_arr.astype('float32') / 255.)
sum_arr = np.sum(exp_arr, axis = -1)
#hack for broadcasting...I don't know broadcasting
softy = (exp_arr.T / sum_arr.T).T
return np.sum((softy * range(num_classes) * 255. / float(num_classes)), axis = -1).astype('uint8')
def convert_to_viz_sharp(np_arr):
'''Similar to the above, but just taking the argmax, hopefully giving a sharper visualization.
'''
num_classes = np_arr.shape[-1]
a_m = np.argmax(np_arr, axis = -1)
return (a_m * 255. / float(num_classes)).astype('uint8')
def sigmoid_it(np_arr):
sigm = 1. / (1. + np.exp( - np_arr))
return (255 * sigm).astype('uint8')
for val_num in range(val_count):
idx = val_steps[val_num]['_id']
fn = coll.find({'item_for' : idx})[0]['filename']
fs = gridfs.GridFS(coll.database, collname)
fh = fs.get_last_version(fn)
saved_data[val_num] = cPickle.loads(fh.read())['validation_results']
fh.close()
exp_dir = os.path.join(save_loc, exp_id)
if not os.path.exists(exp_dir):
os.mkdir(exp_dir)
for val_num, val_data in saved_data.iteritems():
val_dir = os.path.join(exp_dir, 'val_' + str(val_num))
if not os.path.exists(val_dir):
os.mkdir(val_dir)
for tgt_desc, tgt in val_data[target_name].iteritems():
tgt_images = [arr for step_results in tgt for arr in step_results]
for (instance_num, arr) in enumerate(tgt_images):
instance_dir = os.path.join(val_dir, 'instance_' + str(instance_num))
if not os.path.exists(instance_dir):
os.mkdir(instance_dir)
if len(arr.shape) == 4:
fn = os.path.join(instance_dir, tgt_desc + '_' + str(instance_num) + '.jpeg')
arr = convert_to_viz_sharp(arr)
im = Image.fromarray(arr)
im.save(fn)
#just save in human-readable form if 1-array
elif len(arr.shape) == 1:
fn = os.path.join(instance_dir, tgt_desc + '_' + str(instance_num) + '.txt')
np.savetxt(fn, arr)
else:
assert len(arr.shape) == 3
fn = os.path.join(instance_dir, tgt_desc + '_' + str(instance_num) + '.jpeg')
if one_channel_softmax and 'pred' in tgt_desc:
arr = sigmoid_it(arr)
im = Image.fromarray(arr)
im.save(fn)
| 29.607143 | 131 | 0.701448 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 858 | 0.258745 |
a9039f8421d00114c0ba14dfaca35466584a7fcb | 1,543 | py | Python | server/main_node/create_tables.py | noderod/DARLMID | 5737dbe222ce5a5a847c1d0a8d1af64dda87e5b2 | [
"MIT"
]
| null | null | null | server/main_node/create_tables.py | noderod/DARLMID | 5737dbe222ce5a5a847c1d0a8d1af64dda87e5b2 | [
"MIT"
]
| null | null | null | server/main_node/create_tables.py | noderod/DARLMID | 5737dbe222ce5a5a847c1d0a8d1af64dda87e5b2 | [
"MIT"
]
| null | null | null | """
BASICS
Creates the necessary tables and users.
"""
import os
import psycopg2
con = psycopg2.connect (host = os.environ["POSTGRES_URL"], database = os.environ["POSTGRES_DB"], user = os.environ["POSTGRES_USER"], password = os.environ["POSTGRES_PASSWORD"])
cur = con.cursor()
# Creates main user table
cur.execute("""
CREATE TABLE IF NOT EXISTS user_data (
user_id serial PRIMARY KEY,
username VARCHAR (256) UNIQUE NOT NULL,
password VARCHAR (256) NOT NULL,
salt VARCHAR (256) NOT NULL,
date_creation TIMESTAMP NOT NULL,
last_action TIMESTAMP NOT NULL,
last_login TIMESTAMP NOT NULL,
last_logout TIMESTAMP NOT NULL
)""")
# Creates a read only user (SELECT)
# Query is done in an unsafe way because it is the only way, sanitizing it will cause issues
# No user input
read_only_postgres_user = os.environ["R_USERNAME"]
cur.execute("CREATE USER "+ read_only_postgres_user + " WITH ENCRYPTED PASSWORD %s", (os.environ["R_PASSWORD"],))
cur.execute("GRANT SELECT ON ALL TABLES IN SCHEMA public TO " + read_only_postgres_user)
# Creates a write user (SELECT, INSERT, UPDATE)
write_postgres_user = os.environ["RW_USERNAME"]
cur.execute("CREATE USER "+ write_postgres_user + " WITH ENCRYPTED PASSWORD %s", (os.environ["RW_PASSWORD"],))
cur.execute("GRANT SELECT, INSERT, DELETE, UPDATE ON ALL TABLES IN SCHEMA public TO " + write_postgres_user)
cur.execute("GRANT SELECT, USAGE ON ALL SEQUENCES IN SCHEMA public TO " + write_postgres_user)
con.commit()
con.close ()
| 32.829787 | 176 | 0.720674 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,024 | 0.663642 |
a90540d0d0a5a9bc45b650e47d3f81668b272c4b | 338 | py | Python | test from collections import defaultdict.py | meeve602/nn-network | 2bc422785b8d7e5fa78d73a218f5ed8d499902e7 | [
"Apache-2.0"
]
| null | null | null | test from collections import defaultdict.py | meeve602/nn-network | 2bc422785b8d7e5fa78d73a218f5ed8d499902e7 | [
"Apache-2.0"
]
| null | null | null | test from collections import defaultdict.py | meeve602/nn-network | 2bc422785b8d7e5fa78d73a218f5ed8d499902e7 | [
"Apache-2.0"
]
| null | null | null | from collections import defaultdict
computing_graph = defaultdict(list)#defaultdict(list),会构建一个默认value为list的字典,
"""
for (key, value) in data:
result[key].append(value)
print(result)#defaultdict(<class 'list'>, {'p': [1, 2, 3], 'h': [1, 2, 3]})
"""
n = 'p'
m = [1,2,23]
computing_graph[n].append(m)
print(computing_graph)
| 26 | 76 | 0.659763 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 211 | 0.582873 |
a905bc7c157d96b2e4f0eee9148f0267c5d741fe | 597 | py | Python | examples/web-scraper/playground.py | relikd/botlib | d0c5072d27db1aa3fad432457c90c9e3f23f22cc | [
"MIT"
]
| null | null | null | examples/web-scraper/playground.py | relikd/botlib | d0c5072d27db1aa3fad432457c90c9e3f23f22cc | [
"MIT"
]
| null | null | null | examples/web-scraper/playground.py | relikd/botlib | d0c5072d27db1aa3fad432457c90c9e3f23f22cc | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
from botlib.curl import Curl
from botlib.html2list import HTML2List, MatchGroup
URL = 'https://www.vice.com/en/topic/motherboard'
SOURCE = Curl.get(URL, cache_only=True)
SELECT = '.vice-card__content'
match = MatchGroup({
'url': r'<a href="([^"]*)"',
'title': r'<h3[^>]*><a [^>]*>([\s\S]*?)</a>[\s\S]*?</h3>',
'desc': r'<p[^>]*>([\s\S]*?)</p>',
'wrong-regex': r'<a xref="([\s\S]*?)"',
})
for elem in reversed(HTML2List(SELECT).parse(SOURCE)):
match.set_html(elem)
for k, v in match.to_dict().items():
print(k, '=', v)
print()
break
| 28.428571 | 62 | 0.571189 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 236 | 0.39531 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.