blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2 values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220 values | src_encoding stringclasses 30 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 2 10.3M | extension stringclasses 257 values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aaa856e1b4ceb5000f6ed483577d1b5f78a93e9b | 0ddcf5569f3214583ceb8ce65734d087bfe6e26f | /main.py | 3dcd6c61f282de0d01112405ddb4c6b2c9cc6a6e | [] | no_license | kubawirus/pythonCanteraTrial | ad8ebab2173e3761ee77afcef5864cc73d35b600 | f9455a312c0deb52f6fa189532c6a497fc4fb2e5 | refs/heads/master | 2023-05-01T05:12:27.325423 | 2021-05-11T12:24:44 | 2021-05-11T12:24:44 | 364,248,420 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 42 | py | import cantera as ct
import numpy as np
| [
"k.wieremiejczuk@gmail.com"
] | k.wieremiejczuk@gmail.com |
0509f599fc55aff09422b32059466ba37f55ba10 | 4b7deb5769a689a333efe7b3a32a6a0ac69d67bc | /windows/samples/python/sample_open3d_pclviewer.py | bb7249a9ea684bcdb953b157657f6deb39961a14 | [] | no_license | ZC1231/SDK | cadc4b884b2f05fbd0d4b72448ea60e76c00fbae | 13bc36b5ce8a76a30ad4d469a00e8df75203abfb | refs/heads/master | 2022-11-29T06:12:49.086402 | 2020-08-11T12:38:33 | 2020-08-11T12:38:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,071 | py | import sys, os
import numpy as np
import time
import open3d as o3d
import dmcam
# -- init the lib with default log file
dmcam.init(None)
# -- init with specified log file
# dmcam.init("test.log")
# -- set debug level
dmcam.log_cfg(dmcam.LOG_LEVEL_INFO, dmcam.LOG_LEVEL_DEBUG, dmcam.LOG_LEVEL_NONE)
# -- list device
print(" Scanning dmcam device ..")
devs = dmcam.dev_list()
if devs is None:
print(" No device found")
sys.exit(1)
print("found %d device" % len(devs))
for i in range(len(devs)):
print("#%d: %s" % (i, dmcam.dev_get_uri(devs[i], 256)[0]))
print(" Open dmcam device ..")
# open the first device
dev = dmcam.dev_open(devs[0])
# Or open by URI
# dev = dmcam.dev_open_by_uri(br"xxx")
assert dev is not None
# - set capture config -
cap_cfg = dmcam.cap_cfg_t()
cap_cfg.cache_frames_cnt = 10 # framebuffer = 10
cap_cfg.on_error = None # use cap_set_callback_on_error to set cb
cap_cfg.on_frame_rdy = None # use cap_set_callback_on_frame_ready to set cb
cap_cfg.en_save_replay = False # True = save replay, False = not save
cap_cfg.en_save_dist_u16 = False # True to save dist stream for openni replay
cap_cfg.en_save_gray_u16 = False # True to save gray stream for openni replay
cap_cfg.fname_replay = os.fsencode("dm_replay.oni") # set replay filename
dmcam.cap_config_set(dev, cap_cfg)
# dmcam.cap_set_callback_on_frame_ready(dev, on_frame_rdy)
# dmcam.cap_set_callback_on_error(dev, on_cap_err)
print(" Set paramters ...")
wparams = {
dmcam.PARAM_INTG_TIME: dmcam.param_val_u(),
dmcam.PARAM_FRAME_RATE: dmcam.param_val_u(),
dmcam.PARAM_MOD_FREQ: dmcam.param_val_u(),
}
# set dual frequency modulation, note that mod_freq0 should always be larger than mod_freq1
# you can trivially set mod_freq1 to zeros, if single frequency modulation is desired
wparams[dmcam.PARAM_MOD_FREQ].mod_freq0=100000000
wparams[dmcam.PARAM_MOD_FREQ].mod_freq1=36000000
wparams[dmcam.PARAM_INTG_TIME].intg.intg_us = 1000
wparams[dmcam.PARAM_FRAME_RATE].frame_rate.fps = 20
amp_min_val = dmcam.filter_args_u()
amp_min_val.min_amp = 80
if not dmcam.filter_enable(dev, dmcam.DMCAM_FILTER_ID_AMP, amp_min_val,
sys.getsizeof(amp_min_val)):
print("set amp to %d %% failed" % amp_min_val.min_amp)
if not dmcam.param_batch_set(dev, wparams):
print(" set parameter failed")
print(" Start capture ...")
dmcam.cap_start(dev)
f = bytearray(640 * 480 * 4 * 2)
print(" sampling 100 frames ...")
count = 0
run = True
vis = o3d.visualization.Visualizer()
vis.create_window()
opt = vis.get_render_option()
opt.background_color = np.asarray([0, 0, 0])
opt.point_size = 1
opt.show_coordinate_frame = True
pcd = o3d.geometry.PointCloud()
bind_flag = False
while run:
# get one frame
finfo = dmcam.frame_t()
ret = dmcam.cap_get_frames(dev, 1, f, finfo)
# print("get %d frames" % ret)
if ret > 0:
w = finfo.frame_info.width
h = finfo.frame_info.height
print(" frame @ %d, %d, %dx%d" %
(finfo.frame_info.frame_idx, finfo.frame_info.frame_size, w, h))
dist_cnt, dist = dmcam.frame_get_distance(dev, w * h, f, finfo.frame_info)
gray_cnt, gray = dmcam.frame_get_gray(dev, w * h, f, finfo.frame_info)
_, pcloud = dmcam.frame_get_pcl(dev, w * h*3, dist, w, h, None)
pcd.points=o3d.utility.Vector3dVector(pcloud.reshape(-1, 3))
if not bind_flag:
vis.add_geometry(pcd)
bind_flag = True
else:
vis.update_geometry(pcd)
vis.poll_events()
vis.update_renderer()
#o3d.visualization.draw_geometries([pcd])
# dist = dmcam.raw2dist(int(len(f) / 4), f)
# gray = dmcam.raw2gray(int(len(f) / 4), f)
else:
break
time.sleep(0.01)
# break
vis.destroy_window()
print(" Stop capture ...")
dmcam.cap_stop(dev)
print(" Close dmcam device ..")
dmcam.dev_close(dev)
dmcam.uninit()
| [
"U1@ip-192-168-254-95.cn-northwest-1.compute.internal"
] | U1@ip-192-168-254-95.cn-northwest-1.compute.internal |
1b2a6c3181548e466eacfa3b040cbc883242e73b | 35f1a21affd266e0069bfc5a1c83218847f13802 | /pastie-5073437.py | 9cc5c027ce00562a66e8461c02cfa8768964c92c | [] | no_license | KarenWest/pythonClassProjects | ff1e1116788174a2affaa96bfcb0e97df3ee92da | 5aa496a71d36ffb9892ee6e377bd9f5d0d8e03a0 | refs/heads/master | 2016-09-16T15:20:26.882688 | 2014-02-21T20:07:57 | 2014-02-21T20:07:57 | 17,055,355 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 772 | py | #balance = 5000
#annualInterestRate = 0.18
#monthlyPaymentRate = 0.02
months = range(1, 13) # 1, 2, ... , 11, 12
owe = balance # It made sense to me to call this total amount oweing
totalPaid = 0
for month in months:
minPay = owe * monthlyPaymentRate # calculate our minimum payment
interest = (owe - minPay) * (annualInterestRate / 12) # same for interest
owe = owe - minPay + interest # calculate our new balance
totalPaid += minPay # Sum up how much we've paid so far
print('Month: %d' % month) # %d will be replaced by month
print('Minimum monthly payment: %.2f' % minPay) # %.2f replaced by minPay, with 2 decimal places
print('Remaining balance: %.2f' % owe)
print('Total paid %.2f' % totalPaid)
print('Remaining balance: %.2f' % owe)
| [
"KarenWest15@gmail.com"
] | KarenWest15@gmail.com |
4d909ba4892e6c9c564466ba0ea7fe903b3857ab | 8bc7ba8eb10e30b38f2bcf00971bfe540c9d26b7 | /paxes_cinder/k2aclient/v1/virtualswitch_manager.py | 6d956eb5bdf9ebcdab6aba2f1378e4c6151dbbdc | [
"Apache-2.0"
] | permissive | windskyer/k_cinder | f8f003b2d1f9ca55c423ea0356f35a97b5294f69 | 000ee539ee4842a158071d26ee99d12c7c0a87da | refs/heads/master | 2021-01-10T02:19:51.072078 | 2015-12-08T15:24:33 | 2015-12-08T15:24:33 | 47,629,931 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,938 | py | #
#
# =================================================================
# =================================================================
"""VirtualSwitch interface."""
from paxes_cinder.k2aclient import base
from paxes_cinder.k2aclient.v1 import k2uom
class VirtualSwitchManager(base.ManagerWithFind):
"""Manage :class:`ClientNetworkAdapter` resources."""
resource_class = k2uom.VirtualSwitch
def new(self):
return self.resource_class(self, None)
def list(self, managedsystem, xa=None):
"""Get a list of all VirtualSwitch for a particular
ManagedSystem accessed through a particular hmc.
:rtype: list of :class:`ClientNetworkAdapter`.
"""
return self._list("/rest/api/uom/ManagedSystem/%s/VirtualSwitch"
% managedsystem, xa=xa)
def get(self, managedsystem, virtualswitch, xa=None):
"""Given managedsystem, get a specific VirtualSwitch.
:param virtualswitch: The ID of the :class:`VirtualSwitch`.
:rtype: :class:`VirtualSwitch`
"""
return self._get("/rest/api/uom/ManagedSystem/%s/VirtualSwitch/%s"
% (managedsystem, virtualswitch,),
xa=xa)
def delete(self, managedsystem, virtualswitch, xa=None):
"""Delete the specified instance
"""
return self._delete("uom",
managedsystem,
child=virtualswitch,
xa=xa)
def deletebyid(self, managedsystem_id, virtualswitch_id, xa=None):
"""Delete the specified instance
"""
return self._deletebyid("uom",
"ManagedSystem",
managedsystem_id,
child_type=k2uom.VirtualSwitch,
child_id=virtualswitch_id,
xa=xa)
| [
"leidong@localhost"
] | leidong@localhost |
fcb2435eb093fb368a090ef2efed05fd1120970b | 2e83b09448d2756ac0c8f77568086763391a43c8 | /trackback.py | 6014ed7933bc4f0d5720fe1f24124721456b4d4e | [] | no_license | raghvendra98/Computer-vision-OpenCV | f298cee5600bff7abfdaf9cc69ae1793affeb923 | 084b8f4061b3871a2103680af73301629f18df32 | refs/heads/master | 2023-02-17T01:45:53.735727 | 2021-01-16T13:42:31 | 2021-01-16T13:42:31 | 320,251,637 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 685 | py | import numpy as np
import cv2 as cv
def nothing(x):
print(x)
# Create a black image, a window
cv.namedWindow('image')
cv.createTrackbar('CP', 'image', 10, 400, nothing)
switch = 'color/gray'
cv.createTrackbar(switch, 'image', 0, 1, nothing)
while(1):
img = cv.imread('trex.png')
pos = cv.getTrackbarPos('CP', 'image')
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img, str(pos), (50, 150), font, 3, (0, 0, 255), 10)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
s = cv.getTrackbarPos(switch, 'image')
if s == 0:
pass
else:
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img = cv.imshow('image',img)
cv.destroyAllWindows() | [
"50679225+raghvendra98@users.noreply.github.com"
] | 50679225+raghvendra98@users.noreply.github.com |
a4e7a4cadea98270cebf7bd8ab170c2f030ac42c | f0ec40da9043db89265b2f90f7c77f896b9344aa | /instaclone/migrations/0004_auto_20170724_0943.py | 8a0c180cc08c42cdb1e0a091134b137a40d1d4c7 | [] | no_license | shivajaat/InstaClone | 9c5547837ec639195a93f316dcd82703d2e0b621 | c0cabe48abde151920c5a480738523acee819a84 | refs/heads/master | 2021-01-02T08:35:36.497159 | 2017-08-01T17:16:11 | 2017-08-01T17:16:11 | 99,025,465 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 640 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-24 04:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instaclone', '0003_auto_20170724_0940'),
]
operations = [
migrations.AlterField(
model_name='usermodel',
name='email',
field=models.CharField(max_length=40, unique=True),
),
migrations.AlterField(
model_name='usermodel',
name='username',
field=models.CharField(max_length=20, unique=True),
),
]
| [
"shivajaat21@gmail.com"
] | shivajaat21@gmail.com |
5f844ff0add74663d1b5f8196c9802f858ac8f5b | ea384acfec1ae21bc8583258ecaa187ded4b22d6 | /data/base/prototypes/entity/miningDrills.py | 9f855b6f52051c33e371df5debe3a40a633cb7d9 | [
"MIT"
] | permissive | cmk1988/Jactorio | da03e97d0fa8bfbf9428e45aa2e4772c0ea9542b | 4056b4c16614d566ec8d90b250621e03645bf4d2 | refs/heads/master | 2023-03-28T03:05:24.337666 | 2021-03-13T20:31:30 | 2021-03-13T20:31:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,510 | py | import jactorioData as j
def addSprite(spritePath):
return (j.Sprite()
.load(spritePath)
.frames(8)
.sets(8)
)
def createDrill(name, icon, spriteN, spriteE, spriteS, spriteW):
(j.MiningDrill(name)
.rotatable(True)
.pickupTime(0.1)
.miningSpeed(1)
.item(
j.Item(name + "-item")
.sprite(
j.Sprite()
.load(icon)
)
)
.sprite(addSprite(spriteN))
.spriteE(addSprite(spriteE))
.spriteS(addSprite(spriteS))
.spriteW(addSprite(spriteW))
.tileWidth(3)
.tileHeight(3)
# resource output: up, right, down left
# <U>
# [0] [ ] [ ]
# <L> [ ] [ ] [ ] <R>
# [ ] [ ] [ ]
# <D>
.resourceOutput(j._OutputTile4Way(
(
(1, -1),
(3, 1),
(1, 3),
(-1, 1)
)
))
)
createDrill("electric-mining-drill",
"base/graphics/icon/electric-mining-drill.png",
"base/graphics/entity/electric-mining-drill/electric-mining-drill-N.png",
"base/graphics/entity/electric-mining-drill/electric-mining-drill-E.png",
"base/graphics/entity/electric-mining-drill/electric-mining-drill-S.png",
"base/graphics/entity/electric-mining-drill/electric-mining-drill-W.png")
| [
"jaihysc@gmail.com"
] | jaihysc@gmail.com |
b6accd03937aff683e9c67bcc79daa3e0d5517c3 | 5f80ca7e63eef57c044d937d60a6e3d6e8f138cc | /b2week4.py | adebb2539d6fac6ce435a543badb661b745bb0e4 | [] | no_license | sjerkovic/Bioinformatics-specialization | 49125231650a2db1423f3f2ef49130e99b754bd6 | 1d599934675c8663a61fdedd8944aea0e2cd8ea6 | refs/heads/main | 2023-04-15T20:31:33.249693 | 2021-05-02T22:11:42 | 2021-05-02T22:11:42 | 363,510,584 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 287 | py | def spectral_convolution(spectrum):
spectrum_int = sorted([int(v) for v in spectrum.split()])
convolution = []
for i in spectrum_int:
for j in spectrum_int:
a = i-j
if a>0:
convolution.append(a)
return convolution
| [
"noreply@github.com"
] | sjerkovic.noreply@github.com |
e463337960661352eec76273356b1323176686ca | 04ae1836b9bc9d73d244f91b8f7fbf1bbc58ff29 | /170/Solution.py | 1ece9965f93617191e3d6e484aeefd64c54f0c67 | [] | no_license | zhangruochi/leetcode | 6f739fde222c298bae1c68236d980bd29c33b1c6 | cefa2f08667de4d2973274de3ff29a31a7d25eda | refs/heads/master | 2022-07-16T23:40:20.458105 | 2022-06-02T18:25:35 | 2022-06-02T18:25:35 | 78,989,941 | 14 | 6 | null | null | null | null | UTF-8 | Python | false | false | 2,272 | py | """
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
Example 1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Example 2:
add(3); add(1); add(2);
find(3) -> true
find(6) -> false
"""
from collections import defaultdict
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.count = 0
self.numbers = defaultdict(list)
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
self.numbers[number].append(self.count)
self.count += 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for num, indexs in self.numbers.items():
tmp = value - num
if tmp in self.numbers:
if tmp == num and len(indexs) > 1:
return True
if tmp != num:
return True
return False
class TwoSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = {}
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: None
"""
if number not in self.nums:
self.nums[number] = 1
else:
self.nums[number] += 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for key in self.nums:
second = value - key
if ((key != second) and second in self.nums) or (key == second and self.nums[key] > 1):
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value) | [
"zrc720@gmail.com"
] | zrc720@gmail.com |
51bacc265849e99d5638fe2aa84fb25204c57781 | a0dda8be5892a390836e19bf04ea1d098e92cf58 | /叶常春视频例题/chap05/5-2-9-生词清单.py | 6c9697103cde9015e7e96499929c29627c18643d | [] | no_license | wmm98/homework1 | d9eb67c7491affd8c7e77458ceadaf0357ea5e6b | cd1f7f78e8dbd03ad72c7a0fdc4a8dc8404f5fe2 | refs/heads/master | 2020-04-14T19:22:21.733111 | 2019-01-08T14:09:58 | 2019-01-08T14:09:58 | 164,055,018 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 307 | py | # 例5-2-9 生词清单
new_words = []
for i in range(1, 101):
word = input("输入生词:")
if word == "*":
break # break语句的作用是跳出循环,执行循环后面的语句。
if word not in new_words:
new_words.append(word)
print("生词清单:", new_words) | [
"792545884@qq.com"
] | 792545884@qq.com |
927c002da1456a2be2e42271cff26c52213d5fc3 | 85c594b9f5af241d25a4957ba57c65cc1b473008 | /pywrap/setup.py | 43dced996b3fb659e394fca25776f618590906ed | [] | no_license | jeffli678/autoit | 84dca4a78b892a0ab8a7b00c3682481c70d667d3 | a0e57b382abe3d4caed9d2371672fd003bed4c61 | refs/heads/master | 2021-05-27T10:58:32.741270 | 2012-10-10T16:55:30 | 2012-10-10T16:55:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 516 | py | from distutils.core import setup, Extension
import platform
osname = platform.system()
if osname == "Windows":
shared_libs = []
else:
shared_libs = []
module = Extension('pyautoit',
sources = ['pyautoit.cpp'],
libraries = shared_libs,
library_dirs = [],
extra_objects = ["../build/lib/libautoit.a"],
)
setup(name = 'pyautoit',
version = '0.2.0',
description = 'Python module wrapping libautoit',
author = 'kimzhang',
author_email = 'analyst004@gmail.com',
ext_modules = [module])
| [
"analyst004@gmail.com"
] | analyst004@gmail.com |
323801345ddf65b4f2d46b72eae6c8c91ab6e767 | 11147666888ce8a0d6bd540b1d1d4bf7a788f4bb | /server/botserver.py | 84f5477d38903f2a824ba9d8243e8d3f9b0b299b | [
"MIT"
] | permissive | Kileak/Kileak-Slack-Base-Bot | 4ef4312955db30e54dd36e2f50e279c33af7fce2 | 5a1c14b96383f4d5bbbde87670d4f080530c4fdf | refs/heads/master | 2021-01-20T08:24:33.079050 | 2017-09-07T12:20:43 | 2017-09-07T12:20:43 | 101,556,351 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,200 | py | import json
import threading
import time
from slackclient import SlackClient
from handlers.handler_factory import *
from handlers import *
from util.loghandler import *
from bottypes.invalid_console_command import *
class BotServer(threading.Thread):
# global lock for locking global data in bot server
threadLock = threading.Lock()
userList = []
def __init__(self):
log.debug("Parse config file and initialize threading...")
threading.Thread.__init__(self)
def lock(self):
"""Acquire global lock for working with global (not thread-safe) data."""
BotServer.threadLock.acquire()
def release(self):
"""Release global lock after accessing global (not thread-safe) data."""
BotServer.threadLock.release()
def updateUserList(self, slack_client):
self.lock()
log.debug("Retrieving user list")
api_call = slack_client.api_call("users.list")
if api_call.get('ok'):
BotServer.userList = api_call.get('members')
self.release()
def getUser(self, userName):
self.lock()
foundUser = None
for user in BotServer.userList:
if 'name' in user and user.get('name') == userName:
foundUser = user
break
self.release()
return foundUser
def quit(self):
log.info("Shutting down")
self.running = False
def sendMessage(self, channelID, msg):
self.slack_client.api_call(
"chat.PostMessage", channel=channelID, text=msg, as_user=True)
def load_config(self):
self.lock()
with open("./config.json") as f:
self.config = json.load(f)
self.release()
def get_config_option(self, option):
self.lock()
result = None
if option in self.config:
result = self.config[option]
self.release()
return result
def set_config_option(self, option, value):
self.lock()
try:
if option in self.config:
self.config[option] = value
log.info("Updated configuration: {} => {}".format(option, value))
with open("./config.json", "w") as f:
json.dump(self.config, f)
else:
raise InvalidConsoleCommand("The specified configuration option doesn't exist: {}".format(option))
finally:
self.release()
def parseSlackMessage(self, slackMessage):
"""
The Slack Real Time Messaging API is an events firehose.
Return (message, channel, user) if the message is directed at the bot,
otherwise return (None, None, None).
"""
message_list = slackMessage
for msg in message_list:
if msg.get("type") == "message":
if self.botAT in msg.get("text", ""):
# return text after the @ mention, whitespace removed
return msg['text'].split(self.botAT)[1].strip().lower(), msg['channel'], msg['user']
elif msg.get("text", "").startswith('!'):
# return text after the !
return msg['text'][1:].strip().lower(), msg['channel'], msg['user']
return None, None, None
def searchBotUser(self, botName):
log.debug("Trying to resolve bot user in slack")
self.updateUserList(self.slack_client)
self.botName = botName
botUser = self.getUser(self.botName)
if botUser:
self.botID = botUser['id']
self.botAT = "<@%s>" % self.botID
log.debug("Found bot user %s (%s)" % (self.botName, self.botID))
self.running = True
else:
log.error("Could not find bot user. Abort...")
self.running = False
def run(self):
log.info("Starting server thread...")
self.load_config()
self.slack_client = SlackClient(self.get_config_option('api_key'))
self.searchBotUser(self.get_config_option('bot_name'))
if self.botID:
# 1 second delay between reading from firehose
READ_WEBSOCKET_DELAY = 1
if self.slack_client.rtm_connect():
log.info("Connection successful...")
log.info("Initializing handlers...")
# Might even pass the bot server for handlers?
HandlerFactory.initialize(
self.slack_client, self.botID)
# Main loop
while self.running:
command, channel, user = self.parseSlackMessage(
self.slack_client.rtm_read())
if command:
log.debug("Received bot command : %s (%s)" %
(command, channel))
HandlerFactory.process(
self.slack_client, self, command, channel, user)
time.sleep(READ_WEBSOCKET_DELAY)
else:
log.error("Connection failed. Invalid slack token or bot id?")
log.info("Shutdown complete...")
| [
"razor99@gmx.de"
] | razor99@gmx.de |
abb8d377bfc14fc3f720ebee1401edf33b988493 | e0ea106f98cf3bff4a9473d4b225f56da60314d6 | /percy/__init__.py | a1e13d8a562a1a9380d0e06e996b210fa34e65a9 | [
"MIT"
] | permissive | getsentry/python-percy-client | e80dbf257a168cd08ed2af4cf0fbcc80f20ddaac | c3a80ed567ad40b2f1eaaea76f0886aa6f0367eb | refs/heads/master | 2023-08-05T23:24:46.855782 | 2017-07-14T00:45:20 | 2017-07-14T00:45:20 | 97,176,225 | 1 | 2 | MIT | 2020-10-27T22:44:01 | 2017-07-14T00:32:31 | Python | UTF-8 | Python | false | false | 285 | py | # -*- coding: utf-8 -*-
__author__ = 'Perceptual Inc.'
__email__ = 'team@percy.io'
__version__ = '1.0.1'
from percy.client import *
from percy.config import *
from percy.environment import *
from percy.resource import *
from percy.resource_loader import *
from percy.runner import *
| [
"mike@fotinakis.com"
] | mike@fotinakis.com |
6abcb0d176f43e109d8555a90281fa679fce1a72 | 64ac3af07036f240bc333f58f9ff9924d6fea06a | /modelrerank/src/main.py | 4502decd697e2341bdca9cb97474a8a809929668 | [
"Apache-2.0"
] | permissive | stevencdang/AutoML-DS-Components | b9e12011fd958f4734f323f4882806e8be4b64f2 | b0490262d3db5307c37f82c92e25cd938dd3a242 | refs/heads/master | 2023-01-10T13:06:27.167187 | 2019-03-28T18:11:40 | 2019-03-28T18:11:40 | 175,680,072 | 0 | 0 | Apache-2.0 | 2023-01-04T23:30:19 | 2019-03-14T18:42:27 | Python | UTF-8 | Python | false | false | 2,992 | py |
# Author: Steven C. Dang
# Main script for importing provided D3M dataset schemas for operation on datasets
import logging
import os.path as path
import sys
import json
import pprint
import argparse
import csv
import pandas as pd
# Workflow component specific imports
from ls_utilities.ls_logging import setup_logging
from ls_utilities.cmd_parser import get_default_arg_parser
from ls_utilities.ls_wf_settings import *
from ls_dataset.d3m_dataset import D3MDataset
from modeling.models import *
from modeling.component_out import *
__version__ = '0.1'
if __name__ == '__main__':
# Parse argumennts
parser = get_default_arg_parser("Rerank Model")
parser.add_argument('-model_id', type=str,
help='the name of the dataset to import')
parser.add_argument('-new_rank', type=int,
help='the new rank to resort the specified model')
parser.add_argument('-file0', type=argparse.FileType('r'),
help='the tab-separated list of models to select from')
args = parser.parse_args()
if args.is_test is not None:
is_test = args.is_test == 1
else:
is_test = False
# Get config file
config = SettingsFactory.get_settings(path.join(args.programDir, 'program', 'settings.cfg'),
program_dir=args.programDir,
working_dir=args.workingDir,
is_test=is_test
)
# Setup Logging
setup_logging(config)
logger = logging.getLogger('model_rerank')
### Begin Script ###
logger.info("Reranking the models according to new given rank")
logger.debug("Running Model Rerank with arguments: %s" % str(args))
if args.is_test is not None:
is_test = args.is_test == 1
else:
is_test = False
# Decode the models from file
logger.debug("ModelRank file input: %s" % args.file0)
m_index, ranked_models = ModelRankSetIO.from_file(args.file0)
selected_mid = m_index[int(args.model_id)]
model = ranked_models[selected_mid]
logger.debug("Seleted Model ID:\t %s" % selected_mid)
logger.debug("Seleted Ranked Model:\t%s" % str(model.to_dict()))
new_rank = int(args.new_rank)
logger.debug("Previous Rank %i\t New rank: %i" % (model.rank, new_rank))
# Resort the ranked models
ranks = range(1, len(ranked_models)+1)
mid_ranks = {mdl.rank: mid for mid, mdl in ranked_models.items()}
ordered_models = [mid_ranks[i] for i in ranks if mid_ranks[i] != selected_mid]
ordered_models.insert(new_rank - 1, selected_mid)
# Update new ranks for all models
for i, mid in enumerate(ordered_models):
ranked_models[mid].update_rank(i+1)
# Write dataset info to output file
out_file_path = path.join(args.workingDir, config.get('Output', 'out_file'))
ModelRankSetIO.to_file(out_file_path, ranked_models, m_index)
| [
"stevencdang@gmail.com"
] | stevencdang@gmail.com |
54256fc282316da722359a762ee5dc1ab76d62a0 | 09c4fef0e8941a40b5cdd1b1f689031361852727 | /csvwriter.py | d1aef78e356fdc96b6f3a281462513cd9776bdd1 | [] | no_license | jw910731/NTNU_TextProcessing_Final | c109fa3d1c391638817902c2fb5073e9063ad1a8 | 3ce60778b4868251e9de4e2a980b3f118a9c0352 | refs/heads/main | 2023-02-12T20:06:20.516885 | 2021-01-12T07:31:01 | 2021-01-12T07:31:01 | 307,621,039 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 114 | py | import pandas as pd
def csvwrite(DICT):
pd.DataFrame(DICT).to_csv('output.csv', header=True,encoding='utf-8') | [
"adam20001002@gmail.com"
] | adam20001002@gmail.com |
d4e630393d97b23b24b61c540310af9eced66716 | 4d4fcde3efaa334f7aa56beabd2aa26fbcc43650 | /server/src/uds/core/managers/userservice/comms.py | e2b06381d46b8a78ab640c8bf0c609b7fff00dda | [] | no_license | xezpeleta/openuds | a8b11cb34eb0ef7bb2da80f67586a81b2de229ef | 840a7a02bd7c9894e8863a8a50874cdfdbf30fcd | refs/heads/master | 2023-08-21T17:55:48.914631 | 2021-10-06T10:39:06 | 2021-10-06T10:39:06 | 414,489,331 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,264 | py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2019-2021 Virtual Cable S.L.U.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L.U. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
"""
import os
import json
import base64
import tempfile
import logging
import typing
import requests
if typing.TYPE_CHECKING:
from uds.models import UserService
logger = logging.getLogger(__name__)
TIMEOUT = 2
class NoActorComms(Exception):
pass
class OldActorVersion(NoActorComms):
pass
def _requestActor(
userService: 'UserService',
method: str,
data: typing.Optional[typing.MutableMapping[str, typing.Any]] = None,
minVersion: typing.Optional[str] = None,
) -> typing.Any:
"""
Makes a request to actor using "method"
if data is None, request is done using GET, else POST
if no communications url is provided or no min version, raises a "NoActorComms" exception (or OldActorVersion, derived from NoActorComms)
Returns request response value interpreted as json
"""
url = userService.getCommsUrl()
if not url:
# logger.warning('No notification is made because agent does not supports notifications: %s', userService.friendly_name)
raise NoActorComms(
'No notification urls for {}'.format(userService.friendly_name)
)
minVersion = minVersion or '2.0.0'
version = userService.getProperty('actor_version') or '0.0.0'
if '-' in version or version < minVersion:
logger.warning(
'Pool %s has old actors (%s)', userService.deployed_service.name, version
)
raise OldActorVersion(
'Old actor version {} for {}'.format(version, userService.friendly_name)
)
url += '/' + method
proxy = userService.deployed_service.proxy
try:
if proxy:
r = proxy.doProxyRequest(url=url, data=data, timeout=TIMEOUT)
else:
verify: typing.Union[bool, str]
cert = userService.getProperty('cert')
# cert = '' # Untils more tests, keep as previous.... TODO: Fix this when fully tested
if cert:
# Generate temp file, and delete it after
verify = tempfile.mktemp('udscrt')
with open(verify, 'wb') as f:
f.write(cert.encode()) # Save cert
else:
verify = False
if data is None:
r = requests.get(url, verify=verify, timeout=TIMEOUT)
else:
r = requests.post(
url,
data=json.dumps(data),
headers={'content-type': 'application/json'},
verify=verify,
timeout=TIMEOUT,
)
if verify:
try:
os.remove(typing.cast(str, verify))
except Exception:
logger.exception('removing verify')
js = r.json()
if version >= '3.0.0':
js = js['result']
logger.debug('Requested %s to actor. Url=%s', method, url)
except Exception as e:
logger.warning(
'Request %s failed: %s. Check connection on destination machine: %s',
method,
e,
url,
)
js = None
return js
def notifyPreconnect(userService: 'UserService', userName: str, protocol: str) -> None:
"""
Notifies a preconnect to an user service
"""
ip, hostname = userService.getConnectionSource()
try:
_requestActor(
userService,
'preConnect',
{'user': userName, 'protocol': protocol, 'ip': ip, 'hostname': hostname},
)
except NoActorComms:
pass # If no preconnect, warning will appear on UDS log
def checkUuid(userService: 'UserService') -> bool:
"""
Checks if the uuid of the service is the same of our known uuid on DB
"""
try:
uuid = _requestActor(userService, 'uuid')
if (
uuid and uuid != userService.uuid
): # Empty UUID means "no check this, fixed pool machine"
logger.info(
'Machine %s do not have expected uuid %s, instead has %s',
userService.friendly_name,
userService.uuid,
uuid,
)
return False
except NoActorComms:
pass
return True # Actor does not supports checking
def requestScreenshot(userService: 'UserService') -> bytes:
"""
Returns an screenshot in PNG format (bytes) or empty png if not supported
"""
emptyPng = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
try:
png = _requestActor(
userService, 'screenshot', minVersion='3.0.0'
) # First valid version with screenshot is 3.0
except NoActorComms:
png = None
return base64.b64decode(png or emptyPng)
def sendScript(userService: 'UserService', script: str, forUser: bool = False) -> None:
"""
If allowed, send script to user service
"""
try:
data: typing.MutableMapping[str, typing.Any] = {'script': script}
if forUser:
data['user'] = forUser
_requestActor(userService, 'script', data=data)
except NoActorComms:
pass
def requestLogoff(userService: 'UserService') -> None:
"""
Ask client to logoff user
"""
try:
_requestActor(userService, 'logout', data={})
except NoActorComms:
pass
def sendMessage(userService: 'UserService', message: str) -> None:
"""
Sends an screen message to client
"""
try:
_requestActor(userService, 'message', data={'message': message})
except NoActorComms:
pass
| [
"dkmaster@dkmon.com"
] | dkmaster@dkmon.com |
c886c20cf7de550debdfb0a88d9edcbafb45a992 | 0726db2d56b29f02a884885718deeddbf86df628 | /lienp/visualize.py | af217e55f8ec1524e381eb022bcd47bbb2f01101 | [] | no_license | makora9143/EquivCNP | 515dfd95557d8d3a21d3fc0f295ce885a9deb913 | a78dea12ab672e796c86427823c9f1b2fdd8df8d | refs/heads/master | 2023-03-17T04:34:26.320055 | 2021-03-05T18:02:18 | 2021-03-05T18:02:18 | 254,292,834 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,239 | py | import io
import PIL.Image
import matplotlib.pyplot as plt
import torch
from torchvision.transforms import ToTensor, ToPILImage
from torchvision.utils import make_grid
def mnist_plot_function(target_x, target_y, context_x, context_y):
img = torch.zeros((28, 28, 3))
img[:, :, 2] = torch.ones((28, 28))
idx = (context_x + 14).clamp(0, 27).long()
img[idx[:, 0], idx[:, 1]] = context_y
print(f'num context:{context_x.shape[0]}')
plt.figure(figsize=(8, 4))
plt.subplot(121)
plt.imshow(img.numpy())
plt.gray()
plt.subplot(122)
plt.imshow(target_y.reshape(28, 28).numpy())
plt.show()
def plot_and_save_image(ctxs, tgts, preds, epoch=None):
ctx_img = []
tgt_img = []
pred_img = []
for ctx, tgt, tgt_y_dist in zip(ctxs, tgts, preds):
ctx_coords, ctx_values = ctx
tgt_coords, tgt_values = tgt
img = torch.zeros((28, 28, 3))
img[:, :, 2] = torch.ones((28, 28))
idx = (ctx_coords[0] + 14).clamp(0, 27).long()
img[idx[:, 0], idx[:, 1]] = ctx_values[0]
ctx_img.append(img.unsqueeze(0))
tgt_img.append(tgt_values.reshape(1, 1, 28, 28).repeat(1, 3, 1, 1))
pred_img.append(tgt_y_dist.mean.reshape(1, 1, 28, 28).repeat(1, 3, 1, 1))
ctx_img = torch.cat(ctx_img, 0).permute(0, 3, 1, 2).unsqueeze(1).to(torch.device('cpu'))
tgt_img = torch.cat(tgt_img, 0).unsqueeze(1).to(torch.device('cpu'))
pred_img = torch.cat(pred_img, 0).unsqueeze(1).to(torch.device('cpu'))
img = torch.cat([ctx_img, tgt_img, pred_img], 1).reshape(-1, 3, 28, 28)
img = make_grid(img, nrow=6).permute(1, 2, 0).clamp(0, 1)
plt.imsave("epoch_{}.png".format(epoch if epoch is not None else "test"), img.numpy())
def plot_and_save_image2(ctxs, tgts, preds, img_shape, epoch=None):
ctx_img = []
tgt_img = []
pred_img = []
C, W, H = img_shape
for ctx_mask, tgt, tgt_y_dist in zip(ctxs, tgts, preds):
img = torch.zeros((W, H, 3))
img[:, :, 2] = torch.ones((W, H))
img[ctx_mask[0, 0] == 1] = tgt[0, 0][ctx_mask[0, 0] == 1].unsqueeze(-1)
ctx_img.append(img)
tgt_img.append(tgt.repeat(1, 3//C, 1, 1))
pred_img.append(tgt_y_dist.mean.reshape(1, W, H, C).repeat(1, 1, 1, 3//C))
ctx_img = torch.stack(ctx_img, 0).permute(0, 3, 1, 2).unsqueeze(1).to(torch.device('cpu'))
tgt_img = torch.cat(tgt_img, 0).unsqueeze(1).to(torch.device('cpu'))
pred_img = torch.cat(pred_img, 0).unsqueeze(1).to(torch.device('cpu')).permute(0, 1, 4, 2, 3)
img = torch.cat([ctx_img, tgt_img, pred_img], 1).reshape(-1, 3, W, H)
img = make_grid(img, nrow=6).permute(1, 2, 0).clamp(0, 1)
plt.imsave("epoch_{}.png".format(epoch if epoch is not None else "test"), img.numpy())
def plot_and_save_graph(ctxs, tgts, preds, gp_preds, epoch=None):
graphs = []
for ctx, tgt, tgt_y_dist, gp_dist in zip(ctxs, tgts, preds, gp_preds):
ctx_coords, ctx_values = ctx
tgt_coords, tgt_values = tgt
mean = tgt_y_dist.mean.cpu()
lower, upper = tgt_y_dist.confidence_region()
gp_mean = gp_dist.mean.cpu()
gp_lower, gp_upper = gp_dist.confidence_region()
plt.plot(tgt_coords.reshape(-1).cpu(), gp_mean.detach().cpu().reshape(-1), color='green')
plt.fill_between(tgt_coords.cpu().reshape(-1), gp_lower.detach().cpu().reshape(-1), gp_upper.detach().cpu().reshape(-1), alpha=0.2, color='green')
plt.plot(tgt_coords.reshape(-1).cpu(), mean.detach().cpu().reshape(-1), color='blue')
plt.fill_between(tgt_coords.cpu().reshape(-1), lower.detach().cpu().reshape(-1), upper.detach().cpu().reshape(-1), alpha=0.2, color='blue')
plt.plot(tgt_coords.reshape(-1).cpu(), tgt_values.reshape(-1), '--', color='gray')
plt.plot(ctx_coords.reshape(-1).cpu(), ctx_values.reshape(-1).cpu(), 'o', color='black')
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
plt.clf()
plt.close()
img = PIL.Image.open(buf)
img = ToTensor()(img)
buf.close()
graphs.append(img)
img = ToPILImage()(make_grid(torch.stack(graphs, 0), nrow=2))
img.save("epoch_{}.png".format(epoch if epoch is not None else "test"))
| [
"makoto.kawano@gmail.com"
] | makoto.kawano@gmail.com |
a1b2a9fb37f905611061cfcd13a857ef8d26ffe9 | e068f64dfbcc00ae4c84db0432b9fbcc8d2df0c7 | /orchestra/google/marketing_platform/utils/schema/erf/TargetUnion.py | 6f7fed3d24853e27ba56bee71d7ecb070e656b11 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | trakken/orchestra | 947d58bbe9a645c3554c295dd4512e86b67641a5 | 4803530a7df9c685893aca87250e3f736de23bc8 | refs/heads/master | 2022-12-09T04:05:50.871943 | 2020-03-02T16:09:49 | 2020-03-02T16:09:49 | 295,346,069 | 0 | 0 | Apache-2.0 | 2020-09-14T08:01:09 | 2020-09-14T08:01:08 | null | UTF-8 | Python | false | false | 1,201 | py | ###########################################################################
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
#
###########################################################################
TargetUnion_Schema = [
{ "name":"union",
"type":"RECORD",
"mode":"REPEATED",
"fields":[
{ "name":"criteria_id",
"type":"INTEGER",
"mode":"NULLABLE",
},
{ "name":"parameter",
"type":"STRING",
"mode":"NULLABLE",
},
{ "name":"excluded",
"type":"BOOLEAN",
"mode":"NULLABLE",
},
]
},
{ "name":"excluded",
"type":"BOOLEAN",
"mode":"NULLABLE",
},
]
| [
"kingsleykelly@google.com"
] | kingsleykelly@google.com |
0e185c34961eff4289c4c9d576294c3a43be2ae6 | 4dd9a94828221013244d56443ce988b49c749523 | /neural_net.py | 589a7d86c407d6c653e2bd7c4fd28d4e7a919928 | [] | no_license | dhorrall/deep_learning_foundations | e452084d91c684ebc9d54de452041ecff2704733 | 714457299508bf9b7a5b3b18dd260c842c432cfe | refs/heads/master | 2021-01-09T06:16:20.121329 | 2017-06-06T14:27:49 | 2017-06-06T14:27:49 | 80,946,135 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,106 | py | '''
Created on Jan 29, 2017
@author: derekh1
'''
from numpy import exp, array, random, dot
class NeuralNetwork():
def __init__(self):
# Seed the random number generator, so it generates the same numbers
# every time the program runs.
random.seed(1)
# We model a single neuron, with 3 input connections and 1 output connection.
# We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1
# and mean 0.
self.synaptic_weights = 2 * random.random((3, 1)) - 1
# The Sigmoid function, which describes an S shaped curve.
# We pass the weighted sum of the inputs through this function to
# normalise them between 0 and 1.
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
# The derivative of the Sigmoid function.
# This is the gradient of the Sigmoid curve.
# It indicates how confident we are about the existing weight.
def __sigmoid_derivative(self, x):
return x * (1 - x)
# We train the neural network through a process of trial and error.
# Adjusting the synaptic weights each time.
def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations):
for iteration in xrange(number_of_training_iterations):
# Pass the training set through our neural network (a single neuron).
output = self.think(training_set_inputs)
# Calculate the error (The difference between the desired output
# and the predicted output).
error = training_set_outputs - output
# Multiply the error by the input and again by the gradient of the Sigmoid curve.
# This means less confident weights are adjusted more.
# This means inputs, which are zero, do not cause changes to the weights.
adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output))
# Adjust the weights.
self.synaptic_weights += adjustment
# The neural network thinks.
def think(self, inputs):
# Pass inputs through our neural network (our single neuron).
return self.__sigmoid(dot(inputs, self.synaptic_weights))
if __name__ == "__main__":
#Intialise a single neuron neural network.
neural_network = NeuralNetwork()
print "Random starting synaptic weights: "
print neural_network.synaptic_weights
# The training set. We have 4 examples, each consisting of 3 input values
# and 1 output value.
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
# Train the neural network using a training set.
# Do it 10,000 times and make small adjustments each time.
neural_network.train(training_set_inputs, training_set_outputs, 100000)
print "New synaptic weights after training: "
print neural_network.synaptic_weights
# Test the neural network with a new situation.
print "Considering new situation [1, 0, 0] -> ?: "
print neural_network.think(array([1, 0, 0]))
| [
"derekh1@oc7043351046.ibm.com"
] | derekh1@oc7043351046.ibm.com |
d155707dd0625574b9dc3d610d97d6cc26fbfe3f | 8c2d17c1dd5409d63bde7907cdee4adaf4e9443a | /day_3.py | 81eac927ebee6866133652e83eeba8b84259704f | [] | no_license | kmb5/AdventOfCode2019 | f4099686028f7ddd5895918c9c55a7080936cc8c | f10dce035d6134800b4c83e07e1aa2a40061f49e | refs/heads/master | 2020-12-01T21:19:46.357511 | 2019-12-30T09:41:20 | 2019-12-30T09:41:20 | 230,774,194 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,653 | py | #import pygame
#from pygame.locals import QUIT
from PIL import Image, ImageDraw
def main():
filename = 'inputs/day_3_input.txt'
with open(filename) as f:
puzzle_input = f.read().splitlines()
solution_part_1 = part_1(puzzle_input)
print(f'Part 1 solution: {solution_part_1}')
def part_1(puzzle_input):
wire_1 = puzzle_input[0].split(',')
wire_2 = puzzle_input[1].split(',')
origin_point = (8500,16000)
# Arbitrary number so that the wires will
# fit entriely on the image we generate at the end.
# For sure there is a math way of calculating this but I could not figure out,
# it was just trial and error until the whole image fit.
path_1 = draw_path(wire_1, start_coordinates=origin_point)
path_2 = draw_path(wire_2, start_coordinates=origin_point)
result = list(set(path_1).intersection(path_2))
index_of_origin = result.index(origin_point)
result.pop(index_of_origin) # removing the intersection at origin point
manhattans = []
for i in result:
'''Calculate Manhattan taxicab distance between each point and the origin'''
distance = abs((origin_point[0] - i[0])) + abs((origin_point[1] - i[1]))
manhattans.append(distance)
smallest_dist = min(manhattans) # This is our solution
''' This is only needed to render an image with the paths,
it is not a requirement for solving the case!'''
img = Image.new('RGB', ((15000,19000)))
# Again an arbitrary image size so that everything fits
ImageDraw.Draw(img).point(path_1, fill='red')
ImageDraw.Draw(img).point(path_2, fill='yellow')
img.save('day_3_visualisation.jpg')
return smallest_dist
def draw_path(wire_path: list, start_coordinates: tuple) -> list:
path = []
path.append(start_coordinates)
# Initializing the path with the starting coordinates
for instruction in wire_path:
direction = instruction[0]
distance = int(instruction[1:])
prev_point_x = path[-1][0]
prev_point_y = path[-1][1]
if direction == 'L':
new_points = [(prev_point_x - x, prev_point_y) for x in range(1, distance + 1)]
elif direction == 'R':
new_points = [(prev_point_x + x, prev_point_y) for x in range(1, distance + 1)]
elif direction == 'U':
new_points = [(prev_point_x, prev_point_y + y) for y in range(1, distance + 1)]
elif direction == 'D':
new_points = [(prev_point_x, prev_point_y - y) for y in range(1, distance + 1)]
path.extend(new_points)
return path
if __name__ == '__main__':
main() | [
"noreply@github.com"
] | kmb5.noreply@github.com |
d906c6552a6f100ecb942e4634c4b7e28aa9643d | e5cf384933ccc0b54edfc1e775e56586bc100f74 | /pixiv_downloader/pixiv_downloader.py | 1f858e4e6da6edd7f92feb021b5f5213814f07ce | [] | no_license | Einsbon/DeepLearning-with-Pixiv | bda902c07a955fe3bff081fb10986ca7e2fdaad0 | 642aadc892766623a5f861ab448975f36deab8ce | refs/heads/master | 2020-03-28T14:30:19.162858 | 2018-09-12T18:48:56 | 2018-09-12T18:48:56 | 148,493,338 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,885 | py | from selenium import webdriver
from bs4 import BeautifulSoup
import time
import urllib.request
import urllib
import getpass
import os
import shutil
phantompath = r'C:\Users\Einsbon\Documents\Python_Projects\python_window\crawler\pixiv_low_quality_image_crawler\phantomjs.exe'
chromepath = 'C:\\Users\\Einsbon\\Documents\\Python Scripts\\crawler\\pixiv_low_quality_image_crawler\\chromedriver.exe'
urlVocaloid = r"https://www.pixiv.net/search.php?s_mode=s_tag_full&word=VOCALOID&type=illust&blt=100&mode=safe"
urlMiku = r'https://www.pixiv.net/search.php?s_mode=s_tag_full&word=%E5%88%9D%E9%9F%B3%E3%83%9F%E3%82%AF&type=illust&blt=100&mode=safe'
urlLogin = 'https://accounts.pixiv.net/login?lang=ko&source=pc&view_type=page&ref=wwwtop_accounts_index'
def driverSetup(web, userId, userpd, urlFirst):
web.get(urlFirst)
web.implicitly_wait(10)
web.find_element_by_xpath(
'/html/body/div[3]/div[3]/div/form/div[1]/div[1]/input').send_keys(
userId)
web.find_element_by_xpath(
'/html/body/div[3]/div[3]/div/form/div[1]/div[2]/input').send_keys(
userpd)
web.find_element_by_xpath(
'/html/body/div[3]/div[3]/div/form/button').click()
web.set_window_size(1020, 960)
def scrollUpToDown(web):
web.execute_script("window.scrollTo(0, 400);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 800);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 1200);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 1600);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 2000);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 2400);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 2800);")
time.sleep(0.15)
web.execute_script("window.scrollTo(0, 3200);")
def checkLoaded(elements):
for element in elements:
est = str(element)
if est.find('p0_master1200') == -1:
print(est)
return False
return True
opener = urllib.request.URLopener()
opener.addheader('Referer', 'https://www.pixiv.net/')
def downloadImage(url, name):
image = opener.open(url)
data = image.read()
f = open(name, 'wb')
f.write(data)
f.close()
image.close()
'''
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib.request.Request(url, headers=headers) # The assembled request
response = urllib.request.urlopen(req) # store the response
# create a new file and write the image
f = open(name, 'wb')
f.write(response.read())
f.close()'''
def crawling(web, repeatNum, savePath):
while repeatNum > 0:
print('\n\nNumber of pages remaining: ' + str(repeatNum))
print('Current_url:' + str(web.current_url))
scrollUpToDown(web)
web.implicitly_wait(20)
html = web.page_source
soup = BeautifulSoup(html, 'html.parser')
count = 0
elements = soup.find_all('div', {'class': '_309ad3C'})
print(checkLoaded(elements))
while checkLoaded(elements) == False:
print('waiting')
time.sleep(0.8)
elements = soup.find_all('div', {'class': '_309ad3C'})
if count == 5:
scrollUpToDown(web)
if count > 12:
web.refresh()
scrollUpToDown(web)
count = 0
count += 1
urlList = []
downloadedWell = True
downloadcount = 0
for element in elements:
# print(element)
est = str(element)
if (est.find('(') != -1 & est.find(')') != -1):
est = est[est.find('(')+2: est.find(')')-1]
urlList.append(est)
filename = savePath + "\\" + est.split('/')[-1]
print(est)
print(filename)
try:
if os.path.isfile(filename):
print(': already')
else:
downloadImage(est, filename)
print(': downloaded')
downloadcount += 1
except:
print('error, refrestart this page')
downloadedWell = False
break
if downloadedWell == False:
web.refresh()
continue
print('Downloaded images in this page: ' + str(downloadcount))
web.find_element_by_xpath(
'//*[@id="wrapper"]/div[1]/div/nav/div/span[2]/a').click()
repeatNum -= 1
def main():
# print("launch path" + os.getcwd())
# print('phantom path' + phantompath)
print(' ')
#userId = input('Id:')
#userPd = getpass.getpass('Password:')
userId = 'sbkim0316@naver.com'
userPd = 'airplane0316'
web = webdriver.Chrome(os.path.abspath(os.path.dirname(__file__)) + '/chromedriver.exe')
driverSetup(web, userId, userPd, urlLogin)
#startUrl = input('Start url:')
startUrl = r'https://www.pixiv.net/search.php?s_mode=s_tag_full&word=VOCALOID&type=illust&blt=1000&mode=safe'
#savePath = input('Path to save:')
savePath = r'D:\picture\miku300-999'
pageNumber = int(input('Number of pages to download:'))
web.get(startUrl)
crawling(web, pageNumber, savePath)
if __name__ == "__main__":
main()
| [
"noreply@github.com"
] | Einsbon.noreply@github.com |
082b2931c6c4dbd7173131856b1c308a119963b8 | 18740007244035abf66efb0c4c37eca457806cce | /infrastructure/cloudformation/troposphere/storage.py | 5ce481321753c61486729cc7dacb45fbe8b5d2a6 | [] | no_license | khueue/khueue-diary | 7773b34fc0214cdd04133cd8cb38ec5e8096318c | 90de164b997ebde328d4f116b94f588a3c394cec | refs/heads/master | 2020-04-07T02:28:26.654045 | 2019-01-22T12:37:23 | 2019-01-22T12:37:23 | 157,977,843 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,135 | py | import troposphere
import troposphere.cloudfront
import troposphere.s3
import awacs
import awacs.s3
CONFIG = {
'app_bucket': {
'name': 'khueue-diary-app',
},
'pipeline_bucket': {
'name': 'khueue-diary-pipeline',
'object_lifetime_days': 30,
},
'log_bucket': {
'name': 'khueue-diary-logs',
'object_lifetime_days': 30,
},
}
template = troposphere.Template()
log_bucket = troposphere.s3.Bucket(
'LogBucket',
template=template,
BucketName=CONFIG['log_bucket']['name'],
AccessControl='LogDeliveryWrite',
LifecycleConfiguration=troposphere.s3.LifecycleConfiguration(
Rules=[
troposphere.s3.LifecycleRule(
Id='DeleteOldObjects',
Status='Enabled',
ExpirationInDays=CONFIG['log_bucket']['object_lifetime_days'],
),
],
),
)
pipeline_bucket = troposphere.s3.Bucket(
'PipelineBucket',
template=template,
BucketName=CONFIG['pipeline_bucket']['name'],
LoggingConfiguration=troposphere.s3.LoggingConfiguration(
DestinationBucketName=troposphere.Ref(log_bucket),
LogFilePrefix='pipeline-s3/',
),
LifecycleConfiguration=troposphere.s3.LifecycleConfiguration(
Rules=[
troposphere.s3.LifecycleRule(
Id='DeleteOldObjects',
Status='Enabled',
ExpirationInDays=CONFIG['pipeline_bucket']['object_lifetime_days'],
),
],
),
)
app_bucket = troposphere.s3.Bucket(
'AppBucket',
template=template,
BucketName=CONFIG['app_bucket']['name'],
LoggingConfiguration=troposphere.s3.LoggingConfiguration(
DestinationBucketName=troposphere.Ref(log_bucket),
LogFilePrefix='app-s3/',
),
WebsiteConfiguration=troposphere.s3.WebsiteConfiguration(
IndexDocument="index.html",
),
)
app_bucket_policy = troposphere.s3.BucketPolicy(
'AppBucketPolicy',
template=template,
Bucket=CONFIG['app_bucket']['name'],
PolicyDocument=awacs.aws.Policy(
Statement=[
awacs.aws.Statement(
Effect=awacs.aws.Allow,
Principal=awacs.aws.Principal('AWS', [
'*',
]),
Action=[
awacs.aws.Action('s3', 'GetObject'),
],
Resource=[
awacs.s3.ARN('/'.join([
CONFIG['app_bucket']['name'],
'*',
])),
],
),
],
),
)
print(template.to_json())
| [
"khueue@gmail.com"
] | khueue@gmail.com |
075026177bd5d8967534c7183b390a63941c8beb | f4205df28c7b9817acd03aa78c24adcc501a65b8 | /run.py | 766037e23811d8ad0a4f210904cad02d954fcc1e | [
"MIT"
] | permissive | chelseaayoo/Password-manager | d8133f6827b30aa919f2cd179ffd5c0ecfb3ae23 | e7abe7c334427e40e78515066845e8cf742b367d | refs/heads/master | 2023-08-28T09:45:20.495179 | 2021-10-26T06:15:49 | 2021-10-26T06:15:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,661 | py | #!/usr/bin/env python3.8
#!/usr/bin/env python3.6
from credential import Credential
from user import User
def create_credential(login_username,password):
'''
Function to create a new credential
'''
new_credential = Credential(login_username,password)
return new_credential
def save_credentials(credential):
'''
Function to save credential
'''
credential.save_credential()
def del_credential(credential):
'''
Function to delete a credential
'''
credential.delete_credential()
def find_credential(login_username):
'''
Function that finds a credential by email and returns the credential
'''
return Credential.find_by_login_username(login_username)
def check_existing_credentials(login_username):
'''
Function that check if a credential exists with that login_username and return a Boolean
'''
return Credential.credential_exist(login_username)
def display_credentials():
'''
Function that returns all the saved credentials
'''
return Credential.display_credentials()
def create_user(email,first_name,last_name):
'''
Function to create a new user
'''
new_user = User(email,first_name,last_name)
return new_user
def save_users(user):
'''
Function to save user
'''
user.save_user()
def del_user(user):
'''
Function to delete a user
'''
user.delete_user()
def find_user(email):
'''
Function that finds a user by email and returns the user
'''
return User.find_by_email(email)
def check_existing_users(email):
'''
Function that check if a user exists with email and return a Boolean
'''
return User.user_exist(email)
def display_users():
'''
Function that returns all the saved users
'''
return User.display_users()
def main():
print("Hello Welcome to your credential list. What is your name?")
login_username = input()
print(f"Hello {login_username}. what would you like to do?")
print('\n')
while True:
print("Use these short codes : cc - create a new credential, dc - display credentials, fc -find a credential, delc -delete credential, ex -exit the credential list ")
short_code = input().lower()
if short_code == 'cc':
print("New Credential")
print("-"*10)
print ("First name ....")
first_name = input()
print("Last name ...")
last_name = input()
print("Login username ...")
login_username = input()
print("Password ...")
password = input()
print("Email address for account login ...")
email = input()
save_credentials(create_credential(login_username,password)) # create and save new credential.
print ('\n')
print(f"New Credential with login username: {login_username} with password: {password} created")
print ('\n')
elif short_code == 'dc':
if display_credentials():
print("Here is a list of all your credentials")
print('\n')
for credential in display_credentials():
print(f"Login Username : {credential.login_username} Password: {credential.password}")
print('\n')
else:
print('\n')
print("You dont seem to have any credentials saved yet")
print('\n')
elif short_code == 'fc':
print("Enter the login username you used while creating your credential")
search_login_username = input()
if check_existing_credentials(search_login_username):
search_credential = find_credential(search_login_username)
print(f"{search_credential.login_username} Your password is {search_credential.password}")
print('-' * 20)
# print(f"Phone number.......{search_contact.phone_number}")
# print(f"Email address.......{search_contact.email}")
else:
print("That credential does not exist")
elif short_code == 'delc':
if del_credential(create_credential):
print("choose credentials to delete")
print('\n')
for credential in del_credential():
print("{credential}")
else:
print('\n')
print("no credential deleted")
print('\n')
elif short_code == "ex":
print("Bye .......")
break
else:
print("I really didn't get that. Please use the short codes")
if __name__ == '__main__':
main() | [
"chelsea.ayoo@student.moringaschool.com"
] | chelsea.ayoo@student.moringaschool.com |
d547c8a2ec1e142851a69e65f88b8dd40d883aaf | 5bf143f904a19a8ff94cf4a7ef8da8da25de3458 | /analyze_sentiment.py | 8d744c14a23fb55013f1cb8285781cf4c8a71f11 | [] | no_license | kurobeko1259/multsum | 7d51a181e43ae8ce28aab7af6e8dee9a48d276ad | cfd4fe98c8371578c804ec85197a75a59fa92869 | refs/heads/master | 2020-04-06T23:00:45.765070 | 2018-11-21T06:34:18 | 2018-11-21T06:34:18 | 157,854,903 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,649 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, re, math, numpy
from sets import Set
f = open(os.path.dirname(__file__)+"/emotion_words_positive.txt")
#positive_emotions = Set(f.readlines())
positive_emotions = set()
for pos in f.readlines():
#print pos
positive_emotions.add(pos.replace("\n", ""))
f = open(os.path.dirname(__file__)+"/emotion_words_negative.txt")
negative_emotions = set()
for neg in f.readlines():
#print neg
negative_emotions.add(neg.replace("\n", ""))
def analyze_sentiment(sentences):
emo_vectors = []
for s in sentences:
#print s
positive_count = 0
negative_count = 0
positive_frac = 0.0
negative_frac = 0.0
#words = s.split()
#words = re.findall(r"[\w']+", s)
if len(s) > 0:
for w in s:
#"print w
w = filter(str.isalnum, w)
if w.lower() in positive_emotions:
#print "positive! "+w
positive_count += 1
elif w.lower() in negative_emotions:
#print "negative! "+w
negative_count += 1
positive_frac = float(positive_count) / float(len(s))
negative_frac = float(negative_count) / float(len(s))
emo_vec = [positive_frac, negative_frac]
emo_vectors.append(emo_vec)
# cosinesim is btw -1 and 1.
# use:
# 1+cosinesimilarity(vec1,vec2)/2
positive_matrix = numpy.zeros((len(sentences), len(sentences)))
negative_matrix = numpy.zeros((len(sentences), len(sentences)))
min_simpos = 1.0
max_simpos = 0.0
min_simneg = 1.0
max_simneg = 0.0
#print "Number of lines: "+str(len(emo_vectors))
for normalize in [1,0]:
for i in range(len(emo_vectors)):
for j in range(len(emo_vectors)):
simpos = 1-abs(emo_vectors[i][0]-emo_vectors[j][0])
simneg = 1-abs(emo_vectors[i][1]-emo_vectors[j][1])
sim = simpos
if normalize == 1:
if simpos > max_simpos:
max_simpos = simpos
if simpos < min_simpos:
min_simpos = simpos
if simneg > max_simneg:
max_simneg = simneg
if simneg < min_simneg:
min_simneg = simneg
else:
normalized_simpos = 0.0
normalized_simneg = 0.0
if len(sentences[i]) > 0 and len(sentences[j]) > 1:
if max_simpos-min_simpos > 0.0:
normalized_simpos = (simpos-min_simpos)/(max_simpos-min_simpos)
if max_simneg-min_simneg > 0.0:
normalized_simneg = (simneg-min_simneg)/(max_simneg-min_simneg)
positive_matrix[i][j] = normalized_simpos
negative_matrix[i][j] = normalized_simneg
return (positive_matrix, negative_matrix)
| [
"[s.u.zzz1259@icloud.com]"
] | [s.u.zzz1259@icloud.com] |
a7e699f06dbaa2415ab8f0ce348214b552cfc045 | 2c5302a8f6962c2de4849c0a49271033ca4fbfbd | /Day-30/Day_30_VishwaPatel.py | 24b68063b1058a4c94682b5d6b1d95b172b53b5a | [] | no_license | 136tejas/30DayOfPython | 4db35033e413b9ec7dc6c0c0871d12b6a1e39555 | 20df271cd8ed3170aad2ee359a6a28f9f682a5b5 | refs/heads/main | 2023-08-11T10:51:39.357383 | 2021-10-04T07:34:44 | 2021-10-04T07:34:44 | 379,897,363 | 0 | 0 | null | 2021-06-24T11:10:35 | 2021-06-24T11:10:35 | null | UTF-8 | Python | false | false | 445 | py | import numpy as np
m = int(input('Enter rows'))
n = int(input('Enter columns'))
l = []
b = []
for i in range(m):
l = []
for j in range(n):
e = int(input('Enter element: '))
l.append(e)
b.append(l)
print("Original matrix")
print(np.matrix(b))
for i in range(m):
for j in range(n):
if i > j or i == j:
continue
else:
b[i][j] = 0
print("Changed matrix")
print(np.matrix(b))
| [
"noreply@github.com"
] | 136tejas.noreply@github.com |
8d44b23e3c33f8af0e8609deae0bf22a79867a27 | 20d87b9d0bac919a7fd9c07af940b5813784b1f6 | /flask_sqlite_sqlalchemy/app.py | 8d3f610ac364d8124add2dd5a33a4f9698ada2e7 | [] | no_license | anacarolinacv/api-python-flask-example | 679e26bc5a43e64aab2457b95ba1013bad951056 | 96438e369084af6e8f6bcd02f437e331b6b67abe | refs/heads/main | 2023-06-20T00:01:56.811601 | 2021-07-15T01:15:49 | 2021-07-15T01:15:49 | 386,044,169 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 331 | py | from flask import jsonify
from marshmallow import ValidationError
from na import ma
from db import db
from server.instance import server
api = server.api
app = server.app
@app.before_first_request
def create_tables():
db.create_all()
if __name__ == '__main__':
db.init_app(app)
ma.init_app(app)
server.run()
| [
"ana.vasconcelos@ccc.ufcg.edu.br"
] | ana.vasconcelos@ccc.ufcg.edu.br |
8cea560fba02030a0a26133fc24eb1c13946c0a5 | ae6177cf2ebe87c3749f03e0ffaade2dac8b8688 | /AulasPython/Parte1/Semana4/decrescente.py | 275cbedae0412d30178947b70b66b0b611437eff | [] | no_license | jmarq76/Learning_Programming | 8a7c598a733c1ba9983103e4aa284bed80ffabbe | bf15d351e239529645fb74a355e296d085683921 | refs/heads/master | 2022-11-17T23:03:32.236684 | 2020-07-07T12:05:56 | 2020-07-07T12:05:56 | 277,804,012 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 417 | py |
decrescente = True
anterior = int(input("Digite o primeiro número da sequência: "))
valor = 1
while valor != 0 and decrescente:
valor = int(input("Digite o próximo da sequência: "))
if valor > anterior:
decrescente = False
anterior = valor
if decrescente:
print("A sequência está em ordem decrescente! :-) ")
else:
print("A sequência não está em ordem decrescente! :-( ") | [
"58978254+jmarq76@users.noreply.github.com"
] | 58978254+jmarq76@users.noreply.github.com |
cffd64491c65e0ffc66d3cb53f6958c2596eb53b | 7bdb103ab024adf67fdd209af6377e86659656dc | /pydicom/errors.py | 8872313e29db0a934a18f8302a83025a4f3b3365 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | glemaitre/pydicom | b58b71f3a0082595a4d62586be21b574c63a76f9 | d88f78e90a8df1cc314858049edaa403be3f5526 | refs/heads/master | 2020-02-26T14:13:25.970610 | 2017-07-31T22:35:55 | 2017-08-01T12:41:22 | 58,641,730 | 0 | 0 | NOASSERTION | 2023-04-29T22:22:23 | 2016-05-12T12:59:33 | Python | UTF-8 | Python | false | false | 876 | py | # errors.py
"""Module for pydicom exception classes"""
#
# Copyright (c) 2013 Darcy Mason
# This file is part of pydicom, released under a modified MIT license.
# See the file LICENSE included with this distribution, also
# available at https://github.com/pydicom/pydicom
#
class InvalidDicomError(Exception):
"""Exception that is raised when the the file does not seem
to be a valid dicom file, usually when the four characters
"DICM" are not present at position 128 in the file.
(According to the dicom specification, each dicom file should
have this.)
To force reading the file (because maybe it is a dicom file without
a header), use read_file(..., force=True).
"""
def __init__(self, *args):
if not args:
args = ('The specified file is not a valid DICOM file.', )
Exception.__init__(self, *args)
| [
"darcymason@gmail.com"
] | darcymason@gmail.com |
d019acbd04f6f92c44b1c6b5ef4f6c1d988e6d74 | c50c22c8f814c8d9b697337891904aa0be0edf56 | /shortest_string.py | b26e0a4d78a888e7c2d4a6252bf9b0d4e510728a | [] | no_license | mhiloca/Codewars | a6dc6e8ea5e5c1e97fb4a3d01a059b3120b556b7 | 3155e4b20fbd96c8e7fbe6564014a136d095c079 | refs/heads/master | 2020-07-11T12:41:19.997254 | 2019-11-01T12:44:38 | 2019-11-01T12:44:38 | 204,541,593 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 222 | py | """
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
"""
def find_short(s):
return min(len(x) for x in s) | [
"mhiloca@gmail.com"
] | mhiloca@gmail.com |
40cf04c7d362189c7309e4ba6a220708a877cf9a | a4e2bd84a06e41a446b521a4a16ecf85e8aee76a | /locate_chromedriver.py | 968593b2dcbe3e79d6acfe7d62da1c0bde8ea2ec | [] | no_license | 526avijitgupta/Bookaway-testing | 273715bb07ab2b5216e4231b1ca63024846c0953 | cb3babd4b60de2e5b1e931fc63880987385ad052 | refs/heads/master | 2021-01-22T09:04:12.689869 | 2014-10-31T13:35:52 | 2014-10-31T13:35:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 387 | py | #!/usr/bin/python
# Filename: local_settings.py
import os
print "Locating chromedriver on your machine.."
chromedriver = os.popen("find / -name 'chromedriver' -not -name '*.*' 2>/dev/null").read()
chromedriver = str(chromedriver.split("\n")[0])
if(chromedriver):
print ("chromedriver found! Executing Script..")
else:
print ("Unable to find chromedriver!")
# End of local_settings.py
| [
"526avijitgupta@gmail.com"
] | 526avijitgupta@gmail.com |
9782fd2180f9d64e673c362aad00d0e19916f9e3 | dcdde01af29567eba920ffcf340605251aa726be | /flask/flsk.py | 7964838ff06455a8dc7653023413917e3b9739b6 | [] | no_license | MeherMS/python | b9f3d77ef97a72f4e68deb77f767fa45f7160a43 | 66296d552755a11600a8fba4d241efa13e0f3b50 | refs/heads/main | 2023-03-25T11:07:41.007216 | 2021-03-27T23:40:59 | 2021-03-27T23:40:59 | 352,113,082 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 855 | py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from flask import Flask, jsonify, request
import pickle
import json
# load model
model = pickle.load(open('model.pkl','rb'))
data = {'Pclass': 3
, 'Age': 2
, 'SibSp': 1
, 'Fare': 50}
data = json.dumps(data)
# app
app = Flask(__name__)
# routes
@app.route('/', methods=['POST'])
def predict():
# get data
#data = request.get_json(force=True)
# convert data into dataframe
data.update((x, [y]) for x, y in data.items())
data_df = pd.DataFrame.from_dict(data)
# predictions
result = model.predict(data_df)
# send back to browser
output = {'results': int(result[0])}
# return data
return jsonify(results=output)
if __name__ == '__main__':
app.run(port = 5000, debug=True)
# In[ ]:
# In[ ]:
# In[ ]:
| [
"noreply@github.com"
] | MeherMS.noreply@github.com |
d4ec50f6dfaad60ee5b78a209f3dfea8cc4a1456 | eabe353d086aacfe2953eaf5ec8cf71668ae1448 | /backend/card/migrations/0001_initial.py | 3dbd597c01a62d3b027b59fd1094d179e39c1c4d | [] | no_license | epc91/oblique-strategies | d5961e7b0ac92b3338cc6bddf213673d2779661a | de9ac2b1a75b44944534750178641ae1b34604a0 | refs/heads/main | 2023-07-10T11:30:05.971381 | 2021-08-24T23:16:38 | 2021-08-24T23:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 554 | py | # Generated by Django 3.2.6 on 2021-08-14 01:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Card',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('own', models.BooleanField(default=False)),
('description', models.CharField(max_length=70)),
],
),
]
| [
"eduardopeschke@gmail.com"
] | eduardopeschke@gmail.com |
0c2357d7adb5b24a1223a63d777fbf1484ae81ab | 6bcb73fc72587d24927eb9f1450ba3e676c421cf | /setup.py | 9d6ec105a703c31f0bd3be9f32394427a8abd00f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SorchaYang/Scopy | ed26cb9026de898e89e1d39bb7a8af2d041a34a9 | 897f9f0f41a90e0cff1e2fd28a7e82cfac051306 | refs/heads/master | 2022-06-09T19:14:14.962262 | 2020-05-07T10:16:07 | 2020-05-07T10:16:07 | 262,022,320 | 4 | 0 | MIT | 2020-05-07T10:40:58 | 2020-05-07T10:40:58 | null | UTF-8 | Python | false | false | 1,702 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 13:21:07 2019
@Author: Zhi-Jiang Yang, Dong-Sheng Cao
@Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China
@Homepage: http://www.scbdd.com
@Mail: yzjkid9@gmail.com; oriental-cds@163.com
@Blog: https://blog.moyule.me
I love my senpai forerver!:P
"""
from __future__ import absolute_import
from distutils.core import setup
# print(__doc__)
package_data= {'scopy':['structure_alert/*','druglikeness/*','fingerprint/*',
'visualize/*','pretreat/*','data/SMARTS/*','data/PATT/*',
'data/ACID/*','data/*','data/Crippen/*','data/EFG/*','data/Demo/*',
'data/MC/mcloud/*','data/MC/mcloud/ertl/mcloud/*',
'data/MOL/*','data/PubChem/*',]}
#package_data= {'scopy':['structure_alert/*','druglikeness/*','test/*','data/SMARTS/*','data/PATT/*','data/ACID/*','data/*','data/Crippen/*','fingerprint/*']}
setup(name="cbdd-scopy",
version="1.1.2",
license="MIT",
description="A filter tool for HTS and VS",
long_description="Scopy (Screening COmpounds in PYthon), based on RDKit, is an integrated negative design python library designed for screening out undesiable compounds in the early drug discovery.",
author="Zhi-Jiang Yang (Kotori), Dong-Sheng Cao",
author_email="yzjkid9@gmail.com",
maintainer="Zhi-Jiang Yang (Kotori)",
maintainer_email="kotori@cbdd.me",
url="https://github.com/kotori-y/Scopy",
package_data=package_data,
# include_package_data=True,
package_dir={'scopy':'scopy'},
py_modules = ['scopy.ScoConfig'],
packages=['scopy']
)
| [
"yzjkid9@gmail.com"
] | yzjkid9@gmail.com |
c5d4d2f46c24a51bf6824c2c8735e80bc1f67f80 | 3f4464c932403615c1fbbaf82eaec096426b1ef5 | /StartOutPy4/CH6 Files and Exceptions/write_sales.py | ecb7c7a8611babac6e9db4c42a7bbdc92ed31f8e | [] | no_license | arcstarusa/prime | 99af6e3fed275982bf11ada7bf1297294d527e91 | 5f1102aa7b6eaba18f97eb388525d48ab4cac563 | refs/heads/master | 2020-03-22T14:07:08.079963 | 2019-05-09T11:45:21 | 2019-05-09T11:45:21 | 140,154,408 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 740 | py | # This program prompts the user for sales amounts
# and writes those amounts to the sales.txt file. 6-8
def main():
# Get the numbers of days.
num_days = int(input('For how many days do ' + 'you have sales? '))
# Open a nuew file named sales.txt.
sales_file = open('sales.txt', 'w')
# Get the amount of sales for each day and write
# it to the file.
for count in range (1, num_days + 1):
# Get the sales for a day.
sales = float(input('Enter the sales for day #' + str(count) + ': '))
# Write the sales amount to the file.
sales_file.write(str(sales) + '\n')
# Close the file.
sales_file.close()
print('Data written to sales.txt')
# Call the main function.
main() | [
"40938410+edwardigarashi@users.noreply.github.com"
] | 40938410+edwardigarashi@users.noreply.github.com |
7afc571991601facfe9836680cdc867c586faa8b | ae3b0909aa4b9f96c17385c1c2e62721817121fe | /policy/task_decomposition_all_without_task.py | 580d0829db47525b4d360c18566c1892655c7fe7 | [] | no_license | saki-37/StarCraft | 9f58912f8006e60559d174fdb046c7fc16c15728 | a915116526478a00690393554f7ddf11b5acda5e | refs/heads/master | 2023-07-13T08:17:26.665932 | 2021-08-19T02:32:16 | 2021-08-19T02:32:16 | 398,439,928 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,091 | py | '''不传0。没有task score。按列求和选择最优动作。
'''
import torch
import os
from network.task_rnn_all import TaskRNNAll, TaskRNNAllwoTask
from network.task_decomposition_all import TaskDecompositionAll
import torch.nn.functional as F
import time
class TDAll:
def __init__(self, args):
self.n_actions = args.n_actions
self.n_agents = args.n_agents
self.state_shape = args.state_shape
self.obs_shape = args.obs_shape
self.n_tasks = args.n_tasks
input_shape = self.obs_shape
# 根据参数决定RNN的输入维度
if args.last_action:
input_shape += self.n_actions
if args.reuse_network:
input_shape += self.n_agents
# 神经网络
self.eval_rnn = TaskRNNAllwoTask(input_shape, args) # 每个agent选动作的网络
self.target_rnn = TaskRNNAllwoTask(input_shape, args)
self.eval_task_net = TaskDecompositionAll(args) # 把agentsQ值加起来的网络
self.target_task_net = TaskDecompositionAll(args)
self.args = args
if self.args.cuda:
self.eval_rnn.cuda()
self.target_rnn.cuda()
self.eval_task_net.cuda()
self.target_task_net.cuda()
self.model_dir = args.model_dir + '/' + args.alg + '/' + args.map
# 如果存在模型则加载模型
if self.args.load_model:
if os.path.exists(self.model_dir + '/rnn_net_params.pkl'):
path_rnn = self.model_dir + '/rnn_net_params.pkl'
path_qmix = self.model_dir + '/td_net_params.pkl'
map_location = 'cuda:0' if self.args.cuda else 'cpu'
self.eval_rnn.load_state_dict(torch.load(path_rnn, map_location=map_location))
self.eval_task_net.load_state_dict(torch.load(path_qmix, map_location=map_location))
print('Successfully load the model: {} and {}'.format(path_rnn, path_qmix))
else:
raise Exception("No model!")
# 让target_net和eval_net的网络参数相同
self.target_rnn.load_state_dict(self.eval_rnn.state_dict())
self.target_task_net.load_state_dict(self.eval_task_net.state_dict())
self.eval_parameters = list(self.eval_task_net.parameters()) + list(self.eval_rnn.parameters())
if args.optimizer == "RMS":
self.optimizer_rnn = torch.optim.RMSprop(self.eval_rnn.parameters(), lr=args.lr)
self.optimizer_mix = torch.optim.RMSprop(self.eval_task_net.parameters(), lr=args.lr*10)
# 执行过程中,要为每个agent都维护一个eval_hidden
# 学习过程中,要为每个episode的每个agent都维护一个eval_hidden、target_hidden
self.eval_hidden = None
self.target_hidden = None
print('Init alg Task Decomposition')
def learn(self, batch, max_episode_len, train_step, epsilon=None): # train_step表示是第几次学习,用来控制更新target_net网络的参数
'''
在learn的时候,抽取到的数据是四维的,四个维度分别为 1——第几个episode 2——episode中第几个transition
3——第几个agent的数据 4——具体obs维度。因为在选动作时不仅需要输入当前的inputs,还要给神经网络输入hidden_state,
hidden_state和之前的经验相关,因此就不能随机抽取经验进行学习。所以这里一次抽取多个episode,然后一次给神经网络
传入每个episode的同一个位置的transition
'''
episode_num = batch['o'].shape[0]
self.init_hidden(episode_num)
for key in batch.keys(): # 把batch里的数据转化成tensor
if key == 'u':
batch[key] = torch.tensor(batch[key], dtype=torch.long)
else:
batch[key] = torch.tensor(batch[key], dtype=torch.float32)
s, s_next, u, r, avail_u, avail_u_next, terminated = batch['s'], batch['s_next'], batch['u'], \
batch['r'], batch['avail_u'], batch['avail_u_next'],\
batch['terminated']
mask = 1 - batch["padded"].float() # 用来把那些填充的经验的TD-error置0,从而不让它们影响到学习
# 得到每个agent对应的Q值,维度为(episode个数, max_episode_len, n_agents, n_tasks , n_actions )
# i_task shape: (episode个数, max_episode_len, n_agents)
q_evals, q_targets, u_max_q_targets = self.get_q_values(batch, max_episode_len)
if self.args.cuda:
s = s.cuda()
u = u.cuda()
r = r.cuda()
s_next = s_next.cuda()
terminated = terminated.cuda()
mask = mask.cuda()
# 取每个agent动作对应的Q值,并且把最后不需要的一维去掉,因为仅采取一个动作。(n_episode, episode_len, n_agent)
u_shape = list(u.shape) # u.shape : (n_episode, episode_len, n_agent, 1)
u_shape.insert(3, self.n_tasks)
u = u.unsqueeze(-2).expand(u_shape) # u shape: (n_episode, episode_len, n_agent, n_tasks, 1)
q_evals = torch.gather(q_evals, dim=4, index=u).squeeze(4) #q shape: (n_episode, episode_len, n_agent, n_tasks)
# 得到target_q
avail_u_shape = u_shape
avail_u_shape[-1] = self.n_actions
avail_u_next = avail_u_next.unsqueeze(-2).expand(avail_u_shape)
q_targets[avail_u_next == 0.0] = - 9999999
# 通过 i_task_target 选择对应行,找出最大价值的动作,选出该动作对应的所有任务的q值。
i_task_target_shape = list(q_targets.shape) # q_targets.shape: (n_episode, episode_len, n_agent, n_tasks, n_actions)
# i_task_target_shape[-2] = self.n_tasks
i_task_target_shape[-1] = 1 # i_task_target_shape.shape: (n_episode, episode_len, n_agent, n_tasks, 1)
q_targets_seletor = u_max_q_targets.unsqueeze(-2).expand(i_task_target_shape) # shape: (n_episode, episode_len, n_agents, n_tasks, 1)
q_targets = torch.gather(q_targets, dim=-1, index=q_targets_seletor).squeeze(-1) # shape: (n_episode, episode_len, n_agents, n_tasks)
hyper_networks, q_values_list = self.eval_task_net(q_evals, s)
hyper_networks_target, q_targets_list = self.target_task_net(q_targets, s_next)
q_total_eval = sum(self.calc_q_total(q_values_list, hyper_networks))
q_total_target = sum(self.calc_q_total(q_targets_list, hyper_networks_target))
# q_total_target = self.target_qmix_net(q_targets, s_next, i_task_target)
targets = r.sum(dim=-1).unsqueeze(-1) + self.args.gamma * q_total_target * (1 - terminated)
td_error = (q_total_eval - targets.detach())
masked_td_error = mask * td_error # 抹掉填充的经验的td_error
# 不能直接用mean,因为还有许多经验是没用的,所以要求和再比真实的经验数,才是真正的均值
loss1 = (masked_td_error ** 2).sum() / mask.sum()
q_tasks = self.calc_q_total(q_values_list, hyper_networks, is_grad4rnn=False)
q_tasks_targets = self.calc_q_total(q_targets_list, hyper_networks_target, is_grad4rnn=False)
q_tasks = torch.cat(q_tasks, dim=-1)
q_tasks_targets = torch.cat(q_tasks_targets, dim=-1)
q_tasks_targets = r + self.args.gamma * q_tasks_targets * (1 - terminated)
td_task_error = (q_tasks - q_tasks_targets.detach())
task_mask = mask.expand(td_task_error.shape)
masked_td_task_error = task_mask * td_task_error
loss2 = (masked_td_task_error ** 2).sum() / task_mask.sum()
# loss = loss1+loss2
self.optimizer_rnn.zero_grad()
self.optimizer_mix.zero_grad()
# loss1.backward(retain_graph=True)
loss1.backward()
# for parm in self.eval_task_net.parameters():
# x =parm.grad.data.cpu().numpy()
loss2.backward()
# loss.backward()
torch.nn.utils.clip_grad_norm_(self.eval_parameters, self.args.grad_norm_clip)
self.optimizer_rnn.step()
self.optimizer_mix.step()
if train_step > 0 and train_step % self.args.target_update_cycle == 0:
self.target_rnn.load_state_dict(self.eval_rnn.state_dict())
self.target_task_net.load_state_dict(self.eval_task_net.state_dict())
def calc_q_total(self, q_list, hyper_networks, is_grad4rnn=True):
'''
Params:
q_list: n_task长list.代表第i任务输入的q。
'''
Qi_list = []
# 把计算过程搬到这里
for i in range(self.n_tasks):
qi = q_list[i]
w1, b1, w2, b2 = hyper_networks[i]
# 传入的q_values是三维的,shape为(episode_num, max_episode_len, n_agents)
episode_num = qi.size(0)
qi = qi.view(-1, 1, self.args.n_agents) # (episode_num * max_episode_len, 1, n_agents) = (1920,1,5)
if is_grad4rnn:
hidden = F.elu(torch.bmm(qi, w1.detach()) + b1.detach()) # (1920, 1, 32)
Qi = torch.bmm(hidden, w2.detach()) + b2.detach() # (1920, 1, 1)
# hidden = F.elu(torch.bmm(qi, w1) + b1) # (1920, 1, 32)
# Qi = torch.bmm(hidden, w2) + b2 # (1920, 1, 1)
else:
hidden = F.elu(torch.bmm(qi.detach(), w1) + b1) # (1920, 1, 32)
Qi = torch.bmm(hidden, w2) + b2 # (1920, 1, 1)
Qi = Qi.view(episode_num, -1, 1) # (32, 60, 1)
Qi_list.append(Qi)
return Qi_list
def _get_inputs(self, batch, transition_idx):
'''
Return:
inputs: (n_episode*n_agent, n_obs+n_actions+n_agent)
'''
# 取出所有episode上该transition_idx的经验,u_onehot要取出所有,因为要用到上一条
obs, obs_next, u_onehot = batch['o'][:, transition_idx], \
batch['o_next'][:, transition_idx], batch['u_onehot'][:]
# obs: (n_episode, n_agent, n_obs)
episode_num = obs.shape[0]
inputs, inputs_next = [], []
inputs.append(obs)
inputs_next.append(obs_next)
# 给obs添加上一个动作、agent编号
if self.args.last_action:
# inputs append (n_episode, n_agent, n_action) tensor
if transition_idx == 0: # 如果是第一条经验,就让前一个动作为0向量
inputs.append(torch.zeros_like(u_onehot[:, transition_idx]))
else:
inputs.append(u_onehot[:, transition_idx - 1])
inputs_next.append(u_onehot[:, transition_idx])
if self.args.reuse_network:
# 因为当前的obs三维的数据,每一维分别代表(episode编号,agent编号,obs维度),直接在dim_1上添加对应的向量
# 即可,比如给agent_0后面加(1, 0, 0, 0, 0),表示5个agent中的0号。而agent_0的数据正好在第0行,那么需要加的
# agent编号恰好就是一个单位矩阵,即对角线为1,其余为0
inputs.append(torch.eye(self.args.n_agents).unsqueeze(0).expand(episode_num, -1, -1))
inputs_next.append(torch.eye(self.args.n_agents).unsqueeze(0).expand(episode_num, -1, -1))
# 要把obs中的三个拼起来,并且要把episode_num个episode、self.args.n_agents个agent的数据拼成40条(40,96)的数据,
# 因为这里所有agent共享一个神经网络,每条数据中带上了自己的编号,所以还是自己的数据
inputs = torch.cat([x.reshape(episode_num * self.args.n_agents, -1) for x in inputs], dim=1)
inputs_next = torch.cat([x.reshape(episode_num * self.args.n_agents, -1) for x in inputs_next], dim=1)
return inputs, inputs_next
def get_q_values(self, batch, max_episode_len, require_grad=True):
# 按照时间顺序将q拼接起来
episode_num = batch['o'].shape[0]
q_evals, q_targets = [], []
u_max_q_targets= []
for transition_idx in range(max_episode_len):
# inputs, inputs_next:(episode_num * n_agents, n_obs+n_actions+n_agent).表示
inputs, inputs_next = self._get_inputs(batch, transition_idx) # 给obs加last_action、agent_id
if self.args.cuda:
inputs = inputs.cuda()
inputs_next = inputs_next.cuda()
self.eval_hidden = self.eval_hidden.cuda()
self.target_hidden = self.target_hidden.cuda()
# q_eval维度为 (n_episode*n_agent, n_tasks, n_action)
q_eval, self.eval_hidden = self.eval_rnn(inputs, self.eval_hidden)
q_target, self.target_hidden= self.target_rnn(inputs_next, self.target_hidden)
# 把q_eval维度重新变回(episode_num, n_agents, n_tasks, n_actions)
q_eval = q_eval.view(episode_num, self.n_agents, self.n_tasks,-1)
q_target = q_target.view(episode_num, self.n_agents, self.n_tasks, -1)
# u_max_q_targets (n_episode, n_agents, 1 )
u_max_q_target = q_target.sum(dim=2).argmax(dim=-1).unsqueeze(-1)
q_evals.append(q_eval)
q_targets.append(q_target)
u_max_q_targets.append(u_max_q_target)
# 得的q_eval和q_target是一个列表,列表里装着max_episode_len个数组,数组的的维度是(episode_num, n_agents, n_tasks, n_actions)
# q_evals: (episode个数, max_episode_len, n_agents, n_tasks, n_actions)的数组
q_evals = torch.stack(q_evals, dim=1)
q_targets = torch.stack(q_targets, dim=1)
u_max_q_targets = torch.stack(u_max_q_targets, dim=1) # u_max_q_targets (n_episode, max_episode_len, n_agents, 1 )的数组
return q_evals, q_targets, u_max_q_targets
def find_task_q(self, q):
'''
Params:
q: (n_episode, n_tasks, n_actions+1)
Returns:
q: (n_episode, n_tasks, n_actions)
i_task: (n_episode, n_tasks, n_actions)
'''
q_shape = q.shape
# 1. 取最后一个维度第一个数作为task selector, 选择最擅长的task
_, i_task = q[...,0].max(dim = -1) # i_task shape: (n_episode)
# 2. 取对应项相乘,计算
i_task = i_task.unsqueeze(-1).unsqueeze(-1) # i_task shape: (n_episode, 1, 1)
i_task_shape = list(q_shape)
i_task_shape[-2] = 1
i_task = i_task.expand(i_task_shape) # i_task_shape: (n_episode, 1, n_action + 1)
q = torch.gather(q, dim=-2, index=i_task) # q shape (n_episode, 1, n_action + 1)。 选择q中仅与最高分任务的一行
q = (q[...,0].unsqueeze(-1) *q[...,1:]).squeeze(-2) # task_score * 对应动作q值。 q shape : (n_episode, n_action)
i_task = i_task.squeeze(1) # 将 i_task task维度去掉(因为该维度值必为1)
i_task = i_task[..., 0] # i_task shape (n_episode)
return q, i_task
def init_hidden(self, episode_num):
# 为每个episode中的每个agent都初始化一个eval_hidden、target_hidden
self.eval_hidden = torch.zeros((episode_num, self.n_agents, self.args.rnn_hidden_dim))
self.target_hidden = torch.zeros((episode_num, self.n_agents, self.args.rnn_hidden_dim))
def save_model(self, train_step):
num = str(train_step // self.args.save_cycle)
if not os.path.exists(self.model_dir):
os.makedirs(self.model_dir)
time_n = time.time()
torch.save(self.eval_task_net.state_dict(), self.model_dir + '/' + num +str(time_n) + '_td_net_params.pkl')
torch.save(self.eval_rnn.state_dict(), self.model_dir + '/' + num +str(time_n) + '_rnn_net_params.pkl')
| [
"852488062@qq.com"
] | 852488062@qq.com |
ee3ca22e9c0f5e05bbf59b552966f070d8a674d9 | 8613ec7f381a6683ae24b54fb2fb2ac24556ad0b | /20~29/ABC021/honest.py | 9c7f3d43c9ab13670129a435bb52b6b7b42038ab | [] | no_license | Forest-Y/AtCoder | 787aa3c7dc4d999a71661465349428ba60eb2f16 | f97209da3743026920fb4a89fc0e4d42b3d5e277 | refs/heads/master | 2023-08-25T13:31:46.062197 | 2021-10-29T12:54:24 | 2021-10-29T12:54:24 | 301,642,072 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 296 | py | n = int(input())
a, b = map(int, input().split())
m = int(input())
x, y = [0] * m, [0] * m
data = [[] for _ in range(n)]
for i in range(m):
x, y = map(int, input().split())
data[x - 1].append(y - 1)
data[y - 1].append(x - 1)
dist = [[-1] * n for i in range(n)]
dist[a - 1][b - 1] = 0 | [
"yuuya15009@gmail.com"
] | yuuya15009@gmail.com |
c7a1545c04ec79435caf4f721bcbd105da6ab6dc | 18e6cf3e0f748b55738d927c9ea0b0dda71dd60c | /modelo mvc/main.py | fa3118ceea937e8e73a8b6cd0e7db5ad20be8448 | [] | no_license | Adjailson/AulasETE | d0d94697d2c74afb4b38c176d34d6264e2e12ff3 | 0a223e41e8680a7eddac6443a4d9c21ab5d808b9 | refs/heads/main | 2023-09-04T18:52:38.252095 | 2021-11-23T14:48:22 | 2021-11-23T14:48:22 | 399,248,907 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 48 | py | from view.telaView import TelaView
TelaView()
| [
"noreply@github.com"
] | Adjailson.noreply@github.com |
d78e4bb780d288b7d29be51d0fba08d43575ed04 | e0e60b1efc1d91e39dfba9b612d82cf32b5efcda | /mysite/Grade_A/models.py | 4be9ab3e9110a63784716f2acd792856cbe9f654 | [] | no_license | Apaisley/Grade-A | f187b76c1a74a3edca35712dd361f6c49d60fbe6 | d750372c7e0e6c31efb1eb2699b84f7c56df3887 | refs/heads/master | 2021-09-23T03:54:51.311184 | 2020-03-12T00:56:45 | 2020-03-12T00:56:45 | 238,564,849 | 0 | 0 | null | 2021-09-22T19:40:01 | 2020-02-05T22:54:50 | Python | UTF-8 | Python | false | false | 5,374 | py | from django.db import models
from taggit.managers import TaggableManager
from django.utils.datetime_safe import datetime
from django.dispatch import receiver
from django.db.models.signals import post_save
import numpy as np
from django.contrib.auth.models import User
# Create your models here.
#////////////////////-------User and profile////////////////////////////////////
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
#////////////////////----Product-Model -----////////////////////////////////////////////////////////////////////////////////
class Products(models.Model):
# effect choices
UPLIFTED = 'UP'
HAPPY = 'HA'
RELAXED ='RE'
ENERGETIC='EN'
CREATIVE ='CE'
FOCUSED ='FO'
TALKATIVE ='TA'
EUPHORIC='EU'
GIGGLY ='GI'
HUNGRY ='HU'
AROUSED ='AR'
TINGLY= 'TI'
SLEEPY= 'SL'
Effects_Choices = [
(UPLIFTED, 'Uplifted'),
(HAPPY, 'Happy'),
(RELAXED, 'Relaxed'),
(ENERGETIC, 'Energetic'),
(CREATIVE,'Creative' ),
(FOCUSED,'Focused'),
(TALKATIVE,'Talkative'),
(EUPHORIC, 'Euphoric'),
(GIGGLY, 'Giggly'),
(HUNGRY, 'Hungry'),
(AROUSED, 'Aroused'),
(TINGLY, 'Tingy'),
(SLEEPY, 'Sleepy')]
#catagories choices ///////////////////////////////////////////////////////////////////////////////
POLLEN ='PL'
FEM_POLLEN ='FP'
SEEDS = 'SD'
FEM_SEEDS ='FS'
AUTO_SEEDS ='AS'
FLOWER ='FL'
CONCENTRATES ='CS'
EDIBLES ='ES'
Catagories_Choices =[
(POLLEN,'Pollen'),
(FEM_POLLEN, 'Feminized Pollen'),
(SEEDS, 'Seeds'),
(FEM_SEEDS,'Feminized Seeds'),
(AUTO_SEEDS, 'Auto Flowering Seeds'),
(FLOWER, 'Flower'),
(CONCENTRATES,'Concentrates'),
(EDIBLES, 'Edibles')]
#variety
SATIVA ='SA'
INDICA ='IN'
HYBRID ='HY'
Variety_choices =[
(SATIVA, 'Sativa'),
(INDICA, 'Indica'),
(HYBRID, 'Hybrid')]
name = models.CharField(max_length = 30)
catagory = models.CharField(max_length = 30, choices=Catagories_Choices)
variety = models.CharField(max_length= 2, choices=Variety_choices)
price = models.DecimalField(decimal_places=2, max_digits=20, default=0.00)
quantity = models.IntegerField()
Image = models.ImageField(default="Null")
description = models.CharField(max_length= 256, blank=True, null=True)
effects = models.CharField(max_length= 2 ,choices=Effects_Choices)
objects =models.Manager()
Review = models.ForeignKey('Review', on_delete=models.CASCADE,blank=True ,null=True)
tags = TaggableManager()
def average_rating(self):
all_ratings = map(lambda x: x.rating, self.review_set.all())
return np.mean(all_ratings)
def __str__(self):
return self.name,self.price
class Meta:
indexes =[
models.Index(fields=['name'])
]
#///////////////////////----Review-Model---/////////////////////////////////////
class Review(models.Model):
rating_choices = zip(range(6), range(6))
item = models.ForeignKey(Products, on_delete=models.CASCADE)
pub_date = models.DateTimeField('date published')
user = models.CharField(max_length=100)
comment = models.CharField(max_length=200)
rating = models.IntegerField(choices=rating_choices)
def __str__(self):
return ( )
#////////////////////////////-----Cart--------///////////////////////////////////////////////////////////////////
class Cart(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
count = models.PositiveIntegerField(default=0)
total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2)
updated = models.DateTimeField(auto_now_add=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "User: {} has {} items in their cart. Their total is ${}".format(self.user , self.count, self.total)
#/////////////////////----------Entry-------------------///////////////////////////////////////
class Entry(models.Model):
product = models.ForeignKey(Products, null=True, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
def __str__(self):
return"This entry contains {} {}(s).".format(self.quantity, self.product.name)
@receiver(post_save, sender=Entry)
def update_cart(sender, instance, **kwargs):
line_cost = instance.quantity * instance.product.line.cost
instance.cart.total += line_cost
instance.cart.count += instance.quantity
instance.cart.updated = datetime.now()
#////////////////////////////////////////////////////////////////////////////////////////////// | [
"apaisley2017@gmail.com"
] | apaisley2017@gmail.com |
ba928fba58eaca0bce8982e702f44206ea394ad4 | 631d667ad3f5ef759923e63644e82af5e6bdebf6 | /Cryptology/Cyphers/Cyphers/CypherGeneration/Bifid/BifidUtil.py | 7f6969a258ced04ba6d69ce894d5b5c5178752f2 | [] | no_license | frankbryce/First | e808537593f96fb693e65bb909cd1a84dc2fa76e | a69ccb715a65d7647272402790674336e72431f0 | refs/heads/master | 2020-12-28T23:34:58.777395 | 2014-05-15T00:15:52 | 2014-05-15T00:15:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,195 | py | import StrUtil as s
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ' # intentionally missing 'j'
Table = []
Result = []
def SetKey(keyword):
global Table
keyword = jtoi(s.StripStr(keyword))
keyalph = s.GenerateKeyedAlphabet(keyword,alphabet)
Table = [keyalph[i:i+5] for i in xrange(0, len(keyalph), 5)]
return Table
def jtoi(c):
return c.upper().replace("J","I")
def GetRow(c):
global Table
c = jtoi(c)
return [i for i,row in enumerate(Table) if c in row][0]
def GetCol(c):
global Table
c = jtoi(c)
return [row.index(c) for _,row in enumerate(Table) if c in row][0]
def GetChr(r,c):
global Table
return Table[r][c]
def GenerateResult(str):
str = jtoi(s.StripStr(str))
nums = [GetRow(c) for c in str]+[GetCol(c) for c in str]
numtuples = [nums[i:i+2] for i in xrange(0, len(nums), 2)]
return ''.join([GetChr(r,c) for (r,c) in numtuples])
def GenerateInput(str):
str = jtoi(s.StripStr(str))
tuples = [[GetRow(c),GetCol(c)] for c in str]
nums = [item for tuple in tuples for item in tuple]
coords = [(nums[i],nums[i+len(nums)/2]) for i in range(len(nums)/2)]
return ''.join([GetChr(r,c) for (r,c) in coords]) | [
"jonnyjack7@gmail.com"
] | jonnyjack7@gmail.com |
4bbad83e050e46e0bd882f7147d3faa597ef6614 | 26d6c34df00a229dc85ad7326de6cb5672be7acc | /msgraph-cli-extensions/beta/files_beta/setup.py | 917c1b376b39507335d14d388323f62f011a8a2c | [
"MIT"
] | permissive | BrianTJackett/msgraph-cli | 87f92471f68f85e44872939d876b9ff5f0ae6b2c | 78a4b1c73a23b85c070fed2fbca93758733f620e | refs/heads/main | 2023-06-23T21:31:53.306655 | 2021-07-09T07:58:56 | 2021-07-09T07:58:56 | 386,993,555 | 0 | 0 | NOASSERTION | 2021-07-17T16:56:05 | 2021-07-17T16:56:05 | null | UTF-8 | Python | false | false | 1,858 | py | #!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from codecs import open
from setuptools import setup, find_packages
# HISTORY.rst entry.
VERSION = '0.1.0'
try:
from azext_files_beta.manual.version import VERSION
except ImportError:
pass
# The full list of classifiers is available at
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: MIT License',
]
DEPENDENCIES = []
try:
from azext_files_beta.manual.dependency import DEPENDENCIES
except ImportError:
pass
with open('README.md', 'r', encoding='utf-8') as f:
README = f.read()
with open('HISTORY.rst', 'r', encoding='utf-8') as f:
HISTORY = f.read()
setup(
name='files_beta',
version=VERSION,
description='Microsoft Azure Command-Line Tools Files Extension',
author='Microsoft Corporation',
author_email='azpycli@microsoft.com',
url='https://github.com/Azure/azure-cli-extensions/tree/master/files_beta',
long_description=README + '\n\n' + HISTORY,
license='MIT',
classifiers=CLASSIFIERS,
packages=find_packages(),
install_requires=DEPENDENCIES,
package_data={'azext_files_beta': ['azext_metadata.json']},
)
| [
"japhethobalak@gmail.com"
] | japhethobalak@gmail.com |
d005e74749c88692012dd32e899d20852ffbc130 | c223e858c9ebf1b734221e4db4b3d594993a5536 | /thespian/system/timing.py | ec5f22afa79083a0f4d2f9c23f08117403194959 | [
"MIT"
] | permissive | jfasenfest/Thespian | 17f9738aff648328a40f94d3225427d82fe27e39 | 5979a2c9791b774fb620253bb62253c95cf7d4b5 | refs/heads/master | 2020-12-26T00:27:09.446001 | 2016-11-28T21:48:20 | 2016-11-28T21:48:20 | 48,067,029 | 0 | 0 | null | 2016-11-21T23:17:52 | 2015-12-15T20:24:12 | Python | UTF-8 | Python | false | false | 6,566 | py | from datetime import datetime, timedelta
###
### Time Management
###
def timePeriodSeconds(basis, other=None):
if isinstance(basis, datetime):
if isinstance(other, datetime):
return timePeriodSeconds(other - basis)
if isinstance(basis, timedelta):
try:
return basis.total_seconds()
except AttributeError:
# Must be Python 2.6... which doesn't have total_seconds yet
return (basis.days * 24.0 * 60 * 60) + basis.seconds + (basis.microseconds / 1000.0 / 1000)
raise TypeError('Cannot determine time from a %s argument'%str(type(basis)))
def toTimeDeltaOrNone(timespec):
if timespec is None: return None
if isinstance(timespec, timedelta): return timespec
if isinstance(timespec, int): return timedelta(seconds=timespec)
if isinstance(timespec, float):
return timedelta(seconds=int(timespec),
microseconds = int((timespec - int(timespec)) * 1000 * 1000))
raise TypeError('Unknown type for timespec: %s'%type(timespec))
class ExpiryTime(object):
def __init__(self, duration):
self._time_to_quit = None if duration is None else (datetime.now() + duration)
def expired(self):
return False if self._time_to_quit is None else (datetime.now() >= self._time_to_quit)
def remaining(self, forever=None):
return forever if self._time_to_quit is None else \
(timedelta(seconds=0) if datetime.now() > self._time_to_quit else \
(self._time_to_quit - datetime.now()))
def remainingSeconds(self, forever=None):
return forever if self._time_to_quit is None else \
(0 if datetime.now() > self._time_to_quit else \
timePeriodSeconds(self._time_to_quit - datetime.now()))
def __str__(self):
if self._time_to_quit is None: return 'Forever'
if self.expired():
return 'Expired_for_%s'%(datetime.now() - self._time_to_quit)
return 'Expires_in_' + str(self.remaining())
def __eq__(self, o):
if isinstance(o, timedelta):
o = ExpiryTime(o)
if self._time_to_quit == o._time_to_quit: return True
if self._time_to_quit == None or o._time_to_quit == None: return False
if self.expired() and o.expired(): return True
return abs(self._time_to_quit - o._time_to_quit) < timedelta(microseconds=1)
def __lt__(self, o):
try:
if self._time_to_quit is None and o._time_to_quit is None: return False
except Exception: pass
if self._time_to_quit is None: return False
if isinstance(o, timedelta):
o = ExpiryTime(o)
if o._time_to_quit is None: return True
return self._time_to_quit < o._time_to_quit
def __gt__(self, o):
try:
if self._time_to_quit is None and o._time_to_quit is None: return False
except Exception: pass
return not self.__lt__(o)
def __le__(self, o): return self.__eq__(o) or self.__lt__(o)
def __ge__(self, o): return self.__eq__(o) or self.__gt__(o)
def __ne__(self, o): return not self.__eq__(o)
def __bool__(self): return self.expired()
def __nonzero__(self): return self.expired()
class ExpirationTimer(object):
"""Keeps track of a duration relative to an original time and
indicates whether that duration has expired or how much time is
left before it expires. As an optimization, this object will
not call datetime.now() itself and must be updated via the
`update_time_now()` method to accurately measure elapsed
time.
May also be initialized with a duration of None, indicating
that it should never timeout and that `remaining()` should
return the forever value (defaulting to None).
"""
def __init__(self, duration, timenow=None):
self._time_now = timenow or datetime.now()
self._time_to_quit = None if duration is None else (self._time_now + duration)
def update_time_now(self, timenow):
"Call this to update the elapsed time."
self._time_now = timenow
def expired(self):
"Returns true if the indicated duration has passed since this was created."
return False if self._time_to_quit is None else (self._time_now >= self._time_to_quit)
def remaining(self, forever=None):
"""Returns a timedelta of remaining time until expiration, or 0 if the
duration has already expired. Returns forever if no timeout."""
return forever if self._time_to_quit is None else \
(timedelta(seconds=0) if self._time_now > self._time_to_quit else \
(self._time_to_quit - self._time_now))
def remainingSeconds(self, forever=None):
"""Similar to `remaining()`, but returns an floating point value of the
number of remaining seconds instead of returning a
timedelta object.
"""
return forever if self._time_to_quit is None else \
(0 if self._time_now > self._time_to_quit else \
timePeriodSeconds(self._time_to_quit - self._time_now))
def __str__(self):
if self._time_to_quit is None: return 'Forever'
if self.expired():
return 'Expired_for_%s'%(self._time_now - self._time_to_quit)
return 'Expires_in_' + str(self.remaining())
def __eq__(self, o):
if isinstance(o, timedelta):
o = ExpiryTime(o)
if self._time_to_quit == o._time_to_quit: return True
if self._time_to_quit == None or o._time_to_quit == None: return False
if self.expired() and o.expired(): return True
return abs(self._time_to_quit - o._time_to_quit) < timedelta(microseconds=1)
def __lt__(self, o):
try:
if self._time_to_quit is None and o._time_to_quit is None: return False
except Exception: pass
if self._time_to_quit is None: return False
if isinstance(o, timedelta):
o = ExpiryTime(o)
if o._time_to_quit is None: return True
return self._time_to_quit < o._time_to_quit
def __gt__(self, o):
try:
if self._time_to_quit is None and o._time_to_quit is None: return False
except Exception: pass
return not self.__lt__(o)
def __le__(self, o): return self.__eq__(o) or self.__lt__(o)
def __ge__(self, o): return self.__eq__(o) or self.__gt__(o)
def __ne__(self, o): return not self.__eq__(o)
def __bool__(self): return self.expired()
def __nonzero__(self): return self.expired()
| [
"kquick@godaddy.com"
] | kquick@godaddy.com |
08b555c7ec6ff9ee16e439791eb8fbf841af3b69 | 8d74ac2b0acad1a10bc916d8566181ac801c7597 | /articles/migrations/0007_auto_20210305_2120.py | 4b9e92250ae194fa86adcf0379f40449a515f1d4 | [] | no_license | PatrickBoynton/news-app | e459b08f651258388d0d20074d94a685ad57d44f | 125464d4ff89d7a2297536e39ba4dd770e5089fa | refs/heads/main | 2023-08-22T00:17:30.512303 | 2021-09-24T05:19:32 | 2021-09-24T05:19:32 | 343,518,497 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 832 | py | # Generated by Django 3.1.7 on 2021-03-05 21:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0006_auto_20210305_0416'),
]
operations = [
migrations.AlterField(
model_name='article',
name='article_status',
field=models.CharField(choices=[('pending', 'pending'), ('published', 'published'), ('rejected', 'rejected'), ('archived', 'archived')], default='draft', max_length=80),
),
migrations.AlterField(
model_name='article',
name='article_type',
field=models.CharField(choices=[('astronomy', 'astronomy'), ('cosmology', 'cosmology'), ('exoplanets', 'exoplanets'), ('editorial', 'editorial')], default='astronomy', max_length=80),
),
]
| [
"jpboynton3@gmail.com"
] | jpboynton3@gmail.com |
62a6d539be9bbfbbbbed23228177058ae2f177d0 | 189d590adf09e309862e5f3aef1012c8a6e0b337 | /userbot/plugin/rename.py | d34526cdf9e8f7d497224a26489c06d9e3e5c380 | [
"MIT"
] | permissive | LegitWoLf/BlackShadowBot | dbabec745ccbb6dac5615dfaa5dd8a24849c9c4b | be3e3e5f390141944ce2f412274cbb0e1463c493 | refs/heads/master | 2022-07-02T21:30:25.346111 | 2020-05-15T11:50:04 | 2020-05-15T11:50:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,728 | py | """Rename Telegram Files
Syntax:
.rename file.name
.rnupload file.name
.rnstreamupload file.name
By @Ck_ATR"""
import aiohttp
import asyncio
from datetime import datetime
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
import json
import os
import requests
import subprocess
from telethon import events
from telethon.tl.types import DocumentAttributeVideo
from telethon.errors import MessageNotModifiedError
import time
from userbot.utils import progress, humanbytes, time_formatter, admin_cmd
import io
import math
import os
from pySmartDL import SmartDL
thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg"
def get_video_thumb(file, output=None, width=90):
metadata = extractMetadata(createParser(file))
p = subprocess.Popen([
'ffmpeg', '-i', file,
'-ss', str(int((0, metadata.get('duration').seconds)[metadata.has('duration')] / 2)),
'-filter:v', 'scale={}:-1'.format(width),
'-vframes', '1',
output,
], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if not p.returncode and os.path.lexists(file):
return output
@borg.on(admin_cmd("rename (.*)"))
async def _(event):
if event.fwd_from:
return
await event.edit("Renaming in process 🙄🙇♂️🙇♂️🙇♀️ It might take some time if file size is big")
input_str = event.pattern_match.group(1)
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
start = datetime.now()
file_name = input_str
reply_message = await event.get_reply_message()
# c_time = time.time()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await borg.download_media(
reply_message,
downloaded_file_name
)
end = datetime.now()
ms = (end - start).seconds
if os.path.exists(downloaded_file_name):
await event.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms))
else:
await event.edit("Error Occurred\n {}".format(input_str))
else:
await event.edit("Syntax // `.rename file.name` as reply to a Telegram media")
@borg.on(admin_cmd("rnupload (.*)"))
async def _(event):
if event.fwd_from:
return
thumb = None
if os.path.exists(thumb_image_path):
thumb = thumb_image_path
await event.edit("Rename & Upload in process 🙄🙇♂️🙇♂️🙇♀️ It might take some time if file size is big")
input_str = event.pattern_match.group(1)
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
start = datetime.now()
file_name = input_str
reply_message = await event.get_reply_message()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await borg.download_media(
reply_message,
downloaded_file_name
)
end = datetime.now()
ms_one = (end - start).seconds
if os.path.exists(downloaded_file_name):
c_time = time.time()
await borg.send_file(
event.chat_id,
downloaded_file_name,
force_document=False,
supports_streaming=False,
allow_cache=False,
reply_to=event.message.id,
thumb=thumb,
)
end_two = datetime.now()
os.remove(downloaded_file_name)
ms_two = (end_two - end).seconds
await event.edit("Downloaded in {} seconds. Uploaded in {} seconds.".format(ms_one, ms_two))
else:
await event.edit("File Not Found {}".format(input_str))
else:
await event.edit("Syntax // .rnupload file.name as reply to a Telegram media")
@borg.on(admin_cmd("rnstreamupload (.*)"))
async def _(event):
if event.fwd_from:
return
await event.edit("Rename & Upload as Streamable in process 🙄🙇♂️🙇♂️🙇♀️ It might take some time if file size is big")
input_str = event.pattern_match.group(1)
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
start = datetime.now()
file_name = input_str
reply_message = await event.get_reply_message()
c_time = time.time()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await borg.download_media(
reply_message,
downloaded_file_name
)
end_one = datetime.now()
ms_one = (end_one - start).seconds
if os.path.exists(downloaded_file_name):
thumb = None
if not downloaded_file_name.endswith((".mkv", ".mp4", ".mp3", ".flac")):
await event.edit("Sorry. But I don't think {} is a streamable file. Please try again.\n**Supported Formats**: MKV, MP4, MP3, FLAC".format(downloaded_file_name))
return False
if os.path.exists(thumb_image_path):
thumb = thumb_image_path
else:
thumb = get_video_thumb(downloaded_file_name, thumb_image_path)
start = datetime.now()
metadata = extractMetadata(createParser(downloaded_file_name))
duration = 0
width = 0
height = 0
if metadata.has("duration"):
duration = metadata.get('duration').seconds
if os.path.exists(thumb_image_path):
metadata = extractMetadata(createParser(thumb_image_path))
if metadata.has("width"):
width = metadata.get("width")
if metadata.has("height"):
height = metadata.get("height")
# Telegram only works with MP4 files
# this is good, since with MKV files sent as streamable Telegram responds,
# Bad Request: VIDEO_CONTENT_TYPE_INVALID
# c_time = time.time()
try:
await borg.send_file(
event.chat_id,
downloaded_file_name,
thumb=thumb,
caption="reuploaded by [IndianBot](https://github.com/blackshadow98/BlackShadowBot",
force_document=False,
allow_cache=False,
reply_to=event.message.id,
attributes=[
DocumentAttributeVideo(
duration=duration,
w=width,
h=height,
round_message=False,
supports_streaming=True
)
]
)
except Exception as e:
await event.edit(str(e))
else:
end = datetime.now()
os.remove(downloaded_file_name)
ms_two = (end - end_one).seconds
await event.edit("Downloaded in {} seconds. Uploaded in {} seconds.".format(ms_one, ms_two))
else:
await event.edit("File Not Found {}".format(input_str))
else:
await event.edit("Syntax // .rnstreamupload file.name as reply to a Telegram media")
| [
"noreply@github.com"
] | LegitWoLf.noreply@github.com |
07774d6b330c67e1c6a3bd8784a7181f14658bae | 329e8d1ac5b2d38fef727921fdcebc9435dc8842 | /sysdetails.py | 419b8d78f0c693d716f6e4f0dec0d2d730574463 | [
"MIT"
] | permissive | ChankitSaini/DaisyX-Extra | 082a9a008df458bd3aeb765c068055598bea5978 | e1cafbbb4f5a7845ffd70e16e4395e7e797b2cf7 | refs/heads/main | 2023-04-24T02:25:15.715245 | 2021-05-14T05:18:19 | 2021-05-14T05:18:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,673 | py | import platform
import sys
from datetime import datetime
import psutil
from telethon import __version__
from DaisyX.utils import admin_cmd, sudo_cmd
from DaisyX import ALIVE_NAME
# ================= CONSTANT =================
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else bot.me.first_name
# ============================================
@bot.on(admin_cmd(outgoing=True, pattern=r"spc$"))
@bot.on(sudo_cmd(allow_sudo=True, pattern=r"spc$"))
async def psu(event):
uname = platform.uname()
softw = "**System Information**\n"
softw += f"`System : {uname.system}`\n"
softw += f"`Release : {uname.release}`\n"
softw += f"`Version : {uname.version}`\n"
softw += f"`Machine : {uname.machine}`\n"
# Boot Time
boot_time_timestamp = psutil.boot_time()
bt = datetime.fromtimestamp(boot_time_timestamp)
softw += f"`Boot Time: {bt.day}/{bt.month}/{bt.year} {bt.hour}:{bt.minute}:{bt.second}`\n"
# CPU Cores
cpuu = "**CPU Info**\n"
cpuu += "`Physical cores : " + str(psutil.cpu_count(logical=False)) + "`\n"
cpuu += "`Total cores : " + str(psutil.cpu_count(logical=True)) + "`\n"
# CPU frequencies
cpufreq = psutil.cpu_freq()
cpuu += f"`Max Frequency : {cpufreq.max:.2f}Mhz`\n"
cpuu += f"`Min Frequency : {cpufreq.min:.2f}Mhz`\n"
cpuu += f"`Current Frequency: {cpufreq.current:.2f}Mhz`\n\n"
# CPU usage
cpuu += "**CPU Usage Per Core**\n"
for i, percentage in enumerate(psutil.cpu_percent(percpu=True)):
cpuu += f"`Core {i} : {percentage}%`\n"
cpuu += "**Total CPU Usage**\n"
cpuu += f"`All Core: {psutil.cpu_percent()}%`\n"
# RAM Usage
svmem = psutil.virtual_memory()
memm = "**Memory Usage**\n"
memm += f"`Total : {get_size(svmem.total)}`\n"
memm += f"`Available : {get_size(svmem.available)}`\n"
memm += f"`Used : {get_size(svmem.used)}`\n"
memm += f"`Percentage: {svmem.percent}%`\n"
# Bandwidth Usage
bw = "**Bandwith Usage**\n"
bw += f"`Upload : {get_size(psutil.net_io_counters().bytes_sent)}`\n"
bw += f"`Download: {get_size(psutil.net_io_counters().bytes_recv)}`\n"
help_string = f"{str(softw)}\n"
help_string += f"{str(cpuu)}\n"
help_string += f"{str(memm)}\n"
help_string += f"{str(bw)}\n"
help_string += "**Engine Info**\n"
help_string += f"`Python {sys.version}`\n"
help_string += f"`Telethon {__version__}`"
await event.edit(help_string)
def get_size(inputbytes, suffix="B"):
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if inputbytes < factor:
return f"{inputbytes:.2f}{unit}{suffix}"
inputbytes /= factor
| [
"noreply@github.com"
] | ChankitSaini.noreply@github.com |
62604aec9fec8d853af4fd5bdc81a077ae397e7c | 4e567fc53288f53cdcfa37c0f5490a29cf4bc0cd | /projects-inventory/inventory/inventorya.py | dc89e6b234d8d28aaf3a41b5b98a5039f3ac59d3 | [] | no_license | sidarmawan/ansible_training | 3e4bba3bde4557a23c92735314f09328319463c9 | 77d3acb3430143458de07ca2b8257f3a2637f59b | refs/heads/master | 2022-04-08T06:01:31.043044 | 2020-01-16T09:56:41 | 2020-01-16T09:56:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 103 | py | htttps://materials.example.com/labs/projects-inventory/inventorya.py: Unsupported scheme ‘htttps’.
| [
"student@workstation.lab.example.com"
] | student@workstation.lab.example.com |
65a4c9be5fe8054649cd3ece5dbe367bc18a3e9e | 2dc17d12ff6ea9794177c81aa4f385e4e09a4aa5 | /archive/55JumpGame.py | f503b433be7298c6acd75a571e1e0b2c43dd3322 | [] | no_license | doraemon1293/Leetcode | 924b19f840085a80a9e8c0092d340b69aba7a764 | 48ba21799f63225c104f649c3871444a29ab978a | refs/heads/master | 2022-10-01T16:20:07.588092 | 2022-09-08T02:44:56 | 2022-09-08T02:44:56 | 122,086,222 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Python | false | false | 398 | py | # coding=utf-8
'''
Created on 2017�3�7�
@author: Administrator
'''
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
mini_true = len(nums) - 1
for i in xrange(len(nums) - 1, -1, -1):
if nums[i] >= (mini_true - i):
mini_true = i
return mini_true == 0
| [
"yanhuang1293@gmail.com"
] | yanhuang1293@gmail.com |
ea6f324c9eaa7e365c7e8d1385843b1e0080dd62 | 5f0ce32209a69ca934174631df447b8d4d13caaa | /bibliotecaMath.py | 408d5eaecc1fb58bbb5282697c3d4545a2ba33a6 | [] | no_license | arthurcardosof/praticando-python | 8fea1da81ab09402d35db9f8cebfeaae664e90bb | f3c997e1963ddf1caad0396a6ec52803dc309583 | refs/heads/master | 2020-12-21T07:48:17.650179 | 2020-01-26T19:26:00 | 2020-01-26T19:26:00 | 236,363,509 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 459 | py | '''
Exercicio: Crie uma função para verificar se uma palavra é palíndrome. Retorna true se for uma palavra palíndrome, e false se não for.
Exemplos de palavras palindromes: ovo, arara
'arara' -> [0], [1], [2]
'''
def palindrome(palavra): return palavra == palavra[::-1]
print(palindrome('arara'))
print(palindrome('murilo'))
print(palindrome('OVO'))
def contaAte1000():
for i in range(1000):
print(i)
contaAte1000()
| [
"panchobauer@gmail.com"
] | panchobauer@gmail.com |
db7d00585385b6589b6b11d0e3b16814d349cc17 | a61ebd1507eeaa334aff44800b022ef0a258752a | /Code/CodeChef/remainder.py | 37c511c002d48cc5390d47f937a2ec559c35e257 | [
"MIT"
] | permissive | Jimut123/competitive_programming | 14ce0ab65414e6086763519f95487cddc91205a9 | b4cdebaceee719c1a256921829ebafda11c515f5 | refs/heads/master | 2023-03-05T15:42:57.194176 | 2022-04-08T08:53:26 | 2022-04-08T08:53:26 | 156,541,142 | 1 | 0 | null | 2019-05-29T17:10:28 | 2018-11-07T12:09:55 | C++ | UTF-8 | Python | false | false | 152 | py | #jimutbahanpal@yahoo.com
t = int(input())
l = []
for i in range(t):
m,n = map(int,input().split())
l.append(m%n)
for item in l:
print(item)
| [
"jimutbahanpal@yahoo.com"
] | jimutbahanpal@yahoo.com |
3bb37917a0398704646cc7328ac2b1f67c1f8a85 | 1ca5995b3f1debd011cf4c9d3382979ad103ff40 | /ros_workspace/src/regions/src/applytransformations.py | 167f015c21a78140e0270e815319a39cff8b1325 | [] | no_license | rcxking/cv_final_project | 06e864554affd19d062909c6b6b3d5e907f19f4f | 8751cd15d23afe721e4c523675dcd4648a4e2308 | refs/heads/master | 2020-06-01T17:53:19.579281 | 2015-05-15T16:24:24 | 2015-05-15T16:24:24 | 34,287,134 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,160 | py | #!/usr/bin/python
'''
applytransformations.py - This script applies a series of transformations
to an input side of images and pickles the data.
Bryant Pong / Micah Corah
CSCI-4962
5/10/15
Last Updated: Bryant Pong: 5/14/15 - 5:10 PM
'''
# Python Imports:
import cv2
import numpy as np
from matplotlib import pyplot as plt
import cPickle as pickle # cPickle is faster for Python 2.x
import os # listdir()
import transformations as tf # Custom transformations
'''
This function loads pickled data of images and features
to process.
'''
def loadImages(imgFolder):
return [pickle.load(open(imgFolder+"/20150423_152021.dat", "rb"))]
# Main function:
def transform():
# Load the images to run transformations on:
data = loadImages("../../../../data/pickle")
print("There are: " + str(len(data)) + " datasets to process")
# Global dataset:
globalData = []
datasetNum = 1
imgNum = 1
for dataset in data:
print("Now extracting images from dataset: " + str(datasetNum))
print("There are: " + str(len(dataset)) + " images in this dataset")
for img in dataset:
print("Now extracting features for image : " + str(imgNum) + " of dataset: " + str(datasetNum))
# Extract the image and feature set from each image:
image = img[0]
features = img[1]
imgWidth = image.shape[1]
imgHeight = image.shape[0]
# Resize the images and features:
resizedImage = cv2.resize(image, (int(0.5*imgWidth),int(0.5*imgHeight)))
resizedFeatures = features * 0.5
globalData.append( (resizedImage, resizedFeatures) )
'''
Apply the following transformations to each image:
Transformations 1 - 12: Rotate the image from -30 degrees to 30 degrees
in increments of 5 degrees
Transformations 13 - 14: Generate two perspective transformations with added
random Gaussian noise to stimulate vibrations in the
robot while traveling
Transformations 15 - 16: Generate two saturation transformations with
increasing/decreasing saturation levels to simulate
shadows and sunlight
'''
# Generate the rotated images:
rotImg, rotFeatures = tf.rotateCenter(resizedImage, resizedFeatures, -10)
rotImg2, rotFeatures2 = tf.rotateCenter(resizedImage, resizedFeatures, 10)
globalData.append( (rotImg, rotFeatures) )
globalData.append( (rotImg2, rotFeatures2) )
# Generate transformations 13 - 14 (Perspective Transformations):
trans13, trans13Features = tf.hTrans(resizedImage, resizedFeatures)
trans14, trans14Features = tf.hTrans(resizedImage, resizedFeatures)
globalData.append( (trans13, trans13Features))
globalData.append( (trans14, trans14Features))
# Generate transformations 15 - 16 (Saturation Transformations):
trans15 = tf.sTran(resizedImage, -50)
trans16 = tf.sTran(resizedImage, 50)
globalData.append( (trans15, resizedFeatures) )
globalData.append( (trans16, resizedFeatures) )
imgNum += 1
imgNum = 0
datasetNum += 1
print("data dump complete")
return globalData
# Main function runner:
if __name__ == "__main__":
transform()
| [
"rcxking@gmail.com"
] | rcxking@gmail.com |
a34d691e65e99a6c67292407136f05cfbeaeb546 | bafacfb2290ba3d32963ecfbfb6a749e71438050 | /cli_site/cli/migrations/0002_auto_20190705_1248.py | 004b28b80608f1b9385ba5bd9682755af98f08ac | [] | no_license | OneTallProgrammer/django-cli | 185066a564d52afe9f07301b0e94383b72735f64 | 8107b68b57c101fb20cdf857fbd6e5fe9bcbc69a | refs/heads/master | 2020-06-14T05:24:05.038459 | 2019-07-10T19:20:21 | 2019-07-10T19:20:21 | 194,916,074 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 841 | py | # Generated by Django 2.2.2 on 2019-07-05 12:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cli', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Agent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('agent_name', models.CharField(max_length=200)),
('agent_type', models.IntegerField()),
],
),
migrations.AddField(
model_name='command',
name='agent_id',
field=models.ForeignKey(default=-1, on_delete=django.db.models.deletion.CASCADE, to='cli.Agent'),
preserve_default=False,
),
]
| [
"jmcauthen@live.com"
] | jmcauthen@live.com |
c80f4c821974aa8bd95e8d011cc9d0f71baae2a6 | 19e4d45d574d6dedd46fa9fac20faa1151fa2601 | /Euler49-PrimePermutations.py | a15d07ba65b2b5b3933211a5860e9f535f18255b | [] | no_license | zzflux/ProjectEuler | bba88d5e42232aa0d39d8325a7752f0983084135 | 796d0ed72738031a300a0e950bb792d046518e73 | refs/heads/master | 2021-01-01T05:14:19.125012 | 2016-04-25T22:45:17 | 2016-04-25T22:45:17 | 56,016,380 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,861 | py | #Project Euler problem #49
#Prime permutations
#Jon McMahon 2016
import DivisibilityTools as dtools
import itertools as itools
import math
DIGITS = 4
SEQ_LEN = 3
BLACKLIST = ((1487, 4817, 8147),)
PRIMELIST = dtools.primeListWithDigits(DIGITS)
PRIMESET = frozenset(PRIMELIST)
GREATEST_PRIME = max(PRIMELIST)
SMALLEST_PRIME = min(PRIMELIST)
def sequenceGenerator(prefix = None):
#print('Called with prefix=', prefix)
if not prefix:
for p in PRIMELIST:
for grp in sequenceGenerator((p,)):
if len(grp) == SEQ_LEN:
yield grp
elif len(prefix) == 1:
#print('Set1:', set(int(''.join(_)) for _ in itools.permutations(str(prefix[-1]))))
#print('Set2:', '*primes*')
#print('Set3:', set(range(prefix[-1] + 1, GREATEST_PRIME + 1)))
#print('Intersection:', sorted(set(int(''.join(_)) for _ in itools.permutations(str(prefix[-1]))) & PRIMESET & set(range(prefix[-1] + 1, GREATEST_PRIME + 1))))
for nextprime in sorted(set(int(''.join(_)) for _ in itools.permutations(str(prefix[-1]))) & PRIMESET & set(range(prefix[-1] + 1, GREATEST_PRIME + 1))):
#print('Supposedly calling on', prefix + (nextprime,))
for g in sequenceGenerator(prefix + (nextprime,)):
yield g
elif len(prefix) == SEQ_LEN:
yield prefix
else:
#print('Seq len:', len(prefix))
np = 2 * prefix[-1] - prefix[0]
if np in (PRIMESET & set(int(''.join(_)) for _ in itools.permutations(str(prefix[-1])))):
for g in sequenceGenerator(prefix + (np,)):
yield g
else:
#print('Impossible')
pass
if __name__ == '__main__':
for seq in sequenceGenerator():
if not seq in BLACKLIST:
print('Answer:', ''.join(str(_) for _ in seq))
| [
"jonmcmahon21@gmail.com"
] | jonmcmahon21@gmail.com |
aa9c2bf1b305cc6403a880948c9ce34f01af5268 | 2d19317ab9af09be9e6c8f0a25d4a43d4632b680 | /first_project/urls.py | 44eee9ee4a82b0a41d31cece1c0325b3b2218316 | [] | no_license | rudiq4/first_project | 73837d297b21ccd7c706fc08373473e9e4cd8b29 | ba0e987f863f599da9700c355875af76158b76f0 | refs/heads/master | 2021-01-25T13:41:56.102967 | 2018-03-27T14:15:26 | 2018-03-27T14:15:26 | 123,607,387 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,132 | py | """first_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('Auto.urls')),
url(r'^', include('Post.urls')),
url(r'user/', include('User.urls')),
] \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | [
"rudikvovan@gmail.com"
] | rudikvovan@gmail.com |
81aa064e876bd2b4d52c97a334447ea805b84532 | e32f87eeccab48b690af53cc9e9c5558c21ce589 | /brownian_tree/tools/size.py | b27caad8c830dc1ab0fcbb3d859a992928c9627a | [] | no_license | mblicharz/diffusion-limited-aggregation | c822f21f7d0c0e7aba8c0dbe870bcff8ec650b7e | 40ed87c9d909ddf154483365a3c8bf525adb2b5b | refs/heads/master | 2023-05-31T11:38:11.878870 | 2021-07-02T15:14:00 | 2021-07-02T15:14:00 | 378,947,926 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 368 | py | class Size:
def __init__(self, max_x: int, max_y: int):
self._validate(max_x, max_y)
self.max_x = max_x
self.max_y = max_y
def _validate(self, max_x, max_y) -> bool:
if max_x < 0 or max_y < 0:
raise ValueError(
"Both dimensions should be equal or greater than 0."
)
return True
| [
"maciej.blicharz@protonmail.com"
] | maciej.blicharz@protonmail.com |
6093d2129fcc9b86264e32f2199313f4ee2360fc | bdf86d69efc1c5b21950c316ddd078ad8a2f2ec0 | /venv/Lib/site-packages/twisted/web/_http2.py | 1a425a7729ffd88e8e0c2c4b4f98294cbdc6f975 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | DuaNoDo/PythonProject | 543e153553c58e7174031b910fd6451399afcc81 | 2c5c8aa89dda4dec2ff4ca7171189788bf8b5f2c | refs/heads/master | 2020-05-07T22:22:29.878944 | 2019-06-14T07:44:35 | 2019-06-14T07:44:35 | 180,941,166 | 1 | 1 | null | 2019-06-04T06:27:29 | 2019-04-12T06:05:42 | Python | UTF-8 | Python | false | false | 45,541 | py | # -*- test-case-name: twisted.web.test.test_http2 -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
HTTP2 Implementation
This is the basic server-side protocol implementation used by the Twisted
Web server for HTTP2. This functionality is intended to be combined with the
HTTP/1.1 and HTTP/1.0 functionality in twisted.web.http to provide complete
protocol support for HTTP-type protocols.
This API is currently considered private because it's in early draft form. When
it has stabilised, it'll be made public.
"""
from __future__ import absolute_import, division
import io
import sys
import warnings
from collections import deque
import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import priority
from twisted.internet._producer_helpers import _PullToPush
from twisted.internet.defer import Deferred
from twisted.internet.error import ConnectionLost
from twisted.internet.interfaces import (
IProtocol, ITransport, IConsumer, IPushProducer, ISSLTransport
)
from twisted.internet.protocol import Protocol
from twisted.logger import Logger
from twisted.protocols.policies import TimeoutMixin
from twisted.python.failure import Failure
from zope.interface import implementer
# This API is currently considered private.
__all__ = []
_END_STREAM_SENTINEL = object()
# Python versions 2.7.3 and older don't have a memoryview object that plays
# well with the struct module, which h2 needs. On those versions, just refuse
# to import.
if sys.version_info < (2, 7, 4):
warnings.warn(
"HTTP/2 cannot be enabled because this version of Python is too "
"old, and does not fully support memoryview objects.",
UserWarning,
stacklevel=2,
)
raise ImportError("HTTP/2 not supported on this Python version.")
@implementer(IProtocol, IPushProducer)
class H2Connection(Protocol, TimeoutMixin):
"""
A class representing a single HTTP/2 connection.
This implementation of L{IProtocol} works hand in hand with L{H2Stream}.
This is because we have the requirement to register multiple producers for
a single HTTP/2 connection, one for each stream. The standard Twisted
interfaces don't really allow for this, so instead there's a custom
interface between the two objects that allows them to work hand-in-hand here.
@ivar conn: The HTTP/2 connection state machine.
@type conn: L{h2.connection.H2Connection}
@ivar streams: A mapping of stream IDs to L{H2Stream} objects, used to call
specific methods on streams when events occur.
@type streams: L{dict}, mapping L{int} stream IDs to L{H2Stream} objects.
@ivar priority: A HTTP/2 priority tree used to ensure that responses are
prioritised appropriately.
@type priority: L{priority.PriorityTree}
@ivar _consumerBlocked: A flag tracking whether or not the L{IConsumer}
that is consuming this data has asked us to stop producing.
@type _consumerBlocked: L{bool}
@ivar _sendingDeferred: A L{Deferred} used to restart the data-sending loop
when more response data has been produced. Will not be present if there
is outstanding data still to send.
@type _consumerBlocked: A L{twisted.internet.defer.Deferred}, or L{None}
@ivar _outboundStreamQueues: A map of stream IDs to queues, used to store
data blocks that are yet to be sent on the connection. These are used
both to handle producers that do not respect L{IConsumer} but also to
allow priority to multiplex data appropriately.
@type _outboundStreamQueues: A L{dict} mapping L{int} stream IDs to
L{collections.deque} queues, which contain either L{bytes} objects or
C{_END_STREAM_SENTINEL}.
@ivar _sender: A handle to the data-sending loop, allowing it to be
terminated if needed.
@type _sender: L{twisted.internet.task.LoopingCall}
@ivar abortTimeout: The number of seconds to wait after we attempt to shut
the transport down cleanly to give up and forcibly terminate it. This
is only used when we time a connection out, to prevent errors causing
the FD to get leaked. If this is L{None}, we will wait forever.
@type abortTimeout: L{int}
@ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be
used to forcibly close the transport if it doesn't close cleanly.
@type _abortingCall: L{twisted.internet.base.DelayedCall}
"""
factory = None
site = None
abortTimeout = 15
_log = Logger()
_abortingCall = None
def __init__(self, reactor=None):
config = h2.config.H2Configuration(
client_side=False, header_encoding=None
)
self.conn = h2.connection.H2Connection(config=config)
self.streams = {}
self.priority = priority.PriorityTree()
self._consumerBlocked = None
self._sendingDeferred = None
self._outboundStreamQueues = {}
self._streamCleanupCallbacks = {}
self._stillProducing = True
if reactor is None:
from twisted.internet import reactor
self._reactor = reactor
# Start the data sending function.
self._reactor.callLater(0, self._sendPrioritisedData)
# Implementation of IProtocol
def connectionMade(self):
"""
Called by the reactor when a connection is received. May also be called
by the L{twisted.web.http._GenericHTTPChannelProtocol} during upgrade
to HTTP/2.
"""
self.setTimeout(self.timeOut)
self.conn.initiate_connection()
self.transport.write(self.conn.data_to_send())
def dataReceived(self, data):
"""
Called whenever a chunk of data is received from the transport.
@param data: The data received from the transport.
@type data: L{bytes}
"""
self.resetTimeout()
try:
events = self.conn.receive_data(data)
except h2.exceptions.ProtocolError:
# A remote protocol error terminates the connection.
dataToSend = self.conn.data_to_send()
self.transport.write(dataToSend)
self.transport.loseConnection()
self.connectionLost(Failure())
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
self._requestReceived(event)
elif isinstance(event, h2.events.DataReceived):
self._requestDataReceived(event)
elif isinstance(event, h2.events.StreamEnded):
self._requestEnded(event)
elif isinstance(event, h2.events.StreamReset):
self._requestAborted(event)
elif isinstance(event, h2.events.WindowUpdated):
self._handleWindowUpdate(event)
elif isinstance(event, h2.events.PriorityUpdated):
self._handlePriorityUpdate(event)
elif isinstance(event, h2.events.ConnectionTerminated):
self.transport.loseConnection()
self.connectionLost(ConnectionLost("Remote peer sent GOAWAY"))
dataToSend = self.conn.data_to_send()
if dataToSend:
self.transport.write(dataToSend)
def timeoutConnection(self):
"""
Called when the connection has been inactive for
L{self.timeOut<twisted.protocols.policies.TimeoutMixin.timeOut>}
seconds. Cleanly tears the connection down, attempting to notify the
peer if needed.
We override this method to add two extra bits of functionality:
- We want to log the timeout.
- We want to send a GOAWAY frame indicating that the connection is
being terminated, and whether it was clean or not. We have to do this
before the connection is torn down.
"""
self._log.info(
"Timing out client {client}", client=self.transport.getPeer()
)
# Check whether there are open streams. If there are, we're going to
# want to use the error code PROTOCOL_ERROR. If there aren't, use
# NO_ERROR.
if (self.conn.open_outbound_streams > 0 or
self.conn.open_inbound_streams > 0):
error_code = h2.errors.ErrorCodes.PROTOCOL_ERROR
else:
error_code = h2.errors.ErrorCodes.NO_ERROR
self.conn.close_connection(error_code=error_code)
self.transport.write(self.conn.data_to_send())
# Don't let the client hold this connection open too long.
if self.abortTimeout is not None:
# We use self.callLater because that's what TimeoutMixin does, even
# though we have a perfectly good reactor sitting around. See
# https://twistedmatrix.com/trac/ticket/8488.
self._abortingCall = self.callLater(
self.abortTimeout, self.forceAbortClient
)
# We're done, throw the connection away.
self.transport.loseConnection()
def forceAbortClient(self):
"""
Called if C{abortTimeout} seconds have passed since the timeout fired,
and the connection still hasn't gone away. This can really only happen
on extremely bad connections or when clients are maliciously attempting
to keep connections open.
"""
self._log.info(
"Forcibly timing out client: {client}",
client=self.transport.getPeer()
)
# We want to lose track of the _abortingCall so that no-one tries to
# cancel it.
self._abortingCall = None
self.transport.abortConnection()
def connectionLost(self, reason):
"""
Called when the transport connection is lost.
Informs all outstanding response handlers that the connection has been
lost, and cleans up all internal state.
"""
self._stillProducing = False
self.setTimeout(None)
for stream in self.streams.values():
stream.connectionLost(reason)
for streamID in list(self.streams.keys()):
self._requestDone(streamID)
# If we were going to force-close the transport, we don't have to now.
if self._abortingCall is not None:
self._abortingCall.cancel()
self._abortingCall = None
# Implementation of IPushProducer
#
# Here's how we handle IPushProducer. We have multiple outstanding
# H2Streams. Each of these exposes an IConsumer interface to the response
# handler that allows it to push data into the H2Stream. The H2Stream then
# writes the data into the H2Connection object.
#
# The H2Connection needs to manage these writes to account for:
#
# - flow control
# - priority
#
# We manage each of these in different ways.
#
# For flow control, we simply use the equivalent of the IPushProducer
# interface. We simply tell the H2Stream: "Hey, you can't send any data
# right now, sorry!". When that stream becomes unblocked, we free it up
# again. This allows the H2Stream to propagate this backpressure up the
# chain.
#
# For priority, we need to keep a backlog of data frames that we can send,
# and interleave them appropriately. This backlog is most sensibly kept in
# the H2Connection object itself. We keep one queue per stream, which is
# where the writes go, and then we have a loop that manages popping these
# streams off in priority order.
#
# Logically then, we go as follows:
#
# 1. Stream calls writeDataToStream(). This causes a DataFrame to be placed
# on the queue for that stream. It also informs the priority
# implementation that this stream is unblocked.
# 2. The _sendPrioritisedData() function spins in a tight loop. Each
# iteration it asks the priority implementation which stream should send
# next, and pops a data frame off that stream's queue. If, after sending
# that frame, there is no data left on that stream's queue, the function
# informs the priority implementation that the stream is blocked.
#
# If all streams are blocked, or if there are no outstanding streams, the
# _sendPrioritisedData function waits to be awoken when more data is ready
# to send.
#
# Note that all of this only applies to *data*. Headers and other control
# frames deliberately skip this processing as they are not subject to flow
# control or priority constraints.
def stopProducing(self):
"""
Stop producing data.
This tells the L{H2Connection} that its consumer has died, so it must
stop producing data for good.
"""
self.connectionLost(ConnectionLost("Producing stopped"))
def pauseProducing(self):
"""
Pause producing data.
Tells the L{H2Connection} that it has produced too much data to process
for the time being, and to stop until resumeProducing() is called.
"""
self._consumerBlocked = Deferred()
def resumeProducing(self):
"""
Resume producing data.
This tells the L{H2Connection} to re-add itself to the main loop and
produce more data for the consumer.
"""
if self._consumerBlocked is not None:
d = self._consumerBlocked
self._consumerBlocked = None
d.callback(None)
def _sendPrioritisedData(self, *args):
"""
The data sending loop. This function repeatedly calls itself, either
from L{Deferred}s or from
L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
This function sends data on streams according to the rules of HTTP/2
priority. It ensures that the data from each stream is interleved
according to the priority signalled by the client, making sure that the
connection is used with maximal efficiency.
This function will execute if data is available: if all data is
exhausted, the function will place a deferred onto the L{H2Connection}
object and wait until it is called to resume executing.
"""
# If producing has stopped, we're done. Don't reschedule ourselves
if not self._stillProducing:
return
stream = None
while stream is None:
try:
stream = next(self.priority)
except priority.DeadlockError:
# All streams are currently blocked or not progressing. Wait
# until a new one becomes available.
assert self._sendingDeferred is None
self._sendingDeferred = Deferred()
self._sendingDeferred.addCallback(self._sendPrioritisedData)
return
# Wait behind the transport.
if self._consumerBlocked is not None:
self._consumerBlocked.addCallback(self._sendPrioritisedData)
return
self.resetTimeout()
remainingWindow = self.conn.local_flow_control_window(stream)
frameData = self._outboundStreamQueues[stream].popleft()
maxFrameSize = min(self.conn.max_outbound_frame_size, remainingWindow)
if frameData is _END_STREAM_SENTINEL:
# There's no error handling here even though this can throw
# ProtocolError because we really shouldn't encounter this problem.
# If we do, that's a nasty bug.
self.conn.end_stream(stream)
self.transport.write(self.conn.data_to_send())
# Clean up the stream
self._requestDone(stream)
else:
# Respect the max frame size.
if len(frameData) > maxFrameSize:
excessData = frameData[maxFrameSize:]
frameData = frameData[:maxFrameSize]
self._outboundStreamQueues[stream].appendleft(excessData)
# There's deliberately no error handling here, because this just
# absolutely should not happen.
# If for whatever reason the max frame length is zero and so we
# have no frame data to send, don't send any.
if frameData:
self.conn.send_data(stream, frameData)
self.transport.write(self.conn.data_to_send())
# If there's no data left, this stream is now blocked.
if not self._outboundStreamQueues[stream]:
self.priority.block(stream)
# Also, if the stream's flow control window is exhausted, tell it
# to stop.
if self.remainingOutboundWindow(stream) <= 0:
self.streams[stream].flowControlBlocked()
self._reactor.callLater(0, self._sendPrioritisedData)
# Internal functions.
def _requestReceived(self, event):
"""
Internal handler for when a request has been received.
@param event: The Hyper-h2 event that encodes information about the
received request.
@type event: L{h2.events.RequestReceived}
"""
stream = H2Stream(
event.stream_id,
self, event.headers,
self.requestFactory,
self.site,
self.factory
)
self.streams[event.stream_id] = stream
self._streamCleanupCallbacks[event.stream_id] = Deferred()
self._outboundStreamQueues[event.stream_id] = deque()
# Add the stream to the priority tree but immediately block it.
try:
self.priority.insert_stream(event.stream_id)
except priority.DuplicateStreamError:
# Stream already in the tree. This can happen if we received a
# PRIORITY frame before a HEADERS frame. Just move on: we set the
# stream up properly in _handlePriorityUpdate.
pass
else:
self.priority.block(event.stream_id)
def _requestDataReceived(self, event):
"""
Internal handler for when a chunk of data is received for a given
request.
@param event: The Hyper-h2 event that encodes information about the
received data.
@type event: L{h2.events.DataReceived}
"""
stream = self.streams[event.stream_id]
stream.receiveDataChunk(event.data, event.flow_controlled_length)
def _requestEnded(self, event):
"""
Internal handler for when a request is complete, and we expect no
further data for that request.
@param event: The Hyper-h2 event that encodes information about the
completed stream.
@type event: L{h2.events.StreamEnded}
"""
stream = self.streams[event.stream_id]
stream.requestComplete()
def _requestAborted(self, event):
"""
Internal handler for when a request is aborted by a remote peer.
@param event: The Hyper-h2 event that encodes information about the
reset stream.
@type event: L{h2.events.StreamReset}
"""
stream = self.streams[event.stream_id]
stream.connectionLost(
ConnectionLost("Stream reset with code %s" % event.error_code)
)
self._requestDone(event.stream_id)
def _handlePriorityUpdate(self, event):
"""
Internal handler for when a stream priority is updated.
@param event: The Hyper-h2 event that encodes information about the
stream reprioritization.
@type event: L{h2.events.PriorityUpdated}
"""
try:
self.priority.reprioritize(
stream_id=event.stream_id,
depends_on=event.depends_on or None,
weight=event.weight,
exclusive=event.exclusive,
)
except priority.MissingStreamError:
# A PRIORITY frame arrived before the HEADERS frame that would
# trigger us to insert the stream into the tree. That's fine: we
# can create the stream here and mark it as blocked.
self.priority.insert_stream(
stream_id=event.stream_id,
depends_on=event.depends_on or None,
weight=event.weight,
exclusive=event.exclusive,
)
self.priority.block(event.stream_id)
def writeHeaders(self, version, code, reason, headers, streamID):
"""
Called by L{twisted.web.http.Request} objects to write a complete set
of HTTP headers to a stream.
@param version: The HTTP version in use. Unused in HTTP/2.
@type version: L{bytes}
@param code: The HTTP status code to write.
@type code: L{bytes}
@param reason: The HTTP reason phrase to write. Unused in HTTP/2.
@type reason: L{bytes}
@param headers: The headers to write to the stream.
@type headers: L{twisted.web.http_headers.Headers}
@param streamID: The ID of the stream to write the headers to.
@type streamID: L{int}
"""
headers.insert(0, (b':status', code))
try:
self.conn.send_headers(streamID, headers)
except h2.exceptions.StreamClosedError:
# Stream was closed by the client at some point. We need to not
# explode here: just swallow the error. That's what write() does
# when a connection is lost, so that's what we do too.
return
else:
self.transport.write(self.conn.data_to_send())
def writeDataToStream(self, streamID, data):
"""
May be called by L{H2Stream} objects to write response data to a given
stream. Writes a single data frame.
@param streamID: The ID of the stream to write the data to.
@type streamID: L{int}
@param data: The data chunk to write to the stream.
@type data: L{bytes}
"""
self._outboundStreamQueues[streamID].append(data)
# There's obviously no point unblocking this stream and the sending
# loop if the data can't actually be sent, so confirm that there's
# some room to send data.
if self.conn.local_flow_control_window(streamID) > 0:
self.priority.unblock(streamID)
if self._sendingDeferred is not None:
d = self._sendingDeferred
self._sendingDeferred = None
d.callback(streamID)
if self.remainingOutboundWindow(streamID) <= 0:
self.streams[streamID].flowControlBlocked()
def endRequest(self, streamID):
"""
Called by L{H2Stream} objects to signal completion of a response.
@param streamID: The ID of the stream to write the data to.
@type streamID: L{int}
"""
self._outboundStreamQueues[streamID].append(_END_STREAM_SENTINEL)
self.priority.unblock(streamID)
if self._sendingDeferred is not None:
d = self._sendingDeferred
self._sendingDeferred = None
d.callback(streamID)
def abortRequest(self, streamID):
"""
Called by L{H2Stream} objects to request early termination of a stream.
This emits a RstStream frame and then removes all stream state.
@param streamID: The ID of the stream to write the data to.
@type streamID: L{int}
"""
self.conn.reset_stream(streamID)
self.transport.write(self.conn.data_to_send())
self._requestDone(streamID)
def _requestDone(self, streamID):
"""
Called internally by the data sending loop to clean up state that was
being used for the stream. Called when the stream is complete.
@param streamID: The ID of the stream to clean up state for.
@type streamID: L{int}
"""
del self._outboundStreamQueues[streamID]
self.priority.remove_stream(streamID)
del self.streams[streamID]
cleanupCallback = self._streamCleanupCallbacks.pop(streamID)
cleanupCallback.callback(streamID)
def remainingOutboundWindow(self, streamID):
"""
Called to determine how much room is left in the send window for a
given stream. Allows us to handle blocking and unblocking producers.
@param streamID: The ID of the stream whose flow control window we'll
check.
@type streamID: L{int}
@return: The amount of room remaining in the send window for the given
stream, including the data queued to be sent.
@rtype: L{int}
"""
# TODO: This involves a fair bit of looping and computation for
# something that is called a lot. Consider caching values somewhere.
windowSize = self.conn.local_flow_control_window(streamID)
sendQueue = self._outboundStreamQueues[streamID]
alreadyConsumed = sum(
len(chunk) for chunk in sendQueue
if chunk is not _END_STREAM_SENTINEL
)
return windowSize - alreadyConsumed
def _handleWindowUpdate(self, event):
"""
Manage flow control windows.
Streams that are blocked on flow control will register themselves with
the connection. This will fire deferreds that wake those streams up and
allow them to continue processing.
@param event: The Hyper-h2 event that encodes information about the
flow control window change.
@type event: L{h2.events.WindowUpdated}
"""
streamID = event.stream_id
if streamID:
if not self._streamIsActive(streamID):
# We may have already cleaned up our stream state, making this
# a late WINDOW_UPDATE frame. That's fine: the update is
# unnecessary but benign. We'll ignore it.
return
# If we haven't got any data to send, don't unblock the stream. If
# we do, we'll eventually get an exception inside the
# _sendPrioritisedData loop some time later.
if self._outboundStreamQueues.get(streamID):
self.priority.unblock(streamID)
self.streams[streamID].windowUpdated()
else:
# Update strictly applies to all streams.
for stream in self.streams.values():
stream.windowUpdated()
# If we still have data to send for this stream, unblock it.
if self._outboundStreamQueues.get(stream.streamID):
self.priority.unblock(stream.streamID)
def getPeer(self):
"""
Get the remote address of this connection.
Treat this method with caution. It is the unfortunate result of the
CGI and Jabber standards, but should not be considered reliable for
the usual host of reasons; port forwarding, proxying, firewalls, IP
masquerading, etc.
@return: An L{IAddress} provider.
"""
return self.transport.getPeer()
def getHost(self):
"""
Similar to getPeer, but returns an address describing this side of the
connection.
@return: An L{IAddress} provider.
"""
return self.transport.getHost()
def openStreamWindow(self, streamID, increment):
"""
Open the stream window by a given increment.
@param streamID: The ID of the stream whose window needs to be opened.
@type streamID: L{int}
@param increment: The amount by which the stream window must be
incremented.
@type increment: L{int}
"""
self.conn.acknowledge_received_data(increment, streamID)
data = self.conn.data_to_send()
if data:
self.transport.write(data)
def _isSecure(self):
"""
Returns L{True} if this channel is using a secure transport.
@returns: L{True} if this channel is secure.
@rtype: L{bool}
"""
# A channel is secure if its transport is ISSLTransport.
return ISSLTransport(self.transport, None) is not None
def _send100Continue(self, streamID):
"""
Sends a 100 Continue response, used to signal to clients that further
processing will be performed.
@param streamID: The ID of the stream that needs the 100 Continue
response
@type streamID: L{int}
"""
headers = [(b':status', b'100')]
self.conn.send_headers(headers=headers, stream_id=streamID)
self.transport.write(self.conn.data_to_send())
def _respondToBadRequestAndDisconnect(self, streamID):
"""
This is a quick and dirty way of responding to bad requests.
As described by HTTP standard we should be patient and accept the
whole request from the client before sending a polite bad request
response, even in the case when clients send tons of data.
Unlike in the HTTP/1.1 case, this does not actually disconnect the
underlying transport: there's no need. This instead just sends a 400
response and terminates the stream.
@param streamID: The ID of the stream that needs the 100 Continue
response
@type streamID: L{int}
"""
headers = [(b':status', b'400')]
self.conn.send_headers(
headers=headers,
stream_id=streamID,
end_stream=True
)
self.transport.write(self.conn.data_to_send())
stream = self.streams[streamID]
stream.connectionLost(ConnectionLost("Invalid request"))
self._requestDone(streamID)
def _streamIsActive(self, streamID):
"""
Checks whether Twisted has still got state for a given stream and so
can process events for that stream.
@param streamID: The ID of the stream that needs processing.
@type streamID: L{int}
@return: Whether the stream still has state allocated.
@rtype: L{bool}
"""
return streamID in self.streams
@implementer(ITransport, IConsumer, IPushProducer)
class H2Stream(object):
"""
A class representing a single HTTP/2 stream.
This class works hand-in-hand with L{H2Connection}. It acts to provide an
implementation of L{ITransport}, L{IConsumer}, and L{IProducer} that work
for a single HTTP/2 connection, while tightly cleaving to the interface
provided by those interfaces. It does this by having a tight coupling to
L{H2Connection}, which allows associating many of the functions of
L{ITransport}, L{IConsumer}, and L{IProducer} to objects on a
stream-specific level.
@ivar streamID: The numerical stream ID that this object corresponds to.
@type streamID: L{int}
@ivar producing: Whether this stream is currently allowed to produce data
to its consumer.
@type producing: L{bool}
@ivar command: The HTTP verb used on the request.
@type command: L{unicode}
@ivar path: The HTTP path used on the request.
@type path: L{unicode}
@ivar producer: The object producing the response, if any.
@type producer: L{IProducer}
@ivar site: The L{twisted.web.server.Site} object this stream belongs to,
if any.
@type site: L{twisted.web.server.Site}
@ivar factory: The L{twisted.web.http.HTTPFactory} object that constructed
this stream's parent connection.
@type factory: L{twisted.web.http.HTTPFactory}
@ivar _producerProducing: Whether the producer stored in producer is
currently producing data.
@type _producerProducing: L{bool}
@ivar _inboundDataBuffer: Any data that has been received from the network
but has not yet been received by the consumer.
@type _inboundDataBuffer: A L{collections.deque} containing L{bytes}
@ivar _conn: A reference to the connection this stream belongs to.
@type _conn: L{H2Connection}
@ivar _request: A request object that this stream corresponds to.
@type _request: L{twisted.web.iweb.IRequest}
@ivar _buffer: A buffer containing data produced by the producer that could
not be sent on the network at this time.
@type _buffer: L{io.BytesIO}
"""
# We need a transport property for t.w.h.Request, but HTTP/2 doesn't want
# to expose it. So we just set it to None.
transport = None
def __init__(self, streamID, connection, headers,
requestFactory, site, factory):
"""
Initialize this HTTP/2 stream.
@param streamID: The numerical stream ID that this object corresponds
to.
@type streamID: L{int}
@param connection: The HTTP/2 connection this stream belongs to.
@type connection: L{H2Connection}
@param headers: The HTTP/2 request headers.
@type headers: A L{list} of L{tuple}s of header name and header value,
both as L{bytes}.
@param requestFactory: A function that builds appropriate request
request objects.
@type requestFactory: A callable that returns a
L{twisted.web.iweb.IRequest}.
@param site: The L{twisted.web.server.Site} object this stream belongs
to, if any.
@type site: L{twisted.web.server.Site}
@param factory: The L{twisted.web.http.HTTPFactory} object that
constructed this stream's parent connection.
@type factory: L{twisted.web.http.HTTPFactory}
"""
self.streamID = streamID
self.site = site
self.factory = factory
self.producing = True
self.command = None
self.path = None
self.producer = None
self._producerProducing = False
self._hasStreamingProducer = None
self._inboundDataBuffer = deque()
self._conn = connection
self._request = requestFactory(self, queued=False)
self._buffer = io.BytesIO()
self._convertHeaders(headers)
def _convertHeaders(self, headers):
"""
This method converts the HTTP/2 header set into something that looks
like HTTP/1.1. In particular, it strips the 'special' headers and adds
a Host: header.
@param headers: The HTTP/2 header set.
@type headers: A L{list} of L{tuple}s of header name and header value,
both as L{bytes}.
"""
gotLength = False
for header in headers:
if not header[0].startswith(b':'):
gotLength = (
_addHeaderToRequest(self._request, header) or gotLength
)
elif header[0] == b':method':
self.command = header[1]
elif header[0] == b':path':
self.path = header[1]
elif header[0] == b':authority':
# This is essentially the Host: header from HTTP/1.1
_addHeaderToRequest(self._request, (b'host', header[1]))
if not gotLength:
if self.command in (b'GET', b'HEAD'):
self._request.gotLength(0)
else:
self._request.gotLength(None)
self._request.parseCookies()
expectContinue = self._request.requestHeaders.getRawHeaders(b'expect')
if expectContinue and expectContinue[0].lower() == b'100-continue':
self._send100Continue()
# Methods called by the H2Connection
def receiveDataChunk(self, data, flowControlledLength):
"""
Called when the connection has received a chunk of data from the
underlying transport. If the stream has been registered with a
consumer, and is currently able to push data, immediately passes it
through. Otherwise, buffers the chunk until we can start producing.
@param data: The chunk of data that was received.
@type data: L{bytes}
@param flowControlledLength: The total flow controlled length of this
chunk, which is used when we want to re-open the window. May be
different to C{len(data)}.
@type flowControlledLength: L{int}
"""
if not self.producing:
# Buffer data.
self._inboundDataBuffer.append((data, flowControlledLength))
else:
self._request.handleContentChunk(data)
self._conn.openStreamWindow(self.streamID, flowControlledLength)
def requestComplete(self):
"""
Called by the L{H2Connection} when the all data for a request has been
received. Currently, with the legacy L{twisted.web.http.Request}
object, just calls requestReceived unless the producer wants us to be
quiet.
"""
if self.producing:
self._request.requestReceived(self.command, self.path, b'HTTP/2')
else:
self._inboundDataBuffer.append((_END_STREAM_SENTINEL, None))
def connectionLost(self, reason):
"""
Called by the L{H2Connection} when a connection is lost or a stream is
reset.
@param reason: The reason the connection was lost.
@type reason: L{str}
"""
self._request.connectionLost(reason)
def windowUpdated(self):
"""
Called by the L{H2Connection} when this stream's flow control window
has been opened.
"""
# If we don't have a producer, we have no-one to tell.
if not self.producer:
return
# If we're not blocked on flow control, we don't care.
if self._producerProducing:
return
# We check whether the stream's flow control window is actually above
# 0, and then, if a producer is registered and we still have space in
# the window, we unblock it.
remainingWindow = self._conn.remainingOutboundWindow(self.streamID)
if not remainingWindow > 0:
return
# We have a producer and space in the window, so that producer can
# start producing again!
self._producerProducing = True
self.producer.resumeProducing()
def flowControlBlocked(self):
"""
Called by the L{H2Connection} when this stream's flow control window
has been exhausted.
"""
if not self.producer:
return
if self._producerProducing:
self.producer.pauseProducing()
self._producerProducing = False
# Methods called by the consumer (usually an IRequest).
def writeHeaders(self, version, code, reason, headers):
"""
Called by the consumer to write headers to the stream.
@param version: The HTTP version.
@type version: L{bytes}
@param code: The status code.
@type code: L{int}
@param reason: The reason phrase. Ignored in HTTP/2.
@type reason: L{bytes}
@param headers: The HTTP response headers.
@type: Any iterable of two-tuples of L{bytes}, representing header
names and header values.
"""
self._conn.writeHeaders(version, code, reason, headers, self.streamID)
def requestDone(self, request):
"""
Called by a consumer to clean up whatever permanent state is in use.
@param request: The request calling the method.
@type request: L{twisted.web.iweb.IRequest}
"""
self._conn.endRequest(self.streamID)
def _send100Continue(self):
"""
Sends a 100 Continue response, used to signal to clients that further
processing will be performed.
"""
self._conn._send100Continue(self.streamID)
def _respondToBadRequestAndDisconnect(self):
"""
This is a quick and dirty way of responding to bad requests.
As described by HTTP standard we should be patient and accept the
whole request from the client before sending a polite bad request
response, even in the case when clients send tons of data.
Unlike in the HTTP/1.1 case, this does not actually disconnect the
underlying transport: there's no need. This instead just sends a 400
response and terminates the stream.
"""
self._conn._respondToBadRequestAndDisconnect(self.streamID)
# Implementation: ITransport
def write(self, data):
"""
Write a single chunk of data into a data frame.
@param data: The data chunk to send.
@type data: L{bytes}
"""
self._conn.writeDataToStream(self.streamID, data)
return
def writeSequence(self, iovec):
"""
Write a sequence of chunks of data into data frames.
@param iovec: A sequence of chunks to send.
@type iovec: An iterable of L{bytes} chunks.
"""
for chunk in iovec:
self.write(chunk)
def loseConnection(self):
"""
Close the connection after writing all pending data.
"""
self._conn.endRequest(self.streamID)
def abortConnection(self):
"""
Forcefully abort the connection by sending a RstStream frame.
"""
self._conn.abortRequest(self.streamID)
def getPeer(self):
"""
Get information about the peer.
"""
return self._conn.getPeer()
def getHost(self):
"""
Similar to getPeer, but for this side of the connection.
"""
return self._conn.getHost()
def isSecure(self):
"""
Returns L{True} if this channel is using a secure transport.
@returns: L{True} if this channel is secure.
@rtype: L{bool}
"""
return self._conn._isSecure()
# Implementation: IConsumer
def registerProducer(self, producer, streaming):
"""
Register to receive data from a producer.
This sets self to be a consumer for a producer. When this object runs
out of data (as when a send(2) call on a socket succeeds in moving the
last data from a userspace buffer into a kernelspace buffer), it will
ask the producer to resumeProducing().
For L{IPullProducer} providers, C{resumeProducing} will be called once
each time data is required.
For L{IPushProducer} providers, C{pauseProducing} will be called
whenever the write buffer fills up and C{resumeProducing} will only be
called when it empties.
@param producer: The producer to register.
@type producer: L{IProducer} provider
@param streaming: L{True} if C{producer} provides L{IPushProducer},
L{False} if C{producer} provides L{IPullProducer}.
@type streaming: L{bool}
@raise RuntimeError: If a producer is already registered.
@return: L{None}
"""
if self.producer:
raise ValueError(
"registering producer %s before previous one (%s) was "
"unregistered" % (producer, self.producer))
if not streaming:
self.hasStreamingProducer = False
producer = _PullToPush(producer, self)
producer.startStreaming()
else:
self.hasStreamingProducer = True
self.producer = producer
self._producerProducing = True
def unregisterProducer(self):
"""
@see: L{IConsumer.unregisterProducer}
"""
# When the producer is unregistered, we're done.
if self.producer is not None and not self.hasStreamingProducer:
self.producer.stopStreaming()
self._producerProducing = False
self.producer = None
self.hasStreamingProducer = None
# Implementation: IPushProducer
def stopProducing(self):
"""
@see: L{IProducer.stopProducing}
"""
self.producing = False
self.abortConnection()
def pauseProducing(self):
"""
@see: L{IPushProducer.pauseProducing}
"""
self.producing = False
def resumeProducing(self):
"""
@see: L{IPushProducer.resumeProducing}
"""
self.producing = True
consumedLength = 0
while self.producing and self._inboundDataBuffer:
# Allow for pauseProducing to be called in response to a call to
# resumeProducing.
chunk, flowControlledLength = self._inboundDataBuffer.popleft()
if chunk is _END_STREAM_SENTINEL:
self.requestComplete()
else:
consumedLength += flowControlledLength
self._request.handleContentChunk(chunk)
self._conn.openStreamWindow(self.streamID, consumedLength)
def _addHeaderToRequest(request, header):
"""
Add a header tuple to a request header object.
@param request: The request to add the header tuple to.
@type request: L{twisted.web.http.Request}
@param header: The header tuple to add to the request.
@type header: A L{tuple} with two elements, the header name and header
value, both as L{bytes}.
@return: If the header being added was the C{Content-Length} header.
@rtype: L{bool}
"""
requestHeaders = request.requestHeaders
name, value = header
values = requestHeaders.getRawHeaders(name)
if values is not None:
values.append(value)
else:
requestHeaders.setRawHeaders(name, [value])
if name == b'content-length':
request.gotLength(int(value))
return True
return False
| [
"teadone@naver.com"
] | teadone@naver.com |
8d4588530f69c619168a4cc1e6f9fb07ba1e6326 | d2c4934325f5ddd567963e7bd2bdc0673f92bc40 | /tests/artificial/transf_RelativeDifference/trend_Lag1Trend/cycle_12/ar_12/test_artificial_128_RelativeDifference_Lag1Trend_12_12_20.py | b92931e266c853cfe294b5ace5bc7d11ca7edc8c | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jmabry/pyaf | 797acdd585842474ff4ae1d9db5606877252d9b8 | afbc15a851a2445a7824bf255af612dc429265af | refs/heads/master | 2020-03-20T02:14:12.597970 | 2018-12-17T22:08:11 | 2018-12-17T22:08:11 | 137,104,552 | 0 | 0 | BSD-3-Clause | 2018-12-17T22:08:12 | 2018-06-12T17:15:43 | Python | UTF-8 | Python | false | false | 280 | py | import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order = 12); | [
"antoine.carme@laposte.net"
] | antoine.carme@laposte.net |
89474e153defaaa9938f24de4429e92defcd0542 | d723b9c2dcfc9e3366928fd0ea18ee5ee19c2b3c | /backend/apps/detections/upload_sets.py | 140c2d9bcfbee0781d15cc18a2aab00c879d9188 | [] | no_license | skarzi/yb_hackathon_2019 | ff8266e89ae6fa74d57c61e4117d6fc176dba825 | 83c3d96795f6b14f97683ad5c998579adb3faaf4 | refs/heads/master | 2020-09-11T01:34:55.206979 | 2020-07-19T07:50:16 | 2020-07-19T07:50:16 | 221,895,345 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 219 | py | from flask import current_app
from flask_uploads import (
IMAGES,
UploadSet,
configure_uploads,
)
detections = UploadSet(name='detections', extensions=IMAGES)
configure_uploads(current_app, (detections,))
| [
"skarzynski_lukasz@protonmail.com"
] | skarzynski_lukasz@protonmail.com |
a04bc47a13938f0f6f6d24f671bdcad4533f47f9 | 362efa5644c13e9a370e4d6ce4730833358e0ff0 | /MyWebsite/AGR/AGR/settings.py | 8bcd4ef8e2ed8fe4edddf75d747689f7b2af9f82 | [] | no_license | ISS-IS-IRSPM-AGR/-IRSPM | f07d7133d3005fbb14e784d8a2e719613f17dc0a | 556fc45cb31ddf56dd557305a603a514eaab672c | refs/heads/master | 2023-04-01T03:11:23.162711 | 2021-03-14T16:24:38 | 2021-03-14T16:24:38 | 347,680,073 | 0 | 1 | null | 2021-03-14T16:21:41 | 2021-03-14T15:51:06 | JavaScript | UTF-8 | Python | false | false | 3,153 | py | """
Django settings for AGR project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'whfxmu35o6%2)9z71og9*efq^7++so1%@i-nwekkj2d8&fi=$t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'AGRApi.apps.ApiConfig',
'rest_framework',
'AGRFrontend.apps.FrontendConfig'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'AGR.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'AGR.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/AGRFrontend/static/'
| [
"21048103+antoniadevina@users.noreply.github.com"
] | 21048103+antoniadevina@users.noreply.github.com |
33bb22d6d151a3b8a644cd786b43bd9822fdbecd | 8f02ed34ca9d4c82cf3b6305792e0b43cb032456 | /motor_descuento/test/test_articulos.py | e8008d54a3a3d2ce86cabe415c54fdde4a89b02c | [
"Apache-2.0"
] | permissive | angelquin1986/tiptopDescuentos | 977569c15a9e5d3632177f4f7ce39c156931be3a | 6bca61d3142b75eee0e72f3932aeabcf1457526a | refs/heads/master | 2023-07-30T02:09:35.119053 | 2020-06-19T17:11:47 | 2020-06-19T17:11:47 | 272,595,003 | 0 | 0 | Apache-2.0 | 2021-09-22T19:15:28 | 2020-06-16T02:53:13 | TypeScript | UTF-8 | Python | false | false | 1,509 | py | """
@author aquingaluisa
"""
# Cargamos el módulo unittest
import os
import random
import pytest
from django.test import TestCase
# Creamos una clase heredando de TestCase
from motor_descuento.logica_negocio import ln_articulo as ln_articulo, ln_descuento
from motor_descuento.modelo.modelo_productos import Product
from motor_descuento.test import util_test
class TestArticulos(TestCase):
fixtures = ['db.json', 'descuento.json']
def setUp(self):
util_test.product();
util_test.stok_items()
# Creamos una prueba para probar un valor inicial
@pytest.mark.django_db
def test_crear_articulos(self):
categorias_list = list(ln_articulo.consultar_categoria_id_list())
producto_list = list(ln_articulo.consultar_product_id_list())
stok_list = list(ln_articulo.consultar_stock_id_list())
discount_list = list(ln_descuento.obtener_descuento_list())
print(categorias_list)
print(producto_list)
print(stok_list)
print(discount_list[0].json_data)
brand_id_list = [1, 2, 3, 4, 5]
# product_list = []
# is_create = False
# for numero in [10000]:
# product = Product(name='Producto_' + str(numero), description='Producto_' + str(numero), tax_rate=12)
# product.brand_id = random.choice(brand_id_list)
# product_list.append(product)
# is_create = ln_articulo.crear_producto_list(product_list)
# self.assertEqual(True, is_create)
| [
"aquingaluisa@galapagosislands.com"
] | aquingaluisa@galapagosislands.com |
71402662a43efd9f3ece9bfc6b5fb824add27987 | c676bf5e77ba43639faa6f17646245f9d55d8687 | /tests/ut/python/ops/test_tuple_slice.py | ea5112995c06203210d7c6ca569e2949187c6f26 | [
"Apache-2.0",
"BSD-3-Clause-Open-MPI",
"MPL-2.0-no-copyleft-exception",
"LGPL-2.1-only",
"BSD-3-Clause",
"MPL-2.0",
"MPL-1.0",
"Libpng",
"AGPL-3.0-only",
"MPL-1.1",
"LicenseRef-scancode-proprietary-license",
"MIT",
"IJG",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Z... | permissive | zhengnengjin/mindspore | 1e2644e311f54a8bd17010180198a46499e9c88f | 544b859bb5f46611882749088b44c5aebae0fba1 | refs/heads/master | 2022-05-13T05:34:21.658335 | 2020-04-28T06:39:53 | 2020-04-28T06:39:53 | 259,522,589 | 2 | 0 | Apache-2.0 | 2020-04-28T03:35:33 | 2020-04-28T03:35:33 | null | UTF-8 | Python | false | false | 4,665 | py | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" test_tuple_slice """
import numpy as np
import pytest
from mindspore import Tensor
from mindspore.nn import Cell
import mindspore.ops.operations as P
from ....mindspore_test_framework.mindspore_test import mindspore_test
from ....mindspore_test_framework.pipeline.forward.compile_forward \
import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
from ....mindspore_test_framework.pipeline.forward.verify_exception \
import pipeline_for_verify_exception_for_case_by_case_config
class NetWork_1(Cell):
""" NetWork_1 definition """
def __init__(self):
super(NetWork_1, self).__init__()
self.addN = P.AddN()
def construct(self, tensor_tuple):
tensor_tuple_slice0 = tensor_tuple[:]
tensor_tuple_slice1 = tensor_tuple[:3]
tensor_tuple_slice2 = tensor_tuple[1:]
tensor_tuple_slice3 = tensor_tuple[2:5:1]
sum0 = self.addN(tensor_tuple_slice0)
sum1 = self.addN(tensor_tuple_slice1)
sum2 = self.addN(tensor_tuple_slice2)
sum3 = self.addN(tensor_tuple_slice3)
ret = sum0 + sum1 + sum2 + sum3
return ret
class NetWork_2(Cell):
""" NetWork_2 definition """
def __init__(self):
super(NetWork_2, self).__init__()
self.addN = P.AddN()
def construct(self, tensor_tuple):
tensor_tuple_slice0 = tensor_tuple[::-1]
tensor_tuple_slice1 = tensor_tuple[-1::-1]
tensor_tuple_slice2 = tensor_tuple[:-4:-1]
tensor_tuple_slice3 = tensor_tuple[-6:3]
tensor_tuple_slice4 = tensor_tuple[-1:-6:-2]
sum0 = self.addN(tensor_tuple_slice0)
sum1 = self.addN(tensor_tuple_slice1)
sum2 = self.addN(tensor_tuple_slice2)
sum3 = self.addN(tensor_tuple_slice3)
sum4 = self.addN(tensor_tuple_slice4)
ret = sum0 + sum1 + sum2 + sum3 + sum4
return ret
class NetWork_3(Cell):
""" NetWork_3 definition """
def __init__(self):
super(NetWork_3, self).__init__()
self.addN = P.AddN()
def construct(self, tensor_tuple, start, stop, step=1):
tensor_tuple_slice0 = tensor_tuple[start:stop:step]
res = self.addN(tensor_tuple_slice0)
return res
test_cases = [
('SlicePositive', {
'block': NetWork_1(),
'desc_inputs': [(Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.zeros([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.zeros([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)))],
}),
('SliceNegative', {
'block': NetWork_2(),
'desc_inputs': [(Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.zeros([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.zeros([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)))],
}),
]
test_cases_for_verify_exception = [
('SliceStartCross', {
'block': (NetWork_3(), {'exception': RuntimeError}),
'desc_inputs': [*(Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.zeros([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)))],
}),
('SliceStepZero', {
'block': (NetWork_3(), {'exception': RuntimeError}),
'desc_inputs': [*(Tensor(np.ones([2, 3, 4], np.int32)),
Tensor(np.zeros([2, 3, 4], np.int32)),
Tensor(np.ones([2, 3, 4], np.int32)))],
}),
]
@mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
def test_compile():
return test_cases
@mindspore_test(pipeline_for_verify_exception_for_case_by_case_config)
def test_check_exception():
return test_cases_for_verify_exception
| [
"leon.wanghui@huawei.com"
] | leon.wanghui@huawei.com |
4ac983d36e1373bef3ae2040efb427f6810916b4 | 83e85a05d87d784d5beffe8d3c7c709bda9ffe6b | /py_src/samoa/request/replication_state.py | f1edef830b6e914167e2526762a1c227ed5af975 | [] | no_license | jgraettinger/samoa | 42c3015e525f3fdad61725ff4be569e758b32cc9 | 36d17dddeea0cc28a223e839ebf3cfb0bf3f7c07 | refs/heads/master | 2020-04-09T10:11:22.750684 | 2011-10-22T22:32:23 | 2011-10-22T22:32:23 | 533,368 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 38 | py | from _request import ReplicationState
| [
"johng@boomer.(none)"
] | johng@boomer.(none) |
f63c373acfcbf528968315471e17ac98b2ea26b0 | 595471f4acc7c6db2b414019e069bcb510f24edc | /blog/migrations/0001_initial.py | 41c9e2d8887c36b9e654ce6c7e8239d8ee358c7c | [] | no_license | UshieChris/Blog-PROJECT | 9ffcbde536283443e6743d8b729691d18e4e1432 | 3bd751c49f95101579a9d6d0dc59c5f730ad1ec6 | refs/heads/main | 2023-03-30T03:39:48.214184 | 2021-04-09T16:29:01 | 2021-04-09T16:29:01 | 356,331,503 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 785 | py | # Generated by Django 3.0.5 on 2020-12-18 10:44
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='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('body', models.TextField()),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"chrisushie301@gmail.com"
] | chrisushie301@gmail.com |
f3b980f098f1f78d08ed82f4a62c12949fb78bde | 5c3fcfd1c30036154af34de9fbf11b77ebd31777 | /9444/ass1/hw1/src/part3.py | 05bd53f4097cb69ca9688d6c2d276e110cb6ed30 | [] | no_license | Skylerliutian/UNSW_19T3 | d5fc13a744aa6193c904404b9ef37010e89261a0 | cdc6324b5622a7326869f58c0cc53dd9976f22cb | refs/heads/master | 2022-04-16T13:37:43.400815 | 2020-03-27T09:46:43 | 2020-03-27T09:46:43 | 250,228,085 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,778 | py | #!/usr/bin/env python3
"""
part3.py
UNSW COMP9444 Neural Networks and Deep Learning
ONLY COMPLETE METHODS AND CLASSES MARKED "TODO".
DO NOT MODIFY IMPORTS. DO NOT ADD EXTRA FUNCTIONS.
DO NOT MODIFY EXISTING FUNCTION SIGNATURES.
DO NOT IMPORT ADDITIONAL LIBRARIES.
DOING SO MAY CAUSE YOUR CODE TO FAIL AUTOMATED TESTING.
"""
import torch
from torchvision import datasets, transforms
from torch import nn, optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
class Linear(nn.Module):
"""
DO NOT MODIFY
Linear (10) -> ReLU -> LogSoftmax
"""
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 10)
def forward(self, x):
x = x.view(x.shape[0], -1) # make sure inputs are flattened
x = F.relu(self.fc1(x))
x = F.log_softmax(x, dim=1) # preserve batch dim
return x
class FeedForward(nn.Module):
"""
TODO: Implement the following network structure
Linear (256) -> ReLU -> Linear(64) -> ReLU -> Linear(10) -> ReLU-> LogSoftmax
"""
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 64)
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.log_softmax(x, dim=1)
return x
class CNN(nn.Module):
"""
TODO: Implement CNN Network structure
conv1 (channels = 10, kernel size= 5, stride = 1) -> Relu -> max pool (kernel size = 2x2) ->
conv2 (channels = 50, kernel size= 5, stride = 1) -> Relu -> max pool (kernel size = 2x2) ->
Linear (256) -> Relu -> Linear (10) -> LogSoftmax
Hint: You will need to reshape outputs from the last conv layer prior to feeding them into
the linear layers.
"""
def __init__(self):
super().__init__()
# in_channels = 1 gray_scale
self.conv1 = nn.Conv2d(1, 10, 5, 1)
# in_channels = the first conv1 out_channels
self.conv2 = nn.Conv2d(10, 50, 5, 1)
self.fc1 = nn.Linear(50 * 4 * 4, 256)
self.fc2 = nn.Linear(256, 10)
self.max_pool = nn.MaxPool2d((2, 2))
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, (2, 2))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, (2, 2))
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = F.log_softmax(x, dim=1)
return x
class NNModel:
def __init__(self, network, learning_rate):
"""
Load Data, initialize a given network structure and set learning rate
DO NOT MODIFY
"""
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Download and load the training data
trainset = datasets.KMNIST(root='./data', train=True, download=True, transform=transform)
self.trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=False)
# Download and load the test data
testset = datasets.KMNIST(root='./data', train=False, download=True, transform=transform)
self.testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)
self.model = network
"""
TODO: Set appropriate loss function such that learning is equivalent to minimizing the
cross entropy loss. Note that we are outputting log-softmax values from our networks,
not raw softmax values, so just using torch.nn.CrossEntropyLoss is incorrect.
Hint: All networks output log-softmax values (i.e. log probabilities or.. likelihoods.).
"""
self.lossfn = nn.NLLLoss()
self.optimizer = optim.Adam(self.model.parameters(), lr=learning_rate)
self.num_train_samples = len(self.trainloader)
self.num_test_samples = len(self.testloader)
def view_batch(self):
"""
TODO: Display first batch of images from trainloader in 8x8 grid
Do not make calls to plt.imshow() here
Return:
1) A float32 numpy array (of dim [28*8, 28*8]), containing a tiling of the batch images,
place the first 8 images on the first row, the second 8 on the second row, and so on
2) An int 8x8 numpy array of labels corresponding to this tiling
"""
train_x, train_y = next(iter(self.trainloader))
x = train_x.view(8, 8, 28, 28).permute(0, 2, 1, 3).reshape(8 * 28, 8 * 28).numpy()
y = train_y.reshape(8, 8)
return x, y.numpy()
# dataiter = iter(self.trainloader)
# images, labels = dataiter.next()
# labels = labels.view(8, 8).numpy()
# image_grid = torch.empty(0)
# for i in range(8):
# img_row = images.numpy()[i * 8:(i + 1) * 8][:][:][:].reshape(8, 28, 28)
# imgs = torch.from_numpy(img_row)
# row = imgs[0]
# for j in range(1, 8):
# row = torch.cat((row, imgs[j]), dim=1)
# image_grid = torch.cat((image_grid, row))
# return image_grid, labels
def train_step(self):
"""
Used for submission tests and may be usefull for debugging
DO NOT MODIFY
"""
self.model.train()
for images, labels in self.trainloader:
log_ps = self.model(images)
loss = self.lossfn(log_ps, labels)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
return
def train_epoch(self):
self.model.train()
for images, labels in self.trainloader:
log_ps = self.model(images)
loss = self.lossfn(log_ps, labels)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
return
def eval(self):
self.model.eval()
accuracy = 0
with torch.no_grad():
for images, labels in self.testloader:
log_ps = self.model(images)
ps = torch.exp(log_ps)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equals.type(torch.FloatTensor))
return accuracy / self.num_test_samples
def plot_result(results, names):
"""
Take a 2D list/array, where row is accuracy at each epoch of training for given model, and
names of each model, and display training curves
"""
for i, r in enumerate(results):
plt.plot(range(len(r)), r, label=names[i])
plt.legend()
plt.title("KMNIST")
plt.xlabel("Epoch")
plt.ylabel("Test accuracy")
plt.grid(True)
plt.tight_layout()
plt.show()
plt.savefig("./part_2_plot.png")
def main():
models = [Linear(), FeedForward(), CNN()] # Change during development
epochs = 10
results = []
# Can comment the below out during development
images, labels = NNModel(Linear(), 0.003).view_batch()
print(labels)
plt.imshow(images, cmap="Greys")
plt.show()
for model in models:
print(f"Training {model.__class__.__name__}...")
m = NNModel(model, 0.003)
accuracies = [0]
for e in range(epochs):
m.train_epoch()
accuracy = m.eval()
print(f"Epoch: {e}/{epochs}.. Test Accuracy: {accuracy}")
accuracies.append(accuracy)
results.append(accuracies)
plot_result(results, [m.__class__.__name__ for m in models])
if __name__ == "__main__":
main()
| [
"skyler151096@gmail.com"
] | skyler151096@gmail.com |
7d4cf1affeb7426291e784ea8cf7e185ac843347 | 3bd3441d6cf42b50ce627db32495004d1e515d63 | /Lesson2/weather_station.py | e9c0349c1930f32517de816f5972e5bfe26f3c5e | [] | no_license | MikalaiMikalalai/head_first_design_patterns | cf8006a3b7d8f531a4872d150a73b5ed77b88a23 | 8792eae3d73e30912f93bf56c7d7b2d844e3d5ec | refs/heads/master | 2021-02-27T02:22:25.057364 | 2020-04-18T02:22:43 | 2020-04-18T02:22:43 | 245,570,150 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,367 | py | ######################################################
# Observer #
######################################################
import abc
import collections
######################################################
# Interfaces #
######################################################
WeatherParams = collections.namedtuple('WeatherParams', ['temperature', 'humidity', 'pressure'])
class Subject(abc.ABC):
@abc.abstractmethod
def register_observer(self, observer):
pass
@abc.abstractmethod
def remove_observer(self, observer):
pass
@abc.abstractmethod
def notify_observers(self):
pass
class Observer(abc.ABC):
@abc.abstractmethod
def update(self):
pass
class DisplayElement(abc.ABC):
@abc.abstractmethod
def display(self, weather_params: WeatherParams):
pass
######################################################
# Implementations #
######################################################
class WeatherData(Subject):
def __init__(self):
self.observers = []
self.__temperature: float
self.__humidity: float
self.__pressure: float
def register_observer(self, observer):
self.observers.append(observer)
def remove_observer(self, observer):
self.observers.remove(observer)
def notify_observers(self):
for obs in self.observers:
obs.update()
def measurements_changed(self):
self.notify_observers()
def set_measurments(self, temperature, humidity, pressure):
self.__temperature = temperature
self.__humidity = humidity
self.__pressure = pressure
self.measurements_changed()
def get_weather_params(self):
return WeatherParams(self.__temperature,
self.__humidity,
self.__pressure)
class CurrentConditionsDisplay(Observer, DisplayElement):
def __init__(self, weather_data):
self.weather_data = weather_data
self.weather_data.register_observer(self)
def update(self):
self.display(self.weather_data.get_weather_params())
def display(self, weather_params):
print(f'Current conditions: {weather_params.temperature}F degrees'
f' and {weather_params.humidity}% humidity')
class StatisticsDisplay(Observer, DisplayElement):
def __init__(self, weather_data):
self.weather_data = weather_data
self.weather_data.register_observer(self)
def update(self):
curr_weather_params = self.weather_data.get_weather_params()
statistics_weather_params = WeatherParams(curr_weather_params.temperature - 2,
curr_weather_params.humidity - 2,
curr_weather_params.pressure - 2)
self.display(statistics_weather_params)
def display(self, weather_params):
print(f'Previous conditions: {weather_params.temperature}F degrees'
f' and {weather_params.humidity}% humidity')
class ForecastDisplay(Observer, DisplayElement):
def __init__(self, weather_data):
self.weather_data = weather_data
self.weather_data.register_observer(self)
def update(self):
curr_weather_params = self.weather_data.get_weather_params()
forecast_weather_params = WeatherParams(curr_weather_params.temperature + 2,
curr_weather_params.humidity + 2,
curr_weather_params.pressure + 2)
self.display(forecast_weather_params)
def display(self, weather_params):
print(f'Tomorrow conditions: {weather_params.temperature}F degrees'
f' and {weather_params.humidity}% humidity')
if __name__ == '__main__':
# Initializing objects
weather_data = WeatherData()
current_display = CurrentConditionsDisplay(weather_data)
statistics_display = StatisticsDisplay(weather_data)
forecast_display = ForecastDisplay(weather_data)
# Starting weather station
weather_data.set_measurments(80, 65, 30.4)
weather_data.set_measurments(82, 70, 29.2)
weather_data.set_measurments(78, 90, 29.2)
| [
"mikalaip@google.com"
] | mikalaip@google.com |
72a405e1ba0507690cafee76a320b4682d94aac3 | b236c7ce962b3f35d70589993833f24eaf3ce948 | /train.py | 1f188e44283e9df69675b39c5da3d4783585b862 | [
"MIT"
] | permissive | Wblossom/Retinaface--without-landm | 499e11ef4fe51c7684c04769e4b4b3f0480f828e | 53c3574c95abab3665ce51de81cbf54b10d97fc9 | refs/heads/main | 2023-01-01T06:39:54.481816 | 2020-10-21T10:48:09 | 2020-10-21T10:48:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,341 | py | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn
import argparse
import torch.utils.data as data
from data import WiderFaceDetection, detection_collate, preproc, cfg_mnet, cfg_re50
from layers.modules import MultiBoxLoss
from layers.functions.prior_box import PriorBox
from tqdm import tqdm
import time
import datetime
import math
from models.retinaface import RetinaFace
parser = argparse.ArgumentParser(description='Retinaface Training')
parser.add_argument('--training_dataset', default='/home/disk/zhy/widerface/label.txt', help='Training dataset directory')
parser.add_argument('--network', default='resnet50', help='Backbone network mobile0.25 or resnet50')
parser.add_argument('--num_workers', default=4, type=int, help='Number of workers used in dataloading')
parser.add_argument('--lr', '--learning-rate', default=1e-4, type=float, help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, help='momentum')
parser.add_argument('--resume_net', default='./weights/Resnet50_Final_1.pth', help='resume net for retraining')
# parser.add_argument('--resume_net', default=None, help='resume net for retraining')
parser.add_argument('--resume_epoch', default=0, type=int, help='resume iter for retraining')
parser.add_argument('--weight_decay', default=5e-4, type=float, help='Weight decay for SGD')
parser.add_argument('--gamma', default=0.1, type=float, help='Gamma update for SGD')
parser.add_argument('--save_folder', default='./weights/', help='Location to save checkpoint models')
args = parser.parse_args()
if not os.path.exists(args.save_folder):
os.mkdir(args.save_folder)
cfg = None
if args.network == "mobile0.25":
cfg = cfg_mnet
elif args.network == "resnet50":
cfg = cfg_re50
rgb_mean = (128)
# rgb_mean = (104, 117, 123) # bgr order
num_classes = 2
img_dim = cfg['image_size']
num_gpu = cfg['ngpu']
batch_size = cfg['batch_size']
max_epoch = cfg['epoch']
gpu_train = cfg['gpu_train']
num_workers = args.num_workers
momentum = args.momentum
weight_decay = args.weight_decay
initial_lr = args.lr
gamma = args.gamma
training_dataset = args.training_dataset
save_folder = args.save_folder
net = RetinaFace(cfg=cfg)
print("Printing net...")
print(net)
if args.resume_net is not None:
print('Loading resume network...')
state_dict = torch.load(args.resume_net)
# create new OrderedDict that does not contain `module.`
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
head = k[:7]
if head == 'module.':
name = k[7:] # remove `module.`
else:
name = k
new_state_dict[name] = v
net.load_state_dict(new_state_dict,strict=False)
if num_gpu > 1 and gpu_train:
net = torch.nn.DataParallel(net).cuda()
else:
net = net.cuda()
cudnn.benchmark = True
# setup optimizer
params = filter(lambda p: p.requires_grad, net.parameters())
# optimizer = optim.SGD(params, lr=initial_lr, momentum=momentum, weight_decay=weight_decay)
optimizer = optim.Adam(params, lr=initial_lr, betas=(0.9, 0.99))
criterion = MultiBoxLoss(num_classes, 0.35, True, 0, True, 7, 0.35, False)
priorbox = PriorBox(cfg, image_size=(img_dim, img_dim))
with torch.no_grad():
priors = priorbox.forward()
priors = priors.cuda()
def train():
net.train()
epoch = 0 + args.resume_epoch
print('Loading Dataset...')
dataset = WiderFaceDetection( training_dataset,preproc(img_dim, rgb_mean))
epoch_size = math.ceil(len(dataset) / batch_size)
max_iter = max_epoch * epoch_size
stepvalues = (cfg['decay1'] * epoch_size, cfg['decay2'] * epoch_size, cfg['decay3'] * epoch_size)
step_index = 0
if args.resume_epoch > 0:
start_iter = args.resume_epoch * epoch_size
else:
start_iter = 0
for iteration in range(start_iter, max_iter):
if iteration % epoch_size == 0:
# create batch iterator
batch_iterator = iter(data.DataLoader(dataset, batch_size, shuffle=True, num_workers=num_workers, collate_fn=detection_collate))
if (epoch % 5 == 0 and epoch > 0) or (epoch % 5 == 0 and epoch > cfg['decay1']):
torch.save(net.state_dict(), save_folder + cfg['name']+ '_epoch_' + str(epoch) + '.pth')
epoch += 1
load_t0 = time.time()
if iteration in stepvalues:
step_index += 1
lr = adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size)
# load train data
images, targets = next(batch_iterator)
# print(targets)
images = images.cuda()
targets = [anno.cuda() for anno in targets]
# forward
out = net(images)
# backprop
optimizer.zero_grad()
# loss_l, loss_c, loss_landm = criterion(out, priors, targets)
loss_l, loss_c = criterion(out, priors, targets)
# loss = cfg['loc_weight'] * loss_l + loss_c + loss_landm
loss = cfg['loc_weight'] * loss_l + loss_c
loss.backward()
optimizer.step()
load_t1 = time.time()
batch_time = load_t1 - load_t0
eta = int(batch_time * (max_iter - iteration))
print('Epoch:{}/{} || Epochiter: {}/{} || Iter: {}/{} || Loc: {:.4f} Cla: {:.4f} || LR: {:.8f} || Batchtime: {:.4f} s || ETA: {}'
.format(epoch, max_epoch, (iteration % epoch_size) + 1,
epoch_size, iteration + 1, max_iter, loss_l.item(), loss_c.item(), lr, batch_time, str(datetime.timedelta(seconds=eta))))
torch.save(net.state_dict(), save_folder + cfg['name'] + '_Final.pth')
# torch.save(net.state_dict(), save_folder + 'Final_Retinaface.pth')
def adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size):
"""Sets the learning rate
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
warmup_epoch = -1
if epoch <= warmup_epoch:
lr = 1e-6 + (initial_lr-1e-6) * iteration / (epoch_size * warmup_epoch)
else:
lr = initial_lr * (gamma ** (step_index))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
if __name__ == '__main__':
train()
| [
"kylin33@outlook.com"
] | kylin33@outlook.com |
4b4a097a95f1da6da6dfa3927d7c83d66941ecdf | d8f0761acc94f9f1c0365e5a1716c9e17c6e4e16 | /scrapers/bs4_selectors/selector.py | cabcd3ea0bed6889945755aac7fe5cf0cdf9cd8c | [] | no_license | lesleyfon/one-time-scrapers | 75ca851107d59b4f2b7cd816b2ae46ecd11d6bc0 | 6ee5443497c9e05924abf5704c16112beb740064 | refs/heads/master | 2023-05-02T12:58:21.693133 | 2021-05-21T13:09:57 | 2021-05-21T13:09:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,990 | py | ##############################
#
# Beautiful Soup cheat sheet
#
# by
#
# Code Monkey King
#
##############################
# Step 1: import packages
import requests
from bs4 import BeautifulSoup
# Step 2: define target URL
url = 'https://podsearch.com/listing/car-talk.html'
# Step 3: make HTTP request to the target URL
response = requests.get(url)
# Step 4: parse entire HTML document
content = BeautifulSoup(response.text, 'lxml')
# Step 5: parse PARENT element conteining needed data
parent = content.find('div', {'class': 'col-md-8 col-sm-12 col-xs-12 pdl0'})
# Step 6: parse CHILD element containing the exact data we need
child = parent.find('span').text
# Step 7: split the target string if needed
data = child.split(': ')[-1]
# Step 8: print data to console
print(data)
#####################################
#
# Useful data extraction techniques
#
#####################################
# extract FIRST data occurence by unique class
description = content.find('p', {'class': 'pre-line'}).text
print('\n', description)
# extract ALL data occurences by unique class
text = [
item.text
for item in
content.find_all('p', {'class': 'pre-line'})
]
print('\n', text)
# reference similar data occurences by index
print('\n', text[0])
print('\n', text[1])
# join list elements into one single string by whatever character
print('\n', '\n joined by new line \n'.join(text))
# reference element by whatever attribute (ID in this case)
button = content.find('button', {'id': 'headerSearchButton'}).text
print(button)
# extract FIRST other but textual node data element, e.g. HREF attribute or whatever
link = content.find('a')['href']
print(link)
# extract ALL other but textual node data elements, e.g. HREF attribute or whatever
links = [
link['href']
for link in
content.find_all('a')
# filter on condition if needed
#if link['href'] == 'https://podsearch.com/listing/rethinking-weight-loss.html'
]
print(links)
| [
"freesoft.for.people@gmail.com"
] | freesoft.for.people@gmail.com |
ea9bdeb9e2025531d7f315d480fb6d55a59df027 | ab36c659808a9c6f7b4dc873fbffd63d4b7a54cc | /functions.py | 0b8ce7451229eecd8741cb36884c4b506c1cb54f | [] | no_license | Mixpap/Ptyxiaki | 697da20d66f48df1adea1961871b3fdc4ac06913 | 6cb2dd1196f2bab275b81d17a35a85044d64b40f | refs/heads/master | 2021-01-22T13:42:16.877514 | 2015-07-28T13:02:45 | 2015-07-28T13:02:45 | 27,761,005 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 30,905 | py | from astropy.io import fits
from astropy import wcs
from astropy.table import Table
import numpy as np
import pywcsgrid2
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.colors import LogNorm
from matplotlib.patches import Rectangle
from mpl_toolkits.axes_grid1.inset_locator import inset_axes,zoomed_inset_axes,mark_inset
from scipy.optimize import curve_fit
from IPython.display import clear_output, display, HTML
#===================Constants==================================================
ab12CO=77. ##Abundancy ratio of 12co to 13co (Schoier et al. 2002 )
ab13CO=8. ##Abundancy ratio of 13co to c18o (Schoier et al. 2002)
ab12CO_H2=8.5e-5 ##Abundancy ratio of 12CO to H2 (Frerking et al. 1982)
ab13CO_H2=1.25e-6 ##Abundancy ratio of 13CO to H2 (Moore et al. 2007)
ab18CO_H2=1.7e-7 ##Abundancy ratio of C18O to H2 (Frerking et al. 1982)
hk=0.0479924335 #* 10e9
h=6.626e-34 ##(J*s) Planck's const
k=1.381e-23 ##(J/K) Boltzman const
eo=8.85e-12 ##(F/m) permitivity const
Tbg=2.7 ##(K) Background Temp
c=3.e8 ##(m/s) speed of light
Msol=1.98892e30 ##(kg) Solar mass in kg
mH=1.67e-27 ##atomic hydrogen mass in kg
mH2=2*mH ##(kg) mass of H2 in kg
mmw=2.33 ##mean mol weight wrt no of Hydrogen mols
SQARSCTSR=206265.**2 ##no of stradians in arcsec squared
dp=0.112*3.3365e30 ##(C*m) CO dipole moment (0.112 debye)
pac=3.08568e16 ##(m) one parsec in metres
v_co12_j32=345.796 #GHz
v_co13_j32=330.5879 #GHz
v_c18o_j32=329.331 #GHz
m_CO12=28.01 #atomic units
m_CO13=29.02 #atomic units
m_C18O=29.999 #atomic units
amu=1.66e-24 #g
k_b=1.38e-16 #erg/K
vres=0.83
velocity=np.array([-20.06933116, -20.90281358, -21.736296 , -22.56977842,
-23.40326084, -24.23674326, -25.07022567, -25.90370809,
-26.73719051, -27.57067293, -28.40415535, -29.23763777,
-30.07112019, -30.90460261, -31.73808503, -32.57156745,
-33.40504986, -34.23853228, -35.0720147 , -35.90549712,
-36.73897954, -37.57246196, -38.40594438, -39.2394268 ,
-40.07290922, -40.90639164, -41.73987405, -42.57335647,
-43.40683889, -44.24032131, -45.07380373, -45.90728615,
-46.74076857, -47.57425099, -48.40773341, -49.24121582,
-50.07469824, -50.90818066, -51.74166308, -52.5751455 ,
-53.40862792, -54.24211034, -55.07559276, -55.90907518,
-56.7425576 , -57.57604001, -58.40952243, -59.24300485,
-60.07648727, -60.90996969, -61.74345211, -62.57693453,
-63.41041695, -64.24389937, -65.07738179, -65.9108642 ,
-66.74434662, -67.57782904, -68.41131146, -69.24479388, -70.0782763 ])
#==============================================================================
def open_map(fits_file):
"""
Usage: Pixel_map, Wcs_Coords = open_map('fits_file')
Input: A 2D/3D fits file
Return: Numpy Masked Array of pixel Map,
WCS object of Map
"""
image = fits.getdata(fits_file)
image= np.ma.masked_array(image , np.isnan(image))
w = wcs.WCS(fits_file)
return image,w
def denoise_map(m,rms):
"""
Usage: DeNoised_map = denoise_map(map,RMS_map)
Input: A 2D pixel map
Return: Numpy Masked Array where snr>3
"""
return np.ma.masked_where(m<3.0*rms,m)
def cube_to_max(cube,option=1):
"""
Input: A 3D Masked Cube_Map
Option 1: (X,Y)=(X-Pixels,Y-Pixels)
Option 2: (X,Y)=(Y-Pixels,Velocity)
Option 3: (X,Y)=(X-Pixels,Velocity)
Return: Masked Maximum Intensity Map
"""
xx=1 if option==2 else 2
yy=1 if option==1 else 0
X=cube.shape[xx]
Y=cube.shape[yy]
mapmax=np.ma.masked_array(np.zeros((Y,X)),mask=np.ones((Y,X)))
for y in range(Y):
for x in range(X):
if (option==1):
value = cube[:,y,x].max()
elif (option==2):
value = cube[y,x,:].max()
elif (option==3):
value = cube[y,:,x].max()
else:
print 'Options Only (1,2,3)'
break
if (value.dtype=='float32'):
mapmax[y,x]=value
return mapmax
def plot_map(image,coords,title='title',cm ='RdPu'):
"""
Usage: plot_map(pixel_map,WCS_Coords)
Input: 2D pixel Map, WCS object of the Map
Output: Plot of The Image with a WCS Compass
"""
ax1 = pywcsgrid2.subplot(111, wcs=coords)
im = ax1.imshow(image,origin='low',cmap=cm)
ax1.add_compass(loc=5,color='black')
ax1.set_title(title)
plt.colorbar(im)
def save_to_fits(image,coords,filename):
wheader=coords.to_header()
hdu=fits.PrimaryHDU(data=image,header=wheader)
hdu.writeto(filename)
def plot_maps(coords,fn,cm='coolwarm',norm='log',fs=(20,10),**kwargs):
"""
Usage: plot_maps(maps=[list_of_maps],titles=[list_of_titles],fn=filename(put f for not saving),norm='log',fs=figsize,coords=wcs,cm=colormap)
Input: 2D pixel Maps, WCS object of the Maps
Output: Plot all Subplots of The Images with WCS Compass
"""
plt.rcParams['figure.figsize'] = fs
nm=len(kwargs['maps'])
a=[[]]*nm
for i,m in enumerate(kwargs['maps']):
vmax=m.max()
a[i]=(pywcsgrid2.subplot(1,nm,i,wcs=coords))
a[i].grid()
if norm=='log':
im=a[i].imshow(m,origin='low',cmap=cm,norm=LogNorm(),aspect=1.)
else:
im=a[i].imshow(m,origin='low',cmap=cm,aspect=1.)
a[i].set_title(kwargs['titles'][i])
a[i].add_compass(loc=5,color='black')
ains = inset_axes(a[i], width='2%', height='37%', loc=1)
cb=plt.colorbar(im,cax=ains)
plt.tight_layout()
if (fn !='f'):
plt.savefig(fn,bbox_inches='tight')
def initial_est(map_thick,map_thin,abundance):
"""
Initial Estimation of Optical Thickness using
two Isotopes and its abundance ratio
Input: Pixel_map of one isotope, Pixel_map of Optical Thick Isotope,
abudance ratio
Return: Masked Pixel_map of Optical Thickness
"""
map_thick=np.ma.masked_where(map_thick==0.0,map_thick)
ratio = map_thin/map_thick
tau=-abundance*np.log(1-ratio)
return tau
def tau_new(tau,map_thick,map_thin,abundance):
ratio=map_thick/map_thin
e=np.exp(-tau)
eab=np.exp(-tau/abundance)
return tau-(ratio*(1-eab)-(1-e))/(ratio*eab/abundance-e)
def final_est(map_thick,map_thin,T0,abundance,maxiter=5):
"""
Final Estimation of Optical Thickness using two Isotopes,
its abundance ratio and the Initial Estimation
Input: Pixel_map of Optical Thick isotope, Pixel_map of Optical Thin Isotope,
Initial estimation Pixel_map, abudance ratio and MaxIterations = 5
Return: Pixel_map of Optical Thickness
"""
for i in range(maxiter):
tau=tau_new(T0,map_thick,map_thin,abundance)
return tau
def Tr_est(Ta,nfss=0.77):
"""
True Temperature Estimation
Input: Pixel_map of Optical Thick Isotope, fss parameter
Return: Pixel_map of True Temperature
"""
return Ta/nfss
def gaussian(x, a, x0, sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
def gauss_fit(T,N):
"""
!! Warning: Extreme Slow !!
Runs a Scipy Curve Gaussian fit through every pixel of non-Masked Map
Input: A 3D pixel map
Return: 2D Map of GPeak Position, 2D Map of FWHM
"""
#Z,Y,X=T.shape[0],N,N
Z,Y,X=T.shape[0],T.shape[1],T.shape[2]
xx=np.linspace(0,1,61)
Peak_Map=np.zeros((Y,X))
HW=np.zeros((Y,X))
for y in range(Y):
for x in range(X):
s=Spectra(T,y,x)
if np.ma.is_masked(s):
Peak_Map[y,x]=0.0
FW[y,x]=0.0
else:
try:
popt, pcov = curve_fit(gaussian,xx,s)
Peak_Map[y,x]=popt[1]
FW[y,x]=2.355*np.abs(popt[2])
except:
Peak_Map[y,x]=0.0
FW[y,x]=0.0
pass
return Peak_Map,FW
def Tx_est(v,Tr,Tbg=2.7):
"""
Excitation Temperature Estimation
Input: Frequency of observation in GHz, Pixel_map of Optical Thick Isotope, Cosmic Background Temperature
Return: Pixel_map of Excitation Temperature
"""
T0=hk*v
A=Tr+T0/(np.exp(T0/Tbg)-1)
Tx = T0/np.log(1+T0/A)
return Tx
def Spectra(cube_map,y,x):
"""
Spectrum of Selected Coordinates
Input: Cube Map, pixel Coordinates
Return: Vector of Spectrum Values
"""
return cube_map[:,y,x]
def Spectra9(cube_map,y,x):
"""
Mean Spectrum of 3x3 Selected Coordinates
Input: Cube Map, pixel Coordinates
Return: Mean Spectrum, Standard Deviation Spectrum
"""
a=[]
for j in [y-1,y,y+1]:
for i in [x-1,x,x+1]:
a.append(np.nan_to_num(cube_map[:,j,i]))
a=np.array(a)
return np.mean(a, axis=0),np.std(a, axis=0)
def MassEst(od,TR,Tex,d,res,j,i,X,fco):
"""
od=optical depth
TR=Integral
Tex=Excitation Temp
d=distance in kpc
res=pixel resolution
j,i=line
X=CO to H2 abundance
fco=frequency of line in Hz
MG=MassEst(tau12_f,Integral12_fix,Tx12,d=2.,res=7.7,j=3,i=2,X=functions.ab12CO_H2,fco=functions.v_co12_j32*1e9)
"""
dist=d*1e3*pac ##distance to the cloud in metres
sq_pxsz=(res**2)*SQARSCTSR ##squared pixel size in steradian
ODcor=od/(1-np.exp(-od)) ##Optical depth correction
"""****************************************
Set the Nij equation terms (result in m^-2)
****************************************"""
term1=1.49*1e25 ##
term2=0.364*(Tex+0.922) ## the partition function Z
term3=2.765*1e-9*(i*(i+1)) ## h*vio/k
term4=4.798*1e-11 ## h/k
Nco=(term1/(fco*j))*term2*np.exp(term3/Tex)*(1-np.exp(-term4*fco/Tex))*((1/(np.exp(term4*fco/Tex)-1))-(1/(np.exp(term4*fco/Tbg)-1)))**(-1)*ODcor*1e3*TR ##should be in cm^-2
MGas=(1E-4)*(1E-6)*2.8*mH2*dist*dist*sq_pxsz*X*Nco/Msol
return MGas
def Integral_to_mass(integral,Tx,tau):
d=2000.*pac
X=1./(8.5e-5)
A=1.28e14
T10=h *115.271*10**9 /k
T32=h *v_co12_j32*10**9 /k
Tbg=2.7
Z=0.36156*(Tx+0.922)
BB=np.exp(T10/Tx)
B=(1.-np.exp(-T32/Tx))
C=(1./(np.exp(T32/Tx)-1.)-1./(np.exp(T32/Tbg)-1.))**(-1)
D=tau/(1.-np.exp(-tau))
integ=integral*1000.
N=A*Z*BB*B*C*D*integ
M=N*2.8*(3.35e-27)*(7.7/206265)**2 *X *d**2
return M/Msol
def map_showXY(map12,map12m,map12my,map12mx,map13,map13m,map18,map18m,ta12,ta13,Tx12,Tx13,Tx18,wcs,y,x,dy,dx,dv,gf,s):
"""
To use with IPython interact
"""
#===================================Fitting======================
#gf=0.2 #gooud fit parameter ~10%
index_deviation=[10,2] #Max and Min Index Deviation for Second Derivative Mask
xx=velocity
#===========CO12=======================
s12=Spectra(map12,y,x)
#----mask------
der2=np.diff(s12,2.) #Second Derivative
m = np.ones(len(s12), dtype=bool)
ind1=np.argsort(der2)[0]+1
ind2=np.argsort(der2)[1]+1
i=0
while (np.abs(ind1-ind2)>index_deviation[0] or np.abs(ind1-ind2)<index_deviation[1]):
#print np.abs(ind1-ind2),np.abs(ind1-ind2)>15
ind2=np.argsort(der2)[i]+1
i=i+1
m[ind1:ind2]=False
m[ind2:ind1]=False
#---end of mask-----
try:
popt12, pcov12 = curve_fit(gaussian, xx[m], s12[m],p0=[s12.max(),xx[np.argmax(s12)],1.5],diag=(0.01,0.01))
except:
popt12,pcov12=np.zeros((3)),np.zeros((3,3))
sd12= np.sqrt(np.diag(pcov12)) #Standard Deviation
fit12 = (sd12<gf*np.abs(popt12)).all() #Good Fit?
FWHM12=2.355*np.abs(popt12[2]) #Fitted Full Width Half Maximum
FWTM12=1.865*FWHM12
outflow=False
if (FWTM12>4.):
outflow=True
FWHM12t=0.00001*2.355*np.sqrt(k_b*Tx12[y,x]/(m_CO12*amu)) #theoretical (thermal)
########################################
# s912=Spectra9(map12,y,x)[0]
# popt912, pcov912 = curve_fit(gaussian, xx, s912,p0=[s912.max(),xx[np.argmax(s12)],1.5],diag=(0.01,0.01))
# sd912= np.sqrt(np.diag(pcov912))
#===========CO13=======================
s13=Spectra(map13,y,x)
try:
popt13, pcov13 = curve_fit(gaussian, xx, s13,p0=[0.25*popt12[0],popt12[1],popt12[2]],diag=(0.005,0.005))
except:
popt13,pcov13=np.zeros((3)),np.zeros((3,3))
sd13= np.sqrt(np.diag(pcov13)) #Standard Deviation
fit13 = (sd13<gf*np.abs(popt13)).all() #Good Fit?
FWHM13=2.355*np.abs(popt13[2]) #Fitted Full Width Half Maximum
FWHM13t=0.00001*2.355*np.sqrt(k_b*Tx13[y,x]/(m_CO13*amu)) #theoretical (thermal)
########################################################
# s913=Spectra9(map13,y,x)[0]
# popt913, pcov913 = curve_fit(gaussian, xx, s913,p0=[0.25*popt912[0],popt912[1],popt912[2]],diag=(0.1,0.1))
# sd913= np.sqrt(np.diag(pcov913))
#===========CO18=======================
s18=Spectra(map18,y,x)
try:
popt18, pcov18 = curve_fit(gaussian, xx, s18,p0=[0.25*popt13[0],popt13[1],popt13[2]],diag=(0.001,0.001))
except:
popt18,pcov18=np.zeros((3)),np.zeros((3,3))
sd18= np.sqrt(np.diag(pcov18)) #Standard Deviation
fit18 = (sd18<gf*np.abs(popt18)).all() #Good Fit?
FWHM18=2.355*np.abs(popt18[2]) #Fitted Full Width Half Maximum
FWHM18t=0.00001*2.355*np.sqrt(k_b*Tx18[y,x]/(m_C18O*amu)) #theoretical (thermal)
#================TABLE========================================
col1=['$^{12}CO$ $T_{B}$','$^{13}CO$ $T_{B}$','$C^{18}O$ $T_{B}$',r'$\tau^{12}$',r'$\tau^{13}$','$^{12}CO$ $T_{X}$','$^{13}CO$ $T_{X}$',r'$^{12}CO$ FWHM',r'$^{12}CO$ FWTM',r'$^{13}CO$ FWHM',r'$C^{18}O$ FWHM',r'$^{12}CO$ Integral',r'$^{12}CO$ Core Integral', r'$^{12}CO$ Wings Integral','$^{12}CO$ Mass','$^{12}CO$ Core Mass','$^{12}CO$ Wings Mass',r'$^{12}CO$ Blue Wing Speed (Absolute)',r'$^{12}CO$ Red Wing Speed (Absolute)',r'$^{12}CO$ (Blue,Right) Wings Momentum']
i12all=s12.sum()*vres
i12b=s12[xx<popt13[1]-FWHM13/2].sum()*vres if fit13 else np.nan
i12r=s12[xx>popt13[1]+FWHM13/2].sum()*vres if fit13 else np.nan
i12=i12b+i12r
#i12=(s12[xx<popt13[1]-FWHM13/2].sum()+s12[xx>popt13[1]+FWHM13/2].sum())*vres if fit13 else np.nan
i12core=i12all-i12 if fit13 else np.nan
Mb=Integral_to_mass(i12b,Tx12[y,x],ta12[y,x]) if i12b else np.nan
Mr=Integral_to_mass(i12r,Tx12[y,x],ta12[y,x]) if i12r else np.nan
MG= Integral_to_mass(i12,Tx12[y,x],ta12[y,x]) if i12 else np.nan
MGall=Integral_to_mass(i12all,Tx12[y,x],ta12[y,x]) if i12 else np.nan
MGcore=Integral_to_mass(i12core,Tx12[y,x],ta12[y,x]) if i12 else np.nan
Vrel=popt13[1]
xx1=np.logical_and(xx<=Vrel-FWHM13/2,xx>=Vrel-10.)
xx2=np.logical_and(xx>=Vrel+FWHM13/2,xx<=Vrel+10.)
Vb=(xx[xx1]*s12[xx1]).sum()/s12[xx1].sum()
Vr=(xx[xx2]*s12[xx2]).sum()/s12[xx2].sum()
Pb=Mb*Vb/np.cos(57.3)
Pr=Mr*Vr/np.cos(57.3)
if outflow:
si='%0.2f $K\,km\,s^{-1}$'%i12
sm='%0.2f $M_{\odot}$ ($M_{B}$: %0.2f, $M_{R}$: %0.2f) // Ratio (all): %0.2f (core): %0.2f'%(MG,Mb,Mr,MG/MGall,MG/MGcore)
siall='%0.2f $K\,km\,s^{-1}$'%i12all
small='%0.2f $M_{\odot}$'%MGall
sicore='%0.2f $K\,km\,s^{-1}$'%i12core
smcore='%0.2f $M_{\odot}$'%MGcore
else:
si='0.0 (%0.2f) $K\,km\,s^{-1}$'%i12
sm='0.0 (%0.2f) $M_{\odot}$'%MG
siall='0.0 (%0.2f) $K\,km\,s^{-1}$'%i12all
small='0.0 (%0.2f) $M_{\odot}$'%MGall
sicore='0.0 (%0.2f) $K\,km\,s^{-1}$'%i12core
smcore='0.0 (%0.2f) $M_{\odot}$'%MGcore
col2=np.array(['%0.2f'%map12m[y,x],'%0.2f'%map13m[y,x],'%0.2f'%map18m[y,x],'%0.2f'%ta12[y,x],'%0.2f'%ta13[y,x],'%0.2f K'%Tx12[y,x],'%0.2f K'%Tx13[y,x],'%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM12,FWHM12t),'%0.2f $km\,s^{-1}$'%FWTM12,'%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM13,FWHM13t),'%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM18,FWHM18t),siall,sicore,si,small,smcore,sm,'%0.2f (%0.2f) $km\,s^{-1}$'%(Vb-Vrel,Vb),'%0.2f (%0.2f) $km\,s^{-1}$'%(Vr-Vrel,Vr),'%0.2f,%0.2f // %0.2f $M_{\odot} km\,s^{-1}$'%(Pb,Pr,Pb+Pr)])
t=Table([col1,col2],names=('Name','Value'),meta={'name': 'first table'})
display(t)
#col1=np.array(['$^{12}CO$ $T_{B}$','%0.2f'%map12m[y,x]])
#col2=np.array(['$^{13}CO$ $T_{B}$','%0.2f'%map13m[y,x]])
#col3=np.array(['$C^{18}O$ $T_{B}$','%0.2f'%map18m[y,x]])
#col4=np.array([r'$\tau^{12}$','%0.2f'%ta12[y,x]])
#col5=np.array([r'$\tau^{13}$','%0.2f'%ta13[y,x]])
#col6=np.array(['$^{12}CO$ $T_{X}$','%0.2f K'%Tx12[y,x]])
#col7=np.array(['$^{13}CO$ $T_{X}$','%0.2f K'%Tx13[y,x]])
#col8=np.array([r'$^{12}CO$ FWHM','%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM12,FWHM12t)])
#col9=np.array([r'$^{13}CO$ FWHM','%0.2f $km\,s^{-1}$'%FWTM12])
#col10=np.array(['$^{13}CO$ $T_{B}$','%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM13,FWHM13t)])
#col11=np.array([r'$C^{18}O$ FWHM','%0.2f $km\,s^{-1}$ (thermal: %0.2f)'%(FWHM18,FWHM18t)])
#col12=np.array([r'$^{12}CO$ Wings Integral',si])
#col13=np.array(['$^{12}CO$ Wings Mass',sm])
#t=Table([col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13])
#display(t)
#t.write('test.tex',format='latex')
#================Print==============================================
# print 'tau12: %0.3f'%ta12[y,x]
# print 'tau13: %0.3f'%ta13[y,x]
# print '12CO Excitation Temperature: %0.2f'%Tx12[y,x]
# print '13CO Excitation Temperature: %0.2f'%Tx13[y,x]
# print 'C18O Excitation Temperature: %0.2f'%Tx18[y,x]
# print '12CO FWHM: %0.2f km/s || Theoretical (thermal): %0.2f km/s (Ratio:%0.2f) || Larson L: %0.2f pc || Larson M: %0.2f Mo'%(FWHM12,FWHM12t,FWHM12/FWHM12t,(FWHM12/1.1)**(1/0.38),(FWHM12/0.42)**(1/0.2))
# print '13CO FWHM: %0.2f km/s || Theoretical (thermal): %0.2f km/s (Ratio:%0.2f) || Larson L: %0.2f pc || Larson M: %0.2f Mo'%(FWHM13,FWHM13t,FWHM13/FWHM13t,(FWHM13/1.1)**(1/0.38),(FWHM13/0.42)**(1/0.2))
# print 'C18O FWHM: %0.2f km/s || Theoretical (thermal): %0.2f km/s (Ratio:%0.2f) || Larson L: %0.2f pc || Larson M: %0.2f Mo'%(FWHM18,FWHM18t,FWHM18/FWHM18t,(FWHM18/1.1)**(1/0.38),(FWHM18/0.42)**(1/0.2))
# if fit13:
# print 'Wings Integral in $^{12}CO$: %0.2f K'%(s12[xx<popt13[1]-FWHM13/2].sum()+s12[xx>popt13[1]+FWHM13/2].sum())
#===========================================================================
#===========PLOTS=======================
#===========================================================================
plt.rcParams['figure.figsize'] = 22, 35
#dy,dx,dv=20,20,10
vmax=np.argmax(s13)
v1,v2=vmax-dv,vmax+dv
#===========================================
#===Map=====================================
gs = gridspec.GridSpec(11, 8)
#====ax1-Main Map===============================
ax1=plt.subplot(gs[1:5,2:7]) #Axis for Main Map
ax1.set_title('$^{12}CO$ Excitation Temperatures')
#mim=ax1.imshow(map12m,origin='low',cmap='coolwarm')
mim=ax1.imshow(Tx12.data,origin='low',cmap='coolwarm') #Excitation Map
ax1.axvline(x=x,color='k',ls='dashed',linewidth=1.0,alpha=0.6) #Current X
ax1.annotate('$x$=%d'%x,(x+5,5),color='k',size=20)
ax1.axhline(y=y,color='k',ls='dashed',linewidth=1.0,alpha=0.6) #Current Y
ax1.annotate('$y$=%d'%y,(5,y+5),color='k',size=20)
ax1bar = inset_axes(ax1, width='2%', height='40%', loc=4) #axis for colorbar
ax1.annotate(s='', xy=(530,40), xytext=(579,40), arrowprops={'arrowstyle':'|-|','linewidth':2.0})
ax1.text(542,43,'3 pc',color='white',fontsize=15)
plt.colorbar(mim,cax=ax1bar) #colorbar
#=====================================
axv0=plt.subplot(gs[0,2:7],sharex=ax1) #Axis for (X,Velocity) Map
axv0.set_title(' $^{12}CO$ Max $T_{B}$')
lev=np.linspace(0,map12mx.max(),20) #Contourf Levels
mimx=axv0.contourf(np.arange(0,map12mx.shape[1]),velocity,map12mx,levels=lev,cmap='coolwarm')
axv0.xaxis.tick_top()
axv0.axvline(x=x,color='k',ls='dashed',linewidth=1.0,alpha=0.75) #Current X
axv1=plt.subplot(gs[1:5,7],sharey=ax1) #Axis for (X,Velocity) Map
axv1.set_title('$^{12}CO$ Max $T_{B}$')
lev=np.linspace(0,map12my.max(),20) #Contourf Levels
mimx=axv1.contourf(velocity,np.arange(0,map12my.shape[1]),np.rot90(map12my,3),levels=lev,cmap='coolwarm')
axv1.yaxis.tick_right()
axv1.axhline(y=y,color='k',ls='dashed',linewidth=1.0,alpha=0.75) #Current Y
#===========================
#==Zoom=======
x1, x2, y1, y2 = x-dx, x+dx, y-dy, y+dy #Define Region
region12=map12m[y1:y2,x1:x2]
region13=map13m[y1:y2,x1:x2]
if ((x+dx>350) and (y+dy>250)): #dx=20, 7
axins = zoomed_inset_axes(ax1, 140./np.max([dx,dy]), loc=3) #Axis for Zoom
else:
axins = zoomed_inset_axes(ax1, 140./np.max([dx,dy]), loc=1) #Axis for Zoom
#axins.set_title('$^{12}CO$ and $^{13}CO$ (contours) \n max$T_{B}$ $(K)$')
c12=axins.contourf(map12m,levels=np.linspace(region12.min(),region12.max(),15))
c13=axins.contour(map13m,cmap='gnuplot',levels=np.linspace(region13.min(),region13.max(),7),alpha=0.75)
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
mark_inset(ax1, axins, loc1=2, loc2=3, fc="none", ec="1.",lw=2.)
axins.set_title('Max $T_{B}$ Contours:$^{13}CO$ \n Max $T_{B}$ Filled Contours:$^{12}CO$ ')
# axins12 = inset_axes(axins, width='2%', height='25%', loc=2)
# cbar12=plt.colorbar(c12,cax=axins12)
# cbar12.ax.set_title('$^{12}CO$ \n maxT $(K)$')
#
# axins13 = inset_axes(axins, width='2%', height='25%', loc=1)
# cbar13=plt.colorbar(c13,cax=axins13)
# cbar13.ax.set_title('$^{13}CO$ \n maxT $(K)$')
#==Map-Rectangles
dd=0.5
rect1 = [Rectangle((x-dx,y-dd), width=2.*dx, height=2.*dd, fill=False,color='red',linewidth=1.2,alpha=0.75)]
axins.add_artist(rect1[0])
rect2 = [Rectangle((x-dd,y-dy), width=2.*dd, height=2.*dy, fill=False,color='red',linewidth=1.2,alpha=0.75)]
axins.add_artist(rect2[0])
rect3= [Rectangle((x-1.5,y-1.5), width=3, height=3, fill=False,color='green',linewidth=1.5,alpha=0.95)]
axins.add_artist(rect3[0])
#=================3D Velocities==================================================
#Parameters
hl_lw=3 #Highlight LineWidth
lev_18 = [popt18[0]/2.] #C18O Contour Display
lev_13 = popt13[0]/2. #CO13 Contour Display
min13=0.75
min12=0.
num_levels_12=10
num_levels_13=8
#======X-line=========================
ax1y=plt.subplot(gs[5:7,2:])
ax1y.set_ylabel('Velocity $(km\,s^{-1})$')
ax1y.set_xlabel('X-Pixel')
region13y=map13[v1:v2,y,x-dx:x+dx] #CO13 zoom region
region12y=map12[v1:v2,y,x-dx:x+dx] #CO12 zoom region
region18y=map18[v1:v2,y,x-dx:x+dx] #CO18 zoom region
lev13y = np.linspace(np.abs(region13y.min())+min13,region13y.max(),num_levels_13)
lev12y = np.linspace(min12,region12y.max(),num_levels_12)
lev18y=lev_18
cy=ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region13y,levels=lev13y,linewidths=2.1,cmap='gnuplot',alpha=0.8)
if fit13:
ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region13y,[lev_13],linestyles='--',linewidths=hl_lw,colors='red',alpha=1.)
c2y=ax1y.contourf(np.arange(x-dx,x+dx,1),velocity[v1:v2],region12y,levels=lev12y)
if fit18:
ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region18y,lev18y,linestyles='--',linewidths=hl_lw,colors='black',alpha=0.8)
ax1y.contour(np.arange(x-dx,x+dx,1),velocity[v1:v2],region18y,[s18.max()*0.8],linewidths=hl_lw+1,colors='black',alpha=0.8)
ax1y.plot(np.ones(velocity[v1:v2].shape)*x,velocity[v1:v2],'--')
#===CO12 Colorbar Hacks======================================
axinsy12 = inset_axes(ax1y, width='35%', height='3%', loc=2)
cbary12=plt.colorbar(c2y,cax=axinsy12,orientation='horizontal')
cbary12.ax.set_title('$^{12}CO$ $T_{B}$ $(K)$')
#===CO13 Colorbar Hacks======================================
axinsy13 = inset_axes(ax1y, width='30%', height='3%', loc=1)
cbary13=plt.colorbar(cy,cax=axinsy13,orientation='horizontal')
cbary13.ax.set_title('$^{13}CO$ $T_{B}$ $(K)$')
#==========Y-line===============================================================
ax1x=plt.subplot(gs[1:5,:2])
ax1x.set_xlabel('Velocity $(km\,s^{-1})$')
ax1x.set_ylabel('Y-Pixel')
region13x=map13[v1:v2,y-dy:y+dy,x]
region12x=map12[v1:v2,y-dy:y+dy,x]
region18x=map18[v1:v2,y-dy:y+dy,x]
lev13x = np.linspace(np.abs(region13x.min())+min13,region13x.max(),num_levels_13)
lev12x = np.linspace(min12,region12x.max(),num_levels_12)
lev18x=lev_18
cx=ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region13x,3),levels=lev13x,linewidths=2.1,cmap='gnuplot',alpha=0.8)
if fit13:
ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region13x,3),[lev_13],linestyles='--',linewidths=hl_lw,colors='red',alpha=1.)
c2x=ax1x.contourf(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region12x,3),levels=lev12x)
if fit18:
ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region18x,3),lev18x,linestyles='--',linewidths=hl_lw,colors='black',alpha=0.8)
ax1x.contour(velocity[v1:v2],np.arange(y-dy,y+dy),np.rot90(region18y,3),[s18.max()*0.8],linewidths=hl_lw+1,colors='black',alpha=0.8)
ax1x.plot(velocity[v1:v2],np.ones(velocity[v1:v2].shape)*y,'--')
#===CO12 Colorbar Hacks======================================
axinsx12 = inset_axes(ax1x, width='3%', height='30%', loc=2)
cbarx12=plt.colorbar(c2x,cax=axinsx12)
cbarx12.ax.set_title('$^{12}CO$ \n $T_{B}$ $(K)$')
#===CO13 Colorbar Hacks======================================
axinsx13 = inset_axes(ax1x, width='3%', height='30%', loc=1)
cbarx13=plt.colorbar(cx,cax=axinsx13)
cbarx13.ax.set_title('$^{13}CO$ \n $T_{B}$ $(K)$')
axinsx13.yaxis.set_ticks_position("left")
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#============================================================================
x_p=xx.min()
#x_mean= xx.mean() #For Text Annotation
ax2=plt.subplot(gs[7,:])
y_p=s12.max()
ax2.set_title('$^{12}CO$ // $FWHM=$%0.3f'%(FWHM12))
ax2.plot(xx,s12,label='CO12')
ax2.plot(xx[m],s12[m],'ko',label='Masked CO12 Data')
ax2.plot(xx,gaussian(xx,popt12[0],popt12[1],popt12[2]),label='Fit to Masked Data')
if fit12:
ax2.fill_between(xx,gaussian(xx,popt12[0]-sd12[0],popt12[1]-sd12[1],popt12[2]-sd12[2]),gaussian(xx,popt12[0]+sd12[0],popt12[1]+sd12[1],popt12[2]+sd12[2]),alpha=0.25)
ax2.annotate(r'Fit Parameters for CO12: $A=$%0.3f +/-%0.3f, $x_0=$%0.3f +/-%0.3f, $\sigma=$%0.3f +/-%0.3f'%(popt12[0],sd12[0],popt12[1],sd12[1],popt12[2],sd12[2]),(x_p,y_p))
hline=np.linspace(popt12[1]-FWHM12/2,popt12[1]+FWHM12/2,10)
ax2.plot(hline,np.ones(hline.shape)*popt12[0]/2,color='r',label='HalfMaximum of fit CO12')
ax2.plot(xx,s13,alpha=0.7,label='CO13')
ax2.plot(xx,s18,alpha=0.5,label='C18O')
if fit18:
ax2.axvspan(popt18[1]-FWHM18/2.,popt18[1]+FWHM18/2.,alpha=0.15)
if fit13:
ax2.axvspan(popt13[1]-FWHM13/2.,popt13[1]+FWHM13/2.,alpha=0.15,color='green')
ax2.legend()
ax3=plt.subplot(gs[8,:],sharex=ax2)
y_p=s13.max()
ax3.set_title('$^{13}CO$ // $FWHM=$%0.3f'%(FWHM13))
ax3.plot(xx,s13,'ko',label='CO13')
ax3.plot(xx,gaussian(xx,popt13[0],popt13[1],popt13[2]),label='Fit to CO13')
if fit13:
ax3.fill_between(xx,gaussian(xx,popt13[0]-sd13[0],popt13[1]-sd13[1],popt13[2]-sd13[2]),gaussian(xx,popt13[0]+sd13[0],popt13[1]+sd13[1],popt13[2]+sd13[2]),alpha=0.25)
ax3.annotate(r'Fit Parameters for CO13: $A=$%0.3f +/-%0.3f, $x_0=$%0.3f +/-%0.3f, $\sigma=$%0.3f +/-%0.3f'%(popt13[0],sd13[0],popt13[1],sd13[1],popt13[2],sd13[2]),(x_p,y_p))
hline=np.linspace(popt13[1]-FWHM13/2,popt13[1]+FWHM13/2,10)
ax3.plot(hline,np.ones(hline.shape)*popt13[0]/2,color='r',label='HalfMaximum of fit CO13')
ax3.plot(xx,s18,alpha=0.5,label='C18O')
if fit18:
ax3.axvspan(popt18[1]-FWHM18/2,popt18[1]+FWHM18/2,alpha=0.15)
if fit13:
ax3.axvspan(popt13[1]-FWHM13/2.,popt13[1]+FWHM13/2.,alpha=0.15,color='green')
ax3.legend()
ax4=plt.subplot(gs[9,:],sharex=ax2)
y_p=s18.max()
ax4.set_title(r'$C^{18}O$ // $FWHM=$%0.3f'%(FWHM18))
ax4.plot(xx,s18,'ko',label='C18O')
if fit18:
ax4.plot(xx,gaussian(xx,popt18[0],popt18[1],popt18[2]),label='Fit to CO18')
ax4.fill_between(xx,gaussian(xx,popt18[0]-sd18[0],popt18[1]-sd18[1],popt18[2]-sd18[2]),gaussian(xx,popt18[0]+sd18[0],popt18[1]+sd18[1],popt18[2]+sd18[2]),alpha=0.25)
ax4.annotate(r'Fit Parameters for CO18: $A=$%0.3f +/-%0.3f, $x_0=$%0.3f +/-%0.3f, $\sigma=$%0.3f +/-%0.3f'%(popt18[0],sd18[0],popt18[1],sd18[1],popt18[2],sd18[2]),(x_p,y_p))
hline=np.linspace(popt18[1]-FWHM18/2,popt18[1]+FWHM18/2,10)
ax4.plot(hline,np.ones(hline.shape)*popt18[0]/2,color='r',label='HalfMaximum of fit CO18')
ax4.axvspan(popt18[1]-FWHM18/2,popt18[1]+FWHM18/2,alpha=0.15)
ax4.legend()
ax5=plt.subplot(gs[10,:],sharex=ax2)
ax5.set_title(r'$^{12}CO$ Wings')
ax5.fill_between(xx[xx1],s12[xx1],alpha=0.7,color='blue')
ax5.fill_between(xx[xx2],s12[xx2],alpha=0.7,color='red')
if outflow:
ax5.annotate(r'Outflow Mass Estimation: %0.2f $M_{\odot}$'%MG,(x_p,s12.max()-2),fontsize=17)
ax5.annotate(r'Outflow Momentum Estimation: %0.2f $M_{\odot}\, km \, s^{-1}$'%(Pb+Pr),(x_p,s12.max()-0.4*s12.max()),fontsize=17)
ax5.annotate(r'Blue Outflow: %0.2f $M_{\odot}$'%Mb,(popt13[1]-10,y_p),fontsize=13)
ax5.annotate(r'$V_B:$ %0.2f $km\,s^{-1}$'%Vb,(Vb,y_p+5),fontsize=12)
ax5.annotate(r'$V_R:$ %0.2f $km\,s^{-1}$'%Vr,(Vr,y_p+5),fontsize=12)
ax5.annotate(r'Red Outflow: %0.2f $M_{\odot}$'%Mr,(popt13[1]+5,y_p),fontsize=13)
ax5.vlines(Vb,0,s12.max())
ax5.vlines(Vr,0,s12.max())
#ax6=plt.subplot(gs[11:,:],sharex=ax2)
#ax6.set_title('3X3 Mean and Standard Deviation Spectrum')
#ave12=Spectra9(map12,y,x)
#ave13=Spectra9(map13,y,x)
#ave18=Spectra9(map18,y,x)
#ax6.plot(xx,ave12[0],color='blue',label='CO12 Mean')
#ax6.fill_between(xx,ave12[0]-ave12[1],ave12[0]+ave12[1],color='blue',alpha=0.25)
#ax6.plot(xx,ave13[0],color='green',label='CO12 Mean')
#ax6.fill_between(xx,ave13[0]-ave13[1],ave13[0]+ave13[1],color='green',alpha=0.25)
#ax6.plot(xx,ave18[0],color='red',label='CO12 Mean')
#ax6.fill_between(xx,ave18[0]-ave18[1],ave18[0]+ave18[1],color='red',alpha=0.25)
# ax6.plot(xx,gaussian(xx,popt913[0],popt913[1],popt913[2]),'--',linewidth=3.,label='Fit')
#ax6.legend()
plt.tight_layout()
if s:
plt.savefig('full%d-%d'%(y,x),bbox_inches='tight')
#t.write('t%d-%d.tex'%(y,x),format='latex')
| [
"mighalis@gmail.com"
] | mighalis@gmail.com |
27818e0cbd1150b9c136e42d2890085eb3918eeb | e5a1e766d32fa2475b23e8bda93462ea98938a8f | /new_chat/wsgi.py | 2f4a3672370594a951791355a78a5ed6f3af4d72 | [] | no_license | ShoaibMoeen/Django_Chat_App | 7993efeb603d6df7315108822dff1a2513df8dba | 27c8c99d5f7308c710741b0454f81ec85ff3707a | refs/heads/master | 2023-03-05T20:29:35.349574 | 2021-02-17T09:27:02 | 2021-02-17T09:27:02 | 338,788,856 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | """
WSGI config for new_chat project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_chat.settings')
application = get_wsgi_application()
| [
"shoaibmoeen4343@gmail.com"
] | shoaibmoeen4343@gmail.com |
0ee4eca75016f2b835c19c87122bb9b245e074d6 | f69580425242d3c2e27881f0c85be73915a6f81e | /pydnd/character/models.py | 84079f946cf1dddd30273502390f5c778fe56e77 | [] | no_license | pyasi/pydnd | 83c9a8626e60b32797d9c6abbdf9ba7ab36bdb4e | a2e880c8a7264d313cad56f9ea0eec72309ac20e | refs/heads/master | 2020-03-07T08:37:43.767559 | 2018-05-03T13:57:53 | 2018-05-03T13:57:53 | 127,384,097 | 0 | 0 | null | 2018-05-03T13:57:54 | 2018-03-30T05:09:48 | Python | UTF-8 | Python | false | false | 1,770 | py | from django.db import models
from pydnd.mechanics.models import MagicSchool
class AbilityScore(models.Model):
name = models.CharField(max_length=100, unique=True)
full_name = models.CharField(max_length=100)
desc = models.CharField(max_length=10000)
def __str__(self):
return self.full_name
class Skill(models.Model):
name = models.CharField(max_length=100, unique=True)
desc = models.CharField(max_length=10000)
ability_score = models.ForeignKey(AbilityScore, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.name
class Spell(models.Model):
name = models.CharField(max_length=100, unique=True)
desc = models.CharField(max_length=10000)
higher_level = models.CharField(max_length=10000, null=True)
range = models.CharField(max_length=1000)
components = models.CharField(max_length=1000)
ritual = models.CharField(max_length=10000)
duration = models.CharField(max_length=1000)
concentration = models.CharField(max_length=1000)
casting_time = models.CharField(max_length=1000)
level = models.IntegerField()
school = models.ForeignKey(MagicSchool, on_delete=models.CASCADE, null=True)
class SpellCastingClass(models.Model):
name = models.CharField(max_length=100, unique=True)
ability_score = models.ManyToManyField(AbilityScore)
cantrips = models.CharField(max_length=10000, null=True)
preparing_and_casting = models.CharField(max_length=10000, null=True)
spellcasting_ability = models.CharField(max_length=10000, null=True)
ritual_casting = models.CharField(max_length=10000, null=True)
spellcasting_focus = models.CharField(max_length=10001, null=True)
spell_slots = models.CharField(max_length=10000, null=True)
| [
"pyasi8192@gmail.com"
] | pyasi8192@gmail.com |
58a803cde41cd78a494ce62be9283c642fa86e83 | eaea162301e30aece2bafc08a868c33ebe753324 | /main.py | d5db9e0a139f8043fbf0bd4dfdd9e6903ff8179d | [] | no_license | LAEQ/Pollution_StructurationTools | a56616638e20368c2d1fa41634d6cc277376b378 | 5439f9e148a0055781100fd9164c9068dd260199 | refs/heads/master | 2020-04-21T04:10:47.345888 | 2019-07-24T14:35:54 | 2019-07-24T14:35:54 | 169,305,682 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,072 | py | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 14:15:16 2018
@author: GelbJ
"""
Racine = "E:/Datas/_Montreal 2019/A)_FieldData"
######################################################
### Config Steph
######################################################
#Users = ["ID1_JR"]
#Users=["ID2_LN"]
#Users=["ID3_MS"]
#Users=["ID4_TA"]
Avoid=[]
#####################################################
## Programme principal
#####################################################
from Config import Config
from JG_Structuring_BD import PollutionBD
import sys
sys.path.append(Config["JBasicsPath"])
for User in Users :
Path = Racine+"/"+User
#generation de la BD (depuis le debut si necessaire)
BD = PollutionBD(Path,Config,Erase=True)
#nettoyage des CSV
BD.CleanCSVs()
# #creation de la BD SQLITE
BD.Fill()
## #Generation des fichiers SHP
## Avoid = ["ID3_VJ_2019-02-25_TRAJET03",#pas de gps...
## ]
BD.GenerateShps(Avoid = Avoid)
BD.EvaluateShps()
BD.PrepareTimeExcel() | [
"noreply@github.com"
] | LAEQ.noreply@github.com |
3f710f824a9ba3fc05f946ea786168e280edb9f3 | 05040f0dce123be0d88e760808fdf6b1bbf1ac43 | /backend/manage.py | 38f19f1341ecef8ebd95be44a20975de9823d12e | [] | no_license | crowdbotics-apps/mobile-8-dec-dev-16453 | 8026421c163ab200a0106faaf3567faf469b348f | 3cc2feeba0d1a753a98db7167491e5a28d7ae6fe | refs/heads/master | 2023-01-23T10:02:48.817260 | 2020-12-08T15:42:47 | 2020-12-08T15:42:47 | 319,665,608 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 642 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mobile_8_dec_dev_16453.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
80a957f639ad9152f7478c2f7c5faf20dff26992 | 3907034857319c47efd09429f994ff4c8a34a642 | /bienes/urls.py | 9cb1ec71e2006a9673df3a25d19c1a410aaa861f | [] | no_license | xcarlx/bienes | c018af7582f725e06d354144bac8641e348192ab | 48a69798ead5d627b38a2d9afe84ad484ca4e7da | refs/heads/master | 2020-04-17T02:36:14.054458 | 2019-02-19T20:44:15 | 2019-02-19T20:44:15 | 166,143,291 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,038 | py | """bienes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('apps.home.urls')),
path('', include('apps.servicio.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| [
"cruiz@regioncajamarca.gob.pe"
] | cruiz@regioncajamarca.gob.pe |
14539757dac6949ee5971550e5ce037dd82f2b1f | d1a6f7a61035e8e85f70663677eef0794ed42b8f | /create dictonary.py | 3c5eb2d0df31c49d8ad7a5a6594eefab23a1db46 | [] | no_license | shubhamfursule/Create-Dictonry | aaf9a665dc14c950c54c9713b2f9d879f239f822 | d251528ae1b654a72964fb7daf43d404d4a3c5ba | refs/heads/main | 2023-02-09T03:20:07.039319 | 2020-12-28T18:15:44 | 2020-12-28T18:15:44 | 325,084,068 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | dicts={}
while True:
try:
key,value=map(str,input().split(","))
except:
print("Please Enter proper way")
else:
if key=="STOP":
break
else:
try:
dicts.update({key:int(value)})
except:
print("please Enter proper type!")
print(dicts)
| [
"noreply@github.com"
] | shubhamfursule.noreply@github.com |
ec63ed048f6211cd69e8bc2bc40d3e6f418eaf0d | 336cd9225281befde93e01858ede15f70d3e5b47 | /params/cartpole_obs/shm_default copy.py | 2ab5c02726c7c6586d11fff9f5736ea8bffe8c5f | [] | no_license | GuancongLuo/mpc-mpnet-py | 7d6ba9f0c954185a724421091b1b098ec6d148e6 | 3d8d8ef743fd467fd2ffe177021edc6e852fd094 | refs/heads/master | 2023-02-06T03:49:06.072105 | 2020-12-07T11:01:08 | 2020-12-07T11:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,333 | py | import numpy as np
def get_params():
params = {
'solver_type': "cem",
'n_problem': 1,
'n_sample': 32,
'n_elite': 8,
'n_t': 1,
'max_it': 5,
'converge_r': 0.1,
'dt': 2e-3,
'mu_u': [0],
'sigma_u': [400],
'mu_t': 0.5,
'sigma_t': 0.5,
't_max': 1,
'verbose': False, # True,#
'step_size': 1,
"goal_radius": 1.5,
"sst_delta_near": .3,
"sst_delta_drain": 0.1,
"goal_bias": 0.05,
"width": 4,
"hybrid": False,
"hybrid_p": 0.0,
"cost_samples": 1,
"mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k_external_small_model.pt",
#"mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k_external_v2_deep.pt",
# "mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k.pt",
# "mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k_nonorm.pt",
# "mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_subsample0.5_10k.pt",
# "cost_predictor_weight_path": "mpnet/exported/output/cartpole_obs/cost_10k.pt",
"cost_predictor_weight_path": "mpnet/exported/output/cartpole_obs/cost_10k.pt",
"cost_to_go_predictor_weight_path": "mpnet/exported/output/cartpole_obs/cost_to_go_obs.pt",
"refine": False,
"using_one_step_cost": False,
"refine_lr": 0,
"refine_threshold": 0,
"device_id": "cuda:3",
"cost_reselection": False,
"number_of_iterations": 100000,
"weights_array": [1, 1, 1, 0.5],
'max_planning_time': 50,
'shm_max_steps': 40
}
cuda_batch_params = {
'solver_type' : "cem",
'n_problem' : 1,
'n_sample': 32,
'n_elite': 2,
'n_t': 1,
'max_it': 5,
'converge_r': 1e-1,
'dt': 2e-3,
'mu_u': [0],
'sigma_u': [400],
'mu_t': 0.4,
'sigma_t': 0.5,
't_max': 1,
'verbose': False,#True,#
'step_size': 1,
"goal_radius": 1.5,
"sst_delta_near": .6,
"sst_delta_drain": .3,
"goal_bias": 0.05,
"width": 4,
"hybrid": False,
"hybrid_p": 0.0,
"cost_samples": 5,
"mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k_external_small_model.pt",
#"mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k_external_v2_deep.pt",
# "mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k.pt",
# "mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_10k_nonorm.pt",
# "mpnet_weight_path":"mpnet/exported/output/cartpole_obs/mpnet_subsample0.5_10k.pt",
"cost_predictor_weight_path": "mpnet/exported/output/cartpole_obs/cost_10k.pt",
"cost_to_go_predictor_weight_path": "mpnet/exported/output/cartpole_obs/cost_to_go_obs.pt",
"refine": False,
"using_one_step_cost": False,
"refine_lr": 0.0,
"refine_threshold": 0.0,
"device_id": "cuda:0",
"cost_reselection": False,
"number_of_iterations": 40000,
"weights_array": [1, 1, 1, .5],
'max_planning_time': 50,
'shm_max_steps': 40
}
return cuda_batch_params
| [
"you@example.com"
] | you@example.com |
5d8565f123ea80979f9cd6a4454521fd2ddff15c | b0de612c2f7d03399c0d02c5aaf858a72c9ad818 | /armi/nuclearDataIO/cccc/tests/test_rzflux.py | 93771c4e863ba214363f58516bdda65027c1eb5c | [
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | wangcj05/armi | 2007e7abf4b422caca0157fc4405b7f45fc6c118 | 8919afdfce75451b291e45ca1bc2e03c044c2090 | refs/heads/master | 2022-12-22T00:05:47.561722 | 2022-12-13T16:46:57 | 2022-12-13T16:46:57 | 277,868,987 | 0 | 0 | Apache-2.0 | 2020-07-07T16:32:40 | 2020-07-07T16:32:39 | null | UTF-8 | Python | false | false | 2,673 | py | # Copyright 2019 TerraPower, LLC
#
# 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.
"""
Test rzflux reading and writing.
"""
# pylint: disable=missing-function-docstring,missing-class-docstring,protected-access,invalid-name,no-self-use,no-method-argument,import-outside-toplevel
import os
import unittest
from armi.nuclearDataIO.cccc import rzflux
from armi.utils.directoryChangers import TemporaryDirectoryChanger
THIS_DIR = os.path.dirname(__file__)
# This RZFLUX was made by DIF3D 11 in a Cartesian test case.
SIMPLE_RZFLUX = os.path.join(THIS_DIR, "fixtures", "simple_cartesian.rzflux")
class TestRzflux(unittest.TestCase):
"""Tests the rzflux class"""
def test_readRzflux(self):
"""Ensure we can read a RZFLUX file."""
flux = rzflux.readBinary(SIMPLE_RZFLUX)
self.assertEqual(
flux.groupFluxes.shape, (flux.metadata["NGROUP"], flux.metadata["NZONE"])
)
def test_writeRzflux(self):
"""Ensure that we can write a modified RZFLUX file."""
with TemporaryDirectoryChanger():
flux = rzflux.readBinary(SIMPLE_RZFLUX)
rzflux.writeBinary(flux, "RZFLUX2")
self.assertTrue(binaryFilesEqual(SIMPLE_RZFLUX, "RZFLUX2"))
# perturb off-diag item to check row/col ordering
flux.groupFluxes[2, 10] *= 1.1
flux.groupFluxes[12, 1] *= 1.2
rzflux.writeBinary(flux, "RZFLUX3")
flux2 = rzflux.readBinary("RZFLUX3")
self.assertAlmostEqual(flux2.groupFluxes[12, 1], flux.groupFluxes[12, 1])
def test_rwAscii(self):
"""Ensure that we can read/write in ascii format."""
with TemporaryDirectoryChanger():
flux = rzflux.readBinary(SIMPLE_RZFLUX)
rzflux.writeAscii(flux, "RZFLUX.ascii")
flux2 = rzflux.readAscii("RZFLUX.ascii")
self.assertTrue((flux2.groupFluxes == flux.groupFluxes).all())
def binaryFilesEqual(fn1, fn2):
"""True if two files are bytewise identical."""
with open(fn1, "rb") as f1, open(fn2, "rb") as f2:
for byte1, byte2 in zip(f1, f2):
if byte1 != byte2:
return False
return True
| [
"noreply@github.com"
] | wangcj05.noreply@github.com |
f4ef0d969896be33f79af58aaa8261cb2e9aec27 | f112dfe38732f131156556ab724e2b9a01d317ae | /week6/12-olimp-results.py | 84111b344ca01350a77d270fb1eafcce9b46a3ef | [] | no_license | pharick/python-coursera | 2a92bf467e0ddd35a573ea4e29fff9a37e45bd24 | 3e24ac9385eada126e7c4753f71cd38181987fbf | refs/heads/master | 2020-04-04T03:44:45.067099 | 2019-03-20T07:10:22 | 2019-03-20T07:10:22 | 155,724,086 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 227 | py | n = int(input())
students = []
for i in range(n):
student = input().split()
students.append((student[0], int(student[1])))
students.sort(key=lambda student: -student[1])
for student in students:
print(student[0])
| [
"artemforkunov@gmail.com"
] | artemforkunov@gmail.com |
70dd6b6891e4793418f9b327dcf8ddb1de563ef7 | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/clouds_20200703183549.py | deecd69a4f52fe13e3dd7c9a278d545d91b636a2 | [] | no_license | MaryanneNjeri/pythonModules | 56f54bf098ae58ea069bf33f11ae94fa8eedcabc | f4e56b1e4dda2349267af634a46f6b9df6686020 | refs/heads/master | 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 439 | py | def jumpingClouds(c):
i = 0
jumps = 0
while i < len(c)-2:
if c[i] == 0 and c[i+2] == 0:
print('here')
print('c---->',c[i],'i-->',i)
jumps +=1
i +=2
elif c[i] == 0 and c[i+1] == 0:
print('here2')
print('c---->',c[i],'i-->',i)
jumps +=1
i +=1
print(jumps)
jumpingClouds([0 ,0, 1, 0, 0, 1, 0]) | [
"mary.jereh@gmail.com"
] | mary.jereh@gmail.com |
2dda85a9ba04d01eb6f79efbf26e1aa3f5fe73a8 | b23f9b54f622032e71a80a497ca2d7dbd48469ad | /setup.py | d7560750ca56a0500f4ae92ea7dba81932711c29 | [] | no_license | h4ck3rm1k3/pycparserext | 15cf0a02429f3fd6bad977cd612e74ca7b20b891 | 489fd9c4804e7b3f17760b0800cf81a930a2ec7e | refs/heads/master | 2021-01-21T08:32:39.114178 | 2016-04-03T05:22:38 | 2016-04-03T05:22:38 | 55,293,358 | 0 | 0 | null | 2016-04-02T12:29:40 | 2016-04-02T12:29:40 | null | UTF-8 | Python | false | false | 893 | py | #!/usr/bin/env python
# -*- coding: latin1 -*-
from setuptools import setup
setup(name="pycparserext",
version="2016.1",
description="Extensions for pycparser",
long_description=open("README.rst", "r").read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Other Audience',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Utilities',
],
install_requires=[
"ply>=3.4",
"pycparser>=2.14",
],
author="Andreas Kloeckner",
url="http://pypi.python.org/pypi/pycparserext",
author_email="inform@tiker.net",
license="MIT",
packages=["pycparserext"])
| [
"inform@tiker.net"
] | inform@tiker.net |
82f795bf9a7875dc84a5097c204ab284d9770801 | d232b3aa9449ad13a5b33f141d432c5a9f46aa7e | /Day3-1.py | bd0c791662db9a061f1774f4ef8d4bda64cf922f | [] | no_license | stephanie19950405/Python200805 | e75ba082faa65367a977652e65b2088e3d4669c5 | ad8a71874b0919aad49e6f9fe5cf214121a050a7 | refs/heads/master | 2022-11-26T02:59:39.331128 | 2020-08-05T08:41:29 | 2020-08-05T08:41:29 | 285,170,878 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 172 | py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 5 09:26:48 2020
@author: AE401
"""
for i in range(1,10):
for j in range(1,10):
print(i,"x",j,"=",i*j) | [
"noreply@github.com"
] | stephanie19950405.noreply@github.com |
c961d180e49b2f37329b439a63ed3caf39182499 | 61febabc6aa34b7c47208aa7be5dfca88287ddaf | /Ch. 5 If Statements/Alien_Colors_2.py | f3d2b2cede94db66aee11d3245b9b9571a6284d5 | [] | no_license | chrisstophere/Python-Crash-Course | 4be7262acc2ff8ad26d99aceb028c25e4c7f9b0b | 702c44734e93df68ec55831626fb7a7a22ce2b8d | refs/heads/master | 2021-05-24T10:31:54.679224 | 2020-05-07T21:10:09 | 2020-05-07T21:10:09 | 253,520,738 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 215 | py | alien_color = 'red'
if alien_color == 'green':
print(f"You shot the {alien_color} alien. You earned 5 points.")
elif alien_color != 'green':
print(f"You shot the {alien_color} alien. You earned 10 points.") | [
"chris@ewentech.com"
] | chris@ewentech.com |
4bbf1ff6013d7a48ce63d817454fb8940a26487f | 7d23fff61314842d6d7d8ca106382d163a04f139 | /watch/models.py | 3a423333ca2230cec766903c543e4a2e444032de | [
"MIT"
] | permissive | GeGe-K/Neighbourhood | 8b71bc789a72d34769436a5a912ffde87b3c014b | 366667dff147141558732e5c6f5004fe4cff221e | refs/heads/master | 2022-12-09T18:26:27.536704 | 2019-01-16T14:13:37 | 2019-01-16T14:13:37 | 165,236,886 | 0 | 0 | MIT | 2022-12-08T01:32:31 | 2019-01-11T12:00:41 | Python | UTF-8 | Python | false | false | 3,462 | py | from django.db import models
from django.contrib.auth.models import User
import datetime as dt
# Create your models here.
class Location(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Neighbourhood(models.Model):
'''
Neighbourhood class has the following properties
'''
neighbourhood_name = models.CharField(max_length = 30)
neighborhood_location = models.ForeignKey('Location', on_delete = models.CASCADE, null = True, blank =True)
occupants = models.IntegerField(null = True)
admin = models.ForeignKey(User, on_delete = models.CASCADE)
def create_neighbourhood(self):
self.save
def delete_neighbourhood(self):
self.delete()
def __str__(self):
return self.neighbourhood_name
@classmethod
def find_neighbourhood(cls, neighbourhood_id):
neighbourhood = cls.objects.get(id = neighbourhood_id)
return neighbourhood
def update_nighbourhood(self):
self.save()
def update_occupants(self):
self.occupants +=1
self.save()
class UserProfile(models.Model):
'''
UserProfile class has the following properties
'''
first_name = models.CharField(max_length=20, blank=True)
last_name = models.CharField(max_length=20,blank=True)
email = models.EmailField()
user = models.ForeignKey(User,on_delete=models.CASCADE)
neighborhood = models.ForeignKey('Neighbourhood', on_delete=models.CASCADE, null=True, blank=True)
def assign_neighbourhood(self, neighbourhood):
self.neighbourhood = neighborhood
self.save()
def save_profile(self):
self.save()
def delete_profile(self):
self.delete()
def __str__(self):
return f'{self.user.username}'
class Business(models.Model):
'''
Business class has the following properties
'''
business_name = models.CharField(max_length = 50)
owner = models.ForeignKey(User, on_delete = models.CASCADE)
business_neighbourhood = models.ForeignKey(
'Neighbourhood', on_delete = models.CASCADE)
email = models.EmailField()
def create_business(self):
self.save()
def delete_business(self):
self.delete()
@classmethod
def find_business(cls, business_id):
business = cls.objects.get(id = business_id)
return business
def update_business(self, business_name):
self.name = business_name
self.save()
def __str__(self):
return self.business_name
class EmergencyContacts(models.Model):
'''
Emergency contact class has the following properties
'''
name = models.CharField(max_length = 30)
contacts = models.CharField(max_length = 20)
email = models.EmailField()
neighbourhood_contact = models.ForeignKey(
'Neighbourhood', on_delete = models.CASCADE)
def __str__(self):
return f'{self.name},{self.email}'
class Post(models.Model):
'''
Post class has the following properties
'''
title = models.CharField(max_length=40)
post_description = models.TextField(blank = True)
posted_by = models.ForeignKey(User, on_delete = models.CASCADE)
post_hood = models.ForeignKey('Neighbourhood', on_delete = models.CASCADE)
posted_on = models.DateTimeField(auto_now_add = True)
def __str__(self):
return f'{self.title},{self.post_hood.neighbourhood_name}'
| [
"gloriagivondo@gmail.com"
] | gloriagivondo@gmail.com |
f0ec7fdedb65b26187793048fe26edf04bd719b9 | b06b79983d2dbe596e9ad2171694f9124cdc7fc1 | /Python/memoryExample.py | 432ad951664f2b50a485e499b2e98253b74d72f5 | [] | no_license | ljthink/TDC-2 | 87e89124eb08c3b181f0aca2bed4a5beca43dd88 | b09ed8783a2401e8eaa35eb99a3bff79aaa382c3 | refs/heads/master | 2022-11-19T06:44:14.588905 | 2020-07-23T00:24:32 | 2020-07-23T00:24:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 702 | py | from QuartusMemory import QuartusMemory
q = QuartusMemory()
# Find index of instance named RAM1
inst = q.find_instance('RAM1')
# Read memory from device
arr = q.read_mem(inst,True)
# Print contents of address 0x04
print('Arr1:')
for k in arr[4]:
print(str(k) + ' ',end='')
print()
# Copy the array and change one of the bits in 0x04
arr2 = arr
arr2[4][1] = 1
# Print the new array
print('Arr2:')
for k in arr2[4]:
print(str(k) + ' ',end='')
print()
# Write the memory to the device
q.write_mem(inst,arr2,True)
# Read memory into a new array
arr3 = q.read_mem(inst,True)
# Print to confirm that memory was changed
print('Arr3:')
for k in arr3[4]:
print(str(k) + ' ',end='')
print()
| [
"me@lramsey.com"
] | me@lramsey.com |
cc578e23762a3824d2011e2c493327ac6fa7534f | 40361071089b4f243962c5dd2e0bd6144f76acbd | /cell_count_utils.py | 769ebe2450f13b3cdaf08e2d1dc651be248d2d58 | [] | no_license | liaorongfan/cell-counting | d555d06e8113ffc2dcf4c19e1e4003a9c61f8fac | 0f0640225fa3f6884efdd315158bf14dc47bedc1 | refs/heads/main | 2023-05-05T20:17:46.539954 | 2021-05-23T14:39:40 | 2021-05-23T14:39:40 | 370,076,359 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,942 | py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def plt_show(img, figsize=(24, 6), gray=True):
"""默认画灰度图"""
plt.figure(figsize=figsize)
plt.grid(False)
if gray:
plt.imshow(img, 'gray')
else:
plt.imshow(img)
plt.show()
pass
def plt_show_(img, figsize=(24, 6), gray=True):
"""默认画灰度图"""
plt.figure(figsize=figsize)
plt.grid(False)
if gray:
plt.imshow(img, 'gray')
else:
plt.imshow(img)
plt.show()
pass
def prt(*args):
# print(*args)
pass
class SegCircle:
"""找出图片中的培养皿并擦除其他部分"""
def __call__(self, input_img):
"""
args:
input_img:array; rgb格式图像
ret:
seged_img:ndarray; 检测出的培养皿图片,格式RGB,
尺寸固定到(nh, nw) = (900, 900 * (w / h))
"""
# img = cv2.imread(img_path)
img = self.resize(input_img)
seged_img = self._seg_circle(img)
return seged_img
def _seg_circle(self, img):
"""
args:
img:ndarray; rgb格式图片
"""
img_hw = img.shape[:2]
circles = self.detect_circle(img) # ; print('r = ', circles[0][2])
center_hw, radius = (circles[0][1], circles[0][0]), (circles[0][2]) # 圆心格式:(y, x) (h, w) (行, 列)
mask = self.dis_map(img_hw, center_hw, radius)
mask = mask.astype(np.uint8)
res = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)
# plt_show(res, figsize=(12,12))
return res
@staticmethod
def detect_circle(img):
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gaussian = cv2.GaussianBlur(gray, (5, 5), 0)
circles_ = cv2.HoughCircles(
gaussian, cv2.HOUGH_GRADIENT, dp=1, minDist=500,
param1=200, param2=75, minRadius=100, maxRadius=500
)
circles = circles_[0, :, :]
circles = np.uint16(np.around(circles))
return circles
@staticmethod
def dis_map(img_shape, center, r):
img_h, img_w = img_shape
ch, cw = center
tensor_h, tensor_w = np.meshgrid(np.arange(img_h), np.arange(img_w), indexing='ij')
tensor = np.zeros((img_h, img_w, 2))
tensor_mask = np.zeros((img_h, img_w))
tensor[:, :, 0] = tensor_h
tensor[:, :, 1] = tensor_w
distances = np.sqrt((tensor[:, :, 0] - ch) ** 2 + (tensor[:, :, 1] - cw) ** 2)
tensor_mask[distances <= r] = 255
return tensor_mask
@staticmethod
def resize(img, fixed_size=900):
h, w, _ = img.shape # opencv.readimg 格式(h, w)
nh, nw = fixed_size, int(fixed_size * (w / h))
img_resize = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_CUBIC) # resize格式(w, h)
return img_resize
def count_metric(count_num, labeled_num):
count_num = np.array(count_num)
labeled_num = np.array(labeled_num)
error = np.abs(count_num - labeled_num) / labeled_num
error = np.round(error, 2)
return error
def count_record(config, batch, label, count_num, error):
with open("count_log.txt", "a") as f:
mean_error = np.array(error).mean().round(3)
f.write("Image list:" + str(batch) + "\n")
f.write("config:\n")
f.write("min_cell_area:" + str(config["min_cell_area"]) + "|" +
"max_cell_area:" + str(config["max_cell_area"]) + "\n")
f.write("hsv_low:" + str(config["hsv_low"]) + "|" +
"hsv_up:" + str(config["hsv_up"]) + "\n")
f.write("\tmin_cell_area:" + str(config["min_cell_area"]) + "|" +
"good_cell_area:" + str(config["good_cell_area"]) + "\n")
f.write("\tadjust_ratio_low:" + str(config["adjust_ratio_low"]) + "|" +
"adjust_ratio_up:" + str(config["adjust_ratio_up"]) + "\n")
f.write("cell label num:" + str(label) + "\n")
f.write("cell count num:" + str(count_num) + "\n")
f.write("cell count err:" + str(error) + '\nmean error:' + str(mean_error) + "\n\n")
def hsv_dist_plot(hsv):
plt.figure(figsize=(15, 8))
sns.distplot(hsv[:, :, 0].flatten(), color="Y")
sns.distplot(hsv[:, :, 1].flatten(), color="G")
sns.distplot(hsv[:, :, 2].flatten(), color="Black")
plt.show()
def hsv_select(img, hsv, h=[0, 255], s=[0, 255], v=[0, 255], show_mask=False):
"""拿到h[], s[], v[]数值范围内的图像"""
low_purple = np.array([h[0], s[0], v[0]]) # [h, s, v]
high_purple = np.array([h[1], s[1], v[1]])
mask = cv2.inRange(hsv, low_purple, high_purple)
# print(mask.shape) # 二维 二值(0/255)
if show_mask:
plt_show(mask, figsize=(15, 15))
masked_image = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask)
plt_show(masked_image, figsize=(15, 15))
return masked_image
| [
"15670381505@163.com"
] | 15670381505@163.com |
701090d667fe4a9f5daf26aa08d32a2d7dde0dcb | cda5f9506ff9a05ca6cc5c6fd29a56bb645f03e3 | /Grasshopper-Terminal-game-combat-function.py | 1265b0149a59ea7ccf489495107d14273b4188b1 | [] | no_license | zecollokaris/toy-problems | bc28799f41cdbddfa5a4a56c613031b3f52430bc | 66f6462ace04afbe025d90956573ef295d66f41f | refs/heads/master | 2020-03-25T00:20:17.099894 | 2018-08-04T20:12:16 | 2018-08-04T20:12:16 | 143,180,896 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,004 | py | #############################################################################################################
######Question######
# Create a combat function that takes the player's current health and the amount of damage recieved,
# and returns the player's new health.
# Health can't be less than 0.
#############################################################################################################
######BDD######
# 1. Subtract health - damage
# 2. If health - damge is less than 0 we must return 0
# 3. return health - damage
#############################################################################################################
######Solution#####
def combat(health,damage):
if health-damage < 0:
return 0
return health - damage
#############################################################################################################
############################################################################################################# | [
"collo.kariss@gmail.com"
] | collo.kariss@gmail.com |
f974ed4dfce8a8ce9c6813f917c8078319276785 | d6de09317cf3aeba4af26ae9ebacb3669f85899b | /oAuth/venv/bin/pip3 | 9c8aec44a34ad396320fcc678c1c0230d62a0182 | [] | no_license | Vaibhav-Kotadiya/Flask-oAuth | 66a0fd57ab3242cc81ecdef250d69b166248ff59 | 817ef470328cd5341fdb7ffa0354b3574d3dd936 | refs/heads/master | 2022-12-09T07:02:49.437622 | 2020-09-15T16:03:54 | 2020-09-15T16:03:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 411 | #!/Users/mac/PycharmProjects/Flask-oAuth/oAuth/venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3')()
)
| [
"mac@MACs-MacBook-Pro.local"
] | mac@MACs-MacBook-Pro.local | |
3ef2026eb83017aa5c24665674b8d15767fb2008 | 51d8f003828d6ee6e6611f0e133b1e35cf400601 | /ipaxi/ixbr_api/core/tests/use_cases_tests/test_service_use_case.py | 830992ce3f08fe190f0264ea26fd19099f6e8a39 | [
"Apache-2.0"
] | permissive | tatubola/xpto | 23b5f7a42c13c7d39eb321e52b9b4b2d1ef76c4c | 6ed8cec23b06bccb1edf57e6b67af017f9a162d3 | refs/heads/master | 2020-04-02T11:05:24.560009 | 2018-10-23T17:41:10 | 2018-10-23T17:41:10 | 154,370,519 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,817 | py | from unittest.mock import patch
from django.core.exceptions import ValidationError
from django.test import TestCase
from model_mommy import mommy
from ...models import ContactsMap, MLPAv4, Tag
from ...use_cases.service_use_case import delete_service_use_case
from ..login import DefaultLogin
class ServiceUseCaseTest(TestCase):
def setUp(self):
DefaultLogin.__init__(self)
p = patch('ixbr_api.core.models.HistoricalTimeStampedModel.full_clean')
p.start()
self.addCleanup(p.stop)
p = patch('ixbr_api.core.models.create_all_ips')
p.start()
self.addCleanup(p.stop)
p = patch('ixbr_api.core.models.create_tag_by_channel_port')
p.start()
self.addCleanup(p.stop)
def test_delete_service_use_case(self):
tag = mommy.make(Tag, status='PRODUCTION')
contacts_map = mommy.make(ContactsMap)
service_mlpav4 = mommy.make(MLPAv4, tag=tag, make_m2m=True)
service_mlpav4.asn.contactsmap_set.add(contacts_map)
self.assertEqual(MLPAv4.objects.filter(pk=service_mlpav4.pk).count(), 1)
delete_service_use_case(pk=service_mlpav4.pk)
self.assertEqual(MLPAv4.objects.filter(pk=service_mlpav4.pk).count(), 0)
def test_fail_delete_service_use_case(self):
tag = mommy.make(Tag, status='PRODUCTION')
contacts_map = mommy.make(ContactsMap)
service_mlpav4 = mommy.make(MLPAv4, tag=tag, make_m2m=True)
service_mlpav4.asn.contactsmap_set.add(contacts_map)
self.assertEqual(MLPAv4.objects.filter(pk=service_mlpav4.pk).count(), 1)
with self.assertRaisesMessage(ValidationError, "Invalid service primary key"):
delete_service_use_case(pk=tag.pk)
self.assertEqual(MLPAv4.objects.filter(pk=service_mlpav4.pk).count(), 1)
| [
"dmoniz@nic.br"
] | dmoniz@nic.br |
89fe832ad18539d9ffcc91dc818c1d4a5827b99c | 0f2391cb82f218ed7505266c5f708725ed064427 | /roman-numerals-take-two/roman.py | d47eb096b46c40035d14e9d809a97c71d456881a | [] | no_license | tomviner/tdd-dojo | e34c6ecb1fd27113b0a0b33a5609c23d6695d226 | 3e35847b2e1d7b73132ee3a07a546abe26322e74 | refs/heads/master | 2021-01-22T02:34:06.146674 | 2014-11-25T14:07:51 | 2014-11-25T14:07:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 518 | py | """
Roman Numerals
Write a function to convert from normal numbers to Roman Numerals: e.g.
1 => I
4 => IV
7 => VII
10 => X
99 => XCIX
"""
LOOKUP_NUMERALS = (
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I'),
)
def to_roman(num):
for digit, letter in LOOKUP_NUMERALS:
if num >= digit:
return letter + (to_roman(num - digit) or '')
| [
"tom.viner@hogarthww.com"
] | tom.viner@hogarthww.com |
8b7bcd726beabde390de9d1928fa4f6a36307508 | 2e0a18c571b5f8000e9900e9a332eca5aff54f0f | /guppe/Seção 7/Deque.py | f759ccf0d293c473ffd25d117524a60bebc7daff | [] | no_license | LucasFerreiraB/Teste | bbf57e92db2bcc4795316c513959d2674252264b | d2b542aff96a27a727706df887506336062fbbda | refs/heads/master | 2022-09-27T11:38:07.755660 | 2020-06-05T18:38:22 | 2020-06-05T18:38:22 | 269,750,327 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 435 | py | """
Modulo Collections - Deque
Podemos dizer que o Deque é uma lista de alto performance.
"""
# Import
from collections import deque
# Criando deques
deq = deque('lucas')
print(deq)
# Adicionando elementos no deque
deq.append('y') # adiciona no final
print(deq)
deq.appendleft('k') # adiciona no comeco
print(deq)
# Remover elementos
print(deq.pop()) # Remove o ultimo elemento
print(deq)
print(deq.popleft())
print(deq)
| [
"lucasferreira9b@gmail.com"
] | lucasferreira9b@gmail.com |
dca84f844680918ece78d15a17c804d7d4f4dc67 | b7683c108e68ee2d28573edf55923eb34cc2f5ee | /3_Image_Processing/9_Contours/1_Intro/1_Contours_on_binary.py | 9be454d9d82d0531c5524d093ed11ff8b9fa6b0f | [] | no_license | aCuissot/openVC_win_py_tutorial | cc42ab1a1fb6eaefe5a91c7e1bb1926a776b0e01 | 7186b629747cb16f2bf42a03d2339d3dc3ea77bd | refs/heads/master | 2020-05-18T12:17:04.619047 | 2019-07-10T13:45:00 | 2019-07-10T13:45:00 | 184,403,715 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 525 | py | import numpy as np
import cv2 as cv
im = cv.imread('../../../Data/in/a.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
_, thresh = cv.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(im, contours, -1, (0, 255, 0), 3)
"""
pour ne dessiner qu'un contour, le 3e par ex:
cv.drawContours(im, contours, 2, (0, 255, 0), 3)
ou
cnt = contours[3]
cv.drawContours(img, [cnt], 0, (0,255,0), 3)
"""
cv.imshow('', im)
cv.waitKey(0)
cv.destroyAllWindows() | [
"harrypotter9752@gmail.com"
] | harrypotter9752@gmail.com |
2508cb82f30d9ebd8cad74771e679948dda148d0 | 0a5618aba3e801cbd986a3c8a02c8bfbaafddb4d | /data_utils/utils.py | 36cd93312e8cabda8dbeb6b8b3a25c5a7a9bcf00 | [] | no_license | hmcck27/ps-helper-nlp | 2f899c2ae22524e5531c78b2a257ac0a0b043c7b | 6a99aa6a91477ac35f94b1548c9e8e9b441b9b8b | refs/heads/master | 2023-08-27T22:59:05.846434 | 2021-10-28T07:14:05 | 2021-10-28T07:14:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,718 | py | import json
import torch
from pathlib import Path
class Config:
def __init__(self, json_path):
with open(json_path, mode='r') as io:
params = json.loads(io.read())
self.__dict__.update(params)
def save(self, json_path):
with open(json_path, mode='w') as io:
json.dump(self.__dict__, io, indent=4)
def update(self, json_path):
with open(json_path, mode='r') as io:
params = json.loads(io.read())
self.__dict__.update(params)
@property
def dict(self):
return self.__dict__
class CheckpointManager:
def __init__(self, model_dir):
if not isinstance(model_dir, Path):
model_dir = Path(model_dir)
self._model_dir = model_dir
def save_checkpoint(self, state, filename):
torch.save(state, self._model_dir / filename)
def load_checkpoint(self, filename):
state = torch.load(self._model_dir / filename, map_location=torch.device('cpu'))
return state
class SummaryManager:
def __init__(self, model_dir):
if not isinstance(model_dir, Path):
model_dir = Path(model_dir)
self._model_dir = model_dir
self._summary = {}
def save(self, filename):
with open(self._model_dir / filename, mode='w') as io:
json.dump(self._summary, io, indent=4)
def load(self, filename):
with open(self._model_dir / filename, mode='r') as io:
metric = json.loads(io.read())
self.update(metric)
def update(self, summary):
self._summary.update(summary)
def reset(self):
self._summary = {}
@property
def summary(self):
return self._summary | [
"backend@JK.local"
] | backend@JK.local |
5656efc34e8254aae61d10bea0f54846789da243 | 338062cc2bb422f1364fd18ad5e721f6f713907a | /30. Библиотеки Python. Встроенные модули/Классная работа/Дни рождения друзей.py | 901cba0c8631ab75c84e2788ce36d59850346786 | [] | no_license | rady1337/FirstYandexLyceumCourse | f3421d5eac7e7fbea4f5e266ebeb6479b89941cf | 0d27e452eda046ddd487d6471eeb7d9eb475bd39 | refs/heads/master | 2022-06-17T03:07:51.017888 | 2020-05-12T22:17:34 | 2020-05-12T22:17:34 | 263,459,364 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 119 | py | import datetime as dtdin = dt.datetime.now()dn = dt.timedelta(days=int(input()))print((din + dn).day, (din + dn).month) | [
"noreply@github.com"
] | rady1337.noreply@github.com |
87edc282a225d250961e93168a4da4a287edcf14 | 97f0f649b007f0ac9f7e2c7f4efdec1f06d6b154 | /decision_implementation.py | 9314086d4dd4f91519211d6d8a107c731d0b37a2 | [] | no_license | ajaymalik2592/projects | de877ea8aebde28900158a6c9a1f576caf64ccd5 | 0cabd9f85f6b056d82c28243157a06c64f45afc8 | refs/heads/master | 2020-05-14T08:24:03.121768 | 2019-04-16T16:03:59 | 2019-04-16T16:03:59 | 181,722,431 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,056 | py | import numpy as np
import math
import csv
import random
data = []
with open('shuffled_data.csv', "rt") as filereader:
fil = csv.reader(filereader, delimiter= ' ' )
for rows in fil:
data.append(rows)
formated_data = []
i = 0
for da in data:
if(i == 207):
break
i+=1
da = da[0]
da = da.split(",")
data_new = []
j = 0
for x in da:
j+=1
data_new.append(float(x))
if( j == 60):
break
if(da[-1] == 'M'):
data_new.append(1)
else:
data_new.append(0)
formated_data.append(data_new)
rows = len(formated_data)
cols = len(formated_data[0])
""" here onward analysis part on decision tree of the project, data set in list form easy to compute """
rock = 0
metal = 0
for x in formated_data:
if(x[-1] == 0):
rock += 1
else:
metal += 1
value = []
for x in range(cols - 1):
value.append(0)
for x in range(rows):
for y in range(cols - 1):
value[y] += formated_data[x][y]
distributed, min_max, gain = [], [], []
for x in range(cols ):
distributed.append([0, 0])
min_max.append([100, 0])
if(cols-1 == x):
break
gain.append([1, 0, 0])
test_rows = 170
for x in range(int(test_rows)):
for y in range(cols ):
if(y != cols-1):
distributed[y][formated_data[x][-1]] += formated_data[x][y]
min_max[y][0] = min(min_max[y][0], formated_data[x][y])
min_max[y][1] = max(min_max[y][1], formated_data[x][y])
else:
distributed[ y ][formated_data[x] [ -1 ] ] += 1
matels_in_test = distributed[cols-1][1]
solid_in_test = distributed[cols -1][0]
def gain_ratio(di):
r = 0
if(di[0][0] == 0 or di[0][1] == 0):
pass
else:
r -= di[0][0] * math.log( di[0][0]/ (di[0][0] + di[0][1]) , 2) + di[0][1] * math.log(di[0][1]/ (di[0][0] + di[0][1]) , 2)
if(di[1][0] ==0 or di[1][1] == 0):
pass
else:
r -= di[1][0] * math.log( di[1][0]/ (di[1][0] + di[1][1]) , 2) + di[0][1] * math.log(di[1][1]/ (di[1][0] + di[1][1]) , 2)
p1 = sum(di[0])
p2 = sum(di[1])
print(p1 , " " , p2)
total = p1 + p2
p = 0
if(p1 != 0):
p -= p1 * math.log(p1 / total , 2)
if(p2 != 0):
p -=p2 * math.log(p2 / total,2 )
if(p == 0):
return r * pow(10,100)
return (r / test_rows) / p
for x in range(cols -1):
l = min_max[x][0]
r = min_max[x][1]
i = l * 10000
temp = []
while(i <= 10000 * r):
mid = i / 10000
i += 1
divided = [[0, 0], [0, 0]]
for y in range(test_rows):
if(formated_data[y][x] >= mid):
divided[1][formated_data[y][-1]] += 1
else:
divided[0][formated_data[y][-1]] += 1
temp.append( [gain_ratio(divided), mid] )
i = 100000
index = 0
for xx in temp:
if(xx[0] < i):
i = xx[0]
index = xx[1]
gain[x][0], gain[x][1], gain[x][2] = i, x, index
i = 0
equalize = 0
for x in gain:
equalize = max(equalize, x[0])
final_weighted_for_decisiontree = []
for x in range(cols - 1 ):
final_weighted_for_decisiontree.append([ equalize / gain[x][0] ,gain[x][2] ] )
print(final_weighted_for_decisiontree)
i = 0
aa = ['R', 'M']
tr = 0
tp , fn , fp , tn = 0 ,0, 0, 0
output = []
for index in range(170, 207):
i = 1
j = 1
for x in range(cols -1):
if(formated_data[index][x] >= final_weighted_for_decisiontree[x][1]):
i *= final_weighted_for_decisiontree[x][0]
else:
j *= final_weighted_for_decisiontree[x][0]
if i < j :
if("R" == aa[formated_data[index][-1]] ):
tn += 1
tr += 1
output.append(1)
else : fp += 1; output.append(0)
else:
if("M" == aa[formated_data[index][-1]]):
tr += 1
tp += 1
output.append(1)
else : fn += 1; output.append(0)
print(output)
print(tp, fn)
print(fp, tn)
print(tr * 100/ (207 - 171)) | [
"noreply@github.com"
] | ajaymalik2592.noreply@github.com |
eea41913ddcd22156013f964a4b6b70d017450aa | 8ea896e975fdb967f013e2b69d453df8881eb8f9 | /spark-2.x/src/main/python/ml/logistic_regression_summary_example.py | 26882a8dc7de5dbc1caf79a70959595925d295f6 | [
"Apache-2.0"
] | permissive | lhfei/spark-in-action | 1d0df5a22230e458be2583066537c09d20a1b98b | 0bf915588f4aa36b17b89a2a8f4a055b342e2295 | refs/heads/master | 2022-07-15T05:43:02.805743 | 2020-08-25T07:33:59 | 2020-08-25T07:33:59 | 33,342,589 | 6 | 3 | Apache-2.0 | 2022-06-27T16:13:02 | 2015-04-03T02:36:44 | Scala | UTF-8 | Python | false | false | 2,508 | 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.
#
"""
An example demonstrating Logistic Regression Summary.
Run with:
bin/spark-submit examples/src/main/python/ml/logistic_regression_summary_example.py
"""
from __future__ import print_function
# $example on$
from pyspark.ml.classification import LogisticRegression
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession \
.builder \
.appName("LogisticRegressionSummary") \
.getOrCreate()
# Load training data
training = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")
lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)
# Fit the model
lrModel = lr.fit(training)
# $example on$
# Extract the summary from the returned LogisticRegressionModel instance trained
# in the earlier example
trainingSummary = lrModel.summary
# Obtain the objective per iteration
objectiveHistory = trainingSummary.objectiveHistory
print("objectiveHistory:")
for objective in objectiveHistory:
print(objective)
# Obtain the receiver-operating characteristic as a dataframe and areaUnderROC.
trainingSummary.roc.show()
print("areaUnderROC: " + str(trainingSummary.areaUnderROC))
# Set the model threshold to maximize F-Measure
fMeasure = trainingSummary.fMeasureByThreshold
maxFMeasure = fMeasure.groupBy().max('F-Measure').select('max(F-Measure)').head()
bestThreshold = fMeasure.where(fMeasure['F-Measure'] == maxFMeasure['max(F-Measure)']) \
.select('threshold').head()['threshold']
lr.setThreshold(bestThreshold)
# $example off$
spark.stop()
| [
"lhfeilaile@gmail.com"
] | lhfeilaile@gmail.com |
a6262547823f4b422a3298d7263130a495f95dc7 | 14825e285a5637d0c7e981e3c32c3b961e89f981 | /Identification/Rider.py | e6a641da3302e9d3b322b635a0a257877b712f91 | [] | no_license | simohn/Ride_on_Time | ef43627f6b65732309c41bf51692066e7920f8fc | 7e9ca19ba1c4c82f8423819b61345c686affb454 | refs/heads/master | 2020-04-21T16:31:26.765286 | 2019-08-27T18:10:28 | 2019-08-27T18:10:28 | 169,704,386 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,571 | py | # Code written by Simon Schauppenlehner
# Last change: 22.06.2019
import numpy as np
class Rider:
# Private class variable
_unique_id = 1000
# Public methods
def __init__(self, id=-1):
if id == -1:
self.id = self._get_unique_id()
else:
self.id = id
self.images = []
self.features_average = []
self.features_variance = []
def add_image(self, image):
self.images.append(image)
def get_total_distance(self, image):
total_dist = np.linalg.norm(self.get_features_average()-image.get_features())
return total_dist
def get_id(self):
return self.id
def calc_features_average(self):
images_cnt = len(self.images)
average = np.zeros(2048)
for image in self.images:
average += image.get_features()
average = np.true_divide(average, images_cnt)
self.features_average = average
def calc_features_variance(self):
images_cnt = len(self.images)
variance = np.zeros(2048)
for image in self.images:
variance += np.power((image.get_features()-self.features_average), 2)
variance = np.true_divide(variance, images_cnt)
self.features_variance = variance
def get_features_average(self):
return self.features_average
def get_features_variance(self):
return self.features_variance
# Private methods
@classmethod
def _get_unique_id(cls):
cls._unique_id += 1
return cls._unique_id - 1
| [
"schauppinger@gmail.com"
] | schauppinger@gmail.com |
3da46091f694239b44ce3c59e315748ab9fcae39 | 09efb7c148e82c22ce6cc7a17b5140aa03aa6e55 | /env/lib/python3.6/site-packages/pandas/tests/groupby/test_filters.py | 2ce04fc77408301e12a3a44d30366dafee4d3aad | [
"MIT"
] | permissive | harryturr/harryturr_garmin_dashboard | 53071a23b267116e1945ae93d36e2a978c411261 | 734e04f8257f9f84f2553efeb7e73920e35aadc9 | refs/heads/master | 2023-01-19T22:10:57.374029 | 2020-01-29T10:47:56 | 2020-01-29T10:47:56 | 235,609,069 | 4 | 0 | MIT | 2023-01-05T05:51:27 | 2020-01-22T16:00:13 | Python | UTF-8 | Python | false | false | 20,388 | py | import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Series, Timestamp
import pandas.util.testing as tm
def test_filter_series():
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.Series([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.Series([20, 22, 24], index=[2, 4, 5])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
tm.assert_series_equal(grouped.filter(lambda x: x.mean() < 10), expected_odd)
tm.assert_series_equal(grouped.filter(lambda x: x.mean() > 10), expected_even)
# Test dropna=False.
tm.assert_series_equal(
grouped.filter(lambda x: x.mean() < 10, dropna=False),
expected_odd.reindex(s.index),
)
tm.assert_series_equal(
grouped.filter(lambda x: x.mean() > 10, dropna=False),
expected_even.reindex(s.index),
)
def test_filter_single_column_df():
df = pd.DataFrame([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.DataFrame([20, 22, 24], index=[2, 4, 5])
grouper = df[0].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
tm.assert_frame_equal(grouped.filter(lambda x: x.mean() < 10), expected_odd)
tm.assert_frame_equal(grouped.filter(lambda x: x.mean() > 10), expected_even)
# Test dropna=False.
tm.assert_frame_equal(
grouped.filter(lambda x: x.mean() < 10, dropna=False),
expected_odd.reindex(df.index),
)
tm.assert_frame_equal(
grouped.filter(lambda x: x.mean() > 10, dropna=False),
expected_even.reindex(df.index),
)
def test_filter_multi_column_df():
df = pd.DataFrame({"A": [1, 12, 12, 1], "B": [1, 1, 1, 1]})
grouper = df["A"].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
expected = pd.DataFrame({"A": [12, 12], "B": [1, 1]}, index=[1, 2])
tm.assert_frame_equal(
grouped.filter(lambda x: x["A"].sum() - x["B"].sum() > 10), expected
)
def test_filter_mixed_df():
df = pd.DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()})
grouper = df["A"].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
expected = pd.DataFrame({"A": [12, 12], "B": ["b", "c"]}, index=[1, 2])
tm.assert_frame_equal(grouped.filter(lambda x: x["A"].sum() > 10), expected)
def test_filter_out_all_groups():
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
tm.assert_series_equal(grouped.filter(lambda x: x.mean() > 1000), s[[]])
df = pd.DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()})
grouper = df["A"].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
tm.assert_frame_equal(grouped.filter(lambda x: x["A"].sum() > 1000), df.loc[[]])
def test_filter_out_no_groups():
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
filtered = grouped.filter(lambda x: x.mean() > 0)
tm.assert_series_equal(filtered, s)
df = pd.DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()})
grouper = df["A"].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
filtered = grouped.filter(lambda x: x["A"].mean() > 0)
tm.assert_frame_equal(filtered, df)
def test_filter_out_all_groups_in_df():
# GH12768
df = pd.DataFrame({"a": [1, 1, 2], "b": [1, 2, 0]})
res = df.groupby("a")
res = res.filter(lambda x: x["b"].sum() > 5, dropna=False)
expected = pd.DataFrame({"a": [np.nan] * 3, "b": [np.nan] * 3})
tm.assert_frame_equal(expected, res)
df = pd.DataFrame({"a": [1, 1, 2], "b": [1, 2, 0]})
res = df.groupby("a")
res = res.filter(lambda x: x["b"].sum() > 5, dropna=True)
expected = pd.DataFrame({"a": [], "b": []}, dtype="int64")
tm.assert_frame_equal(expected, res)
def test_filter_condition_raises():
def raise_if_sum_is_zero(x):
if x.sum() == 0:
raise ValueError
else:
return x.sum() > 0
s = pd.Series([-1, 0, 1, 2])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
msg = "the filter must return a boolean result"
with pytest.raises(TypeError, match=msg):
grouped.filter(raise_if_sum_is_zero)
def test_filter_with_axis_in_groupby():
# issue 11041
index = pd.MultiIndex.from_product([range(10), [0, 1]])
data = pd.DataFrame(np.arange(100).reshape(-1, 20), columns=index, dtype="int64")
result = data.groupby(level=0, axis=1).filter(lambda x: x.iloc[0, 0] > 10)
expected = data.iloc[:, 12:20]
tm.assert_frame_equal(result, expected)
def test_filter_bad_shapes():
df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
s = df["B"]
g_df = df.groupby("B")
g_s = s.groupby(s)
f = lambda x: x
msg = "filter function returned a DataFrame, but expected a scalar bool"
with pytest.raises(TypeError, match=msg):
g_df.filter(f)
msg = "the filter must return a boolean result"
with pytest.raises(TypeError, match=msg):
g_s.filter(f)
f = lambda x: x == 1
msg = "filter function returned a DataFrame, but expected a scalar bool"
with pytest.raises(TypeError, match=msg):
g_df.filter(f)
msg = "the filter must return a boolean result"
with pytest.raises(TypeError, match=msg):
g_s.filter(f)
f = lambda x: np.outer(x, x)
msg = "can't multiply sequence by non-int of type 'str'"
with pytest.raises(TypeError, match=msg):
g_df.filter(f)
msg = "the filter must return a boolean result"
with pytest.raises(TypeError, match=msg):
g_s.filter(f)
def test_filter_nan_is_false():
df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
s = df["B"]
g_df = df.groupby(df["B"])
g_s = s.groupby(s)
f = lambda x: np.nan
tm.assert_frame_equal(g_df.filter(f), df.loc[[]])
tm.assert_series_equal(g_s.filter(f), s[[]])
def test_filter_against_workaround():
np.random.seed(0)
# Series of ints
s = Series(np.random.randint(0, 100, 1000))
grouper = s.apply(lambda x: np.round(x, -1))
grouped = s.groupby(grouper)
f = lambda x: x.mean() > 10
old_way = s[grouped.transform(f).astype("bool")]
new_way = grouped.filter(f)
tm.assert_series_equal(new_way.sort_values(), old_way.sort_values())
# Series of floats
s = 100 * Series(np.random.random(1000))
grouper = s.apply(lambda x: np.round(x, -1))
grouped = s.groupby(grouper)
f = lambda x: x.mean() > 10
old_way = s[grouped.transform(f).astype("bool")]
new_way = grouped.filter(f)
tm.assert_series_equal(new_way.sort_values(), old_way.sort_values())
# Set up DataFrame of ints, floats, strings.
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
N = 1000
random_letters = letters.take(np.random.randint(0, 26, N))
df = DataFrame(
{
"ints": Series(np.random.randint(0, 100, N)),
"floats": N / 10 * Series(np.random.random(N)),
"letters": Series(random_letters),
}
)
# Group by ints; filter on floats.
grouped = df.groupby("ints")
old_way = df[grouped.floats.transform(lambda x: x.mean() > N / 20).astype("bool")]
new_way = grouped.filter(lambda x: x["floats"].mean() > N / 20)
tm.assert_frame_equal(new_way, old_way)
# Group by floats (rounded); filter on strings.
grouper = df.floats.apply(lambda x: np.round(x, -1))
grouped = df.groupby(grouper)
old_way = df[grouped.letters.transform(lambda x: len(x) < N / 10).astype("bool")]
new_way = grouped.filter(lambda x: len(x.letters) < N / 10)
tm.assert_frame_equal(new_way, old_way)
# Group by strings; filter on ints.
grouped = df.groupby("letters")
old_way = df[grouped.ints.transform(lambda x: x.mean() > N / 20).astype("bool")]
new_way = grouped.filter(lambda x: x["ints"].mean() > N / 20)
tm.assert_frame_equal(new_way, old_way)
def test_filter_using_len():
# BUG GH4447
df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)})
grouped = df.groupby("B")
actual = grouped.filter(lambda x: len(x) > 2)
expected = DataFrame(
{"A": np.arange(2, 6), "B": list("bbbb"), "C": np.arange(2, 6)},
index=np.arange(2, 6),
)
tm.assert_frame_equal(actual, expected)
actual = grouped.filter(lambda x: len(x) > 4)
expected = df.loc[[]]
tm.assert_frame_equal(actual, expected)
# Series have always worked properly, but we'll test anyway.
s = df["B"]
grouped = s.groupby(s)
actual = grouped.filter(lambda x: len(x) > 2)
expected = Series(4 * ["b"], index=np.arange(2, 6), name="B")
tm.assert_series_equal(actual, expected)
actual = grouped.filter(lambda x: len(x) > 4)
expected = s[[]]
tm.assert_series_equal(actual, expected)
def test_filter_maintains_ordering():
# Simple case: index is sequential. #4621
df = DataFrame(
{"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}
)
s = df["pid"]
grouped = df.groupby("tag")
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
tm.assert_frame_equal(actual, expected)
grouped = s.groupby(df["tag"])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
tm.assert_series_equal(actual, expected)
# Now index is sequentially decreasing.
df.index = np.arange(len(df) - 1, -1, -1)
s = df["pid"]
grouped = df.groupby("tag")
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
tm.assert_frame_equal(actual, expected)
grouped = s.groupby(df["tag"])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
tm.assert_series_equal(actual, expected)
# Index is shuffled.
SHUFFLED = [4, 6, 7, 2, 1, 0, 5, 3]
df.index = df.index[SHUFFLED]
s = df["pid"]
grouped = df.groupby("tag")
actual = grouped.filter(lambda x: len(x) > 1)
expected = df.iloc[[1, 2, 4, 7]]
tm.assert_frame_equal(actual, expected)
grouped = s.groupby(df["tag"])
actual = grouped.filter(lambda x: len(x) > 1)
expected = s.iloc[[1, 2, 4, 7]]
tm.assert_series_equal(actual, expected)
def test_filter_multiple_timestamp():
# GH 10114
df = DataFrame(
{
"A": np.arange(5, dtype="int64"),
"B": ["foo", "bar", "foo", "bar", "bar"],
"C": Timestamp("20130101"),
}
)
grouped = df.groupby(["B", "C"])
result = grouped["A"].filter(lambda x: True)
tm.assert_series_equal(df["A"], result)
result = grouped["A"].transform(len)
expected = Series([2, 3, 2, 3, 3], name="A")
tm.assert_series_equal(result, expected)
result = grouped.filter(lambda x: True)
tm.assert_frame_equal(df, result)
result = grouped.transform("sum")
expected = DataFrame({"A": [2, 8, 2, 8, 8]})
tm.assert_frame_equal(result, expected)
result = grouped.transform(len)
expected = DataFrame({"A": [2, 3, 2, 3, 3]})
tm.assert_frame_equal(result, expected)
def test_filter_and_transform_with_non_unique_int_index():
# GH4620
index = [1, 1, 1, 2, 1, 1, 0, 1]
df = DataFrame(
{"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
index=index,
)
grouped_df = df.groupby("tag")
ser = df["pid"]
grouped_ser = ser.groupby(df["tag"])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
tm.assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid")
# ^ made manually because this can get confusing!
tm.assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
tm.assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
tm.assert_series_equal(actual, expected)
def test_filter_and_transform_with_multiple_non_unique_int_index():
# GH4620
index = [1, 1, 1, 2, 0, 0, 0, 1]
df = DataFrame(
{"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
index=index,
)
grouped_df = df.groupby("tag")
ser = df["pid"]
grouped_ser = ser.groupby(df["tag"])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
tm.assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid")
# ^ made manually because this can get confusing!
tm.assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
tm.assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
tm.assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_float_index():
# GH4620
index = np.array([1, 1, 1, 2, 1, 1, 0, 1], dtype=float)
df = DataFrame(
{"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
index=index,
)
grouped_df = df.groupby("tag")
ser = df["pid"]
grouped_ser = ser.groupby(df["tag"])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
tm.assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid")
# ^ made manually because this can get confusing!
tm.assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
tm.assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
tm.assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_timestamp_index():
# GH4620
t0 = Timestamp("2013-09-30 00:05:00")
t1 = Timestamp("2013-10-30 00:05:00")
t2 = Timestamp("2013-11-30 00:05:00")
index = [t1, t1, t1, t2, t1, t1, t0, t1]
df = DataFrame(
{"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
index=index,
)
grouped_df = df.groupby("tag")
ser = df["pid"]
grouped_ser = ser.groupby(df["tag"])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
tm.assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid")
# ^ made manually because this can get confusing!
tm.assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
tm.assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
tm.assert_series_equal(actual, expected)
def test_filter_and_transform_with_non_unique_string_index():
# GH4620
index = list("bbbcbbab")
df = DataFrame(
{"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]},
index=index,
)
grouped_df = df.groupby("tag")
ser = df["pid"]
grouped_ser = ser.groupby(df["tag"])
expected_indexes = [1, 2, 4, 7]
# Filter DataFrame
actual = grouped_df.filter(lambda x: len(x) > 1)
expected = df.iloc[expected_indexes]
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
expected = df.copy()
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
# Filter Series
actual = grouped_ser.filter(lambda x: len(x) > 1)
expected = ser.take(expected_indexes)
tm.assert_series_equal(actual, expected)
actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False)
NA = np.nan
expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid")
# ^ made manually because this can get confusing!
tm.assert_series_equal(actual, expected)
# Transform Series
actual = grouped_ser.transform(len)
expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid")
tm.assert_series_equal(actual, expected)
# Transform (a column from) DataFrameGroupBy
actual = grouped_df.pid.transform(len)
tm.assert_series_equal(actual, expected)
def test_filter_has_access_to_grouped_cols():
df = DataFrame([[1, 2], [1, 3], [5, 6]], columns=["A", "B"])
g = df.groupby("A")
# previously didn't have access to col A #????
filt = g.filter(lambda x: x["A"].sum() == 2)
tm.assert_frame_equal(filt, df.iloc[[0, 1]])
def test_filter_enforces_scalarness():
df = pd.DataFrame(
[
["best", "a", "x"],
["worst", "b", "y"],
["best", "c", "x"],
["best", "d", "y"],
["worst", "d", "y"],
["worst", "d", "y"],
["best", "d", "z"],
],
columns=["a", "b", "c"],
)
with pytest.raises(TypeError, match="filter function returned a.*"):
df.groupby("c").filter(lambda g: g["a"] == "best")
def test_filter_non_bool_raises():
df = pd.DataFrame(
[
["best", "a", 1],
["worst", "b", 1],
["best", "c", 1],
["best", "d", 1],
["worst", "d", 1],
["worst", "d", 1],
["best", "d", 1],
],
columns=["a", "b", "c"],
)
with pytest.raises(TypeError, match="filter function returned a.*"):
df.groupby("a").filter(lambda g: g.c.mean())
def test_filter_dropna_with_empty_groups():
# GH 10780
data = pd.Series(np.random.rand(9), index=np.repeat([1, 2, 3], 3))
groupped = data.groupby(level=0)
result_false = groupped.filter(lambda x: x.mean() > 1, dropna=False)
expected_false = pd.Series([np.nan] * 9, index=np.repeat([1, 2, 3], 3))
tm.assert_series_equal(result_false, expected_false)
result_true = groupped.filter(lambda x: x.mean() > 1, dropna=True)
expected_true = pd.Series(index=pd.Index([], dtype=int))
tm.assert_series_equal(result_true, expected_true)
| [
"griffin.harrisonn@gmail.com"
] | griffin.harrisonn@gmail.com |
7ee9aa6ee96971123bb69bee59b0a2cc28d60822 | c4ed52e5e9d0b059915bbf84c05b3af15ada4c59 | /test1.py | 0bf4d04c902597be641ec2d3c411cc4d8fe1c954 | [] | no_license | KI0KA/eop-by-Python | a70ae68d8399218d8ceed40032850fb15bdfc113 | 2ce8f1e4055dd6f3953f00c0f06f3b4adc1c8a7d | refs/heads/master | 2022-04-24T13:25:59.266896 | 2020-04-16T23:01:52 | 2020-04-16T23:01:52 | 258,407,300 | 0 | 0 | null | 2020-04-24T04:40:31 | 2020-04-24T04:40:30 | null | UTF-8 | Python | false | false | 103 | py | # test program
def main():
print("my first album".split())
if __name__ == "__main__":
main()
| [
"p9u78sxh@s.okayama-u.ac.jp"
] | p9u78sxh@s.okayama-u.ac.jp |
841c1efe6325c2b67960e896a83526bf52ba892d | eb7541314c5368b8fc7d9264b25ae1f6813829bc | /Longest_Palindromic_Subsequence.py | e0801b6f9927041d8e62d26fc6a1196e8fabf181 | [] | no_license | BibekKoirala/DynamicProgramming | 7f7fbf18a5f2b8113dc232dbd3ba047d898727f1 | 81ca3e83ac4bc320c0cd12e2b638b5a044f7ed09 | refs/heads/master | 2022-12-03T18:08:42.392955 | 2020-08-19T07:30:58 | 2020-08-19T07:30:58 | 283,597,971 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 463 | py | def LPS(s):
Lookup = [[0 if i != j else 1 for i in range(len(s))] for j in range(len(s))]
k = 1
while k < len(s):
i = 0
j = k
while j < len(s):
if s[i] == s[j]:
Lookup[i][j] = Lookup[i + 1][j - 1] + 2
else:
Lookup[i][j] = max(Lookup[i][j - 1], Lookup[i + 1][j])
j += 1
i += 1
k += 1
for i in Lookup:
print(i)
LPS('BABCBAB')
| [
"bibek.high@gmail.com"
] | bibek.high@gmail.com |
14b6e041b02bb82c853acc82a39ce2540e479dbf | 71d1c48161fadaaed2e9c4437e1194ce13b18622 | /working_with_api/english_vocabulary.py | b3b6503565d79ed20257c0d739fc6b1499e9b953 | [] | no_license | ikventure/some_projects | 2f43eef7ebe91e7d2ffaf4f96f2b55a4a8b7c141 | c87a1cab28662de8524ac3d77ba1884bd1fc53b9 | refs/heads/main | 2023-08-16T17:26:53.033466 | 2021-09-14T07:24:42 | 2021-09-14T07:24:42 | 401,194,468 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 636 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 16:15:44 2020
@author: ikventure
"""
filename = 'SUM_of_cet4+6+toefl+gre.txt'
txt = open(filename, "r").read()
txt = txt.lower()
all_words = txt.split()
words1, words2 = [], []
for word in all_words:
if len(word) == 6 and word[0] == word[-1] and word[1] != word[4]:
words1.append(word)
if len(word) == 5 and word[0] == word[-1] and word[1] != word[3]:
words2.append(word)
print(len(words1))
print(len(words2))
for word1 in words1:
for word2 in words2:
if word1[0:2] == word2[0:2] and word1[4:6] == word2[3:5]:
print(word1 + " " + word2) | [
"ikventurelove@gmail.com"
] | ikventurelove@gmail.com |
5cd7b233417a40dd0a9ef71afaa6969d9ba3b514 | 0fc891df6703ce3f91fe6005a6c582e573ed6c13 | /CWMT/user_login/migrations/0015_auto_20170811_1319.py | a97c1ba8d678eadfeaa3a8c5c6947edbde7ec3a2 | [] | no_license | Zeco-01/CWMT2017-REG | ce155343575d3b8b49eda584b40bdd1716368e38 | 5e71ddc38f3020d1582d0b38f2f8d0eace615b88 | refs/heads/master | 2021-01-02T22:19:25.372629 | 2017-09-18T06:46:11 | 2017-09-18T06:46:11 | 99,318,036 | 1 | 1 | null | 2017-08-11T15:17:24 | 2017-08-04T07:47:43 | Python | UTF-8 | Python | false | false | 521 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-11 13:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_login', '0014_auto_20170811_1310'),
]
operations = [
migrations.AlterField(
model_name='user',
name='register_number',
field=models.CharField(blank=True, max_length=20, primary_key=True, serialize=False, unique=True),
),
]
| [
"leezehua@outlook.com"
] | leezehua@outlook.com |
2cf7a4b05dd7a1a4b8cd95fbc9af7fcfbc6af2ce | b42af24fae93c62573256c47bc10df396a098c01 | /snakegameyash.py | 3547106350dc9cc09401cc31f74ed7a3425382c4 | [] | no_license | YashVardhan-444/snakegame | ac597e284e4b4eb74038dd06200538dc930de494 | ac5807808dd45cfcb90898ab0112e45db1b9ff98 | refs/heads/main | 2023-07-13T11:18:31.361490 | 2021-08-13T16:11:17 | 2021-08-13T16:11:17 | 308,942,232 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,348 | py | import pygame
from pygame import mixer
import time
import random
pygame.init()
white = (255, 255, 255) # constants defined to be used in the code ahead
# These parameters are color code for red,green and blue respectively
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
dis_width = 1100 # width of display screen
dis_height = 600 # height of display screen
pygame.display.set_mode()
bgimg = pygame.image.load("tree.jpg")
bgimg = pygame.transform.scale(bgimg, (dis_width, dis_height)).convert_alpha()
# creating window with width and height as parameters
dis = pygame.display.set_mode((dis_width, dis_height))
# providing caption at the top of the window
pygame.display.set_caption('Snake Game by Yash vardhan')
# to keep tack of time we built an object 'clock' for predefined function clock()
clock = pygame.time.Clock()
snake_block = 10 # size of block
snake_speed = 20 # speed of snake
font_style = pygame.font.SysFont(
"bahnschrift", 25) # for font play again or quit
score_font = pygame.font.SysFont("calibri", 25) # for font of score
def Your_score(score): # method for score
value = score_font.render("Your Score: " + str(score), True, black)
dis.blit(value, [0, 0])
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 3, dis_height / 2])
def gameLoop():
mixer.music.load("background.wav")
mixer.music.play(-1)
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
while not game_over:
dis.blit(bgimg, (0, 0))
while game_close == True:
dis.fill(black)
message("You Lost! Press P-Play Again or Q-Quit", yellow)
Your_score(Length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_p:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(
0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(
0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
| [
"noreply@github.com"
] | YashVardhan-444.noreply@github.com |
a2c28551321a031321b269385b8a40dee9d39c56 | f4434c85e3814b6347f8f8099c081ed4af5678a5 | /sdk/tables/azure-data-tables/azure/data/tables/_generated/aio/operations/_service_operations.py | 4ef1391d9b929f9750111cbb76a4882ccc33b059 | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | permissive | yunhaoling/azure-sdk-for-python | 5da12a174a37672ac6ed8e3c1f863cb77010a506 | c4eb0ca1aadb76ad892114230473034830116362 | refs/heads/master | 2022-06-11T01:17:39.636461 | 2020-12-08T17:42:08 | 2020-12-08T17:42:08 | 177,675,796 | 1 | 0 | MIT | 2020-03-31T20:35:17 | 2019-03-25T22:43:40 | Python | UTF-8 | Python | false | false | 13,225 | 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 typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from ... import models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ServiceOperations:
"""ServiceOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.data.tables.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def set_properties(
self,
table_service_properties: "models.TableServiceProperties",
timeout: Optional[int] = None,
request_id_parameter: Optional[str] = None,
**kwargs
) -> None:
"""Sets properties for an account's Table service endpoint, including properties for Analytics and
CORS (Cross-Origin Resource Sharing) rules.
:param table_service_properties: The Table Service properties.
:type table_service_properties: ~azure.data.tables.models.TableServiceProperties
:param timeout: The timeout parameter is expressed in seconds.
:type timeout: int
:param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character
limit that is recorded in the analytics logs when analytics logging is enabled.
:type request_id_parameter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
restype = "service"
comp = "properties"
content_type = kwargs.pop("content_type", "application/xml")
accept = "application/xml"
# Construct URL
url = self.set_properties.metadata['url'] # type: ignore
path_format_arguments = {
'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['restype'] = self._serialize.query("restype", restype, 'str')
query_parameters['comp'] = self._serialize.query("comp", comp, 'str')
if timeout is not None:
query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0)
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str')
if request_id_parameter is not None:
header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str')
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(table_service_properties, 'TableServiceProperties', is_xml=True)
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.TableServiceError, response)
raise HttpResponseError(response=response, model=error)
response_headers = {}
response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id'))
response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id'))
response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version'))
if cls:
return cls(pipeline_response, None, response_headers)
set_properties.metadata = {'url': '/'} # type: ignore
async def get_properties(
self,
timeout: Optional[int] = None,
request_id_parameter: Optional[str] = None,
**kwargs
) -> "models.TableServiceProperties":
"""Gets the properties of an account's Table service, including properties for Analytics and CORS
(Cross-Origin Resource Sharing) rules.
:param timeout: The timeout parameter is expressed in seconds.
:type timeout: int
:param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character
limit that is recorded in the analytics logs when analytics logging is enabled.
:type request_id_parameter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: TableServiceProperties, or the result of cls(response)
:rtype: ~azure.data.tables.models.TableServiceProperties
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.TableServiceProperties"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
restype = "service"
comp = "properties"
accept = "application/xml"
# Construct URL
url = self.get_properties.metadata['url'] # type: ignore
path_format_arguments = {
'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['restype'] = self._serialize.query("restype", restype, 'str')
query_parameters['comp'] = self._serialize.query("comp", comp, 'str')
if timeout is not None:
query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0)
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str')
if request_id_parameter is not None:
header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.TableServiceError, response)
raise HttpResponseError(response=response, model=error)
response_headers = {}
response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id'))
response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id'))
response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version'))
deserialized = self._deserialize('TableServiceProperties', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get_properties.metadata = {'url': '/'} # type: ignore
async def get_statistics(
self,
timeout: Optional[int] = None,
request_id_parameter: Optional[str] = None,
**kwargs
) -> "models.TableServiceStats":
"""Retrieves statistics related to replication for the Table service. It is only available on the
secondary location endpoint when read-access geo-redundant replication is enabled for the
account.
:param timeout: The timeout parameter is expressed in seconds.
:type timeout: int
:param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character
limit that is recorded in the analytics logs when analytics logging is enabled.
:type request_id_parameter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: TableServiceStats, or the result of cls(response)
:rtype: ~azure.data.tables.models.TableServiceStats
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.TableServiceStats"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
restype = "service"
comp = "stats"
accept = "application/xml"
# Construct URL
url = self.get_statistics.metadata['url'] # type: ignore
path_format_arguments = {
'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['restype'] = self._serialize.query("restype", restype, 'str')
query_parameters['comp'] = self._serialize.query("comp", comp, 'str')
if timeout is not None:
query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0)
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str')
if request_id_parameter is not None:
header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.TableServiceError, response)
raise HttpResponseError(response=response, model=error)
response_headers = {}
response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id'))
response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id'))
response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version'))
response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date'))
deserialized = self._deserialize('TableServiceStats', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get_statistics.metadata = {'url': '/'} # type: ignore
| [
"noreply@github.com"
] | yunhaoling.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.