blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 288 | content_id stringlengths 40 40 | detected_licenses listlengths 0 112 | license_type stringclasses 2 values | repo_name stringlengths 5 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 684 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 147 values | src_encoding stringclasses 25 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 128 12.7k | extension stringclasses 142 values | content stringlengths 128 8.19k | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
377290350c8709f3863a64ab8d860ca274944ee4 | 1d0bb94bc33b80b96f47f4b8ff204a6711af7eac | /app.py | 8c33fb7173b9c81cd464c8d6782ef69326458ad7 | [] | no_license | mfwarren/kpi | 9ff78de66b240ea41b1b560ea00ef76d1b6a681d | 239272e06b616873413f4942424c28dc8e7fd4b3 | refs/heads/master | 2016-09-05T18:58:57.040531 | 2015-05-08T13:37:27 | 2015-05-08T13:37:27 | 34,973,160 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,553 | py | #!/usr/bin/env python
from gevent import monkey
monkey.patch_all()
import time
import os
import datetime
import pytz
from threading import Thread
import dateutil.parser
from refreshbooks import api as freshbooks_api
from github import Github
import requests
from flask import Flask, render_template
from flask.ext.socketio import SocketIO
TIMEZONE = pytz.timezone('America/Edmonton')
app = Flask(__name__)
app.config['SECRET_KEY'] = 'n7xw34tydr897123gj9s34r76t'
socketio =SocketIO(app)
thread = None
hub = Github(os.environ['GITHUB_USERNAME'], os.environ['GITHUB_PASSWORD'])
freshbooks = freshbooks_api.TokenClient(
os.environ['FRESHBOOKS_DOMAIN'],
os.environ['FRESHBOOKS_API_TOKEN'],
user_agent='KPIDashboard/1.0'
)
def check_commit(commit_url, timeseries):
"""
Get information about a particualr commit
"""
r = requests.get(commit_url)
data = r.json()
print(commit_url)
print(data)
date = dateutil.parser.parse(data['commit']['committer']['date']).date()
stats = data['stats']
timeseries[date.isoformat()].append(stats)
def process_push_event(event, timeseries):
for commit in event.payload['commits']:
# check_commit(commit['url'], timeseries)
local_date = event.created_at.replace(tzinfo=pytz.utc).astimezone(TIMEZONE).date()
timeseries[local_date.isoformat()] += 1
def process_issues_event(event, timeseries):
# need to convert created_at from UTC to MST
local_date = event.created_at.replace(tzinfo=pytz.utc).astimezone(TIMEZONE).date()
timeseries[local_date.isoformat()] += 1
def recent_issues():
date_array = [datetime.date.today() + datetime.timedelta(days=-i) for i in range(7)]
timeseries = {d.isoformat(): 0 for d in date_array}
user = hub.get_user('mfwarren')
events = user.get_events()
for event in events:
try:
if event.type == 'IssuesEvent':
process_issues_event(event, timeseries)
except:
break
return sum(timeseries.values())
def recent_commits():
date_array = [datetime.date.today() + datetime.timedelta(days=-i) for i in range(7)]
timeseries = {d.isoformat(): 0 for d in date_array}
user = hub.get_user('mfwarren')
events = user.get_events()
for event in events:
try:
if event.type == 'PushEvent':
process_push_event(event, timeseries)
except:
break
return timeseries[datetime.date.today().isoformat()], sum(timeseries.values())
def background_thread():
while True:
issues = 0
commits_today = 0
commits_this_week = 0
client_count = 0
try:
issues = recent_issues()
commits_today, commits_this_week = recent_commits()
except Exception as ex:
print("Github crashed")
try:
client_count = freshbooks.client.list().clients.attrib['total']
except:
print("freshbooks crashed")
socketio.emit('response', {'issues': issues,
'commits': commits_this_week,
'commits_today': commits_today,
'critical_number': client_count}, namespace='')
time.sleep(60*30) # 30 minutes
@app.route('/')
def index():
global thread
if thread is None:
thread = Thread(target=background_thread)
thread.start()
return render_template('index.html')
@socketio.on('event')
def message(message):
pass
if __name__ == '__main__':
socketio.run(app)
| [
"matt.warren@gmail.com"
] | matt.warren@gmail.com |
11de6c893af7b3b2e87c793fc57f5b71eeb79bf3 | 65bf0113da75390c4cf3960b6a409aca15569a06 | /orders/models.py | ba438c4bcc8db09fb277ffc7b398d222c68cb9a4 | [] | no_license | wenpengfan/opsadmin | e7701538265253653adb1c8ce490e0ce71d3b4f6 | 3d997259353dc2734ad153c137a91f3530e0a8ec | refs/heads/master | 2023-03-29T11:50:10.756596 | 2020-11-16T02:41:18 | 2020-11-16T02:41:18 | 313,171,594 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,142 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from appconf.models import Database, Project, AppOwner
# Create your models here.
class Require(models.Model):
title = models.CharField(max_length=255, verbose_name=u"标题", null=True, blank=False)
description = models.CharField(max_length=5000, verbose_name=u"需求描述", null=True, blank=True)
status = models.BooleanField(verbose_name=u"部署状态", default=False)
create_time = models.DateTimeField(verbose_name=u"创建时间", auto_now_add=True)
operating_time = models.DateTimeField(verbose_name=u"预约操作时间", null=True, blank=False)
update_time = models.DateTimeField(verbose_name=u"更新时间", auto_now=True)
order_user = models.CharField(max_length=255, verbose_name=u"提交用户", null=True, blank=True)
owner = models.ForeignKey(AppOwner, verbose_name=u"负责人", on_delete=models.deletion.SET_NULL, null=True, blank=False)
completion_time = models.DateTimeField(verbose_name=u"完成时间", null=True, blank=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['-completion_time','operating_time']
class DBScript(models.Model):
db_name = models.ForeignKey(Database, verbose_name=u"数据库", on_delete=models.deletion.SET_NULL, null=True, blank=False)
description = models.CharField(max_length=5000, verbose_name=u"更新描述", null=True, blank=True)
script_name = models.CharField(max_length=255, verbose_name=u"脚本名称", null=True, blank=False)
status = models.BooleanField(verbose_name=u"部署状态", default=False)
create_time = models.DateTimeField(verbose_name=u"创建时间", auto_now_add=True)
operating_time = models.DateTimeField(verbose_name=u"预约操作时间", null=True, blank=False)
update_time = models.DateTimeField(verbose_name=u"更新时间", auto_now=True)
order_user = models.CharField(max_length=255, verbose_name=u"提交用户", null=True, blank=True)
env = models.CharField(max_length=10, verbose_name=u"环境", null=True, blank=False)
completion_time = models.DateTimeField(verbose_name=u"完成时间", null=True, blank=True)
def __unicode__(self):
return self.script_name
class Meta:
ordering = ['-completion_time','operating_time']
class Deploy(models.Model):
app_name = models.ForeignKey(Project, verbose_name=u"应用名称", on_delete=models.deletion.SET_NULL, null=True, blank=False)
description = models.CharField(max_length=5000, verbose_name=u"更新描述", null=True, blank=False)
version = models.CharField(max_length=255, verbose_name=u"程序版本号", blank=False,unique=True)
conf_version = models.ForeignKey('Config',to_field="conf_version", verbose_name=u"配置版本号",
on_delete=models.deletion.SET_NULL, null=True, blank=True)
status = models.BooleanField(verbose_name=u"部署状态", default=False)
create_time = models.DateTimeField(verbose_name=u"创建时间", auto_now_add=True)
operating_time = models.DateTimeField(verbose_name=u"预约操作时间", null=True, blank=False)
update_time = models.DateTimeField(verbose_name=u"更新时间", auto_now=True)
order_user = models.CharField(max_length=255, verbose_name=u"提交用户", null=True, blank=True)
order_status = models.BooleanField(verbose_name=u"工单状态", default=False)
dbscript = models.ForeignKey(DBScript, verbose_name=u"数据库工单", on_delete=models.deletion.SET_NULL, null=True, blank=True)
is_new = models.BooleanField(verbose_name=u"是否新应用", default=False)
is_tested = models.IntegerField(u"是否测试通过,0:未确定,1:测试通过,2:测试未通过", default=0, null=True, blank=False)
completion_time = models.DateTimeField(verbose_name=u"完成时间", null=True, blank=True)
def __unicode__(self):
return self.version
class Meta:
unique_together = ('app_name', 'version',)
ordering = ['-completion_time','operating_time']
class Config(models.Model):
app_name = models.ForeignKey(Project, verbose_name=u"应用名称",on_delete=models.deletion.SET_NULL, null=True, blank=False)
env = models.CharField(max_length=255, verbose_name=u"环境", null=True, blank=False)
description = models.CharField(max_length=5000, verbose_name=u"更新描述", null=True, blank=False)
conf_version = models.CharField(max_length=255, verbose_name=u"配置版本号", blank=False,unique=True)
app_version = models.ForeignKey('Deploy',to_field="version", verbose_name=u"程序版本号",
on_delete=models.deletion.SET_NULL, null=True, blank=True)
status = models.BooleanField(verbose_name=u"部署状态", default=False)
create_time = models.DateTimeField(verbose_name=u"创建时间", auto_now_add=True)
operating_time = models.DateTimeField(verbose_name=u"预约操作时间", null=True, blank=False)
update_time = models.DateTimeField(verbose_name=u"更新时间", auto_now=True)
order_user = models.CharField(max_length=255, verbose_name=u"提交用户", null=True, blank=True)
order_status = models.BooleanField(verbose_name=u"工单状态", default=False)
completion_time = models.DateTimeField(verbose_name=u"完成时间", null=True, blank=True)
def __unicode__(self):
return self.conf_version
class Meta:
unique_together = ('app_name', 'conf_version','app_version')
ordering = ['-completion_time','operating_time']
class Document(models.Model):
doc_id = models.IntegerField(u"文档编号", default=0)
name = models.CharField(u"应用名称", max_length=50, default=None, null=False, blank=False)
description = models.CharField(u"应用描述", max_length=5000, null=True, blank=True)
current_ver = models.CharField(u"当前版本", max_length=255, null=True, blank=True)
next_ver = models.CharField(u"后续版本", max_length=255, null=True, blank=True)
language_type = models.CharField(u"语言类型", max_length=30, null=True, blank=False)
app_type = models.CharField(u"程序类型", max_length=30, null=True, blank=False)
app_arch = models.CharField(u"程序框架", max_length=30, null=True, blank=True)
code_address = models.CharField(u"代码库地址", max_length=255, null=True, blank=False)
start_cmd = models.CharField(u"启动命令", max_length=255, null=True, blank=True)
stop_cmd = models.CharField(u"停止命令", max_length=255, null=True, blank=True)
config_detail = models.TextField(u"配置文件说明", max_length=1000, null=True, blank=True)
docker_expose = models.TextField(u"Docker容器说明", max_length=1000, null=True, blank=True)
app_monitor = models.CharField(u"需要的业务监控项", max_length=255, null=True, blank=True)
need_ha = models.CharField(u"高可用说明", default="无需高可用", max_length=30, null=False, blank=False)
need_dn = models.CharField(u"需要新增域名", max_length=255, null=True, blank=True)
need_location = models.CharField(u"需要新增二级目录", max_length=255, null=True, blank=True)
uri_mapping_from = models.CharField(u"URI映射来源", max_length=255, null=True, blank=True)
uri_mapping_to = models.CharField(u"URI映射目标", max_length=255, null=True, blank=True)
need_wan = models.CharField(u"是否需要访问外网", default="否", max_length=2, null=False, blank=False)
requester = models.CharField(u"调用方", max_length=255, null=True, blank=True)
rely_on = models.TextField(u"应用依赖的其他需求", max_length=255, null=True, blank=True)
product_id = models.IntegerField(u"所属产品线", default=0, null=True, blank=True)
dev_id = models.IntegerField(u"开发负责人", default=0, null=True, blank=True)
ops_id = models.IntegerField(u"运维负责人", default=0, null=True, blank=True)
def __unicode__(self):
return self.name
class Meta:
unique_together = ('doc_id', 'current_ver',)
| [
"you@example.com"
] | you@example.com |
46f246599c2d98d4fc3accaaaca6b5bb5e65db56 | 957187f350bc0f74ccb99d7b652ee705dd746cea | /app_botiquin/migrations/0002_auto_20150801_2326.py | 4a62f821016102d781b46c7ab7589d090b015d47 | [] | no_license | dbsiavichay/botiquinmagap | 8188aa9905300c96ca94c2bc658f58141ea38aef | 5cc0eda2e89fae90ce6ab7217141b53919aed5b4 | refs/heads/master | 2021-01-01T18:48:32.406184 | 2015-08-04T23:46:48 | 2015-08-04T23:46:48 | 32,053,265 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 968 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('app_botiquin', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='grupoproducto',
options={'verbose_name': 'grupo de producto', 'verbose_name_plural': 'grupos de producto'},
),
migrations.AlterModelOptions(
name='medidaproducto',
options={'verbose_name': 'medida de producto', 'verbose_name_plural': 'medidas de producto'},
),
migrations.AlterModelOptions(
name='producto',
options={'verbose_name': 'producto', 'verbose_name_plural': 'productos'},
),
migrations.AlterModelOptions(
name='tipoproducto',
options={'verbose_name': 'tipo de producto', 'verbose_name_plural': 'tipos de producto'},
),
]
| [
"dbsiavichay@gmail.com"
] | dbsiavichay@gmail.com |
42ba1e3c015f20441c374256ce07cf703eadaaad | 9814fc360414ed900573181485966f63a56b261d | /setup.py | 965ede863e91d9a8138bf2f09c34795175da88de | [
"MIT"
] | permissive | krallin/captain-comeback | 7d38425ec8f3b51626418f6dc6a6abfa8fa7cda3 | e02e3774eab62d7b8ba454331a785e2ae32c89fc | refs/heads/master | 2023-09-03T19:52:22.155417 | 2016-07-07T14:42:34 | 2016-07-07T16:17:02 | 62,813,918 | 0 | 1 | null | 2016-07-07T14:37:49 | 2016-07-07T14:37:48 | null | UTF-8 | Python | false | false | 1,668 | py | #!/usr/bin/env python
# coding: utf-8
import os
from setuptools import setup
HERE = os.path.dirname(__file__)
with open(os.path.join(HERE, 'README.md')) as readme_file:
readme = readme_file.read()
with open(os.path.join(HERE, 'CHANGELOG.md')) as history_file:
changelog = history_file.read()
requirements = ["linuxfd>=1.0,<2", "psutil>=4.3,<5", "six>=1.0,<2"]
test_requirements = []
setup(
name='captain_comeback',
version='0.1.0',
description="Userland container OOM manager.",
long_description=readme + '\n\n' + changelog,
author="Thomas Orozco",
author_email='thomas@aptible.com',
url='https://github.com/krallin/captain_comeback',
packages=[
'captain_comeback',
'captain_comeback.restart',
'captain_comeback.test'
],
include_package_data=True,
install_requires=requirements,
license="MIT license",
zip_safe=False,
keywords='captain_comeback',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='captain_comeback.test',
tests_require=test_requirements,
entry_points={'console_scripts': [
'captain-comeback = captain_comeback.cli:cli_entrypoint']}
)
| [
"thomas@orozco.fr"
] | thomas@orozco.fr |
b597e2e13e7f65f2a8bed1b72a651e20fdcb6a35 | 81407be1385564308db7193634a2bb050b4f822e | /testdemo/pytestdemo/ssh-copy-id.py | d8024561b2c7733acd24f0b2f173d39c8f5e8a1c | [
"MIT"
] | permissive | gottaegbert/penter | 6db4f7d82c143af1209b4259ba32145aba7d6bd3 | 8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d | refs/heads/master | 2022-12-30T14:51:45.132819 | 2020-10-09T05:33:23 | 2020-10-09T05:33:23 | 305,266,398 | 0 | 0 | MIT | 2020-10-19T04:56:02 | 2020-10-19T04:53:05 | null | UTF-8 | Python | false | false | 1,620 | py | """ssh-copy-id for Windows.
Example usage: python ssh-copy-id.py ceilfors@my-remote-machine
This script is dependent on msysgit by default as it requires scp and ssh.
For convenience you can also try that comes http://bliker.github.io/cmder/.
"""
# python ssh-copy-id.py root@xx.xx.xx.xx
import argparse, os
from subprocess import call
def winToPosix(win):
"""Converts the specified windows path as a POSIX path in msysgit.
Example:
win: C:\\home\\user
posix: /c/home/user
"""
posix = win.replace('\\', '/')
return "/" + posix.replace(':', '', 1)
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--identity_file", help="identity file, default to ~\\.ssh\\idrsa.pub", default=os.environ['HOME']+"\\.ssh\\id_rsa.pub")
parser.add_argument("-d", "--dry", help="run in the dry run mode and display the running commands.", action="store_true")
parser.add_argument("remote", metavar="user@machine")
args = parser.parse_args()
local_key = winToPosix(args.identity_file)
remote_key = "~/temp_id_rsa.pub"
# Copy the public key over to the remote temporarily
scp_command = "scp {} {}:{}".format(local_key, args.remote, remote_key)
print(scp_command)
if not args.dry:
call(scp_command)
# Append the temporary copied public key to authorized_key file and then remove the temporary public key
ssh_command = ("ssh {} "
"mkdir ~/.ssh;"
"touch ~/.ssh/authorized_keys;"
"cat {} >> ~/.ssh/authorized_keys;"
"rm {};").format(args.remote, remote_key, remote_key)
print(ssh_command)
if not args.dry:
call(ssh_command) | [
"350840291@qq.com"
] | 350840291@qq.com |
ad092d278eb7c28c208e8cd80fb0a6b2851e33a9 | 746e0181955176741385091fe795e360a5f8fa3f | /yushubook/app/web/auth.py | 98a647abd4d89c6f9643a1d3edea07eb8d377e93 | [] | no_license | zhengpanone/flask_web | c26547483219011d9f1051d383f0d9a0a72d48df | 87d324ffee503aaa794c415ba6e16785dbf84d99 | refs/heads/master | 2022-07-22T09:07:47.939938 | 2019-12-18T07:14:21 | 2019-12-18T07:14:21 | 206,232,120 | 0 | 0 | null | 2022-06-28T14:44:55 | 2019-09-04T04:35:50 | JavaScript | UTF-8 | Python | false | false | 2,718 | py | from flask import render_template, request, redirect, url_for, flash
from flask_login import login_user, logout_user
from app.forms.auth import RegisterForm, LoginForm, EmailForm, ResetPasswordForm
from app.models.base import db
from app.models.user import User
from . import web
__author__ = 'zhengpanone'
@web.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
with db.auto_commit():
user = User()
user.set_attrs(form.data)
db.session.add(user)
# db.session.commit()
return redirect(url_for('web.login'))
return render_template('auth/register.html', form=form)
@web.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
user = User.query.filter_by(email=form.email.data).first()
if user and user.check_password(form.password.data):
login_user(user, remember=True)
next = request.args.get('next')
if not next or not next.startswith('/'):
next = url_for('web.index')
return redirect(next)
else:
flash('账号不存在或密码错误')
return render_template('auth/login.html', form=form)
@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():
form = EmailForm(request.form)
if request.method == 'POST':
if form.validate():
account_email = form.email.data
user = User.query.filter_by(email=account_email).first_or_404()
from app.lib.email import send_mail
send_mail(form.email.data, '重置你的密码', 'email/reset_password.html', user=user, token=user.generate_token())
flash('一封邮件已发送到邮箱' + account_email + ',请及时查收')
# return redirect(url_for('web.login'))
return render_template('auth/forget_password_request.html', form=form)
@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
form = ResetPasswordForm(request.form)
if request.method == 'POST' and form.validate():
success = User.reset_password(token, form.password1.data)
if success:
flash('密码重置成功')
return redirect(url_for('web.login'))
else:
flash('密码重置失败')
return render_template('auth/forget_password.html')
@web.route('/change/password', methods=['GET', 'POST'])
def change_password():
pass
@web.route('/logout')
def logout():
logout_user()
return redirect(url_for('web.index'))
| [
"zhengpanone@hotmail.com"
] | zhengpanone@hotmail.com |
02646855dd3fe965ae1abbf7f8ac90f9fb74127b | adf2e802c7563e4b7b7cc279a54deceb6a803098 | /openapi_client/models/pdf_save_as_png_response.py | d67e711a78498d5c15d094309115b2d000f36c8c | [] | no_license | Orpalis/passportpdfsdk-python | 2466f7568becf2bd386bd9e4e00b4e3c1e642727 | 257d305ca9e6508d44fe521a1e4721f1835e8d0e | refs/heads/master | 2022-04-24T15:58:21.257112 | 2020-04-27T11:09:37 | 2020-04-27T11:09:37 | 254,665,250 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,129 | py | # coding: utf-8
"""
PassportPDF API
Another brick in the cloud # noqa: E501
The version of the OpenAPI document: 1.0.1
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
class PdfSaveAsPNGResponse(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'error': 'Error',
'remaining_tokens': 'int',
'page_images': 'list[PageImage]'
}
attribute_map = {
'error': 'Error',
'remaining_tokens': 'RemainingTokens',
'page_images': 'PageImages'
}
def __init__(self, error=None, remaining_tokens=None, page_images=None, local_vars_configuration=None): # noqa: E501
"""PdfSaveAsPNGResponse - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._error = None
self._remaining_tokens = None
self._page_images = None
self.discriminator = None
if error is not None:
self.error = error
if remaining_tokens is not None:
self.remaining_tokens = remaining_tokens
self.page_images = page_images
@property
def error(self):
"""Gets the error of this PdfSaveAsPNGResponse. # noqa: E501
:return: The error of this PdfSaveAsPNGResponse. # noqa: E501
:rtype: Error
"""
return self._error
@error.setter
def error(self, error):
"""Sets the error of this PdfSaveAsPNGResponse.
:param error: The error of this PdfSaveAsPNGResponse. # noqa: E501
:type: Error
"""
self._error = error
@property
def remaining_tokens(self):
"""Gets the remaining_tokens of this PdfSaveAsPNGResponse. # noqa: E501
Specifies the number of remaining tokens. # noqa: E501
:return: The remaining_tokens of this PdfSaveAsPNGResponse. # noqa: E501
:rtype: int
"""
return self._remaining_tokens
@remaining_tokens.setter
def remaining_tokens(self, remaining_tokens):
"""Sets the remaining_tokens of this PdfSaveAsPNGResponse.
Specifies the number of remaining tokens. # noqa: E501
:param remaining_tokens: The remaining_tokens of this PdfSaveAsPNGResponse. # noqa: E501
:type: int
"""
self._remaining_tokens = remaining_tokens
@property
def page_images(self):
"""Gets the page_images of this PdfSaveAsPNGResponse. # noqa: E501
The page(s) of the PDF saved as PNG image(s). # noqa: E501
:return: The page_images of this PdfSaveAsPNGResponse. # noqa: E501
:rtype: list[PageImage]
"""
return self._page_images
@page_images.setter
def page_images(self, page_images):
"""Sets the page_images of this PdfSaveAsPNGResponse.
The page(s) of the PDF saved as PNG image(s). # noqa: E501
:param page_images: The page_images of this PdfSaveAsPNGResponse. # noqa: E501
:type: list[PageImage]
"""
self._page_images = page_images
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PdfSaveAsPNGResponse):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, PdfSaveAsPNGResponse):
return True
return self.to_dict() != other.to_dict()
| [
"e.carrere@orpalis.com"
] | e.carrere@orpalis.com |
b03483024f8dbee4a47691a1248905822c5c67f2 | e3765def4a180f1d51eaef3884448b0bb9be2cd3 | /example/13.3.4_reconstruct_create_fleet/game_functions.py | 01b601c1630e2d7ae6580554ff2caa2de174d3e5 | [] | no_license | spearfish/python-crash-course | cbeb254efdf0c1ab37d8a7d2fa0409194f19fa2b | 66bc42d41395cc365e066a597380a96d3282d30b | refs/heads/master | 2023-07-14T11:04:49.276764 | 2021-08-20T10:02:27 | 2021-08-20T10:02:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,109 | py | #!/usr/bin/env python3
import sys
import pygame
from bullet import Bullet
from alien import Alien
# check the events, and modify ship and bullets according to settings
def check_events(ship, bullets, settings) :
'''check for keyboard input and mouse move'''
# pygame's event class has a method get.
for event in pygame.event.get() :
if event.type == pygame.QUIT :
sys.exit()
elif event.type == pygame.KEYDOWN :
check_key_down_events(event, settings, ship, bullets)
elif event.type == pygame.KEYUP :
check_key_up_events(event, ship)
def check_key_down_events(event, settings, ship, bullets) :
''' handles key down events. '''
if event.key == pygame.K_RIGHT :
ship.moving_right = True
elif event.key == pygame.K_LEFT :
ship.moving_left = True
elif event.key == pygame.K_SPACE :
fire_bullet(settings, bullets, ship)
elif event.key == pygame.K_q :
sys.exit()
def fire_bullet(settings, bullets, ship) :
if len(bullets) < settings.bullets_allowed :
new_bullet = Bullet(settings, ship)
bullets.add(new_bullet)
def check_key_up_events(event, ship):
''' handles key up events. '''
if event.key == pygame.K_RIGHT :
ship.moving_right = False
elif event.key == pygame.K_LEFT :
ship.moving_left = False
def update_screen(settings, screen, ship, bullets, aliens) :
''' redraw the screen '''
# setting the color for the new screen.
screen.fill(settings.bg_color)
# draw the new screen.
ship.blitme()
# draw the bullets.
# Group.spirtes() method gives us a list of bullet object (sprites).
for bullet in bullets.sprites() :
# update the screen with the fleet of bullets.
bullet.draw_bullet(screen)
# draw the alien
aliens.draw(screen)
# show the screen
pygame.display.flip()
def update_bullets(bullets) :
''' remove bullets if bullet run out of the screen '''
# we should not delete list element when we are in for loop
# this will cause chaos for the index of the element during for loop execution.
for bullet in bullets.copy() :
if bullet.rect.bottom < 0 :
# remove the elemnts from the sprite group
bullets.remove(bullet)
def create_fleet(settings, screen, aliens) :
''' creates a fleet on the screen '''
# calculate number of aliens in a row
alien = Alien(settings, screen)
number_aliens_x = get_number_aliens_x(settings, alien.rect.width)
alien_height = alien.rect.height
for index in range(number_aliens_x) :
create_alien(settings, screen, aliens, index)
def get_number_aliens_x(settings, alien_width) :
space_x = settings.screen_width - alien_width * 2
number_aliens_x = space_x // ( 2 * alien_width )
return number_aliens_x
def create_alien(settings, screen, aliens, index) :
alien = Alien(settings, screen)
alien_width = alien.rect.width
alien.x = alien_width + 2 * alien_width * index
alien.rect.x = alien.x
aliens.add(alien)
| [
"jingchen@tutanota.com"
] | jingchen@tutanota.com |
8b282c325b4e4b9b70b53d8a2da4dc881e6a881d | 3562fa51db47b1b1e97785191f0c04644d47c283 | /python/plat3/1395.py | e2d0dff2789f4aa3d406947ea475b1da19862513 | [] | no_license | seono/algorithm | c74181d564525e3a0214824c4a619c51cd52a042 | 78a252b29290eaa1ea076d76cd83e5dbbb7d8d89 | refs/heads/master | 2021-07-13T07:13:41.523888 | 2021-04-24T14:05:00 | 2021-04-24T14:05:00 | 244,609,427 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,182 | py | import sys
input = sys.stdin.readline
output = sys.stdout.write
N, M = map(int,input().split())
tree = [0]*(4*N)
lazy = [0]*(4*N)
def propagate(node,now_s,now_e):
if lazy[node]:
tree[node]=(now_e-now_s+1)-tree[node]
if now_s!=now_e:
lazy[node<<1]^=1
lazy[node<<1|1]^=1
lazy[node]=0
def update(now_s,now_e,s,e,node):
propagate(node,now_s,now_e)
if now_s>e or now_e<s:return
if s<=now_s and now_e<=e:
tree[node]=(now_e-now_s+1)-tree[node]
if now_s!=now_e:
lazy[node<<1]^=1
lazy[node<<1|1]^=1
return
mid = (now_e+now_s)>>1
update(now_s,mid,s,e,node<<1)
update(mid+1,now_e,s,e,node<<1|1)
tree[node]=tree[node<<1] + tree[node<<1|1]
def query(now_s,now_e,s,e,node):
propagate(node,now_s,now_e)
if e<now_s or s>now_e:return 0
if s<=now_s and now_e<=e:return tree[node]
mid = (now_e+now_s)>>1
return query(now_s,mid,s,e,node<<1)+query(mid+1,now_e,s,e,node<<1|1)
for _ in range(M):
cmd, i, j = map(int,input().split())
if cmd==0:
update(1,N,i,j,1)
else:
output("%d\n"%query(1,N,i,j,1))
#print(tree[:2*N]) | [
"tjsh0111@gmail.com"
] | tjsh0111@gmail.com |
7a3e5d086048d2b3fd47910b56f0d85fcb4d8453 | 6ee533cb075c80663e6ce15e049046aeaf54f880 | /mp/migrations/0001_initial.py | e28828b5ad2531f412626acc293e3544519a282e | [] | no_license | ARDaVinci/arttnet | 21afd6c00a9ec27aae3bd12fb2cf18126226d112 | fbc762852839960f2382ef9a5662d47419d943e0 | refs/heads/master | 2023-04-01T17:09:11.628441 | 2021-04-23T19:06:13 | 2021-04-23T19:06:13 | 360,658,769 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,117 | py | # Generated by Django 3.2 on 2021-04-22 14:57
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='Messageprive',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('creation_date', models.DateTimeField(auto_now=True)),
('title', models.CharField(max_length=500)),
('text', models.TextField(max_length=5000)),
('all_answers', models.IntegerField(default=0)),
('receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='receiver', to=settings.AUTH_USER_MODEL)),
('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"Vous@exemple.com"
] | Vous@exemple.com |
273d2a79ff8672a69151a5d581e2a4c1059ac710 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /benchmark/startCirq668.py | d6a190b3715fe3cd9362da7477ea50eaef3b7ef7 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,871 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=12
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=9
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[2])) # number=8
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.X.on(input_qubit[2])) # number=7
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=6
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=10
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=11
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq668.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
adc6788eb8ddf274faef776b14af7bd7bc8f8565 | fdbcc456e953b29c96b5c66b96a3f00e7605107c | /stats/generic.py | 5b17449424b8e522e2c56e7ca3f7cdbeac42e940 | [] | no_license | paulsavala/student-monitoring-backend | a0a86f59eda063fffa538974e9cda2636b899da4 | df729e647adc9ad3d31d7ece30e0488dbe0f035a | refs/heads/master | 2022-12-03T22:42:28.354093 | 2020-08-31T01:22:09 | 2020-08-31T01:22:09 | 257,088,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 478 | py | import numpy as np
from scipy.stats import beta
class GenericDistribution:
def __init__(self, **kwargs):
pass
def fit(self, assignment_collection):
raise NotImplementedError
def conf_int(self, assignment_collection, conf_level=0.05):
raise NotImplementedError
def pdf(self, assignment_collection):
raise NotImplementedError
def p_value(self, x, assignment_collection, one_tailed=False):
raise NotImplementedError
| [
"paulsavala@gmail.com"
] | paulsavala@gmail.com |
ae30419213eabe7a8d336d33dce31950f52c7c41 | 424c73412ccebe09198bf91c3601a61ad2242932 | /azure-mgmt-containerservice/azure/mgmt/containerservice/container_service_client.py | 5f3e1d60bcaf9f0ce8a77a7ff3916612bd372bc2 | [
"MIT"
] | permissive | arifulmondal/azure-sdk-for-python | 25c7ad16ba572c2e2bee60e117258c556ea5bdc3 | 38b3ce0fe3fdd6dd1e607627c611b8a9c97c2372 | refs/heads/master | 2021-03-24T13:50:32.389409 | 2017-10-23T18:38:49 | 2017-10-23T18:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,483 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.service_client import ServiceClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.container_services_operations import ContainerServicesOperations
from . import models
class ContainerServiceClientConfiguration(AzureConfiguration):
"""Configuration for ContainerServiceClient
Note that all parameters used to create this instance are saved as instance
attributes.
:param credentials: Credentials needed for the client to connect to Azure.
:type credentials: :mod:`A msrestazure Credentials
object<msrestazure.azure_active_directory>`
:param subscription_id: Subscription credentials which uniquely identify
Microsoft Azure subscription. The subscription ID forms part of the URI
for every service call.
:type subscription_id: str
:param str base_url: Service URL
"""
def __init__(
self, credentials, subscription_id, base_url=None):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
if not base_url:
base_url = 'https://management.azure.com'
super(ContainerServiceClientConfiguration, self).__init__(base_url)
self.add_user_agent('containerserviceclient/{}'.format(VERSION))
self.add_user_agent('Azure-SDK-For-Python')
self.credentials = credentials
self.subscription_id = subscription_id
class ContainerServiceClient(object):
"""The Container Service Client.
:ivar config: Configuration for client.
:vartype config: ContainerServiceClientConfiguration
:ivar container_services: ContainerServices operations
:vartype container_services: azure.mgmt.containerservice.operations.ContainerServicesOperations
:param credentials: Credentials needed for the client to connect to Azure.
:type credentials: :mod:`A msrestazure Credentials
object<msrestazure.azure_active_directory>`
:param subscription_id: Subscription credentials which uniquely identify
Microsoft Azure subscription. The subscription ID forms part of the URI
for every service call.
:type subscription_id: str
:param str base_url: Service URL
"""
def __init__(
self, credentials, subscription_id, base_url=None):
self.config = ContainerServiceClientConfiguration(credentials, subscription_id, base_url)
self._client = ServiceClient(self.config.credentials, self.config)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self.api_version = '2017-01-31'
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self.container_services = ContainerServicesOperations(
self._client, self.config, self._serialize, self._deserialize)
| [
"laurent.mazuel@gmail.com"
] | laurent.mazuel@gmail.com |
ef66115bb76808efd291616eb713cbc9d8cfdd66 | 41d9b92ef2a74a4ba05d27ffbe3beb87884c4ce7 | /supervised_learning/0x01-classification/4-neuron.py | 2e62079af446cbe189d8a81e2f081f500022e808 | [] | no_license | JosephK89/holbertonschool-machine_learning | 3f96d886c61d8de99a23e4348fb045b9c930740e | aa5c500f7d8ebeec951f9ab5ec017cae64007c25 | refs/heads/main | 2023-08-14T18:42:53.481354 | 2021-10-10T19:53:40 | 2021-10-10T19:53:40 | 386,248,140 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,314 | py | #!/usr/bin/env python3
"""neuron class module"""
import numpy as np
class Neuron:
"""Neuron class"""
def __init__(self, nx):
"""Class Initialization"""
if type(nx) != int:
raise TypeError("nx must be an integer")
if nx < 1:
raise ValueError("nx must be a positive integer")
self.__W = np.random.randn(1, nx)
self.__b = 0
self.__A = 0
@property
def W(self):
"""getter function for weights"""
return self.__W
@property
def b(self):
"""getter function for biases"""
return self.__b
@property
def A(self):
"""getter function for A"""
return self.__A
def forward_prop(self, X):
"""forward propagation function"""
Z = np.matmul(self.__W, X) + self.__b
self.__A = 1 / (1 + np.exp(-Z))
return self.__A
def cost(self, Y, A):
"""model cost function"""
cost_array = np.multiply(np.log(A), Y) + np.multiply((
1 - Y), np.log(1.0000001 - A))
cost = -np.sum(cost_array) / len(A[0])
return cost
def evaluate(self, X, Y):
"""evaluate neurons function"""
self.forward_prop(X)
cost = self.cost(Y, self.__A)
return (np.where(self.__A > 0.5, 1, 0), cost)
| [
"josephkamel262@gmail.com"
] | josephkamel262@gmail.com |
76eb0dc5718888863c17c3c6aa25053e1371d456 | 1a6c2be5ff1a8364c97a1ede23c824b2579ecf79 | /tfx/dsl/io/filesystem_registry_test.py | 236551f774277bfe81963eaddb2ea0bfc465df50 | [
"Apache-2.0"
] | permissive | 418sec/tfx | fa1a4690df2178e9c6bd24f97df0bbde7436df95 | df1529c91e52d442443eca5968ff33cf0a38dffa | refs/heads/master | 2023-04-18T12:25:38.098958 | 2021-04-28T16:11:00 | 2021-04-28T16:11:00 | 333,769,030 | 2 | 1 | Apache-2.0 | 2021-04-28T16:11:01 | 2021-01-28T13:35:14 | null | UTF-8 | Python | false | false | 5,808 | py | # Lint as: python2, python3
# Copyright 2019 Google LLC. 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.
"""Tests for tfx.dsl.components.base.base_driver."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tfx.dsl.io import filesystem
from tfx.dsl.io import filesystem_registry
from tfx.dsl.io.plugins import local
from tfx.dsl.io.plugins import tensorflow_gfile
class FakeFilesystemA(filesystem.Filesystem):
pass
class FakeFilesystemB(filesystem.Filesystem):
pass
class FakeFilesystemC(filesystem.Filesystem):
pass
class FilesystemRegistryTest(tf.test.TestCase):
def testRegistry(self):
registry = filesystem_registry.FilesystemRegistry()
# Test exceptions properly raised when schemes not registered.
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_scheme('')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_path('/tmp/my/file')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_scheme('gs://')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_path('gs://bucket/tmp/my/file')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_scheme('s3://')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_path('s3://bucket/tmp/my/file')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_path('unknown://bucket/tmp/my/file')
# Test after local filesystem is registered.
registry.register(local.LocalFilesystem, 20)
self.assertIs(local.LocalFilesystem, registry.get_filesystem_for_scheme(''))
self.assertIs(local.LocalFilesystem,
registry.get_filesystem_for_path('/tmp/my/file'))
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_scheme('gs://')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_path('gs://bucket/tmp/my/file')
with self.assertRaisesRegexp(Exception, 'is not available for use'):
registry.get_filesystem_for_path('unknown://bucket/tmp/my/file')
# Test after Tensorflow filesystems are registered with higher priority.
registry.register(
tensorflow_gfile.TensorflowFilesystem, 10, use_as_fallback=True)
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_scheme(''))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path('/tmp/my/file'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_scheme('gs://'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path('gs://bucket/tmp/my/file'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_scheme('s3://'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path('s3://bucket/tmp/my/file'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_scheme('hdfs://'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path('hdfs://bucket/tmp/my/file'))
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path(
'unknown://bucket/tmp/my/file'))
# Test that fallback filesystems are correctly prioritized. `FilesystemA`
# should not be used as the fallback since it has lower priority than
# `TensorflowFilesystem`.
registry.register(FakeFilesystemA, 15, use_as_fallback=True)
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path(
'unknown://bucket/tmp/my/file'))
# A filesystem registered without `use_as_fallback=True` should not be used
# as a fallback.
registry.register(FakeFilesystemB, 5)
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path(
'unknown://bucket/tmp/my/file'))
# `FakeFilesystemC` is a fallback with higher priority than
# `TensorflowFilesystem` and so should be used as the fallback.
registry.register(FakeFilesystemC, 5, use_as_fallback=True)
self.assertIs(FakeFilesystemC,
registry.get_filesystem_for_path(
'unknown://bucket/tmp/my/file'))
# Test usage of byte paths.
self.assertIs(tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_scheme(b'hdfs://'))
self.assertIs(
tensorflow_gfile.TensorflowFilesystem,
registry.get_filesystem_for_path(b'hdfs://bucket/tmp/my/file'))
with self.assertRaisesRegexp(ValueError, 'Invalid path type'):
registry.get_filesystem_for_path(123)
if __name__ == '__main__':
tf.test.main()
| [
"tensorflow-extended-nonhuman@googlegroups.com"
] | tensorflow-extended-nonhuman@googlegroups.com |
a1ec748cd25073683f73de54d482230285066f6e | 3d2939ae9ce30b15c1c3cd18bb7bc1db655863fe | /openturns/1.8/user_manual/_generated/openturns-Multinomial-1.py | ed23bba47e9242992b3d6844b0dc0765204c63fc | [] | no_license | ThibaultDelage/openturns.github.io | 07c9d6c98118a7695c35192a59814c23a71cb861 | 726a8f9ae97dc27d78a822f4d46976af56691802 | refs/heads/master | 2020-05-07T14:06:08.368744 | 2019-04-08T14:05:56 | 2019-04-08T14:05:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,484 | py | import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View
if (ot.Multinomial().__class__.__name__=='ComposedDistribution'):
correlation = ot.CorrelationMatrix(2)
correlation[1, 0] = 0.25
aCopula = ot.NormalCopula(correlation)
marginals = [ot.Normal(1.0, 2.0), ot.Normal(2.0, 3.0)]
distribution = ot.ComposedDistribution(marginals, aCopula)
elif (ot.Multinomial().__class__.__name__=='CumulativeDistributionNetwork'):
distribution = ot.CumulativeDistributionNetwork([ot.Normal(2),ot.Dirichlet([0.5, 1.0, 1.5])], ot.BipartiteGraph([[0,1], [0,1]]))
else:
distribution = ot.Multinomial()
dimension = distribution.getDimension()
if dimension <= 2:
if distribution.getDimension() == 1:
distribution.setDescription(['$x$'])
pdf_graph = distribution.drawPDF()
cdf_graph = distribution.drawCDF()
fig = plt.figure(figsize=(10, 4))
plt.suptitle(str(distribution))
pdf_axis = fig.add_subplot(121)
cdf_axis = fig.add_subplot(122)
View(pdf_graph, figure=fig, axes=[pdf_axis], add_legend=False)
View(cdf_graph, figure=fig, axes=[cdf_axis], add_legend=False)
else:
distribution.setDescription(['$x_1$', '$x_2$'])
pdf_graph = distribution.drawPDF()
fig = plt.figure(figsize=(10, 5))
plt.suptitle(str(distribution))
pdf_axis = fig.add_subplot(111)
View(pdf_graph, figure=fig, axes=[pdf_axis], add_legend=False) | [
"schueller@phimeca.com"
] | schueller@phimeca.com |
1f846a0df6dbb11c408ad08429e4a3048165f03c | 0819c03aae157f0a73488911380d26d796026839 | /ProjectEuler/ProjectEuler/Euler015.py | e9afa56b00daba148bd6a8cc8c81f9d2b7272c00 | [] | no_license | mohi-othman/mohi-euler-python | 5c53f02a94a9541623758595e9dd602122f4bb5f | 71aec394684362733a502eb3b4c3f88a18565387 | refs/heads/master | 2016-09-05T16:05:37.161813 | 2012-11-07T19:40:21 | 2012-11-07T19:40:21 | 32,092,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,310 | py | import time
class node:
def __init__(self):
self.children = []
class network:
def __init__(self, firstNode, targetNodes):
self.firstNode = firstNode
self.targetNodes = targetNodes
def getFreshResultDict(self):
result = dict()
for target in self.targetNodes:
result[target] = 0
return result
def move(destination, targets, resultDict):
if destination in targets:
resultDict[destination]+=1
else:
for newDestination in destination.children:
move(newDestination, targets, resultDict)
def buildSquare(dimension):
grid = []
for i in range(0, dimension+1):
row = []
for j in range(0, dimension+1):
newNode = node()
row.append(newNode)
grid.append(row)
for i in range(0, dimension+1):
for j in range(0, dimension+1):
if j<dimension:
grid[i][j].children.append(grid[i][j+1])
if i<dimension:
grid[i][j].children.append(grid[i+1][j])
result = network(grid[0][0], [grid[dimension][dimension]])
return result
def buildTriangle(dimension):
tree = []
for i in range(0, dimension+1):
level = []
for j in range(0, i+2):
newNode = node()
level.append(newNode)
tree.append(level)
for i in range(0, dimension):
for j in range(0, i+2):
tree[i][j].children.append(tree[i+1][j])
tree[i][j].children.append(tree[i+1][j+1])
result = network(tree[0][0], tree[dimension])
return result
def buildPartialTriangle(dimension):
if (dimension)%2==0:
halfPoint = (dimension + 2) // 2
else:
halfPoint = (dimension + 1) // 2
tree = []
for i in range(0, dimension+1):
level = []
for j in range(0, (i+2,halfPoint)[i+2 > halfPoint]):
newNode = node()
level.append(newNode)
tree.append(level)
for i in range(0, dimension):
for j in range(0, (i+2,halfPoint)[i+2 > halfPoint]):
tree[i][j].children.append(tree[i+1][j])
if j < halfPoint - 1:
tree[i][j].children.append(tree[i+1][j+1])
result = network(tree[0][0], tree[dimension])
return result
def solve():
dimension = 20
squareNetwork = buildSquare(dimension)
gridResultDict = squareNetwork.getFreshResultDict()
triangleNetwork = buildTriangle(dimension)
treeResultDict = triangleNetwork.getFreshResultDict()
partialTriangleNetwork = buildPartialTriangle(dimension)
smallTreeResultDict = partialTriangleNetwork.getFreshResultDict()
t = time.clock()
move(triangleNetwork.firstNode, triangleNetwork.targetNodes, treeResultDict)
print("Triangle network result is:", sum([x**2 for x in treeResultDict.values()]))
print("Triangle network done in:",time.clock() - t)
t = time.clock()
move(partialTriangleNetwork.firstNode, partialTriangleNetwork.targetNodes, smallTreeResultDict)
if dimension%2==0:
result = 2 * sum([x**2 for x in smallTreeResultDict.values() if x < max(smallTreeResultDict.values())]) + max(smallTreeResultDict.values())**2
else:
result = 2 * sum([x**2 for x in smallTreeResultDict.values()])
print("Partial triangle result is:", result)
print("Partial triangle network done in:",time.clock() - t)
t = time.clock()
move(squareNetwork.firstNode, squareNetwork.targetNodes, gridResultDict)
print("Square network result is:", sum(gridResultDict.values()))
print("Square network done in:",time.clock() - t)
####################################################################################
def solvePascalTriangle(dimension):
t = time.clock()
level = [1,1]
for i in range(2, dimension+1):
newLevel = [1]
for j in range(0, len(level)-1):
newLevel.append(level[j]+level[j+1])
newLevel.append(1)
level = newLevel
print("Result is:", sum([x**2 for x in level]))
print("Pascal triangle done in:",time.clock() - t)
| [
"muhyedeno@PTS-WS-001.ptsdomain.com"
] | muhyedeno@PTS-WS-001.ptsdomain.com |
bf2ffece548fa7bd8cc89eabcda5c3a1929f6e4a | bb6ebff7a7f6140903d37905c350954ff6599091 | /tools/perf/page_sets/__init__.py | 36a23b43274917573f2ba939d7e0eeffdddd5422 | [
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | Python | false | false | 585 | py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import inspect
import os
import sys
from telemetry.core import discover
from telemetry.page import page_set
# Import all submodules' PageSet classes.
start_dir = os.path.dirname(os.path.abspath(__file__))
top_level_dir = os.path.dirname(start_dir)
base_class = page_set.PageSet
for cls in discover.DiscoverClasses(
start_dir, top_level_dir, base_class).values():
setattr(sys.modules[__name__], cls.__name__, cls)
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
fc8906480f952922d83cf3d060c29ff2fd9f1753 | ee96ec6e09b0cc1af28ec7b77808eb4fa6611ca8 | /components/collector/tests/source_collectors/cobertura_jenkins_plugin/test_uncovered_lines.py | ba7a4b2fc18da91ca3b88bffa86002a81af0639d | [
"Apache-2.0"
] | permissive | Erik-Stel/quality-time | eb1b8db2022a91f06fc0edfc966dbec7a972b88c | 602b6970e5d9088cb89cc6d488337349e54e1c9a | refs/heads/master | 2023-03-28T13:22:11.043108 | 2021-03-18T14:27:18 | 2021-03-18T14:27:18 | 269,277,099 | 0 | 0 | Apache-2.0 | 2021-03-18T14:20:21 | 2020-06-04T06:20:28 | Python | UTF-8 | Python | false | false | 753 | py | """Unit tests for the Cobertura Jenkins plugin uncovered lines collector."""
from .base import CoberturaJenkinsPluginTestCase
class CoberturaJenkinsPluginUncoveredLinesTest(CoberturaJenkinsPluginTestCase):
"""Unit tests for the Cobertura Jenkins plugin uncovered lines collector."""
METRIC_TYPE = "uncovered_lines"
COBERTURA_JENKINS_PLUGIN_JSON = dict(results=dict(elements=[dict(denominator=15, numerator=13, name="Lines")]))
async def test_uncovered_lines(self):
"""Test that the number of uncovered lines and the total number of lines are returned."""
response = await self.collect(get_request_json_return_value=self.COBERTURA_JENKINS_PLUGIN_JSON)
self.assert_measurement(response, value="2", total="15")
| [
"noreply@github.com"
] | Erik-Stel.noreply@github.com |
a651609a35436a53f6a614b63ab7428a107075b2 | 82b946da326148a3c1c1f687f96c0da165bb2c15 | /sdk/python/pulumi_azure_native/notificationhubs/v20160301/list_notification_hub_keys.py | 2962a60d0ff4849a1f70790baa8413ed3a56e586 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | morrell/pulumi-azure-native | 3916e978382366607f3df0a669f24cb16293ff5e | cd3ba4b9cb08c5e1df7674c1c71695b80e443f08 | refs/heads/master | 2023-06-20T19:37:05.414924 | 2021-07-19T20:57:53 | 2021-07-19T20:57:53 | 387,815,163 | 0 | 0 | Apache-2.0 | 2021-07-20T14:18:29 | 2021-07-20T14:18:28 | null | UTF-8 | Python | false | false | 5,190 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__all__ = [
'ListNotificationHubKeysResult',
'AwaitableListNotificationHubKeysResult',
'list_notification_hub_keys',
]
@pulumi.output_type
class ListNotificationHubKeysResult:
"""
Namespace/NotificationHub Connection String
"""
def __init__(__self__, key_name=None, primary_connection_string=None, primary_key=None, secondary_connection_string=None, secondary_key=None):
if key_name and not isinstance(key_name, str):
raise TypeError("Expected argument 'key_name' to be a str")
pulumi.set(__self__, "key_name", key_name)
if primary_connection_string and not isinstance(primary_connection_string, str):
raise TypeError("Expected argument 'primary_connection_string' to be a str")
pulumi.set(__self__, "primary_connection_string", primary_connection_string)
if primary_key and not isinstance(primary_key, str):
raise TypeError("Expected argument 'primary_key' to be a str")
pulumi.set(__self__, "primary_key", primary_key)
if secondary_connection_string and not isinstance(secondary_connection_string, str):
raise TypeError("Expected argument 'secondary_connection_string' to be a str")
pulumi.set(__self__, "secondary_connection_string", secondary_connection_string)
if secondary_key and not isinstance(secondary_key, str):
raise TypeError("Expected argument 'secondary_key' to be a str")
pulumi.set(__self__, "secondary_key", secondary_key)
@property
@pulumi.getter(name="keyName")
def key_name(self) -> Optional[str]:
"""
KeyName of the created AuthorizationRule
"""
return pulumi.get(self, "key_name")
@property
@pulumi.getter(name="primaryConnectionString")
def primary_connection_string(self) -> Optional[str]:
"""
PrimaryConnectionString of the AuthorizationRule.
"""
return pulumi.get(self, "primary_connection_string")
@property
@pulumi.getter(name="primaryKey")
def primary_key(self) -> Optional[str]:
"""
PrimaryKey of the created AuthorizationRule.
"""
return pulumi.get(self, "primary_key")
@property
@pulumi.getter(name="secondaryConnectionString")
def secondary_connection_string(self) -> Optional[str]:
"""
SecondaryConnectionString of the created AuthorizationRule
"""
return pulumi.get(self, "secondary_connection_string")
@property
@pulumi.getter(name="secondaryKey")
def secondary_key(self) -> Optional[str]:
"""
SecondaryKey of the created AuthorizationRule
"""
return pulumi.get(self, "secondary_key")
class AwaitableListNotificationHubKeysResult(ListNotificationHubKeysResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return ListNotificationHubKeysResult(
key_name=self.key_name,
primary_connection_string=self.primary_connection_string,
primary_key=self.primary_key,
secondary_connection_string=self.secondary_connection_string,
secondary_key=self.secondary_key)
def list_notification_hub_keys(authorization_rule_name: Optional[str] = None,
namespace_name: Optional[str] = None,
notification_hub_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListNotificationHubKeysResult:
"""
Namespace/NotificationHub Connection String
:param str authorization_rule_name: The connection string of the NotificationHub for the specified authorizationRule.
:param str namespace_name: The namespace name.
:param str notification_hub_name: The notification hub name.
:param str resource_group_name: The name of the resource group.
"""
__args__ = dict()
__args__['authorizationRuleName'] = authorization_rule_name
__args__['namespaceName'] = namespace_name
__args__['notificationHubName'] = notification_hub_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:notificationhubs/v20160301:listNotificationHubKeys', __args__, opts=opts, typ=ListNotificationHubKeysResult).value
return AwaitableListNotificationHubKeysResult(
key_name=__ret__.key_name,
primary_connection_string=__ret__.primary_connection_string,
primary_key=__ret__.primary_key,
secondary_connection_string=__ret__.secondary_connection_string,
secondary_key=__ret__.secondary_key)
| [
"noreply@github.com"
] | morrell.noreply@github.com |
611bd7353b0fbdc7b5663cd846967b689d762292 | 8b606215d26314c046b24f779cad1d29679de73f | /GroundSegment/GroundSegment/models/__init__.py | 67a0a2722a371aa69c721afc1836ade5d5fc417b | [] | no_license | unlamgidsa/unlam_gs_backend | b5a76660458fd43557602840eb24f838aabc4ce2 | 6284a5d55b8fe3b5b7c8f3a8def505409f7ea735 | refs/heads/master | 2023-07-20T10:30:30.618320 | 2022-12-29T21:55:51 | 2022-12-29T21:55:51 | 244,700,010 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,486 | py | from GroundSegment.models.Satellite import Satellite
from GroundSegment.models.Tle import Tle
from GroundSegment.models.Parameter import Parameter
from GroundSegment.models.SatelliteState import SatelliteState
from GroundSegment.models.Propagation import Propagation
from GroundSegment.models.PropagationDetail import PropagationDetail
from GroundSegment.models.Pasada import Pasada
#from GroundSegment.models.Site import Site
from GroundSegment.models.Notification.Notification import Notification
from GroundSegment.models.Notification.Contact import Contact
from GroundSegment.models.Notification.MessageTemplate import MessageTemplate
from GroundSegment.models.Notification.NotificationType import NotificationType
from GroundSegment.models.Notification.AlarmTypeNotificationType import AlarmTypeNotificationType
from GroundSegment.models.SubSystem import SubSystem
from GroundSegment.models.Log import Log
from GroundSegment.models.Watchdog import Watchdog
from GroundSegment.models.DCPData import DCPData
from GroundSegment.models.DCPPlatform import DCPPlatform
from GroundSegment.models.Alarm import *
from GroundSegment.models.DownlinkFrame import DownlinkFrame
from GroundSegment.models.Country import Country
from GroundSegment.models.State import State
from GroundSegment.models.PassGeneration import PassGeneration
from GroundSegment.models.Eclipse import Eclipse
from GroundSegment.models.TrackPoint import TrackPoint
from GroundSegment.models.UserItem import UserItem
| [
"pablosoligo1976@gmail.com"
] | pablosoligo1976@gmail.com |
9fe6dbd17637c2e9944165ad8b3a493d8a867030 | a4681043cb56a9ab45be32a62fa9700b391f087f | /Exercícios/ex_txt01.py | 2d55dd693973772b33747357a92538abd6f9af71 | [] | no_license | MarceloDL-A/Python | b16b221ae4355b6323092d069bf83d1d142b9975 | c091446ae0089f03ffbdc47b3a6901f4fa2a25fb | refs/heads/main | 2023-01-01T02:29:31.591861 | 2020-10-27T19:04:11 | 2020-10-27T19:04:11 | 301,565,957 | 0 | 0 | null | 2020-10-27T19:04:12 | 2020-10-05T23:41:30 | Python | UTF-8 | Python | false | false | 277 | py | valores_celulares = [850, 2230, 150, 3500, 5000]
with open('valores_celulares.txt', 'a') as arquivo:
for valor in valores_celulares:
arquivo.write(str(valor) + '\n')
with open('valores_celulares.txt', 'r') as arquivo:
for valor in arquivo:
print(valor) | [
"marcelo.delmondes.lima@usp.br"
] | marcelo.delmondes.lima@usp.br |
e2e9ef0272dab73fa72d9f8bf0360e7edffc4e5b | b9e6499ab7431a2dd514fa97e7ee99dfe4c1ef3f | /corehq/apps/reports/filters/fixtures.py | b1d405cf5fe618a016ff744ca772b08d95b379fc | [] | no_license | kennknowles/commcare-hq | 9bcae8301b5888b4aaf374b684a7670c2f6fa0e7 | b1b894f4cb4a266b2dff7598cf9a9ae295bfa671 | refs/heads/master | 2023-08-16T05:50:31.822089 | 2013-09-03T22:23:28 | 2013-09-03T22:24:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,884 | py | import json
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_noop
from corehq.apps.fixtures.models import FixtureDataType, FixtureDataItem
from corehq.apps.locations.util import load_locs_json, location_hierarchy_config
from corehq.apps.reports.filters.base import BaseReportFilter
class AsyncDrillableFilter(BaseReportFilter):
# todo: add documentation
# todo: cleanup template
"""
example_hierarchy = [{"type": "state", "display": "name"},
{"type": "district", "parent_ref": "state_id", "references": "id", "display": "name"},
{"type": "block", "parent_ref": "district_id", "references": "id", "display": "name"},
{"type": "village", "parent_ref": "block_id", "references": "id", "display": "name"}]
"""
template = "reports/filters/drillable_async.html"
hierarchy = [] # a list of fixture data type names that representing different levels of the hierarchy. Starting with the root
def fdi_to_json(self, fdi):
return {
'fixture_type': fdi.data_type_id,
'fields': fdi.fields,
'id': fdi.get_id,
'children': getattr(fdi, '_children', None),
}
fdts = {}
def data_types(self, index=None):
if not self.fdts:
self.fdts = [FixtureDataType.by_domain_tag(self.domain, h["type"]).one() for h in self.hierarchy]
return self.fdts if index is None else self.fdts[index]
@property
def api_root(self):
return reverse('api_dispatch_list', kwargs={'domain': self.domain,
'resource_name': 'fixture',
'api_name': 'v0.1'})
@property
def full_hierarchy(self):
ret = []
for i, h in enumerate(self.hierarchy):
new_h = dict(h)
new_h['id'] = self.data_types(i).get_id
ret.append(new_h)
return ret
def generate_lineage(self, leaf_type, leaf_item_id):
leaf_fdi = FixtureDataItem.get(leaf_item_id)
for i, h in enumerate(self.hierarchy[::-1]):
if h["type"] == leaf_type:
index = i
lineage = [leaf_fdi]
for i, h in enumerate(self.full_hierarchy[::-1]):
if i < index or i >= len(self.hierarchy)-1: continue
real_index = len(self.hierarchy) - (i+1)
lineage.insert(0, FixtureDataItem.by_field_value(self.domain, self.data_types(real_index - 1),
h["references"], lineage[0].fields[h["parent_ref"]]).one())
return lineage
@property
def filter_context(self):
root_fdis = [self.fdi_to_json(f) for f in FixtureDataItem.by_data_type(self.domain, self.data_types(0).get_id)]
f_id = self.request.GET.get('fixture_id', None)
selected_fdi_type = f_id.split(':')[0] if f_id else None
selected_fdi_id = f_id.split(':')[1] if f_id else None
if selected_fdi_id:
index = 0
lineage = self.generate_lineage(selected_fdi_type, selected_fdi_id)
parent = {'children': root_fdis}
for i, fdi in enumerate(lineage[:-1]):
this_fdi = [f for f in parent['children'] if f['id'] == fdi.get_id][0]
next_h = self.hierarchy[i+1]
this_fdi['children'] = [self.fdi_to_json(f) for f in FixtureDataItem.by_field_value(self.domain,
self.data_types(i+1), next_h["parent_ref"], fdi.fields[next_h["references"]])]
parent = this_fdi
return {
'api_root': self.api_root,
'control_name': self.label,
'control_slug': self.slug,
'selected_fdi_id': selected_fdi_id,
'fdis': json.dumps(root_fdis),
'hierarchy': self.full_hierarchy
}
class AsyncLocationFilter(BaseReportFilter):
# todo: cleanup template
label = ugettext_noop("Location")
slug = "location_async"
template = "reports/filters/location_async.html"
@property
def filter_context(self):
api_root = reverse('api_dispatch_list', kwargs={'domain': self.domain,
'resource_name': 'location',
'api_name': 'v0.3'})
selected_loc_id = self.request.GET.get('location_id')
return {
'api_root': api_root,
'control_name': self.label, # todo: cleanup, don't follow this structure
'control_slug': self.slug, # todo: cleanup, don't follow this structure
'loc_id': selected_loc_id,
'locations': json.dumps(load_locs_json(self.domain, selected_loc_id)),
'hierarchy': location_hierarchy_config(self.domain),
}
| [
"biyeun@dimagi.com"
] | biyeun@dimagi.com |
e78104325761a22e41990587c6657fa0264a1470 | 117f066c80f3863ebef74463292bca6444f9758a | /finnhub_swagger_api/test/test_economic_event.py | 0680dd1b78155cbf3a758cdb20d37aad4454646f | [] | no_license | cottrell/notebooks | c6de3842cbaeb71457d270cbe6fabc8695a6ee1b | 9eaf3d0500067fccb294d064ab78d7aaa03e8b4d | refs/heads/master | 2023-08-09T22:41:01.996938 | 2023-08-04T22:41:51 | 2023-08-04T22:41:51 | 26,830,272 | 3 | 1 | null | 2023-03-04T03:58:03 | 2014-11-18T21:14:23 | Python | UTF-8 | Python | false | false | 945 | py | # coding: utf-8
"""
Finnhub API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import finnhub_swagger_api
from finnhub_swagger_api.models.economic_event import EconomicEvent # noqa: E501
from finnhub_swagger_api.rest import ApiException
class TestEconomicEvent(unittest.TestCase):
"""EconomicEvent unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testEconomicEvent(self):
"""Test EconomicEvent"""
# FIXME: construct object with mandatory attributes with example values
# model = finnhub_swagger_api.models.economic_event.EconomicEvent() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
"cottrell@users.noreply.github.com"
] | cottrell@users.noreply.github.com |
e2ffbcc78019f39efbb8a5987a61e52a6a20f3a7 | 5bc369d49b16bc46e23b76621144223dc4226997 | /model/backboneelement.py | 758f0a7a409f6cfe67910f0eba872570df4ea431 | [
"MIT"
] | permissive | beda-software/fhir-py-experements | 90d8e802f92f9e691d47d6ea4b33fda47957383a | 363cfb894fa6f971b9be19340cae1b0a3a4377d8 | refs/heads/master | 2022-12-17T05:19:59.294901 | 2020-02-26T03:54:13 | 2020-02-26T03:54:13 | 241,292,789 | 0 | 0 | MIT | 2022-12-08T03:38:55 | 2020-02-18T06:53:02 | Python | UTF-8 | Python | false | false | 610 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/BackboneElement) on 2020-02-03.
# 2020, SMART Health IT.
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Optional, List
from .element import Element
@dataclass
class BackboneElement(Element):
""" Base for elements defined inside a resource.
Base definition for all elements that are defined inside a resource - but
not those in a data type.
"""
resource_type: ClassVar[str] = "BackboneElement"
modifierExtension = None | [
"ir4y.ix@gmail.com"
] | ir4y.ix@gmail.com |
222d5f8b367a6c13cd3e6b528fbb411a5aabb6af | d768f07ed90c0274e2d9d935eaf5ecfe734a1f56 | /export_analysis_data.py | a6837acdf7c614c00fc7a18f92724da0cf03ffb4 | [] | no_license | bvillasen/simulation_analysis | cfd0b5de865d2fb5992d828b2824079e6798774b | 645f0c397172ed30a713368942eec9ca68a9761a | refs/heads/master | 2023-06-02T19:06:39.851760 | 2021-06-25T18:40:58 | 2021-06-25T18:40:58 | 298,894,454 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,053 | py | import os, sys
import numpy as np
import pickle
sys.path.append('tools')
from tools import *
#Append analysis directories to path
extend_path()
from parameters_UVB_rates import param_UVB_Rates
from simulation_grid import Simulation_Grid
from simulation_parameters import *
from plot_UVB_Rates import Plot_Grid_UVB_Rates
create_directory( root_dir )
create_directory( figures_dir )
SG = Simulation_Grid( parameters=param_UVB_Rates, sim_params=sim_params, job_params=job_params, dir=root_dir )
SG.Get_Grid_Status( check_queue=False )
SG.Load_Grid_Analysis_Data( )
sim_ids = SG.sim_ids
data_out = {}
for sim_id in sim_ids:
data_out[sim_id] = {}
data_out[sim_id]['z'] = SG.Grid[sim_id]['analysis']['z']
data_out[sim_id]['T0'] = SG.Grid[sim_id]['analysis']['T0']
data_out[sim_id]['F_mean'] = SG.Grid[sim_id]['analysis']['F_mean']
data_out[sim_id]['parameters'] = SG.Grid[sim_id]['parameters']
out_file_name = root_dir + 'scale_H_T0.pkl'
f = open( out_file_name, "wb")
pickle.dump( data_out, f)
print ( f'Saved File: {out_file_name}' )
| [
"bvillasen@gmail.com"
] | bvillasen@gmail.com |
bdb5ac7c0f0dce9ca493553586d860621320d1fa | 793d8e06dd50b9e211833f962ac1d10fd425a1df | /tests/test_component.py | 981987983cbf7af2fae75115e0c7f8fab43c5b0a | [
"Apache-2.0"
] | permissive | iqduke/fruit | 7e715dae9e9dd56e7cd9cce8bba7de3504659ed4 | 56c39c6eae1312a2e71052602c21079de08b57d8 | refs/heads/master | 2021-01-12T04:19:35.897109 | 2016-12-27T10:09:08 | 2016-12-27T10:09:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,434 | py | #!/usr/bin/env python3
# Copyright 2016 Google 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.
from nose2.tools import params
from fruit_test_common import *
COMMON_DEFINITIONS = '''
#include "test_common.h"
struct X;
struct Annotation1 {};
using XAnnot1 = fruit::Annotated<Annotation1, X>;
struct Annotation2 {};
using XAnnot2 = fruit::Annotated<Annotation2, X>;
'''
@params(
('X', 'X*'),
('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, X*>'))
def test_component_conversion(XAnnot, XPtrAnnot):
source = '''
struct X {
using Inject = X();
};
fruit::Component<> getComponent() {
return fruit::createComponent();
}
fruit::Component<XAnnot> getXComponent() {
return getComponent();
}
int main() {
fruit::Component<XAnnot> component = getXComponent();
fruit::Injector<XAnnot> injector(component);
injector.get<XPtrAnnot>();
}
'''
expect_success(
COMMON_DEFINITIONS,
source,
locals())
@params('X', 'fruit::Annotated<Annotation1, X>')
def test_copy(XAnnot):
source = '''
struct X {
using Inject = X();
};
fruit::Component<XAnnot> getComponent() {
fruit::Component<XAnnot> c = fruit::createComponent();
fruit::Component<XAnnot> copy = c;
return copy;
}
int main() {
fruit::Component<XAnnot> component = getComponent();
fruit::Injector<XAnnot> injector(component);
injector.get<XAnnot>();
}
'''
expect_success(
COMMON_DEFINITIONS,
source,
locals())
@params('X*', 'fruit::Annotated<Annotation1, X*>')
def test_error_non_class_type(XPtrAnnot):
source = '''
struct X {};
InstantiateType(fruit::Component<XPtrAnnot>)
'''
expect_compile_error(
'NonClassTypeError<X\*,X>',
'A non-class type T was specified. Use C instead.',
COMMON_DEFINITIONS,
source,
locals())
@params('X', 'fruit::Annotated<Annotation1, X>')
def test_error_repeated_type(XAnnot):
source = '''
struct X {};
InstantiateType(fruit::Component<XAnnot, XAnnot>)
'''
expect_compile_error(
'RepeatedTypesError<XAnnot, XAnnot>',
'A type was specified more than once.',
COMMON_DEFINITIONS,
source,
locals())
def test_repeated_type_with_different_annotation_ok():
source = '''
struct X {};
InstantiateType(fruit::Component<XAnnot1, XAnnot2>)
'''
expect_success(
COMMON_DEFINITIONS,
source)
@params('X', 'fruit::Annotated<Annotation1, X>')
def test_error_type_required_and_provided(XAnnot):
source = '''
struct X {};
InstantiateType(fruit::Component<fruit::Required<XAnnot>, XAnnot>)
'''
expect_compile_error(
'RepeatedTypesError<XAnnot, XAnnot>',
'A type was specified more than once.',
COMMON_DEFINITIONS,
source,
locals())
def test_type_required_and_provided_with_different_annotations_ok():
source = '''
struct X {};
InstantiateType(fruit::Component<fruit::Required<XAnnot1>, XAnnot2>)
'''
expect_success(
COMMON_DEFINITIONS,
source)
@params('X', 'fruit::Annotated<Annotation1, X>')
def test_error_no_binding_found(XAnnot):
source = '''
struct X {};
fruit::Component<XAnnot> getComponent() {
return fruit::createComponent();
}
'''
expect_compile_error(
'NoBindingFoundError<XAnnot>',
'No explicit binding nor C::Inject definition was found for T.',
COMMON_DEFINITIONS,
source,
locals())
def test_error_no_factory_binding_found():
source = '''
struct X {};
fruit::Component<std::function<std::unique_ptr<X>()>> getComponent() {
return fruit::createComponent();
}
'''
expect_compile_error(
'NoBindingFoundError<std::function<std::unique_ptr<X(,std::default_delete<X>)?>\(\)>',
'No explicit binding nor C::Inject definition was found for T.',
COMMON_DEFINITIONS,
source)
def test_error_no_factory_binding_found_with_annotation():
source = '''
struct X {};
fruit::Component<fruit::Annotated<Annotation1, std::function<std::unique_ptr<X>()>>> getComponent() {
return fruit::createComponent();
}
'''
expect_compile_error(
'NoBindingFoundError<fruit::Annotated<Annotation1,std::function<std::unique_ptr<X(,std::default_delete<X>)?>\(\)>>',
'No explicit binding nor C::Inject definition was found for T.',
COMMON_DEFINITIONS,
source)
if __name__ == '__main__':
import nose2
nose2.main()
| [
"poletti.marco@gmail.com"
] | poletti.marco@gmail.com |
28f1e50f76dfb843b32fc6522e966b977acac0d5 | 7a402a4e06eb728f36923816748c210122fc383c | /C/0207.py | 6f212e28bcec2de71e9e7a5ddfef745f0c4e059a | [] | no_license | au-aist2120-19sp/york-lecture-files | 8eb6a0bb7d9f7ff9984262efc95fb87b3a59c3ab | a38cf780f3deda84663355812d765ab40ee6ea0c | refs/heads/master | 2020-04-19T18:59:46.387355 | 2019-04-25T21:17:45 | 2019-04-25T21:17:45 | 168,377,456 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,982 | py | menu = '''
1) Burger
2) Fries
3) Checkout
'''
while True:
print(menu)
choice = input('Enter choice: ')
if choice == '3':
break
elif choice == '1':
print('Mmm. Wouldn\'t you like some fries?')
elif choice == '2':
print('Okay, but what about a juicy burger?')
else:
print('Enter a valid choice, dear customer')
print('enjoy your meal')
menu = '''
1) Burger ($3)
2) Fries ($1)
3) Checkout
'''
subtotal = 0
while True:
print(menu)
choice = input('Enter choice: ')
if choice == '3':
break
elif choice == '1':
print('Mmm. Wouldn\'t you like some fries?')
subtotal = subtotal + 3 # subtotal += 3
elif choice == '2':
print('Okay, but what about a juicy burger?')
subtotal += 1
else:
print('Enter a valid choice, dear customer')
print(f'You subtotal is {subtotal}')
print('enjoy your meal')
print(f'but first give me ${subtotal}')
# Summation
sun = 0
for n in range(1,6): #15
print(f'{sun} + {n} = {sun + n}')
sun += n
print(sun)
# Factorial
prod = 1
for n in range(1,6): #120
print(f'{prod} x {n} = {prod * n}')
prod *= n
print(prod)
tofind = 'o'
for c in "hello world":
if c == tofind:
print('yeah I found ' + tofind)
break
else:
print('boo I didn\'t find ' + tofind)
from math import sqrt as squirt
for n in range(26,37):
sq = squirt(n)
isq = int(sq)
if sq == isq:
print(f'yeah, {n} has an int root: {sq:.0f}')
break
else:
print('NOT FOUND')
str = "what's up?"
seq = []
for c in str:
if c != "'":
seq.append(c)
print(seq)
print(''.join(seq))
str = "what's up?"
seq = []
for c in str:
if c not in 'tsp':
seq.append(c)
print(seq)
print(''.join(seq))
# LIST COMPREHENSIONS
# [EXPR for x in SEQ (if EXPR2)]
seq = [c for c in str if c not in 'tsp']
print(seq)
[True for x in range(10)]
['default' for x in range(10)]
[x % 2 == True for x in range(10)]
| [
"paul@yorkfamily.com"
] | paul@yorkfamily.com |
1ba1dd25a4e97e2b5e0c797f2fd932dc29cb1d92 | d24f81b52917a7b0629fe615149ef4ac8a0bd049 | /backend/backend/urls.py | ff3520d0fb21d4109441eb4412346d7446d3cff9 | [] | no_license | ScrollPage/Test-Chat | f533c8d1112a4bc639d9659a126b9a9f886f68b2 | 3911b7555ca684b3eb31e9857d007fda3b6c7cd3 | refs/heads/master | 2023-01-03T13:37:44.600044 | 2020-10-30T08:43:27 | 2020-10-30T08:43:27 | 288,795,592 | 0 | 0 | null | 2020-08-24T13:35:51 | 2020-08-19T17:31:59 | JavaScript | UTF-8 | Python | false | false | 994 | py | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from .yasg import urlpatterns as doc_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('contact.api.urls')),
path('api/v1/', include('chat.api.urls')),
path('api/v1/', include('community.api.urls')),
path('api/v1/', include('feed.api.urls')),
path('api/v1/', include('score.api.urls')),
path('api/v1/', include('notifications.api.urls')),
path('api/v1/', include('parties.api.urls')),
path('api/v1/', include('like.api.urls')),
path('api/v1/', include('comments.api.urls')),
path('api/v1/', include('photos.api.urls')),
path('api-auth/', include('rest_framework.urls')),
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')),
]
urlpatterns += doc_urls
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) | [
"54814200+reqww@users.noreply.github.com"
] | 54814200+reqww@users.noreply.github.com |
57f77d61bfe442fe9917a5c076d507d598a55945 | ac83d1ddb84ecc904c73bdf779f458bd77efc98c | /test/programytest/dynamic/maps/test_successormap.py | 0a3b5850cb2d148fe8b8e20bd8184f4a9557f69f | [
"MIT"
] | permissive | secrecy27/chatbot | 77829f32a15e17563f038663aebebdb71e52c5a7 | e65a753cf665a4d6d97b57703431cba5331e4f0b | refs/heads/master | 2022-07-24T08:39:57.788009 | 2020-07-16T03:55:21 | 2020-07-16T03:55:21 | 130,678,143 | 4 | 4 | NOASSERTION | 2022-07-06T19:49:14 | 2018-04-23T10:12:01 | Python | UTF-8 | Python | false | false | 586 | py | import unittest
from programy.dynamic.maps.successor import SuccessorMap
from programy.context import ClientContext
from programytest.aiml_tests.client import TestClient
class TestSingularMaps(unittest.TestCase):
def setUp(self):
self._client_context = ClientContext(TestClient(), "testid")
def test_successor(self):
map = SuccessorMap(None)
self.assertEqual("2", map.map_value(self._client_context, "1"))
def test_successor_text(self):
map = SuccessorMap(None)
self.assertEqual("", map.map_value(self._client_context, "one"))
| [
"secrecy418@naver.com"
] | secrecy418@naver.com |
7e05009aba2e6b6f03f7c0b0439a1d17bbfc4249 | bf6f19c55f3af3704161e176384bcaf1c2b37537 | /pandas_demo/intro.py | 2b6a18f702a5dee13d47465865a4aa05bef0ffd6 | [] | no_license | huqinwei/python_demo | b0ba32e832533625b5ab55d56d3f3b2f6801d645 | 92da5ea2e480a9f57f8fbd619340bd9c9779cfd4 | refs/heads/master | 2021-07-18T19:23:09.914949 | 2019-01-26T13:37:47 | 2019-01-26T13:37:47 | 148,871,279 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,861 | py | # View more python tutorials on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
from __future__ import print_function
import pandas as pd
import numpy as np
s = pd.Series([1,3,6,np.nan,4,1]) # similar with 1D numpy
print(s)
dates = pd.date_range('20160101', periods=6)
dates2 = ['20160102','20160101','20160103','20140101','20160103','20160401',]
df = pd.DataFrame(np.random.randn(6,4), index=dates2, columns=['A','B','C','D'])
print('df:\n',df)
print('df[B]:\n',df['B'])
df2 = pd.DataFrame({'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo'})
print(df2)
print(df2.dtypes)
print(df.index)
print(df.columns)
print(df.values)
#print(df.describe())
#print(df.T)
print('##############################')
print('index axis=0:\n',df.sort_index(axis=0, ascending=False))
print('index axis=0 ascending:\n',df.sort_index(axis=0, ascending=True))
print('index axis=1:\n',df.sort_index(axis=1, ascending=False))
print('index axis=1 ascending:\n',df.sort_index(axis=1, ascending=True))
#print(df.sort_index(axis=2, ascending=False))#no axis
#print(df.sort_values(by='B'))
df3 = pd.DataFrame({'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo'},columns=dates)
print('df3:\n',df3)
print(df3.dtypes)
| [
"qw072117@foxmail.com"
] | qw072117@foxmail.com |
e85a1e5147376b3a1c8fd9465a3d03454be0361b | defae005fad18f91be83de5b8e2fd51e3cbfbb35 | /base_app/utilities/menus/base_main_window.py | 172ccfe8b969003eb58def704e46bc63c3021cea | [] | no_license | MRedAero/BaseApp | 018f9887cd89abbd6117bcc43f8f8dca281220b0 | 8e16ff2f2d0dbc322e4c35a61ce298abe31797b0 | refs/heads/master | 2021-03-19T10:13:01.245176 | 2015-04-27T10:08:15 | 2015-04-27T10:08:15 | 32,956,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | from PyQt4 import QtGui
from base_main_window_ui import Ui_MainWindow
class BaseMainWindow(QtGui.QMainWindow):
def __init__(self):
super(BaseMainWindow, self).__init__()
self.base_ui = Ui_MainWindow().setupUi(self)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main_window = BaseMainWindow()
main_window.show()
app.exec_()
| [
"michael.j.redmond@gmail.com"
] | michael.j.redmond@gmail.com |
c044bc1d86e1de9fa6116743028140440a45ae37 | 6c547e3312e2d1bd3dab123b831053ed7aef7b6d | /tests/test_QTML-T362_Chrome.py | 2dd0f705b88231fc31ba6ece6341109dce4889eb | [] | no_license | kenito2050/BICL | 8c4239f1e897e4dfc04aa35e827816242b41d5dd | 82891aba56cc49c9cf96ce82472847c4cb10828f | refs/heads/master | 2020-12-31T22:10:44.784193 | 2020-02-10T23:00:10 | 2020-02-10T23:00:10 | 239,039,817 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,585 | py | import pytest
from selenium import webdriver
import time
from config_globals import *
from pages.BICL.login.LoginPage import LoginPage
from pages.generic_page.generic_page import generic_page
from pages.BICL.default_page.user_drop_down.user_drop_down import user_drop_down
from pages.BICL.default_page.default_page import default_page
from pages.BICL.housekeeping.housekeeping import housekeeping
from utilities.environments.environments_BICL import Environments_BICL
from utilities.date_time_generator.date_time_generator import date_time_generator
import pandas as pd
class Test_login_Chrome:
@pytest.mark.smoke
@pytest.mark.bicl
def test_login_chrome(self, browser, env):
driver = browser
# Create Time Stamp Variable (using Date Time Generator Class in utilities)
dg = date_time_generator()
time_stamp = dg.return_time_stamp()
# This section reads in values from csv file using Pandas Library
# Declare Test Case ID
test_case_ID = 'QTML-T362'
# Declare csv directory
df = pd.read_csv(csv_directory)
# print(df)
# Select Row where "Test_Case_ID" Column Matches the test_case_ID declared above (Line 31)
# This is the row that contains the data values for this test scenario
test_case_row = df.loc[df.Test_Case_ID == test_case_ID]
# print(test_case_row)
# Read in Values from "test_case_row" object
test_scenario = test_case_row['Test_Scenario'].values[0]
username = test_case_row['User'].values[0]
password = test_case_row['Password'].values[0]
browser = test_case_row['Browser'].values[0]
account_number = test_case_row['account_number'].values[0]
rep_code = test_case_row['rep_code'].values[0]
test_data1 = test_case_row['test_data1'].values[0]
test_data2 = test_case_row['test_data_2'].values[0]
control_point_1 = test_case_row['control_point_1'].values[0]
control_point_2 = test_case_row['control_point_2'].values[0]
control_point_3 = test_case_row['control_point_3'].values[0]
control_point_4 = test_case_row['control_point_4'].values[0]
# To DEBUG, Uncomment this NEXT line AND Comment lines 13, 15 and 18. Also, SHIFT + TAB lines 17 - 86 (This will remove indents)
# driver = webdriver.Chrome(str(CONFIG_PATH / 'chromedriver.exe'))
## Select Appropriate URL based on the Environment Value (env)
# env = "UAT"
baseURL = Environments_BICL.return_environments(env)
# baseURL = "https://beta.bi.dev.wedbus.com"
driver.get(baseURL)
driver.maximize_window()
time.sleep(5)
# Login to Site
lp = LoginPage(driver)
# Verify if page loads (username_field should be clickable), if not, throw exception and take screenshot
lp.verify_username_field_displays(test_case_ID, browser, env, time_stamp)
lp.login(username, password)
lp.click_login_button()
time.sleep(10)
gp = generic_page(driver)
# Take Screenshot 1
screenshot_number = "1"
time_stamp_1 = dg.return_time_stamp()
gp.take_screenshot(test_case_ID, browser, control_point_1, screenshot_number, env, time_stamp_1)
dp = default_page(driver)
# Timeout method for page to load, timeout set to 30 seconds
gp.verify_page_loads(test_case_ID, browser, env, time_stamp)
time.sleep(15)
# Click Housekeeping
dp.click_housekeeping_icon()
time.sleep(15)
h = housekeeping(driver)
time.sleep(5)
# Click ACAT Status
h.click_acat_status()
time.sleep(5)
# Validate that correct panel displays (correct title displays on screen)
gp.validate_correct_text_displays(test_data1, test_case_ID, browser, env, time_stamp)
time.sleep(5)
# Take Screenshot 2
screenshot_number = "2"
time_stamp_2 = dg.return_time_stamp()
gp.take_screenshot(test_case_ID, browser, control_point_2, screenshot_number, env, time_stamp_2)
time.sleep(5)
# Click User Drop Down (on BICL Default Page)
dp.click_user_drop_down()
udd = user_drop_down(driver)
udd.click_logout()
# Take Screenshot 3
screenshot_number = "3"
time_stamp_3 = dg.return_time_stamp()
gp.take_screenshot(test_case_ID, browser, control_point_3, screenshot_number, env, time_stamp_3)
time.sleep(5)
# Close Browser
driver.quit() | [
"ken.villarruel@gmail.com"
] | ken.villarruel@gmail.com |
b1d51f180d8265f912b4de42692b767d6bb4182f | f85ce2baf753d65e8666bbda062acbdb0ccdb5ad | /leetcode/venv/lib/python2.7/site-packages/pyutil/ss/stream_core.py | 9ca853266c8734b7be2a2e8d21ba9627aff2e949 | [] | no_license | KqSMea8/PycharmProjects | 2a9d3fa59d08c77daf63be427da27695d4dea471 | c592d879fd79da4e0816a4f909e5725e385b6160 | refs/heads/master | 2020-04-14T11:54:56.435247 | 2019-01-02T10:15:36 | 2019-01-02T10:15:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 212 | py | # -*- coding: utf-8 -*-
from pyutil.etcd.etcd_util import get as etcd_get
# 服务降级策略:0 正常 1 降级
def get_stream_core_webdb_level():
return int(etcd_get("/web/stream/core/webdb/level", 0))
| [
"zhangyifeng@bytedance.com"
] | zhangyifeng@bytedance.com |
d1d3507dbf447a62f4869036ced20c2b6fc6cccc | fcc9c7d713179694d6e19c98693185789a1d90b9 | /CMGTools/H2TauTau/python/proto/analyzers/MuEleAnalyzer.py | b68e41c2a4d2462d41412fa681438a8bc5c6d5a9 | [] | no_license | hengne/cmg-cmssw | aedada0ce15562380d42dcc5c241d67fb8c65965 | 03946e4ce821b6186c8f881e2bbe4b2a30917b2d | refs/heads/CMGTools-from-CMSSW_7_4_7 | 2020-04-05T23:12:59.317945 | 2015-07-31T08:55:33 | 2015-07-31T08:55:33 | 40,015,437 | 0 | 1 | null | 2015-07-31T16:55:04 | 2015-07-31T16:55:04 | null | UTF-8 | Python | false | false | 6,679 | py | import operator
from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle
from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import Muon, GenParticle
# RIC: 16/2/15 need to fix the Electron object first
# from PhysicsTools.Heppy.physicsobjects.HTauTauElectron import HTauTauElectron as Electron
from PhysicsTools.Heppy.physicsobjects.Electron import Electron
from CMGTools.H2TauTau.proto.analyzers.DiLeptonAnalyzer import DiLeptonAnalyzer
from CMGTools.H2TauTau.proto.physicsobjects.DiObject import MuonElectron
class MuEleAnalyzer( DiLeptonAnalyzer ):
DiObjectClass = MuonElectron
LeptonClass = Muon
OtherLeptonClass = Electron
def declareHandles(self):
super(MuEleAnalyzer, self).declareHandles()
self.handles ['diLeptons' ] = AutoHandle('cmgMuEleCorSVFitFullSel', 'std::vector<pat::CompositeCandidate>')
self.handles ['otherLeptons'] = AutoHandle('slimmedElectrons' , 'std::vector<pat::Electron>' )
self.handles ['leptons' ] = AutoHandle('slimmedMuons' , 'std::vector<pat::Muon>' )
self.mchandles['genParticles'] = AutoHandle('prunedGenParticles' , 'std::vector<reco::GenParticle>' )
def buildDiLeptons(self, cmgDiLeptons, event):
'''Build di-leptons, associate best vertex to both legs,
select di-leptons with a tight ID muon.
The tight ID selection is done so that dxy and dz can be computed
(the muon must not be standalone).
'''
diLeptons = []
for index, dil in enumerate(cmgDiLeptons):
pydil = self.__class__.DiObjectClass(dil)
# pydil = MuonElectron(dil)
pydil.leg1().associatedVertex = event.goodVertices[0]
pydil.leg2().associatedVertex = event.goodVertices[0]
pydil.leg2().rho = event.rho
if not self.testLeg2( pydil.leg2(), 999999 ):
continue
# pydil.mvaMetSig = pydil.met().getSignificanceMatrix()
diLeptons.append( pydil )
pydil.mvaMetSig = pydil.met().getSignificanceMatrix()
return diLeptons
def buildLeptons(self, cmgLeptons, event):
'''Build muons for veto, associate best vertex, select loose ID muons.
The loose ID selection is done to ensure that the muon has an inner track.'''
leptons = []
for index, lep in enumerate(cmgLeptons):
pyl = self.__class__.LeptonClass(lep)
#pyl = Muon(lep)
pyl.associatedVertex = event.goodVertices[0]
leptons.append( pyl )
return leptons
def buildOtherLeptons(self, cmgOtherLeptons, event):
'''Build electrons for third lepton veto, associate best vertex.
'''
otherLeptons = []
for index, lep in enumerate(cmgOtherLeptons):
pyl = self.__class__.OtherLeptonClass(lep)
#import pdb ; pdb.set_trace()
#pyl = Electron(lep)
pyl.associatedVertex = event.goodVertices[0]
pyl.rho = event.rho
otherLeptons.append( pyl )
return otherLeptons
def process(self, event):
result = super(MuEleAnalyzer, self).process(event)
if result is False:
# trying to get a dilepton from the control region.
# it must have well id'ed and trig matched legs,
# di-lepton and tri-lepton veto must pass
result = self.selectionSequence(event, fillCounter = False,
leg1IsoCut = self.cfg_ana.looseiso1,
leg2IsoCut = self.cfg_ana.looseiso2)
if result is False:
# really no way to find a suitable di-lepton,
# even in the control region
return False
event.isSignal = False
else:
event.isSignal = True
event.genMatched = None
if self.cfg_comp.isMC:
# print event.eventId
genParticles = self.mchandles['genParticles'].product()
event.genParticles = map( GenParticle, genParticles)
leg1DeltaR, leg2DeltaR = event.diLepton.match( event.genParticles )
if leg1DeltaR>-1 and leg1DeltaR < 0.1 and \
leg2DeltaR>-1 and leg2DeltaR < 0.1:
event.genMatched = True
else:
event.genMatched = False
return True
def testLeg1ID(self, muon):
'''Tight muon selection, no isolation requirement'''
# RIC: 9 March 2015
return muon.muonID('POG_ID_Medium')
def testLeg1Iso(self, muon, isocut):
'''Muon isolation to be implemented'''
# RIC: this leg is the muon,
# needs to be implemented here
# For now taken straight from mt channel
if isocut is None:
isocut = self.cfg_ana.iso1
return muon.relIso(dBetaFactor=0.5, allCharged=0)<isocut
def testVertex(self, lepton):
'''Tests vertex constraints, for mu and electron'''
return abs(lepton.dxy()) < 0.045 and abs(lepton.dz ()) < 0.2
def testLeg2ID(self, electron):
'''Electron ID. To be implemented'''
# RIC: this leg is the electron,
# needs to be implemented here
# For now taken straight from et channel
return electron.electronID('POG_MVA_ID_Run2_NonTrig_Tight') and \
self.testVertex(electron)
def testLeg2Iso(self, electron, isocut):
'''Electron Isolation. Relative isolation
dB corrected factor 0.5
all charged aprticles
'''
# RIC: this leg is the electron,
# needs to be implemented here
# For now taken straight from et channel
if isocut is None:
isocut = self.cfg_ana.iso2
return electron.relIso(dBetaFactor=0.5, allCharged=0) < isocut
def thirdLeptonVeto(self, leptons, otherLeptons, ptcut = 10, isocut = 0.3) :
'''The tri-lepton veto. To be implemented'''
return True
def leptonAccept(self, leptons):
'''The di-lepton veto, returns false if > one lepton.
e.g. > 1 mu in the mu tau channel.
To be implemented.'''
return True
def bestDiLepton(self, diLeptons):
'''Returns the best diLepton (1st precedence opposite-sign,
2nd precedence highest pt1 + pt2).'''
osDiLeptons = [dl for dl in diLeptons if dl.leg1().charge() != dl.leg2().charge()]
if osDiLeptons : return max( osDiLeptons, key=operator.methodcaller( 'sumPt' ) )
else : return max( diLeptons, key=operator.methodcaller( 'sumPt' ) )
| [
"jan.steggemann@cern.ch"
] | jan.steggemann@cern.ch |
c43ed3e2de1b6a302d4e2050a585230e34d3f23d | 6ec209c1f6f3ca8017a5373ba2e85da38dfda90c | /tree/114.py | 42e297bdf6ee4dc3cb36dd8fa348e0e637032d34 | [
"Apache-2.0"
] | permissive | MingfeiPan/leetcode | a70192233f7112ce39cc7b09d782bdcc52d29d06 | 057d9f014cf207ab4e50e14e5a9e015724de1386 | refs/heads/master | 2022-05-09T01:40:39.599374 | 2022-04-10T15:03:07 | 2022-04-10T15:03:07 | 60,593,146 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 716 | py | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return
# pre-order traversal
l = []
l.append(root)
while l:
cur = l.pop()
if cur.right:
l.append(cur.right)
if cur.left:
l.append(cur.left)
if l:
cur.right = l[-1] #如果left 存在则指向left 否则指向right
cur.left = None
| [
"113104667@umail.ucc.ie"
] | 113104667@umail.ucc.ie |
1295ef0e561f0cce1242427cda2074929386f143 | eb15c60ef607040fb9f7fbca789405b8b26a86b1 | /batchpr/updater.py | 32140c6de55b9ea30721e056b19016c6004637b4 | [
"BSD-2-Clause"
] | permissive | bsipocz/batchpr | 5d2c32c3872e8b9b62d9e5ad51c3e041d661a330 | 5fbce1d357bf6e4f26ed3fcb0bda6f0a9447c614 | refs/heads/master | 2020-04-15T18:30:59.436646 | 2017-08-29T13:58:00 | 2017-08-29T13:58:00 | 164,914,948 | 0 | 0 | BSD-2-Clause | 2019-01-09T18:19:52 | 2019-01-09T18:19:46 | Python | UTF-8 | Python | false | false | 6,396 | py | import os
import abc
import six
import sys
import time
import shutil
import tempfile
import subprocess
from textwrap import indent
from github import Github
from termcolor import colored
import requests
GITHUB_RAW_FILENAME = "https://raw.githubusercontent.com/{repo}/master/{filename}"
class BranchExistsException(Exception):
pass
@six.add_metaclass(abc.ABCMeta)
class Updater(object):
def __init__(self, token, author_name=None, author_email=None):
self.github = Github(token)
self.token = token
self.user = self.github.get_user()
self.author_name = author_name
self.author_email = author_email
self.repo = None
self.fork = None
def info(self, message):
print(message)
def run(self, repositories, delay=0):
if isinstance(repositories, six.string_types):
repositories = [repositories]
start_dir = os.path.abspath('.')
for ir, repository in enumerate(repositories):
if ir > 0:
time.sleep(delay)
print(colored('Processing repository: {0}'.format(repository), 'cyan'))
self.repo_name = repository
try:
print(' > Ensuring repository exists')
self.ensure_repo_set_up()
except Exception:
self.error(" An error occurred when trying to get the repository")
continue
try:
print(' > Ensuring fork exists (and creating if not)')
self.ensure_fork_set_up()
except Exception:
self.error(" An error occurred when trying to set up a fork")
continue
# Go to temporary directory
directory = tempfile.mkdtemp()
try:
os.chdir(directory)
try:
self.clone_fork()
except BranchExistsException:
self.error(" Branch {0} already exists - skipping repository".format(self.branch_name))
continue
except Exception:
self.error(" An error occurred when cloning fork - skipping repository")
continue
if not self.process_repo():
self.warn(" Skipping repository")
return
self.commit_changes()
if '--dry' not in sys.argv:
try:
url = self.open_pull_request()
print(colored(' Pull request opened: {0}'.format(url), 'green'))
except Exception:
self.error(" An error occurred when opening pull request - skipping repository")
continue
finally:
os.chdir(start_dir)
def add(self, filename):
self.run_command('git add {0}'.format(filename))
def copy(self, filename1, filename2):
shutil.copy(filename1, filename2)
def warn(self, message):
print(colored(message, 'magenta'))
def error(self, message):
print(colored(message, 'red'))
def check_file_exists(self, filename):
r = requests.get(GITHUB_RAW_FILENAME.format(repo=self.repo_name, filename=filename))
return r.status_code == 200
def ensure_repo_set_up(self):
self.repo = self.github.get_repo(self.repo_name)
def ensure_fork_set_up(self):
if self.repo.owner.login != self.user.login:
self.fork = self.user.create_fork(self.repo)
else:
self.fork = self.repo
def clone_fork(self, dirname='.'):
# Go to working directory
os.chdir(dirname)
# Clone the repository
self.run_command('git clone --depth 1 {0}'.format(self.fork.ssh_url))
os.chdir(self.repo.name)
# Make sure the branch doesn't already exist
try:
self.run_command('git checkout origin/{0}'.format(self.branch_name))
except:
pass
else:
raise BranchExistsException()
# Update to the latest upstream master
self.run_command('git remote add upstream {0}'.format(self.repo.clone_url))
self.run_command('git fetch upstream')
self.run_command('git checkout upstream/master')
self.run_command('git checkout -b {0}'.format(self.branch_name))
# Initialize submodules
self.run_command('git submodule init')
self.run_command('git submodule update')
def commit_changes(self):
if self.author_name:
self.run_command('git -c "user.name={0}" '
' -c "user.email={1}" '
' commit -m "{2}"'.format(self.author_name,
self.author_email,
self.commit_message))
else:
self.run_command('git commit -m "{0}"'.format(self.commit_message))
def open_pull_request(self):
self.run_command('git push https://astrobot:{0}@github.com/{1} {2}'.format(self.token, self.fork.full_name, self.branch_name))
result = self.repo.create_pull(title=self.pull_request_title,
body=self.pull_request_body,
base='master',
head='{0}:{1}'.format(self.fork.owner.login, self.branch_name))
return result.html_url
def run_command(self, command):
print(" > {0}".format(command))
p = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
p.wait()
output = p.communicate()[0].decode('utf-8').strip()
if ('--verbose' in sys.argv or p.returncode != 0) and output:
print(indent(output, ' ' * 4))
if p.returncode == 0:
return output
else:
raise Exception("Command '{0}' failed".format(command))
@abc.abstractmethod
def process_repo(self):
pass
@abc.abstractproperty
def branch_name(self):
pass
@abc.abstractproperty
def commit_message(self):
pass
@abc.abstractproperty
def pull_request_body(self):
pass
| [
"thomas.robitaille@gmail.com"
] | thomas.robitaille@gmail.com |
d5cc595979455d5e2cefd473cdc1d313daa2943f | ea872f0a2bcc4270b7089120e3eb2f8dd32a165e | /Baxter/devel/lib/python2.7/dist-packages/ric_board/msg/_Named_Data.py | ef3e76ac2b7e06e7ba4ae90f31c0d93c6b47d1fb | [] | no_license | ZhenYaGuo/Warehouse-Robotic-System | 2def137478911f499c45276aa3103a0b68ebb8d7 | 47b78d111b387102e29d2596bd5dc7c704f74f8f | refs/heads/master | 2021-08-24T04:12:43.379580 | 2017-12-08T01:48:09 | 2017-12-08T01:48:09 | 113,405,332 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,452 | py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from ric_board/Named_Data.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class Named_Data(genpy.Message):
_md5sum = "14a4844ed23f715d29194ae2fc141a58"
_type = "ric_board/Named_Data"
_has_header = False #flag to mark the presence of a Header object
_full_text = """float32 data
string name
"""
__slots__ = ['data','name']
_slot_types = ['float32','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
data,name
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(Named_Data, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.data is None:
self.data = 0.
if self.name is None:
self.name = ''
else:
self.data = 0.
self.name = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
buff.write(_struct_f.pack(self.data))
_x = self.name
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
start = end
end += 4
(self.data,) = _struct_f.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.name = str[start:end].decode('utf-8')
else:
self.name = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.write(_struct_f.pack(self.data))
_x = self.name
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
start = end
end += 4
(self.data,) = _struct_f.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.name = str[start:end].decode('utf-8')
else:
self.name = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
_struct_f = struct.Struct("<f")
| [
"31947861+ZhenYaGuo@users.noreply.github.com"
] | 31947861+ZhenYaGuo@users.noreply.github.com |
f81673adb2493b5d2d8ac7090a4f0b33f6e6cdc1 | e9e91f17b6ad129923ddb9e5cd086d0cef150a1f | /novel_site/apps/novel/migrations/0002_auto_20181012_1146.py | b8fca43b376cbfb2df558c1e3b976142b8ecd4d0 | [] | no_license | gzgdouru/novel_site | 45148b56521e23399d3289bee9c73b1c46145cd3 | 8879217f6dcc5f657adefaeb9d18914ce1dd9d90 | refs/heads/master | 2020-04-06T12:50:46.436608 | 2018-11-14T01:46:12 | 2018-11-14T01:46:12 | 146,424,571 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 540 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-10-12 11:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('novel', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='novel',
name='image',
field=models.ImageField(blank=True, default='default_novel.jpg', max_length=200, null=True, upload_to='novel/', verbose_name='小说图片'),
),
]
| [
"18719091650@163.com"
] | 18719091650@163.com |
f141b66fb751e15b9e5d356d965e6aa9723b10f0 | bb6ebff7a7f6140903d37905c350954ff6599091 | /chrome/common/extensions/docs/server2/whats_new_data_source.py | fd26764017dd1bd3f012009ae3dd3526d222e101 | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | Python | false | false | 3,498 | py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from itertools import groupby
from operator import itemgetter
import posixpath
from data_source import DataSource
from extensions_paths import JSON_TEMPLATES, PUBLIC_TEMPLATES
from future import Future
class WhatsNewDataSource(DataSource):
''' This class creates a list of "what is new" by chrome version.
'''
def __init__(self, server_instance, _):
self._parse_cache = server_instance.compiled_fs_factory.ForJson(
server_instance.host_file_system_provider.GetTrunk())
self._object_store = server_instance.object_store_creator.Create(
WhatsNewDataSource)
self._api_models = server_instance.api_models
self._availability_finder = server_instance.availability_finder
self._api_categorizer = server_instance.api_categorizer
def _GenerateChangesListWithVersion(self, platform, whats_new_json):
return [{
'id': change_id,
'type': change['type'],
'description': change['description'],
'version': change['version']
} for change_id, change in whats_new_json.iteritems()]
def _GetAPIVersion(self, platform, api_name):
version = None
category = self._api_categorizer.GetCategory(platform, api_name)
if category == 'chrome':
channel_info = self._availability_finder.GetAPIAvailability(
api_name).channel_info
channel = channel_info.channel
if channel == 'stable':
version = channel_info.version
return version
def _GenerateAPIListWithVersion(self, platform):
data = []
for api_name, api_model in self._api_models.IterModels():
version = self._GetAPIVersion(platform, api_name)
if version:
api = {
'name': api_name,
'description': api_model.description,
'version' : version,
'type': 'apis',
}
data.append(api)
data.sort(key=itemgetter('version'))
return data
def _GenerateWhatsNewDict(self):
whats_new_json_future = self._parse_cache.GetFromFile(
posixpath.join(JSON_TEMPLATES, 'whats_new.json'))
def _MakeDictByPlatform(platform):
whats_new_json = whats_new_json_future.Get()
platform_list = []
apis = self._GenerateAPIListWithVersion(platform)
apis.extend(self._GenerateChangesListWithVersion(platform,
whats_new_json))
apis.sort(key=itemgetter('version'), reverse=True)
for version, group in groupby(apis, key=itemgetter('version')):
whats_new_by_version = {
'version': version,
}
for item in group:
item_type = item['type']
if item_type not in whats_new_by_version:
whats_new_by_version[item_type] = []
whats_new_by_version[item_type].append(item)
platform_list.append(whats_new_by_version)
return platform_list
def resolve():
return {
'apps': _MakeDictByPlatform('apps'),
'extensions': _MakeDictByPlatform('extensions')
}
return Future(callback=resolve)
def _GetCachedWhatsNewData(self):
data = self._object_store.Get('whats_new_data').Get()
if data is None:
data = self._GenerateWhatsNewDict().Get()
self._object_store.Set('whats_new_data', data)
return data
def get(self, key):
return self._GetCachedWhatsNewData().get(key)
def Cron(self):
return self._GenerateWhatsNewDict()
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
087ad34833a0b4b6cd390d4910591bafd8977bfd | 8636c0fba825b4b7c5ca30c202e2e09afaf05e95 | /practicing_apps/tkinterTermoJuevesII/main.py | 83fcef9d568ca215f8376ab16bbc5dd075c81e6c | [] | no_license | manuetov/m02_boot_0 | 33fe5876ab0fbbcfcb08e2ccaee5144a57d71c57 | 04d3dceffda78b37a709cd08ef7a1dc1d31478b4 | refs/heads/master | 2021-10-12T02:45:55.161385 | 2019-01-31T20:27:14 | 2019-01-31T20:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,039 | py | from tkinter import *
from tkinter import ttk
class NumberEntry(ttk.Entry)
class mainApp(Tk):
entrada = None
tipoUnidad = None
__temperaturaAnt = ""
def __init__(self):
Tk.__init__(self)
self.title("Termómetro")
self.geometry("210x150")
self.configure(bg="#ECECEC")
self.resizable(0,0)
self.temperatura = StringVar(value="")
self.temperatura.trace("w", self.validateTemperature)
self.tipoUnidad = StringVar(value="F")
self.createLayout()
def createLayout(self):
self.entrada = ttk.Entry(self, textvariable=self.temperatura).place(x=10, y=10)
self.lblUnidad = ttk.Label(self, text="Grados:").place(x=10, y=50)
self.rb1 = ttk.Radiobutton(self, text="Fahrenheit", variable=self.tipoUnidad, value="F",command=self.selected).place(x=20, y=70)
self.rb2 = ttk.Radiobutton(self, text="Celsius", variable=self.tipoUnidad, value="C", command=self.selected).place(x=20, y=95)
def start(self):
self.mainloop()
def validateTemperature(self, *args):
nuevoValor = self.temperatura.get()
print("nuevoValor", nuevoValor,"vs valorAnterior", self.__temperaturaAnt)
try:
float(nuevoValor)
self.__temperaturaAnt = nuevoValor
print("fija valor anterior a", self.__temperaturaAnt)
except:
self.temperatura.set(self.__temperaturaAnt)
print("recupera valor anterior ", self.__temperaturaAnt)
def selected(self):
resultado = 0
toUnidad = self.tipoUnidad.get()
grados = float(self.temperatura.get())
if toUnidad == 'F':
resultado = grados * 9/5 + 32
elif toUnidad == 'C':
resultado = (grados - 32) * 5/9
else:
resultado = grados
self.temperatura.set(resultado)
if __name__ == '__main__':
app = mainApp()
app.start() | [
"monterdi@gmail.com"
] | monterdi@gmail.com |
9b13a527404e03d33c008e8e26f41f9477864f2a | b99195cf2d181dec5c31aa7e58d747f474153802 | /Decision making and loop/Find Armstrong Number in an Interval.py | 535db3c64285194403e3dc59dbe320ff35181beb | [] | no_license | eldadpuzach/MyPythonProjects | b1b4d56a822fd781c7c4c7a9e4bb5408c180c187 | 3a961a7c265caf1369067d98e94564f01f1bde74 | refs/heads/master | 2020-03-20T18:07:43.319331 | 2019-02-13T22:07:10 | 2019-02-13T22:07:10 | 137,570,971 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 475 | py | # check Armstrong numbers in certain interval
# To take input from the user
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower, upper + 1):
# order of number
order = len(str(num))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
| [
"eldadpuzach@gmail.com"
] | eldadpuzach@gmail.com |
ef2f06d85a6c61ac5b042627f79667fcc7c3e334 | 82ffae21bc27e91643bcc344c89d2684b1105e56 | /train.py | bd024a2c5a3e7d90fe3700f9cf7ac95daa909997 | [] | no_license | liuchongwei/IB-INN | 4f4df0a0f9295fa4d9cc900170d1b7b59217dd7e | 440b75d5fbafec75842b18c9e7b6f03a8d76d16d | refs/heads/master | 2023-04-08T11:51:39.745227 | 2021-04-15T17:25:30 | 2021-04-15T17:25:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,366 | py | from os.path import join
from time import time
import sys
import numpy as np
from tqdm import tqdm
import torch.optim
import data
from model import GenerativeClassifier
from VIB import WrapperVIB
import evaluation
def train(args):
N_epochs = eval(args['training']['n_epochs'])
beta = eval(args['training']['beta_IB'])
train_nll = bool(not eval(args['ablations']['no_NLL_term']))
train_class_nll = eval(args['ablations']['class_NLL'])
label_smoothing = eval(args['data']['label_smoothing'])
grad_clip = eval(args['training']['clip_grad_norm'])
train_vib = eval(args['ablations']['vib'])
interval_log = eval(args['checkpoints']['interval_log'])
interval_checkpoint = eval(args['checkpoints']['interval_checkpoint'])
interval_figure = eval(args['checkpoints']['interval_figure'])
save_on_crash = eval(args['checkpoints']['checkpoint_when_crash'])
output_dir = args['checkpoints']['output_dir']
resume = args['checkpoints']['resume_checkpoint']
ensemble_index = eval(args['checkpoints']['ensemble_index'])
if ensemble_index is None:
ensemble_str = ''
else:
ensemble_str = '.%.2i' % (ensemble_index)
logfile = open(join(output_dir, f'losses{ensemble_str}.dat'), 'w')
live_loss = eval(args['checkpoints']['live_updates'])
if train_vib:
inn = WrapperVIB(args)
else:
inn = GenerativeClassifier(args)
inn.cuda()
dataset = data.Dataset(args)
def log_write(line, endline='\n'):
print(line, flush=True)
logfile.write(line)
logfile.write(endline)
plot_columns = ['time', 'epoch', 'iteration',
'L_x_tr',
'L_x_val',
'L_y_tr',
'L_y_val',
'acc_tr',
'acc_val',
'delta_mu_val']
train_loss_names = [l for l in plot_columns if l[-3:] == '_tr']
val_loss_names = [l for l in plot_columns if l[-4:] == '_val']
header_fmt = '{:>15}' * len(plot_columns)
output_fmt = '{:15.1f} {:04d}/{:04d} {:04d}/{:04d}' + '{:15.5f}' * (len(plot_columns) - 3)
output_fmt_live = '{:15.1f} {:04d}/{:04d} {:04d}/{:04d}'
for l_name in plot_columns[3:]:
if l_name in train_loss_names:
output_fmt_live += '{:15.5f}'
else:
output_fmt_live += '{:>15}'.format('')
if eval(args['training']['exponential_scheduler']):
print('Using exponential scheduler')
sched = torch.optim.lr_scheduler.StepLR(inn.optimizer, gamma=0.002 ** (1/N_epochs), step_size=1)
else:
print('Using milestone scheduler')
sched = torch.optim.lr_scheduler.MultiStepLR(inn.optimizer, gamma=0.1,
milestones=eval(args['training']['scheduler_milestones']))
log_write(header_fmt.format(*plot_columns))
if resume:
inn.load(resume)
t_start = time()
if train_nll:
beta_x = 2. / (1 + beta)
beta_y = 2. * beta / (1 + beta)
else:
beta_x, beta_y = 0., 1.
try:
for i_epoch in range(N_epochs):
running_avg = {l: [] for l in train_loss_names}
for i_batch, (x,l) in enumerate(dataset.train_loader):
x, y = x.cuda(), dataset.onehot(l.cuda(), label_smoothing)
losses = inn(x, y)
if train_class_nll:
loss = 2. * losses['L_cNLL_tr']
else:
loss = beta_x * losses['L_x_tr'] - beta_y * losses['L_y_tr']
loss.backward()
torch.nn.utils.clip_grad_norm_(inn.trainable_params, grad_clip)
inn.optimizer.step()
inn.optimizer.zero_grad()
if live_loss:
print(output_fmt_live.format(*([(time() - t_start) / 60.,
i_epoch, N_epochs,
i_batch, len(dataset.train_loader)]
+ [losses[l].item() for l in train_loss_names])),
flush=True, end='\r')
for l_name in train_loss_names:
running_avg[l_name].append(losses[l_name].item())
if not i_batch % interval_log:
for l_name in train_loss_names:
running_avg[l_name] = np.mean(running_avg[l_name])
val_losses = inn.validate(dataset.val_x, dataset.val_y)
for l_name in val_loss_names:
running_avg[l_name] = val_losses[l_name].item()
losses_display = [(time() - t_start) / 60.,
i_epoch, N_epochs,
i_batch, len(dataset.train_loader)]
losses_display += [running_avg[l] for l in plot_columns[3:]]
#TODO visdom?
log_write(output_fmt.format(*losses_display))
running_avg = {l: [] for l in train_loss_names}
sched.step()
if i_epoch > 2 and (val_losses['L_x_val'].item() > 1e5 or not np.isfinite(val_losses['L_x_val'].item())):
if high_loss:
raise RuntimeError("loss is astronomical")
else:
high_loss = True
else:
high_loss = False
if i_epoch > 0 and (i_epoch % interval_checkpoint) == 0:
inn.save(join(output_dir, f'model_{i_epoch}{ensemble_str}.pt'))
if (i_epoch % interval_figure) == 0 and not inn.feed_forward and not train_vib:
evaluation.val_plots(join(output_dir, f'figs_{i_epoch}{ensemble_str}.pdf'), inn, dataset)
except:
if save_on_crash:
inn.save(join(output_dir, f'model_ABORT{ensemble_str}.pt'))
raise
finally:
logfile.close()
try:
for k in list(inn.inn._buffers.keys()):
if 'tmp_var' in k:
del inn.inn._buffers[k]
except AttributeError:
# Feed-forward nets dont have the wierd FrEIA problems, skip
pass
inn.save(join(output_dir, f'model{ensemble_str}.pt'))
| [
"lynton.ardizzone@iwr.uni-heidelberg.de"
] | lynton.ardizzone@iwr.uni-heidelberg.de |
db1c8172d34f9db120085047d2d4df1f2e1ce3c5 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_152/ch40_2020_09_28_14_38_11_448144.py | 869700df39676380d5c581c9967c8ac41f46af87 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 144 | py | def soma_valores(lista):
soma = 0
i = 0
size = len(lista)
while(i<size):
soma += lista[i]
i += 1
return soma | [
"you@example.com"
] | you@example.com |
f36445558f08904ce3cbc28219071f55910a3326 | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-5/04c0870f3abb72e4d68e5e712e5eb4445eff4161-<_get_lzma_file>-fix.py | 406e9e4f070822a7fc5cd2a117bdddaaa5b300af | [] | no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 504 | py | def _get_lzma_file(lzma):
"\n Importing the `LZMAFile` class from the `lzma` module.\n\n Returns\n -------\n class\n The `LZMAFile` class from the `lzma` module.\n\n Raises\n ------\n RuntimeError\n If the `lzma` module was not imported correctly, or didn't exist.\n "
if (lzma is None):
raise RuntimeError('lzma module not available. A Python re-install with the proper dependencies, might be required to solve this issue.')
return lzma.LZMAFile | [
"dg1732004@smail.nju.edu.cn"
] | dg1732004@smail.nju.edu.cn |
f99a2d4d664426b40ad53acceb227493989c5cfa | d5905fa195a09883da60c584fd547e7cc5adab6a | /circhic/tests/test_utils.py | 34c41f3fab1f561a54ee31f51e964051f2cea0fb | [
"BSD-3-Clause"
] | permissive | ijunier/circhic_dev | 1370182f5a92d32d384f5d99a0556836d88cccb8 | d312cebd555058859daa7bf0bb5aabcc18ecd748 | refs/heads/master | 2023-01-07T20:43:22.449704 | 2020-07-20T13:20:41 | 2020-07-20T13:20:41 | 275,118,657 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 571 | py | from circhic import utils
import numpy as np
import pytest
def test_convert_xy_to_thetar():
lengths = np.array([42])
random_state = np.random.RandomState(seed=42)
n = 100
x = random_state.randint(0, lengths.sum(), n)
y = random_state.randint(0, lengths.sum(), n)
# Flush test to check the code runs
theta, r = utils.convert_xy_to_thetar((x, y), lengths)
with pytest.raises(ValueError):
utils.convert_xy_to_thetar((x, y[:-1]), lengths)
with pytest.raises(ValueError):
utils.convert_xy_to_thetar((x+42, y), lengths)
| [
"nelle.varoquaux@gmail.com"
] | nelle.varoquaux@gmail.com |
b17418f3c281dddaa920214c07c65cae375c55ba | 1587aad7b5df3159015a06ec70137ca9cbdb74d3 | /Fundamentals/Basics/comparearrays.py | af84baa6c18f4cfe6a49aef6c53112e5dedb44a5 | [] | no_license | brysonmckenzie/Python-Flask-Django | 21d7302401859dc7a3ade677238f739f32e87aaa | 38460ff4f321906b57c9c0167278e774e791a327 | refs/heads/master | 2021-01-18T16:37:19.737987 | 2017-08-16T08:16:35 | 2017-08-16T08:16:35 | 100,465,043 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 292 | py | def CompareArrays(arr1,arr2):
if len(arr1) != len (arr2):
return False
elif len(arr1) == len (arr2):
for i in arr1:
if arr1 != arr2:
print arr1,arr2
return False
else:
return True
| [
"brysonmckenzie83@gmail.com"
] | brysonmckenzie83@gmail.com |
75a8c49083279d509530d4fc722e78913c10ba38 | 8c2791898f9bd5640353a7ba8088b6263da0ffa3 | /client/commands/__init__.py | 8035b273e180ba4438600a4f4d31eb92dd6db582 | [
"MIT"
] | permissive | dalejung/pyre-check | 570e123da8097cbceb331638ef915da410d05a85 | 1bcd0a68ff5dc6e4ab36992088de5a6cb5a82531 | refs/heads/master | 2020-03-25T22:43:20.049890 | 2018-08-10T04:46:04 | 2018-08-10T04:48:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 854 | py | # Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from .analyze import Analyze as Analyze # noqa
from .check import Check as Check # noqa
from .error_handling import ErrorHandling as ErrorHandling # noqa
from .incremental import Incremental as Incremental # noqa
from .initialize import Initialize as Initialize # noqa
from .kill import Kill as Kill # noqa
from .persistent import Persistent as Persistent # noqa
from .query import Query as Query # noqa
from .rage import Rage as Rage # noqa
from .restart import Restart as Restart # noqa
from .start import Start # noqa
from .stop import Stop as Stop # noqa
from .command import ( # noqa; noqa; noqa
ClientException as ClientException,
Command as Command,
)
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
5675bc2d9d63337fe3c0cd7ce20077b8d0f5b066 | 553965e00fe5d7ba217b399d1b36f603743c9724 | /chromeos/components/file_manager/resources/gen_main_html.py | 624c8f318a61226d9874bfdf729c6e84e40f4cb0 | [
"BSD-3-Clause"
] | permissive | zoracon/chromium | 3892e77996c03807c7fb96f535d84745e6540a8c | eaa78fd27b11621c877c62e022f1c0c4f47c5c12 | refs/heads/master | 2023-01-02T17:18:46.663596 | 2020-11-18T18:56:44 | 2020-11-18T18:56:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,214 | py | #!/usr/bin/env python
#
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generate SWA files app main.html from files app main.html"""
import fileinput
import optparse
import os
import shutil
import sys
_SWA = '<script type="module" src="chrome://file-manager/main.js"></script>'
def GenerateSwaMainHtml(source, target, root):
"""Copy source file to target, do SWA edits, then add BUILD time stamp."""
# Copy source (main.html) file to the target (main.html) file.
shutil.copyfile(source, target)
# Edit the target file.
for line in fileinput.input(target, inplace=True):
# Add _SWA <script> tag after the <head> tag.
if line.find('<head>') >= 0:
print line + ' ' + _SWA
# Add <meta> charset="utf-8" attribute.
elif line.find('<meta ') >= 0:
sys.stdout.write(line.replace('<meta ', '<meta charset="utf-8" '))
# Root rewrite files app <link> stylesheet href attribute.
elif line.find('<link rel="stylesheet"') >= 0:
if not 'href="chrome://' in line:
href = 'href="' + root + 'ui/file_manager/file_manager/'
sys.stdout.write(line.replace('href="', href))
else:
sys.stdout.write(line)
# Remove files app foreground/js <script> tags: SWA app must lazy-load
# them after the SWA app has initialized needed resources.
elif line.find('<script src="foreground/js/') == -1:
sys.stdout.write(line)
# Create a BUILD time stamp for the target file.
open(target + '.stamp', 'a').close()
def main(args):
parser = optparse.OptionParser()
parser.add_option('--source', help='Files app main.html source file.')
parser.add_option('--target', help='Target SWA main.html for output.')
parser.add_option('--root', help='Source root: chrome/src path.')
options, _ = parser.parse_args(args)
if options.source and options.target and options.root:
target = os.path.join(os.getcwd(), options.target)
GenerateSwaMainHtml(options.source, target, options.root)
return
raise SyntaxError('Usage: all arguments are required.')
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4eae384c04fc6ece4f04f2b9d2b08fa2e38fe0ba | 9716a77ef1d0ba5ef9a61be04f6229494744d5d5 | /chapter06 정렬/수 정렬하기3.py | 8e0a8c303ae70ce83339bf67079a86549562e250 | [] | no_license | korea-space-codingmonster/Algorithm_Study | 98b00c81839cf8ac8365d3982c25650a21226ce9 | 8c92857e458994a2d1d77dc3ea0d4b645b8b6a4b | refs/heads/main | 2023-06-03T20:00:52.915447 | 2021-06-20T05:51:47 | 2021-06-20T05:51:47 | 329,354,196 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 573 | py | # 문제
# N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
# 입력
# 첫째 줄에 수의 개수 N(1 ≤ N ≤ 10,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 숫자가 주어진다. 이 수는 10,000보다 작거나 같은 자연수이다.
# 출력
# 첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
# 예제 입력 1 복사
# 10
# 5
# 2
# 3
# 1
# 4
# 2
# 3
# 5
# 1
# 7
# 예제 출력 1 복사
# 1
# 1
# 2
# 2
# 3
# 3
# 4
# 5
# 5
# 7
| [
"replituser@example.com"
] | replituser@example.com |
6a712c9174d946d711b862d455e296f516466cbb | e7f67295e62fc5301ab23bce06c61f2311c2eeee | /mjml/helpers/py_utils.py | 945f8f9a0e51353211751f6935e021af74d3e325 | [
"MIT"
] | permissive | bayesimpact/mjml-stub | 94d10588359990cd58d2085429b19a3777c51f15 | 30bab3f2e197d2f940f58439f2e8cd9fadb58d48 | refs/heads/main | 2023-05-08T11:54:19.313877 | 2021-01-25T21:30:48 | 2021-01-25T21:30:48 | 344,026,118 | 0 | 0 | MIT | 2021-03-03T06:31:49 | 2021-03-03T06:31:48 | null | UTF-8 | Python | false | false | 1,037 | py |
import re
__all__ = [
'is_nil',
'is_empty',
'is_not_empty',
'is_not_nil',
'omit',
'parse_float',
'parse_int',
'strip_unit',
]
def omit(attributes, keys):
if isinstance(keys, str):
keys = (keys, )
_attrs = dict(attributes)
for key in keys:
if key in _attrs:
_attrs.pop(key)
return _attrs
def parse_float(value_str):
match = re.search(r'^([-+]?\d+(.\d+)?)*', value_str)
return float(match.group(1))
def parse_int(value_str):
if isinstance(value_str, int):
return value_str
match = re.search(r'^([-+]?\d+)*', value_str)
return int(match.group(1))
def strip_unit(value_str):
match = re.search(r'^(\d+).*', value_str)
return int(match.group(1))
def is_nil(v):
return (v is None)
def is_not_nil(v):
return not is_nil(v)
def is_empty(v):
if v is None:
return True
elif hasattr(v, 'strip'):
return not bool(v.strip())
return not bool(v)
def is_not_empty(v):
return not is_empty(v)
| [
"felix.schwarz@oss.schwarz.eu"
] | felix.schwarz@oss.schwarz.eu |
619e77d5ddd1def133e212f22da11d5ffd178366 | 639b8dee007e50e64f1cbb94c2f06f114c7824c8 | /config/config.py | 25ecdf38a473f3adc73cbef56ebd86cde3e49f6a | [] | no_license | mskoko/Voice-assistant | 42f40b457f06a16e26b408e5a2368b0b69360634 | d46f2cc13115c6e8261d8ce8c0534fb62692621f | refs/heads/master | 2022-12-03T10:17:55.459744 | 2020-08-15T13:17:50 | 2020-08-15T13:17:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,990 | py | # - *- coding: utf- 8 - *-
import logging
import os
LOG_FILE = "voice_assistant.log"
logging.basicConfig(level=logging.DEBUG, filename="voice_assistant.log",
format='%(asctime)s: %(levelname)s - %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging
# logging - debug, info, warning, error, critical
PROVIDED_LANGUAGES = {
"english": "en-US",
"serbian": "sr-RS",
"default": "en-US"
}
LANGUAGES_IN_SERBIAN = os.path.abspath("data/languages/langs_in_serbian.json")
LANG_CODES = "data/languages/langs_codes.json"
RECOGNITION_METHODS = {
"bing": "recognize_bing",
"google": "recognize_google",
"google_cloud": "recognize_google_cloud",
"houndify": "recognize_houndify",
"ibm": "recognize_ibm",
"sphinx": "recognize_sphinx",
"wit": "recognize_wit",
"azure": "recognize_azure"
}
# tts audio config
PATH_TO_AUDIO_DIR = r"data/audio/"
DEFAULT_AUDIO_FILE = PATH_TO_AUDIO_DIR + "temporary.mp3"
# semantic processor
ENGLISH_DICTIONARY_PATH = "data/words/words-en.json"
SERBIAN_DICTIONARY_PATH = "data/words/words-sr.json"
# keywords
ENGLISH_KEYWORDS = "data/keywords/keywords-en.json"
SERBIAN_KEYWORDS = "data/keywords/keywords-sr.json"
LANG_KEYWORDS = {
"en": ENGLISH_KEYWORDS,
"sr": SERBIAN_KEYWORDS
}
# messages
CALL_MESSAGE = {"en": "I'm ready for a new command", "sr": "Spreman sam za novu komandu."}
# commands
COMMANDS = "data/commands/commands.json"
# TODO: refactor path variables to be in dictionary form for simpler usage
# action result statuses
SUCCESS = 1
FAIL = 0
FATAL = -1
# exception messages
GENERIC_MESSAGE_EN = "Some internal error occurred. Check the log for more details!"
GENERIC_MESSAGE_SR = "Došlo je do interne greške. Proverite log fajl za više detalja!"
EXCEPTION_MESSAGES = {
"KeyError": {
"en": GENERIC_MESSAGE_EN,
"sr": GENERIC_MESSAGE_SR
},
"TypeError": {
"en": GENERIC_MESSAGE_EN,
"sr": GENERIC_MESSAGE_SR
},
"ValueError": {
"en": GENERIC_MESSAGE_EN,
"sr": GENERIC_MESSAGE_SR
},
"AssertionError": {
"en": GENERIC_MESSAGE_EN,
"sr": GENERIC_MESSAGE_SR
},
"IndexError": {
"en": GENERIC_MESSAGE_EN,
"sr": GENERIC_MESSAGE_SR
},
"speech_recognition.UnknownValueError": {
"en": "Speech cannot be analyzed or recognized!",
"sr": "Vaš govor ne može biti obrađen ili prepoznat!"
},
"speech_recognition.RequestError": {
"en": "Request error problem. Check API limits and connectivity status!",
"sr": "Problemi sa slanjem zahteva. Proverite API limit i status mreže!"
},
# TODO: handle when error occurs in speaking module - how to inform user
"gtts.tts.gTTSError": {
"en": "I have a problem with speaking. Probably you reached out the API limit!",
"sr": "Imam problem sa govorom. Verovatno si probio API limit!"
},
"pyowm.exceptions.api_response_error.NotFoundError": {
"en": "The weather forecast cannot be estimated. I cannot find that location!",
"sr": "Ne mogu da procenim vremensku prognozu. Ne mogu da pronađem tu lokaciju!"
},
"pyowm.exceptions.api_call_error.APICallError": {
"en": "The weather forecast cannot be estimated. I cannot find that location!",
"sr": "Ne mogu da procenim vremensku prognozu. Ne mogu da pronađem tu lokaciju!"
},
"smtplib.SMTPAuthenticationError":
{
"en": "There is some problem with email authentication. Check your email address credentials.",
"sr": "Došlo je do problema sa autentifikacijom email naloga. Proveri kredencijale."
},
"smtplib.SMTPNotSupportedError": {
"en": "There is some problem with email settings configuration.",
"sr": "Postoje određeni problemi sa podešavanjima emaila."
},
"smtplib.SMTPHeloError": {
"en": "There is some problem with email settings configuration.",
"sr": "Postoje određeni problemi sa podešavanjima emaila."
},
"smtplib.SMTPDataError": {
"en": "There is some problem with email settings configuration.",
"sr": "Postoje određeni problemi sa podešavanjima emaila."
},
"smtplib.SMTPConnectError": {
"en": "There is some problem with an email connection.",
"sr": "Postoje određeni problemi sa konekcijom ka emaila serveru."
},
"smtplib.SMTPServerDisconnected": {
"en": "There is some problem with an email connection.",
"sr": "Postoje određeni problemi sa konekcijom ka emaila serveru."
},
"smtplib.SMTPSenderRefused": {
"en": "Sender's email settings are not valid.",
"sr": "Postoje određeni problemi sa podešavanjima emaila pošiljaoca."
},
"smtplib.SMTPRecipientsRefused": {
"en": "Recipient's email settings are not valid. Check the recipient's email address.",
"sr": "Postoje određeni problemi sa podešavanjima emaila primaoca. Proveri da li si uneo validnu adresu."
},
"wikipedia.exceptions.PageError": {
"en": "I cannot find anything on Wikipedia that suits your query. Try another one or try again with more precise"
" speech.",
"sr": "Nisam uspeo da nađem ništa na Vikipediji što odgovara tvom zahtevu. Probaj sa nekim drugim zahtevom ili probaj"
"ponovo, ali probaj da budeš precizniji u govoru."
},
"exceptions.exceptions.GoogleSearchException": {
"en": "Google search cannot find anything that suits your query.",
"sr": "Gugl pretraga nije našla ništa što odgovara tvom upitu."
},
"exceptions.exceptions.VoiceAssistantException": {
"en": "Fatal error. The application could not proceed.",
"sr": "Došlo je do fatalne interne greške. Aplikacija ne može nastaviti sa radom."
},
"exception": {
"en": GENERIC_MESSAGE_EN,
"sr": GENERIC_MESSAGE_SR
}
}
# credentials
OWM_API_KEY = "5ab8013f8b3c54d28b8f8035ffd40f0a"
OMDB_API_KEY = "56674ea0"
PROXY_MAIL = "lindo.voice.assistant@gmail.com"
MAIL_PASSWORD = "mizcechlykbgsfhx"
# weather params
# NOTE: only some of params are included (most important ones)
WEATHER_PARAMS = {"clouds", "detailed_status", "dewpoint", "heat_index", "humidex", "humidity", "pressure", "rain",
"reference_time", "snow", "status", "sunrise_time", "sunset_time", "temperature",
"visibility_distance", "weather_code", "weather_icon_name", "weather_icon_url", "wind"}
# format <name in json response>: (json_subvalue or alias, child/alias, display name)
# hr stands for croatian _language because OWM API doesn't support serbian, so instead of serbian (sr),
# croatian _language is used (hr)
WEATHER_PARAMETERS = {
"clouds": ("clouds", "alias", {"en": "clouds", "hr": "oblačnost"}),
"pressure": ("press", "child", {"en": "pressure", "hr": "pritisak"}),
"wind": ("speed", "child", {"en": "wind speed", "hr": "brzina vetra"}),
# "snow":("snow", "child", ),
"humidity": ("humidity", "alias", {"en": "humidity", "hr": "vlažnost vazduha"}),
"temperature_min": ("temp_min", "child", {"en": "minimum temperature", "hr": "minimalna dnevna temperatura"}),
"temperature_max": ("temp_max", "child", {"en": "maximum temperature", "hr": "maksimalna dnevna temperatura"}),
"temperature": ("temp", "child", {"en": "temperature", "hr": "prosečna dnevna temperatura"}),
"detailed_status": ("detailed_status", "alias", {"en": "detailed status", "hr": "detaljniji opis"}),
"reference_time": ("reference_time", "alias", {"en": "reference time", "hr": "trenutak merenja"})
# "rain":{}
}
# social networks urls
FACEBOOK_BASE_URL = "https://www.facebook.com/"
TWITTER_BASE_URL = "https://twitter.com/"
INSTAGRAM_BASE_URL = "https://instagram.com/"
LINKEDIN_BASE_URL = "https://www.linkedin.com/in/"
# serial communication params
SERIAL_PORT = "/dev/ttyUSB0"
DEFAULT_BAUD_RATE = 9600
| [
"nenadpantelickg@gmail.com"
] | nenadpantelickg@gmail.com |
754374375b34782f7c5e7f47fac2212c270272c6 | cfdf0fde6786c160e059502d3c4d5f679d63867e | /myApp/apiApp/management/commands/fetch.py | d10c7e295cf0280c2ed66fa3d529329481a42c20 | [
"MIT"
] | permissive | mdmarjanhossain0/Django-Demo-for-client | 30a89989c1e5446175377c174024ddc02cb3c660 | 5f345b2c9ec35f4d7210ce0de5fc7c2f36a33427 | refs/heads/main | 2023-07-13T23:38:34.992579 | 2021-08-18T13:54:19 | 2021-08-18T13:54:19 | 397,874,162 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,162 | py | from django.core.management.base import BaseCommand
import django
import os
import requests
from apiApp import models
class Command(BaseCommand):
help = 'Fetch Data From API.'
def handle(self, *args, **kwargs):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myApp.settings")
django.setup()
response = requests.get('https://restcountries.eu/rest/v2/all').json()
for data in response:
try:
table = models.ApiApp()
table.name = data.get('name')
table.alpha2code = data.get('alpha2code')
table.alpha3code = data.get('alpha3code')
table.capital = data.get('capital')
table.population = data.get('population')
table.timezones = data.get('timezones')
table.languages = data.get('languages')
table.borders = data.get('borders')
table.save()
print("Please Wait...")
except Exception as ex:
print(ex)
# print("Could Not Save: ", data.get('name'))
self.stdout.write("Action Completed!")
| [
"airriaislam@gmail.com"
] | airriaislam@gmail.com |
8cb7bea7bd989fe62805917eb6e5763389439f49 | a4ea28288898ff957d69f4fff2ea353aac09ec48 | /commander/thirdparty/covertutils/handlers/responseonly.py | 486eba43da1dfcdee6de07212316f213e5670f51 | [
"Apache-2.0"
] | permissive | how2how/ToyHome | d520b453b17a2bcd08e204cf209333cb02d2a3cf | 4457b1d28e21ed6fd4ab980a0f7fed345c570ae3 | refs/heads/master | 2021-06-19T16:51:44.116241 | 2019-09-18T16:43:26 | 2019-09-18T16:43:26 | 148,563,602 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,364 | py | from abc import ABCMeta, abstractmethod
from covertutils.handlers import BaseHandler
from covertutils.helpers import defaultArgMerging
class ResponseOnlyHandler( BaseHandler ) :
"""
This handler doesn't send messages with the `sendAdHoc` method. It implements a method `queueSend` to queue messages, and send them only if it is queried with a `request_data` message.
Can be nicely paired with :class:`covertutils.handlers.InterrogatingHandler` for a Client-Server approach.
"""
__metaclass__ = ABCMeta
Defaults = {'request_data' : 'X'}
def __init__( self, recv, send, orchestrator, **kw ) :
"""
:param str request_data: The data that, when received as message, a stored chunk will be sent.
"""
super(ResponseOnlyHandler, self).__init__( recv, send, orchestrator, **kw )
arguments = defaultArgMerging( self.Defaults, kw )
self.request_data = arguments['request_data']
self.preferred_send = self.queueSend
def onMessage( self, stream, message ) :
beacon = (message == self.request_data) # got a beacon message?
# if beacon :
# print "List of messages '%s' " % self.to_send_list
# if not self.readifyQueue() : return False
self.readifyQueue()
# print "Raw packets pending: %s" % len(self.to_send_raw)
if self.to_send_raw :
to_send = self.to_send_raw.pop(0)
self.send_function( to_send )
return True
return False
| [
"test@test.com"
] | test@test.com |
4482823c9b7d35b19f0b0ea846cfe8c197e4ca64 | 1c751c001357d23fe10e7a42490e3b76434dfa18 | /tools/py/zzcat.py | ba0a398a4f941704bfc9fae8f1c75e1a41730fa8 | [] | no_license | pie-crust/etl | 995925199a71b299544bfac1ed8f504f16fbadc2 | 14b19b542eaa69b8679ce7df4d9a5d2720b3c5c7 | refs/heads/master | 2022-12-12T18:40:31.866907 | 2019-10-14T15:46:16 | 2019-10-14T15:46:16 | 215,082,544 | 0 | 0 | null | 2022-12-08T05:22:54 | 2019-10-14T15:43:04 | Python | UTF-8 | Python | false | false | 1,180 | py | #!~/python27/bin/python
#s3://home-pmt-accounting-dev/racct/DY_Position_SD/file_0_100.2019-06-17.13_39_12.IQ.csv.gz test.csv.gz
from boto.s3.connection import S3Connection
import gzip
import csv
import io
class ReadOnce(object):
def __init__(self, k):
self.key = k
self.has_read_once = False
def read(self, size=0):
if self.has_read_once:
return b''
data = self.key.read(size)
if not data:
self.has_read_once = True
return data
class ReadFromS3:
def __init__(self, options):
conn = S3Connection()
self.bucket = conn.get_bucket(options['s3']['bucket'], validate=False)
def stream_file(self, file):
key = self.bucket.get_key(file)
gz_file = gzip.GzipFile(fileobj=key, mode='r')
#print gz_file.read(100)
reader = csv.DictReader(io.TextIOWrapper(
gz_file, newline="", encoding="utf-8-sig"), delimiter='\t')
#for line in reader:
# print(line)
def main(options):
tsr = ReadFromS3(options)
tsr.stream_file('racct/DY_Position_SD/file_0_100.2019-06-17.13_39_12.IQ.csv.gz test.csv.gz')
if __name__ == "__main__":
options = {
's3':{
'user': 's_dev_racct',
#'key': ,
'bucket':'home-pmt-accounting-dev',
}
}
main(options)
| [
"olek.buzu@gmail.com"
] | olek.buzu@gmail.com |
1259e96f551d528f6556f7d5d26d78d353838ab1 | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /YqeS2Ta52jyjS7cD7_4.py | b358e4ae709bb1d13c75abcf0c661fd77ecf4fc0 | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 134 | py |
def is_prime(n):
if n == 0 or n == 1:
return False
for i in range(2,n):
if n % i == 0:
return False
return True
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
3e3fdbd3a6d4194fc93724c838eeb04603f31191 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/17/usersdata/71/6755/submittedfiles/lecker.py | f80187761dd3724711eed58af6e9bd198d3cdcc8 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 399 | py | # -*- coding: utf-8 -*-
from __future__ import division
import math
a = input("Insira o valor de a: ")
b = input("Insira o valor de b: ")
c = input("Insira o valor de c: ")
d = input("Insira o valor de d: ")
if a>b and b>=c and c>=d:
print("S")
elif a=<b and b>c and c>=d:
print("S")
elif a=<b and b<c and c>d:
print("S")
elif a=<b and b=<c and c<d:
print("S")
else:
print("N") | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
236cd21d398219589f77bf3b49cc6d3600f4a6ae | 21e73840ea6db347141b7c569bf9e70e617adbd4 | /src/posts/admin.py | 1093ba83e6e05259b916218134bc354c68e2f7b8 | [] | no_license | ratulkhan44/djangoBlog | 4b41e011fddb3095ef5c5ccbab8f711d054ed019 | 1da4a2fe96ae34cebd8d286bc1ab27d1623a7045 | refs/heads/master | 2023-01-23T14:27:08.225993 | 2020-11-28T15:26:17 | 2020-11-28T15:26:17 | 316,205,197 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 257 | py | from django.contrib import admin
from .models import Post, PostView, Like, Comment, User
# Register your models here.
admin.site.register(User)
admin.site.register(Post)
admin.site.register(PostView)
admin.site.register(Comment)
admin.site.register(Like)
| [
"ratulcse.khan@gmail.com"
] | ratulcse.khan@gmail.com |
b0a8b8742f5ffd386452964a27070ef0a186c91f | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_118/2541.py | 2571b77cac41e1d084f5c0929f63a1dc9bec94f1 | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,562 | py | '''
Created on 13/04/2013
@author: Rafael
'''
def cuadradoPalindromos(listaPalindromo):
listResult=[]
for i in listaPalindromo:
listResult.append(i*i)
return listResult
def hallaPalindromo(minNum, maxNum):
list = range(minNum, maxNum + 1)
listPalindromo = []
listaPalindromoCuadrado = []
for i in list:
cad = str(i)
bandera = False
if len(cad) == 1:
listPalindromo.append(i);
else:
if len(cad) % 2 == 0:
pivote = int(len(cad) / 2)
bandera = validaPalindromo(pivote, cad)
else:
pivote = int(len(cad) / 2)
bandera = validaPalindromo(pivote, cad[:pivote] + cad[pivote + 1:])
if(bandera == True):
listPalindromo.append(i)
listaPalindromoCuadrado = cuadradoPalindromos(listPalindromo)
listaPalindromoAux = []
for i in listaPalindromoCuadrado:
cad = str(i)
bandera = False
if len(cad) == 1:
listaPalindromoAux.append(i);
else:
if len(cad) % 2 == 0:
pivote = int(len(cad) / 2)
bandera = validaPalindromo(pivote, cad)
else:
pivote = int(len(cad) / 2)
bandera = validaPalindromo(pivote, cad[:pivote] + cad[pivote + 1:])
if(bandera == True):
listaPalindromoAux.append(i)
return len(listaPalindromoAux)
def validaPalindromo(pivote, cadena):
j = 0
for i in range(1, pivote + 1):
if(cadena[pivote - i] != cadena[pivote + j]):
return False
j += 1
return True
if __name__ == '__main__':
fileIn = open("C-small-attempt0.in")
iter = int (fileIn.readline())
l = range(iter)
listaEntrada = []
listaPalindromos = []
for i in l:
cad = fileIn.readline()
cad = cad[:-1]
auxList = cad.split(" ")
listaEntrada.append(auxList)
fileIn.close()
for i in listaEntrada:
list = []
min = pow(int(i[0]), 0.5)
if(min%1!=0):
min=min+1
min = "%.2f" % min
max = "%.2f" % pow(int(i[1]), 0.5)
listaPalindromos.append( hallaPalindromo(int(min[:-3]), int(max[:-3])))
fileOut = open("output.txt",'w')
for i in range(len(listaPalindromos)):
fileOut.writelines("Case #%d: %s" % (i + 1, listaPalindromos[i])+'\n')
fileOut.close()
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
535dc67b848397904e9589a841cb3eed33579914 | d3efc82dfa61fb82e47c82d52c838b38b076084c | /crossmarketetf_bak/crossmarket_redemption_HA/YW_CETFSS_SHSH_067.py | 4f03de4f7cd81d8e34ba46a0bc890d0b0db273ca | [] | no_license | nantongzyg/xtp_test | 58ce9f328f62a3ea5904e6ed907a169ef2df9258 | ca9ab5cee03d7a2f457a95fb0f4762013caa5f9f | refs/heads/master | 2022-11-30T08:57:45.345460 | 2020-07-30T01:43:30 | 2020-07-30T01:43:30 | 280,388,441 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,173 | py | #!/usr/bin/python
# -*- encoding: utf-8 -*-
import sys
sys.path.append("/home/yhl2/workspace/xtp_test")
from crossmarketetf.cetfservice.cetf_main_service import *
from crossmarketetf.cetfservice.cetf_get_components_asset import *
from crossmarketetf.cetfservice.cetf_utils import *
from mysql.QueryOrderErrorMsg import queryOrderErrorMsg
from service.mainService import *
from mysql.getUpOrDownPrice import getUpPrice
class YW_CETFSS_SHSH_067(xtp_test_case):
def test_YW_CETFSS_SHSH_067(self):
# -----------ETF申购-------------
title = ('T日申购ETF-T日赎回当天申购的ETF-T日卖出T日的ETF')
# 定义当前测试用例的期待值
# 期望状态:初始、未成交、全成、废单、撤废、内部撤单
# xtp_ID和cancel_xtpID默认为0,不需要变动
case_goal = {
'期望状态': '全成',
'errorID': 0,
'errorMSG': '',
'是否生成报单': '是',
'是否是撤废': '否',
'xtp_ID': 0,
'cancel_xtpID': 0,
}
logger.warning(title)
unit_info = {
'ticker': '530690', # etf代码
'etf_unit': 1.0 , # etf申赎单位数
'etf_unit_sell': 1.0, # etf卖出单位数
}
# 查询ETF申购前成分股持仓
component_stk_info = cetf_get_all_component_stk(Api,unit_info['ticker'])
# 查询etf最小申赎数量
unit_number = query_creation_redem_unit(unit_info['ticker'])
# etf申赎数量
quantity = int(unit_info['etf_unit'] * unit_number)
# 定义委托参数信息------------------------------------------
wt_reqs = {
'business_type':
Api.const.XTP_BUSINESS_TYPE['XTP_BUSINESS_TYPE_ETF'],
'order_client_id':
2,
'market':
Api.const.XTP_MARKET_TYPE['XTP_MKT_SH_A'],
'ticker':
unit_info['ticker'],
'side':
Api.const.XTP_SIDE_TYPE['XTP_SIDE_PURCHASE'],
'price_type':
Api.const.XTP_PRICE_TYPE['XTP_PRICE_LIMIT'],
'quantity':
quantity
}
g_func.cetf_parm_init(case_goal['期望状态'])
rs1 = cetf_service_test(Api, case_goal, wt_reqs,component_stk_info,)
etf_creation_log(case_goal, rs1)
self.assertEqual(rs1['用例测试结果'], True)
# -----------ETF赎回-------------
case_goal['期望状态'] = '废单'
case_goal['errorID'] = 11010121
case_goal['errorMSG'] = queryOrderErrorMsg(11010121)
# 查询ETF赎回前成分股持仓
component_stk_info2 =cetf_get_all_component_stk(Api,unit_info['ticker'])
# 定义委托参数信息------------------------------------------
wt_reqs = {
'business_type':
Api.const.XTP_BUSINESS_TYPE['XTP_BUSINESS_TYPE_ETF'],
'order_client_id':
2,
'market':
Api.const.XTP_MARKET_TYPE['XTP_MKT_SH_A'],
'ticker':
unit_info['ticker'],
'side':
Api.const.XTP_SIDE_TYPE['XTP_SIDE_REDEMPTION'],
'price_type':
Api.const.XTP_PRICE_TYPE['XTP_PRICE_LIMIT'],
'quantity':
quantity
}
g_func.cetf_parm_init(case_goal['期望状态'])
rs2 = cetf_service_test(Api, case_goal, wt_reqs,component_stk_info2)
etf_creation_log(case_goal, rs2)
self.assertEqual(rs2['用例测试结果'], True)
# --------二级市场,卖出etf-----------
case_goal['期望状态'] = '全成'
case_goal['errorID'] = 0
case_goal['errorMSG'] = ''
# 二级市场卖出的etf数量
quantity = int(unit_info['etf_unit_sell'] * unit_number)
quantity_list = split_etf_quantity(quantity)
# 查询涨停价
limitup_px = getUpPrice(unit_info['ticker'])
rs3 = {}
for etf_quantity in quantity_list:
wt_reqs_etf = {
'business_type':
Api.const.XTP_BUSINESS_TYPE['XTP_BUSINESS_TYPE_CASH'],
'order_client_id':
2,
'market':
Api.const.XTP_MARKET_TYPE['XTP_MKT_SH_A'],
'ticker':
unit_info['ticker'],
'side':
Api.const.XTP_SIDE_TYPE['XTP_SIDE_SELL'],
'price_type':
Api.const.XTP_PRICE_TYPE['XTP_PRICE_BEST5_OR_CANCEL'],
'price':
limitup_px,
'quantity':
etf_quantity
}
ParmIni(Api, case_goal['期望状态'], wt_reqs['price_type'])
rs3 = serviceTest(Api, case_goal, wt_reqs_etf)
if rs3['用例测试结果'] is False:
etf_sell_log(case_goal, rs3)
self.assertEqual(rs3['用例测试结果'], True)
return
etf_sell_log(case_goal, rs3)
if __name__ == '__main__':
unittest.main()
| [
"418033945@qq.com"
] | 418033945@qq.com |
ebd34678904d8f650aa47877f6328d14b8087b89 | 801f367bd19b8f2ab08669fd0a85aad7ace961ac | /project/experiments/exp_020_random_bodies_revisit/src/gym_envs/my_envs.py | 4bdd9eeb25ef7e90771dc38a768f4ec97b664343 | [
"MIT"
] | permissive | Wendong-Huo/thesis-bodies | d91b694a6b1b6a911476573ed1ed27eb27fb000d | dceb8a36efd2cefc611f6749a52b56b9d3572f7a | refs/heads/main | 2023-04-17T18:32:38.541537 | 2021-03-12T19:53:23 | 2021-03-12T19:53:23 | 623,471,326 | 1 | 0 | null | 2023-04-04T12:45:48 | 2023-04-04T12:45:47 | null | UTF-8 | Python | false | false | 2,604 | py | import numpy as np
import pybullet
from pybullet_envs.gym_locomotion_envs import WalkerBaseBulletEnv
from pybullet_envs.robot_locomotors import WalkerBase
class MyWalkerBase(WalkerBase):
def __init__(self, fn, robot_name, action_dim, obs_dim, power):
super().__init__(fn, robot_name, action_dim, obs_dim, power)
# e.g. fn = "".../300.xml"
self.robot_id = int(fn.split("/")[-1].split(".")[0])
class MyWalkerBaseBulletEnv(WalkerBaseBulletEnv):
def __init__(self, robot, render=False):
self._last_x = 0
self._history_x = []
self._history_dx = []
super().__init__(robot, render=render)
def step(self, a):
obs = super().step(a)
self.camera_adjust()
return obs
def reset(self):
self._history_x = []
self._history_dx = []
obs = super().reset()
self.pybullet = self._p
self.camera_angle = 0
return obs
def show_body_id(self):
if self._p:
self._p.addUserDebugText(f"{self.xml.split('/')[-1]}", [-0.5, 0, 1], [0, 0, 1])
def camera_adjust(self):
self.camera_simpy_follow_robot()
def camera_simpy_follow_robot(self, rotate=False):
if self._p:
self.camera_angle += 1
distance = 4
pitch = -10
if rotate:
yaw = self.camera_angle
else:
yaw = 0
_current_x = self.robot.body_xyz[0]
_current_y = self.robot.body_xyz[1]
lookat = [_current_x, _current_y, 0.7]
self._p.resetDebugVisualizerCamera(distance, yaw, pitch, lookat)
def camera_follow_robot(self):
if self._p:
distance = 4
pitch = -5
yaw = 0
# Smooth Camera
if len(self._history_x) > 0:
self._last_x = self._history_x[-1]
self._history_x.append(self.robot.body_xyz[0])
self._history_dx.append(self.robot.body_xyz[0] - self._last_x)
_average_speed = np.mean(self._history_dx) if len(self._history_dx) <= 11 else np.mean(self._history_dx[-10:])
_current_x = self._last_x + _average_speed
# print(_current_x, self.robot.body_xyz[0])
lookat = [_current_x, 0, 0.7]
self._p.resetDebugVisualizerCamera(distance, yaw, pitch, lookat)
def set_view(self):
if self._p:
distance = 3
pitch = -80
yaw = 0
lookat = [0, 0, 0]
self._p.resetDebugVisualizerCamera(distance, yaw, pitch, lookat)
| [
"sliu1@uvm.edu"
] | sliu1@uvm.edu |
3e3cd56dc57fe0dabd04a2540c24b971c3c33c09 | 80f1d4300aa4de8824ad76f3a2606e5ad020e638 | /right-to-left.py | 860ea3112096156c63467813db036b252ee3516c | [] | no_license | deanstreet/checkio | cf14419e921a6ffa18466ba2f01968ec1de271e4 | 825f648c5cbb8d02fe26cd675ddc0913296c0417 | refs/heads/master | 2021-01-02T08:24:53.693247 | 2015-05-11T00:01:00 | 2015-05-11T00:01:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 615 | py | def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
return ','.join(map(lambda x: x.replace('right', 'left'), phrases))
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left"
assert left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left"
assert left_join(("brightness wright",)) == "bleftness wleft", "One phrase"
assert left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace"
| [
"mauricio.abreua@gmail.com"
] | mauricio.abreua@gmail.com |
02a4a248f3ff1f507622c9bba64ddc55b45a3f52 | f90341eea9ae5750ae34fee0fbab253c19b89ff0 | /abilian/sbe/apps/documents/tests/test_parser.py | 6cf799cb20ac801946a993d52476497b665d702e | [] | no_license | 0decimal0/abilian-sbe | f8e5d6ed1474484bbf35dc2a2d13029cbe47eb4e | bcf08c4aec1d761d2e525006fe2c1291cc00e0b8 | refs/heads/master | 2021-01-24T23:41:37.866768 | 2015-12-14T11:02:01 | 2015-12-14T11:02:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,839 | py | from ..cmis.parser import Entry
XML_ENTRY = """\
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:app="http://www.w3.org/2007/app"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/">
<cmisra:object xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmis:properties>
<cmis:propertyString propertyDefinitionId="cmis:name">
<cmis:value>Toto Titi</cmis:value>
</cmis:propertyString>
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">
<cmis:value>cmis:folder</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
<title>Toto Titi</title>
</entry>
"""
XML_ENTRY_WITH_CONTENT = """\
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:app="http://www.w3.org/2007/app"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/">
<cmisra:content>
<cmisra:mediatype>text/plain</cmisra:mediatype>
<cmisra:base64>VGVzdCBjb250ZW50IHN0cmluZw==</cmisra:base64>
</cmisra:content>
<cmisra:object
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmis:properties>
<cmis:propertyString propertyDefinitionId="cmis:name">
<cmis:value>testDocument</cmis:value>
</cmis:propertyString>
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">
<cmis:value>cmis:document</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
<title>testDocument</title>
</entry>
"""
def test_parse_folder_entry():
e = Entry(XML_ENTRY)
assert e.name == "Toto Titi"
assert e.type == "cmis:folder"
def test_parse_document_entry():
e = Entry(XML_ENTRY_WITH_CONTENT)
assert e.name == "testDocument"
assert e.type == "cmis:document"
assert e.content == "Test content string"
| [
"sf@fermigier.com"
] | sf@fermigier.com |
257323258e584c6ede80fc932efea1422a39ea6c | 64267b1f7ca193b0fab949089b86bc7a60e5b859 | /slehome/account/migrations/0007_auto_20150124_2357.py | 9dc78adf7b4c13fd262250eef42336da3db7bb8e | [] | no_license | hongdangodori/slehome | 6a9f2b4526c2783932627b982df0540762570bff | 3e558c78c3943dadf0ec485738a0cc98dea64353 | refs/heads/master | 2021-01-17T12:00:34.221088 | 2015-02-06T13:44:00 | 2015-02-06T13:44:00 | 28,847,585 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 531 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0006_auto_20150124_2347'),
]
operations = [
migrations.AlterField(
model_name='basicmemberinformation',
name='auth_key',
field=models.CharField(default='f26e2ff059e1c71478e358c3f6eb407f217bd163e39fc1b7ab7a53c10c918989', max_length=64),
preserve_default=True,
),
]
| [
"chungdangogo@gmail.com"
] | chungdangogo@gmail.com |
51e916768da88495398585f4f2062d91c0e36cfb | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03426/s835842924.py | 6a7b12f94298b54775e9eaca3a758d891cefb3a6 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 702 | py | import sys;input=sys.stdin.readline
H, W, D = map(int, input().split())
def dist(x, y):
return abs(x[0]-y[0]) + abs(x[1]-y[1])
X = []
for _ in range(H):
X.append(list(map(int, input().split())))
d = dict()
for i in range(H):
x = X[i]
for j in range(W):
d[x[j]] = (i, j)
Ls = []
for i in range(1, D+1):
tmp = [0]
st = d[i]
j = i
while j in d:
tmp.append(tmp[-1]+dist(st, d[j]))
st = d[j]
j += D
Ls.append(tmp)
Q = int(input())
for _ in range(Q):
x, y = map(int, input().split())
a, b = divmod(x, D)
c, d = divmod(y, D)
if b > 0:
print(Ls[b-1][c+1]-Ls[b-1][a+1])
else:
print(Ls[b-1][c]-Ls[b-1][a])
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
98c348967b90cbac75baa5e05e551e2d52e3a16a | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02714/s632667651.py | fa656fe0bf144d612f78ab8ca7788c47309163aa | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 261 | py | from collections import *
N=int(input())
S=input()
c=Counter(S)
ans=c['R']*c['G']*c['B']
for i in range(N):
for j in range(i+1,N):
if S[i]==S[j]:
continue
k=j*2-i
if k>=N or S[k]==S[i] or S[k]==S[j]:
continue
ans-=1
print(ans)
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
04d35b32d242e45e128b6a2f356d510d254e23f8 | 01de66bc478982722cb25120e9d15c39a235a051 | /python3/Library/Database/__init__.py | d595d0b40a3f9816257ed0044b084ab44fd52335 | [] | no_license | ptracton/experimental | 2503c2e8ead7e5719d7aee612fb2ba4d219e6c87 | 7d4a27126f7f2a93f7216b9ea4eed15789599bf3 | refs/heads/master | 2020-06-08T08:21:43.100928 | 2018-04-08T04:54:22 | 2018-04-08T04:54:22 | 7,012,360 | 4 | 7 | null | null | null | null | UTF-8 | Python | false | false | 378 | py |
"""
This is the init for our Database Libary.
"""
__all__ = ['Postgres']
import os
import sys
sys.path.append("/user/tractp1/scratch/src/experimental/python3/Library/Database")
sys.path.append("/home/ptracton/src/software/experimental/python3/Library/Database")
sys.path.append('c:\\Users\\tractp1\\src\\software\\experimental\\python3\\Library\\Database')
import Postgres
| [
"ptracton@gmail.com"
] | ptracton@gmail.com |
4f1c677f0d7ba0732c066ffc7c83a94bdc902f04 | e73cd093ab804f3abe5efb14ce9af244c02ff5e1 | /todolist/urls.py | 52a6418268ecb901fd267833e3af073cfd1b8256 | [] | no_license | zhangfanjm/xadmin_Dj | 7c1d1e6b52f1d91755deaea36b4a356782796d36 | 72adc022e7fbe19e34cdc1d10ec6c0e1e152dbed | refs/heads/master | 2021-06-22T08:45:43.045362 | 2019-07-30T02:44:40 | 2019-07-30T02:44:40 | 199,424,964 | 0 | 0 | null | 2021-06-10T21:47:36 | 2019-07-29T09:47:08 | Python | UTF-8 | Python | false | false | 237 | py | from django.urls import path, include
from .import views
app_name = 'todolist'
urlpatterns = [
path('home/', views.home, name='主页'),
path('about/', views.about, name='关于'),
path('edit/', views.edit, name='编辑'),
] | [
"unknown@example.com"
] | unknown@example.com |
d2cf755b7757dc878ef76f0dcbcfca0aaa9c2f2e | 3f13885fdb0649374d866d24a43f86ccc6b4c782 | /apps/dns_pod/serializers.py | 2a47a921f91b8bb89af969adb71cb72ac1bcf18a | [] | no_license | linkexf/oneops | 426b271c00c5b4b4c55d1d91bf42030dab29623a | 64a9c7fd949b6220234a276614ab6555dc8cc17c | refs/heads/master | 2020-12-10T04:45:55.681731 | 2019-11-28T09:02:30 | 2019-11-28T09:02:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 408 | py |
from rest_framework import serializers
from dns_pod.models import Zone, Record
class ZoneSerializer(serializers.ModelSerializer):
class Meta:
model = Zone
fields = ('id', 'domain_name', 'type', 'comment')
class RecordSerializer(serializers.ModelSerializer):
class Meta:
model = Record
fields = ('id', 'zone', 'host', 'type', 'data', 'ttl', 'mx_priority', 'view')
| [
"andykaiyu@163.com"
] | andykaiyu@163.com |
91499efe1318209699fc0774996e2d989fdce2cf | b46f5825b809c0166622149fc5561c23750b379c | /AppImageBuilder/app_dir/runtimes/classic/helpers/test_qt.py | 32d64d7c94fe1937b457aa1232f754928e1b31ac | [
"MIT"
] | permissive | gouchi/appimage-builder | 22b85cb682f1b126515a6debd34874bd152a4211 | 40e9851c573179e066af116fb906e9cad8099b59 | refs/heads/master | 2022-09-28T09:46:11.783837 | 2020-06-07T19:44:48 | 2020-06-07T19:44:48 | 267,360,199 | 0 | 0 | MIT | 2020-05-27T15:42:25 | 2020-05-27T15:42:24 | null | UTF-8 | Python | false | false | 2,176 | py | # Copyright 2020 Alexis Lopez Zubieta
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
import unittest
from .qt import Qt
class QtHelperTestCase(unittest.TestCase):
def setUp(self) -> None:
self.app_dir_files = [
'/AppDir/usr/lib/x86_64-linux-gnu/libQt5Core.so.5',
'/AppDir/usr/lib/x86_64-linux-gnu/qt5/libexec/QtWebProcess',
'/AppDir/usr/lib/x86_64-linux-gnu/qt5/plugins/platforms/libqxcb.so',
'/AppDir/usr/lib/x86_64-linux-gnu/qt5/qml/org/kde/plasma/components/Label.qml',
'/AppDir/usr/share/qt5/translations/qtbase_en.qm'
]
self.app_dir = '/AppDir'
self.qt = Qt(self.app_dir, self.app_dir_files)
def test_get_qt_(self):
self.assertEqual(self.qt._get_qt_conf_prefix_path('/AppDir/lib/x86_64'), '../..')
def test_get_qt_libs_path(self):
self.assertEqual(self.qt._get_qt_libs_path(), 'usr/lib/x86_64-linux-gnu')
def test_get_qt_lib_exec_path(self):
self.assertEqual(self.qt._get_qt_lib_exec_path(), 'usr/lib/x86_64-linux-gnu/qt5/libexec')
def test_get_qt_plugins_path(self):
self.assertEqual(self.qt._get_qt_plugins_path(), 'usr/lib/x86_64-linux-gnu/qt5/plugins')
def test_get_qt_qml_path(self):
self.assertEqual(self.qt._get_qt_qml_path(), 'usr/lib/x86_64-linux-gnu/qt5/qml')
def test_get_qt_translations_path(self):
self.assertEqual(self.qt._get_qt_translations_path(), 'usr/share/qt5/translations')
def test_get_qt_data_dir(self):
self.assertEqual(self.qt._get_qt_data_dir(), 'usr/share/qt5')
if __name__ == '__main__':
unittest.main()
| [
"contact@azubieta.net"
] | contact@azubieta.net |
d82556b2fa08b9b5bf669d8a5260876206ab8720 | fc678a0a5ede80f593a29ea8f43911236ed1b862 | /146-LRUCache.py | 0a03d9ada59e10ced0060bfe5e5ab5d7ae005f87 | [] | no_license | dq-code/leetcode | 4be0b1b154f8467aa0c07e08b5e0b6bd93863e62 | 14dcf9029486283b5e4685d95ebfe9979ade03c3 | refs/heads/master | 2020-12-13T15:57:30.171516 | 2017-11-07T17:43:19 | 2017-11-07T17:43:19 | 35,846,262 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,954 | py | class Node(object):
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
class DoubleLinkedList(object):
def __init__(self):
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.tail.prev = self.head
self.head.next = self.tail
def remove(self, node):
tempPrev = node.prev
tempNext = node.next
tempPrev.next = tempNext
tempNext.prev = tempPrev
def addFirst(self, node):
curHead = self.head.next
self.head.next = node
node.next = curHead
curHead.prev = node
node.prev = self.head
def removeLast(self):
curTail = self.tail.prev
curTailPrev = curTail.prev
curTailPrev.next = self.tail
self.tail.prev = curTailPrev
return curTail
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.cache = DoubleLinkedList()
self.map = {}
self.capacity = capacity
def isFull(self):
return len(self.map) >= self.capacity
def get(self, key):
"""
:rtype: int
"""
if key in self.map:
self.cache.remove(self.map[key])
self.cache.addFirst(self.map[key])
return self.map[key].val
return -1
def set(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
if key in self.map:
self.map[key].val = value
self.cache.remove(self.map[key])
self.cache.addFirst(self.map[key])
else:
if len(self.map) >= self.capacity:
del self.map[self.cache.tail.prev.key]
lastNode = self.cache.removeLast()
newNode = Node(key, value)
self.map[key] = newNode
self.cache.addFirst(newNode)
| [
"dengqianwork@gmail.com"
] | dengqianwork@gmail.com |
f8202b25cbf0d1cf4eb8728ee8dd4f2ac4be6fe0 | d7cde25f64c784238919b5a4463aca8e98e1042d | /json2.py | 17bd12a4f1a2f2ccaed3d62658b168eaa7f5ef28 | [] | no_license | kwoshvick/pythonscripts | 6d684dbaaaa7d317c5393f7fd982e115770db3c4 | 1c56f21faab098752fcfdcbd2e28590e904a4e0c | refs/heads/master | 2021-09-23T03:19:31.799045 | 2018-09-20T06:20:47 | 2018-09-20T06:20:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 513 | py | __author__ = 'kwoshvick'
import urllib.request as rq
import json
list_numbers = list()
# http://python-data.dr-chuck.net/comments_42.json
# http://python-data.dr-chuck.net/comments_171968.json
url = input("Please Enter URL: ")
urlhandler = rq.urlopen(url).read().decode()
jsondata = json.loads(urlhandler)
#print(json.dumps(jsondata,indent=4))
comments = jsondata['comments']
#print(comments)
for numbers in comments:
num=int(numbers['count'])
list_numbers.append(num)
print(sum(list_numbers))
| [
"kwoshvick@gmail.com"
] | kwoshvick@gmail.com |
7473164a03951ff6879bfaa6df6e9a56ab92202d | 75f6bbcdf10dec884202b3136feb0317842df55f | /apps/task/migrations/0014_taskscript_script_name.py | d71fecd9858efaf7f356441edd75b3326109e7d7 | [] | no_license | qt-pay/python-devops | bafa305fbcd7bef4498857ab75be7447bc1e0a42 | 60e9481ab84628cf817fde1c52f4a15d5085e503 | refs/heads/main | 2023-03-15T12:39:45.813287 | 2021-01-24T18:40:38 | 2021-01-24T18:40:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 466 | py | # Generated by Django 2.2.2 on 2021-01-09 17:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('task', '0013_remove_taskscript_script_name'),
]
operations = [
migrations.AddField(
model_name='taskscript',
name='script_name',
field=models.CharField(blank=True, max_length=32, null=True, unique=True, verbose_name='脚本名称'),
),
]
| [
"yans121@sina.com"
] | yans121@sina.com |
2c5ba50c4354a7a56ca98be6d504781db5df0726 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/72/usersdata/161/32028/submittedfiles/tomadas.py | 0c042de34b3f1ac31dff8e3c9989b37274d5862e | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | # -*- coding: utf-8 -*-
import math
#COMECE SEU CODIGO AQUI
T1=int(input('Informe o número de tomadas da primeira régua:'))
T2=int(input('Informe o número de tomadas da segunda régua:'))
T3=int(input('Informe o número de tomadas da terceira régua:'))
T4=int(input('Informe o número de tomadas da quarta régua:'))
T=(T1-1)+(T2-1)+(T3-1)+T4
print('T')
| [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
3687eb472a1646c1b493cf9ccb45d1cd84cf9d77 | c1bd12405d244c5924a4b069286cd9baf2c63895 | /azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/connectivity_issue_py3.py | 441d34f087704a1372caae1431882ebe92453a81 | [
"MIT"
] | permissive | lmazuel/azure-sdk-for-python | 972708ad5902778004680b142874582a284a8a7c | b40e0e36cc00a82b7f8ca2fa599b1928240c98b5 | refs/heads/master | 2022-08-16T02:32:14.070707 | 2018-03-29T17:16:15 | 2018-03-29T17:16:15 | 21,287,134 | 1 | 3 | MIT | 2019-10-25T15:56:00 | 2014-06-27T19:40:56 | Python | UTF-8 | Python | false | false | 2,129 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ConnectivityIssue(Model):
"""Information about an issue encountered in the process of checking for
connectivity.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar origin: The origin of the issue. Possible values include: 'Local',
'Inbound', 'Outbound'
:vartype origin: str or ~azure.mgmt.network.v2017_09_01.models.Origin
:ivar severity: The severity of the issue. Possible values include:
'Error', 'Warning'
:vartype severity: str or ~azure.mgmt.network.v2017_09_01.models.Severity
:ivar type: The type of issue. Possible values include: 'Unknown',
'AgentStopped', 'GuestFirewall', 'DnsResolution', 'SocketBind',
'NetworkSecurityRule', 'UserDefinedRoute', 'PortThrottled', 'Platform'
:vartype type: str or ~azure.mgmt.network.v2017_09_01.models.IssueType
:ivar context: Provides additional context on the issue.
:vartype context: list[dict[str, str]]
"""
_validation = {
'origin': {'readonly': True},
'severity': {'readonly': True},
'type': {'readonly': True},
'context': {'readonly': True},
}
_attribute_map = {
'origin': {'key': 'origin', 'type': 'str'},
'severity': {'key': 'severity', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'context': {'key': 'context', 'type': '[{str}]'},
}
def __init__(self, **kwargs) -> None:
super(ConnectivityIssue, self).__init__(**kwargs)
self.origin = None
self.severity = None
self.type = None
self.context = None
| [
"noreply@github.com"
] | lmazuel.noreply@github.com |
6f0abd001fc4ea2a018990b3eea17370b082a5ff | c1f09426670b5efe35956acd19c67a2de72af284 | /python/5.concurrent/ZCoroutine/z_spider/1.pyquery.py | 203181b9993d604b17a4b4e6131cdfed178857fc | [
"Apache-2.0"
] | permissive | keasyops/BaseCode | 388218d89d60b958c1fcc50eb15f29eafabaea1f | 0255f498e1fe67ed2b3f66c84c96e44ef1f7d320 | refs/heads/master | 2023-05-08T05:08:39.754170 | 2021-05-26T10:48:01 | 2021-05-26T10:48:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,056 | py | import asyncio
import aiohttp
from pyquery import PyQuery
error_urls = set()
# 获取页面html
async def fetch(session, url):
async with session.get(url) as response:
if response.status == 200:
return await response.text()
else:
error_urls.add(url) # 待处理的url集合
# 阻塞方法
def saves(results):
with open("www.biquge.cm.txt", "a+", encoding="utf-8") as fs:
fs.writelines(results)
print("ok")
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "http://www.biquge.cm/12/12097/")
pq = PyQuery(html)
results = [
item.text() + ":" + item.attr("href") + "\n"
for item in pq.items("dd a")
]
# print(pq("dd a").text())
# 兼容阻塞旧代码
await asyncio.get_running_loop().run_in_executor(None, saves, results)
if __name__ == "__main__":
import time
start_time = time.time()
asyncio.run(main())
print(time.time() - start_time)
| [
"39723758+lotapp@users.noreply.github.com"
] | 39723758+lotapp@users.noreply.github.com |
f28a1c6306277227ba9d8d0c585124aee5fa06f9 | 54277288865f738e44d7be1d6b41b19c63af267e | /configs/srtcp/r2plus1d_18_got10k_syn3x/finetune_hmdb51.py | 8bec58ef23f6b18b9d12f72d1e6dcdf965326cd4 | [] | no_license | scenarios/SR-SVRL | 7b41d29e16cff3020f333efc28a624d85bba4537 | 26e89ecb29355635b10a355f2f16f1b5db9c4e9b | refs/heads/master | 2023-02-26T06:16:13.314491 | 2021-01-30T16:30:57 | 2021-01-30T16:30:57 | 307,295,720 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 324 | py | _base_ = '../r3d_18_got10k_syn3x/finetune_hmdb51.py'
work_dir = './output/tcp/r2plus1d_18_got10k_syn3x/finetune_hmdb51/'
model = dict(
backbone=dict(
type='R2Plus1D',
pretrained='./output/tcp/r2plus1d_18_got10k_syn3x/pretraining/epoch_300.pth',
),
cls_head=dict(
num_classes=51
)
)
| [
"zyz0205@hotmail.com"
] | zyz0205@hotmail.com |
5ed876f70146b5735041edb9aa96dd8f7a27affe | 62bdd0d6ea614613eda76cba1862effb86f2acb7 | /dj4e_2/myarts/models.py | 31a9407d60ee6ee586a73e216aa66fb8edfa720d | [] | no_license | aman007shrestha/Django4everybody | bb2d1df8d681ddac369b1bdde13aff2b9bf08148 | 659bfd579b13d5d7b59022dec3dd3c14c7c37608 | refs/heads/main | 2023-01-21T06:39:48.560094 | 2020-12-02T06:55:20 | 2020-12-02T06:55:20 | 317,775,981 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 631 | py | from django.db import models
from django.core.validators import MinLengthValidator
from django.contrib.auth.models import User
from django.conf import settings
# Create your models here.
class Article(models.Model):
title = models.CharField(
max_length=200,
validators=[MinLengthValidator(2, "Title must be greater than a character")]
)
text = models.TextField()
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_at = models.DateTimeField('Published Date', auto_now_add=True)
updated_at = models.DateTimeField("Last Updated", auto_now=True)
def __str__(self):
return self.title | [
"KAN007BCT@student.kec.edu.np"
] | KAN007BCT@student.kec.edu.np |
76d1a103a3d9419a8f07e15c521acb164732079c | 6169a0af24553278c9493c9ac14d2351e9085afd | /tests/system/providers/google/cloud/gcs/example_firestore.py | 9be3b8dd8dcf3d071209a5d3b5743a6375bbd08b | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | Nextdoor/airflow | c994f8fbaf48bebd891300f44dd78a58fd0b057b | 863ec46e25ea49d6d5b006d8fd3a83f50aa9db79 | refs/heads/master | 2023-06-12T19:25:58.052324 | 2023-01-20T17:43:14 | 2023-01-20T17:43:14 | 54,076,271 | 7 | 8 | Apache-2.0 | 2023-06-05T20:38:53 | 2016-03-17T00:34:45 | Python | UTF-8 | Python | false | false | 6,327 | py | #
# 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.
"""
Example Airflow DAG that shows interactions with Google Cloud Firestore.
Prerequisites
=============
This example uses two Google Cloud projects:
* ``GCP_PROJECT_ID`` - It contains a bucket and a firestore database.
* ``G_FIRESTORE_PROJECT_ID`` - it contains the Data Warehouse based on the BigQuery service.
Saving in a bucket should be possible from the ``G_FIRESTORE_PROJECT_ID`` project.
Reading from a bucket should be possible from the ``GCP_PROJECT_ID`` project.
The bucket and dataset should be located in the same region.
If you want to run this example, you must do the following:
1. Create Google Cloud project and enable the BigQuery API
2. Create the Firebase project
3. Create a bucket in the same location as the Firebase project
4. Grant Firebase admin account permissions to manage BigQuery. This is required to create a dataset.
5. Create a bucket in Firebase project and
6. Give read/write access for Firebase admin to bucket to step no. 5.
7. Create collection in the Firestore database.
"""
from __future__ import annotations
import os
from datetime import datetime
from urllib.parse import urlsplit
from airflow import models
from airflow.providers.google.cloud.operators.bigquery import (
BigQueryCreateEmptyDatasetOperator,
BigQueryCreateExternalTableOperator,
BigQueryDeleteDatasetOperator,
BigQueryInsertJobOperator,
)
from airflow.providers.google.cloud.operators.gcs import GCSCreateBucketOperator, GCSDeleteBucketOperator
from airflow.providers.google.firebase.operators.firestore import CloudFirestoreExportDatabaseOperator
from airflow.utils.trigger_rule import TriggerRule
ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID")
DAG_ID = "example_google_firestore"
GCP_PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "example-gcp-project")
FIRESTORE_PROJECT_ID = os.environ.get("G_FIRESTORE_PROJECT_ID", "example-firebase-project")
BUCKET_NAME = f"bucket_{DAG_ID}_{ENV_ID}"
DATASET_NAME = f"dataset_{DAG_ID}_{ENV_ID}"
EXPORT_DESTINATION_URL = os.environ.get("GCP_FIRESTORE_ARCHIVE_URL", "gs://INVALID BUCKET NAME/namespace/")
EXPORT_PREFIX = urlsplit(EXPORT_DESTINATION_URL).path
EXPORT_COLLECTION_ID = os.environ.get("GCP_FIRESTORE_COLLECTION_ID", "firestore_collection_id")
DATASET_LOCATION = os.environ.get("GCP_FIRESTORE_DATASET_LOCATION", "EU")
if BUCKET_NAME is None:
raise ValueError("Bucket name is required. Please set GCP_FIRESTORE_ARCHIVE_URL env variable.")
with models.DAG(
DAG_ID,
start_date=datetime(2021, 1, 1),
schedule="@once",
catchup=False,
tags=["example", "firestore"],
) as dag:
create_bucket = GCSCreateBucketOperator(task_id="create_bucket", bucket_name=BUCKET_NAME)
create_dataset = BigQueryCreateEmptyDatasetOperator(
task_id="create_dataset",
dataset_id=DATASET_NAME,
location=DATASET_LOCATION,
project_id=GCP_PROJECT_ID,
)
# [START howto_operator_export_database_to_gcs]
export_database_to_gcs = CloudFirestoreExportDatabaseOperator(
task_id="export_database_to_gcs",
project_id=FIRESTORE_PROJECT_ID,
body={"outputUriPrefix": EXPORT_DESTINATION_URL, "collectionIds": [EXPORT_COLLECTION_ID]},
)
# [END howto_operator_export_database_to_gcs]
# [START howto_operator_create_external_table_multiple_types]
create_external_table_multiple_types = BigQueryCreateExternalTableOperator(
task_id="create_external_table",
bucket=BUCKET_NAME,
table_resource={
"tableReference": {
"projectId": GCP_PROJECT_ID,
"datasetId": DATASET_NAME,
"tableId": "firestore_data",
},
"schema": {
"fields": [
{"name": "name", "type": "STRING"},
{"name": "post_abbr", "type": "STRING"},
]
},
"externalDataConfiguration": {
"sourceFormat": "DATASTORE_BACKUP",
"compression": "NONE",
"csvOptions": {"skipLeadingRows": 1},
},
},
)
# [END howto_operator_create_external_table_multiple_types]
read_data_from_gcs_multiple_types = BigQueryInsertJobOperator(
task_id="execute_query",
configuration={
"query": {
"query": f"SELECT COUNT(*) FROM `{GCP_PROJECT_ID}.{DATASET_NAME}.firestore_data`",
"useLegacySql": False,
}
},
)
delete_dataset = BigQueryDeleteDatasetOperator(
task_id="delete_dataset",
dataset_id=DATASET_NAME,
project_id=GCP_PROJECT_ID,
delete_contents=True,
trigger_rule=TriggerRule.ALL_DONE,
)
delete_bucket = GCSDeleteBucketOperator(
task_id="delete_bucket", bucket_name=BUCKET_NAME, trigger_rule=TriggerRule.ALL_DONE
)
(
# TEST SETUP
create_bucket
>> create_dataset
# TEST BODY
>> export_database_to_gcs
>> create_external_table_multiple_types
>> read_data_from_gcs_multiple_types
# TEST TEARDOWN
>> delete_dataset
>> delete_bucket
)
from tests.system.utils.watcher import watcher
# This test needs watcher in order to properly mark success/failure
# when "tearDown" task with trigger rule is part of the DAG
list(dag.tasks) >> watcher()
from tests.system.utils import get_test_run # noqa: E402
# Needed to run the example DAG with pytest (see: tests/system/README.md#run_via_pytest)
test_run = get_test_run(dag)
| [
"noreply@github.com"
] | Nextdoor.noreply@github.com |
7ff31e753171c8ee1b134daddd4f357f9b1005f2 | 95386eb0d35216dec743388b2718da15f61b608d | /NETCONF/CODE/cisco_XR_netconf_2.py | 51c0d0e66d9773f20f106e54327e21ec87ee7c61 | [] | no_license | Preet2fun/NetworkProgramming | 930c48601d7f5199510479126806be298ccfcca5 | 78bf55d05574d85c373ad88df10c5df4139ed178 | refs/heads/master | 2020-05-17T23:54:48.517255 | 2019-09-30T09:43:45 | 2019-09-30T09:43:45 | 184,040,833 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 807 | py | #! /usr/bin/python3.6
from ncclient import manager
from cisco_device import IOS_XR
import sys
import xmltodict
import logging
logger = logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s: %(message)s',stream=sys.stdout)
netconf_filter = open("ietf_fileter_interface.xml").read()
print (netconf_filter)
with manager.connect(host=IOS_XR['address'],port=IOS_XR['port'],username=IOS_XR['username'],\
password=IOS_XR['password'],hostkey_verify=False,device_params={'name': 'default'},allow_agent=False, look_for_keys=False) as m:
netconf_reply = m.get(netconf_filter)
interface_dict = xmltodict.parse(netconf_reply)
print(interface_dict)
m.close_session()
#except Exception as e:
# print ("Encountered folloing error..")
# print (e)
# sys.exit()
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
25ad11b9bb7c1e93a1ad963baf5a210ef888e6fb | 2d5d13c4bdc64202a520f32e7d4a44bb75e2004f | /week-02/d01/variable_mutation.py | 22d74862ed356281daca16cc1e29a0bcfc7e14c3 | [] | no_license | green-fox-academy/andrasnyarai | 43b32d5cc4ad3792ef8d621328f9593fc9623e0b | 19759a146ba2f63f1c3e4e51160e6111ca0ee9c3 | refs/heads/master | 2021-09-07T16:19:34.636119 | 2018-02-26T00:38:00 | 2018-02-26T00:38:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 845 | py | a = 3
# make it bigger by 10
print(a + 10)
b = 100
# make it smaller by 7
print(b - 7)
c = 44
# please double c's value
print(c * 2)
d = 125
# please divide by 5 d's value
print(d // 5)
e = 8
# please cube of e's value
print(e ** 3)
f1 = 123
f2 = 345
# tell if f1 is bigger than f2 (pras a boolean)
print(f1 > f2)
g1 = 350
g2 = 200
# tell if the double of g2 is bigger than g1 (pras a boolean)
print((g2 * 2) > g1)
h = 1357988018575474
# tell if it has 11 as a divisor (pras a boolean)
print(h % 11 == 0)
i1 = 10
i2 = 3
# tell if i1 is higher than i2 squared and smaller than i2 cubed (pras a boolean)
print(i1 ** 3 > i2 ** 2)
j = 1521
# tell if j is dividable by 3 or 5 (pras a boolean)
print(j % 3 == 0 or j % 5 == 0)
k = "Apple"
#fill the k variable with its cotnent 4 times
print(str(k) * 4)
| [
"andrasnyarai@gmail.com"
] | andrasnyarai@gmail.com |
4843baf002f6dae0fe5cb1470e278cd63ae8bfc9 | fbdc36fe99d2f49b150b8cb8d2f09fcb10bd7ca4 | /pytorch/train.py | 6e947e04b93dd6dfe8522b3940eada1aa41fe75f | [
"MIT"
] | permissive | MiaoDragon/completion3d | 9ff17cfba8706991f5fe88f6d270007eba06481b | 95430f16ae73c5b27180b542cf1c56f87b4cdbaf | refs/heads/master | 2020-06-14T06:01:22.167439 | 2019-07-29T01:58:19 | 2019-07-29T01:58:19 | 194,927,243 | 0 | 0 | null | 2019-07-02T20:01:59 | 2019-07-02T20:01:59 | null | UTF-8 | Python | false | false | 5,000 | py | """
"""
#from builtins import range
import os
import sys
sys.path.append(os.getcwd())
import _init_paths
from PointNetFCAE import *
#from modules.emd import EMDModule
from tools.obs_data_loader import load_dataset
from tools.import_tool import fileImport
import argparse
import torch
from chamfer_distance import ChamferDistance as chamfer
import torch.nn as nn
import numpy as np
import os
import pickle
#from tools.path_data_loader import load_dataset_end2end
from torch.autograd import Variable
import time
def to_var(x, volatile=False):
if torch.cuda.is_available():
x = x.cuda()
return Variable(x, volatile=volatile)
def main(args):
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
importer = fileImport()
env_data_path = args.env_data_path
path_data_path = args.path_data_path
pcd_data_path = args.pointcloud_data_path
# append all envs and obstacles
#envs_files = os.listdir(env_data_path)
#envs_files = ['trainEnvironments.pkl']
envs_files = ['trainEnvironmentsLarge.pkl']
#envs_files = ['trainEnvironments.pkl']
obstacles = []
for envs_file in envs_files:
envs = importer.environments_import(env_data_path + envs_file)
print("Loading obstacle data...\n")
obs = load_dataset(envs, pcd_data_path, importer)
obstacles.append(obs)
obstacles = np.stack(obstacles).astype(float)[0].reshape(len(obs),-1,3)
print(obstacles.shape)
print("Loaded dataset, targets, and pontcloud obstacle vectors: ")
print("\n")
if not os.path.exists(args.trained_model_path):
os.makedirs(args.trained_model_path)
# Build the models
net = PointNetFCAE(code_ntfs=1024, num_points=len(obstacles[0]), output_channels=3)
if torch.cuda.is_available():
net.cuda()
# Loss and Optimizer
params = list(net.parameters())
optimizer = torch.optim.Adam(params, lr=args.learning_rate)
total_loss = []
epoch = 1
sm = 100 # start saving models after 100 epochs
criterion = chamfer()
print("Starting epochs...\n")
# epoch=1
done = False
for epoch in range(args.num_epochs):
# while (not done)
# every time use a new obstacle
start = time.time()
print("epoch" + str(epoch))
avg_loss = 0
for i in range(0, len(obstacles), args.batch_size):
# Forward, Backward and Optimize
# zero gradients
net.zero_grad()
# convert to pytorch tensors and Varialbes
bobs = torch.from_numpy(obstacles[i:i+args.batch_size]).type(torch.FloatTensor)
#bobs = to_var(bobs).view(len(bobs), -1, 3).permute(0,2,1)
bobs = to_var(bobs)
# forward pass through encoder
bt = net(bobs)
# compute overall loss and backprop all the way
loss1, loss2 = criterion(bobs, bt)
#loss1, loss2 = criterion(bobs, bt)
print('loss1')
print(loss1)
print('loss2')
print(loss2)
loss = torch.mean(loss1) + torch.mean(loss2)
print('loss:')
print(loss)
avg_loss = avg_loss+loss.data
loss.backward()
optimizer.step()
print("--average loss:")
# Save the models
if epoch == sm:
print("\nSaving model\n")
print("time: " + str(time.time() - start))
torch.save(net.state_dict(), os.path.join(
args.trained_model_path, 'pointnet_'+str(epoch)+'.pkl'))
#if (epoch != 1):
sm = sm+100 # save model after every 50 epochs from 100 epoch ownwards
torch.save(total_loss, 'total_loss.dat')
print(encoder.state_dict())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--env_data_path', type=str, default='./env/environment_data/')
parser.add_argument('--path_data_path', type=str, default='./data/train/paths/')
parser.add_argument('--pointcloud_data_path', type=str, default='./data/train/pcd/')
parser.add_argument('--trained_model_path', type=str, default='./models/sample_train/', help='path for saving trained models')
parser.add_argument('--batch_size', type=int, default=100)
parser.add_argument('--learning_rate', type=float, default=0.001)
parser.add_argument('--num_epochs', type=int, default=200)
parser.add_argument('--enc_input_size', type=int, default=16053)
parser.add_argument('--enc_output_size', type=int, default=60)
parser.add_argument('--mlp_input_size', type=int, default=74)
parser.add_argument('--mlp_output_size', type=int, default=7)
parser.add_argument('--train_ratio', type=float, default=0.8)
parser.add_argument('--envs_file', type=str, default='trainEnvironments.pkl')
parser.add_argument('--path_data_file', type=str, default='trainPaths.pkl')
args = parser.parse_args()
main(args)
| [
"innocentmyl@gmail.com"
] | innocentmyl@gmail.com |
82e3b37bdb2ad82c4f96ac43d5740de6895f4863 | 3df19730d14ee920f9efb5949a39b2b7ce03890b | /layerviewer/normalize.py | 2ce0e883731472496aff3e3df6a0238e3c4bff69 | [] | no_license | shalevy1/ivigraph | 6948f66ffa06e5132d5884658d1e78122ab6604c | 4e8c29d92d36cee27de3f9100d20df5c8ce706c7 | refs/heads/master | 2023-03-16T15:44:06.248049 | 2013-08-05T16:40:25 | 2013-08-05T16:40:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | def norm01(dataIn,channelWise=False):
out=dataIn.copy()
if channelWise==False:
out-=out.min()
out/=out.max()
else :
for c in range(dataIn.shape[2]):
out[:,:,c]-=out[:,:,c].min()
out[:,:,c]/=out[:,:,c].max()
return out
| [
"thorsten.beier@iwr.uni-heidelberg.de"
] | thorsten.beier@iwr.uni-heidelberg.de |
fa561650bdf461db8a95273cbd2fbb8bdc7b0e54 | 191a7f83d964f74a2b3c7faeb4fc47d9c63d521f | /.history/main_20210529105730.py | dfdfad8f4b990aa7ac7b90bed6d22e6fbfa94693 | [] | no_license | AndreLiu1225/Kinder-Values-Survey | 2a317feee8d5b17c27da2b2116742656e35d8ab9 | 090c27da0c822abb7dfc0ec6e13ae1b3dcb7bbf3 | refs/heads/master | 2023-05-03T00:26:00.481423 | 2021-06-04T03:24:19 | 2021-06-04T03:24:19 | 371,989,154 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,582 | py | from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, IntegerField, SelectField, RadioField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError
import datetime
import plotly.graph_objs as go
app = Flask(__name__)
app.config['SECRET_KEY'] = "0c8973c8a5e001bb0c816a7b56c84f3a"
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///site.db"
db = SQLAlchemy(app)
class Survey(db.Model):
age = db.Column(db.Integer, nullable=False, primary_key=True)
email = db.Column(db.String(50), unique=True, nullable=False)
profession = db.Column(db.String(50), nullable=False)
power = db.Column(db.Integer, nullable=False)
tradition = db.Column(db.Integer, nullable=False)
achievement = db.Column(db.Integer, nullable=False)
stimulation = db.Column(db.Integer, nullable=False)
hedonism = db.Column(db.Integer, nullable=False)
conformity = db.Column(db.Integer, nullable=False)
self_direction = db.Column(db.Integer, nullable=False)
benevolence = db.Column(db.Integer, nullable=False)
universalism = db.Column(db.Integer, nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
def __repr__(self):
return f"Survey('{self.age}', '{self.name}', '{self.date_posted}')"
# @staticmethod
# def is_email_in_database(email):
# return True if Survey.query.filter_by(email=email).first() else False
class MCQ(FlaskForm):
email = StringField("What is your email?", validators=[DataRequired(), Email(message=('Not a valid email address')), Length(max=50)])
age = IntegerField("Please enter your age", validators=[DataRequired()])
profession = StringField("What is your profession?", validators=[DataRequired(), Length(max=30)])
power = IntegerField("Do you desire a higher social status and dominance over others? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
tradition = IntegerField("Do you care about preserving traditions? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
achievement = IntegerField("Is achievement according to social standards important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
stimulation = IntegerField("Do you prefer novel and exciting challenges in life? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
hedonism = IntegerField("Is personal gratification the most important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
conformity = IntegerField("Do you think restraint of actions against social norms is important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
self_direction = IntegerField("Do you think independent thought and action are important (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
benevolence = IntegerField("Are preserving and enhancing the welfare of your friends and family the most important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
universalism = IntegerField("I find it important to understand, tolerate, appreciate and protect all ethnicities and people. (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
submit = SubmitField("Submit")
@app.route('/', methods=['POST','GET'])
def values_quiz():
form = MCQ()
if form.validate_on_submit():
post = Survey(age=form.age.data, email=form.email.data, profession=form.profession.data, power=form.power.data,
tradition=form.tradition.data, achievement=form.achievement.data, stimulation=form.stimulation.data,
hedonism=form.hedonism.data, conformity=form.conformity.data, self_direction=form.self_direction.data,
benevolence=form.benevolence.data, universalism=form.universalism.data)
# if Survey.is_email_in_database(form.email.data):
# flash(f"The user with {form.email.data} has already filled the survey", "danger")
db.session.add(post)
db.session.commit()
flash(f'Survey is completed by {form.email.data}', 'success')
return redirect(url_for('data_dashboard'))
else:
flash('Ensure all questions are answered correctly', 'warning')
return render_template('MCQ.html', form=form)
@app.route('/results', methods=['POST','GET'])
def data_dashboard():
# power = request.form.get('power')
# tradition = request.form.get('tradition')
# achievement = request.form.get('achievement')
# stimulation = request.form.get('stimulation')
# hedonism = request.form.get('hedonism')
# conformity = request.form.get('conformity')
# self_direction = request.form.get('self_direction')
# benevolence = request.form.get('benevolence')
# universalism = request.form.get('universalism')
return render_template('data_dashboard.html')
if __name__ == "__main__":
app.run(debug=True)
| [
"andreliu2004@gmail.com"
] | andreliu2004@gmail.com |
8a4bc42d9cafe0d8a4ab3a08aefcb128066c613a | d6eca1b4b056beb41ac494db7399e1f146099c97 | /alien_invasion/exercise/key.py | 7a13a30d303781ea41b65e756d2a29ca1604771a | [] | no_license | liangsongyou/python-crash-course-code | 15090b48d77de1115bfaaaa6e5638a9bb9b3c7cc | f369e18030f2aafe358dd0fab1e479ca7bf4ceb8 | refs/heads/master | 2021-05-08T06:42:29.147923 | 2017-08-11T06:41:30 | 2017-08-11T06:41:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 429 | py | from os import sys
import pygame
def main():
"""Main loop of the window."""
pygame.init()
scr_size = (1386,700)
screen = pygame.display.set_mode(scr_size)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
print('{}'.format(event.key))
pygame.display.flip()
main() | [
"ramzanm461@gmail.com"
] | ramzanm461@gmail.com |
d02961f6bb0710a6363c4a70e20835eb34887b2a | b681f93e6790f86f5710820e5ba3aa35fefa6f25 | /Fred2/Apps/EpitopeAssembly.py | e0422ad80f47fb04fc50623c73547ae310e60a65 | [] | no_license | SteffenK12/Fred2 | 89be9d081cae4dda6be6ba49c13155910f4ecd00 | 4d627ee1f28380efb3c6af61895623d33ff8785d | refs/heads/master | 2020-04-05T23:39:27.786786 | 2015-10-09T14:18:37 | 2015-10-09T14:18:37 | 44,380,401 | 0 | 0 | null | 2015-10-16T11:18:44 | 2015-10-16T11:18:44 | null | UTF-8 | Python | false | false | 5,349 | py | __author__ = 'schubert'
import argparse, sys, os
from Fred2.Core.Peptide import Peptide
from Fred2.Core.Base import ACleavageSitePrediction
from Fred2.IO.FileReader import read_lines
from Fred2.EpitopeAssembly.EpitopeAssembly import EpitopeAssembly
from Fred2.CleavagePrediction import CleavageSitePredictorFactory
def main():
parser = argparse.ArgumentParser(description="Reads peptide sequences and predicts best arrangement "+
"for a string-of-beats peptide vaccine based on proteasomal cleavage prediction.")
parser.add_argument("-i", "--input",
nargs="+",
required=True,
help="peptide file (one peptide per line),"
+" or peptide sequences as sequences (max 50)"
)
input_types = parser.add_mutually_exclusive_group(required=True)
input_types.add_argument("-pf","--pepfile",
action="store_true",
help= "Specifies the input as peptide file")
input_types.add_argument("-p","--peptide",
action="store_true",
help= "Specifies the input as peptide sequences")
parser.add_argument("-m", "--method",
default="PCM",
help="Specifies the Cleavage Site prediction tool to use - default PCM."
)
parser.add_argument("-s", "--solver",
default="glpk",
help="Specifies the ILP solver to use (must be installed) - default glpk"
)
parser.add_argument("-o", "--output",
required=True,
help="Specifies the output path. Results will be written to CSV")
parser.add_argument("-v", "--verbose",
action="store_true",
help="Specifies verbose run."
)
parser.add_argument("-am", "--available",
required=False,
action="store_true",
help="Returns all available methods and their allele models.")
#COMMENT: These options are hidden and only used for ETK2
parser.add_argument("-html", "--html",
required=False,
action="store_true",
help=argparse.SUPPRESS)
parser.add_argument("-od", "--outdir",
required=False,
default="",
help=argparse.SUPPRESS)
args = parser.parse_args()
if args.available:
for pred, obj in ACleavageSitePrediction.registry.iteritems():
if pred not in ["ACleavageSitePrediction", "APSSMCleavageSitePredictor"]:
print "Method: ",pred
print "Supported Length: ", " ".join(map(str, getattr(obj, "_"+pred+"__supported_length")))
print
sys.exit(0)
if args.pepfile:
peptides = read_lines(args.input, type="Peptide")
else:
peptides = [Peptide(s) for s in args.input]
cleav_pred = CleavageSitePredictorFactory(args.method)
assembler = EpitopeAssembly(peptides, cleav_pred, solver=args.solver, verbosity=1 if args.verbose else 0)
result = assembler.solve()
output = args.output if args.outdir == "" else args.outdir + os.path.basename(args.output)
with open(output, "w") as out:
out.write("Order,Peptide\n")
out.write("\n".join("%i,%s"%(i+1,str(p)) for i, p in enumerate(result)))
if args.html:
begin_html = """<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="/static/style/etk.css" type="text/css" />
<script type="text/javascript" src="/static/scripts/libs/jquery/jquery.js"></script>
<script type="text/javascript" src="/static/scripts/libs/jquery/jquery.tablesorter.js"></script>
<script type="text/javascript" src="/static/scripts/libs/etk.js"></script>
</head>
<body>
<div class="document">"""
setting = """ <h2 class="etk-heading">Peptide String-of-Beats Design</h2>
<table class="etk-parameterT">
<tr> <th class ="etk-innerHeading" colspan="2"> Parameters </th></tr>
<tr>
<th>Cleave Site Prediction Method:</th>
<td>%s</td>
</tr>
</table>"""%args.method
table="""
<input id="etk-search" placeholder=" filter">
<table class="etk-sortT etk-resultsT etk-filterT">
<thead>
<tr>
<th>Order</th><th>Peptide</th>
</tr>
</thead>"""+"".join("<tr><td>%i</td><td>%s</td></tr>"%(i+1,p) for i, p in enumerate(result))+"</table>"
end_html = "</div></body></html>"
html_out = ".".join(output.split(".")[:-1])+".html"
with open(html_out, "w") as html_o:
html_o.write(begin_html+setting+table+end_html)
if __name__ == "__main__":
main()
| [
"schubert@informatik.uni-tuebingen.de"
] | schubert@informatik.uni-tuebingen.de |
6b98fd9480c24ce1dfbab89aa37782b26192a924 | 4e04db11d891f869a51adf0e0895999d425f29f6 | /tests/accounting/testcases/tc_connect.py | 3461941a88ef6bf289dc812d1e69a820ca204837 | [] | no_license | mthangaraj/ix-ec-backend | 21e2d4b642c1174b53a86cd1a15564f99985d23f | 11b80dbd665e3592ed862403dd8c8d65b6791b30 | refs/heads/master | 2022-12-12T12:21:29.237675 | 2018-06-20T13:10:21 | 2018-06-20T13:10:21 | 138,033,811 | 0 | 0 | null | 2022-06-27T16:54:14 | 2018-06-20T13:04:22 | JavaScript | UTF-8 | Python | false | false | 2,283 | py | from rest_framework.test import APITestCase
from portalbackend.lendapi.accounts.models import Company
from tests.constants import ResponseCodeConstant, CompanyConstant, TestConstants
from tests.utils import TestUtils
class _001_ConnectionTestCase(APITestCase):
"""
Tests the Connection View
"""
def setUp(self):
self.userid = ''
self.superuser = TestUtils._create_superuser()
self.company = TestUtils._create_company(1, CompanyConstant.COMPANY_NAME_001)
TestUtils._create_companymeta(self.company.id)
self.user = TestUtils._create_user('ut_user001', self.company.id)
self.login = TestUtils._admin_login(self.client)
def test_001_connect_company_success(self):
"""
Creating connection for given company
"""
TestUtils._create_accounting_configuration(Company.QUICKBOOKS)
self.data = {
"company": self.company.id
}
response = self.client.get('/lend/v1/connect/', self.data, format='json', secure=TestConstants.SECURE_CONNECTION,
HTTP_HOST=TestConstants.HOST_URL)
code = response.status_code
self.assertEqual(code, ResponseCodeConstant.REDIRECT_302)
def test_002_connect_company_without_company_id(self):
"""
Creating connection for not existing company
"""
TestUtils._create_accounting_configuration(Company.QUICKBOOKS)
self.data = {
}
response = self.client.get('/lend/v1/connect/', self.data, format='json', secure=TestConstants.SECURE_CONNECTION,
HTTP_HOST=TestConstants.HOST_URL)
code = response.status_code
self.assertEqual(code, ResponseCodeConstant.RESOURCE_NOT_FOUND_404)
def test_003_connect_company_without_accounting_configuration(self):
"""
Creating connection for given company without accounting configuration
"""
self.data = {
}
response = self.client.get('/lend/v1/connect/', self.data, format='json', secure=TestConstants.SECURE_CONNECTION,
HTTP_HOST=TestConstants.HOST_URL)
code = response.status_code
self.assertEqual(code, ResponseCodeConstant.RESOURCE_NOT_FOUND_404)
| [
"thangaraj.matheson@ionixxtech.com"
] | thangaraj.matheson@ionixxtech.com |
52ceffb3c9ec7ddad2e6056a9dde0fd42ae567a4 | 6fa81aea23e36b58c7d7788a2b6f3d98440a6891 | /basic-manipulations/break.py | f25ad1b6a962e8dc3533cda83c3693da01fab903 | [] | no_license | grbalmeida/python3 | 673b0cbde3481350795d41fb6ebf06633a70b462 | 3a542cea13f4442dcf7703b843df8f2bd44e9065 | refs/heads/master | 2020-04-29T09:40:20.635795 | 2019-03-17T05:08:28 | 2019-03-17T05:08:28 | 176,033,385 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 291 | py | # coding: utf-8
salary = int(input('Salário? '))
tax = 27
while tax > 0:
tax = input('Imposto ou (s) para sair: ')
if not tax:
tax = 27.
elif tax == 's':
break
else:
tax = float(tax)
print('Valor real: {0}'.format(salary - salary * tax * 0.01)) | [
"g.r.almeida@live.com"
] | g.r.almeida@live.com |
912d082a6dbe74f145802096419eb2c4ce1772a1 | 4cade98f144c81d98898de89763d4fcc7e6ae859 | /tests/rendering/repeat_separate_callback.py | 93e1614196d4f5d88f50767af65aca66f8754f88 | [
"Apache-2.0"
] | permissive | ndparker/tdi | be115c02721aa5829e60b9af820b4157ba24a394 | 65a93080281f9ce5c0379e9dbb111f14965a8613 | refs/heads/master | 2021-01-21T04:54:51.390643 | 2016-06-15T19:55:35 | 2016-06-15T19:55:35 | 13,570,597 | 4 | 1 | null | 2013-10-20T14:59:37 | 2013-10-14T19:14:14 | Python | UTF-8 | Python | false | false | 630 | py | #!/usr/bin/env python
import warnings as _warnings
_warnings.resetwarnings()
_warnings.filterwarnings('error')
from tdi import html
template = html.from_string("""
<node tdi="item">
<node tdi="nested">
<node tdi="subnested"></node>
</node><tdi tdi=":-nested">
</tdi>
</node>
""".lstrip())
class Model(object):
def render_item(self, node):
def sep(node):
node.hiddenelement = False
node.nested.repeat(self.repeat_nested, [1, 2, 3, 4], separate=sep)
return True
def repeat_nested(self, node, item):
node['j'] = item
model = Model()
template.render(model)
| [
"ndparker@users.noreply.github.com"
] | ndparker@users.noreply.github.com |
0b8646becbebeb2e60b26401ced6a214df15b8a5 | d9d75e429261d3f2b1075e0f7b598c756cb53a56 | /env/lib/python3.9/site-packages/django/contrib/admin/__init__.py | da396593162743eef0420c635f6044e7c811c764 | [] | no_license | elisarocha/django-tdd-course | f89ccff07c8fd5114ae10fcb9a400be562f088db | 7333fb9b5a5f8ea0f8fe7367234de21df589be59 | refs/heads/main | 2023-02-25T11:22:23.737594 | 2021-02-01T19:53:42 | 2021-02-01T19:53:42 | 334,710,716 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,498 | py | from django.contrib.admin.decorators import register
from django.contrib.admin.filters import (AllValuesFieldListFilter,
BooleanFieldListFilter,
ChoicesFieldListFilter,
DateFieldListFilter,
EmptyFieldListFilter,
FieldListFilter, ListFilter,
RelatedFieldListFilter,
RelatedOnlyFieldListFilter,
SimpleListFilter)
from django.contrib.admin.options import (HORIZONTAL, VERTICAL, ModelAdmin,
StackedInline, TabularInline)
from django.contrib.admin.sites import AdminSite, site
from django.utils.module_loading import autodiscover_modules
__all__ = [
"register",
"ModelAdmin",
"HORIZONTAL",
"VERTICAL",
"StackedInline",
"TabularInline",
"AdminSite",
"site",
"ListFilter",
"SimpleListFilter",
"FieldListFilter",
"BooleanFieldListFilter",
"RelatedFieldListFilter",
"ChoicesFieldListFilter",
"DateFieldListFilter",
"AllValuesFieldListFilter",
"EmptyFieldListFilter",
"RelatedOnlyFieldListFilter",
"autodiscover",
]
def autodiscover():
autodiscover_modules("admin", register_to=site)
default_app_config = "django.contrib.admin.apps.AdminConfig"
| [
"ecdgrocha@gmail.com"
] | ecdgrocha@gmail.com |
a9e1c39ac344a4077757def33a8fb95fab0757da | 6a607ff93d136bf9b0c6d7760394e50dd4b3294e | /CodePython/python_file/SSPassword.py | 0a00267cdf0932e971e83597190057c7c84a1732 | [] | no_license | n3n/CP2014 | d70fad1031b9f764f11ecb7da607099688e7b1de | 96a7cdd76f9e5d4fd8fb3afa8cd8e416d50b918c | refs/heads/master | 2020-05-15T07:08:17.510719 | 2014-02-14T03:21:05 | 2014-02-14T03:21:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 416 | py | txt1 = raw_input()
txt2 = raw_input()
start = 0
store = {}
for j in xrange(len(txt2)):
tmp = ''
for i in xrange(1,len(txt2)+1):
if txt2[j:i] in txt1:
tmp = txt2[j:i]
if len(tmp) > 0:
store[tmp] = len(tmp)
val = store.values()
val.sort()
if len(val) == 0:
print 'Error!'
else:
for x in store:
if store[x] == val[-1]:
print x
break
| [
"s6070069@kmitl.ac.th"
] | s6070069@kmitl.ac.th |
114f29441491d265e57420d9a1e9f0120e7f3ef9 | 447aadd08a07857c3bcf826d53448caa8b6a59ee | /bin/python-config | 943b73297bb756dfe3e5f8227160dfde867f44aa | [] | no_license | aydanaderi/Site1 | 57461e9a43ddc7b7372d2e1690c37b09f73cbdef | 30dce3e5a52a221208b28bcaac51a57a35cd82c6 | refs/heads/master | 2021-06-03T11:30:54.317056 | 2020-05-01T13:43:07 | 2020-05-01T13:43:07 | 254,337,037 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,343 | #!/home/ayda/Documents/Site/bin/python
import sys
import getopt
import sysconfig
valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags',
'ldflags', 'help']
if sys.version_info >= (3, 2):
valid_opts.insert(-1, 'extension-suffix')
valid_opts.append('abiflags')
if sys.version_info >= (3, 3):
valid_opts.append('configdir')
def exit_with_usage(code=1):
sys.stderr.write("Usage: {0} [{1}]\n".format(
sys.argv[0], '|'.join('--'+opt for opt in valid_opts)))
sys.exit(code)
try:
opts, args = getopt.getopt(sys.argv[1:], '', valid_opts)
except getopt.error:
exit_with_usage()
if not opts:
exit_with_usage()
pyver = sysconfig.get_config_var('VERSION')
getvar = sysconfig.get_config_var
opt_flags = [flag for (flag, val) in opts]
if '--help' in opt_flags:
exit_with_usage(code=0)
for opt in opt_flags:
if opt == '--prefix':
print(sysconfig.get_config_var('prefix'))
elif opt == '--exec-prefix':
print(sysconfig.get_config_var('exec_prefix'))
elif opt in ('--includes', '--cflags'):
flags = ['-I' + sysconfig.get_path('include'),
'-I' + sysconfig.get_path('platinclude')]
if opt == '--cflags':
flags.extend(getvar('CFLAGS').split())
print(' '.join(flags))
elif opt in ('--libs', '--ldflags'):
abiflags = getattr(sys, 'abiflags', '')
libs = ['-lpython' + pyver + abiflags]
libs += getvar('LIBS').split()
libs += getvar('SYSLIBS').split()
# add the prefix/lib/pythonX.Y/config dir, but only if there is no
# shared library in prefix/lib/.
if opt == '--ldflags':
if not getvar('Py_ENABLE_SHARED'):
libs.insert(0, '-L' + getvar('LIBPL'))
if not getvar('PYTHONFRAMEWORK'):
libs.extend(getvar('LINKFORSHARED').split())
print(' '.join(libs))
elif opt == '--extension-suffix':
ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
if ext_suffix is None:
ext_suffix = sysconfig.get_config_var('SO')
print(ext_suffix)
elif opt == '--abiflags':
if not getattr(sys, 'abiflags', None):
exit_with_usage()
print(sys.abiflags)
elif opt == '--configdir':
print(sysconfig.get_config_var('LIBPL'))
| [
"ayda.f.naderi@gmail.com"
] | ayda.f.naderi@gmail.com | |
01ccdf77b9751e5d0b06610abd85dfec1a411893 | a1615563bb9b124e16f4163f660d677f3224553c | /LI/lib/python3.8/site-packages/astropy/table/connect.py | 20778cbcf66bf2fed8dc443a2322609ea7ab97d9 | [
"MIT"
] | permissive | honeybhardwaj/Language_Identification | 2a247d98095bd56c1194a34a556ddfadf6f001e5 | 1b74f898be5402b0c1a13debf595736a3f57d7e7 | refs/heads/main | 2023-04-19T16:22:05.231818 | 2021-05-15T18:59:45 | 2021-05-15T18:59:45 | 351,470,447 | 5 | 4 | MIT | 2021-05-15T18:59:46 | 2021-03-25T14:42:26 | Python | UTF-8 | Python | false | false | 4,446 | py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy.io import registry
from .info import serialize_method_as
__all__ = ['TableRead', 'TableWrite']
__doctest_skip__ = ['TableRead', 'TableWrite']
class TableRead(registry.UnifiedReadWrite):
"""Read and parse a data table and return as a Table.
This function provides the Table interface to the astropy unified I/O
layer. This allows easily reading a file in many supported data formats
using syntax such as::
>>> from astropy.table import Table
>>> dat = Table.read('table.dat', format='ascii')
>>> events = Table.read('events.fits', format='fits')
Get help on the available readers for ``Table`` using the``help()`` method::
>>> Table.read.help() # Get help reading Table and list supported formats
>>> Table.read.help('fits') # Get detailed help on Table FITS reader
>>> Table.read.list_formats() # Print list of available formats
See also: https://docs.astropy.org/en/stable/io/unified.html
Parameters
----------
*args : tuple, optional
Positional arguments passed through to data reader. If supplied the
first argument is typically the input filename.
format : str
File format specifier.
units : list, dict, optional
List or dict of units to apply to columns
descriptions : list, dict, optional
List or dict of descriptions to apply to columns
**kwargs : dict, optional
Keyword arguments passed through to data reader.
Returns
-------
out : `Table`
Table corresponding to file contents
Notes
-----
"""
def __init__(self, instance, cls):
super().__init__(instance, cls, 'read')
def __call__(self, *args, **kwargs):
cls = self._cls
units = kwargs.pop('units', None)
descriptions = kwargs.pop('descriptions', None)
out = registry.read(cls, *args, **kwargs)
# For some readers (e.g., ascii.ecsv), the returned `out` class is not
# guaranteed to be the same as the desired output `cls`. If so,
# try coercing to desired class without copying (io.registry.read
# would normally do a copy). The normal case here is swapping
# Table <=> QTable.
if cls is not out.__class__:
try:
out = cls(out, copy=False)
except Exception:
raise TypeError('could not convert reader output to {} '
'class.'.format(cls.__name__))
out._set_column_attribute('unit', units)
out._set_column_attribute('description', descriptions)
return out
class TableWrite(registry.UnifiedReadWrite):
"""
Write this Table object out in the specified format.
This function provides the Table interface to the astropy unified I/O
layer. This allows easily writing a file in many supported data formats
using syntax such as::
>>> from astropy.table import Table
>>> dat = Table([[1, 2], [3, 4]], names=('a', 'b'))
>>> dat.write('table.dat', format='ascii')
Get help on the available writers for ``Table`` using the``help()`` method::
>>> Table.write.help() # Get help writing Table and list supported formats
>>> Table.write.help('fits') # Get detailed help on Table FITS writer
>>> Table.write.list_formats() # Print list of available formats
The ``serialize_method`` argument is explained in the section on
`Table serialization methods
<https://docs.astropy.org/en/latest/io/unified.html#table-serialization-methods>`_.
See also: https://docs.astropy.org/en/stable/io/unified.html
Parameters
----------
*args : tuple, optional
Positional arguments passed through to data writer. If supplied the
first argument is the output filename.
format : str
File format specifier.
serialize_method : str, dict, optional
Serialization method specifier for columns.
**kwargs : dict, optional
Keyword arguments passed through to data writer.
Notes
-----
"""
def __init__(self, instance, cls):
super().__init__(instance, cls, 'write')
def __call__(self, *args, serialize_method=None, **kwargs):
instance = self._instance
with serialize_method_as(instance, serialize_method):
registry.write(instance, *args, **kwargs)
| [
"honey.bhardwaj.18cse@bmu.edu.in"
] | honey.bhardwaj.18cse@bmu.edu.in |
58364a12ae6bcd575ef90327f0483265e2a95353 | 36da6c5f553d4eb97cc2b6798d8017f313b2705e | /knowledgeCity0610/remoteio/remoteioMgr_old.py | 6fcb05c017354391204d8f286d5bfe7a2b081e7c | [] | no_license | MOZIJANE/jingxin | da10476edfc25ffbbe87eb8f127c600ce6ad30ce | 01e7e419b15da1b6a7c127d1db1a042a24a12146 | refs/heads/master | 2023-06-06T05:05:11.953104 | 2021-06-23T04:27:22 | 2021-06-23T04:27:22 | 378,850,323 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,888 | py | # coding=utf-8
# lzxs 2018-8-2 create
import sys, os
import threading
import json
import setup
if __name__ == '__main__':
setup.setCurPath(__file__)
import utility
# import remoteio.remoteioControl as remoteioControl
import modbusapi
import log
import time
import modbus_tk.defines as mdef
import lock as lockImp
g_remoteioList = None
import alarm.aliveApi
D0 = 0x0000
D1 = 0x0001
D2 = 0x0002
D3 = 0x0003
D4 = 0x0004
D5 = 0x0005
D6 = 0x0006
D7 = 0x0007
D10 = 0x0010 # 0 01/05 1 号 DO 值 读写
D11 = 0x0011 # 1 01/05 2 号 DO 值 读写
D12 = 0x0012 # 2 01/05 3 号 DO 值 读写
D13 = 0x0013 # 3 01/05 4 号 DO 值 读写
D14 = 0x0014 # 4 01/05 5 号 DO 值 读写
D15 = 0x0015 # 5 01/05 6 号 DO 值 读写
D16 = 0x0016 # 6 01/05 7 号 DO 值 读写
D17 = 0x0017 # 7 01/05 8 号 DO 值 读写
IO_LENTH = 8
def get(id):
return getList()[id]
def _loadRemoteioList():
file = "/remoteio.json"
with open(os.path.abspath(os.path.dirname(__file__)) + file, 'r') as f:
remoteioList = json.load(f)
ret = {}
for remoteioId in remoteioList:
if remoteioList[remoteioId]["enable"].lower() == "false":
continue
ip = remoteioList[remoteioId]["ip"]
port = remoteioList[remoteioId]["port"]
remoteio = remoteioInfo(remoteioId, ip, port)
ret[remoteioId] = remoteio
return ret
def getList():
global g_remoteioList
if g_remoteioList is None:
g_remoteioList = _loadRemoteioList()
return g_remoteioList
def writeDO(id, index, value):
remoteioInfo= get(id)
remoteioInfo.writeDO(index,value)
return {}
def writeDOList(id, values):
remoteioInfo = get(id)
remoteioInfo.writeDOList(values)
return {}
def readDI(id, index):
remoteioInfo = get(id)
result=remoteioInfo.readDI(index)
return {"status":result}
def readDO(id, index):
remoteioInfo = get(id)
result=remoteioInfo.readDO(index)
return {"status":result}
def readDIList(id):
remoteioInfo = get(id)
result=remoteioInfo.readDIList()
return {"status":result}
def readDOList(id):
remoteioInfo = get(id)
result=remoteioInfo.readDOList()
return {"status":result}
class remoteioInfo:
def __init__(self, remoteioId, ip, port,slaverId=1):
self.id = remoteioId
self.ip = ip
self.port = port
self.slaverId = 1
self.m_lock = threading.RLock()
self.master = modbusapi.tcpMaster(self.slaverId, self.ip)
# DO操作
def writeDO(self,index,value):
try:
ioAddr = getDoAddr(index)
self._write(ioAddr, value)
except Exception as ex:
self.master.close()
self.master = None
log.exception("%s writeDO fail"%self.id,ex)
raise
def writeDOList(self,value):
try:
l = list(map(lambda x: int(x), value.split(',')))
self._write(D10,l,IO_LENTH)
except Exception as ex:
self.master.close()
self.master = None
log.exception("%s writeDOList fail"%self.id,ex)
raise
def readDI(self,index):
try:
ioAddr = getDiAddr(index)
return self._read(ioAddr)
except Exception as ex:
self.master.close()
self.master = None
log.exception("%s readDI fail"%self.id,ex)
raise
def readDIList(self):
try:
return self._read(D0, IO_LENTH)
except Exception as ex:
self.master.close()
self.master = None
log.exception("%s readDIList fail"%self.id,ex)
raise
# DI操作
def readDO(self,index):
try:
ioAddr = getDoAddr(index)
return self._read(ioAddr)
except Exception as ex:
self.master.close()
self.master = None
log.exception("%s readDO fail"%self.id,ex)
raise
def readDOList(self):
try:
return self._read(D10, IO_LENTH)
except Exception as ex:
self.master.close()
self.master = None
log.exception("%s readDOList fail"%self.id,ex)
raise
@lockImp.lock(None)
def _read(self,addr,length=None):
if self.master is None:
self.master = modbusapi.tcpMaster(self.slaverId, self.ip)
self.master.open()
time.sleep(0.5)
if length:
s = self.master.read(mdef.READ_COILS,addr, length)
else:
s = self.master.read(mdef.READ_COILS,addr,1)[0]
return s
@lockImp.lock(None)
def _write(self,addr,value,length=None):
if self.master is None:
self.master = modbusapi.tcpMaster(self.slaverId, self.ip)
self.master.open()
time.sleep(0.5)
if length:
s = self.master.write(mdef.WRITE_MULTIPLE_COILS,addr, value, length)
else:
s = self.master.write(mdef.WRITE_SINGLE_COIL,addr,value)
return s
def getDiAddr(addr):
if addr == 1:
ioAddr = D10
elif addr == 2:
ioAddr = D11
elif addr == 3:
ioAddr = D12
elif addr == 4:
ioAddr = D13
elif addr == 5:
ioAddr = D14
elif addr == 6:
ioAddr = D15
elif addr == 7:
ioAddr = D16
elif addr == 8:
ioAddr = D17
else:
raise Exception("参数错误")
return ioAddr
def getDoAddr(addr):
if addr == 1:
ioAddr = D10
elif addr == 2:
ioAddr = D11
elif addr == 3:
ioAddr = D12
elif addr == 4:
ioAddr = D13
elif addr == 5:
ioAddr = D14
elif addr == 6:
ioAddr = D15
elif addr == 7:
ioAddr = D16
elif addr == 8:
ioAddr = D17
else:
raise Exception("参数错误")
return ioAddr
def remoteioCheck():
import shell
checkCount = 0
g_laststatus = {}
remoteiolistalarm = {}
remoteiolist = getList()
if not remoteiolistalarm:
for id in remoteiolist:
info = get(id)
g_laststatus.update({id:True})
larm =alarm.aliveApi.aliveObj(moid=id, typeId=39998, desc="远程控制IO离线异常", timeoutSecond=60, domain="agv")
remoteiolistalarm.update({id:larm})
# log.info("++++++++remoteiolistalarm",larm, id,info.ip)
while not utility.is_exited():
for id in remoteiolist:
info = get(id)
if shell.ping(info.ip, showLog=False):
remoteiolistalarm[id].check()
time.sleep(5)
checkThread = threading.Thread(target=remoteioCheck,name="remoteio.ping")
checkThread.start()
if __name__ == '__main__':
utility.run_tests()
| [
"1051945562@qq.com"
] | 1051945562@qq.com |
49dcedfd70d8de54cf3d3d22aef12b1c668a5e73 | f908adce7e25824f7daaffddfaacb2a18b3e721b | /feder/cases/migrations/0007_auto_20180325_2244.py | 8f103956f10efc94fc5f727235b3590001bc9abe | [
"MIT"
] | permissive | miklobit/feder | 7c0cfdbcb0796f8eb66fd67fa4dabddb99370a7c | 14a59e181a18af5b625ccdcbd892c3b886a8d97e | refs/heads/master | 2023-01-13T23:03:51.266990 | 2020-11-12T14:31:52 | 2020-11-12T15:47:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 466 | py | # Generated by Django 2.0.3 on 2018-03-25 22:44
import autoslug.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("cases", "0006_alias")]
operations = [
migrations.AlterField(
model_name="case",
name="slug",
field=autoslug.fields.AutoSlugField(
editable=False, populate_from="name", unique=True, verbose_name="Slug"
),
)
]
| [
"naczelnik@jawnosc.tk"
] | naczelnik@jawnosc.tk |
5fb3a9efc2ea2479de46661403dc3c73482abc60 | 4e88ad4f7a14d4c1027d711ad19a70d616182cc4 | /backend/task/api/v1/urls.py | b3f694c192411f08420616b0dac4bb7edb39b6c1 | [] | no_license | crowdbotics-apps/test-24834 | 11c153b1f3a409a183de97cd822568f471ab2629 | 33b0b0b6a1793da8d2970b29a6c23152b2e6ec4b | refs/heads/master | 2023-03-15T15:47:38.489644 | 2021-03-05T18:28:00 | 2021-03-05T18:28:00 | 344,269,628 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 437 | py | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .viewsets import MessageViewSet, RatingViewSet, TaskViewSet, TaskTransactionViewSet
router = DefaultRouter()
router.register("tasktransaction", TaskTransactionViewSet)
router.register("task", TaskViewSet)
router.register("message", MessageViewSet)
router.register("rating", RatingViewSet)
urlpatterns = [
path("", include(router.urls)),
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
52263aca0037892c333edd8b32660fb688936773 | 78f43f8bd07ae0fc91738a63cd7bbca08ae26066 | /leetcode/bfs_dfs/android_unlock_patterns_dfs.py | c71381245a6537441a29e3c941330844a078db20 | [] | no_license | hanrick2000/LeetcodePy | 2f3a841f696005e8f0bf4cd33fe586f97173731f | b24fb0e7403606127d26f91ff86ddf8d2b071318 | refs/heads/master | 2022-04-14T01:34:05.044542 | 2020-04-12T06:11:29 | 2020-04-12T06:11:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,073 | py | from typing import List
class Solution:
"""
consist of minimum of m keys and maximum n keys
Runtime: 416 ms, faster than 78.53%
"""
def numberOfPatterns(self, m: int, n: int) -> int:
skip = {(1, 7): 4, (1, 3): 2, (1, 9): 5, (2, 8): 5, (3, 7): 5, (3, 9): 6, (4, 6): 5, (7, 9): 8}
res = 0
def dfs(visited: List[int], prev: int) -> None:
nonlocal res
if len(visited) >= m:
res += 1
if len(visited) == n:
return
for i in range(1, 10):
if i not in visited:
# sort the vertices of the edge before lookup `skip`
edge = (min(prev, i), max(prev, i))
if edge not in skip or skip[edge] in visited:
dfs(visited + [i], i)
# for i in range(1, 10): # Runtime: 1092 ms, faster than 45.76%
for i in [1, 2, 5]:
if i == 5:
res *= 4
dfs([i], i)
return res
print(Solution().numberOfPatterns(1, 1))
| [
"dofu@ebay.com"
] | dofu@ebay.com |
792f6de6a225614864c5e4c376444da1f50d4038 | e5e0d729f082999a9bec142611365b00f7bfc684 | /tensorflow/python/estimator/canned/dnn_linear_combined.py | e28499368f1687c4ab4972f04888da66a47b0f5a | [
"Apache-2.0"
] | permissive | NVIDIA/tensorflow | ed6294098c7354dfc9f09631fc5ae22dbc278138 | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | refs/heads/r1.15.5+nv23.03 | 2023-08-16T22:25:18.037979 | 2023-08-03T22:09:23 | 2023-08-03T22:09:23 | 263,748,045 | 763 | 117 | Apache-2.0 | 2023-07-03T15:45:19 | 2020-05-13T21:34:32 | C++ | UTF-8 | Python | false | false | 1,349 | py | # Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""dnn_linear_combined python module.
Importing from tensorflow.python.estimator is unsupported
and will soon break!
"""
# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_estimator.python.estimator.canned import dnn_linear_combined
# Include attrs that start with single underscore.
_HAS_DYNAMIC_ATTRIBUTES = True
dnn_linear_combined.__all__ = [
s for s in dir(dnn_linear_combined) if not s.startswith('__')
]
from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import *
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
b4d4ceaff1275f2eb8b9a5807035b802950627f8 | 9a2413b572c0f89b1f80899a10237657d9393bd6 | /sdk/python/pulumi_keycloak/openid/client_optional_scopes.py | a52259f31c6be7621a5ada153c069d32b6118951 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | jaxxstorm/pulumi-keycloak | 5c25363ece6af49dad40bd693ce07b1fa0dedd74 | 2fc7b1060b725a40d2ada745aa0d10130243a0b5 | refs/heads/master | 2022-10-10T13:11:04.290703 | 2020-06-05T19:11:19 | 2020-06-05T19:11:19 | 270,870,883 | 0 | 0 | NOASSERTION | 2020-06-09T01:08:56 | 2020-06-09T01:08:55 | null | UTF-8 | Python | false | false | 3,482 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class ClientOptionalScopes(pulumi.CustomResource):
client_id: pulumi.Output[str]
optional_scopes: pulumi.Output[list]
realm_id: pulumi.Output[str]
def __init__(__self__, resource_name, opts=None, client_id=None, optional_scopes=None, realm_id=None, __props__=None, __name__=None, __opts__=None):
"""
Create a ClientOptionalScopes resource with the given unique name, props, and options.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
if client_id is None:
raise TypeError("Missing required property 'client_id'")
__props__['client_id'] = client_id
if optional_scopes is None:
raise TypeError("Missing required property 'optional_scopes'")
__props__['optional_scopes'] = optional_scopes
if realm_id is None:
raise TypeError("Missing required property 'realm_id'")
__props__['realm_id'] = realm_id
super(ClientOptionalScopes, __self__).__init__(
'keycloak:openid/clientOptionalScopes:ClientOptionalScopes',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name, id, opts=None, client_id=None, optional_scopes=None, realm_id=None):
"""
Get an existing ClientOptionalScopes resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param str id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["client_id"] = client_id
__props__["optional_scopes"] = optional_scopes
__props__["realm_id"] = realm_id
return ClientOptionalScopes(resource_name, opts=opts, __props__=__props__)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| [
"public@paulstack.co.uk"
] | public@paulstack.co.uk |
2704e6f84e46c139529f9206e7c2166217968b5a | e61e664d95af3b93150cda5b92695be6551d2a7c | /vega/modules/tensformers/pooler.py | 89b4fdf3207eb1794f0a6c40a086cfe87d580336 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | huawei-noah/vega | 44aaf8bb28b45f707ed6cd4e871ba70fc0c04846 | 12e37a1991eb6771a2999fe0a46ddda920c47948 | refs/heads/master | 2023-09-01T20:16:28.746745 | 2023-02-15T09:36:59 | 2023-02-15T09:36:59 | 273,667,533 | 850 | 184 | NOASSERTION | 2023-02-15T09:37:01 | 2020-06-20T08:20:06 | Python | UTF-8 | Python | false | false | 1,383 | py | # -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. 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.
"""This is Pooler for Bert."""
from vega.modules.operators import ops
from vega.modules.module import Module
from vega.common.class_factory import ClassType, ClassFactory
@ClassFactory.register(ClassType.NETWORK)
class Pooler(Module):
"""Pooler layer to pooling first_token from encoder."""
def __init__(self, config):
super(Pooler, self).__init__()
self.dense = ops.Linear(config.hidden_size, config.hidden_size)
self.activation = ops.Tanh()
def call(self, hidden_states):
"""Get token and pooling."""
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
| [
"zhangjiajin@huawei.com"
] | zhangjiajin@huawei.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.