hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3ac70080d2ba84f213f06c587171c79abbd5554a | 4,122 | py | Python | code/data_acquire/getTweets.py | siwei-li/tweet_stock | 5c265a747f06388f303f314d812879cfff90f938 | [
"MIT"
] | null | null | null | code/data_acquire/getTweets.py | siwei-li/tweet_stock | 5c265a747f06388f303f314d812879cfff90f938 | [
"MIT"
] | null | null | null | code/data_acquire/getTweets.py | siwei-li/tweet_stock | 5c265a747f06388f303f314d812879cfff90f938 | [
"MIT"
] | null | null | null | import datetime
from Scweet.scweet import scrape
import pandas as pd
from datetime import date
search_word_list = ["$AAPL"]
last_date = date.today().strftime('%Y-%m-%d')
start_date = (date.today() - datetime.timedelta(days=59)).strftime('%Y-%m-%d')
path = "../tweets/"
data = scrape(words=search_word_list, since="2021-10-01", until="2021-10-02",interval=1, \
lang="en",
resume=False)
print(data)
# for search_word in search_word_list:
# c = twint.Config()
# c.search = search_word
# c.Pandas = True
# twint.run.Search(c)
# Tweets_df = twint.storage.panda.Tweets_df
# Tweets_df.to_csv(path + search_word + "_" + start_date + "_" + last_date + ".csv")
# import pandas as pd
#
# from tweepy.api import API
# from tweepy.auth import OAuthHandler
# from tweepy.cursor import Cursor
#
# # Plug in developer account keys
# consumer_key = "ZoGaaYZ67GDr0TurYWv4aHXLN"
# consumer_secret = "IPlIp6O2nDd9gZaugIqfB6fjaGdCPIHevoJS3fx6TTeeNluJgE"
# access_token = "1116849769-LSw3UzWyCNvqxE1PYffAbxhQyOhgVlXnIqbpZIx"
# access_token_secret = "FoPG2ZEQ96szKZFaJXrbQNJymkUWveNQCzkB0GlcMLXvC"
# # bear = "AAAAAAAAAAAAAAAAAAAAAOVtUQEAAAAA%2Fj0c5rWaSPh1afiD7Xa%2B6TweD8s%3DT7INjLcED97ezLZcVj6djgBaTmqFMFfxEJpJZSVGpvvhe1WbbM"
#
# # Give Python your developer account keys
# auth = OAuthHandler(consumer_key, consumer_secret)
# auth.set_access_token(access_token, access_token_secret) # twitter api set ups
#
# api = API(auth,
# wait_on_rate_limit=True,
# # wait_on_rate_limit_notify=True,
# retry_count=10000,
# retry_delay=60,
# timeout=120)
#
# import GetOldTweets3 as got
#
# # Define variables below
# path = ""
# start_date = '2021-10-06'
# last_date = '2021-10-14'
# # search_word_list = ["$AAPL", "AAPL"]
# search_word_list = ["Trump"]
#
# if __name__ == "__main__":
# # search for each word in search list separately
# for search_word in search_word_list:
# print("Current search word: " + search_word)
# # search for each date separately
# for date_since in pd.date_range(start=start_date, end=last_date):
# df = pd.DataFrame([])
# print(date_since.strftime('%Y−%m−%d'))
#
# # extract tweets
# tweets = Cursor(
# api,
# # api.search,
# q=search_word,
# extended=True,
# lang="en",
# until=(date_since + dt.timedelta(days=1)).strftime('%Y−%m−%d'),
# # since=date_since.strftime('%Y−%m−%d'),
# result_type="recent",
# ).items()
# # print(tweets)
#
# # tweetCriteria = got.manager.TweetCriteria().setQuerySearch(search_word) \
# # .setSince(date_since.strftime('%Y−%m−%d'))\
# # .setUntil((date_since + dt.timedelta(days=1)).strftime('%Y−%m−%d'))
# # tweets = got.manager.TweetManager.getTweets(tweetCriteria)
#
# # put content of object into list
# users_locs = [[search_word,
# # tweet.username,
# tweet.user.screen_name,
# # tweet.geo,
# tweet.user.location,
# tweet.text,
# # tweet.date
# tweet.created_at
# ] for tweet in tweets]
# # make a df
# tweet_text = pd.DataFrame(data=users_locs,
# columns=["search_word", "user", "location", "text", "date"])
# # merge the df with the other results for different dates and search words
# df = df.append(tweet_text)
# # save daily results
# df = df.reset_index(drop=True)
# print(f"{len(df)} Tweets in total.")
#
# if not df.empty:
# df.to_csv(path + search_word + "" + date_since.strftime('%Y−%m−%d') + ".csv")
| 37.472727 | 129 | 0.565745 | 453 | 4,122 | 4.993377 | 0.364238 | 0.075155 | 0.037135 | 0.029178 | 0.134394 | 0.116711 | 0.098143 | 0.072502 | 0.033599 | 0.033599 | 0 | 0.030899 | 0.309073 | 4,122 | 109 | 130 | 37.816514 | 0.759129 | 0.840126 | 0 | 0 | 0 | 0 | 0.09707 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0.083333 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
3acc2dccc0b9182da0a2f313b50a9e7c2fb3ba57 | 2,041 | py | Python | ihome/ihome/utils/checkid.py | xyuzi/ihome | ab74e4efb73c14d2b410f6c19c6b2a35f8fd720e | [
"MIT"
] | null | null | null | ihome/ihome/utils/checkid.py | xyuzi/ihome | ab74e4efb73c14d2b410f6c19c6b2a35f8fd720e | [
"MIT"
] | 10 | 2021-03-19T11:31:11.000Z | 2022-02-10T10:44:16.000Z | ihome/ihome/utils/checkid.py | xyuzi/ihome | ab74e4efb73c14d2b410f6c19c6b2a35f8fd720e | [
"MIT"
] | null | null | null | W = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] # 加权系数
M_run = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 闰年每月天数
M_ping = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 平年每月天数
def check(id_number):
try:
id_number = str(id_number)
except:
return None
if len(id_number) != 18 or not id_number[:-1].isdigit() and (id_number[-1] != 'X' or id_number[-1] != 'x'):
return None
id_number_dict = dict()
id_number_dict['地址码'] = int(id_number[:6])
# 校验身份证地址码
if len(str(id_number_dict['地址码'])) != 6:
return None
id_number_dict['YY'] = int(id_number[6:10])
# 校验身份证年份
if len(str(id_number_dict['YY'])) != 4 or id_number_dict['YY'] > 2019:
return None
id_number_dict['MM'] = int(id_number[10:12])
# 校验身份证月份
if id_number_dict['MM'] > 12 or id_number_dict['MM'] == 0:
return None
id_number_dict['DD'] = int(id_number[12:14])
# 校验身份证日期
if id_number_dict['YY'] % 400 == 0 or (id_number_dict['YY'] % 4 == 0 and id_number_dict['YY'] % 100 != 0):
if id_number_dict['DD'] > M_run[id_number_dict['MM'] - 1]:
return None
else:
if id_number_dict['DD'] > M_ping[id_number_dict['MM'] - 1]:
return None
id_number_dict['顺序码'] = id_number[14:17]
# 校验身份证顺序码
# if (int(id_number_dict['顺序码'][-1]) % 2 == 0 and id_sex == '男') or (
# int(id_number_dict['顺序码'][-1]) % 2 == 1 and id_sex == '女'):
# print('身份证号码顺序码错误')
# return None
if id_number[17] == 'X' or id_number[17] == 'x':
id_number_dict['校验码'] = 10
else:
id_number_dict['校验码'] = int(id_number[17])
# 校验身份证校验码
A = list(map(int, list(id_number[:-1])))
id_S = sum([x * y for (x, y) in zip(A, W)])
id_N = (12 - id_S % 11) % 11
if id_N == id_number_dict['校验码']:
return True
else:
return None
if __name__ == '__main__':
print(check('11010119900307651X'))
print(check('110101199003072551'))
print(check(110101199003072551))
| 34.59322 | 111 | 0.56002 | 333 | 2,041 | 3.192192 | 0.243243 | 0.293509 | 0.259643 | 0.079022 | 0.334901 | 0.206961 | 0.137347 | 0.037629 | 0.037629 | 0.037629 | 0 | 0.121353 | 0.261147 | 2,041 | 58 | 112 | 35.189655 | 0.583554 | 0.120039 | 0 | 0.255814 | 0 | 0 | 0.05275 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.023256 | false | 0 | 0 | 0 | 0.232558 | 0.069767 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3ad7e7dc441525dc13d23c5abf231dce0988ee2d | 1,282 | py | Python | radiovis/models.py | mervij/radiodns | 01543cf1e4de8de335af0301616e089c35fc67f8 | [
"Apache-2.0"
] | null | null | null | radiovis/models.py | mervij/radiodns | 01543cf1e4de8de335af0301616e089c35fc67f8 | [
"Apache-2.0"
] | 8 | 2021-05-17T10:54:28.000Z | 2021-06-08T12:02:37.000Z | radiovis/models.py | mervij/radiodns | 01543cf1e4de8de335af0301616e089c35fc67f8 | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 Radio Moreeni
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.db import models
class Image(models.Model):
image = models.ImageField(upload_to='images/')
def __str__(self):
return f'{self.image}'
class ImageSlide(models.Model):
trigger_time = models.DateTimeField(null=True)
image = models.ForeignKey(Image, on_delete=models.CASCADE)
link = models.CharField(max_length=512, blank=True)
sent = models.DateTimeField(null=True, editable=False)
def __str__(self):
return str(self.sent)
class TextSlide(models.Model):
message = models.CharField(max_length=128, default='')
sent = models.DateTimeField(null=True, editable=False)
def __str__(self):
return f'{self.sent}, "{self.message}"'
| 31.268293 | 74 | 0.726989 | 179 | 1,282 | 5.111732 | 0.564246 | 0.065574 | 0.032787 | 0.052459 | 0.159563 | 0.159563 | 0.131148 | 0.131148 | 0.131148 | 0.131148 | 0 | 0.013208 | 0.173167 | 1,282 | 40 | 75 | 32.05 | 0.85 | 0.429017 | 0 | 0.294118 | 0 | 0 | 0.066852 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.176471 | false | 0 | 0.058824 | 0.176471 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
3add13e07600a3e8ac0277ad5a85ed8b6c37c66d | 149 | py | Python | Python Exercicios/tabuada.py | candido00/Python | 4b6721d55828191ca2ede0c5a0c36f6f5afdad55 | [
"MIT"
] | null | null | null | Python Exercicios/tabuada.py | candido00/Python | 4b6721d55828191ca2ede0c5a0c36f6f5afdad55 | [
"MIT"
] | null | null | null | Python Exercicios/tabuada.py | candido00/Python | 4b6721d55828191ca2ede0c5a0c36f6f5afdad55 | [
"MIT"
] | null | null | null | numero = int(input("Digite um numero para calcular tabuada: "))
tab = 0
while (tab <= 10):
print (tab ,"X",numero,"=", numero * tab)
tab +=1
| 24.833333 | 63 | 0.597315 | 22 | 149 | 4.045455 | 0.681818 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.034188 | 0.214765 | 149 | 5 | 64 | 29.8 | 0.726496 | 0 | 0 | 0 | 0 | 0 | 0.281879 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3aec288a57313268e8b9645d0fbfd8350334bac5 | 575 | py | Python | thelma/repositories/rdb/schema/tables/tube.py | fogathmann/TheLMA | ac330a0005da4fea2f1387da9ff9938611ad1481 | [
"MIT"
] | 1 | 2020-07-12T22:47:58.000Z | 2020-07-12T22:47:58.000Z | thelma/repositories/rdb/schema/tables/tube.py | papagr/TheLMA | d2dc7a478ee5d24ccf3cc680888e712d482321d0 | [
"MIT"
] | null | null | null | thelma/repositories/rdb/schema/tables/tube.py | papagr/TheLMA | d2dc7a478ee5d24ccf3cc680888e712d482321d0 | [
"MIT"
] | 1 | 2020-07-12T22:40:36.000Z | 2020-07-12T22:40:36.000Z | """
Container table.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Table
__docformat__ = "reStructuredText en"
__all__ = ['create_table']
def create_table(metadata, container_tbl):
"Table factory."
tbl = Table('tube', metadata,
Column('container_id', Integer,
ForeignKey(container_tbl.c.container_id),
primary_key=True),
Column('barcode', String, nullable=False))
return tbl
| 25 | 64 | 0.666087 | 60 | 575 | 6.133333 | 0.466667 | 0.190217 | 0.271739 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.248696 | 575 | 22 | 65 | 26.136364 | 0.851852 | 0.053913 | 0 | 0 | 0 | 0 | 0.123412 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0.333333 | 0 | 0.466667 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
3af115d969414e81383db0d1cd3046611a16de1c | 346 | py | Python | yunionclient/api/dbinstanceaccounts.py | yunionyun/python_yunionsdk | 40a567b80f6fb3ebc72d8cc6313b334a201b2f00 | [
"Apache-2.0"
] | 3 | 2021-09-22T11:34:08.000Z | 2022-03-13T04:55:17.000Z | yunionclient/api/dbinstanceaccounts.py | yunionyun/python_yunionsdk | 40a567b80f6fb3ebc72d8cc6313b334a201b2f00 | [
"Apache-2.0"
] | 13 | 2019-06-06T08:25:41.000Z | 2021-07-16T07:26:10.000Z | yunionclient/api/dbinstanceaccounts.py | yunionyun/python_yunionsdk | 40a567b80f6fb3ebc72d8cc6313b334a201b2f00 | [
"Apache-2.0"
] | 7 | 2019-03-31T05:43:36.000Z | 2021-03-04T09:59:05.000Z | from yunionclient.common import base
class Dbinstanceaccount(base.ResourceBase):
pass
class DbinstanceaccountManager(base.StandaloneManager):
resource_class = Dbinstanceaccount
keyword = 'dbinstanceaccount'
keyword_plural = 'dbinstanceaccounts'
_columns = ["Id", "Name", "Dbinstance_Id", "Status", "Dbinstanceprivileges"]
| 26.615385 | 80 | 0.763006 | 29 | 346 | 8.965517 | 0.724138 | 0.169231 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.141619 | 346 | 12 | 81 | 28.833333 | 0.875421 | 0 | 0 | 0 | 0 | 0 | 0.231884 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.125 | 0.125 | 0 | 0.875 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
aae7fb5f3ea48b248531aa920d2ea7bd4a26bb66 | 1,436 | py | Python | wepost/urls.py | Hannidiot/wepost | 98c8a30812bef1a7682b3641048f7c3aa65ba8f9 | [
"MIT"
] | null | null | null | wepost/urls.py | Hannidiot/wepost | 98c8a30812bef1a7682b3641048f7c3aa65ba8f9 | [
"MIT"
] | 1 | 2022-03-02T18:16:12.000Z | 2022-03-02T23:39:14.000Z | wepost/urls.py | Hannidiot/wepost | 98c8a30812bef1a7682b3641048f7c3aa65ba8f9 | [
"MIT"
] | null | null | null | """wepost URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.conf.urls import include,url
from wepost_main.views import index_view
from wepost_main.views import test
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('wepost/', include('wepost_main.urls')),
path('accounts/', include('allauth.urls')),
path('', index_view.index, name="index"),
path('accounts/', include('signuser.urls',namespace='signuser')),
# path('wepost_main/', include('wepost_main.urls', namespace='wepost_main')),
# path('signuser/',include('signuser.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 39.888889 | 81 | 0.728412 | 206 | 1,436 | 5.009709 | 0.320388 | 0.077519 | 0.054264 | 0.023256 | 0.235465 | 0.187016 | 0.146318 | 0 | 0 | 0 | 0 | 0.006478 | 0.139972 | 1,436 | 35 | 82 | 41.028571 | 0.82915 | 0.517409 | 0 | 0.125 | 0 | 0 | 0.124088 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5625 | 0 | 0.5625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
aae9039521789a5d811ceb511b2f5cde4fa43e94 | 512 | py | Python | utils/schema-doc-generator/script.py | polfliet/newrelic-quickstarts | e73e2f6e0844566eaebfc479049612999de93b17 | [
"Apache-2.0"
] | 1 | 2021-09-21T21:15:14.000Z | 2021-09-21T21:15:14.000Z | utils/schema-doc-generator/script.py | polfliet/newrelic-quickstarts | e73e2f6e0844566eaebfc479049612999de93b17 | [
"Apache-2.0"
] | null | null | null | utils/schema-doc-generator/script.py | polfliet/newrelic-quickstarts | e73e2f6e0844566eaebfc479049612999de93b17 | [
"Apache-2.0"
] | null | null | null | import glob
from pathlib import Path
from json_schema_for_humans.generation_configuration import GenerationConfiguration
from json_schema_for_humans.generate import generate_from_filename
config = GenerationConfiguration(template_name="md", show_toc=False)
schema_paths = glob.glob('utils/schemas/*.json')
for path in schema_paths:
# stem is filename without extension
stem = Path(path).stem
print(f'generating doc for: {path}')
generate_from_filename(path, f'docs/{stem}.md', config=config)
| 32 | 83 | 0.794922 | 70 | 512 | 5.6 | 0.485714 | 0.040816 | 0.071429 | 0.086735 | 0.117347 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.119141 | 512 | 15 | 84 | 34.133333 | 0.86918 | 0.066406 | 0 | 0 | 1 | 0 | 0.130252 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.4 | 0 | 0.4 | 0.1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
aafccaaef3796f6f4b530b4baf78a42b15beba5c | 194 | py | Python | tests/test_ops.py | HephaestusProject/pytorch-DCGAN | b3bc52d75dc1023abde74fb1bb5ef118572d0adb | [
"MIT"
] | null | null | null | tests/test_ops.py | HephaestusProject/pytorch-DCGAN | b3bc52d75dc1023abde74fb1bb5ef118572d0adb | [
"MIT"
] | 8 | 2020-07-31T16:03:16.000Z | 2020-10-03T15:10:09.000Z | tests/test_ops.py | HephaestusProject/pytorch-DCGAN | b3bc52d75dc1023abde74fb1bb5ef118572d0adb | [
"MIT"
] | null | null | null | import pytest
import torch
from src.model.ops import Reshape
def test_reshape():
x = torch.empty(128, 100)
y = Reshape(-1, 1).forward(x)
assert y.size() == torch.Size([12800, 1])
| 17.636364 | 45 | 0.654639 | 31 | 194 | 4.064516 | 0.645161 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.089744 | 0.195876 | 194 | 10 | 46 | 19.4 | 0.717949 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | 1 | 0.142857 | false | 0 | 0.428571 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
aaff6aacfb03f9b46395c518b76a4843ed748dd7 | 591 | py | Python | skaio/core/publisher.py | cipriantarta/skaio | 30716a3bd30d055c0c18d10a899522934bb71613 | [
"BSD-3-Clause"
] | null | null | null | skaio/core/publisher.py | cipriantarta/skaio | 30716a3bd30d055c0c18d10a899522934bb71613 | [
"BSD-3-Clause"
] | null | null | null | skaio/core/publisher.py | cipriantarta/skaio | 30716a3bd30d055c0c18d10a899522934bb71613 | [
"BSD-3-Clause"
] | null | null | null | from skaio.core.base.broker import BrokerBase
from skaio.core.base.serializer import TaskSerializer
from skaio.core.brokers.redis import RedisBroker
from skaio.core.serializers.pickle_serializer import PickleSerializer
from skaio.core.base.task import BaseTask
class Publisher:
def __init__(self, broker: BrokerBase=None, serializer: TaskSerializer=None):
self.__broker = broker or RedisBroker.create()
self.__serializer = serializer or PickleSerializer()
async def publish(self, task: BaseTask):
await self.__broker.put(self.__serializer.serialize(task))
| 39.4 | 81 | 0.78511 | 72 | 591 | 6.263889 | 0.416667 | 0.099778 | 0.144124 | 0.113082 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135364 | 591 | 14 | 82 | 42.214286 | 0.882583 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0 | 0.454545 | 0 | 0.636364 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
c901f7dabb75a651fc2f96352a0a3233ebd2efe8 | 456 | py | Python | sphinx_tomyst/transform/__init__.py | QuantEcon/sphinxcontrib-tomyst | b0eeecc787d74681ab3cfeff41d22aa9e56c11c5 | [
"MIT"
] | 4 | 2020-09-26T22:51:46.000Z | 2021-05-10T13:52:49.000Z | sphinx_tomyst/transform/__init__.py | executablebooks/sphinx-tomyst | b0eeecc787d74681ab3cfeff41d22aa9e56c11c5 | [
"MIT"
] | 33 | 2020-09-25T04:26:10.000Z | 2021-06-24T00:42:57.000Z | sphinx_tomyst/transform/__init__.py | QuantEcon/sphinx-tomyst | b0eeecc787d74681ab3cfeff41d22aa9e56c11c5 | [
"MIT"
] | 1 | 2020-08-10T02:51:03.000Z | 2020-08-10T02:51:03.000Z | """
Transform to Intercept Sphinx AST before transforms/post-transforms
"""
from sphinx.transforms import SphinxTransform
from sphinx.util import logging
logger = logging.getLogger(__name__)
def intercept_ast(config, document, tags):
document.document_pretransforms = document.deepcopy()
class InterceptAST(SphinxTransform):
default_priority = 1
def apply(self):
intercept_ast(self.config, self.document, self.app.builder.tags)
| 21.714286 | 72 | 0.769737 | 53 | 456 | 6.471698 | 0.584906 | 0.058309 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.002558 | 0.142544 | 456 | 20 | 73 | 22.8 | 0.87468 | 0.14693 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.222222 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
c909016ca18ee628b31c86f2fd67a068c5aba3fa | 489 | py | Python | naverblog.py | ruby-kim/automatic-tech-blog-management | 5d45598bb87159ae08b5b80ccab81f4683989185 | [
"MIT"
] | null | null | null | naverblog.py | ruby-kim/automatic-tech-blog-management | 5d45598bb87159ae08b5b80ccab81f4683989185 | [
"MIT"
] | null | null | null | naverblog.py | ruby-kim/automatic-tech-blog-management | 5d45598bb87159ae08b5b80ccab81f4683989185 | [
"MIT"
] | null | null | null | import pytz
from bs4 import BeautifulSoup
from datetime import datetime
import requests
import os
# local import
from dotenv import load_dotenv
class NaverBlog:
def __init__(self, blogUrl):
self.url = blogUrl
self.xml = blogUrl.replace("https://", "https://rss.") + ".xml"
self.contents = []
self.curTime = None
def parsing_xml(self):
return
if __name__ == "__main__":
naverBlog = NaverBlog("https://blog.naver.com/dev_rubykim")
| 18.807692 | 71 | 0.662577 | 59 | 489 | 5.237288 | 0.59322 | 0.090615 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.002646 | 0.226994 | 489 | 25 | 72 | 19.56 | 0.814815 | 0.02454 | 0 | 0 | 0 | 0 | 0.139535 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.375 | 0.0625 | 0.625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
c914d2aded3e634de132b65713e4999e7bcd4909 | 1,036 | py | Python | canteen/__init__.py | dbl0null/canteen | 3bef22a2059ef6ac5df178324fbc1dba45316e22 | [
"MIT"
] | 2 | 2016-08-24T18:42:41.000Z | 2017-12-08T00:41:02.000Z | canteen/__init__.py | dbl0null/canteen | 3bef22a2059ef6ac5df178324fbc1dba45316e22 | [
"MIT"
] | null | null | null | canteen/__init__.py | dbl0null/canteen | 3bef22a2059ef6ac5df178324fbc1dba45316e22 | [
"MIT"
] | 2 | 2015-09-22T05:36:27.000Z | 2017-12-08T00:41:21.000Z | # -*- coding: utf-8 -*-
"""
canteen
~~~~~~~
a minimal web framework for the modern web
:author: Sam Gammon <sg@samgammon.com>
:copyright: (c) Sam Gammon, 2014
:license: This software makes use of the MIT Open Source License.
A copy of this license is included as ``LICENSE.md`` in
the root of the project.
"""
debug, __version__ = __debug__, (0, 3)
# stdlib
import __builtin__; export = None
# yay modules!
from . import core
from . import rpc
from . import util
from . import test
from . import base
from . import model
from . import logic
from . import runtime
from . import dispatch
from . import exceptions
# canteen :)
from .rpc import *
from .core import *
from .util import *
from .test import *
from .base import *
from .logic import *
from .model import *
from .runtime import *
from .dispatch import *
from .exceptions import *
__all__ = [export for export in globals() if (
export not in __builtin__.__dict__ and (
not export.startswith('__')))] # export all the things!
| 20.313725 | 67 | 0.681467 | 143 | 1,036 | 4.755245 | 0.468531 | 0.147059 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008653 | 0.219112 | 1,036 | 50 | 68 | 20.72 | 0.831891 | 0.362934 | 0 | 0 | 0 | 0 | 0.003175 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.84 | 0 | 0.84 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
c9162836cb3ef63abac5fbeb5186892c6b69ded5 | 297 | py | Python | api/src/lib/aws_util/s3/csv/read.py | kagemeka/twitter-api-python | c78e2b16177126d7808b90d09d6f565bd89dce5b | [
"MIT"
] | null | null | null | api/src/lib/aws_util/s3/csv/read.py | kagemeka/twitter-api-python | c78e2b16177126d7808b90d09d6f565bd89dce5b | [
"MIT"
] | null | null | null | api/src/lib/aws_util/s3/csv/read.py | kagemeka/twitter-api-python | c78e2b16177126d7808b90d09d6f565bd89dce5b | [
"MIT"
] | null | null | null | import pandas as pd
import tempfile
from lib.aws_util.s3.download import download_from_s3
def read_csv_on_s3(bucket_name: str, obj: str) -> pd.DataFrame:
dir_ = tempfile.mkdtemp()
save_path = f'{dir_}/data.csv'
download_from_s3(bucket_name, obj, save_path)
return pd.read_csv(save_path) | 29.7 | 63 | 0.771044 | 51 | 297 | 4.176471 | 0.529412 | 0.112676 | 0.131455 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015444 | 0.127946 | 297 | 10 | 64 | 29.7 | 0.80695 | 0 | 0 | 0 | 0 | 0 | 0.050336 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.375 | 0 | 0.625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
c91673bdcaf604fa1c451079ba7718d8808f0da6 | 2,908 | py | Python | src/py_dss_tools/model/control/ESPVLControl.py | eniovianna/py_dss_tools | 3057fb0b74facd05a362e4e4a588f79f70aa9dd7 | [
"MIT"
] | 3 | 2021-05-29T00:40:10.000Z | 2021-09-30T17:56:14.000Z | src/py_dss_tools/model/control/ESPVLControl.py | eniovianna/py_dss_tools | 3057fb0b74facd05a362e4e4a588f79f70aa9dd7 | [
"MIT"
] | null | null | null | src/py_dss_tools/model/control/ESPVLControl.py | eniovianna/py_dss_tools | 3057fb0b74facd05a362e4e4a588f79f70aa9dd7 | [
"MIT"
] | 3 | 2021-05-29T00:40:46.000Z | 2022-01-13T22:04:49.000Z | # -*- encoding: utf-8 -*-
"""
Created by Ênio Viana at 22/09/2021 at 23:05:30
Project: py_dss_tools [set, 2021]
"""
class ESPVLControl:
name = "ESPVLControl"
name_plural = "ESPVLControls"
columns = ['basefreq', 'element', 'enabled', 'forecast', 'kvarlimit', 'kwband', 'like', 'localcontrollist',
'localcontrolweights', 'pvsystemlist', 'pvsystemweights', 'storagelist', 'storageweights', 'terminal',
'type']
def __init__(self):
self.__element = None
self.__forecast = None
self.__kvarlimit = None
self.__kwband = None
self.__localcontrollist = None
self.__localcontrolweights = None
self.__pvsystemlist = None
self.__pvsystemweights = None
self.__storagelist = None
self.__storageweights = None
self.__terminal = None
self.__type = None
@property
def element(self):
return self.__element
@element.setter
def element(self, value):
self.__element = value
@property
def forecast(self):
return self.__forecast
@forecast.setter
def forecast(self, value):
self.__forecast = value
@property
def kvarlimit(self):
return self.__kvarlimit
@kvarlimit.setter
def kvarlimit(self, value):
self.__kvarlimit = value
@property
def kwband(self):
return self.__kwband
@kwband.setter
def kwband(self, value):
self.__kwband = value
@property
def localcontrollist(self):
return self.__localcontrollist
@localcontrollist.setter
def localcontrollist(self, value):
self.__localcontrollist = value
@property
def localcontrolweights(self):
return self.__localcontrolweights
@localcontrolweights.setter
def localcontrolweights(self, value):
self.__localcontrolweights = value
@property
def pvsystemlist(self):
return self.__pvsystemlist
@pvsystemlist.setter
def pvsystemlist(self, value):
self.__pvsystemlist = value
@property
def pvsystemweights(self):
return self.__pvsystemweights
@pvsystemweights.setter
def pvsystemweights(self, value):
self.__pvsystemweights = value
@property
def storagelist(self):
return self.__storagelist
@storagelist.setter
def storagelist(self, value):
self.__storagelist = value
@property
def storageweights(self):
return self.__storageweights
@storageweights.setter
def storageweights(self, value):
self.__storageweights = value
@property
def terminal(self):
return self.__terminal
@terminal.setter
def terminal(self, value):
self.__terminal = value
@property
def type(self):
return self.__type
@type.setter
def type(self, value):
self.__type = value
| 23.451613 | 117 | 0.642022 | 275 | 2,908 | 6.501818 | 0.174545 | 0.073826 | 0.09396 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008933 | 0.268569 | 2,908 | 123 | 118 | 23.642276 | 0.831688 | 0.036451 | 0 | 0.131868 | 0 | 0 | 0.061963 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.274725 | false | 0 | 0 | 0.131868 | 0.450549 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
c918a159c8987d3bc8a35c72b224729869659c26 | 452 | py | Python | apps/ventas/admin.py | Marthox1999/ProyectoDesarrolloII | cf19c683ea121b9b1affafdc3f671e7db2304b3a | [
"MIT"
] | null | null | null | apps/ventas/admin.py | Marthox1999/ProyectoDesarrolloII | cf19c683ea121b9b1affafdc3f671e7db2304b3a | [
"MIT"
] | 88 | 2019-06-18T18:28:19.000Z | 2019-09-19T18:54:46.000Z | apps/ventas/admin.py | Marthox1999/Nova | cf19c683ea121b9b1affafdc3f671e7db2304b3a | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Factura, DetallesFactura, DescuentoCategoria, DescuentoSubCategoria, DescuentoProducto, PagosCredito, PagosDebito
# Register your models here.
admin.site.register(Factura)
admin.site.register(DetallesFactura)
admin.site.register(DescuentoCategoria)
admin.site.register(DescuentoSubCategoria)
admin.site.register(DescuentoProducto)
admin.site.register(PagosCredito)
admin.site.register(PagosDebito)
| 37.666667 | 133 | 0.856195 | 47 | 452 | 8.234043 | 0.361702 | 0.162791 | 0.307494 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.059735 | 452 | 11 | 134 | 41.090909 | 0.910588 | 0.057522 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.222222 | 0 | 0.222222 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c91be6e39aa11a826d5c88e03c829db44427baeb | 7,941 | py | Python | Traffic.py | softmicro929/a-deep-rl-approach-for-sdn-routing-optimization | 6aa9e9ad8dfa7353dccf5525bae70c03e568a53d | [
"MIT"
] | 11 | 2018-12-09T03:48:01.000Z | 2022-03-22T07:00:28.000Z | Traffic.py | softmicro929/a-deep-rl-approach-for-sdn-routing-optimization | 6aa9e9ad8dfa7353dccf5525bae70c03e568a53d | [
"MIT"
] | null | null | null | Traffic.py | softmicro929/a-deep-rl-approach-for-sdn-routing-optimization | 6aa9e9ad8dfa7353dccf5525bae70c03e568a53d | [
"MIT"
] | 3 | 2019-04-23T04:30:09.000Z | 2021-04-22T07:32:33.000Z | """
Traffic.py
"""
__author__ = "giorgio@ac.upc.edu"
import numpy as np
from os import listdir
from re import split
from OU import OU
from helper import softmax
def natural_key(string_):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in split(r'(\d+)', string_)]
#
class Traffic():
def __init__(self, nodes_num, type, capacity):
self.nodes_num = nodes_num
self.prev_traffic = None
self.type = type
self.capacity = capacity * nodes_num / (nodes_num - 1)
self.dictionary = {}
self.dictionary['NORM'] = self.normal_traffic
self.dictionary['UNI'] = self.uniform_traffic
self.dictionary['CONTROLLED'] = self.controlled_uniform_traffic
self.dictionary['EXP'] = self.exp_traffic
self.dictionary['OU'] = self.ou_traffic
self.dictionary['STAT'] = self.stat_traffic
self.dictionary['STATEQ'] = self.stat_eq_traffic
self.dictionary['FILE'] = self.file_traffic
self.dictionary['DIR'] = self.dir_traffic
if self.type.startswith('DIR:'):
self.dir = sorted(listdir(self.type.split('DIR:')[-1]), key=lambda x: natural_key((x)))
self.static = None
self.total_ou = OU(1, self.capacity/2, 0.1, self.capacity/2)
self.nodes_ou = OU(self.nodes_num**2, 1, 0.1, 1)
def normal_traffic(self):
t = np.random.normal(capacity/2, capacity/2)
return np.asarray(t * softmax(np.random.randn(self.nodes_num, self.nodes_num))).clip(min=0.001)
def uniform_traffic(self):
t = np.random.uniform(0, self.capacity*1.25)
return np.asarray(t * softmax(np.random.uniform(0, 1, size=[self.nodes_num]*2))).clip(min=0.001)
def controlled_uniform_traffic(self):
t = np.random.uniform(0, self.capacity*1.25)
if self.prev_traffic is None:
self.prev_traffic = np.asarray(t * softmax(np.random.uniform(0, 1, size=[self.nodes_num]*2))).clip(min=0.001)
dist = [1]
dist += [0]*(self.nodes_num**2 - 1)
ch = np.random.choice(dist, [self.nodes_num]*2)
tt = np.multiply(self.prev_traffic, 1 - ch)
nt = np.asarray(t * softmax(np.random.uniform(0, 1, size=[self.nodes_num]*2))).clip(min=0.001)
nt = np.multiply(nt, ch)
self.prev_traffic = tt + nt
return self.prev_traffic
# xxxxxxx
# xxx
# 指数分布
def exp_traffic(self):
a = np.random.exponential(size=self.nodes_num)
b = np.random.exponential(size=self.nodes_num)
# https://blog.csdn.net/u011599639/article/details/77926402
# 计算向量 a,b 外积,[a,b]
T = np.outer(a, b)
# 对角线 填 -1
np.fill_diagonal(T, -1)
T[T!=-1] = np.asarray(np.random.exponential()*T[T!=-1]/np.average(T[T!=-1])).clip(min=0.001)
return T
def stat_traffic(self):
if self.static is None:
string = self.type.split('STAT:')[-1]
v = np.asarray(tuple(float(x) for x in string.split(',')[:self.nodes_num**2]))
M = np.split(v, self.nodes_num)
self.static = np.vstack(M)
return self.static
def stat_eq_traffic(self):
if self.static is None:
value = float(self.type.split('STATEQ:')[-1])
self.static = np.full([self.nodes_num]*2, value, dtype=float)
return self.static
def ou_traffic(self):
t = self.total_ou.evolve()[0]
nt = t * softmax(self.nodes_ou.evolve())
i = np.split(nt, self.nodes_num)
return np.vstack(i).clip(min=0.001)
def file_traffic(self):
if self.static is None:
fname = 'traffic/' + self.type.split('FILE:')[-1]
v = np.loadtxt(fname, delimiter=',')
self.static = np.split(v, self.nodes_num)
return self.static
def dir_traffic(self):
while len(self.dir) > 0:
tm = self.dir.pop(0)
if not tm.endswith('.txt'):
continue
fname = self.type.split('DIR:')[-1] + '/' + tm
v = np.loadtxt(fname, delimiter=',')
return np.split(v, self.nodes_num)
return False
def generate(self):
return self.dictionary[self.type.split(":")[0]]()
# 这样 dictionary [14,14] 代表什么意思呢???
#[[-1.00000000e+00 4.82597027e-01 1.64885219e-01 2.39937374e-01
# 4.24195039e-01 3.90513477e-01 1.73313504e-01 2.39531467e-01
# 8.81383591e-01 2.35750495e-01 9.86736084e-01 1.10174305e+00
# 2.91715890e-02 1.24369249e-01]
# [1.24568554e-01 - 1.00000000e+00 4.58794226e-02 6.67627350e-02
# 1.18032554e-01 1.08660636e-01 4.82245987e-02 6.66497910e-02
# 2.45245574e-01 6.55977330e-02 2.74559976e-01 3.06560741e-01
# 8.11701418e-03 3.46058268e-02]
# [4.41894837e-01 4.76355699e-01 - 1.00000000e+00 2.36834313e-01
# 4.18709012e-01 3.85463046e-01 1.71072076e-01 2.36433655e-01
# 8.69984838e-01 2.32701582e-01 9.73974829e-01 1.08749443e+00
# 2.87943189e-02 1.22760807e-01]
# [3.99306289e-01 4.30445913e-01 1.47067148e-01 - 1.00000000e+00
# 3.78355046e-01 3.48313231e-01 1.54584644e-01 2.13646863e-01
# 7.86138212e-01 2.10274476e-01 8.80105948e-01 9.82684859e-01
# 2.60192056e-02 1.10929475e-01]
# [8.86430104e-01 9.55557740e-01 3.26478072e-01 4.75083769e-01
# - 1.00000000e+00 7.73229329e-01 3.43166350e-01 4.74280060e-01
# 1.74516805e+00 4.66793613e-01 1.95376940e+00 2.18148691e+00
# 5.77606908e-02 2.46255140e-01]
# [6.17537874e-01 6.65696136e-01 2.27443285e-01 3.30970507e-01
# 5.85136215e-01 - 1.00000000e+00 2.39069293e-01 3.30410597e-01
# 1.21578381e+00 3.25195110e-01 1.36110743e+00 1.51974846e+00
# 4.02393985e-02 1.71555405e-01]
# [2.31567998e-01 2.49626667e-01 8.52880256e-02 1.24109275e-01
# 2.19417832e-01 2.01995810e-01 - 1.00000000e+00 1.23899316e-01
# 4.55901789e-01 1.21943582e-01 5.10396098e-01 5.69884250e-01
# 1.50892072e-02 6.43308585e-02]
# [1.68174721e+00 1.81289710e+00 6.19398623e-01 9.01335366e-01
# 1.59350744e+00 1.46698116e+00 6.51059851e-01 - 1.00000000e+00
# 3.31095647e+00 8.85607170e-01 3.70671778e+00 4.13874653e+00
# 1.09584366e-01 4.67198589e-01]
# [1.81548791e+00 1.95706747e+00 6.68656207e-01 9.73013928e-01
# 1.72023088e+00 1.58364262e+00 7.02835289e-01 9.71367859e-01
# - 1.00000000e+00 9.56034948e-01 4.00149396e+00 4.46787974e+00
# 1.18299046e-01 5.04352487e-01]
# [3.39180759e+00 3.65631535e+00 1.24922518e+00 1.81784523e+00
# 3.21384249e+00 2.95865979e+00 1.31308067e+00 1.81476994e+00
# 6.67765480e+00 - 1.00000000e+00 7.47584027e+00 8.34717123e+00
# 2.21013647e-01 9.42262733e-01]
# [3.80108803e+00 4.09751324e+00 1.39996587e+00 2.03719980e+00
# 3.60164835e+00 3.31567343e+00 1.47152663e+00 2.03375342e+00
# 7.48342971e+00 2.00165090e+00 - 1.00000000e+00 9.35440226e+00
# 2.47682778e-01 1.05596308e+00]
# [1.92350407e-01 2.07350720e-01 7.08439274e-02 1.03090538e-01
# 1.82257953e-01 1.67786468e-01 7.44651911e-02 1.02916137e-01
# 3.78691769e-01 1.01291620e-01 4.23957102e-01 - 1.00000000e+00
# 1.25337489e-02 5.34359969e-02]
# [3.30800641e-01 3.56597899e-01 1.21836065e-01 1.77293184e-01
# 3.13443828e-01 2.88556037e-01 1.28063846e-01 1.76993253e-01
# 6.51267039e-01 1.74199439e-01 7.29113514e-01 8.14093818e-01
# - 1.00000000e+00 9.18982306e-02]
# [6.67661381e-01 7.19728489e-01 2.45904104e-01 3.57834288e-01
# 6.32629787e-01 5.82398272e-01 2.58473757e-01 3.57228932e-01
# 1.31446496e+00 3.51590122e-01 1.47158401e+00 1.64310142e+00
# 4.35054974e-02 - 1.00000000e+00]]
| 42.693548 | 121 | 0.61894 | 1,208 | 7,941 | 4.014073 | 0.272351 | 0.024129 | 0.044545 | 0.028872 | 0.171788 | 0.113838 | 0.109713 | 0.058981 | 0.058981 | 0.058981 | 0 | 0.372342 | 0.23599 | 7,941 | 185 | 122 | 42.924324 | 0.4269 | 0.441002 | 0 | 0.113636 | 0 | 0 | 0.024759 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.136364 | false | 0 | 0.056818 | 0.011364 | 0.340909 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c92176317a4e7da05269c6ed1bd7c66b04ed3492 | 1,967 | py | Python | web/routing.py | stephanos/subtitlevocabulary | f452d7f35468912fe3967cfcf81c8f65cab345ec | [
"MIT"
] | 19 | 2017-04-20T00:57:36.000Z | 2018-01-06T10:47:38.000Z | web/routing.py | stephanos/subtitlevocabulary | f452d7f35468912fe3967cfcf81c8f65cab345ec | [
"MIT"
] | null | null | null | web/routing.py | stephanos/subtitlevocabulary | f452d7f35468912fe3967cfcf81c8f65cab345ec | [
"MIT"
] | 3 | 2018-01-01T06:27:48.000Z | 2020-04-09T17:21:28.000Z | import os
import jinja2
from flask_json import as_json
from web.routes.api_analysis import analysis_api
from web.routes.api_search import search_api
from web.routes.api_word import words_api
from web.routes.bootstrap import bootstrap
from web.routes.error import error
from api.dictionary.wordnik import Wordnik
from api.subtitle.opensubtitles import OpenSubtitles
from api.poster.fanart import FanArt
from domain.analyse import Analyser
from domain.corpus import Corpus, CorpusDatabase
from domain.load import Loader
from domain.parse import Parser
from domain.search import Searcher
TEMPLATE_ROOT = 'templates'
def create_routes(app):
app.jinja_loader = jinja2.FileSystemLoader(os.path.join(os.getcwd(), TEMPLATE_ROOT))
opensubtitle_credentials = (app.config['OPENSUBTITLES_USER'], app.config['OPENSUBTITLES_PASS'])
subtitle_api = OpenSubtitles(opensubtitle_credentials)
fanart_key = app.config['FANART_TV_KEY']
poster_api = FanArt(fanart_key)
wordnik_key = app.config['WORDNIK_KEY']
wordnik_api = Wordnik(wordnik_key)
searcher = Searcher(subtitle_api, poster_api)
corpus = Corpus(CorpusDatabase.FULL)
loader = Loader(subtitle_api)
parser = Parser()
analyser = Analyser(loader, parser, corpus)
@app.route('/')
def home_route():
return bootstrap()
@app.route('/m/<id>')
def analysis_route(id):
return bootstrap()
@app.route('/m/<id>/w/<word>')
def word_route(id, word):
return bootstrap()
@app.route('/error')
def error_route():
return error()
@app.route('/api/search/<query>')
@as_json
def search_api_route(query):
return search_api(searcher, query)
@app.route('/api/analysis/<id>')
@as_json
def analysis_api_route(id):
return analysis_api(analyser, poster_api, id)
@app.route('/api/words/<token>')
@as_json
def words_api_route(token):
return words_api(wordnik_api, token)
| 26.226667 | 99 | 0.719878 | 260 | 1,967 | 5.265385 | 0.226923 | 0.040906 | 0.04748 | 0.035062 | 0.065741 | 0.037984 | 0 | 0 | 0 | 0 | 0 | 0.001231 | 0.173869 | 1,967 | 74 | 100 | 26.581081 | 0.841231 | 0 | 0 | 0.111111 | 0 | 0 | 0.078292 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.148148 | false | 0.018519 | 0.296296 | 0.12963 | 0.574074 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
c922ef7067aac258a4e4cf3f6851f864d5293346 | 400 | py | Python | auv_control_pi/admin.py | adrienemery/auv-control-pi | 633fe89b652b07eb6ebe03c0550daa211b122297 | [
"MIT"
] | 9 | 2016-10-02T06:59:37.000Z | 2020-09-24T15:36:10.000Z | auv_control_pi/admin.py | adrienemery/auv-control-pi | 633fe89b652b07eb6ebe03c0550daa211b122297 | [
"MIT"
] | null | null | null | auv_control_pi/admin.py | adrienemery/auv-control-pi | 633fe89b652b07eb6ebe03c0550daa211b122297 | [
"MIT"
] | 4 | 2019-01-12T23:09:34.000Z | 2020-11-05T14:52:42.000Z | from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from solo.admin import SingletonModelAdmin
from .models import Configuration, AUVLog
admin.site.register(Configuration, SingletonModelAdmin)
admin.site.register(AUVLog, admin.ModelAdmin)
# remove auth models from admin
admin.site.unregister(User)
admin.site.unregister(Group)
| 30.769231 | 55 | 0.8375 | 53 | 400 | 6.320755 | 0.339623 | 0.107463 | 0.152239 | 0.125373 | 0.197015 | 0.197015 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0875 | 400 | 12 | 56 | 33.333333 | 0.917808 | 0.0725 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.555556 | 0 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
c92fd7f7ddcd94ac83d53a72a22847708de6dd65 | 848 | py | Python | tests/0100_utils/05_display_settings.py | sveetch/Optimus | 983aebeccd2ada7a5a0ab96f9296d4bba1112022 | [
"MIT"
] | 2 | 2019-05-31T00:23:15.000Z | 2021-04-26T07:26:16.000Z | tests/0100_utils/05_display_settings.py | sveetch/Optimus | 983aebeccd2ada7a5a0ab96f9296d4bba1112022 | [
"MIT"
] | 27 | 2015-04-21T14:43:26.000Z | 2022-01-29T00:42:53.000Z | tests/0100_utils/05_display_settings.py | sveetch/Optimus | 983aebeccd2ada7a5a0ab96f9296d4bba1112022 | [
"MIT"
] | 1 | 2017-05-21T17:32:28.000Z | 2017-05-21T17:32:28.000Z | from optimus.utils import display_settings
class DummySettings(object):
"""
Empty settings object
"""
def __init__(self):
pass
def test_basic(caplog):
"""
Basic initialize without ressources to sync
"""
conf = DummySettings()
conf.STRING = "ok"
conf.INTEGER = 42
conf.SEQ = [1, "hello", 42]
conf.MAP = {"hello": "world"}
conf.LOOSE = "meh"
display_settings(conf, ["STRING", "INTEGER", "SEQ", "MAP", "NOPE"])
# Check base setting directories
assert caplog.record_tuples == [
("optimus", 10, " - Settings.STRING = ok"),
("optimus", 10, " - Settings.INTEGER = 42"),
("optimus", 10, " - Settings.SEQ = [1, 'hello', 42]"),
("optimus", 10, " - Settings.MAP = {'hello': 'world'}"),
("optimus", 10, " - Settings.NOPE = NOT SET"),
]
| 24.228571 | 71 | 0.558962 | 91 | 848 | 5.120879 | 0.494505 | 0.096567 | 0.182403 | 0.04721 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.032051 | 0.264151 | 848 | 34 | 72 | 24.941176 | 0.714744 | 0.114387 | 0 | 0 | 0 | 0 | 0.306944 | 0 | 0 | 0 | 0 | 0 | 0.052632 | 1 | 0.105263 | false | 0.052632 | 0.052632 | 0 | 0.210526 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
c94e2d081759cfe3cc96c9284717b530cf3294f0 | 708 | py | Python | substratest/assets.py | AurelienGasser/substra-tests | 8f64d1b68e9148316e9e83293a4c34580bd18ca4 | [
"Apache-2.0"
] | 16 | 2019-10-25T13:34:42.000Z | 2020-09-01T13:53:44.000Z | substratest/assets.py | AurelienGasser/substra-tests | 8f64d1b68e9148316e9e83293a4c34580bd18ca4 | [
"Apache-2.0"
] | 96 | 2019-10-28T12:52:22.000Z | 2021-05-18T21:55:47.000Z | substratest/assets.py | AurelienGasser/substra-tests | 8f64d1b68e9148316e9e83293a4c34580bd18ca4 | [
"Apache-2.0"
] | 5 | 2019-10-25T13:46:48.000Z | 2021-02-09T09:40:41.000Z | import enum
class AssetType(enum.Enum):
algo = enum.auto()
aggregate_algo = enum.auto()
aggregatetuple = enum.auto()
composite_algo = enum.auto()
composite_traintuple = enum.auto()
data_sample = enum.auto()
dataset = enum.auto()
objective = enum.auto()
node = enum.auto()
testtuple = enum.auto()
traintuple = enum.auto()
compute_plan = enum.auto()
@classmethod
def all(cls):
return [e for e in cls]
@classmethod
def can_be_get(cls):
gettable = cls.all()
gettable.remove(cls.data_sample)
gettable.remove(cls.node)
return gettable
@classmethod
def can_be_listed(cls):
return cls.all()
| 22.125 | 40 | 0.618644 | 86 | 708 | 4.976744 | 0.372093 | 0.224299 | 0.084112 | 0.088785 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.266949 | 708 | 31 | 41 | 22.83871 | 0.824663 | 0 | 0 | 0.115385 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.115385 | false | 0 | 0.038462 | 0.076923 | 0.769231 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
c95f13943e7506d8e635b14bad6e17522594aa6b | 883 | py | Python | mfi_customization/mfi/patch/make_serial_no.py | anuradha-88/mfi_customization | eb19ed43d0178b461f1d9914d2f7b6b55c9d030c | [
"MIT"
] | null | null | null | mfi_customization/mfi/patch/make_serial_no.py | anuradha-88/mfi_customization | eb19ed43d0178b461f1d9914d2f7b6b55c9d030c | [
"MIT"
] | null | null | null | mfi_customization/mfi/patch/make_serial_no.py | anuradha-88/mfi_customization | eb19ed43d0178b461f1d9914d2f7b6b55c9d030c | [
"MIT"
] | null | null | null | import frappe
def execute():
for i in frappe.get_all('Asset',{'docstatus':1},['location','name','serial_no']):
if len(frappe.get_all('Asset Serial No',{'name':i.get("serial_no")})) == 0:
if i.get("serial_no"):
print("1111",i.get("serial_no"))
asset_srl_no = frappe.new_doc("Asset Serial No")
asset_srl_no.update({
"name": i.get("serial_no"),
"location": i.get("location"),
"asset":i.get("name"),
"serial_no":i.get("serial_no")
})
asset_srl_no.save()
# doc = frappe.get_doc('Asset Serial No',{'name':x})
print("******",i.get("serial_no"))
#mfi_customization.mfi.patch.make_serial_no.execute | 40.136364 | 85 | 0.458664 | 100 | 883 | 3.84 | 0.31 | 0.25 | 0.15625 | 0.1875 | 0.244792 | 0.114583 | 0.114583 | 0 | 0 | 0 | 0 | 0.010889 | 0.375991 | 883 | 22 | 86 | 40.136364 | 0.686025 | 0.11325 | 0 | 0 | 0 | 0 | 0.21895 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0.066667 | 0 | 0.133333 | 0.133333 | 0 | 0 | 0 | null | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c96407c99bcbcc54a359ce20f8e6498f45529b67 | 520 | py | Python | tests/tests_imports/test_single_import.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | tests/tests_imports/test_single_import.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | tests/tests_imports/test_single_import.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
import pytest
if __name__ == "__main__":
# import os
# import sys
# sys.path.append(os.path.realpath('..'))
pytest.main([__file__])
from tests.import_check import ImportCheck
def test_single():
# from ooobuild.lo.document.filter_options_request import FilterOptionsRequest
# ns = "ooobuild.lo.document.filter_options_request.FilterOptionsRequest"
ns = "ooobuild.lo.ucb.open_command_argument.OpenCommandArgument"
imc = ImportCheck()
assert imc.load_import(ns) == True
| 32.5 | 82 | 0.732692 | 63 | 520 | 5.714286 | 0.603175 | 0.083333 | 0.1 | 0.133333 | 0.211111 | 0.211111 | 0 | 0 | 0 | 0 | 0 | 0.002273 | 0.153846 | 520 | 15 | 83 | 34.666667 | 0.815909 | 0.428846 | 0 | 0 | 0 | 0 | 0.224138 | 0.196552 | 0 | 0 | 0 | 0 | 0.125 | 1 | 0.125 | false | 0 | 0.5 | 0 | 0.625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
c96f5948b76dab85a8793eb7ce9654314f52d570 | 873 | py | Python | wolk/interfaces/__init__.py | iperformance/WolkConnect-Python | 35c86511f5bb9d47d8ed98ad7623d2ef7ba061e3 | [
"Apache-2.0"
] | null | null | null | wolk/interfaces/__init__.py | iperformance/WolkConnect-Python | 35c86511f5bb9d47d8ed98ad7623d2ef7ba061e3 | [
"Apache-2.0"
] | null | null | null | wolk/interfaces/__init__.py | iperformance/WolkConnect-Python | 35c86511f5bb9d47d8ed98ad7623d2ef7ba061e3 | [
"Apache-2.0"
] | null | null | null | from .ActuationHandler import ActuationHandler
from .ActuatorStatusProvider import ActuatorStatusProvider
from .ConfigurationHandler import ConfigurationHandler
from .ConfigurationProvider import ConfigurationProvider
from .ConnectivityService import ConnectivityService
from .FirmwareInstaller import FirmwareInstaller
from .FirmwareURLDownloadHandler import FirmwareURLDownloadHandler
from .InboundMessageDeserializer import InboundMessageDeserializer
from .OutboundMessageFactory import OutboundMessageFactory
from .OutboundMessageQueue import OutboundMessageQueue
__all__ = [
"ActuationHandler",
"ActuatorStatusProvider",
"ConfigurationHandler",
"ConfigurationProvider",
"ConnectivityService",
"FirmwareInstaller",
"FirmwareURLDownloadHandler",
"InboundMessageDeserializer",
"OutboundMessageFactory",
"OutboundMessageQueue",
]
| 34.92 | 66 | 0.840779 | 51 | 873 | 14.313725 | 0.254902 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.109966 | 873 | 24 | 67 | 36.375 | 0.939511 | 0 | 0 | 0 | 0 | 0 | 0.239404 | 0.134021 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.454545 | 0 | 0.454545 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
c9703ef2605f4a86541cb07083dc8e85a029ce88 | 3,121 | py | Python | snippets/sign-madio.py | liushuaikobe/ConfigAndSnippets | 142fbc727510e7b51fa1069ac6f3865de228edcb | [
"MIT"
] | null | null | null | snippets/sign-madio.py | liushuaikobe/ConfigAndSnippets | 142fbc727510e7b51fa1069ac6f3865de228edcb | [
"MIT"
] | null | null | null | snippets/sign-madio.py | liushuaikobe/ConfigAndSnippets | 142fbc727510e7b51fa1069ac6f3865de228edcb | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Created on 2012-11-18
@author: liushuai
'''
import urllib, urllib2, cookielib, re
class LoginMadio:
login_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4'}
signin_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4','Referer':'http://www.madio.net','Origin':'http://www.madio.net'}
username = ''
password = ''
formhash = ''
cookie = None
cookieFile = "./LoginMadio_Cookie.dat"
def __init__(self, uname, pwd):
self.username = uname
self.password = pwd
self.cookie = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
urllib2.install_opener(opener)
def login(self):
postdata = {'username':self.username, 'password':self.password, 'quickforward':'yes', 'handlekey':'ls'}
postdata = urllib.urlencode(postdata)
print self.username, 'is Logining...'
req = urllib2.Request(url='http://www.madio.net/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1', data=postdata, headers=self.login_header)
result = urllib2.urlopen(req).read()
self.cookie.save(self.cookieFile)
if '登录失败' in result or '密码错误' in result:
print self.username,'login failed,please try later...'
else :
print self.username,'login successfully!'
req_after_logining = urllib2.Request('http://www.madio.net/')
html = urllib2.urlopen(req_after_logining).read()
raw_str = str(re.search(r'<input type="hidden" name="formhash" value="\w+" />',html).group())
raw_value = str(re.search(r'value="\w+"',raw_str).group())
self.formhash = raw_value[7:len(raw_value) - 1]
#print self.formhash
def signin(self):
postdata = {'formhash':self.formhash,'qdxq':'kx','qdmode':3,'todaysay':'','fastreply':1}
postdata = urllib.urlencode(postdata)
print self.username,'is signing...'
req = urllib2.Request(url = 'http://www.madio.net/plugin.php?id=dsu_paulsign:sign&operation=qiandao&infloat=1&sign_as=1&inajax=1',data=postdata,headers=self.signin_header)
result = urllib2.urlopen(req).read()
self.cookie.save(self.cookieFile)
if re.search(r'体力 \d+ 点',result) == None:
print self.username,'sign in failed!Maybe you have signed in today or some other reasons...'
else :
raw_earn = str(re.search(r'体力 \d+ 点',result).group())
earn = str(re.search(r'\d+',raw_earn).group())
print self.username,'signed in successfully,you earn',earn,'points...'
if __name__ == '__main__':
users = {"liushuaikobe1993@163.com":"XXX","zouliping007@163.com":"XXX","xxxpph@qq.com":"XXX"}
for userName in users:
user = LoginMadio(userName,users[userName])
user.login()
user.signin()
print '-' * 60
raw_input('Press Enter to terminate...')
| 48.015385 | 201 | 0.634092 | 405 | 3,121 | 4.804938 | 0.392593 | 0.049332 | 0.052415 | 0.038541 | 0.305755 | 0.293936 | 0.263104 | 0.243577 | 0.156218 | 0.156218 | 0 | 0.033803 | 0.203781 | 3,121 | 64 | 202 | 48.765625 | 0.749296 | 0.012816 | 0 | 0.153846 | 0 | 0.076923 | 0.322772 | 0.015512 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.057692 | 0.019231 | null | null | 0.134615 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
a335611ad6fc4dc915bec7b845089fcaff31bfe6 | 4,540 | py | Python | django/peering_coord/custom_fields.py | netsys-lab/scion-peering-coordinator | cd2fc9e9423242cafe90e71a54f4ad9e763acdae | [
"MIT"
] | null | null | null | django/peering_coord/custom_fields.py | netsys-lab/scion-peering-coordinator | cd2fc9e9423242cafe90e71a54f4ad9e763acdae | [
"MIT"
] | null | null | null | django/peering_coord/custom_fields.py | netsys-lab/scion-peering-coordinator | cd2fc9e9423242cafe90e71a54f4ad9e763acdae | [
"MIT"
] | null | null | null | """Custom Django model fields"""
import ipaddress
from typing import Optional, Union
from django.db import models
from django.core.exceptions import ValidationError
from django.forms import CharField
from peering_coord.scion_addr import ASN
IpAddress = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
IpNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
class AsnField(models.Field):
"""Model field holding an AS number. ASNs are stored as 64-bit integersin the DB."""
description = "AS number"
def get_internal_type(self):
return "BigIntegerField"
def formfield(self, **kwargs):
defaults = {'form_class': CharField}
defaults.update(kwargs)
return super().formfield(**defaults)
def from_db_value(self, value: Optional[int], expression, connection) -> Optional[ASN]:
if value is None:
return value
return ASN(value)
def get_prep_value(self, value: ASN) -> int:
return int(value)
def to_python(self, value: Union[None, int, str, ASN]) -> Optional[ASN]:
if isinstance(value, ASN):
return value
if value is None:
return value
try:
return ASN(value)
except ValueError as e:
raise ValidationError("Invalid AS number: '%(value)s'. Error: %(msg)s",
code='invalid_asn', params={'value': value, 'msg': str(e)})
class IpAddressField(models.Field):
"""IPv4/6 address as ipaddress.IPv4Address or ipaddress.IPv6Address.
Stored in the DB as char(39).
"""
description = "IP address"
def db_type(self, connection):
return 'char(39)'
def formfield(self, **kwargs):
defaults = {'form_class': CharField}
defaults.update(kwargs)
return super().formfield(**defaults)
def from_db_value(self, value: Optional[str], expression, connection) -> Optional[IpAddress]:
if value is None:
return value
# FIXME: rstrip is required to make this work with Postgres for some reason
return ipaddress.ip_address(value.rstrip())
def get_prep_value(self, value: IpAddress) -> str:
return value.exploded
def value_to_string(self, obj) -> str:
return self.get_prep_value(self.value_from_object(obj))
def to_python(self, value: Union[None, str, IpAddress]) -> Optional[IpAddress]:
if isinstance(value, ipaddress.IPv4Address) or isinstance(value, ipaddress.IPv6Address):
return value
if value is None:
return value
try:
return ipaddress.ip_address(value)
except ValueError as e:
raise ValidationError("Invalid IP address: '%(value)s'. Error: %(msg)s",
code='invalid_ip', params={'value': value, 'msg': str(e)})
class IpNetworkField(models.Field):
"""IPv4/6 network definition as ipaddress.IPv4Network or ipaddress.IPv6Network.
Stored in the DB as char(48).
"""
description = "IP network"
def db_type(self, connection):
return 'char(48)'
def formfield(self, **kwargs):
defaults = {'form_class': CharField}
defaults.update(kwargs)
return super().formfield(**defaults)
def from_db_value(self, value: Optional[str], expression, connection) -> Optional[IpNetwork]:
if value is None:
return value
# FIXME: rstrip is required to make this work with Postgres for some reason
return ipaddress.ip_network(value.rstrip())
def get_prep_value(self, value: IpNetwork) -> str:
return value.exploded
def value_to_string(self, obj) -> str:
return self.get_prep_value(self.value_from_object(obj))
def to_python(self, value: Union[None, str, IpAddress]) -> Optional[IpNetwork]:
if isinstance(value, ipaddress.IPv4Network) or isinstance(value, ipaddress.IPv6Network):
return value
if value is None:
return value
try:
return ipaddress.ip_network(value)
except ValueError as e:
raise ValidationError("Invalid IP network definition: '%(value)s'. Error: %(msg)s",
code='invalid_ip', params={'value': value, 'msg': str(e)})
class L4PortField(models.IntegerField):
"""L4 port number."""
description = "L4 port"
def validate(self, value, model_instance):
if value < 0 or value >= 2**16:
raise ValidationError("Invalid L4 port: %(value)d",
code='invalid_port', params={'value': value})
| 34.135338 | 97 | 0.645595 | 549 | 4,540 | 5.256831 | 0.211293 | 0.037422 | 0.038808 | 0.027027 | 0.58316 | 0.573458 | 0.543659 | 0.49203 | 0.450104 | 0.413375 | 0 | 0.009924 | 0.245374 | 4,540 | 132 | 98 | 34.393939 | 0.832458 | 0.104185 | 0 | 0.5 | 0 | 0 | 0.086027 | 0 | 0 | 0 | 0 | 0.015152 | 0 | 1 | 0.2 | false | 0 | 0.066667 | 0.088889 | 0.644444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
a33f381e4e9d104ca2777f1274143dd1bf91483d | 23,470 | py | Python | jb/EDA-DS1.py | james-w-balcomb/kaggle--home-credit-default-risk | b8346ba1640c42daf8457588f7fadd81ded74b8f | [
"Apache-2.0"
] | 4 | 2018-06-13T14:47:35.000Z | 2022-02-05T09:46:11.000Z | jb/EDA-DS1.py | james-w-balcomb/kaggle--home-credit-default-risk | b8346ba1640c42daf8457588f7fadd81ded74b8f | [
"Apache-2.0"
] | null | null | null | jb/EDA-DS1.py | james-w-balcomb/kaggle--home-credit-default-risk | b8346ba1640c42daf8457588f7fadd81ded74b8f | [
"Apache-2.0"
] | 2 | 2018-06-04T00:43:56.000Z | 2022-02-05T14:58:44.000Z |
# coding: utf-8
# In[ ]:
get_ipython().run_line_magic('run', 'NB03-EDA-MetaData-Check.ipynb')
# In[ ]:
# Columns where ‘Count of Unique Values Per Column’ is 2
for column_name in df_columns_number_of_unique_values:
if df_columns_number_of_unique_values[column_name] == 2:
print (column_name, 'dtype: ', df[column_name].dtype)
# # Dichotomous? (AKA binary / boolean)
# Columns where ‘Count of Unique Values Per Column’ is 2
#
# ### Dichotomous:
#
# FLAG_CONT_MOBILE
# FLAG_DOCUMENT_2
# FLAG_DOCUMENT_3
# FLAG_DOCUMENT_4
# FLAG_DOCUMENT_5
# FLAG_DOCUMENT_6
# FLAG_DOCUMENT_7
# FLAG_DOCUMENT_8
# FLAG_DOCUMENT_9
# FLAG_DOCUMENT_10
# FLAG_DOCUMENT_11
# FLAG_DOCUMENT_12
# FLAG_DOCUMENT_13
# FLAG_DOCUMENT_14
# FLAG_DOCUMENT_15
# FLAG_DOCUMENT_16
# FLAG_DOCUMENT_17
# FLAG_DOCUMENT_18
# FLAG_DOCUMENT_19
# FLAG_DOCUMENT_20
# FLAG_DOCUMENT_21
# FLAG_EMAIL
# FLAG_EMP_PHONE
# FLAG_MOBIL
# FLAG_OWN_CAR
# FLAG_OWN_REALTY
# FLAG_PHONE
# FLAG_WORK_PHONE
# LIVE_CITY_NOT_WORK_CITY
# LIVE_REGION_NOT_WORK_REGION
# NAME_CONTRACT_TYPE
# REG_CITY_NOT_LIVE_CITY
# REG_CITY_NOT_WORK_CITY
# REG_REGION_NOT_LIVE_REGION
# REG_REGION_NOT_WORK_REGION
#
# ### Polychotomous
# EMERGENCYSTATE_MODE
#
# ### Non-Model
# TARGET
# In[ ]:
df_dichotomous_column_names = [
'FLAG_CONT_MOBILE',
'FLAG_DOCUMENT_2',
'FLAG_DOCUMENT_3',
'FLAG_DOCUMENT_4',
'FLAG_DOCUMENT_5',
'FLAG_DOCUMENT_6',
'FLAG_DOCUMENT_7',
'FLAG_DOCUMENT_8',
'FLAG_DOCUMENT_9',
'FLAG_DOCUMENT_10',
'FLAG_DOCUMENT_11',
'FLAG_DOCUMENT_12',
'FLAG_DOCUMENT_13',
'FLAG_DOCUMENT_14',
'FLAG_DOCUMENT_15',
'FLAG_DOCUMENT_16',
'FLAG_DOCUMENT_17',
'FLAG_DOCUMENT_18',
'FLAG_DOCUMENT_19',
'FLAG_DOCUMENT_20',
'FLAG_DOCUMENT_21',
'FLAG_EMAIL',
'FLAG_EMP_PHONE',
'FLAG_MOBIL',
'FLAG_OWN_CAR',
'FLAG_OWN_REALTY',
'FLAG_PHONE',
'FLAG_WORK_PHONE',
'LIVE_CITY_NOT_WORK_CITY',
'LIVE_REGION_NOT_WORK_REGION',
'NAME_CONTRACT_TYPE',
'REG_CITY_NOT_LIVE_CITY',
'REG_CITY_NOT_WORK_CITY',
'REG_REGION_NOT_LIVE_REGION',
'REG_REGION_NOT_WORK_REGION'
]
# In[ ]:
for column_name in df_dichotomous_column_names:
if df_columns_number_of_unique_values[column_name] == 2:
print(df[column_name].value_counts(dropna=False, sort=True))
print(df[column_name].value_counts(dropna=False, normalize=True, sort=True))
# # NOT 0/1
#
# ### FLAG_OWN_CAR
# N 202924 (0.659892)
# Y 104587 (0.340108)
#
# ### FLAG_OWN_REALTY
# Y 213312 (0.693673)
# N 94199 (0.306327)
#
# ### NAME_CONTRACT_TYPE
# Cash loans 278232 (0.904787)
# Revolving loans 29279 (0.095213)
# NOTE: This is to be *converted* to a boolean, a la dummy coded, with "Cash loans" as the reference category.
# In[ ]:
df['FLAG_OWN_CAR'] = pd.Series(np.where(df['FLAG_OWN_CAR'].values == 'Y', 1, 0), df.index)
df['FLAG_OWN_CAR'].value_counts(dropna=False, sort=True)
# In[ ]:
df['FLAG_OWN_REALTY'] = pd.Series(np.where(df['FLAG_OWN_REALTY'].values == 'Y', 1, 0), df.index)
df['FLAG_OWN_REALTY'].value_counts(dropna=False, sort=True)
# In[ ]:
#df['NAME_CONTRACT_TYPE__Revolving_loans'] = pd.Series(np.where(df['NAME_CONTRACT_TYPE'].values == 'Revolving loans', 1, 0), df.index)
#df.drop('NAME_CONTRACT_TYPE', axis=1)
df.rename(columns={'NAME_CONTRACT_TYPE': 'NAME_CONTRACT_TYPE__Revolving_loans'}, inplace=True)
#df = df.rename(columns={'NAME_CONTRACT_TYPE': 'NAME_CONTRACT_TYPE__Revolving_loans'})
df['NAME_CONTRACT_TYPE__Revolving_loans'] = pd.Series(np.where(df['NAME_CONTRACT_TYPE__Revolving_loans'].values == 'Revolving loans', 1, 0), df.index)
df['NAME_CONTRACT_TYPE__Revolving_loans'].value_counts(dropna=False, sort=True)
# In[ ]:
# Columns where ‘Count of Unique Values Per Column’ is 3
for column_name in df_columns_number_of_unique_values:
if df_columns_number_of_unique_values[column_name] == 3:
print (column_name, 'dtype: ', df[column_name].dtype)
# In[ ]:
# Columns where ‘Count of Unique Values Per Column’ is 3
for column_name in df_columns_number_of_unique_values:
if df_columns_number_of_unique_values[column_name] == 3:
print(df[column_name].value_counts(dropna=False, sort=True))
print(df[column_name].value_counts(dropna=False, normalize=True, sort=True))
# ### CODE_GENDER
# Looks like we should deal with those four records with a missing value place-holder and convert it to a boolean, with "F" as the reference level.
#
# ### HOUSETYPE_MODE
# Not sure what is going on with this one. A little EDA provided no indication of pattern to the missingness.
# It seems likely that this is Missing Not At Random (MNAR) and, therefore, we should dig deeper.
# For now, moving forward with replacing the missing values with "MISSING" and treating it as "Unknown/Not Provided".
#
# ### REGION_RATING_CLIENT
# This should be treated as a Categorical - Ordinal variable.
# Check this relationship between this and REGION_RATING_CLIENT_W_CITY.
#
# ### REGION_RATING_CLIENT_W_CITY
# This should be treated as a Categorical - Ordinal variable.
# Check this relationship between this and REGION_RATING_CLIENT.
# # CODE_GENDER
# In[ ]:
df.loc[df.SK_ID_CURR == 141289, 'CODE_GENDER'] = 'F'
df.loc[df.SK_ID_CURR == 319880, 'CODE_GENDER'] = 'F'
df.loc[df.SK_ID_CURR == 196708, 'CODE_GENDER'] = 'F'
df.loc[df.SK_ID_CURR == 144669, 'CODE_GENDER'] = 'M'
# # HOUSETYPE_MODE
# # REGION_RATING_CLIENT
# # REGION_RATING_CLIENT_W_CITY
# In[ ]:
df[(df['FLAG_OWN_CAR'] == 0) & (df['OWN_CAR_AGE'].notnull())]
# In[ ]:
df[(df['FLAG_OWN_CAR'] == 1) & (df['OWN_CAR_AGE'].isnull())]
# In[ ]:
df[(df['FLAG_OWN_REALTY'] == 0) & (df['HOUSETYPE_MODE'].notnull())]
# In[ ]:
df[(df['FLAG_OWN_REALTY'] == 1) & (df['HOUSETYPE_MODE'].isnull())]
# # Correlation
# In[ ]:
print(df['EXT_SOURCE_1'].corr(df['EXT_SOURCE_2'], method='pearson'))
print(df['EXT_SOURCE_1'].corr(df['EXT_SOURCE_2'], method='spearman'))
print(df['EXT_SOURCE_1'].corr(df['EXT_SOURCE_2'], method='kendall'))
# In[ ]:
print(df['EXT_SOURCE_2'].corr(df['EXT_SOURCE_3'], method='pearson'))
print(df['EXT_SOURCE_2'].corr(df['EXT_SOURCE_3'], method='spearman'))
print(df['EXT_SOURCE_2'].corr(df['EXT_SOURCE_3'], method='kendall'))
# In[ ]:
print(df['EXT_SOURCE_3'].corr(df['EXT_SOURCE_1'], method='pearson'))
print(df['EXT_SOURCE_3'].corr(df['EXT_SOURCE_1'], method='spearman'))
print(df['EXT_SOURCE_3'].corr(df['EXT_SOURCE_1'], method='kendall'))
# In[ ]:
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_1'], method='pearson'))
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_1'], method='spearman'))
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_1'], method='kendall'))
# In[ ]:
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_2'], method='pearson'))
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_2'], method='spearman'))
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_2'], method='kendall'))
# In[ ]:
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_3'], method='pearson'))
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_3'], method='spearman'))
print(df['AMT_INCOME_TOTAL'].corr(df['EXT_SOURCE_3'], method='kendall'))
# In[ ]:
tmp_df = df[['TARGET', 'EXT_SOURCE_1']]
tmp_df = tmp_df.dropna()
tmp_df['TARGET'] = pd.to_numeric(tmp_df['TARGET'], errors='coerce')
print(tmp_df['TARGET'].dtype)
tmp_df['EXT_SOURCE_1'] = pd.to_numeric(tmp_df['EXT_SOURCE_1'], errors='coerce')
print(tmp_df['EXT_SOURCE_1'].dtype)
print(pointbiserialr(tmp_df['TARGET'], tmp_df['EXT_SOURCE_1']))
# In[ ]:
tmp_df = df[['TARGET', 'EXT_SOURCE_2']]
tmp_df = tmp_df.dropna()
pointbiserialr(tmp_df['TARGET'], tmp_df['EXT_SOURCE_2'])
# In[ ]:
tmp_df = df[['TARGET', 'EXT_SOURCE_3']]
tmp_df = tmp_df.dropna()
pointbiserialr(tmp_df['TARGET'], tmp_df['EXT_SOURCE_3'])
# In[ ]:
tmp_df = df[['TARGET', 'AMT_INCOME_TOTAL']]
tmp_df = tmp_df.dropna()
pointbiserialr(tmp_df['TARGET'], tmp_df['AMT_INCOME_TOTAL'])
# In[ ]:
sns.boxplot(x=df['AMT_INCOME_TOTAL']);
# In[ ]:
#sns.boxplot(x='TARGET', y='AMT_INCOME_TOTAL', data=df);
# In[ ]:
#az = sns.boxplot(x='TARGET', y='AMT_INCOME_TOTAL', data=df);
#az = sns.swarmplot(x='TARGET', y='AMT_INCOME_TOTAL', data=df, color='0.25');
# In[ ]:
sns.violinplot(x='TARGET', y='AMT_INCOME_TOTAL', data=df, scale='count');
# In[ ]:
print(df['AMT_INCOME_TOTAL'].min())
print(df['AMT_INCOME_TOTAL'].max())
print(df['AMT_INCOME_TOTAL'].mean())
print(df['AMT_INCOME_TOTAL'].median())
# In[ ]:
print(np.percentile(df['AMT_INCOME_TOTAL'], 10))
print(np.percentile(df['AMT_INCOME_TOTAL'], 20))
print(np.percentile(df['AMT_INCOME_TOTAL'], 30))
print(np.percentile(df['AMT_INCOME_TOTAL'], 40))
print(np.percentile(df['AMT_INCOME_TOTAL'], 50))
print(np.percentile(df['AMT_INCOME_TOTAL'], 60))
print(np.percentile(df['AMT_INCOME_TOTAL'], 70))
print(np.percentile(df['AMT_INCOME_TOTAL'], 80))
print(np.percentile(df['AMT_INCOME_TOTAL'], 90))
# In[ ]:
tmp_percentile_count_boundaries = list()
tmp_percentile_count_boundaries.append(df['AMT_INCOME_TOTAL'].min() - 1)
for iter in range(10,100,10):
tmp_percentile_count_boundaries.append(np.percentile(df['AMT_INCOME_TOTAL'], iter))
tmp_percentile_count_boundaries.append(df['AMT_INCOME_TOTAL'].max() + 1)
sorted(tmp_percentile_count_boundaries)
# In[ ]:
tmp_percentile_10th = np.percentile(df['AMT_INCOME_TOTAL'], 10)
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] <= tmp_percentile_10th)].count())
tmp_percentile_10th
# In[ ]:
column_name = 'AMT_INCOME_TOTAL'
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[0]) & (df[column_name] <= tmp_percentile_count_boundaries[1])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[1]) & (df[column_name] <= tmp_percentile_count_boundaries[2])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[2]) & (df[column_name] <= tmp_percentile_count_boundaries[3])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[3]) & (df[column_name] <= tmp_percentile_count_boundaries[4])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[4]) & (df[column_name] <= tmp_percentile_count_boundaries[5])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[5]) & (df[column_name] <= tmp_percentile_count_boundaries[6])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[6]) & (df[column_name] <= tmp_percentile_count_boundaries[7])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[7]) & (df[column_name] <= tmp_percentile_count_boundaries[8])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[8]) & (df[column_name] <= tmp_percentile_count_boundaries[9])].count())
print(df[column_name][(df[column_name] >= tmp_percentile_count_boundaries[9]) & (df[column_name] <= tmp_percentile_count_boundaries[10])].count())
# In[ ]:
print(np.percentile(df['AMT_INCOME_TOTAL'], 1))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] <= np.percentile(df['AMT_INCOME_TOTAL'], 1))].count()[0])
print(np.percentile(df['AMT_INCOME_TOTAL'], 99))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] >= np.percentile(df['AMT_INCOME_TOTAL'], 99))].count()[0])
# In[ ]:
print(np.percentile(df['AMT_INCOME_TOTAL'], 0.1))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] <= np.percentile(df['AMT_INCOME_TOTAL'], 0.1))].count()[0])
print(np.percentile(df['AMT_INCOME_TOTAL'], 99.9))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] >= np.percentile(df['AMT_INCOME_TOTAL'], 99.9))].count()[0])
# In[ ]:
print(np.percentile(df['AMT_INCOME_TOTAL'], 0.01))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] <= np.percentile(df['AMT_INCOME_TOTAL'], 0.01))].count()[0])
print(np.percentile(df['AMT_INCOME_TOTAL'], 99.99))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] >= np.percentile(df['AMT_INCOME_TOTAL'], 99.99))].count()[0])
# In[ ]:
print(np.percentile(df['AMT_INCOME_TOTAL'], 0.001))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] <= np.percentile(df['AMT_INCOME_TOTAL'], 0.001))].count()[0])
print(np.percentile(df['AMT_INCOME_TOTAL'], 99.999))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] >= np.percentile(df['AMT_INCOME_TOTAL'], 99.999))].count()[0])
# In[ ]:
print(np.percentile(df['AMT_INCOME_TOTAL'], 0.0001))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] <= np.percentile(df['AMT_INCOME_TOTAL'], 0.0001))].count()[0])
print(np.percentile(df['AMT_INCOME_TOTAL'], 99.9999))
print(df[['AMT_INCOME_TOTAL']][(df['AMT_INCOME_TOTAL'] >= np.percentile(df['AMT_INCOME_TOTAL'], 99.9999))].count()[0])
# In[ ]:
column_name = 'AMT_INCOME_TOTAL'
# In[ ]:
df[column_name].dtype
# In[ ]:
print(df[column_name].min())
print(df[column_name].max())
# In[ ]:
np.histogram(df[column_name])
# In[ ]:
plt.hist(df[column_name])
# In[ ]:
plt.hist(df[column_name])
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
plt.hist(df[column_name],
bins=[0,10000,100000,1000000,10000000,120000000])
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
# An "interface" to matplotlib.axes.Axes.hist() method
n, bins, patches = plt.hist(x=df[column_name],
bins='auto',
color='#0504aa',
alpha=0.7,
rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram of ' + column_name)
#plt.text(23, 45, r'$\mu=15, b=3$')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()
# In[ ]:
# An "interface" to matplotlib.axes.Axes.hist() method
n, bins, patches = plt.hist(x=df[column_name],
bins=10,
color='#0504aa',
alpha=0.7,
rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram of ' + column_name)
#plt.text(23, 45, r'$\mu=15, b=3$')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()
# In[ ]:
plt.hist(df[column_name],
bins=30,
normed=True,
alpha=0.5,
histtype='stepfilled',
color='steelblue',
edgecolor='none')
#plt.ticklabel_format(useOffset=False, style='plain', axis='both')
#plt.ticklabel_format(style='plain', axis='both')
#plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
df[column_name].plot.hist(grid=True,
bins=20,
rwidth=0.9,
color='#607c8e')
plt.title('Histogram of ' + column_name)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.grid(axis='y', alpha=0.75)
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
sp.stats.skew(df[column_name])
# In[ ]:
sp.stats.kurtosis(df[column_name])
# In[ ]:
df[column_name].max()
# In[ ]:
df[df[column_name] == 117000000.0]
# SK_ID_CURR
# 114967
# In[ ]:
df[[column_name]][df[column_name] != 117000000.0].max()
# In[ ]:
#plt.hist(df[[column_name]][df[column_name] != 117000000.0])
#plt.ticklabel_format(style='plain', axis='x')
#plt.show()
#> ---------------------------------------------------------------------------
#> AttributeError Traceback (most recent call last)
#> ~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in ticklabel_format(self, **kwargs)
#> 2567 if axis == 'both' or axis == 'x':
#> -> 2568 self.xaxis.major.formatter.set_scientific(sb)
#> 2569 if axis == 'both' or axis == 'y':
#>
#> AttributeError: 'StrCategoryFormatter' object has no attribute 'set_scientific'
#>
#> During handling of the above exception, another exception occurred:
#>
#> AttributeError Traceback (most recent call last)
#> <ipython-input-42-c0b04d2067b5> in <module>()
#> 1 plt.hist(df[[column_name]][df[column_name] != 117000000.0])
#> ----> 2 plt.ticklabel_format(style='plain', axis='x')
#> 3 plt.show()
#>
#> ~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in ticklabel_format(**kwargs)
#> 3749 @docstring.copy_dedent(Axes.ticklabel_format)
#> 3750 def ticklabel_format(**kwargs):
#> -> 3751 ret = gca().ticklabel_format(**kwargs)
#> 3752 return ret
#> 3753
#>
#> ~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in ticklabel_format(self, **kwargs)
#> 2591 except AttributeError:
#> 2592 raise AttributeError(
#> -> 2593 "This method only works with the ScalarFormatter.")
#> 2594
#> 2595 def locator_params(self, axis='both', tight=None, **kwargs):
#>
#> AttributeError: This method only works with the ScalarFormatter.
# In[ ]:
df[df['SK_ID_CURR'] == '114967']['AMT_INCOME_TOTAL']
#> 12840 117000000.0
#> Name: AMT_INCOME_TOTAL, dtype: float64
# In[ ]:
df.loc[df.SK_ID_CURR == '114967', 'AMT_INCOME_TOTAL'] = 0
# In[ ]:
df[df['SK_ID_CURR'] == '114967']['AMT_INCOME_TOTAL']
#> 12840 0.0
#> Name: AMT_INCOME_TOTAL, dtype: float64
# In[ ]:
plt.hist(df[column_name])
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
df[column_name].max()
# In[ ]:
df[df[column_name] == 18000090.0]['SK_ID_CURR']
#> 203693 336147
#> Name: SK_ID_CURR, dtype: object
# In[ ]:
df[df['SK_ID_CURR'] == '336147']['AMT_INCOME_TOTAL']
#> 203693 18000090.0
#> Name: AMT_INCOME_TOTAL, dtype: float64
# In[ ]:
df.loc[df.SK_ID_CURR == '336147', 'AMT_INCOME_TOTAL'] = 0
# In[ ]:
df[df['SK_ID_CURR'] == '336147']['AMT_INCOME_TOTAL']
#> 203693 0.0
#> Name: AMT_INCOME_TOTAL, dtype: float64
# In[ ]:
plt.hist(df[column_name])
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
df[column_name].max()
# In[ ]:
df[column_name].min()
# In[ ]:
df[column_name].median()
# In[ ]:
plt.hist(df[column_name],
bins=[0,25650,147150,1000000,120000000])
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
plt.hist(df[column_name],
bins=[0,10000,20000,30000,40000,50000,60000,70000,80000,90000,
100000,110000,120000,130000,140000,150000,160000,170000,180000,190000,
200000,210000,220000,230000,240000,250000,260000,270000,280000,290000,
300000,310000,320000,330000,340000,350000,360000,370000,380000,390000,
400000,410000,420000,430000,440000,450000,460000,470000,480000,490000,
500000,510000,520000,530000,540000,550000,560000,570000,580000,590000,
600000,610000,620000,630000,640000,650000,660000,670000,680000,690000,
700000,710000,720000,730000,740000,750000,760000,770000,780000,790000,
800000,810000,820000,830000,840000,850000,860000,870000,880000,890000,
900000,910000,920000,930000,940000,950000,960000,970000,980000,990000,
1000000])
plt.ticklabel_format(style='plain', axis='x')
plt.show()
# In[ ]:
df['ratio__AMT_CREDIT__ANNUITY_RATIO'] = df['AMT_CREDIT'] / df['AMT_ANNUITY']
# In[ ]:
df['ratio__AMT_INCOME_TOTAL__AMT_CREDIT'] = df['AMT_INCOME_TOTAL'] / df['AMT_CREDIT']
# In[ ]:
# How much of the price of the good was financed?
df['ratio__AMT_CREDIT_AMT_GOODS_PRICE'] = df['AMT_CREDIT'] / df['AMT_GOODS_PRICE']
# In[ ]:
DAYS_BIRTH
DAYS_EMPLOYED
DAYS_ID_PUBLISH
DAYS_LAST_PHONE_CHANGE
DAYS_REGISTRATION
# In[ ]:
df['ratio__DAYS_EMPLOYED__DAYS_BIRTH'] = df['DAYS_EMPLOYED'] / df['DAYS_BIRTH']
# In[ ]:
df['ratio__DAYS_ID_PUBLISH__DAYS_BIRTH'] = df['DAYS_ID_PUBLISH'] / df['DAYS_BIRTH']
# In[ ]:
df['ratio__DAYS_LAST_PHONE_CHANGE__DAYS_BIRTH'] = df['DAYS_LAST_PHONE_CHANGE'] / df['DAYS_BIRTH']
# In[ ]:
df['ratio__DAYS_REGISTRATION__DAYS_BIRTH'] = df['DAYS_REGISTRATION'] / df['DAYS_BIRTH']
# In[ ]:
flag_document_column_names = [
'FLAG_DOCUMENT_2',
'FLAG_DOCUMENT_3',
'FLAG_DOCUMENT_4',
'FLAG_DOCUMENT_5',
'FLAG_DOCUMENT_6',
'FLAG_DOCUMENT_7',
'FLAG_DOCUMENT_8',
'FLAG_DOCUMENT_9',
'FLAG_DOCUMENT_10',
'FLAG_DOCUMENT_11',
'FLAG_DOCUMENT_12',
'FLAG_DOCUMENT_13',
'FLAG_DOCUMENT_14',
'FLAG_DOCUMENT_15',
'FLAG_DOCUMENT_16',
'FLAG_DOCUMENT_17',
'FLAG_DOCUMENT_18',
'FLAG_DOCUMENT_19',
'FLAG_DOCUMENT_20',
'FLAG_DOCUMENT_21'
]
# In[ ]:
df[flag_document_column_names].count(axis=1)
# In[ ]:
df[flag_document_column_names].sum(axis=1)
# In[ ]:
df[flag_document_column_names].dtypes
# In[ ]:
df[flag_document_column_names].astype('int').sum(axis=1)
# In[ ]:
df['FLAG_DOCUMENT__count'] = df[flag_document_column_names].astype('int').sum(axis=1)
# In[ ]:
df['FLAG_DOCUMENT__count']
# In[ ]:
list(sorted(set(df['CNT_CHILDREN'].values)))
# In[ ]:
df['CNT_CHILDREN'].value_counts(ascending=True, dropna=False, sort=True)
# In[ ]:
df['CNT_CHILDREN'].value_counts(ascending=True, dropna=False, normalize=True, sort=True)
# # DAYS...
# DAYS_BIRTH
# DAYS_EMPLOYED
# DAYS_ID_PUBLISH
# DAYS_LAST_PHONE_CHANGE
# DAYS_REGISTRATION
# In[ ]:
df['DAYS_BIRTH'].min() / 365.25 * -1
# In[ ]:
df['DAYS_BIRTH'].max() / 365.25 * -1
# In[ ]:
df['DAYS_BIRTH'].value_counts(ascending=True, dropna=False, sort=True)
# In[ ]:
df['DAYS_BIRTH'].value_counts(ascending=True, dropna=False, normalize=True, sort=True)
# In[ ]:
df['DAYS_BIRTH'].hist();
# HOUSETYPE_MODE
# FLAG_OWN_REALTY
# In[ ]:
df['HOUSETYPE_MODE'].value_counts(ascending=True, dropna=False, sort=True)
# In[ ]:
df['FLAG_OWN_REALTY'].value_counts(ascending=True, dropna=False, sort=True)
# In[ ]:
pd.crosstab(df['FLAG_OWN_REALTY'], df['HOUSETYPE_MODE'], dropna=False)
# In[ ]:
pd.crosstab(df['HOUSETYPE_MODE'], df['FLAG_OWN_REALTY'], dropna=False)
# In[ ]:
import scipy.stats as stats
# In[ ]:
df_crosstab = pd.crosstab(index=df['FLAG_OWN_REALTY'], columns=df['HOUSETYPE_MODE'])
print(df_crosstab)
odds_ratio, p_value = stats.fisher_exact(df_crosstab)
print(odds_ratio)
print(p_value)
chi_square_statistic, p_value, degrees_of_freedom, expected_frequencies = stats.chi2_contingency(df_crosstab)
print(chi_square_statistic)
print(p_value)
print(degrees_of_freedom)
print(expected_frequencies)
# In[ ]:
df['HOUSETYPE_MODE'].fillna('MISSING', inplace=True)
# # Missing Values
# # Missing Values Place-Holders
#
# ### "XNA"
# ### 365243
# In[ ]:
df[df['CODE_GENDER'] == 'XNA']
# In[ ]:
df[df['ORGANIZATION_TYPE'] == 'XNA']
# In[ ]:
df[df['DAYS_EMPLOYED'] == 365243]
# In[ ]:
#df[df['CODE_GENDER'] == 'XNA']
#df[[['SK_ID_CURR','DAYS_EMPLOYED']],df['DAYS_EMPLOYED'] == 365243]
df[['SK_ID_CURR','DAYS_EMPLOYED']df['DAYS_EMPLOYED'] == 365243]
# In[ ]:
#df.loc[df['DAYS_EMPLOYED'] == 365243, 'SK_ID_CURR']
df.loc[df['DAYS_EMPLOYED'] == 365243, ['SK_ID_CURR', 'DAYS_EMPLOYED']]
# FLAG_OWN_CAR
# OWN_CAR_AGE
#
# FLAG_OWN_REALTY
#
# In[ ]:
df['FLAG_OWN_REALTY'].value_counts()
# In[ ]:
df['FLAG_OWN_CAR'].value_counts()
# In[ ]:
df['OWN_CAR_AGE'].describe()
# In[ ]:
df['OWN_CAR_AGE'].isnull().sum()
# In[ ]:
sns.violinplot(y='OWN_CAR_AGE', data=df, scale='count');
# In[ ]:
sns.violinplot(x='TARGET', y='OWN_CAR_AGE', data=df, scale='count');
# In[ ]:
sns.boxplot(y=df['OWN_CAR_AGE']);
# In[ ]:
sns.boxplot(x='TARGET', y='OWN_CAR_AGE', data=df);
| 21.832558 | 150 | 0.679932 | 3,440 | 23,470 | 4.338953 | 0.150872 | 0.053665 | 0.083478 | 0.076109 | 0.750435 | 0.705547 | 0.674528 | 0.619724 | 0.550583 | 0.512662 | 0 | 0.06945 | 0.138645 | 23,470 | 1,074 | 151 | 21.852886 | 0.668876 | 0.268385 | 0 | 0.35061 | 0 | 0 | 0.264949 | 0.03444 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.003049 | null | null | 0.243902 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a3464df77696845b07b009c666aa3678b61f43de | 3,879 | py | Python | tests/test_view.py | Philipp-Userlike/django-pystache | c720ee7a4b01f673dd2f476dae2e0c529229efe2 | [
"MIT"
] | 2 | 2015-11-05T08:53:49.000Z | 2016-03-01T22:14:12.000Z | tests/test_view.py | kennethreitz-archive/pystache | f543efac93b753914a20b9daaf84a51382fba445 | [
"MIT"
] | null | null | null | tests/test_view.py | kennethreitz-archive/pystache | f543efac93b753914a20b9daaf84a51382fba445 | [
"MIT"
] | 1 | 2020-02-12T19:11:42.000Z | 2020-02-12T19:11:42.000Z | import unittest
import pystache
from examples.simple import Simple
from examples.complex_view import ComplexView
from examples.lambdas import Lambdas
from examples.inverted import Inverted, InvertedLists
class Thing(object):
pass
class TestView(unittest.TestCase):
def test_basic(self):
view = Simple("Hi {{thing}}!", { 'thing': 'world' })
self.assertEquals(view.render(), "Hi world!")
def test_kwargs(self):
view = Simple("Hi {{thing}}!", thing='world')
self.assertEquals(view.render(), "Hi world!")
def test_template_load(self):
view = Simple(thing='world')
self.assertEquals(view.render(), "Hi world!")
def test_template_load_from_multiple_path(self):
path = Simple.template_path
Simple.template_path = ('examples/nowhere','examples',)
try:
view = Simple(thing='world')
self.assertEquals(view.render(), "Hi world!")
finally:
Simple.template_path = path
def test_template_load_from_multiple_path_fail(self):
path = Simple.template_path
Simple.template_path = ('examples/nowhere',)
try:
view = Simple(thing='world')
self.assertRaises(IOError, view.render)
finally:
Simple.template_path = path
def test_basic_method_calls(self):
view = Simple()
self.assertEquals(view.render(), "Hi pizza!")
def test_non_callable_attributes(self):
view = Simple()
view.thing = 'Chris'
self.assertEquals(view.render(), "Hi Chris!")
def test_view_instances_as_attributes(self):
other = Simple(name='chris')
other.template = '{{name}}'
view = Simple()
view.thing = other
self.assertEquals(view.render(), "Hi chris!")
def test_complex(self):
self.assertEquals(ComplexView().render(),
"""<h1>Colors</h1><ul><li><strong>red</strong></li><li><a href="#Green">green</a></li><li><a href="#Blue">blue</a></li></ul>""")
def test_higher_order_replace(self):
view = Lambdas()
self.assertEquals(view.render(),
'bar != bar. oh, it does!')
def test_higher_order_rot13(self):
view = Lambdas()
view.template = '{{#rot13}}abcdefghijklm{{/rot13}}'
self.assertEquals(view.render(), 'nopqrstuvwxyz')
def test_higher_order_lambda(self):
view = Lambdas()
view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}'
self.assertEquals(view.render(), 'abcdefghijklmnopqrstuvwxyz')
def test_partials_with_lambda(self):
view = Lambdas()
view.template = '{{>partial_with_lambda}}'
self.assertEquals(view.render(), 'nopqrstuvwxyz')
def test_hierarchical_partials_with_lambdas(self):
view = Lambdas()
view.template = '{{>partial_with_partial_and_lambda}}'
self.assertEquals(view.render(), 'nopqrstuvwxyznopqrstuvwxyz')
def test_inverted(self):
view = Inverted()
self.assertEquals(view.render(), """one, two, three, empty list""")
def test_accessing_properties_on_parent_object_from_child_objects(self):
parent = Thing()
parent.this = 'derp'
parent.children = [Thing()]
view = Simple(context={'parent': parent})
view.template = "{{#parent}}{{#children}}{{this}}{{/children}}{{/parent}}"
self.assertEquals(view.render(), 'derp')
def test_context_returns_a_flattened_dict(self):
view = Simple()
view.context_list = [{'one':'1'}, {'two':'2'}, object()]
self.assertEqual(view.context, {'one': '1', 'two': '2'})
def test_inverted_lists(self):
view = InvertedLists()
self.assertEquals(view.render(), """one, two, three, empty list""")
if __name__ == '__main__':
unittest.main()
| 34.327434 | 140 | 0.619232 | 426 | 3,879 | 5.450704 | 0.239437 | 0.054264 | 0.129199 | 0.167959 | 0.437123 | 0.397071 | 0.367356 | 0.245047 | 0.210594 | 0.170973 | 0 | 0.004034 | 0.23305 | 3,879 | 112 | 141 | 34.633929 | 0.776471 | 0 | 0 | 0.314607 | 0 | 0 | 0.15032 | 0.065299 | 0 | 0 | 0 | 0 | 0.202247 | 1 | 0.202247 | false | 0.011236 | 0.067416 | 0 | 0.292135 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a34e50b4e53e329d2fa7d7fb9d15a34c2182d291 | 425 | py | Python | sendWhatsappMessage.py | systemquant/DeFi_PanCakeSwapBot | 39665bfd095e9b571a70699926c080882e5b456d | [
"MIT"
] | 142 | 2021-08-30T19:57:29.000Z | 2022-03-30T15:03:35.000Z | sendWhatsappMessage.py | systemquant/DeFi_PanCakeSwapBot | 39665bfd095e9b571a70699926c080882e5b456d | [
"MIT"
] | 21 | 2021-09-04T20:57:31.000Z | 2022-03-02T00:09:08.000Z | sendWhatsappMessage.py | systemquant/DeFi_PanCakeSwapBot | 39665bfd095e9b571a70699926c080882e5b456d | [
"MIT"
] | 116 | 2021-09-01T13:32:46.000Z | 2022-03-29T05:17:15.000Z | import pywhatkit as py
import keyboard
import time
from datetime import datetime
def sendMessage(numbers, message, price):
for number in numbers:
py.sendwhatmsg(number, "{}: {:.10f}".format(message, price), datetime.now().hour,
datetime.now().minute + 2)
keyboard.press_and_release('ctrl+w')
time.sleep(1)
keyboard.press_and_release('enter')
time.sleep(1)
| 28.333333 | 89 | 0.642353 | 52 | 425 | 5.173077 | 0.596154 | 0.089219 | 0.118959 | 0.171004 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015432 | 0.237647 | 425 | 14 | 90 | 30.357143 | 0.814815 | 0 | 0 | 0.166667 | 0 | 0 | 0.051765 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.083333 | false | 0 | 0.333333 | 0 | 0.416667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
a35da87497581938c34f56b7591df4443a8bd38e | 2,052 | py | Python | bot/py/py-irc-8.5.1/irc/buffer.py | sonoprob/0x56 | fa4cf9365696b1461492244a016e3fb57a33ce7a | [
"Artistic-2.0"
] | 1 | 2020-02-25T10:47:00.000Z | 2020-02-25T10:47:00.000Z | irc/buffer.py | suut/psychic-happiness | 56c0daef93f40b91e8a859f04a4660dde2b5c5c1 | [
"Unlicense"
] | null | null | null | irc/buffer.py | suut/psychic-happiness | 56c0daef93f40b91e8a859f04a4660dde2b5c5c1 | [
"Unlicense"
] | null | null | null | from __future__ import unicode_literals
import re
class LineBuffer(object):
r"""
Buffer bytes read in from a connection and serve complete lines back.
>>> b = LineBuffer()
>>> len(b)
0
>>> b.feed(b'foo\nbar')
>>> len(b)
7
>>> list(b.lines()) == [b'foo']
True
>>> len(b)
3
>>> b.feed(b'bar\r\nbaz\n')
>>> list(b.lines()) == [b'barbar', b'baz']
True
>>> len(b)
0
The buffer will not perform any decoding.
>>> b.feed(b'Ol\xe9\n')
>>> list(b.lines()) == [b'Ol\xe9']
True
The LineBuffer should also act as an iterable.
>>> b.feed(b'iterate\nthis\n')
>>> for line, expected in zip(b, [b'iterate', b'this']):
... assert line == expected
"""
line_sep_exp = re.compile(b'\r?\n')
def __init__(self):
self.buffer = b''
def feed(self, bytes):
self.buffer += bytes
def lines(self):
lines = self.line_sep_exp.split(self.buffer)
# save the last, unfinished, possibly empty line
self.buffer = lines.pop()
return iter(lines)
def __iter__(self):
return self.lines()
def __len__(self):
return len(self.buffer)
class DecodingLineBuffer(LineBuffer):
r"""
Like LineBuffer, but decode the output (default assumes UTF-8).
>>> utf8_word = b'Ol\xc3\xa9'
>>> b = DecodingLineBuffer()
>>> b.feed(b'bar\r\nbaz\n' + utf8_word + b'\n')
>>> list(b.lines()) == ['bar', 'baz', utf8_word.decode('utf-8')]
True
>>> len(b)
0
Some clients will feed latin-1 or other encodings. If your client should
support docoding from these clients (and not raise a UnicodeDecodeError),
set errors='replace':
>>> rb = DecodingLineBuffer()
>>> b.errors = 'replace'
>>> b.feed(b'Ol\xe9\n')
>>> list(b.lines()) == ['Ol\ufffd']
True
"""
encoding = 'utf-8'
errors = 'strict'
def lines(self):
return (line.decode(self.encoding, self.errors)
for line in super(DecodingLineBuffer, self).lines())
| 24.141176 | 77 | 0.57115 | 281 | 2,052 | 4.085409 | 0.3879 | 0.026132 | 0.031359 | 0.038328 | 0.074913 | 0.06446 | 0.06446 | 0.038328 | 0.038328 | 0 | 0 | 0.011229 | 0.262183 | 2,052 | 84 | 78 | 24.428571 | 0.747028 | 0.560429 | 0 | 0.083333 | 0 | 0 | 0.022253 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.083333 | 0.125 | 0.708333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
a36257679bdb3db982e64c451a25613c1cbcc601 | 969 | py | Python | src/cli.py | jpsecher/py-cli | b053ead3b830136517726f036ded713661ab9f3e | [
"0BSD"
] | null | null | null | src/cli.py | jpsecher/py-cli | b053ead3b830136517726f036ded713661ab9f3e | [
"0BSD"
] | null | null | null | src/cli.py | jpsecher/py-cli | b053ead3b830136517726f036ded713661ab9f3e | [
"0BSD"
] | null | null | null | import argparse
from typing import Sequence
class CLI:
def __init__(self, description: str, args: Sequence[str]):
self._cli_args = args
self._parser = argparse.ArgumentParser(description=description)
def set_up_log(self) -> None:
pass
def logfile(self) -> str:
# TODO: yyyy-mm-dd/hh-mm-ss-hash-name.log
return self._args.logdir + '/ost.log'
def epilog(self) -> str:
return self._args.logdir
def parse_args(self) -> None:
self._parser.add_argument(
'-V', '--version', action='count', help='show application version')
self._parser.add_argument(
'-v', '--verbose', action='count', default=0,
help='Verbose output (repeat to increase)')
self._parser.add_argument(
'--logdir', default='logs', metavar='DIR',
help='logs are stored in this directory')
self._args = self._parser.parse_args(args=self._cli_args)
| 32.3 | 79 | 0.617131 | 120 | 969 | 4.791667 | 0.483333 | 0.086957 | 0.067826 | 0.109565 | 0.076522 | 0 | 0 | 0 | 0 | 0 | 0 | 0.001376 | 0.249742 | 969 | 29 | 80 | 33.413793 | 0.789546 | 0.040248 | 0 | 0.136364 | 0 | 0 | 0.158405 | 0 | 0 | 0 | 0 | 0.034483 | 0 | 1 | 0.227273 | false | 0.045455 | 0.090909 | 0.090909 | 0.454545 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a38e9a097ca302efc71274f8e18c61b719a4f6f3 | 1,052 | py | Python | dduplicated/commands.py | messiasthi/Dduplicated | c2958b6e41e761a13ea004e0efce036966fee005 | [
"MIT"
] | null | null | null | dduplicated/commands.py | messiasthi/Dduplicated | c2958b6e41e761a13ea004e0efce036966fee005 | [
"MIT"
] | null | null | null | dduplicated/commands.py | messiasthi/Dduplicated | c2958b6e41e761a13ea004e0efce036966fee005 | [
"MIT"
] | 1 | 2018-02-15T18:09:13.000Z | 2018-02-15T18:09:13.000Z | from dduplicated import scans, fileManager
def detect(paths, verbose=False):
return scans.scan(paths, False, False, verbose)
# Remove all duplicates
def delete(files, verbose=False):
return scans.scan(files, True, False, verbose)
# Make the link to first file
def link(files, verbose=False):
return scans.scan(files, True, True, verbose)
def rmdir(paths):
dirs = []
for path in paths:
dirs += fileManager.rrmdir(path)
return dirs
# Print the help menu
def show_help():
print("""
dduplicate is a simple script in python for detect and delete duplicate files in your directory
finded duplicated files, is possible delete, link or do nothing.
Command:
\tdetect\tPATHS\tfor only search and detect duplicated files in directory.
\tdelete\tPATHS\tfor delete any duplicated files in directory, not first file.
\tlink\tPATHS\tfor link first all duplicates in first file.
\trmdir\tPATHS\tfor remove all directories and subdirectories empty.
\tno-verbose\t\tfor not show all steps executed
\thelp\t\tshow this help
""")
| 29.222222 | 96 | 0.75 | 155 | 1,052 | 5.083871 | 0.458065 | 0.050761 | 0.068528 | 0.087563 | 0.138325 | 0.104061 | 0.104061 | 0.104061 | 0 | 0 | 0 | 0 | 0.16635 | 1,052 | 35 | 97 | 30.057143 | 0.898518 | 0.065589 | 0 | 0 | 0 | 0 | 0.548519 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.208333 | false | 0 | 0.041667 | 0.125 | 0.416667 | 0.041667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
a3a43b217a549397ed1da56f956e5e85c4d32162 | 4,419 | py | Python | upgrade/1.4.5/aquilon/aqdb/model/system.py | ned21/aquilon | 6562ea0f224cda33b72a6f7664f48d65f96bd41a | [
"Apache-2.0"
] | 7 | 2015-07-31T05:57:30.000Z | 2021-09-07T15:18:56.000Z | upgrade/1.4.5/aquilon/aqdb/model/system.py | ned21/aquilon | 6562ea0f224cda33b72a6f7664f48d65f96bd41a | [
"Apache-2.0"
] | 115 | 2015-03-03T13:11:46.000Z | 2021-09-20T12:42:24.000Z | upgrade/1.4.5/aquilon/aqdb/model/system.py | ned21/aquilon | 6562ea0f224cda33b72a6f7664f48d65f96bd41a | [
"Apache-2.0"
] | 13 | 2015-03-03T11:17:59.000Z | 2021-09-09T09:16:41.000Z | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2013 Contributor
#
# 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.
""" Systems are higher level constructs which can provide services """
from datetime import datetime
from sqlalchemy import (Table, Integer, DateTime, Sequence, String, Column,
ForeignKey, UniqueConstraint)
from sqlalchemy.orm import relation, deferred, backref
from aquilon.aqdb.model import Base, DnsDomain, Network
from aquilon.aqdb.column_types import AqStr, IPV4, AqMac
#TODO: enum type for system_type column
#_sys_types = ['host', 'tor_switch', 'console_switch', 'chassis', 'manager',
# 'auxiliary' ]
class System(Base):
""" System: a base class which abstracts out the details of between
all the various kinds of service providers we may use. A System might be
a host/server/workstation, router, firewall, netapp, etc. Naming this
is kind of difficult, but "system" seems neutral, and happens not to
be overloaded by anything I am aware of.
This is exactly what system does. System_id holds a name, and presents
an abstract entity that can provide, or utilize services, hardware,
networks, configuration sources, etc. It's subtyped for flexibilty to
weather future expansion and enhancement without breaking the
fundamental archetypes we're building today.
It is perhaps the most important table so far, and replaces the notion
of 'host' as we've used it in our discussions and designs thus far.
"""
__tablename__ = 'system'
id = Column(Integer, Sequence('SYSTEM_SEQ'), primary_key=True)
name = Column(AqStr(64), nullable=False)
#TODO: create enum_types for this
system_type = Column(AqStr(32), nullable=False)
dns_domain_id = Column(Integer, ForeignKey('dns_domain.id',
name='SYSTEM_DNS_FK'),
nullable=False ) #TODO: default
mac = Column(AqMac(17), nullable=True)
ip = Column(IPV4, nullable=True)
network_id = Column(Integer, ForeignKey('network.id',
name='SYSTEM_NET_ID_FK'),
nullable=True)
creation_date = deferred(Column( DateTime, default=datetime.now,
nullable=False))
comments = deferred(Column('comments', String(255), nullable=True))
dns_domain = relation(DnsDomain)
network = relation(Network, backref='interfaces')
__mapper_args__ = {'polymorphic_on' : system_type}
def _fqdn(self):
return '.'.join([str(self.name),str(self.dns_domain.name)])
fqdn = property(_fqdn)
system = System.__table__
system.primary_key.name='SYSTEM_PK'
system.append_constraint(
UniqueConstraint('name','dns_domain_id', name='SYSTEM_DNS_NAME_UK'))
system.append_constraint( #systm_pt_uk means 'primary tuple'
UniqueConstraint('name', 'dns_domain_id', 'mac', 'ip', name='SYSTEM_PT_UK'))
table = system
class DynamicStub(System):
"""
DynamicStub is a hack to handle stand alone dns records for dynamic
hosts prior to having a properly reworked set of tables for Dns
information. It should not be used by anything other than to create host
records for virtual machines using names similar to
'dynamic-1-2-3-4.subdomain.ms.com'
"""
__tablename__ = 'dynamic_stub'
__mapper_args__ = {'polymorphic_identity':'dynamic_stub'}
system_id = Column(Integer, ForeignKey('system.id',
name='dynamic_stub_system_fk',
ondelete='CASCADE'),
primary_key=True)
DynamicStub.__table__.primary_key.name='dynamic_stub_pk'
| 40.916667 | 80 | 0.66644 | 560 | 4,419 | 5.117857 | 0.478571 | 0.020935 | 0.020935 | 0.026169 | 0.034543 | 0.016748 | 0 | 0 | 0 | 0 | 0 | 0.011415 | 0.246662 | 4,419 | 107 | 81 | 41.299065 | 0.849504 | 0.455759 | 0 | 0.046512 | 0 | 0 | 0.123934 | 0.009879 | 0 | 0 | 0 | 0.018692 | 0 | 1 | 0.023256 | false | 0 | 0.116279 | 0.023256 | 0.604651 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
6e60119d3b530316516c697b435c156b0ce6bd9d | 20,979 | py | Python | web.py | nicehero/h5game_platform | 238d71e51b14781c1178fe97f0a9d7ab7686e75d | [
"BSD-3-Clause"
] | null | null | null | web.py | nicehero/h5game_platform | 238d71e51b14781c1178fe97f0a9d7ab7686e75d | [
"BSD-3-Clause"
] | null | null | null | web.py | nicehero/h5game_platform | 238d71e51b14781c1178fe97f0a9d7ab7686e75d | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import traceback
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.domain.AlipayTradeAppPayModel import AlipayTradeAppPayModel
from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
from alipay.aop.api.domain.AlipayTradeWapPayModel import AlipayTradeWapPayModel
from alipay.aop.api.domain.AlipayTradeQueryModel import AlipayTradeQueryModel
from alipay.aop.api.domain.AlipayTradePayModel import AlipayTradePayModel
from alipay.aop.api.domain.GoodsDetail import GoodsDetail
from alipay.aop.api.domain.SettleDetailInfo import SettleDetailInfo
from alipay.aop.api.domain.SettleInfo import SettleInfo
from alipay.aop.api.domain.SubMerchant import SubMerchant
from alipay.aop.api.request.AlipayOfflineMaterialImageUploadRequest import AlipayOfflineMaterialImageUploadRequest
from alipay.aop.api.request.AlipayTradeAppPayRequest import AlipayTradeAppPayRequest
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
from alipay.aop.api.request.AlipayTradeWapPayRequest import AlipayTradeWapPayRequest
from alipay.aop.api.request.AlipayTradePayRequest import AlipayTradePayRequest
from alipay.aop.api.request.AlipayTradeQueryRequest import AlipayTradeQueryRequest
from alipay.aop.api.response.AlipayOfflineMaterialImageUploadResponse import AlipayOfflineMaterialImageUploadResponse
from alipay.aop.api.response.AlipayTradePayResponse import AlipayTradePayResponse
import tornado.ioloop
import tornado.web
import tornado.escape
import tornado.options
import tornado.websocket
import tornado.autoreload
import tornado.httpclient
import tornado.auth
from tornado.httputil import url_concat
#import urllib2
import base64
import os
import hashlib
import time
import json
import struct
import datetime
import logging
import urllib
import urllib.request
import uuid
import re
import pickle
# 写入pickle
def pickle_write(file_path, data):
f = open("./data/" + file_path, 'wb')
pickle.dump(data, f)
f.close()
# 读取pickle
def pickle_read(file_path):
try:
f = open("./data/" + file_path, 'rb')
data = pickle.load(f)
f.close()
return data
except:
return None
#url1 = "http://127.0.0.1:8810/"
games = {
"tinyHeart":{"name":"TinyHeart","img":"th.png","cost":0.1},
"linkGame":{"name":"连连看","img":"IMG20190118_173659.png","cost":0.0},
"2048":{"name":"2048","img":"2048x.jpg","cost":0.0},
"Gobang":{"name":"五子棋","img":"Gobangx.jpg","cost":0.0},
"RetroSnaker":{"name":"贪吃蛇","img":"snake.jpg","cost":0.0},
"Tetris":{"name":"俄罗斯方块","img":"Tetrisx.jpg","cost":0.0},
"tinyHeartFree":{"name":"TinyHeart免费版","img":"th.png","cost":0.0},
}#game list
plogin = '''
<html>
<style>
center
{
margin-top:100px;
margin-bottom:100px;
margin-right:50px;
margin-left:50px;
}
</style>
<body>
<script src="static/sha256.min.js"></script>
<script>
function getParam(par){
var local_url = document.location.href;
var get = local_url.indexOf(par +"=");
if(get == -1){
return "";
}
var get_par = local_url.slice(par.length + get + 1);
var nextPar = get_par.indexOf("&");
if(nextPar != -1){
get_par = get_par.slice(0, nextPar);
}
return decodeURIComponent(get_par);
}
function login(){
let PARAMS = {}
PARAMS.username = document.getElementById('username').value;
PARAMS.password = sha256(document.getElementById('password').value);
PARAMS.next = getParam('next').replace('/','')
//document.cookie = "username=" + username
//document.cookie = "pass=" + password
//window.location.href='/'
var temp = document.createElement("form");
temp.action = "/login";
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
let r = temp.submit();
console.log(r);
return temp;
}
</script>
<center>
<div>用户名: <input type="text" name="username" id="username"></div>
<div>密码: <input type="password" name="password" id="password"></div>
<div><input type='button' value='登陆' onclick='login()'></input>
<a id="hrefSignup">注册</a></div>
<div><a href="./">返回主页</a></div>
</center>
<script>
let next = getParam('next').replace('/','')
if (next == ""){
document.getElementById("hrefSignup").setAttribute("href","./signup");
}
else {
document.getElementById("hrefSignup").setAttribute("href","./signup?next=" + next);
}
message = "%s";
if (message != ""){
alert(message);
}
</script>
</body></html>
'''
psignup = '''
<html>
<style>
center
{
margin-top:100px;
margin-bottom:100px;
margin-right:50px;
margin-left:100px;
}
</style>
<body>
<script src="static/sha256.min.js"></script>
<script>
function getParam(par){
var local_url = document.location.href;
var get = local_url.indexOf(par +"=");
if(get == -1){
return "";
}
var get_par = local_url.slice(par.length + get + 1);
var nextPar = get_par.indexOf("&");
if(nextPar != -1){
get_par = get_par.slice(0, nextPar);
}
return decodeURIComponent(get_par);
}
function signup(){
let PARAMS = {}
PARAMS.username = document.getElementById('username').value;
PARAMS.password = sha256(document.getElementById('password').value);
let passwordAgain = sha256(document.getElementById('passwordAgain').value);
if (PARAMS.password != passwordAgain){
alert("两次密码输入不同!");
return;
}
PARAMS.next = getParam('next').replace('/','')
//document.cookie = "username=" + username
//document.cookie = "pass=" + password
//window.location.href='/'
var temp = document.createElement("form");
temp.action = "/signup";
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
let r = temp.submit();
console.log(r);
return temp;
}
</script>
<center><div align="left">
<div><div>用户名:</div> <input type="text" name="username" id="username">用户名需要6到12个字母或数字或下划线_,只能字母开头</div>
<div><div>密码:</div> <input type="password" name="password" id="password">密码需要8到12个字母或数字加特殊符号</div>
<div><div>再输入一次密码:</div> <input type="password" name="password" id="passwordAgain"></div>
<div><input type='button' value='注册' onclick='signup()'></input></div>
<div><a href="./">返回主页</a></div>
</div></center>
<script>
message = "%s";
if (message != ""){
alert(message);
}
</script>
</body></html>
'''
NUM_LETTER = re.compile("^(?!\d+$)[\da-zA-Z_]+$") #数字和字母组合,不允许纯数字
FIRST_LETTER = re.compile("^[a-zA-Z]") #只能以字母开头
def account_name_format(Name):
if NUM_LETTER.search(Name):
if FIRST_LETTER.search(Name):
return True
return False
SESSION = {}
USERS = {}
class Session:
def __init__(self, handler):
self.handler = handler
@staticmethod
def _random_str():
'''用随机数来作为session_id'''
return str(uuid.uuid4())
def _get_cookie_sid(self):
'''获取cookie中的session_id'''
cookie_sid = self.handler.get_secure_cookie("__session", None)
return str(cookie_sid, encoding="utf-8") if cookie_sid else None
def __setitem__(self, key, value):
cookie_sid = self._get_cookie_sid()
if not cookie_sid:
cookie_sid = self._random_str()
self.handler.set_secure_cookie("__session", cookie_sid,samesite="Lax")
SESSION.setdefault(cookie_sid, {"username" : ""}).__setitem__(key, value)
def __getitem__(self, key):
cookie_sid = self._get_cookie_sid()
content = SESSION.get(cookie_sid, None)
return content.get(key, None) if content else None
def __delitem__(self, key):
cookie_sid = self._get_cookie_sid()
if not cookie_sid or not SESSION.get(cookie_sid):
raise KeyError(key)
del SESSION[cookie_sid][key]
class MyHandler(tornado.web.RequestHandler):
def get_current_user(self):
current_user = self.session["username"]
if current_user != "":
return current_user
return None
def initialize(self):
self.session = Session(self)
gf = open("index.html",'rb')
mainIndex = gf.read().decode()
gf.close()
gt = '''<div id = "%s" name="game"><a href="./%s"><div><img src="./static/%s"/></div><div><font size="3">%s</font></div></a>
<div><font size="5" color="#FF0000">¥%s</font></div></div>
'''
gt1 = '''<div class="s-top-left">欢迎光临!</div>
<div class="s-top-right">
<div class="noLine"><a href="login">登陆</a></div>
<div class="noLine"><a href="signup">注册</a></div>
</div>
'''
gt2 = '''<div class="s-top-left">你好:%s!</div>
<div class="s-top-right">
<a href="./?logout=1">退出</a>
</div>
'''
class MainHandler(MyHandler):
def get(self):
isLogout = self.get_argument('logout',"")
if isLogout != "":
self.session["username"] = ""
global mainIndex
global gt
global gt1
user = self.current_user
s = ""
u = None
if user in USERS:
u = USERS[user]
print("--------------------")
print(u)
print("--------------------")
for i in games.keys():
scost = "免费";
if games[i]["cost"] > 0.009:
scost = str(games[i]["cost"])
try:
if i in u["had"]:
scost = "已购"
except:
pass
s = s + (gt % (games[i]["name"],i,games[i]["img"],games[i]["name"],scost))
if user != None:
self.write(mainIndex % (gt2%user,s))
else:
self.write(mainIndex % (gt1,s))
class LoginHandler(MyHandler):
def get(self):
self.write(plogin % "")
def post(self):
username = self.get_argument("username")
password = self.get_argument("password")
next = self.get_argument("next")
if len(username) < 6 or len(username) > 12 or not account_name_format(username):
self.write(plogin % "用户名格式错误")
return
if not username in USERS:
u = pickle_read(username)
if not u:
self.write(plogin % "用户名不存在或密码错误")
return
USERS[username] = u
if USERS[username]["password"] != password:
self.write(plogin % "用户名不存在或密码错误")
return
self.session["username"] = username
self.redirect("/" + next)
class SignupHandler(MyHandler):
def get(self):
self.write(psignup % "")
def post(self):
username = self.get_argument("username")
password = self.get_argument("password")
if len(username) < 6 or len(username) > 12 or not account_name_format(username):
self.write(psignup % "用户名格式错误")
return
if len(password) < 8:
self.write(psignup % "密码格式错误")
return
if username in USERS:
self.write(psignup % "用户名已存在")
return
u = pickle_read(username)
if u != None:
self.write(psignup % "用户名已存在")
return
USERS[username] = {"username":username,"password":password}
pickle_write(username,USERS[username])
next = self.get_argument("next")
self.session["username"] = username
self.redirect("/" + next)
#logging.basicConfig(level=logging.INFO,filename='web.log')
logger = logging.getLogger('')
"""
设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥等,其他配置值可以查看AlipayClientConfig的定义。
"""
alipay_client_config = AlipayClientConfig()
alipay_client_config.server_url = 'https://openapi.alipaydev.com/gateway.do'
alipay_client_config.app_id = '2021000118654178'
alipay_client_config.app_private_key = 'MIIEogIBAAKCAQEAlUteUgP7uN0FbS7mTCJHtSzshznBOfVV05EdIfCrKTKAYPcwYgk+uf1VD6HH0FpbIKgMIn5n7kRPwbbRDv5CegjynZXU9TBfluazHF7kIE9rrTMknK1b46XRpcsK1kflc+QDCRwiR25ObkLZuvd1+4SaW7/3gn/f9PTgrfdg0vj2DzXEzMfHWst0uCzy8JXOvadVSlfOdDDiXZvLsv95Ak/0oTb8/RYKYv8IQZnSCuktjYh95kVQFvLNjmCW2cMixncBkmyUS8r5Rh+fN0KhsR0yg3RD0H8U/PrLkEWSIdZwcM0YqKzrbHeaP6EKKbcT7EpiTAxlkIsNNLAiowX0zwIDAQABAoIBABqZHujFxOcemYTmQil2QghJRKqi44YL64qR4/rUAeqJEM41u+z7cK16MNlkHVFFh869ocvTcXjFut/sTjq5meZcCb2BoDs+rwkXePmo/kOzYp+s6OzxBdn9BOjgz8F1da+8A75vwLuxL0/9oQTqaZ6x9T47aUFavu/JYO4dkKaFZQdm25LxpLTV3URG3j+lca2H0d+d9tI6+PUiWReEGbYUw+AwK7HtgMCRvj+QgkVkaiks4TTHaPxelC9YShYszuusUI3q5uM2+1KqUPycCbhH3QTKwJFFcAJhxUTwr7Ucg/m0zgYW5QQAjU/y0bYPJUZSN0FAEsT8KAIcvVhJEkECgYEA9IzzrF6Ih3sI5Y0JP64HokDNBly1uJSxL5CbfGq+S7/ArZfkVXajJMmipu1Nxxa+9wcORpFFD+OzSX7/Q31qK4UJLPYv2mmCnXcdAAliFHoWhdvRc1DeoOnL9hiQ1dkcyc/QHB9KXGL9AKDwFG6UyxRoNaISMknFxvXckeyO/fcCgYEAnEi6iB9gfvbxyL3F5Ge/WFxe1obZz1thonxrQaXOQt/XaahTAfyk0+z5INcWPd3Uc3FcyLRRmU87/uMrGEijk1pwzq90qW/3h7X6vH63GwVaOaoCSpQEZ6AUcYQ0U533R/NSlr1fKHNjPiLxHu5rng6IVXTuzHekzZs/Rjtd6ekCgYAQ7vmog9s8Vl6lVoC/chOBPq9zs1O59kHWo1LA6LtIj3yOCKh86nwdfgDPQjtSf9a1UD3C0ShRE1lEy5BtYe/KF6os/NcPbqLmuGq/p+asuE968V+tdnoT9lxzK/xLcn810jf82oXRo+EU/A/jukx/S2hz3kcYSFdzkW62hATavQKBgB5wG8Q/ODACMH0EWPJvMlknRGFLykgUaCOZT9ptTIrBxdaSLfiJGCEeWjcHLRHHjoUdYxDD7dCKGgk+fToxi4o7ZxUaHwKRCAiqbLchhtAAbt4kOmYEBgeYqeKh+P8AGRUuUruBDnN2ZbHIZGW90b/q3KqoJ4ozEynoPp6TGWthAoGANY5vQwfowDiwX+QNQfQ+LdzHNVeBgVI35iLaK1byUYGhOfGdvydM7tLkjvK6NYHi0VQznXhWvefXYkYj3qlusFbjqwHfk9tm24xLnXonNdKHnvxknYrMwIjYtkB+nzdBu8+/a51/d/MSJrSANlCezNnD+B0I3CV9i8o7NcbfIL0='
alipay_client_config.alipay_public_key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApnBWmglUkd3OtdCSKWrXwUInvfUgeNT+wAgHSzV077PrIb/GFU1Ib/HnABGfcc4kZgf2D0gXsIah8mjxSnKer73Ckqyx8XX/S0zJGnDbWGNPR6C4KLybMDNvzfzkQpxXWSAlYKePbq39k0xLs+cCOUZF/8+d3AD4lw7/Z6miYJHgKOEmB+euKhLCcBIWtxbAIlxwMlu0uWIYanxmW1dpC2DoN55BqKfrUxsIRpaqpXjFG/WSYmC3XCI+xV3jk931JQQfnamgzWRpdoFIDx4fZqhycY/QdalKtmqpuNB5yzRtiRVei1dTlMc+ivM19jFrncFJTAkJaREN74vfq80cXwIDAQAB'
alipay_client_config.sign_type = 'RSA2'
"""
得到客户端对象。
注意,一个alipay_client_config对象对应一个DefaultAlipayClient,定义DefaultAlipayClient对象后,alipay_client_config不得修改,如果想使用不同的配置,请定义不同的DefaultAlipayClient。
logger参数用于打印日志,不传则不打印,建议传递。
"""
client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)
"""
g_model = AlipayTradeQueryModel()
g_model.out_trade_no = "tinyHeart_yuyinda"
g_req = AlipayTradeQueryRequest(biz_model=g_model)
g_o = client.execute(g_req)
print("--------------------------------")
print(g_o)
print("--------------------------------")
g_model = AlipayTradeQueryModel()
g_model.out_trade_no = "tinyHeart_test00001"
g_req = AlipayTradeQueryRequest(biz_model=g_model)
g_o = client.execute(g_req)
print("--------------------------------")
print(g_o)
print("--------------------------------")
"""
class AnyHandler(MyHandler):
def checkAlipay(self,subject,user,name,u):
model = AlipayTradeQueryModel()
model.out_trade_no = subject
req = AlipayTradeQueryRequest(biz_model=model)
o = client.execute(req)
print("--------------------------------")
print(o)
print("--------------------------------")
jo = json.loads(o)
if jo["msg"] == "Success" and float(jo["total_amount"]) + 0.01 >= games[name]["cost"]:
try:
t = "" in u["had"]
except:
u["had"] = []
u["had"].append(name)
USERS[name] = u
pickle_write(user,u)
return True
payUrl = str(games[name]["cost"])+"&product="+name+"&user="+subject
self.redirect('AliPay?amount=' + payUrl)
return False
def isBuy(self,name,user,u):
subject = name + "_" + user
isFind = True
try:
if not name in u["had"]:
isFind = False
except:
isFind = False
if isFind == True:
return True
return self.checkAlipay(subject,user,name,u)
@tornado.web.authenticated
def get(self):
user = self.current_user
name = self.request.path[1:]
if not name in games:
self.write("no game")
return
if not user:
self.redirect('/login?redirect=' + name)
return
u = None
if user in USERS:
u = USERS[user]
if games[name]["cost"] > 0.009:
if not self.isBuy(name,user,u):
return
f = open("./static/" + name + "/index.html", 'rb')
self.write(f.read())
f.close()
class AliPay(MyHandler):
def get(self):
#model = AlipayTradeAppPayModel()
#model = AlipayTradePayModel()
model = AlipayTradeWapPayModel()
#model = AlipayTradePagePayModel()
model.total_amount = self.get_query_argument('amount', '1')
#model.product_code = 'FAST_INSTANT_TRADE_PAY'
model.product_code = 'QUICK_WAP_PAY'
model.subject = self.get_query_argument('user', '0_0')
#model.out_trade_no = str(int(time.time())) + model.subject
model.out_trade_no = model.subject
model.seller_id = "gqfmha3170@sandbox.com"
#model.seller_id = "9youzl@mail.m818.com"
url0 = "http://" + self.request.host + "/"
model.quit_url = url0
#model.timeout_express = '10m'
#request = AlipayTradeAppPayRequest(biz_model=model)
#request.notify_url = url0 + 'AliPayOk'
#response = client.sdk_execute(request)
#logging.info("alipay.trade.app.pay response:" + response)
#self.write(response)
#pay_request = AlipayTradePagePayRequest(biz_model=model)
pay_request = AlipayTradeWapPayRequest(biz_model=model)
#pay_request = AlipayTradePayRequest(biz_model=model)
#pay_request.notify_url = url0 + 'AliPayOk' # 支付后回调地址
pay_request.return_url = url0 + self.get_query_argument('product', '')
#response = client.sdk_execute(pay_request)
#self.write(response)
pay_url = client.page_execute(pay_request, http_method='GET')
self.redirect(pay_url)
def check_pay( params): # 定义检查支付结果的函数
from alipay.aop.api.util.SignatureUtils import verify_with_rsa
sign = params.pop('sign', None) # 取出签名
print('public_key:')
print(public_key)
print('sign:')
print(sign)
params.pop('sign_type') # 取出签名类型
params = sorted(params.items(), key=lambda e: e[0], reverse=False) # 取出字典元素按key的字母升序排序形成列表
message = "&".join(u"{}={}".format(k, v) for k, v in params).encode() # 将列表转为二进制参数字符串
print('message:')
print(message)
# with open(settings.ALIPAY_PUBLIC_KEY_PATH, 'rb') as public_key: # 打开公钥文件
try:
status = verify_with_rsa(public_key, message,sign) # 验证签名并获取结果
return status # 返回验证结果
except Exception as e:
# 访问异常的错误编号和详细信息
print(e.args)
print(str(e))
print(repr(e))
return False
class AliPayOk(tornado.web.RequestHandler):
def post(self):
params = self.request.arguments
logging.info("AliPayOk post")
logging.info(params)
params2 = {}
for key in params.keys():
params2[key] = params[key][0].decode()
params = params2
logging.info("------------------------------------------------------")
logging.info(params)
if params["trade_status"] != "TRADE_SUCCESS" and params["trade_status"] != "TRADE_FINISHED":
logging.info("not success")
return
if check_pay(params):
logging.info("check ok")
m = hashlib.md5()
orderID = "alipay_" + params["trade_no"]
data = params["subject"]
ii = data.find("_")
user = data[ii + 1:]
name = data[:ii]
amount = str(params["total_amount"])
if not name in games:
logging.info("AlipayOK game not exist:" + name)
self.write("not success")
return
if float(amount) + 0.01 < games[name]["cost"]:
logging.info("AlipayOK amount error:" + name + "," + str(amount))
self.write("success")
return
u = pickle_read(user)
if not u:
logging.info("AlipayOK user not exist:" + user)
self.write("not success")
return
try:
t = "" in u["had"]
except:
u["had"] = []
u["had"].append(name)
USERS[name] = u
pickle_write(user,u)
self.write("success")
else:
logging.info("check error")
self.write("failed")
def get(self):
params = self.request.arguments
logging.info("AliPayOk get")
logging.info(params)
params2 = {}
for key in params.keys():
params2[key] = params[key][0].decode()
params = params2
logging.info("------------------------------------------------------")
logging.info(params)
if params["trade_status"] != "TRADE_SUCCESS" and params["trade_status"] != "TRADE_FINISHED":
logging.info("not success")
return
if check_pay(params):
logging.info("check ok")
m = hashlib.md5()
orderID = "alipay_" + params["trade_no"]
data = params["subject"]
ii = data.find("_")
user = data[ii + 1:]
name = data[:ii]
amount = str(params["total_amount"])
if not name in games:
logging.info("AlipayOK game not exist:" + name)
self.write("not success")
return
if float(amount) + 0.01 < games[name]["cost"]:
logging.info("AlipayOK amount error:" + name + "," + str(amount))
self.write("success")
return
u = pickle_read(user)
if not u:
logging.info("AlipayOK user not exist:" + user)
self.write("not success")
return
try:
t = "" in u["had"]
except:
u["had"] = []
u["had"].append(name)
USERS[name] = u
pickle_write(user,u)
self.write("success")
else:
logging.info("check error")
self.write("failed")
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/login", LoginHandler),
(r"/signup", SignupHandler),
(r"/AliPay", AliPay),
(r"/AliPayOk", AliPayOk),
]
for i in games.keys():
handlers.append((r"/" + i,AnyHandler))
settings = dict(
cookie_secret="61oETzKXQAGaYdkL2gEmGeJJFuYh8EQnp2XdTP1o/Vo=",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
static_url_prefix = "/static/",
login_url='/login',
xsrf_cookies=False,
)
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = Application()
app.listen(8810)
loop = tornado.ioloop.IOLoop.instance()
tornado.ioloop.IOLoop.instance().start()
| 33.3 | 1,629 | 0.705992 | 2,520 | 20,979 | 5.766667 | 0.207937 | 0.015483 | 0.018786 | 0.023121 | 0.378888 | 0.317919 | 0.298789 | 0.277525 | 0.263832 | 0.246903 | 0 | 0.025766 | 0.126793 | 20,979 | 629 | 1,630 | 33.352941 | 0.767455 | 0.051909 | 0 | 0.499099 | 0 | 0.014414 | 0.411974 | 0.202999 | 0 | 1 | 0 | 0 | 0 | 1 | 0.043243 | false | 0.027027 | 0.081081 | 0 | 0.210811 | 0.027027 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6e6a283bc4120f1ee94638f84aeed9da4b9483d3 | 341 | py | Python | setup.py | shearern/PyWizard | fac7f859707bc7fe36737caa794c159a66ea0789 | [
"MIT"
] | null | null | null | setup.py | shearern/PyWizard | fac7f859707bc7fe36737caa794c159a66ea0789 | [
"MIT"
] | null | null | null | setup.py | shearern/PyWizard | fac7f859707bc7fe36737caa794c159a66ea0789 | [
"MIT"
] | null | null | null | from distutils.core import setup
setup(
name='py_wizard',
version='2.0',
author='Nathan Shearer',
author_email='shearern@gmail.com',
package_dir={'': 'src', },
packages=[
'py_wizard',
'py_wizard.console_wiz_iface',
'py_wizard.questions',
'py_wizard.tk_wizard_iface',
],
)
| 21.3125 | 38 | 0.589443 | 39 | 341 | 4.871795 | 0.692308 | 0.210526 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007937 | 0.260997 | 341 | 15 | 39 | 22.733333 | 0.746032 | 0 | 0 | 0 | 0 | 0 | 0.372434 | 0.152493 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.071429 | 0 | 0.071429 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6e7152edfa2519c4e8ce2672dce330c0b928bd58 | 820 | py | Python | django_analyses/apps.py | TheLabbingProject/django_analyses | 08cac40a32754a265b37524f08ec6160c69ebea8 | [
"Apache-2.0"
] | 1 | 2020-12-30T12:43:34.000Z | 2020-12-30T12:43:34.000Z | django_analyses/apps.py | TheLabbingProject/django_analyses | 08cac40a32754a265b37524f08ec6160c69ebea8 | [
"Apache-2.0"
] | 59 | 2019-12-25T13:14:56.000Z | 2021-07-22T12:24:46.000Z | django_analyses/apps.py | TheLabbingProject/django_analyses | 08cac40a32754a265b37524f08ec6160c69ebea8 | [
"Apache-2.0"
] | 2 | 2020-05-24T06:44:27.000Z | 2020-07-09T15:47:31.000Z | """
Definition of the :class:`DjangoAnalysesConfig` class.
References
----------
* `Django applications`_
.. _Django applications:
https://docs.djangoproject.com/en/3.0/ref/applications/#module-django.apps
"""
from django.apps import AppConfig
class DjangoAnalysesConfig(AppConfig):
"""
*django_analyses* app configuration.
References
----------
* `AppConfig attributes`_
.. _AppConfig attributes:
https://docs.djangoproject.com/en/3.0/ref/applications/#configurable-attributes
"""
#: Full Python path to the application.
name = "django_analyses"
def ready(self):
"""
Loads the app's signals.
References
----------
* :meth:`~django.apps.AppConfig.ready`
"""
import django_analyses.signals # noqa: F401
| 20.5 | 86 | 0.630488 | 80 | 820 | 6.375 | 0.5125 | 0.058824 | 0.086275 | 0.098039 | 0.172549 | 0.172549 | 0.172549 | 0.172549 | 0.172549 | 0 | 0 | 0.010955 | 0.220732 | 820 | 39 | 87 | 21.025641 | 0.787167 | 0.657317 | 0 | 0 | 0 | 0 | 0.078947 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.4 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
6e73f5cbd34016aeb23c52711aa6d59e997a91f2 | 4,723 | py | Python | Incident-Response/Tools/cyphon/cyphon/aggregator/pumproom/tests/test_planner.py | sn0b4ll/Incident-Playbook | cf519f58fcd4255674662b3620ea97c1091c1efb | [
"MIT"
] | 1 | 2021-07-24T17:22:50.000Z | 2021-07-24T17:22:50.000Z | Incident-Response/Tools/cyphon/cyphon/aggregator/pumproom/tests/test_planner.py | sn0b4ll/Incident-Playbook | cf519f58fcd4255674662b3620ea97c1091c1efb | [
"MIT"
] | 2 | 2022-02-28T03:40:31.000Z | 2022-02-28T03:40:52.000Z | Incident-Response/Tools/cyphon/cyphon/aggregator/pumproom/tests/test_planner.py | sn0b4ll/Incident-Playbook | cf519f58fcd4255674662b3620ea97c1091c1efb | [
"MIT"
] | 2 | 2022-02-25T08:34:51.000Z | 2022-03-16T17:29:44.000Z | # -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon Engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cyphon Engine. If not, see <http://www.gnu.org/licenses/>.
# """
# Tests the Planner class.
# """
# # standard library
# import datetime
# # third party
# from django.test import TestCase
# from django.utils import timezone
# # local
# from aggregator.pipes.models import PipeRateLimit
# from aggregator.plumbers.models import Meter
# from aggregator.pumproom.planner import Planner
# from tests.fixture_manager import get_fixtures
# class PlannerTestCase(TestCase):
# """
# Base class for testing the Planner class.
# """
# fixtures = get_fixtures(['pipes'])
# @staticmethod
# def _create_example_planner():
# """
# Helper mthods that returns an example Planner instance.
# """
# delta = datetime.timedelta(seconds=30)
# end_time = timezone.now() + delta
# meter = Meter(end_time=end_time, remaining_calls=100)
# ratelimit = PipeRateLimit.objects.get(pk=1) # Twitter Search API
# return Planner(meter=meter, ratelimit=ratelimit)
# def setUp(self):
# super(PlannerTestCase, self).setUp()
# self.planner = self._create_example_planner()
# class GetTimeRemainingTestCase(PlannerTestCase):
# """
# Tests the get_time_remaining_in_minutes method.
# """
# def test_for_zero_time(self):
# """
# Tests the get_time_remaining_in_minutes method when there is no time
# remaining in the current rate-limit interval.
# """
# meter = Meter(end_time=timezone.now())
# ratelimit = PipeRateLimit.objects.get(pk=1) # Twitter Search API
# planner = Planner(meter=meter, ratelimit=ratelimit)
# actual = planner.get_time_remaining_in_minutes()
# self.assertAlmostEqual(actual, 0, delta=0.001)
# def test_for_nonzero_time(self):
# """
# Tests the get_time_remaining_in_minutes method when there is time
# remaining in the current rate-limit interval.
# """
# planner = self._create_example_planner()
# actual = planner.get_time_remaining_in_minutes()
# self.assertAlmostEqual(actual, 0.5, delta=0.001)
# class CalculateQueryTimeTestCase(PlannerTestCase):
# """
# Tests the calculate_query_time_in_minutes method.
# """
# def test_for_0_queries_10_remaining(self):
# """
# Tests the calculate_query_time_in_minutes method for no queries.
# """
# actual = self.planner.calculate_query_time_in_minutes(0)
# self.assertAlmostEqual(actual, 0, delta=0.001)
# def test_under_limit(self):
# """
# Tests the calculate_query_time_in_minutes method for a number of queries
# less than the number remaining in the current rate-limit interval.
# """
# actual = self.planner.calculate_query_time_in_minutes(50)
# self.assertAlmostEqual(actual, 0, delta=0.001)
# def test_over_limit_by_1_interval(self):
# """
# Tests the calculate_query_time_in_minutes method for a number of queries
# greater than the number remaining in the current rate-limit interval.
# """
# actual = self.planner.calculate_query_time_in_minutes(300)
# self.assertAlmostEqual(actual, 0.5, delta=0.001)
# def test_over_limit_by_2_intervals(self):
# """
# Tests the calculate_query_time_in_minutes method for a number of queries
# greater than the number remaining in the current rate-limit interval and
# the next interval.
# """
# actual = self.planner.calculate_query_time_in_minutes(999)
# self.assertAlmostEqual(actual, 15.5, delta=0.001)
# def test_over_limit_by_3_intervals(self):
# """
# Tests the calculate_query_time_in_minutes method for a number of queries
# greater than the number remaining in the current rate-limit interval and
# the next two intervals.
# """
# actual = self.planner.calculate_query_time_in_minutes(1000)
# self.assertAlmostEqual(actual, 30.5, delta=0.001)
| 36.612403 | 82 | 0.675206 | 595 | 4,723 | 5.176471 | 0.280672 | 0.046753 | 0.064286 | 0.071429 | 0.568831 | 0.517532 | 0.492857 | 0.492857 | 0.39513 | 0.293182 | 0 | 0.021241 | 0.232479 | 4,723 | 128 | 83 | 36.898438 | 0.828414 | 0.94855 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6e75cf1e9be606accbcd013aeb614e2ad0ce514a | 256 | py | Python | canvas/__main__.py | robinsax/canvas | 6e8b9b260fdda868d687b562926a2038736ec56c | [
"Apache-2.0"
] | 4 | 2018-01-24T01:34:39.000Z | 2021-01-14T21:29:47.000Z | canvas/__main__.py | robinsax/canvas | 6e8b9b260fdda868d687b562926a2038736ec56c | [
"Apache-2.0"
] | 2 | 2018-06-09T22:28:56.000Z | 2018-06-12T01:40:10.000Z | canvas/__main__.py | robinsax/canvas | 6e8b9b260fdda868d687b562926a2038736ec56c | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
'''
The entry point of canvas's CLI.
'''
# Ensure canvas is importable.
import sys
sys.path.insert(0, '.')
# Import and invoke the launch handler.
from canvas import launch_cli
launch_cli((str(),) if len(sys.argv) == 1 else sys.argv[1:])
| 19.692308 | 60 | 0.691406 | 43 | 256 | 4.069767 | 0.674419 | 0.102857 | 0.091429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018519 | 0.15625 | 256 | 12 | 61 | 21.333333 | 0.791667 | 0.445313 | 0 | 0 | 0 | 0 | 0.007576 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
6e8d1ac45ed9400c770efb3476dd3bb9a8c33731 | 419 | py | Python | test/python/importer/jit_ir/node_import/utils.py | burntfalafel/torch-mlir-internal | d3ef58450fc94e9337dc0434fa3af6dd7b54b37f | [
"Apache-2.0"
] | 213 | 2021-09-24T03:26:53.000Z | 2022-03-30T07:11:48.000Z | test/python/importer/jit_ir/node_import/utils.py | burntfalafel/torch-mlir-internal | d3ef58450fc94e9337dc0434fa3af6dd7b54b37f | [
"Apache-2.0"
] | 247 | 2021-09-23T18:49:45.000Z | 2022-03-31T17:19:02.000Z | test/python/importer/jit_ir/node_import/utils.py | burntfalafel/torch-mlir-internal | d3ef58450fc94e9337dc0434fa3af6dd7b54b37f | [
"Apache-2.0"
] | 68 | 2021-09-23T18:23:20.000Z | 2022-03-29T11:18:58.000Z | # -*- Python -*-
# This file is licensed under a pytorch-style license
# See LICENSE.pytorch for license information.
# Helpers for the other tests.
import torch
from torch._C import CompilationUnit
# RUN: %PYTHON %s
# Import TorchScript IR string as ScriptFunction.
def create_script_function(func_name, ts_ir_str):
cu = CompilationUnit()
return cu.create_function(func_name, torch._C.parse_ir(ts_ir_str))
| 26.1875 | 70 | 0.763723 | 61 | 419 | 5.04918 | 0.655738 | 0.038961 | 0.103896 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.150358 | 419 | 15 | 71 | 27.933333 | 0.865169 | 0.486874 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.4 | 0 | 0.8 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
6e9212340db1525fd1f6beb2d6ba6ca618c696f8 | 1,677 | py | Python | envipyarc/gptoolbox.py | envi-idl/envipyarc | a996ea5a2d4b49bf6ade720fbd3f8c68e5cac97c | [
"MIT"
] | null | null | null | envipyarc/gptoolbox.py | envi-idl/envipyarc | a996ea5a2d4b49bf6ade720fbd3f8c68e5cac97c | [
"MIT"
] | null | null | null | envipyarc/gptoolbox.py | envi-idl/envipyarc | a996ea5a2d4b49bf6ade720fbd3f8c68e5cac97c | [
"MIT"
] | null | null | null | """
The ENVI GPToolbox class is used to create python toolboxes capable of running \
ENVI/IDL analytics inside of ArcMap and ArcGIS Pro. Each generated toolbox contains \
one or more GPTools that are lightweight wrappers to running ENVI/IDL tasks through \
the taskengine. For more api documentation on GPToolbox you can \
view the envipyarclib :mod:`GPToolbox <envipyarclib:envipyarclib.gptoolbox>` class.
"""
from string import Template
from envipyarclib import GPToolbox as BaseToolbox
from . import templates
_IMPORTS_TEMPLATE = Template('''
import os
import time
import arcpy
from envipyengine import Task
from envipyengine.error import TaskEngineExecutionError, TaskEngineNotFoundError
''')
_EXECUTE_TEMPLATE = Template('''
task = Task("$taskUri")
try:
task_results = task.execute(input_params, cwd=arcpy.env.scratchFolder)
except (TaskEngineExecutionError, TaskEngineNotFoundError) as err:
messages.addErrorMessage("Task failed to execute")
messages.addErrorMessage(err.args[0])
raise arcpy.ExecuteError
task_results = task_results['outputParameters']
''')
class GPToolbox(BaseToolbox): # pylint: disable=too-few-public-methods
"""
Implementation of the envipyarclib \
:mod:`GPToolbox <envipyarclib:envipyarclib.gptoolbox>` class for ENVI/IDL.
"""
def __init__(self, tasks=None, alias='envi'):
super(GPToolbox, self).__init__(tasks,
alias,
_IMPORTS_TEMPLATE,
_EXECUTE_TEMPLATE,
templates)
| 34.22449 | 86 | 0.670244 | 172 | 1,677 | 6.418605 | 0.534884 | 0.038043 | 0.025362 | 0.048913 | 0.117754 | 0.117754 | 0.117754 | 0.117754 | 0 | 0 | 0 | 0.000801 | 0.255218 | 1,677 | 48 | 87 | 34.9375 | 0.883106 | 0.327967 | 0 | 0.074074 | 1 | 0 | 0.518282 | 0.229433 | 0 | 0 | 0 | 0 | 0 | 1 | 0.037037 | false | 0 | 0.37037 | 0 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
6e99584a09360d7139d742554382c0e9608aba6b | 355 | py | Python | main.py | aalsabag/LiveCaption | 9170cda2b05d9c3016276adf409c62046226dca3 | [
"MIT"
] | 1 | 2021-03-25T17:22:15.000Z | 2021-03-25T17:22:15.000Z | main.py | aalsabag/LiveCaption | 9170cda2b05d9c3016276adf409c62046226dca3 | [
"MIT"
] | null | null | null | main.py | aalsabag/LiveCaption | 9170cda2b05d9c3016276adf409c62046226dca3 | [
"MIT"
] | 1 | 2021-06-28T09:41:39.000Z | 2021-06-28T09:41:39.000Z | #!/usr/bin/env python3
import json
from flask import Flask
from flask.json import jsonify
from vosk import KaldiRecognizer, Model, SetLogLevel
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello_world():
return jsonify({'hello': 'world!!!'})
def main():
app.run(debug=True)
if __name__ == "__main__":
app.run(debug=True) | 20.882353 | 52 | 0.698592 | 49 | 355 | 4.795918 | 0.55102 | 0.076596 | 0.085106 | 0.12766 | 0.161702 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0033 | 0.146479 | 355 | 17 | 53 | 20.882353 | 0.772277 | 0.059155 | 0 | 0.166667 | 0 | 0 | 0.08982 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0.083333 | 0.583333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
6ea44ace2337be42eea61f72184a54eec26b5fd2 | 547 | py | Python | src/panoramic/cli/husky/core/tel/visitors/terminal_visitor.py | kubamahnert/panoramic-cli | 036f45a05d39f5762088ce23dbe367b938192f79 | [
"MIT"
] | 5 | 2020-11-13T17:26:59.000Z | 2021-03-19T15:11:26.000Z | src/panoramic/cli/husky/core/tel/visitors/terminal_visitor.py | kubamahnert/panoramic-cli | 036f45a05d39f5762088ce23dbe367b938192f79 | [
"MIT"
] | 5 | 2020-10-28T10:22:35.000Z | 2021-01-27T17:33:58.000Z | src/panoramic/cli/husky/core/tel/visitors/terminal_visitor.py | kubamahnert/panoramic-cli | 036f45a05d39f5762088ce23dbe367b938192f79 | [
"MIT"
] | 3 | 2021-01-26T07:58:03.000Z | 2021-03-11T13:28:34.000Z | from panoramic.cli.tel_grammar.TelParser import TelParser as AntlrTelParser
from panoramic.cli.tel_grammar.TelVisitor import TelVisitor as AntlrTelVisitor
class TelTerminalVisitor(AntlrTelVisitor):
"""
Visitor that will render all terminal nodes exactly as they are.
"""
def __init__(self):
self._output = []
def visitTerminal(self, node):
if node.symbol.type != AntlrTelParser.EOF:
self._output.append(str(node))
@property
def output_string(self):
return ''.join(self._output)
| 27.35 | 78 | 0.702011 | 63 | 547 | 5.936508 | 0.619048 | 0.080214 | 0.085562 | 0.101604 | 0.139037 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.20841 | 547 | 19 | 79 | 28.789474 | 0.863741 | 0.117002 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.272727 | false | 0 | 0.181818 | 0.090909 | 0.636364 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
6eaac839a433c6bd24c558f75d92e38aee869246 | 1,248 | py | Python | src/dto/console_game_domain_dto.py | rafaelcorazzi/games-consumer | c0f59fcbf37a38e624044fef2a48a36fa986c920 | [
"MIT"
] | null | null | null | src/dto/console_game_domain_dto.py | rafaelcorazzi/games-consumer | c0f59fcbf37a38e624044fef2a48a36fa986c920 | [
"MIT"
] | null | null | null | src/dto/console_game_domain_dto.py | rafaelcorazzi/games-consumer | c0f59fcbf37a38e624044fef2a48a36fa986c920 | [
"MIT"
] | null | null | null | from datetime import datetime
from typing import List
from marshmallow import Schema, fields, post_load
from src.dto.common.base_dto import BaseDto
class ConsoleGamesListDto(BaseDto):
def __init__(self, console_code: str = None,
reference_id: str = None,
title: str = None,
link: str = None):
self.console_code = console_code
self.reference_id = reference_id
self.title = title
self.link = link
@staticmethod
def mapper(data):
return ConsoleGamesListDto(**data)
class ConsoleGamesListDtoSchema(Schema):
console_code = fields.Str()
reference_id = fields.Str()
title = fields.Str()
link = fields.Str()
@post_load
def make_dto(self, data):
return ConsoleGamesListDto(**data)
class ConsoleGamesDto(BaseDto):
def __init__(self, data: List[ConsoleGamesListDto] = None):
self.data = data
@staticmethod
def mapper(data):
return ConsoleGamesDto(**data)
class ConsoleGamesDtoSchema(Schema):
data = fields.List(fields.Nested(ConsoleGamesListDtoSchema))
code_transfer = fields.Int()
@post_load
def make_model(self, data):
return ConsoleGamesDto.mapper(data) | 24 | 64 | 0.665865 | 137 | 1,248 | 5.89781 | 0.291971 | 0.054455 | 0.034653 | 0.044554 | 0.158416 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.245994 | 1,248 | 52 | 65 | 24 | 0.858661 | 0 | 0 | 0.222222 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.111111 | 0.111111 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
6ebcacaaddff805e3b3a7dd2a2f688b83b85fad0 | 3,214 | py | Python | tests/xbmcgui.py | dagwieers/plugin.video.fosdem | d2f7758159eb040b85dd4dccac009f10f519ca28 | [
"MIT"
] | null | null | null | tests/xbmcgui.py | dagwieers/plugin.video.fosdem | d2f7758159eb040b85dd4dccac009f10f519ca28 | [
"MIT"
] | null | null | null | tests/xbmcgui.py | dagwieers/plugin.video.fosdem | d2f7758159eb040b85dd4dccac009f10f519ca28 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright: (c) 2019, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""This file implements the Kodi xbmcgui module, either using stubs or alternative functionality"""
# pylint: disable=invalid-name,unused-argument
from __future__ import absolute_import, division, print_function, unicode_literals
from xbmcextra import kodi_to_ansi
class Dialog:
"""A reimplementation of the xbmcgui Dialog class"""
def __init__(self):
"""A stub constructor for the xbmcgui Dialog class"""
@staticmethod
def ok(heading, message='', line1='', line2='', line3=''):
"""A stub implementation for the xbmcgui Dialog class ok() method"""
heading = kodi_to_ansi(heading)
message = kodi_to_ansi(message)
print('\033[37;44;1mOK:\033[35;49;1m [%s] \033[37;1m%s\033[39;0m' % (heading, message or line1))
class ListItem:
"""A reimplementation of the xbmcgui ListItem class"""
def __init__(self, label='', label2='', path='', offscreen=False):
"""A stub constructor for the xbmcgui ListItem class"""
self.label = kodi_to_ansi(label)
self.label2 = kodi_to_ansi(label2)
self.path = path
@staticmethod
def addContextMenuItems(items, replaceItems=False):
"""A stub implementation for the xbmcgui ListItem class addContextMenuItems() method"""
return
@staticmethod
def addStreamInfo(stream_type, stream_values):
"""A stub implementation for the xbmcgui LitItem class addStreamInfo() method"""
return
@staticmethod
def setArt(key):
"""A stub implementation for the xbmcgui ListItem class setArt() method"""
return
@staticmethod
def setContentLookup(enable):
"""A stub implementation for the xbmcgui ListItem class setContentLookup() method"""
return
@staticmethod
def setInfo(type, infoLabels): # pylint: disable=redefined-builtin
"""A stub implementation for the xbmcgui ListItem class setInfo() method"""
return
@staticmethod
def setIsFolder(isFolder):
"""A stub implementation for the xbmcgui ListItem class setIsFolder() method"""
return
@staticmethod
def setMimeType(mimetype):
"""A stub implementation for the xbmcgui ListItem class setMimeType() method"""
return
def setPath(self, path):
"""A stub implementation for the xbmcgui ListItem class setPath() method"""
self.path = path
@staticmethod
def setProperty(key, value):
"""A stub implementation for the xbmcgui ListItem class setProperty() method"""
return
@staticmethod
def setProperties(dictionary):
"""A stub implementation for the xbmcgui ListItem class setProperties() method"""
return
@staticmethod
def setSubtitles(subtitleFiles):
"""A stub implementation for the xbmcgui ListItem class setSubtitles() method"""
return
@staticmethod
def setUniqueIDs(values, defaultrating=None):
"""A stub implementation for the xbmcgui ListItem class setUniqueIDs() method"""
return
| 34.55914 | 104 | 0.677349 | 369 | 3,214 | 5.826558 | 0.333333 | 0.07907 | 0.090698 | 0.133023 | 0.355349 | 0.286977 | 0.230233 | 0.230233 | 0 | 0 | 0 | 0.017586 | 0.221531 | 3,214 | 92 | 105 | 34.934783 | 0.841727 | 0.465775 | 0 | 0.510204 | 0 | 0.020408 | 0.035142 | 0.031443 | 0 | 0 | 0 | 0 | 0 | 1 | 0.306122 | false | 0 | 0.040816 | 0 | 0.612245 | 0.040816 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
6ec3e398ad827a23e1d174f70ece7000e5ab2640 | 334 | py | Python | Exercicios-Mundo1/ex018.py | WeDias/RespCEV | 3cf0918c5c90e3b2d6dc7e57f2824436c639c04c | [
"MIT"
] | 1 | 2021-02-19T05:13:31.000Z | 2021-02-19T05:13:31.000Z | Exercicios-Mundo1/ex018.py | WeDias/RespCEV | 3cf0918c5c90e3b2d6dc7e57f2824436c639c04c | [
"MIT"
] | null | null | null | Exercicios-Mundo1/ex018.py | WeDias/RespCEV | 3cf0918c5c90e3b2d6dc7e57f2824436c639c04c | [
"MIT"
] | null | null | null | import math
ang = float(input('Digite o valor do Ângulo: '))
seno = float(math.sin(math.radians(ang)))
coso = float(math.cos(math.radians(ang)))
tang = float(math.tan(math.radians(ang)))
print('O Seno Do Ângulo {0} é {1:.3f}\nO Cosseno Do Ângulo {0} é {2:.3f}\nA Tangente Do Ângulo {0} é {3:.3f}'.format(ang, seno, coso, tang))
| 47.714286 | 141 | 0.664671 | 61 | 334 | 3.639344 | 0.47541 | 0.144144 | 0.189189 | 0.135135 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031359 | 0.140719 | 334 | 6 | 142 | 55.666667 | 0.74216 | 0 | 0 | 0 | 0 | 0.166667 | 0.387195 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0.166667 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6ec98c3ebc5eb9c0268eb5a8cff500d41dea7df4 | 370 | py | Python | Chapter13/excise2.py | lixuekai2001/python.Hello-World-Computer-Programming-for-Kids-and-Other-Beginners | e2caaf58af4d2d2ff541d9e7e78f9e5f0778a293 | [
"Apache-2.0"
] | 3 | 2020-03-09T00:35:22.000Z | 2020-10-29T06:26:46.000Z | Chapter13/excise2.py | lixuekai2001/python.Hello-World-Computer-Programming-for-Kids-and-Other-Beginners | e2caaf58af4d2d2ff541d9e7e78f9e5f0778a293 | [
"Apache-2.0"
] | null | null | null | Chapter13/excise2.py | lixuekai2001/python.Hello-World-Computer-Programming-for-Kids-and-Other-Beginners | e2caaf58af4d2d2ff541d9e7e78f9e5f0778a293 | [
"Apache-2.0"
] | 4 | 2020-10-29T06:26:48.000Z | 2021-09-18T13:41:13.000Z | def printAddr (name, num ,str, city, prov ,pcode, country):
print name
print num,
print str
print city,
if prov != "":
print ", "+prov
else:
print ""
print pcode
print country
print
printAddr("tom","43","Main St.","Caton","Guangdong","110011","China")
printAddr("jack","22","2nd Ave.","Hong Kong","","23456","China")
| 23.125 | 69 | 0.57027 | 46 | 370 | 4.586957 | 0.586957 | 0.113744 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.057143 | 0.243243 | 370 | 15 | 70 | 24.666667 | 0.696429 | 0 | 0 | 0 | 0 | 0 | 0.197297 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.857143 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
6ee4db4f0f65570071443f55f2f9853699381d5a | 1,192 | py | Python | hdpview/src/utils/generative_model.py | FumiyukiKato/PrivBTS | d2fae18588b24281d0968b8af09dc9295e73cdda | [
"Apache-2.0"
] | null | null | null | hdpview/src/utils/generative_model.py | FumiyukiKato/PrivBTS | d2fae18588b24281d0968b8af09dc9295e73cdda | [
"Apache-2.0"
] | null | null | null | hdpview/src/utils/generative_model.py | FumiyukiKato/PrivBTS | d2fae18588b24281d0968b8af09dc9295e73cdda | [
"Apache-2.0"
] | null | null | null | from algorithm.hdpview import HDPView
"""
For data synthesis task.
"""
class HDPViewSampler:
@classmethod
def make_model(cls, prng):
return cls(prng)
def __init__(self, prng):
self.prng = prng
def train(self, ct, epsilon, label_attr, ratio=0.9, alpha=1.6, beta=1.2, gamma=0.9):
is_classification = True
p_view, _ = HDPView(ct, epsilon, self.prng, ratio, alpha, beta, gamma, is_classification, label_attr)
self.p_view = p_view
def generate_data(self, n_data):
data = self.p_view.random_sample(self.prng, n_data)
return data
class NonDPHistogram:
@classmethod
def make_model(cls, prng):
return cls(prng)
def __init__(self, prng):
self.prng = prng
def train(self, ct):
distribution = ct.pd_table.values.flatten() / ct.pd_table.values.sum()
self.data = ct.pd_table.index
self.distribution = distribution
def generate_data(self, size):
indices = self.prng.choice(a=range(len(self.distribution)), size=size, p=self.distribution, replace=True)
return self.data[indices].to_frame(index=False) | 28.380952 | 113 | 0.63255 | 158 | 1,192 | 4.594937 | 0.379747 | 0.077135 | 0.03719 | 0.063361 | 0.231405 | 0.231405 | 0.231405 | 0.231405 | 0.231405 | 0.231405 | 0 | 0.009029 | 0.256711 | 1,192 | 42 | 114 | 28.380952 | 0.810384 | 0 | 0 | 0.37037 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.296296 | false | 0 | 0.037037 | 0.074074 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
6eee40ab5872d6874d2740ecfe883855be015d0d | 391 | py | Python | src/main/handlers/index.py | Mono20i06/tms-z43 | 007d51fd2e88698f8a6176c70583c379129d7d0c | [
"MIT"
] | null | null | null | src/main/handlers/index.py | Mono20i06/tms-z43 | 007d51fd2e88698f8a6176c70583c379129d7d0c | [
"MIT"
] | 8 | 2021-01-10T09:38:54.000Z | 2021-02-28T12:33:58.000Z | src/main/handlers/index.py | vadimkondratovich/asd | 5f2db494f739ea663795c5d4a924ced942cb1852 | [
"MIT"
] | null | null | null | from random import randint
from main.custom_types import RequestT
from main.custom_types import ResponseT
from main.util import render_template
TEMPLATE = "index.html"
def handler(_request: RequestT) -> ResponseT:
context = {"random_number": randint(100000, 999999)}
document = render_template(TEMPLATE, context)
response = ResponseT(payload=document)
return response
| 21.722222 | 56 | 0.767263 | 47 | 391 | 6.255319 | 0.531915 | 0.081633 | 0.095238 | 0.129252 | 0.170068 | 0 | 0 | 0 | 0 | 0 | 0 | 0.036364 | 0.15601 | 391 | 17 | 57 | 23 | 0.854545 | 0 | 0 | 0 | 0 | 0 | 0.058824 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.1 | false | 0 | 0.4 | 0 | 0.6 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
42cc6114fb1e33ced6bdc022a34922b180e85e90 | 10,357 | py | Python | LUH2/GLM/preprocess_GCAM.py | ritviksahajpal/LUH2 | aec79f737aebcaa273de5f8f1aeadd3317d03aa4 | [
"MIT"
] | null | null | null | LUH2/GLM/preprocess_GCAM.py | ritviksahajpal/LUH2 | aec79f737aebcaa273de5f8f1aeadd3317d03aa4 | [
"MIT"
] | null | null | null | LUH2/GLM/preprocess_GCAM.py | ritviksahajpal/LUH2 | aec79f737aebcaa273de5f8f1aeadd3317d03aa4 | [
"MIT"
] | null | null | null | import logging
import numpy as np
import pandas
import constants
import pygeoutil.util as util
from preprocess_IAM import IAM
class GCAM(IAM):
"""
Class for GCAM
"""
def __init__(self, path_nc):
IAM.__init__(self, 'GCAM', path_nc)
self.land_var = 'landcoverpercentage'
# Input file paths
self.path_pas = constants.gcam_dir + constants.PASTURE[0]
self.path_frt = constants.gcam_dir + constants.FOREST[0]
self.path_urb = constants.gcam_dir + constants.URBAN[0]
self.path_wh = constants.gcam_dir + constants.WOOD_HARVEST
self.path_ftz = constants.gcam_dir + constants.FERT_DATA
# Output directories
self.gcam_out_fl = constants.out_dir+constants.GCAM_OUT
self.perc_crops_fl = constants.out_dir+constants.GCAM_CROPS
def AEZ_to_national_GCAM(self, data_source = 'wh', out_nc_name = ''):
"""
:param data_source:
:param out_nc_name:
:return:
"""
# Create a dictionary mapping GCAM AEZ's to regions
if data_source == 'wh':
df = util.open_or_die(self.path_wh)
elif data_source == 'ftz': # fertilizer data
df = util.open_or_die(self.path_ftz)
# Insert columns so that we have data for each year
idx = 1
for yr in xrange(constants.GCAM_START_YR + 1, constants.GCAM_END_YR):
# Skip years for which we already have data i.e. multiples of constants.GCAM_STEP_YR
if yr%constants.GCAM_STEP_YR != 0:
df.insert(constants.SKIP_GCAM_COLS + idx, str(yr), np.nan)
idx += 1
# Extract columns with information on GCAM regions
gcam_df = df[['region', 'subsector']]
# Fill in missing values, note that using interpolate
df = df.ix[:, str(constants.GCAM_START_YR):str(constants.GCAM_END_YR)]
df = df.interpolate(axis = 1)
# Concatenate
df = pandas.concat([gcam_df, df], axis=1, join='inner')
# Extract "Russia", "Central Asia", "EU-12", and "Europe-Eastern" into a single larger region with region code 33
merg_df = df.loc[df['region'].isin(['Russia', 'Central Asia', 'EU-12', 'Europe-Eastern'])]
# Create a new row with data for USSR or region code 33
new_row = ['USSR', 'subsector']
new_row.extend(merg_df.ix[:, 2:].sum().tolist())
# Add newly created row to dataframe
df.loc[len(df.index)] = np.array(new_row)
# Group dataframe by region
df = df.groupby('region').sum()
# Remove the subsector column since it interferes with netCDF creation later
df.drop('subsector', axis=1, inplace=True)
# Read in GCAM region country mapping
xdf = util.open_or_die(constants.gcam_dir + constants.GCAM_MAPPING)
map_xdf = xdf.parse("Sheet1")
df_dict = dict((z[0],list(z[1:])) for z in zip(map_xdf['country ISO code'], map_xdf['Modified GCAM Regions'],
map_xdf['GCAM REGION NAME'], map_xdf['country-to-region WH ratios']))
# Create WH output netCDF
onc = util.open_or_die(constants.out_dir + out_nc_name + '_' + str(constants.GCAM_START_YR) + '_' +
str(constants.GCAM_END_YR) + '.nc', 'w')
# dimensions
onc.createDimension('country_code', len(df_dict.keys()))
onc.createDimension('time', constants.GCAM_END_YR - constants.GCAM_START_YR + 1)
# variables
country_code = onc.createVariable('country_code', 'i4', ('country_code',))
time = onc.createVariable('time', 'i4', ('time',))
data = onc.createVariable(out_nc_name, 'f4', ('country_code', 'time',))
# Metadata
country_code.long_name = 'country_code'
country_code.units = 'index'
country_code.standard_name = 'country_code'
time.units = 'year as %Y.%f'
time.calendar = 'proleptic_gregorian'
if data_source == 'wh':
data.units = 'MgC'
data.long_name = 'wood harvest carbon'
elif data_source == 'ftz':
print 'TODO!!'
# Assign data
time[:] = np.arange(constants.GCAM_START_YR, constants.GCAM_END_YR + 1)
country_code[:] = sorted(df_dict.keys())
for idx, ctr in enumerate(country_code[:]):
# Get GCAM region corresponding to country
gcam_reg = df_dict.get(ctr)[1] # GCAM region identifier
gcam_mul = df_dict.get(ctr)[2] # GCAM country-to-region WH ratios
try:
# @TODO: Need to finalize woodharvest calculation
# @TODO: Generalize for data other than wood harvest
data[idx, :] = df.ix[gcam_reg].values.astype(float) * 0.225 * constants.BILLION * gcam_mul
# @TODO: Multiply by 1.3 to account for slash fraction
except:
data[idx, :] = np.zeros(len(time[:]))
onc.close()
def create_GCAM_croplands(self, nc):
"""
:param nc: Empty 3D numpy array (yrs,ny,nx)
:return nc: 3D numpy array containing SUM of all GCAM cropland percentages
"""
# Iterate over all crop categories and add the self.land_var data
for i in range(len(constants.CROPS)):
print('Processing: ' + constants.CROPS[i])
logging.info('Processing: ' + constants.CROPS[i])
ds = util.open_or_die(constants.gcam_dir+constants.CROPS[i])
for j in range(len(self.time)):
nc[j,:,:] += ds.variables[self.land_var][j,:,:].data
ds.close()
# @TODO: Test whether sum of all self.land_var in a given year is <= 1.0
return nc
def create_nc_perc_croplands(self, sum_nc, shape):
"""
Create netcdf file with each crop category represented as fraction of cropland
area and not total grid cell area
:param sum_nc: netCDF file containing 'croplands' which is fraction of area
of cell occupied by all croplands
:param shape: Tuple containing dimensions of netCDF (yrs, ny, nx)
:return: None
"""
print 'Creating cropland nc'
logging.info('Creating cropland nc')
inc = util.open_or_die(sum_nc)
onc = util.open_or_die(self.perc_crops_fl, 'w')
onc.description = 'crops_as_fraction_of_croplands'
# dimensions
onc.createDimension('time',shape[0])
onc.createDimension('lat', shape[1])
onc.createDimension('lon', shape[2])
# variables
time = onc.createVariable('time', 'i4', ('time',))
latitudes = onc.createVariable('lat', 'f4', ('lat',))
longitudes = onc.createVariable('lon', 'f4', ('lon',))
# Metadata
latitudes.units = 'degrees_north'
latitudes.standard_name = 'latitude'
longitudes.units = 'degrees_east'
longitudes.standard_name = 'longitude'
# Assign time
time[:] = self.time
# Assign lats/lons
latitudes[:] = self.lat
longitudes[:] = self.lon
# Assign data
for i in range(len(constants.CROPS)):
print '\t'+constants.CROPS[i]
onc_var = onc.createVariable(constants.CROPS[i], 'f4', ('time', 'lat', 'lon',),fill_value=np.nan)
onc_var.units = 'percentage'
ds = util.open_or_die(constants.gcam_dir+constants.CROPS[i])
# Iterate over all years
for j in range(shape[0]):
onc_var[j,:,:] = ds.variables[self.land_var][j,:,:].data / inc.variables['cropland'][j,:,:]
ds.close()
# @TODO: Copy metadata from original GCAM netcdf
onc.close()
def write_GCAM_nc(self, isum_perc, shape):
"""
:param isum_perc: Sum of self.land_var values for all crop classes
:param shape: Tuple containing dimensions of netCDF (yrs, ny, nx)
:return: Nothing, side-effect is to create a netCDF file with each crop category
represented as fraction of cropland area and not total grid cell area
"""
print 'Creating GCAM file'
logging.info('Creating GCAM file')
# Read in netCDF datasets
ids_pas = util.open_or_die(self.path_pas)
ids_frt = util.open_or_die(self.path_frt)
ids_urb = util.open_or_die(self.path_urb)
iam_nc = util.open_or_die(self.gcam_out_fl, perm = 'w')
iam_nc.description = 'GCAM'
# dimensions
iam_nc.createDimension('time',shape[0])
iam_nc.createDimension('lat', shape[1])
iam_nc.createDimension('lon', shape[2])
# variables
time = iam_nc.createVariable('time', 'i4', ('time',))
latitudes = iam_nc.createVariable('lat', 'f4', ('lat',))
longitudes = iam_nc.createVariable('lon', 'f4', ('lon',))
crp = iam_nc.createVariable('cropland', 'f4', ('time', 'lat', 'lon',),fill_value=np.nan)
pas = iam_nc.createVariable('pasture', 'f4', ('time', 'lat', 'lon',),fill_value=np.nan)
frt = iam_nc.createVariable('forest', 'f4', ('time', 'lat', 'lon',),fill_value=np.nan)
urb = iam_nc.createVariable('urban', 'f4', ('time', 'lat', 'lon',),fill_value=np.nan)
# Metadata
crp.units = 'percentage'
pas.units = 'percentage'
frt.units = 'percentage'
urb.units = 'percentage'
latitudes.units = 'degrees_north'
latitudes.standard_name = 'latitude'
longitudes.units = 'degrees_east'
longitudes.standard_name = 'longitude'
# Assign time
time[:] = self.time
# Assign lats/lons
latitudes[:] = self.lat
longitudes[:] = self.lon
# Assign data to new netCDF file
for i in range(len(self.time)):
crp[i,:,:] = isum_perc[i,:,:]
pas[i,:,:] = ids_pas.variables[self.land_var][i,:,:].data
frt[i,:,:] = ids_frt.variables[self.land_var][i,:,:].data
urb[i,:,:] = ids_urb.variables[self.land_var][i,:,:].data
# @TODO: Copy metadata from original GCAM netcdf
ids_pas.close()
ids_frt.close()
ids_urb.close()
iam_nc.close()
| 38.645522 | 124 | 0.589456 | 1,312 | 10,357 | 4.489329 | 0.217226 | 0.050764 | 0.020374 | 0.026486 | 0.328353 | 0.270968 | 0.214941 | 0.194228 | 0.156197 | 0.144312 | 0 | 0.007727 | 0.287728 | 10,357 | 267 | 125 | 38.790262 | 0.790701 | 0.138843 | 0 | 0.195804 | 0 | 0 | 0.103387 | 0.003806 | 0 | 0 | 0 | 0.014981 | 0 | 0 | null | null | 0 | 0.041958 | null | null | 0.034965 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
42ecbbc6123b69809d8b2641efead142cdb92f46 | 1,025 | py | Python | scripts/rawdata/pytreeros/refills-project_refills_second_review_arm_movement_behavior.py | RazanGhzouli/Behavior-Trees-in-Action | 36d1b62b55dcc748679054fb5cc13235261a5856 | [
"MIT"
] | 2 | 2021-03-12T14:22:41.000Z | 2022-01-30T12:57:08.000Z | scripts/rawdata/pytreeros/refills-project_refills_second_review_arm_movement_behavior.py | RazanGhzouli/Behavior-Trees-in-Action | 36d1b62b55dcc748679054fb5cc13235261a5856 | [
"MIT"
] | null | null | null | scripts/rawdata/pytreeros/refills-project_refills_second_review_arm_movement_behavior.py | RazanGhzouli/Behavior-Trees-in-Action | 36d1b62b55dcc748679054fb5cc13235261a5856 | [
"MIT"
] | null | null | null | from py_trees import Status, Blackboard
from control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal
from py_trees_ros.actions import ActionClient
class ArmMovementBehavior(ActionClient):
def __init__(self, name="", action_namespace='/whole_body_controller/follow_joint_trajectory'):
super(ArmMovementBehavior, self).__init__(name=name, action_spec=FollowJointTrajectoryAction, action_namespace=action_namespace)
# def setup(self, timeout):
# return super(ShelfNavigationBehavior, self).setup(timeout)
def initialise(self):
super(ArmMovementBehavior, self).initialise()
self.action_goal = FollowJointTrajectoryGoal()
self.action_goal.trajectory = Blackboard().get("arm_trajectory")
def update(self):
if not self.action_goal.trajectory:
return Status.FAILURE
return super(ArmMovementBehavior, self).update()
# def terminate(self, new_status):
# super(ShelfNavigationBehavior, self).terminate(new_status)
| 39.423077 | 136 | 0.757073 | 105 | 1,025 | 7.142857 | 0.419048 | 0.06 | 0.112 | 0.064 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.154146 | 1,025 | 25 | 137 | 41 | 0.865052 | 0.188293 | 0 | 0 | 0 | 0 | 0.072904 | 0.055893 | 0 | 0 | 0 | 0 | 0 | 1 | 0.214286 | false | 0 | 0.214286 | 0 | 0.642857 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
42f0c1ce1ecb80ed35cc6ca27678b013c8d1b314 | 389 | py | Python | src/__main__.py | haihala/space-tavern | c5e819c71fa561a9065cb3969a6b1625205f2fd0 | [
"MIT"
] | null | null | null | src/__main__.py | haihala/space-tavern | c5e819c71fa561a9065cb3969a6b1625205f2fd0 | [
"MIT"
] | null | null | null | src/__main__.py | haihala/space-tavern | c5e819c71fa561a9065cb3969a6b1625205f2fd0 | [
"MIT"
] | null | null | null | from constants import CONFPATH
from engine import Engine
from json import load, dump
from os import mkdir
import sys
from os.path import isdir, isfile, dirname
def load_config():
with open(CONFPATH) as f:
return load(f)
def main(resolution):
engine = Engine(load_config(), resolution)
engine.run()
if __name__=="__main__":
main([int(i) for i in sys.argv[1:3]])
| 20.473684 | 46 | 0.706941 | 60 | 389 | 4.416667 | 0.566667 | 0.045283 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006369 | 0.192802 | 389 | 18 | 47 | 21.611111 | 0.83758 | 0 | 0 | 0 | 0 | 0 | 0.020566 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.428571 | 0 | 0.642857 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
42fd0630c8ef6a6c73639b6d7a9278fe5048f1c2 | 273 | py | Python | usaspending_api/views.py | truthiswill/usaspending-api | bd7d915442e2ec94cc830c480ceeffd4479be6c0 | [
"CC0-1.0"
] | null | null | null | usaspending_api/views.py | truthiswill/usaspending-api | bd7d915442e2ec94cc830c480ceeffd4479be6c0 | [
"CC0-1.0"
] | 3 | 2020-02-12T01:16:46.000Z | 2021-06-10T20:36:57.000Z | usaspending_api/views.py | truthiswill/usaspending-api | bd7d915442e2ec94cc830c480ceeffd4479be6c0 | [
"CC0-1.0"
] | null | null | null | from django.http import HttpResponse
from django.views import View
import json
class StatusView(View):
def get(self, request, format=None):
response_object = {
"status": "running"
}
return HttpResponse(json.dumps(response_object))
| 22.75 | 56 | 0.67033 | 31 | 273 | 5.83871 | 0.709677 | 0.110497 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.241758 | 273 | 11 | 57 | 24.818182 | 0.874396 | 0 | 0 | 0 | 0 | 0 | 0.047619 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0 | 0.333333 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
6e0d4ea88408c4581b91f97fff19092653097b98 | 1,489 | py | Python | PRINCESSCF/introduce/models.py | KnS-hacks/1-PrincessDFM-BE | 44073783c3591305ed93378b24693cf86c7ff1ee | [
"MIT"
] | null | null | null | PRINCESSCF/introduce/models.py | KnS-hacks/1-PrincessDFM-BE | 44073783c3591305ed93378b24693cf86c7ff1ee | [
"MIT"
] | 3 | 2021-11-18T10:18:40.000Z | 2021-11-19T05:24:10.000Z | PRINCESSCF/introduce/models.py | KnS-hacks/1-PrincessDFM-BE | 44073783c3591305ed93378b24693cf86c7ff1ee | [
"MIT"
] | null | null | null | from django.db import models
class HashTag(models.Model):
name = models.CharField(primary_key=True, max_length=20)
def __str__(self):
return self.name
class MBTI(models.Model):
name = models.CharField(primary_key=True, max_length=20)
def __str__(self):
return self.name
class Participate(models.Model):
name = models.CharField(primary_key=True, max_length=20)
def __str__(self):
return self.name
class Interest(models.Model):
name = models.CharField(primary_key=True, max_length=20)
def __str__(self):
return self.name
class Member(models.Model):
id = models.BigAutoField(primary_key=True)
school = models.CharField(max_length=100, null=True)
name = models.CharField(max_length=10)
introduce = models.CharField(null=True, blank=True, max_length=1000)
motto = models.CharField(null=True, blank=True, max_length=1000)
team = models.IntegerField(null=True)
participate = models.ManyToManyField(Participate, blank=True)
interest = models.ManyToManyField(Interest, blank=True)
mbti = models.ManyToManyField(MBTI, blank=True)
hashtag = models.ManyToManyField(HashTag, blank=True)
github = models.URLField(blank=True, null=True, max_length=100)
instagram = models.URLField(blank=True, null=True, max_length=100)
pic = models.URLField(blank=True, null=True, max_length=100)
def __str__(self):
return self.name
class Meta:
ordering = ['team'] | 29.196078 | 72 | 0.711216 | 194 | 1,489 | 5.273196 | 0.221649 | 0.096774 | 0.11437 | 0.078201 | 0.57087 | 0.57087 | 0.57087 | 0.542522 | 0.542522 | 0.328446 | 0 | 0.02449 | 0.1773 | 1,489 | 51 | 73 | 29.196078 | 0.810612 | 0 | 0 | 0.4 | 0 | 0 | 0.002685 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.028571 | 0.142857 | 0.971429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
6e280c8c7704a013562649864b9ea24a57b9b2d1 | 237 | py | Python | modules/pyttsx_speak.py | Marvin-Virtual-Assistant/Marvin-v3-client | b3f40051ca5fe75ca73ffe9da7ac0dbf1ac61d31 | [
"Apache-2.0"
] | 3 | 2018-10-13T02:53:53.000Z | 2020-10-14T02:33:36.000Z | modules/pyttsx_speak.py | Marvin-Virtual-Assistant/Marvin-v3-client | b3f40051ca5fe75ca73ffe9da7ac0dbf1ac61d31 | [
"Apache-2.0"
] | null | null | null | modules/pyttsx_speak.py | Marvin-Virtual-Assistant/Marvin-v3-client | b3f40051ca5fe75ca73ffe9da7ac0dbf1ac61d31 | [
"Apache-2.0"
] | 2 | 2018-10-26T04:28:16.000Z | 2018-12-25T08:11:00.000Z | # env imports
from os import path
from marvinenv.lib.sitepackages import pyttsx3
def pyttsx_speak(tts): # function to speak with engine
engine = pyttsx3.init()
engine.say(tts) # que tts data
engine.runAndWait() # speak text
| 26.333333 | 54 | 0.734177 | 34 | 237 | 5.088235 | 0.705882 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010363 | 0.185654 | 237 | 8 | 55 | 29.625 | 0.88601 | 0.274262 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
6e2dd111a47fbe34d6ccf79fa5d43d4e31e00362 | 177 | py | Python | soma.py | gersonraniery/Exercicios | 1f72b1b5e012eee1d90edb50adfe1d60598edb2b | [
"MIT"
] | null | null | null | soma.py | gersonraniery/Exercicios | 1f72b1b5e012eee1d90edb50adfe1d60598edb2b | [
"MIT"
] | null | null | null | soma.py | gersonraniery/Exercicios | 1f72b1b5e012eee1d90edb50adfe1d60598edb2b | [
"MIT"
] | null | null | null | #Criando um algoritmo para somar duas variáveis
a = int(input('Digite um valor:'))
b = int(input('Digite outro valor: '))
soma = a+b
print(f'A soma entre {a} e {b} é {soma}.')
| 25.285714 | 47 | 0.661017 | 32 | 177 | 3.65625 | 0.625 | 0.136752 | 0.239316 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.169492 | 177 | 6 | 48 | 29.5 | 0.795918 | 0.259887 | 0 | 0 | 0 | 0 | 0.523077 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.25 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
281cb8bdfa0e19b583b71d226c20d68a853086e6 | 388 | py | Python | tests/test_cursor.py | adh/ctds | 8c8b562341fb9635e3d89013ff06ffc6b1397abb | [
"MIT"
] | 78 | 2016-03-14T18:02:05.000Z | 2021-11-26T23:23:06.000Z | tests/test_cursor.py | adh/ctds | 8c8b562341fb9635e3d89013ff06ffc6b1397abb | [
"MIT"
] | 64 | 2016-10-18T17:54:08.000Z | 2021-09-30T11:01:02.000Z | tests/test_cursor.py | adh/ctds | 8c8b562341fb9635e3d89013ff06ffc6b1397abb | [
"MIT"
] | 17 | 2016-07-21T20:22:12.000Z | 2020-11-07T01:25:26.000Z | import ctds
from .base import TestExternalDatabase
class TestCursor(TestExternalDatabase):
def test___doc__(self):
self.assertEqual(
ctds.Cursor.__doc__,
'''\
A database cursor used to manage the context of a fetch operation.
:pep:`0249#cursor-objects`
'''
)
def test_typeerror(self):
self.assertRaises(TypeError, ctds.Cursor)
| 20.421053 | 66 | 0.670103 | 43 | 388 | 5.813953 | 0.651163 | 0.056 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.013559 | 0.239691 | 388 | 18 | 67 | 21.555556 | 0.833898 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | 1 | 0.222222 | false | 0 | 0.222222 | 0 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
281e2505b4bdcee6d43687b724f4289249d99d2b | 1,214 | py | Python | dyce/symmetries.py | posita/dyce | aa0180cc1e3607e552e45f9d03af7de667838aea | [
"MIT"
] | 18 | 2021-07-08T07:04:48.000Z | 2022-03-25T07:42:50.000Z | dyce/symmetries.py | posita/dyce | aa0180cc1e3607e552e45f9d03af7de667838aea | [
"MIT"
] | 6 | 2021-07-21T23:40:41.000Z | 2022-01-08T14:50:53.000Z | dyce/symmetries.py | posita/dyce | aa0180cc1e3607e552e45f9d03af7de667838aea | [
"MIT"
] | null | null | null | # ======================================================================================
# Copyright and other protections apply. Please see the accompanying LICENSE file for
# rights and restrictions governing use of this software. All rights not expressly
# waived or licensed are reserved. If that file is missing or appears to be modified
# from its original, then please contact the author before viewing or using this
# software in any capacity.
# ======================================================================================
from __future__ import annotations
import sys
__all__ = (
"comb",
"gcd",
)
# ---- Functions -----------------------------------------------------------------------
if sys.version_info >= (3, 9):
from math import gcd
else:
from functools import reduce
from math import gcd as _gcd
def gcd(*integers: int) -> int:
return reduce(_gcd, integers, 0)
if sys.version_info >= (3, 8):
from math import comb
else:
from fractions import Fraction
from math import factorial
def comb(__n: int, __k: int) -> int:
return int(
Fraction(Fraction(factorial(__n), factorial(__k)), factorial(__n - __k))
)
| 28.904762 | 88 | 0.547776 | 134 | 1,214 | 4.783582 | 0.552239 | 0.049922 | 0.087363 | 0.049922 | 0.053042 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005081 | 0.189456 | 1,214 | 41 | 89 | 29.609756 | 0.646341 | 0.504942 | 0 | 0.090909 | 0 | 0 | 0.011824 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0 | 0.363636 | 0.090909 | 0.545455 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
2839a34e28511b73281f663b11ca618fd836bad5 | 135 | py | Python | P.P.P/arithmetic oprators.py | sadique720/python-basics | 29786e617dcccbfcb73a213cd3d73fc545b837c3 | [
"MIT"
] | 2 | 2019-05-28T10:55:12.000Z | 2019-05-28T10:55:14.000Z | P.P.P/arithmetic oprators.py | sadique720/python-basics | 29786e617dcccbfcb73a213cd3d73fc545b837c3 | [
"MIT"
] | null | null | null | P.P.P/arithmetic oprators.py | sadique720/python-basics | 29786e617dcccbfcb73a213cd3d73fc545b837c3 | [
"MIT"
] | null | null | null | a=10
b=20
a+b #addition
a/b #divde
a-b #substraction
a*b #multiplication
a%b #reminder
a**b #exponent
a//b #floor devision
| 13.5 | 21 | 0.651852 | 26 | 135 | 3.384615 | 0.461538 | 0.159091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.037736 | 0.214815 | 135 | 9 | 22 | 15 | 0.792453 | 0.511111 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
284d04cc695de4adfd6e3c6ac25d8544ba1b3947 | 755 | py | Python | pytma/tests/test_utility.py | aloidia-solutions/nlp-modelling | cc181bf08c5f93d6949d47bb5212dcefb336279d | [
"MIT"
] | 1 | 2019-07-25T21:18:10.000Z | 2019-07-25T21:18:10.000Z | pytma/tests/test_utility.py | brucebcampbell/nlp-modelling | b6e5b6c5b2df7cc20e7de68f32d164981353aaf9 | [
"MIT"
] | 13 | 2019-08-08T15:42:27.000Z | 2019-09-29T20:34:14.000Z | pytma/tests/test_utility.py | aloidia-solutions/nlp-modelling | cc181bf08c5f93d6949d47bb5212dcefb336279d | [
"MIT"
] | 1 | 2019-10-23T19:51:41.000Z | 2019-10-23T19:51:41.000Z | import pytest
import pytma
from pytma import Utility
from pytma.Utility import LogError
def test_logger():
"""
Testing the logging helper.
"""
log = Utility.Logger('.', "test_pytma")
try:
log.info("information")
except LogError:
pytest.fail("Unexpected LogError ..")
try:
log.debug("debugging info")
except LogError:
pytest.fail("Unexpected LogError ..")
try:
log.warning("warning")
except LogError:
pytest.fail("Unexpected LogError ..")
try:
log.error("error")
except LogError:
pytest.fail("Unexpected LogError ..")
try:
log.critical("critical message")
except LogError:
pytest.fail("Unexpected LogError ..")
| 19.358974 | 45 | 0.606623 | 77 | 755 | 5.922078 | 0.337662 | 0.065789 | 0.219298 | 0.263158 | 0.513158 | 0.513158 | 0.421053 | 0.421053 | 0 | 0 | 0 | 0 | 0.272848 | 755 | 38 | 46 | 19.868421 | 0.830601 | 0.035762 | 0 | 0.576923 | 0 | 0 | 0.244726 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.038462 | false | 0 | 0.153846 | 0 | 0.192308 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
28596eea00f6e54a8cb03d3c432442a23adfaaa3 | 267 | py | Python | mqtt/mqtt_publish.py | wichmann/RaspPI | 168609cb237e59a4c895eae798c0dab052aab38b | [
"MIT"
] | null | null | null | mqtt/mqtt_publish.py | wichmann/RaspPI | 168609cb237e59a4c895eae798c0dab052aab38b | [
"MIT"
] | null | null | null | mqtt/mqtt_publish.py | wichmann/RaspPI | 168609cb237e59a4c895eae798c0dab052aab38b | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
# Notwendige Bibliothek installieren:
# pip3 install paho-mqtt
import paho.mqtt.publish as publish
# veröffentliche eine neue Nachricht unter dem angegebenen Thema
publish.single("test/topic", "nachricht", hostname="192.168.24.132")
| 20.538462 | 68 | 0.756554 | 35 | 267 | 5.771429 | 0.857143 | 0.079208 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.056522 | 0.138577 | 267 | 12 | 69 | 22.25 | 0.821739 | 0.554307 | 0 | 0 | 0 | 0 | 0.289474 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
285dcd4b75654f6a7374b0d636b6381ae2a00dbc | 425 | py | Python | dataset_toolkit/Export/AbstractExport.py | PeloriTech/DatasetToolkit | e11e709b59b8d3bbc0e322489f02f1307f251368 | [
"MIT"
] | null | null | null | dataset_toolkit/Export/AbstractExport.py | PeloriTech/DatasetToolkit | e11e709b59b8d3bbc0e322489f02f1307f251368 | [
"MIT"
] | null | null | null | dataset_toolkit/Export/AbstractExport.py | PeloriTech/DatasetToolkit | e11e709b59b8d3bbc0e322489f02f1307f251368 | [
"MIT"
] | null | null | null | from abc import ABC, abstractmethod
from dataset_toolkit.Model.AnnotationModel import AnnotationModel
class AbstractExport(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def append(self, new_dataset_dir: str, new_annotations_dir: str,
annotation_model: AnnotationModel, new_annotation_filename: str):
pass
@abstractmethod
def close(self):
pass | 22.368421 | 80 | 0.705882 | 45 | 425 | 6.488889 | 0.488889 | 0.174658 | 0.143836 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.232941 | 425 | 19 | 81 | 22.368421 | 0.895706 | 0 | 0 | 0.461538 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.230769 | false | 0.230769 | 0.153846 | 0 | 0.461538 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
2862b6ea36d735d587eb2a3602956ee0c3330a8e | 1,375 | py | Python | haasomeapi/dataobjects/custombots/ScriptBot.py | iamcos/haasomeapi | eac1640cc13e1e7649b8a8d6ed88184722c907c8 | [
"MIT"
] | 9 | 2018-07-08T22:40:53.000Z | 2022-03-21T20:32:43.000Z | haasomeapi/dataobjects/custombots/ScriptBot.py | iamcos/haasomeapi | eac1640cc13e1e7649b8a8d6ed88184722c907c8 | [
"MIT"
] | 5 | 2018-08-25T11:48:05.000Z | 2019-12-12T19:57:20.000Z | haasomeapi/dataobjects/custombots/ScriptBot.py | iamcos/haasomeapi | eac1640cc13e1e7649b8a8d6ed88184722c907c8 | [
"MIT"
] | 6 | 2018-08-31T23:49:36.000Z | 2022-01-08T04:51:21.000Z | from typing import Dict
from typing import List
from haasomeapi.dataobjects.custombots.BaseCustomBot import BaseCustomBot
from haasomeapi.dataobjects.custombots.dataobjects.IndicatorOption import IndicatorOption
from haasomeapi.dataobjects.custombots.dataobjects.ScriptBotOrder import ScriptBotOrder
class ScriptBot(BaseCustomBot):
""" Data Object containing a Script Bot
:ivar openOrders = Dict[str, :class:`~haasomeapi.dataobjects.custombots.dataobjects.ScriptBotOrder`]:
:ivar finishedOrder = List[str]:
:ivar cancelledOrders = List[str]:
:ivar availableScript = Dict[str, str]:
:ivar scriptId: str:
:ivar fullScriptName: str:
:ivar botSettings: List[:class:`~haasomeapi.dataobjects.custombots.dataobjects.IndicatorOption`]:
:ivar scriptStatusOk: bool:
:ivar localScriptPath: str:
:ivar lastLongBuyPrice: float:
:ivar lastShortBuyPrice: float:
:ivar lastLongSellPrice: float:
:ivar lastShortSellPrice: float:
"""
openOrders = Dict[str, ScriptBotOrder]
finishedOrder = List[str]
cancelledOrders = List[str]
availableScript = Dict[str, str]
scriptId: str
fullScriptName: str
botSettings: List[IndicatorOption]
scriptStatusOk: bool
localScriptPath: str
lastLongBuyPrice: float
lastShortBuyPrice: float
lastLongSellPrice: float
lastShortSellPrice: float
| 30.555556 | 105 | 0.750545 | 129 | 1,375 | 8 | 0.27907 | 0.040698 | 0.150194 | 0.162791 | 0.236434 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166545 | 1,375 | 44 | 106 | 31.25 | 0.900524 | 0.418909 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.263158 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
2862e4d64497eed04f5f94d32b2828f6b7ffc9f8 | 306 | py | Python | test/redis_node.py | jbfavre/dynomite | 16316ebd317a04f282f81d84864ae83a23472007 | [
"Apache-2.0"
] | 18 | 2016-05-12T18:01:32.000Z | 2021-09-27T08:45:48.000Z | test/redis_node.py | jbfavre/dynomite | 16316ebd317a04f282f81d84864ae83a23472007 | [
"Apache-2.0"
] | null | null | null | test/redis_node.py | jbfavre/dynomite | 16316ebd317a04f282f81d84864ae83a23472007 | [
"Apache-2.0"
] | 1 | 2021-06-17T06:07:07.000Z | 2021-06-17T06:07:07.000Z | #!/usr/bin/python
import redis
from node import Node
class RedisNode(Node):
def __init__(self, host, ip, port):
super(RedisNode, self).__init__(host, ip, port)
self.name = "Redis" + self.name
def get_connection(self):
return redis.StrictRedis(self.host, self.port, db=0)
| 23.538462 | 60 | 0.663399 | 43 | 306 | 4.511628 | 0.534884 | 0.082474 | 0.103093 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004132 | 0.20915 | 306 | 12 | 61 | 25.5 | 0.797521 | 0.052288 | 0 | 0 | 0 | 0 | 0.017301 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.25 | 0.125 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
286bb810282eac89f576f313a1f10e820c1e1733 | 497 | py | Python | versions/gslversions.py | mjmottram/snoing | fc0167cb7492a47f6541f3a30691083d9ae1578d | [
"MIT"
] | null | null | null | versions/gslversions.py | mjmottram/snoing | fc0167cb7492a47f6541f3a30691083d9ae1578d | [
"MIT"
] | null | null | null | versions/gslversions.py | mjmottram/snoing | fc0167cb7492a47f6541f3a30691083d9ae1578d | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# GSLVersions
#
# GSL releases: ROOT seems to require GSL 1.1
#
# Author:
# - 2015-06-05 M Mottram <m.mottram@qmul.ac.uk> first instance
#
####################################################################################################
import gsl
class Gsl116(gsl.Gsl):
""" Package for gsl. """
def __init__(self, system):
""" Initialize the package, set the name."""
super(Gsl116, self).__init__("gsl-1.16", system, "gsl-1.16.tar.gz")
| 23.666667 | 100 | 0.496982 | 59 | 497 | 4.050847 | 0.677966 | 0.050209 | 0.050209 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.053269 | 0.169014 | 497 | 20 | 101 | 24.85 | 0.525424 | 0.406439 | 0 | 0 | 0 | 0 | 0.132184 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.25 | 0 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
286f87c478d4969fc74057c1bb96233774f180b5 | 836 | py | Python | model.py | man4321/messenger-new | 45aa00327ddbedb7ed227b1d93a8b1f1810caa02 | [
"MIT"
] | 1 | 2020-09-09T06:03:48.000Z | 2020-09-09T06:03:48.000Z | model.py | man4321/messenger-new | 45aa00327ddbedb7ed227b1d93a8b1f1810caa02 | [
"MIT"
] | 3 | 2020-06-18T15:09:28.000Z | 2022-03-02T04:42:34.000Z | model.py | man4321/messenger-new | 45aa00327ddbedb7ed227b1d93a8b1f1810caa02 | [
"MIT"
] | null | null | null | from google.appengine.ext import ndb
from google.appengine.api import users
import webapp2
class User(ndb.Model):
firstname=ndb.StringProperty()
lastname=ndb.StringProperty()
username=ndb.StringProperty()
password=ndb.StringProperty()
email=ndb.StringProperty()
user_id=ndb.StringProperty()
class Sender(ndb.Model):
sender_key=ndb.KeyProperty(kind=User)
reciver_key=ndb.KeyProperty(kind=User)
content=ndb.TextProperty()
send_time=ndb.DateTimeProperty(auto_now_add=True)
# class Reciver(ndb.Model):
# reciver_key=ndb.KeyProperty(kind=User)
# content=ndb.TextProperty()
# reciver_time=ndb.DateTimeProperty(auto_now_add=True)
class Feeds(ndb.Model):
user_key=ndb.KeyProperty(kind=User)
post=ndb.TextProperty()
post_time=ndb.DateTimeProperty(auto_now_add=True)
| 26.125 | 58 | 0.746411 | 106 | 836 | 5.754717 | 0.330189 | 0.167213 | 0.111475 | 0.137705 | 0.457377 | 0.37541 | 0.37541 | 0.314754 | 0.177049 | 0 | 0 | 0.001391 | 0.139952 | 836 | 31 | 59 | 26.967742 | 0.84701 | 0.186603 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.052632 | 0.157895 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
28848f45426af5d705b77e21de5c5dbfd0c89709 | 3,979 | py | Python | sniff.py | krzys-h/http-sniff-dashboard | d19346f27dd43befae73ed11dbcf73f46c16dabd | [
"WTFPL"
] | 4 | 2016-08-22T21:55:41.000Z | 2017-08-26T09:55:15.000Z | sniff.py | krzys-h/http-sniff-dashboard | d19346f27dd43befae73ed11dbcf73f46c16dabd | [
"WTFPL"
] | null | null | null | sniff.py | krzys-h/http-sniff-dashboard | d19346f27dd43befae73ed11dbcf73f46c16dabd | [
"WTFPL"
] | null | null | null | import threading
import datetime
import re
import json
from scapy.all import *
from scapy.layers.l2 import *
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
from dnslib.server import DNSLogger, DNSServer
from dnslib.fixedresolver import FixedResolver
resolver = FixedResolver(". 60 IN A 10.15.0.9")
logger = DNSLogger(prefix=False)
server = DNSServer(resolver,port=53,address='',logger=logger)
urls = []
logins = []
images = []
log = open('log', 'a')
def match_password(payload):
result = []
for match in ['pass', 'pwd', 'password', 'haslo']:
pwd = re.search('%s=([a-zA-Z0-9.-]*)' % match, str(payload))
if pwd:
print("Password: %s" % pwd.group(1))
log.write("Password: %s" % pwd.group(1))
pas = pwd.group(1)
pas = pas[:2] + '*' * (len(pas) - 2)
result.append("Password: %s" % pas)
return result
def match_email(payload):
result = []
for match in ['email', 'login', 'username', 'user', 'name']:
login = re.search('%s=([a-zA-Z0-9.-]*)' % match, str(payload))
if login:
print("Login: %s" % login.group(1))
log.write("Login: %s" % login.group(1))
result.append("Login: %s" % login.group(1))
return result
def match_dns(payload):
result = []
host = re.search('Host: ([a-zA-Z0-9.-]*)\r\n', str(payload))
if host:
print("Site: " + host.group(1))
result.append(host.group(1))
log.write("Site: " + host.group(1))
return result
def match_image_path(payload):
result = []
dns = match_dns(payload)
if dns:
m = re.search('([A-Z]+) (.+?\.(png|jpg)) HTTP/1\.[01]\r\n', str(payload))
if m:
url = "http://"+dns[0]+m.group(2)
print("Found image: "+url)
result.append(url)
return result
def annotate(ip, l):
result = []
for item in l:
result.append('[%s] [%s] %s' % (datetime.datetime.now().strftime('%H:%M:%S'), ip, item))
return result
def pkt_callback(pkt):
tcp = pkt.getlayer('TCP')
ip = pkt.getlayer('IP')
if ip and tcp:
if tcp.dport == 80 and ip.src != '127.0.0.1':
global urls
global logins
global images
urls = annotate(ip.src, match_dns(tcp.payload)) + urls
logins = annotate(ip.src, match_email(tcp.payload)) + logins
logins = annotate(ip.src, match_password(tcp.payload)) + logins
images = match_image_path(tcp.payload) + images
if len(urls) > 100:
urls = urls[:100]
if len(logins) > 100:
logins = logins[:100]
if len(images) > 100:
images = images[:100]
class HTTPHandler(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
if self.path == '/':
with open('index.html') as f:
self.wfile.write(f.read())
elif self.path == '/jquery.js':
with open('jquery.js') as f:
self.wfile.write(f.read())
elif self.path == '/urls':
self.wfile.write(json.dumps(list(reversed(sorted(list(set(urls)))))))
elif self.path == '/logins':
self.wfile.write(json.dumps(list(reversed(sorted(list(set(logins)))))))
elif self.path == '/images':
self.wfile.write(json.dumps(images))
else:
print "error", self.path
def do_HEAD(self):
self._set_headers()
def run():
server_address = ('0.0.0.0', 9000)
httpd = HTTPServer(server_address, HTTPHandler)
print 'Starting httpd...'
httpd.serve_forever()
http_thread = threading.Thread(target=run)
http_thread.daemon=False
http_thread.start()
sniff(iface="mon0", prn=pkt_callback, store=0)
| 27.631944 | 97 | 0.567228 | 511 | 3,979 | 4.358121 | 0.287671 | 0.024248 | 0.033678 | 0.008083 | 0.227212 | 0.12573 | 0.10238 | 0.10238 | 0.10238 | 0.10238 | 0 | 0.02481 | 0.270671 | 3,979 | 143 | 98 | 27.825175 | 0.742591 | 0 | 0 | 0.127273 | 0 | 0 | 0.102538 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.054545 | 0.090909 | null | null | 0.054545 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
288f60690bc713d1251a7a8c2039c167ca89225f | 216 | py | Python | A2OJ-11/027_A_Petya_and_Strings.py | vendyv/A2OJ-Ladders | 5ebaf4b3322e19cab687a642bc043161d71bc5ff | [
"MIT"
] | null | null | null | A2OJ-11/027_A_Petya_and_Strings.py | vendyv/A2OJ-Ladders | 5ebaf4b3322e19cab687a642bc043161d71bc5ff | [
"MIT"
] | null | null | null | A2OJ-11/027_A_Petya_and_Strings.py | vendyv/A2OJ-Ladders | 5ebaf4b3322e19cab687a642bc043161d71bc5ff | [
"MIT"
] | null | null | null | """
27 Petya and Strings - https://codeforces.com/problemset/problem/112/A
"""
one = input().lower()
two = input().lower()
if one < two:
print("-1")
elif one > two:
print("1")
else:
print("0")
| 18 | 71 | 0.564815 | 30 | 216 | 4.066667 | 0.7 | 0.163934 | 0.180328 | 0.196721 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.047904 | 0.226852 | 216 | 11 | 72 | 19.636364 | 0.682635 | 0.324074 | 0 | 0 | 0 | 0 | 0.031496 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.375 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
289761c43d301162fc76a469ea36e54f8a98e9eb | 4,006 | py | Python | chrome/common/extensions/docs/server2/future.py | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/common/extensions/docs/server2/future.py | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/common/extensions/docs/server2/future.py | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import sys
import traceback
_no_value = object()
def _DefaultErrorHandler(error):
raise error
def All(futures, except_pass=None, except_pass_log=False):
'''Creates a Future which returns a list of results from each Future in
|futures|.
If any Future raises an error other than those in |except_pass| the returned
Future will raise as well.
If any Future raises an error in |except_pass| then None will be inserted as
its result. If |except_pass_log| is True then the exception will be logged.
'''
def resolve():
resolved = []
for f in futures:
try:
resolved.append(f.Get())
# "except None" will simply not catch any errors.
except except_pass:
if except_pass_log:
logging.error(traceback.format_exc())
resolved.append(None)
pass
return resolved
return Future(callback=resolve)
def Race(futures, except_pass=None, default=_no_value):
'''Returns a Future which resolves to the first Future in |futures| that
either succeeds or throws an error apart from those in |except_pass|.
If all Futures throw errors in |except_pass| then |default| is returned,
if specified. If |default| is not specified then one of the passed errors
will be re-thrown, for a nice stack trace.
'''
def resolve():
first_future = None
for future in futures:
if first_future is None:
first_future = future
try:
return future.Get()
# "except None" will simply not catch any errors.
except except_pass:
pass
if default is not _no_value:
return default
# Everything failed and there is no default value, propagate the first
# error even though it was caught by |except_pass|.
return first_future.Get()
return Future(callback=resolve)
class Future(object):
'''Stores a value, error, or callback to be used later.
'''
def __init__(self, value=_no_value, callback=None, exc_info=None):
self._value = value
self._callback = callback
self._exc_info = exc_info
if (self._value is _no_value and
self._callback is None and
self._exc_info is None):
raise ValueError('Must have either a value, error, or callback.')
def Then(self, callback, error_handler=_DefaultErrorHandler):
'''Creates and returns a future that runs |callback| on the value of this
future, or runs optional |error_handler| if resolving this future results in
an exception.
If |callback| returns a non-Future value then the returned Future will
resolve to that value.
If |callback| returns a Future then it gets chained to the current Future.
This means that the returned Future will resolve to *that* Future's value.
This behaviour is transitive.
For example,
def fortytwo():
return Future(value=42)
def inc(x):
return x + 1
def inc_future(x):
return Future(value=x + 1)
fortytwo().Then(inc).Get() ==> 43
fortytwo().Then(inc_future).Get() ==> 43
fortytwo().Then(inc_future).Then(inc_future).Get() ==> 44
'''
def then():
val = None
try:
val = self.Get()
except Exception as e:
val = error_handler(e)
else:
val = callback(val)
return val.Get() if isinstance(val, Future) else val
return Future(callback=then)
def Get(self):
'''Gets the stored value, error, or callback contents.
'''
if self._value is not _no_value:
return self._value
if self._exc_info is not None:
self._Raise()
try:
self._value = self._callback()
return self._value
except:
self._exc_info = sys.exc_info()
self._Raise()
def _Raise(self):
exc_info = self._exc_info
raise exc_info[0], exc_info[1], exc_info[2]
| 29.895522 | 80 | 0.666251 | 576 | 4,006 | 4.505208 | 0.265625 | 0.046243 | 0.025434 | 0.024277 | 0.137958 | 0.1079 | 0.069364 | 0.04316 | 0.04316 | 0.04316 | 0 | 0.00567 | 0.251623 | 4,006 | 133 | 81 | 30.120301 | 0.859907 | 0.09336 | 0 | 0.238806 | 0 | 0 | 0.022959 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.104478 | 0.044776 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
289fb708a3b4a8d0eacc737db3334f6263a8f6c4 | 88 | py | Python | swea/lv1/alphabet.py | mrbartrns/swacademy_structure | 778f0546030385237c383d81ec37d5bd9ed1272d | [
"MIT"
] | null | null | null | swea/lv1/alphabet.py | mrbartrns/swacademy_structure | 778f0546030385237c383d81ec37d5bd9ed1272d | [
"MIT"
] | null | null | null | swea/lv1/alphabet.py | mrbartrns/swacademy_structure | 778f0546030385237c383d81ec37d5bd9ed1272d | [
"MIT"
] | null | null | null | # SWEA 2050
string = input()
for c in string:
print(ord(c) - ord("A") + 1, end=" ")
| 17.6 | 41 | 0.545455 | 15 | 88 | 3.2 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.074627 | 0.238636 | 88 | 4 | 42 | 22 | 0.641791 | 0.102273 | 0 | 0 | 0 | 0 | 0.025974 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9537a587748a16e07bb00147e1f630d3dee1f4ed | 7,042 | py | Python | 2018/23_ExperimentalEmergencyTeleportation/test_nanobots.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | 1 | 2021-01-03T23:09:28.000Z | 2021-01-03T23:09:28.000Z | 2018/23_ExperimentalEmergencyTeleportation/test_nanobots.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | 6 | 2020-12-26T21:02:42.000Z | 2020-12-26T21:02:52.000Z | 2018/23_ExperimentalEmergencyTeleportation/test_nanobots.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | null | null | null | # ======================================================================
# Experimental Emergency Teleportation
# Advent of Code 2018 Day 23 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ======================================================================
# t e s t _ n a n o b o t s . p y
# ======================================================================
"""Test solver for Advent of Code 2018 day 23,
Experimental Emergency Teleportation"""
# ----------------------------------------------------------------------
# import
# ----------------------------------------------------------------------
import unittest
import aoc_23
import nanobots
# ----------------------------------------------------------------------
# constants
# ----------------------------------------------------------------------
EXAMPLE_TEXT = """
pos=<0,0,0>, r=4
pos=<1,0,0>, r=1
pos=<4,0,0>, r=3
pos=<0,2,0>, r=1
pos=<0,5,0>, r=3
pos=<0,0,3>, r=1
pos=<1,1,1>, r=1
pos=<1,1,2>, r=1
pos=<1,3,1>, r=1
"""
PART_ONE_TEXT = EXAMPLE_TEXT
PART_TWO_TEXT = EXAMPLE_TEXT
PART_ONE_RESULT = 7
PART_TWO_RESULT = 36
# ======================================================================
# TestNanobot
# ======================================================================
class TestNanobot(unittest.TestCase): # pylint: disable=R0904
"Test Nanobot object"
def test_empty_init(self):
"Test the default Nanobot creation"
# 1. Create default Nanobots object
myobj = nanobots.Nanobot()
# 2. Make sure it has the default values
self.assertEqual(myobj.x, None)
self.assertEqual(myobj.y, None)
self.assertEqual(myobj.z, None)
self.assertEqual(myobj.r, None)
def test_text_init(self):
"Test the Nanobot object creation from text"
# 1. Create Nanobot object from text
myobj = nanobots.Nanobot(text='pos=<-22356506,24819383,19709017>, r=53389427')
# 2. Make sure it has the expected values
self.assertEqual(myobj.x, -22356506)
self.assertEqual(myobj.y, 24819383)
self.assertEqual(myobj.z, 19709017)
self.assertEqual(myobj.r, 53389427)
def test_manhattan_distance(self):
# 1. Create some Nanobot objects from text
nb1 = nanobots.Nanobot(text='pos=<0,0,0>, r=4')
nb2 = nanobots.Nanobot(text='pos=<4,0,0>, r=3')
nb3 = nanobots.Nanobot(text='pos=<1,1,1>, r=1')
nb4 = nanobots.Nanobot(text='pos=<1,3,1>, r=4')
# 2. Check the distances
self.assertEqual(nb1.manhattan_distance(nb1), 0)
self.assertEqual(nb1.manhattan_distance(nb2), 4)
self.assertEqual(nb1.manhattan_distance(nb3), 3)
self.assertEqual(nb1.manhattan_distance(nb4), 5)
# 3. Check the ranges
self.assertEqual(nb1.in_range(nb1), True)
self.assertEqual(nb1.in_range(nb2), True)
self.assertEqual(nb1.in_range(nb3), True)
self.assertEqual(nb1.in_range(nb4), False)
# ======================================================================
# TestNanobots
# ======================================================================
class TestNanobots(unittest.TestCase): # pylint: disable=R0904
"Test Nanobots object"
def test_empty_init(self):
"Test the default Nanobots creation"
# 1. Create default Nanobots object
myobj = nanobots.Nanobots()
# 2. Make sure it has the default values
self.assertEqual(myobj.part2, False)
self.assertEqual(myobj.text, None)
self.assertEqual(len(myobj.bots), 0)
def test_text_init(self):
"Test the Nanobots object creation from text"
# 1. Create Nanobots object from text
myobj = nanobots.Nanobots(text=aoc_23.from_text(EXAMPLE_TEXT))
# 2. Make sure it has the expected values
self.assertEqual(myobj.part2, False)
self.assertEqual(len(myobj.text), 9)
self.assertEqual(len(myobj.bots), 9)
# 3. Check distances
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[0]), 0)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[1]), 1)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[2]), 4)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[3]), 2)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[4]), 5)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[5]), 3)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[6]), 3)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[7]), 4)
self.assertEqual(myobj.bots[0].manhattan_distance(myobj.bots[8]), 5)
# 4. Check range
self.assertEqual(myobj.bots[0].in_range(myobj.bots[0]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[1]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[2]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[3]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[4]), False)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[5]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[6]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[7]), True)
self.assertEqual(myobj.bots[0].in_range(myobj.bots[8]), False)
# 4. Check strongest signal
self.assertEqual(myobj.largest_signal_radius(), myobj.bots[0])
# 5. Check number in range
self.assertEqual(myobj.bots_in_range(myobj.bots[0]), 7)
def test_part_one(self):
"Test part one example of Nanobots object"
# 1. Create Nanobots object from text
myobj = nanobots.Nanobots(text=aoc_23.from_text(PART_ONE_TEXT))
# 2. Check the part one result
self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)
def test_part_two(self):
"Test part two example of Nanobots object"
# 1. Create Nanobots object from text
myobj = nanobots.Nanobots(part2=True, text=aoc_23.from_text(PART_TWO_TEXT))
# 2. Check the part two result
self.assertEqual(myobj.part_two(verbose=False), PART_TWO_RESULT)
# ----------------------------------------------------------------------
# module initialization
# ----------------------------------------------------------------------
if __name__ == '__main__':
pass
# ======================================================================
# end t e s t _ n a n o b o t s . p y end
# ======================================================================
| 38.906077 | 86 | 0.520023 | 812 | 7,042 | 4.407635 | 0.150246 | 0.184409 | 0.184409 | 0.12741 | 0.670858 | 0.541213 | 0.453758 | 0.432523 | 0.391171 | 0.274658 | 0 | 0.044339 | 0.218546 | 7,042 | 180 | 87 | 39.122222 | 0.606033 | 0.393496 | 0 | 0.065934 | 0 | 0 | 0.120525 | 0.007561 | 0 | 0 | 0 | 0 | 0.483516 | 1 | 0.076923 | false | 0.010989 | 0.032967 | 0 | 0.131868 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9539c1de135c1f35fc604f864894bcb72a662ef4 | 668 | py | Python | rouver/util.py | srittau/rouver | 29f3b9ca3e96eafc8ceb60e64c40308a5de6c9f6 | [
"MIT"
] | 1 | 2018-02-27T00:31:15.000Z | 2018-02-27T00:31:15.000Z | rouver/util.py | srittau/rouver | 29f3b9ca3e96eafc8ceb60e64c40308a5de6c9f6 | [
"MIT"
] | 69 | 2017-10-21T15:57:55.000Z | 2022-03-29T06:56:26.000Z | rouver/util.py | srittau/rouver | 29f3b9ca3e96eafc8ceb60e64c40308a5de6c9f6 | [
"MIT"
] | null | null | null | import re
from urllib.parse import quote, urljoin
from werkzeug import Request
_url_scheme_re = re.compile(r"^[a-zA-Z][a-zA-Z0-9.+-]*:")
def absolute_url(request: Request, path: str) -> str:
"""
Construct an absolute URL, using the request URL as base.
Non-printable and non-ASCII characters in the path are encoded,
but other characters, most notably slashes and percent signs are
not encoded. Make sure to call urllib.parse.quote() on paths that
can potentially contain such characters before passing them to
absolute_url().
"""
base_url: str = request.base_url
return urljoin(base_url, quote(path, safe="/:?&$@,;+=%~"))
| 31.809524 | 69 | 0.700599 | 100 | 668 | 4.6 | 0.6 | 0.071739 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003683 | 0.187126 | 668 | 20 | 70 | 33.4 | 0.843462 | 0.497006 | 0 | 0 | 0 | 0 | 0.123333 | 0.083333 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.428571 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
95524d4267035709e8eb5036fca197782013e735 | 1,560 | py | Python | analysis/legacy/plot_prob_example.py | Fizzics/desCluster | 43a8cff54619f85e837afd2f78aa9be8ec6ac8c6 | [
"MIT"
] | 2 | 2020-02-21T16:13:37.000Z | 2020-02-21T16:26:03.000Z | analysis/legacy/plot_prob_example.py | boada/HETDEXCluster | 43a8cff54619f85e837afd2f78aa9be8ec6ac8c6 | [
"MIT"
] | null | null | null | analysis/legacy/plot_prob_example.py | boada/HETDEXCluster | 43a8cff54619f85e837afd2f78aa9be8ec6ac8c6 | [
"MIT"
] | null | null | null | import pylab as pyl
import h5py as hdf
import corner
### Targeted ###
################
with hdf.File('./result_targetedPerfect.hdf5', 'r') as f:
dset = f[f.keys()[0]]
#data = dset['IDX', 'HALOID', 'ZSPEC', 'M200c', 'NGAL', 'LOSVD',
# 'LOSVD_err', 'MASS', 'LOSVD_dist']
data = dset['ZSPEC', 'M200c', 'LOSVD',]
mask = ((pyl.log10(data['LOSVD']) > 3.12 ) & (data['M200c'] < 10**14.5) |
(data['LOSVD'] < 50))
data = data[~mask]
badData = data[mask]
X = pyl.column_stack([data['ZSPEC'], pyl.log10(data['M200c']),
pyl.log10(data['LOSVD'])])
f = corner.corner(X, labels=['z', 'Log $M_{200c}$', 'Log $\sigma$'], bins=50,
smooth=True, fill_contours=True)
# add the bars. The axes are row indexed
axes = f.axes
# histogram labels
axes[0].set_ylabel('P(z)')
axes[0].yaxis.set_label_position('right')
axes[4].set_ylabel('P(Log $M_{200c}$)')
axes[4].yaxis.set_label_position('right')
axes[8].set_ylabel('P(Log $\sigma$)')
axes[8].yaxis.set_label_position('right')
# redshift
axes[0].axvspan(0.15,0.19,facecolor='#a60628', alpha=0.25)
axes[3].axvspan(0.15,0.19,facecolor='#a60628', alpha=0.25)
axes[6].axvspan(0.15,0.19,facecolor='#a60628', alpha=0.25)
# LOSVD
axes[6].axhspan(2.55,2.65,facecolor='#a60628', alpha=0.25)
axes[7].axhspan(2.55,2.65,facecolor='#a60628', alpha=0.25)
axes[8].axvspan(2.55,2.65,facecolor='#a60628', alpha=0.25)
# mass
axes[3].axhspan(13.25,13.5,facecolor='#a60628', alpha=0.25)
axes[7].axvspan(13.25,13.5,facecolor='#a60628', alpha=0.25)
axes[4].axvspan(13.25,13.5,facecolor='#a60628', alpha=0.25)
| 29.433962 | 77 | 0.640385 | 262 | 1,560 | 3.751908 | 0.316794 | 0.137335 | 0.183113 | 0.192269 | 0.43235 | 0.4059 | 0.344863 | 0.342828 | 0.342828 | 0.313327 | 0 | 0.131749 | 0.109615 | 1,560 | 52 | 78 | 30 | 0.575954 | 0.119231 | 0 | 0 | 0 | 0 | 0.160954 | 0.02161 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.1 | 0 | 0.1 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9561aa597ebbfd59a8ed0ea18630ff1a37bab5de | 1,165 | py | Python | mozumder/models/i18n/scripts.py | mozumder/django-mozumder | 887ce303249eac2d77de062fd57023dbc4b782dd | [
"MIT"
] | 1 | 2020-06-13T06:12:16.000Z | 2020-06-13T06:12:16.000Z | mozumder/models/i18n/scripts.py | mozumder/django-mozumder | 887ce303249eac2d77de062fd57023dbc4b782dd | [
"MIT"
] | 4 | 2020-06-18T03:53:29.000Z | 2021-06-09T17:56:12.000Z | mozumder/models/i18n/scripts.py | mozumder/django-mozumder | 887ce303249eac2d77de062fd57023dbc4b782dd | [
"MIT"
] | null | null | null | from django.db import models
from datetime import date
# Create your models here.
class Script(models.Model):
"""
For the script designator, use the ISO 15924 standard, four letters with the first letter
uppercase and the last three lowercase.
"""
iso_15294 = models.CharField(max_length=4,unique=True)
code_number = models.CharField(max_length=3,unique=True)
unicode_alias = models.CharField(max_length=75)
unicode_version = models.CharField(max_length=4)
version_date = models.DateField(default=date.today)
def __str__(self):
return self.iso_15294
class ScriptLang(models.Model):
script = models.ForeignKey('Script', related_name='names', on_delete=models.CASCADE)
name = models.CharField(max_length=30)
lang = models.ForeignKey('Lang', related_name='script_langs', on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(
fields = [
'script',
'lang',
],
name='scriptlang_uniquetogether'
)
]
def __str__(self):
return self.name
| 31.486486 | 93 | 0.645494 | 134 | 1,165 | 5.425373 | 0.5 | 0.103164 | 0.123796 | 0.165062 | 0.123796 | 0 | 0 | 0 | 0 | 0 | 0 | 0.025552 | 0.260944 | 1,165 | 36 | 94 | 32.361111 | 0.818815 | 0.133047 | 0 | 0.076923 | 0 | 0 | 0.062626 | 0.025253 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0.076923 | 0.076923 | 0.653846 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
95679b95ec8179097748957a665cf4edeb9d8a22 | 304 | py | Python | Recipes30991/main/management/commands/getcsv.py | Dawid-WSIU-Byd/FoodSearcher-Public | ff664311ac966f37651b7ff4cfddfefa9f463234 | [
"MIT"
] | null | null | null | Recipes30991/main/management/commands/getcsv.py | Dawid-WSIU-Byd/FoodSearcher-Public | ff664311ac966f37651b7ff4cfddfefa9f463234 | [
"MIT"
] | null | null | null | Recipes30991/main/management/commands/getcsv.py | Dawid-WSIU-Byd/FoodSearcher-Public | ff664311ac966f37651b7ff4cfddfefa9f463234 | [
"MIT"
] | null | null | null | from django.core.management.base import BaseCommand
from main.views import get_csv
class Command(BaseCommand):
help = 'Gets data from CSV file'
def handle(self, *args, **options):
get_csv()
self.stdout.write(self.style.SUCCESS('Successfully imported data from CSV'))
| 27.636364 | 85 | 0.690789 | 40 | 304 | 5.2 | 0.7 | 0.057692 | 0.105769 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | 304 | 10 | 86 | 30.4 | 0.866667 | 0 | 0 | 0 | 0 | 0 | 0.197279 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.428571 | 0 | 0.857143 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
957aac4641307daae23ead8b0daf9e91bb61b876 | 858 | py | Python | object_detection_tutorial.py | sbrocks/SiCom | 21018f855fe3d5b032ef608026454499a74b5373 | [
"MIT"
] | null | null | null | object_detection_tutorial.py | sbrocks/SiCom | 21018f855fe3d5b032ef608026454499a74b5373 | [
"MIT"
] | null | null | null | object_detection_tutorial.py | sbrocks/SiCom | 21018f855fe3d5b032ef608026454499a74b5373 | [
"MIT"
] | null | null | null | # IMPORTS
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
# from matplotlib import pyplot as plt ### CWH
from PIL import Image
# What model to download.
from keras.models import model_from_json
model = model_from_json(open("facial_expression_model.json", "r").read())
model.load_weights('facial_expression_model_weight.h5') #load weights
PATH_TO_TEST_IMAGES_DIR = 'object_detection/test_images' #cwh
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
| 27.677419 | 106 | 0.789044 | 141 | 858 | 4.617021 | 0.531915 | 0.046083 | 0.039939 | 0.049155 | 0.058372 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004054 | 0.137529 | 858 | 30 | 107 | 28.6 | 0.875676 | 0.252914 | 0 | 0 | 0 | 0 | 0.160317 | 0.14127 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.647059 | 0 | 0.647059 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
959cc628bda30750590e751639609285a876fa29 | 757 | py | Python | api/schemas.py | hdoupe/psl-stitch | c11bc5250aa33f37b03d9b723682b78e76dce8a3 | [
"MIT"
] | null | null | null | api/schemas.py | hdoupe/psl-stitch | c11bc5250aa33f37b03d9b723682b78e76dce8a3 | [
"MIT"
] | null | null | null | api/schemas.py | hdoupe/psl-stitch | c11bc5250aa33f37b03d9b723682b78e76dce8a3 | [
"MIT"
] | null | null | null | from datetime import datetime
from typing import Optional
from pydantic import BaseModel
class AppException(BaseModel):
owner: str
title: str
msg: str
class AppResponse(BaseModel):
model_pk: Optional[int]
status: str
ready: bool
project: str
url: Optional[str]
exception: Optional[AppException]
class OauthResponse(BaseModel):
access_token: str
expires_in: int
token_type: str
scope: str
refresh_token: str
class OauthToken(BaseModel):
access_token: str
refresh_token: str
expires_at: datetime
class ConnectConfig(BaseModel):
authorization_uri: str
state: str
class User(BaseModel):
username: str
status: str
class UserWithToken(User):
token: OauthToken
| 15.770833 | 37 | 0.706737 | 89 | 757 | 5.910112 | 0.449438 | 0.060837 | 0.076046 | 0.087452 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.228534 | 757 | 47 | 38 | 16.106383 | 0.900685 | 0 | 0 | 0.1875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.09375 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
95a7f94a2a7130236bf57afdc459e93ccf22bd8c | 2,654 | py | Python | logic/field.py | morsisko/Minesweeper | b4572f0a1c5048907a2de2449ad3ebe857f65cd5 | [
"MIT"
] | null | null | null | logic/field.py | morsisko/Minesweeper | b4572f0a1c5048907a2de2449ad3ebe857f65cd5 | [
"MIT"
] | null | null | null | logic/field.py | morsisko/Minesweeper | b4572f0a1c5048907a2de2449ad3ebe857f65cd5 | [
"MIT"
] | null | null | null | class Field:
"""Klasa reprezentująca jedno pole na planszy"""
CLOSED_STATE = 0
FLAGGED_STATE = 1
MAYBE_STATE = 2
OPENED_STATE = 3
def __init__(self, x, y):
self._x = x
self._y = y
self._mines_nearby = 0
self._is_mine = False
self._state = Field.CLOSED_STATE
def __eq__(self, other):
return self._x == other._x and self._y == other._y
def putMine(self):
"""Metoda kładąca mine na pole"""
self._is_mine = True
def isMine(self):
"""Metoda zwracająca True jeżeli pole jest miną, w przeciwnym wypadku False"""
return self._is_mine
def setMinesNearby(self, no):
"""Metoda ustawiająca ilość min w pobliżu pola"""
self._mines_nearby = no
def getMinesNearby(self):
"""Metoda zwracająca ilość min w pobliżu pola"""
return self._mines_nearby
def isClosed(self):
"""Metoda zwracająca True jeżeli pole nie zostało jeszcze odkryte, w przeciwnym wypadku False"""
return self._state == Field.CLOSED_STATE or self._state == Field.FLAGGED_STATE or self._state == Field.MAYBE_STATE
def isOpened(self):
"""Metoda zwracająca True jeżeli pole nie zostało jeszcze odkryte, w przeciwnym wypadku False"""
return self._state == Field.OPENED_STATE
def isMarked(self):
"""Metoda zwracająca True jeżeli pole zostało oznaczone (flagą lub znakiem zapytania), w przeciwnym wypadku False"""
return self._state == Field.FLAGGED_STATE or self._state == Field.MAYBE_STATE
def isFlagged(self):
"""Metoda zwracająca True jeżeli pole zostało oznaczone flagą, w przeciwnym wypadku False"""
return self._state == Field.FLAGGED_STATE
def isMaybeMine(self):
"""Metoda zwracająca True jeżeli pole zostało oznaczone znakiem zapytania, w przeciwnym wypadku False"""
return self._state == Field.MAYBE_STATE
def onRightClick(self):
"""Metoda dokonująca akcji po kliknięciu prawym przyciskiem na pole"""
if self.isOpened():
return
elif self._state == Field.CLOSED_STATE:
self._state = Field.FLAGGED_STATE
elif self._state == Field.FLAGGED_STATE:
self._state = Field.MAYBE_STATE
else:
self._state = Field.CLOSED_STATE
def open(self):
"""Metoda ustawiająca pole w stan otwarty"""
self._state = Field.OPENED_STATE | 37.914286 | 125 | 0.602864 | 304 | 2,654 | 5.065789 | 0.259868 | 0.087662 | 0.136364 | 0.093506 | 0.621429 | 0.498052 | 0.40974 | 0.40974 | 0.377273 | 0.305844 | 0 | 0.002759 | 0.317257 | 2,654 | 70 | 126 | 37.914286 | 0.84713 | 0.30633 | 0 | 0.047619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.309524 | false | 0 | 0 | 0.02381 | 0.642857 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
95af6eb78c72f53f7fd8a2175c19fc18314ec25a | 235 | py | Python | setup.py | fcooper8472/UnitTestingCourse | e824f3805589d221ca8e7173b5dd290c516fad9c | [
"CC-BY-4.0",
"MIT"
] | null | null | null | setup.py | fcooper8472/UnitTestingCourse | e824f3805589d221ca8e7173b5dd290c516fad9c | [
"CC-BY-4.0",
"MIT"
] | null | null | null | setup.py | fcooper8472/UnitTestingCourse | e824f3805589d221ca8e7173b5dd290c516fad9c | [
"CC-BY-4.0",
"MIT"
] | null | null | null | from setuptools import setup, find_packages
setup(
name="patient-analysis",
version='1.0',
packages=find_packages(),
install_requires=[
'matplotlib',
'numpy',
'pytest',
'yapf',
],
)
| 16.785714 | 43 | 0.565957 | 22 | 235 | 5.909091 | 0.818182 | 0.184615 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012048 | 0.293617 | 235 | 13 | 44 | 18.076923 | 0.771084 | 0 | 0 | 0 | 0 | 0 | 0.187234 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.083333 | 0 | 0.083333 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
95b232eed99f00e999da851028e5bc73c562a8c8 | 2,673 | py | Python | apps/core/migrations/0001_initial.py | ylgnerbecton/ruby-dev-test-1 | 2f1deb21aa008b0ffeec31505460080cf89ecf2c | [
"MIT"
] | null | null | null | apps/core/migrations/0001_initial.py | ylgnerbecton/ruby-dev-test-1 | 2f1deb21aa008b0ffeec31505460080cf89ecf2c | [
"MIT"
] | null | null | null | apps/core/migrations/0001_initial.py | ylgnerbecton/ruby-dev-test-1 | 2f1deb21aa008b0ffeec31505460080cf89ecf2c | [
"MIT"
] | null | null | null | # Generated by Django 2.2.10 on 2021-01-04 18:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Directories',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_removed', models.BooleanField(default=False)),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('path', models.CharField(blank=True, max_length=254, null=True, verbose_name='Caminho')),
],
options={
'verbose_name_plural': 'Diretórios',
},
),
migrations.CreateModel(
name='SubPath',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_removed', models.BooleanField(default=False)),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('sub_path', models.CharField(blank=True, max_length=254, null=True, verbose_name='Caminho')),
],
options={
'verbose_name_plural': 'Sub Diretórios',
},
),
migrations.CreateModel(
name='Files',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_removed', models.BooleanField(default=False)),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('name', models.CharField(blank=True, max_length=254, null=True, verbose_name='Nome')),
('upload', models.FileField(blank=True, max_length=254, null=True, upload_to='', verbose_name='Arquivo')),
('directory', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='core.Directories', verbose_name='Diretório')),
],
options={
'verbose_name_plural': 'Arquivos',
},
),
migrations.AddField(
model_name='directories',
name='sub_path',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='core.SubPath', verbose_name='Sub Diretório'),
),
]
| 43.112903 | 169 | 0.580247 | 267 | 2,673 | 5.640449 | 0.277154 | 0.087649 | 0.091633 | 0.103586 | 0.669323 | 0.669323 | 0.669323 | 0.650066 | 0.650066 | 0.650066 | 0 | 0.014576 | 0.281332 | 2,673 | 61 | 170 | 43.819672 | 0.769391 | 0.017209 | 0 | 0.518519 | 1 | 0 | 0.123429 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.037037 | 0 | 0.111111 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
95cc37bd120f5786588efd8774bdeb12beef0088 | 3,067 | py | Python | backend/surveyapi/models.py | sunwenquan/iSurvey | bc14a102e56b33fb4b3612b3bef98183f6e46612 | [
"Apache-2.0"
] | null | null | null | backend/surveyapi/models.py | sunwenquan/iSurvey | bc14a102e56b33fb4b3612b3bef98183f6e46612 | [
"Apache-2.0"
] | null | null | null | backend/surveyapi/models.py | sunwenquan/iSurvey | bc14a102e56b33fb4b3612b3bef98183f6e46612 | [
"Apache-2.0"
] | null | null | null | """
models.py
定义数据库模型
- db.DateTime :在数据库模型中,有DateTime字段,该字段的值是Python 的datetime 类型。需要注意的是,我们在设置datetime时,
要做好时区的选择。
关于时间和日期的操作,请参考 iSurvey/test/time_oper.py
"""
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
surveys = db.relationship('Survey', backref="creator", lazy=False)
def __init__(self, email, password):
self.email = email
self.password = generate_password_hash(password, method='sha256')
@classmethod
def authenticate(cls, **kwargs):
email = kwargs.get('email')
password = kwargs.get('password')
if not email or not password:
return None
user = cls.query.filter_by(email=email).first()
if not user or not check_password_hash(user.password, password):
return None
return user
def to_dict(self):
return dict(id=self.id, email=self.email)
class Survey(db.Model):
__tablename__ = 'surveys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
questions = db.relationship('Question', backref="survey", lazy=False)
creator_id = db.Column(
db.Integer, db.ForeignKey('users.id'), nullable=True)
def to_dict(self):
return dict(id=self.id,
name=self.name,
created_at=self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
questions=[question.to_dict() for question in self.questions])
class Question(db.Model):
__tablename__ = 'questions'
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(500), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
survey_id = db.Column(db.Integer, db.ForeignKey('surveys.id'))
choices = db.relationship('Choice', backref='question', lazy=False)
def to_dict(self):
return dict(id=self.id,
text=self.text,
created_at=self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
survey_id=self.survey_id,
choices=[choice.to_dict() for choice in self.choices])
class Choice(db.Model):
__tablename__ = 'choices'
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(100), nullable=False)
# 选项被选择的个数
selected = db.Column(db.Integer, default=0)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
question_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
def to_dict(self):
return dict(id=self.id,
text=self.text,
created_at=self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
question_id=self.question_id)
| 31.618557 | 83 | 0.646234 | 399 | 3,067 | 4.824561 | 0.245614 | 0.066494 | 0.083117 | 0.070649 | 0.345455 | 0.345455 | 0.345455 | 0.297143 | 0.262857 | 0.155844 | 0 | 0.006731 | 0.224976 | 3,067 | 96 | 84 | 31.947917 | 0.803113 | 0.053146 | 0 | 0.333333 | 0 | 0 | 0.058377 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.095238 | false | 0.111111 | 0.047619 | 0.063492 | 0.68254 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
95ce422dad0a32db39d5b8f9f3afaf5fa35f6fc0 | 152 | py | Python | yc297/1517.py | c-yan/yukicoder | cdbbd65402177225dd989df7fe01f67908484a69 | [
"MIT"
] | null | null | null | yc297/1517.py | c-yan/yukicoder | cdbbd65402177225dd989df7fe01f67908484a69 | [
"MIT"
] | null | null | null | yc297/1517.py | c-yan/yukicoder | cdbbd65402177225dd989df7fe01f67908484a69 | [
"MIT"
] | null | null | null | d = int(input())
a, b = map(int, input().split())
result = 10 ** 15
for i in range(d + 1):
result = min(result, i * a + (d - i) * b)
print(result)
| 19 | 45 | 0.532895 | 28 | 152 | 2.892857 | 0.607143 | 0.197531 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.043478 | 0.243421 | 152 | 7 | 46 | 21.714286 | 0.66087 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.166667 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
95d6c56ba4d533ddd590a5912805df65f7a67ad0 | 706 | py | Python | edgetest/report.py | capitalone/edgetest | 181fbef6e22c77e8e3d22758d2d9392874aadc45 | [
"Apache-2.0"
] | 16 | 2021-12-02T21:13:59.000Z | 2022-03-29T14:04:24.000Z | edgetest/report.py | capitalone/edgetest | 181fbef6e22c77e8e3d22758d2d9392874aadc45 | [
"Apache-2.0"
] | 15 | 2021-11-29T17:58:03.000Z | 2022-03-25T21:51:16.000Z | edgetest/report.py | capitalone/edgetest | 181fbef6e22c77e8e3d22758d2d9392874aadc45 | [
"Apache-2.0"
] | 4 | 2021-12-10T18:30:15.000Z | 2022-03-25T01:47:15.000Z | """Generate rST reports."""
from typing import Any, List
from tabulate import tabulate
from .core import TestPackage
def gen_report(testers: List[TestPackage]) -> Any:
"""Generate a rST report.
Parameters
----------
testers : list
A list of ``TestPackage`` objects.
Returns
-------
Any
The report.
"""
headers = ["Environment", "Passing tests", "Upgraded packages", "Package version"]
rows: List[List] = []
for env in testers:
upgraded = env.upgraded_packages()
for pkg in upgraded:
rows.append([env.envname, env.status, pkg["name"], pkg["version"]])
return tabulate(rows, headers=headers, tablefmt="rst")
| 22.774194 | 86 | 0.613314 | 79 | 706 | 5.455696 | 0.506329 | 0.051044 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.245042 | 706 | 30 | 87 | 23.533333 | 0.80863 | 0.223796 | 0 | 0 | 1 | 0 | 0.14 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0.090909 | 0.272727 | 0 | 0.454545 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
95ee29a03d39fd0101b5c1db751982a9e874fb04 | 240 | py | Python | kaggle_petfinder/utils.py | greatestgoat/kaggle_petfinder | 54ac4e43a3442cfec5a45a0eaced2e09738b08c0 | [
"MIT"
] | 3 | 2020-12-05T15:40:37.000Z | 2021-03-14T01:48:07.000Z | kaggle_petfinder/utils.py | greatestgoat/kaggle_petfinder | 54ac4e43a3442cfec5a45a0eaced2e09738b08c0 | [
"MIT"
] | null | null | null | kaggle_petfinder/utils.py | greatestgoat/kaggle_petfinder | 54ac4e43a3442cfec5a45a0eaced2e09738b08c0 | [
"MIT"
] | 1 | 2021-01-19T22:48:06.000Z | 2021-01-19T22:48:06.000Z | import os
def is_script_running():
script_only_env_keys = {'KAGGLE_DOCKER_IMAGE', 'KAGGLE_CONTAINER_NAME'}
current_os_env = set(os.environ.keys())
is_script = script_only_env_keys.issubset(current_os_env)
return is_script
| 26.666667 | 75 | 0.766667 | 36 | 240 | 4.611111 | 0.527778 | 0.144578 | 0.156627 | 0.204819 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.141667 | 240 | 8 | 76 | 30 | 0.805825 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 0.0875 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.166667 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
95f4a629cb26e2256b125c4e7cf4b276313d766a | 1,082 | py | Python | ovs/dal/hybrids/j_rolebearertoken.py | mflu/openvstorage_centos | 280a98d3e5d212d58297e0ffcecd325dfecef0f8 | [
"Apache-2.0"
] | 1 | 2015-08-29T16:36:40.000Z | 2015-08-29T16:36:40.000Z | ovs/dal/hybrids/j_rolebearertoken.py | rootfs-analytics/openvstorage | 6184822340faea1d2927643330a7aaa781d92d36 | [
"Apache-2.0"
] | null | null | null | ovs/dal/hybrids/j_rolebearertoken.py | rootfs-analytics/openvstorage | 6184822340faea1d2927643330a7aaa781d92d36 | [
"Apache-2.0"
] | null | null | null | # Copyright 2014 CloudFounders NV
#
# 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.
"""
RoleBearerToken module
"""
from ovs.dal.dataobject import DataObject
from ovs.dal.structures import Relation
from ovs.dal.hybrids.role import Role
from ovs.dal.hybrids.bearertoken import BearerToken
class RoleBearerToken(DataObject):
"""
The RoleBearerToken class represents the junction table between Role and BearerToken.
"""
__properties = []
__relations = [Relation('role', Role, 'tokens'),
Relation('token', BearerToken, 'roles')]
__dynamics = []
| 33.8125 | 89 | 0.738447 | 143 | 1,082 | 5.545455 | 0.601399 | 0.075662 | 0.050441 | 0.040353 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009009 | 0.179298 | 1,082 | 31 | 90 | 34.903226 | 0.884009 | 0.612754 | 0 | 0 | 0 | 0 | 0.052083 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.444444 | 0 | 0.888889 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
250507ce271957dbf8fa3e4eb9c1b1228786e894 | 520 | py | Python | tests/test_core/test_part.py | MattTaylorDLS/pymalcolm | 995a8e4729bd745f8f617969111cc5a34ce1ac14 | [
"Apache-2.0"
] | null | null | null | tests/test_core/test_part.py | MattTaylorDLS/pymalcolm | 995a8e4729bd745f8f617969111cc5a34ce1ac14 | [
"Apache-2.0"
] | null | null | null | tests/test_core/test_part.py | MattTaylorDLS/pymalcolm | 995a8e4729bd745f8f617969111cc5a34ce1ac14 | [
"Apache-2.0"
] | null | null | null | import unittest
from malcolm.core import Part, method_takes, Hook
Reset = Hook()
class MyPart(Part):
@method_takes()
@Reset
def foo(self):
pass
@method_takes()
def bar(self):
pass
class TestPart(unittest.TestCase):
def test_init(self):
p = Part("name")
assert p.name == "name"
def test_non_hooked_methods(self):
p = MyPart("")
methods = list(p.create_method_models())
assert methods == [("bar", p.method_models["bar"], p.bar)]
| 17.931034 | 66 | 0.598077 | 66 | 520 | 4.560606 | 0.454545 | 0.109635 | 0.099668 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | 520 | 28 | 67 | 18.571429 | 0.792105 | 0 | 0 | 0.210526 | 0 | 0 | 0.026923 | 0 | 0 | 0 | 0 | 0 | 0.105263 | 1 | 0.210526 | false | 0.105263 | 0.105263 | 0 | 0.421053 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
250623a83494b78656981cb8aaf15988d7509614 | 746 | py | Python | tools/builder/utils.py | ownport/docker-images | 1b4c26a0cae761431cd7016863bae42c5c7529ba | [
"MIT"
] | null | null | null | tools/builder/utils.py | ownport/docker-images | 1b4c26a0cae761431cd7016863bae42c5c7529ba | [
"MIT"
] | 9 | 2020-09-02T08:12:36.000Z | 2021-01-12T04:58:03.000Z | tools/builder/utils.py | ownport/docker-images | 1b4c26a0cae761431cd7016863bae42c5c7529ba | [
"MIT"
] | null | null | null |
from builder.git import RE_MASTER_BRANCH
from builder.git import RE_DEVEL_BRANCH
from builder.git import RE_BUGFIX_BRANCH
from builder.git import RE_FEATURE_BRANCH
from builder.git import RE_EXTRACT_BRANCH_AND_NUM
def get_tag_suffix(branch:str, tag:str) -> str:
''' return a tag suffix based on branch and tag name
'''
tag_suffix = '-'
if RE_DEVEL_BRANCH.match(branch):
tag_suffix += 'devel'
elif RE_MASTER_BRANCH.match(branch):
tag_suffix += 'pre-release'
elif RE_FEATURE_BRANCH.match(branch) or RE_BUGFIX_BRANCH.match(branch):
tag_suffix += '-'.join(RE_EXTRACT_BRANCH_AND_NUM.search(branch).groups())
elif tag and tag.startswith('release/'):
tag_suffix = ''
return tag_suffix
| 32.434783 | 81 | 0.725201 | 111 | 746 | 4.585586 | 0.297297 | 0.141454 | 0.137525 | 0.196464 | 0.495088 | 0.220039 | 0 | 0 | 0 | 0 | 0 | 0 | 0.179625 | 746 | 22 | 82 | 33.909091 | 0.831699 | 0.064343 | 0 | 0 | 0 | 0 | 0.037956 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.0625 | false | 0 | 0.3125 | 0 | 0.4375 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
2524b40112bc8fba27b476338728256215c3edef | 2,464 | py | Python | 13.py | drawwon/JianzhiOffer | 0a6df634dc27b3769e60d11d582ee4bf40825f1d | [
"Apache-2.0"
] | null | null | null | 13.py | drawwon/JianzhiOffer | 0a6df634dc27b3769e60d11d582ee4bf40825f1d | [
"Apache-2.0"
] | null | null | null | 13.py | drawwon/JianzhiOffer | 0a6df634dc27b3769e60d11d582ee4bf40825f1d | [
"Apache-2.0"
] | null | null | null | # # -*- coding:utf-8 -*-
# class Solution:
# def movingCount(self, threshold, rows, cols):
# # write code here
# count = 0
# if rows <= 0 or cols <= 0:
# return 0
# if threshold == 0:
# return rows * cols
# visited = [[False for i in range(cols)] for j in range(rows)]
# count = self.movingCountCore(rows, cols, threshold, 0, 0,visited)
# return count
#
# def movingCountCore(self, rows, cols, threshold, row, col, visited):
# count = 0
# if 0 <= row < rows and 0<= col < cols and not visited[row][col] and self.checkSum(row, col, threshold):
# visited[row][col] = True
# count = 1 + self.movingCountCore(rows, cols, threshold, row + 1, col, visited) + \
# self.movingCountCore(rows, cols, threshold, row - 1, col, visited) + \
# self.movingCountCore(rows, cols, threshold, row, col + 1, visited) + \
# self.movingCountCore(rows, cols, threshold, row, col - 1, visited)
# return count
#
# def checkSum(self, row, col, threshold):
# sumv = 0
# for i in str(row):
# sumv += int(i)
# for j in str(col):
# sumv += int(j)
# if sumv <= threshold:
# return True
# else:
# return False
#
# s = Solution()
# print(s.movingCount(10,1,100))
# -*- coding:utf-8 -*-
# class Solution:
# def movingCount(self, threshold, rows, cols):
# # write code here
# count = 0
# if rows <= 0 or cols <= 0:
# return 0
# if threshold == 0:
# return rows * cols
# count = 0
# if rows!=1 and cols!=1:
# for i in range(rows):
# for j in range(cols):
# if self.checkSum(i,j,threshold):
# count += 1
# if rows==1 or cols == 1:
# for i in range(rows):
# for j in range(cols):
# if self.checkSum(i,j,threshold):
# count += 1
# else:
# break
# return count
# def checkSum(self,row,col,threshold):
# val = 0
# for i in str(row):
# val+=int(i)
# for j in str(col):
# val += int(j)
# if val <= threshold:
# return True
# else:
# return False
| 34.704225 | 113 | 0.465909 | 283 | 2,464 | 4.056537 | 0.155477 | 0.069686 | 0.08885 | 0.117596 | 0.737805 | 0.686411 | 0.60453 | 0.576655 | 0.505226 | 0.505226 | 0 | 0.025291 | 0.40625 | 2,464 | 70 | 114 | 35.2 | 0.759399 | 0.941558 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
252a6ef1c6233cdfa6759d2e48dbb73b6b7d90dd | 233 | py | Python | tests/inputs/numpy-lib/54-some-numpy-ufuncs.py | helq/pytropos | 497ed5902e6e4912249ca0a46b477f9bfa6ae80a | [
"MIT"
] | 4 | 2019-10-06T18:01:24.000Z | 2020-07-03T05:27:35.000Z | tests/inputs/numpy-lib/54-some-numpy-ufuncs.py | helq/pytropos | 497ed5902e6e4912249ca0a46b477f9bfa6ae80a | [
"MIT"
] | 5 | 2021-06-07T15:50:04.000Z | 2021-06-07T15:50:06.000Z | tests/inputs/numpy-lib/54-some-numpy-ufuncs.py | helq/pytropos | 497ed5902e6e4912249ca0a46b477f9bfa6ae80a | [
"MIT"
] | null | null | null | import numpy as np
lst = [[1, 3, 4], [2, 8, 9]]
a = np.size(lst)
a_ = np.array(lst).size
b = np.shape(lst)
b_ = np.array(lst).shape
c = np.ndim(lst)
c_ = np.array(lst).ndim
d = np.dtype(lst)
d_ = np.array(lst).dtype
# show_store()
| 16.642857 | 28 | 0.609442 | 49 | 233 | 2.795918 | 0.44898 | 0.20438 | 0.291971 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031088 | 0.171674 | 233 | 13 | 29 | 17.923077 | 0.678756 | 0.051502 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.1 | 0 | 0.1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
254eb19c2e5045fa6dcddf0f963e789fd6fd2c79 | 2,393 | py | Python | admin/common_auth/models.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | null | null | null | admin/common_auth/models.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | null | null | null | admin/common_auth/models.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | null | null | null | from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
BaseUserManager,
)
from django.db import models
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email, password=password, )
user.is_superuser = True
user.is_admin = True
user.is_staff = True
user.is_active = True
user.save(using=self._db)
return user
def prereg_users(self):
return self.filter(groups__name='prereg_group')
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=30, blank=False)
last_name = models.CharField(max_length=30, blank=False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
confirmed = models.BooleanField(default=False)
osf_id = models.CharField(max_length=5, blank=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
return ('{0} {1}'.format(self.first_name, self.last_name)).strip() or self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __unicode__(self):
return self.email
class Meta:
ordering = ['email']
@property
def osf_user(self):
# import on call to avoid interference w/ django's manage.py commands like collectstatic
from website.models import User as OsfUserModel
if not self.osf_id:
raise RuntimeError('This user does not have an associated Osf User')
return OsfUserModel.load(self.osf_id)
def is_in_group(self, group):
return self.groups.filter(name=group).exists()
def group_names(self):
return self.groups.all().values_list('name', flat=True)
| 29.182927 | 96 | 0.669035 | 299 | 2,393 | 5.197324 | 0.38796 | 0.028958 | 0.06435 | 0.046332 | 0.092664 | 0.092664 | 0.092664 | 0.092664 | 0 | 0 | 0 | 0.005482 | 0.237777 | 2,393 | 81 | 97 | 29.54321 | 0.846491 | 0.055161 | 0 | 0.1 | 0 | 0 | 0.054916 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.15 | false | 0.066667 | 0.05 | 0.1 | 0.583333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
255278f462edf842a8ed2e816ef7e31cdce46b60 | 1,139 | py | Python | test.py | slang-legacy/evenLESS | 83196041c87557c3c59c53b656d69004479b2144 | [
"WTFPL"
] | null | null | null | test.py | slang-legacy/evenLESS | 83196041c87557c3c59c53b656d69004479b2144 | [
"WTFPL"
] | null | null | null | test.py | slang-legacy/evenLESS | 83196041c87557c3c59c53b656d69004479b2144 | [
"WTFPL"
] | null | null | null | #this file can be removed if you don't need to test the evenLESS compiler (nothing relies on it)
import evenless
less = """
@import "lib.css";
.border-radius (@radius: 5px) //a parametric mixin
border-radius: @radius
-moz-border-radius: @radius
color: @radius
//a comment on its own line
//an indented comment
#header
.border-radius(4px)
#header // nested!
.border-radius(4px)
strayrule: #000;
/*a multi-
line
comment*/
.button
.border-radius
.realcss#really {// real CSS/LESS!
arealrule: #000;
arealrule: #000;
#really_indented rule {
arealrule: #000;
.border-radius(4px); //real LESS!!!
arealrule: #000 //didn't really need that ";" anyway
}
a-real-stray-rule: #000;
}
div span, p span, nav span{
font-size: 18px;
}
//back to evenLESS
#header
.border-radius(4px)
#header // nested!
.border-radius(4px)
header // really nested !@#$%^&*()!!!111!!!
.border-radius(4px)
#header // nested!
.border-radius(4px)
#header // a little less nested
.border-radius(4px)
"""
try:
print evenless.compile(less)
except evenless.CalledProcessError as error:
print error.output
print error
| 15.60274 | 96 | 0.67252 | 156 | 1,139 | 4.903846 | 0.455128 | 0.188235 | 0.156863 | 0.137255 | 0.196078 | 0.196078 | 0.196078 | 0.196078 | 0.196078 | 0 | 0 | 0.034115 | 0.176471 | 1,139 | 72 | 97 | 15.819444 | 0.78145 | 0.083407 | 0 | 0.306122 | 0 | 0 | 0.85975 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.040816 | null | null | 0.061224 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
256b949264751bf5733d68066f1badb8e074efc1 | 3,103 | py | Python | Ryven/custom_src/code_gen/CodeGenDialog.py | lidong1266/Ryven-Switch | 68d1f71e81d6564196f44ca49d5903f06db6a4d9 | [
"MIT"
] | 18 | 2021-01-18T09:52:41.000Z | 2022-03-22T10:48:44.000Z | Ryven/custom_src/code_gen/CodeGenDialog.py | xamofb-xsk/Ryven | 8c3dcc613098863ae9fb747e62c0bb9d9eb4cef1 | [
"MIT"
] | null | null | null | Ryven/custom_src/code_gen/CodeGenDialog.py | xamofb-xsk/Ryven | 8c3dcc613098863ae9fb747e62c0bb9d9eb4cef1 | [
"MIT"
] | 3 | 2021-01-18T09:49:42.000Z | 2022-03-22T10:48:47.000Z | from PySide2.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QPlainTextEdit, QShortcut, QMessageBox, QGroupBox, \
QScrollArea, QCheckBox, QLabel
class CodeGenDialog(QDialog):
def __init__(self, modules: dict, parent=None):
super(CodeGenDialog, self).__init__(parent)
self.modules = modules
main_layout = QVBoxLayout()
imports_group_box = QGroupBox('Imports')
imports_group_box.setLayout(QVBoxLayout())
info_text_edit = QPlainTextEdit('''I found the following imports in the inspected components. Please unselect all imports whose source code you want me to include in the output. All checked modules remain imported using the import statements. Notice that import alias names (import ... as ...) of course won\'t work when including the module\'s source. Same goes for imports using 'from' (indicated in the list below). And for those, the whole (direct) source will be included if you unselect a module.''')
info_text_edit.setReadOnly(True)
imports_group_box.layout().addWidget(info_text_edit)
imports_scroll_area = QScrollArea()
imports_scroll_area.setLayout(QVBoxLayout())
self.import_widget_assignment = {'imports': {}, 'fromimports': {}}
# imports
imports_scroll_area.layout().addWidget(QLabel('imports:'))
for i in modules['imports'].keys():
import_check_box = QCheckBox(i)
import_check_box.setChecked(True)
imports_scroll_area.layout().addWidget(import_check_box)
self.import_widget_assignment['imports'][import_check_box] = i
# from-imports
imports_scroll_area.layout().addWidget(QLabel('\'from\'-imports:'))
for i in modules['fromimports'].keys():
names = modules['fromimports'][i][2]
from_names_list = ', '.join(names)
import_check_box = QCheckBox(i + ': ' + from_names_list)
import_check_box.setChecked(True)
imports_scroll_area.layout().addWidget(import_check_box)
self.import_widget_assignment['fromimports'][import_check_box] = i
imports_group_box.layout().addWidget(imports_scroll_area)
main_layout.addWidget(imports_group_box)
button_box = QDialogButtonBox()
button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
main_layout.addWidget(button_box)
self.setLayout(main_layout)
self.resize(500, 500)
self.setWindowTitle('Source Code Gen Manager')
def get_import_selection(self) -> dict:
imports = self.modules['imports']
ia = self.import_widget_assignment['imports']
for k in ia.keys():
imports[ia[k]][1] = k.isChecked()
fromimports = self.modules['fromimports']
fia = self.import_widget_assignment['fromimports']
for k in fia.keys():
fromimports[fia[k]][1] = k.isChecked()
return {'imports': imports, 'fromimports': fromimports} | 44.328571 | 514 | 0.681276 | 359 | 3,103 | 5.668524 | 0.337047 | 0.058968 | 0.055037 | 0.063882 | 0.274693 | 0.142506 | 0.142506 | 0.09828 | 0.09828 | 0.09828 | 0 | 0.004102 | 0.214309 | 3,103 | 70 | 515 | 44.328571 | 0.830599 | 0.006445 | 0 | 0.081633 | 0 | 0.020408 | 0.207076 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.040816 | false | 0 | 0.632653 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
25714ed48d4fa13f4b7b4eb563597c8afc2d48b6 | 9,018 | py | Python | mysite/pages/models.py | cjlee112/socraticqs2 | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | [
"Apache-2.0"
] | 8 | 2015-06-02T15:34:44.000Z | 2019-03-21T12:27:30.000Z | mysite/pages/models.py | cjlee112/socraticqs2 | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | [
"Apache-2.0"
] | 761 | 2015-01-07T05:13:08.000Z | 2022-02-10T10:23:37.000Z | mysite/pages/models.py | cjlee112/socraticqs2 | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | [
"Apache-2.0"
] | 12 | 2015-01-28T20:09:36.000Z | 2018-03-20T13:32:11.000Z | from django.db import models
from djangocms_text_ckeditor import fields
from cms.models.pluginmodel import CMSPlugin
from filer.fields.image import FilerImageField
COLOR_CHOICES = (
("bg-primary", "blue"),
("bg-danger", "red"),
("bg-success", "green"),
("bg-info", "light-blue"),
("bg-warning", "yellow"),
)
LIST_TYPES = (
('list-questions', 'list-questions'),
('list_numeric', 'list_numeric'),
('list-checklist', 'list-checklist'),
('list-header', 'list-header')
)
SLIDE_SHARE_BACK = (
('gray', 'section-2-cols-bg'),
('none', ''),
)
class AbstractPlugin(CMSPlugin):
"""
Abstract Base Class for all Plugins.
"""
hidden = models.BooleanField(default=False)
class Meta:
abstract = True
class LandingPlugin(AbstractPlugin):
"""
Plugin provide widget main page
"""
title = models.CharField(max_length=200, null=True, blank=True)
description = fields.HTMLField(null=True, blank=True)
list_description = fields.HTMLField(null=True, blank=True)
link_button = models.URLField(null=True, blank=True)
text_button = models.CharField(null=True, max_length=70, blank=True)
block_color = models.CharField(max_length=20, choices=COLOR_CHOICES, default='bg-primary')
class BannerPlugin(AbstractPlugin):
"""
Plugin make banner with description and button to go
"""
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField(blank=True)
link_button = models.URLField(blank=True)
text_button = models.CharField(max_length=70, blank=True)
sponsors_text = models.CharField(max_length=200, blank=True)
class ActiveLearningRatesPlugin(AbstractPlugin):
"""
Plugin provide ability to edit Active learting block.
"""
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField(blank=True)
fig_alt = models.CharField(max_length=200, blank=True)
fig_caption = models.CharField(max_length=200, blank=True)
list_text = fields.HTMLField()
class ListPlugin(AbstractPlugin):
"""
General plugin for adding list
of tesises with the title and <li> element class.
"""
title = models.CharField(max_length=200, blank=True)
list_type = models.CharField(max_length=20, choices=LIST_TYPES, default='list-questions')
list_text = fields.HTMLField()
class ChildPersonalGuidesPlugin(AbstractPlugin):
"""
Plugin for personal guides block.
"""
image = FilerImageField(related_name="personal_guides_image", on_delete=models.CASCADE)
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField()
class SocialProofsPlugin(AbstractPlugin):
"""
Plugin for Social Proofs block.
"""
title = models.CharField(max_length=200, blank=True)
post_description = fields.HTMLField()
more_proofs_link = models.URLField(null=True, blank=True)
class ProofPlugin(AbstractPlugin):
"""
Plugin for proof.
"""
proof_icon = FilerImageField(related_name="proof_icon", blank=True, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField()
class KeyNotesSetPlugin(AbstractPlugin):
"""
Plugin for KeyNotes block.
"""
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField()
class KeyNotePlugin(AbstractPlugin):
"""
Plugin for KeyNote.
"""
button_text = models.CharField(max_length=200, blank=True)
uid = models.SlugField(max_length=8, blank=False)
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField()
class ParentPersonalGuidesPlugin(AbstractPlugin):
"""
Parent plugin for Personal Guides.
"""
title = models.CharField(max_length=200, blank=True)
class WorkshopDescriptionPlugin(AbstractPlugin):
"""
Parent plugin Workshop description.
"""
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField(blank=True)
class BenefitsItemPlugin(AbstractPlugin):
"""
Item of benefils
"""
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField(blank=True)
image = FilerImageField(null=True, blank=True, on_delete=models.CASCADE)
class BenefitsPlugin(AbstractPlugin):
"""
Base plugin for benefits
"""
title = models.CharField(max_length=200, blank=True)
description = fields.HTMLField(blank=True)
class FooterPlugin(AbstractPlugin):
"""
Plugin for the footer part of landing page.
"""
footer_text = models.CharField(max_length=100, blank=True)
footer_link = models.CharField(max_length=200, blank=True)
class SocialPlugin(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
class FAQPlugin(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
class FAQItemPlugin(AbstractPlugin):
question = models.TextField(blank=True)
answer = models.TextField(blank=True)
class MiscItemPlugin(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
description_header = fields.HTMLField(blank=True)
list_type = models.CharField(max_length=20, choices=LIST_TYPES, default='list-checklist')
list_text = fields.HTMLField()
description_footer = fields.HTMLField(blank=True)
header_type_text = models.CharField(max_length=200, blank=True)
class InterestedPlugin(AbstractPlugin):
title = models.CharField(max_length=200, default="I’m Interested in the hackathon")
description = models.TextField(
default="Get on our mailing list and we’ll contact you about the next hackathon.")
name_field = models.CharField(max_length=200, default="Name")
email_field = models.CharField(max_length=200, default="Email")
organization_field = models.CharField(max_length=200, default="Institution/Organization")
role_field = models.CharField(max_length=200, default=" Title/Role")
name_error_msg = models.CharField(max_length=200, default="Please enter your name")
organization_error_msg = models.CharField(max_length=200, default="Please enter your Institute/Organization")
email_error_msg = models.CharField(max_length=200, default="Please enter your email")
role_error_msg = models.CharField(max_length=200, default="Please enter your Title/Role")
email_to = models.EmailField(default='dummy@mail.com')
btn_text = models.CharField(max_length=70, default='Schedule to demo')
bg_image = FilerImageField(null=True, blank=True, on_delete=models.CASCADE)
class InterestedForm(models.Model):
"""
Model for save interested form answer and do some later
"""
name = models.CharField(max_length=200, blank=True)
organization = models.CharField(max_length=200, blank=True)
role = models.CharField(max_length=100, blank=True)
email = models.EmailField(blank=True)
class DetailsChildPlugin(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
class DetailsVideoPlugin(AbstractPlugin):
video_url = models.URLField()
description = models.CharField(max_length=200, blank=True)
class DetailsQuotePlugin(AbstractPlugin):
quote_text = models.CharField(max_length=200)
quote_small = models.CharField(max_length=200)
class SlideSharePlugin(AbstractPlugin):
title = models.CharField(max_length=200)
description = fields.HTMLField()
background = models.CharField(default='grey', max_length=70, choices=SLIDE_SHARE_BACK)
class SlideShareItemPlugin(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
slideshare_code = models.TextField()
class BecomeInstructorPlugin(AbstractPlugin):
error_name = models.CharField(max_length=200, blank=True)
agreement_text = models.TextField(blank=True)
class HelpCenterModel(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
description = models.TextField(blank=True)
link_text = models.CharField(max_length=200)
link_url = models.URLField()
class IntercomArticleModel(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
short_description = models.TextField(blank=True)
link_text = models.CharField(max_length=200)
link_url = models.URLField()
class Hero1Model(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
description = models.TextField(blank=True)
best_prattices_text = models.CharField(max_length=200)
best_prattices_link = models.URLField()
bp1_text = models.CharField(max_length=200)
bp1_link = models.URLField()
video_url = models.URLField()
class Hero2Model(AbstractPlugin):
title = models.CharField(max_length=200, blank=True)
description = models.TextField(blank=True)
best_prattices_text = models.CharField(max_length=200)
best_prattices_link = models.URLField()
bp2_text = models.CharField(max_length=200)
bp2_link = models.URLField()
video_url = models.URLField()
| 31.978723 | 113 | 0.729763 | 1,072 | 9,018 | 6.001866 | 0.194963 | 0.083929 | 0.159465 | 0.21262 | 0.577401 | 0.542586 | 0.49285 | 0.406124 | 0.363537 | 0.318154 | 0 | 0.023424 | 0.157352 | 9,018 | 281 | 114 | 32.092527 | 0.823266 | 0.066534 | 0 | 0.298137 | 0 | 0 | 0.068885 | 0.008198 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.024845 | 0 | 0.881988 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
c2502b219f05743f3cce4ca844820a1312dd7686 | 4,653 | py | Python | unit/nvim_io_spec.py | tek/ribosome-py | 8bd22e549ddff1ee893d6e3a0bfba123a09e96c6 | [
"MIT"
] | null | null | null | unit/nvim_io_spec.py | tek/ribosome-py | 8bd22e549ddff1ee893d6e3a0bfba123a09e96c6 | [
"MIT"
] | null | null | null | unit/nvim_io_spec.py | tek/ribosome-py | 8bd22e549ddff1ee893d6e3a0bfba123a09e96c6 | [
"MIT"
] | null | null | null | from typing import Tuple, Any
from kallikrein import k, Expectation, pending
from kallikrein.matchers.either import be_right
from amino import do, List, Right, Nil, Either
from amino.do import Do
from amino.test.spec import SpecBase
from ribosome.nvim.api.data import NvimApi, StrictNvimApi
from ribosome.nvim.io.compute import NvimIO
from ribosome.test.klk.expectable import kn
from ribosome.nvim.io.api import N
from ribosome.nvim.io.data import NError
from ribosome.test.klk.matchers.nresult import nsuccess
vars = dict(a=1)
def handler(vim: StrictNvimApi, method: str, args: List[str], sync: bool) -> Either[List[str], Tuple[NvimApi, Any]]:
return Right((vim.copy(vars=vars), (args.head | 9) + 2))
vim = StrictNvimApi.cons('test', request_handler=handler)
class NvimIoSpec(SpecBase):
'''
suspend $suspend
delay $delay
suspend flat_map $suspend_flat_map
stack safety $stack
stack safety with fatal recover $stack_recover_fatal
stack safety with error recover $stack_recover_error
request $request
bind on request $request_bind
preserve resource state in `recover` $recover
recover an exception with `recover_failure` $recover_failure
execute an effect after error $ensure_failure
'''
def suspend(self) -> Expectation:
def f(v: NvimApi) -> NvimIO[int]:
return N.pure(7)
return k(N.suspend(f).either(vim)).must(be_right(7))
def delay(self) -> Expectation:
def f(v: NvimApi) -> int:
return 7
return k(N.delay(f).either(vim)).must(be_right(7))
def suspend_flat_map(self) -> Expectation:
def h(a: int) -> NvimIO[int]:
return N.pure(a + 2)
def g(a: int) -> NvimIO[int]:
return N.suspend(lambda v, b: h(b), a + 1)
def f(v: NvimApi) -> NvimIO[int]:
return N.pure(7)
return k(N.suspend(f).flat_map(g).flat_map(h).either(vim)).must(be_right(12))
def stack(self) -> Expectation:
@do(NvimIO[int])
def run(a: int) -> Do:
b = yield N.pure(a + 1)
if b < 1000:
yield run(b)
return kn(vim, run, 1).must(nsuccess(1000))
def stack_recover_fatal(self) -> Expectation:
@do(NvimIO[int])
def run(a: int) -> Do:
b = yield N.pure(a + 1)
if b < 1000:
yield N.recover_fatal(run(b), lambda a: N.pure(2000))
else:
raise Exception('error')
return kn(vim, run, 1).must(nsuccess(2000))
@pending
def stack_recover_error(self) -> Expectation:
@do(NvimIO[int])
def run(a: int) -> Do:
b = yield N.pure(a + 1)
if b < 1000:
yield N.recover_error(run(b), lambda a: N.pure(2000))
else:
yield N.error('boom')
return kn(vim, run, 1).must(nsuccess(2000))
def request(self) -> Expectation:
return k(N.request('blub', Nil).run_s(vim).vars) == vars
def request_bind(self) -> Expectation:
@do(NvimIO[int])
def run() -> Do:
ae = yield N.request('blub', List(5))
a = yield N.e(ae)
b = yield N.suspend(lambda v: N.pure(a + 1))
c = yield N.delay(lambda v: b + 3)
return c + 23
updated_vim, result = run().run(vim)
return (
(k(updated_vim.vars) == vars) &
(k(result).must(nsuccess(34))) &
(k(updated_vim.request_log) == List(('blub', List(5))))
)
def recover(self) -> Expectation:
@do(NvimIO[int])
def run() -> Do:
a = yield N.recover_error(N.error('booh'), lambda e: N.pure(1))
b = yield N.suspend(lambda v: N.pure(a + 1))
c = yield N.delay(lambda v: b + 3)
return c + 23
updated_vim, result = run().run(vim)
return k(result).must(nsuccess(28))
def recover_failure(self) -> Expectation:
def boom(v: NvimApi) -> NvimIO[int]:
raise Exception('boom')
@do(NvimIO[int])
def run() -> Do:
a = yield N.recover_failure(N.delay(boom), lambda e: N.pure(1))
return a + 1
result = run().run_a(vim)
return k(result).must(nsuccess(2))
def ensure_failure(self) -> Expectation:
x = 1
def inc(v: NvimApi) -> None:
nonlocal x
x = 2
@do(NvimIO[None])
def run() -> Do:
yield N.ensure_failure(N.error('booze'), lambda a: N.delay(inc))
result = run().run_a(vim)
return (k(x) == 2) & (k(result) == NError('booze'))
__all__ = ('NvimIoSpec',)
| 32.767606 | 116 | 0.574038 | 649 | 4,653 | 4.047766 | 0.1849 | 0.03426 | 0.013704 | 0.031976 | 0.379901 | 0.360868 | 0.31595 | 0.288161 | 0.208984 | 0.208984 | 0 | 0.021483 | 0.289706 | 4,653 | 141 | 117 | 33 | 0.773374 | 0.083817 | 0 | 0.355769 | 0 | 0 | 0.012598 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.115385 | 0.067308 | 0.567308 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
c2555429232f9a8cda4197983694ada140157c8f | 1,198 | py | Python | pycmark_gfm/inlineparser/link_processors.py | tk0miya/pycmark-gfm | db31d034c592fa3139a7bc672b0eae7a6fefa7d9 | [
"Apache-2.0"
] | 1 | 2019-05-12T07:21:02.000Z | 2019-05-12T07:21:02.000Z | pycmark_gfm/inlineparser/link_processors.py | tk0miya/pycmark-gfm | db31d034c592fa3139a7bc672b0eae7a6fefa7d9 | [
"Apache-2.0"
] | null | null | null | pycmark_gfm/inlineparser/link_processors.py | tk0miya/pycmark-gfm | db31d034c592fa3139a7bc672b0eae7a6fefa7d9 | [
"Apache-2.0"
] | null | null | null | """
pycmark_gfm.inlineparser.link_processors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Link processor classes for InlineParser.
:copyright: Copyright 2019 by Takeshi KOMIYA
:license: Apache License 2.0, see LICENSE for details.
"""
import re
from typing import Tuple
from docutils.nodes import Element
from pycmark.inlineparser import backtrack_onerror
from pycmark.inlineparser import link_processors as commonmark
from pycmark.inlineparser.link_processors import LinkTitleParser
from pycmark.readers import TextReader
from pycmark.utils import ESCAPED_CHARS
class LinkCloserProcessor(commonmark.LinkCloserProcessor):
@backtrack_onerror
def parse_link_destination(self, reader: TextReader, document: Element) -> Tuple[str, str]:
reader.step()
destination = LinkDestinationParser().parse(reader, document)
title = LinkTitleParser().parse(reader, document)
assert reader.consume(re.compile(r'\s*\)'))
return destination, title
class LinkDestinationParser(commonmark.LinkDestinationParser):
# spaces are allowed inside angle brackets
pattern = re.compile(r'\s*<((?:[^ <>\n\\]|' + ESCAPED_CHARS + r'| |\\)*)>', re.S)
| 33.277778 | 95 | 0.719533 | 129 | 1,198 | 6.604651 | 0.488372 | 0.064554 | 0.080986 | 0.068075 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005923 | 0.154424 | 1,198 | 35 | 96 | 34.228571 | 0.835143 | 0.222037 | 0 | 0 | 0 | 0 | 0.036504 | 0 | 0 | 0 | 0 | 0 | 0.055556 | 1 | 0.055556 | false | 0 | 0.444444 | 0 | 0.722222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
c25f5fef4a70616370e8dd0de9a703dbe2d9037c | 6,772 | py | Python | agtc/code_generation/type_gens/type_gens_ops.py | PetarMihalj/AGT | 114b1f8ee5a9820ab10a375ff44254b50c018b22 | [
"MIT"
] | 10 | 2021-07-06T16:31:06.000Z | 2021-07-12T11:30:51.000Z | agtc/code_generation/type_gens/type_gens_ops.py | PetarMihalj/AGT | 114b1f8ee5a9820ab10a375ff44254b50c018b22 | [
"MIT"
] | null | null | null | agtc/code_generation/type_gens/type_gens_ops.py | PetarMihalj/AGT | 114b1f8ee5a9820ab10a375ff44254b50c018b22 | [
"MIT"
] | null | null | null | from typing import Tuple, List
from dataclasses import dataclass
from .. import inference_errors as ierr
from .. import type_system as ts
from .. import context
from ..code_blocks import Primitive
from ..type_engine import TypingContext
from . import func_methods, concrete_methods, add_method_to_list
# ---------------------------------------------------------------------
mapping_int_binary = {
"__eq__": (False, "eq"),
"__ne__": (False, "ne"),
'__gt__': (False, "sgt"),
'__lt__': (False, "slt"),
'__ge__': (False, "sge"),
'__le__': (False, "sle"),
'__add__': (True, "add"),
'__sub__': (True, "sub"),
'__mul__': (True, "mul"),
'__div__': (True, "sdiv"),
'__mod__': (True, "srem"),
}
@add_method_to_list(func_methods)
def gen_int_type_ops(
tc: TypingContext,
name: str,
type_argument_types: Tuple[ts.Type],
argument_types: Tuple[ts.Type],
):
if name not in mapping_int_binary:
raise ierr.TypeGenError()
if len(type_argument_types) != 0:
raise ierr.TypeGenError()
if len(argument_types) != 2:
raise ierr.TypeGenError()
if not isinstance(argument_types[0], ts.IntType):
raise ierr.TypeGenError()
if not isinstance(argument_types[1], ts.IntType):
raise ierr.TypeGenError()
if argument_types[0].size != argument_types[1].size:
raise ierr.TypeGenError()
dname = tc.scope_man.new_func_name(f"dummy_func_{name}")
retty = argument_types[0] if mapping_int_binary[name][0] else ts.BoolType()
tc.code_blocks.append(IntTypeOpPrimitive(
dname,
name,
argument_types[0].size,
))
ft = ts.FunctionType(
dname,
retty,
do_not_copy_args = False,
)
return ft
@dataclass
class IntTypeOpPrimitive(Primitive):
mangled_name: str
op: str
size: int
def get_code(self):
def arithmetic(opname):
return [
f"define dso_local i{self.size} @{self.mangled_name}(i{self.size} %0, i{self.size} %1) {{",
f"\t%3 = {opname} nsw i{self.size} %0, %1",
f"\tret i{self.size} %3",
f"}}",
]
def comp(opname):
return [
f"define dso_local i1 @{self.mangled_name}(i{self.size} %0, i{self.size} %1) {{",
f"\t%3 = icmp {opname} i{self.size} %0, %1",
f"\tret i1 %3",
f"}}",
]
a,opname = mapping_int_binary[self.op]
if a:
return arithmetic(opname)
else:
return comp(opname)
# ---------------------------------------------------------------------
mapping_char_binary = {
"__eq__": (False, "eq"),
"__ne__": (False, "ne"),
}
@add_method_to_list(func_methods)
def gen_char_type_ops(
tc: TypingContext,
name: str,
type_argument_types: Tuple[ts.Type],
argument_types: Tuple[ts.Type],
):
if name not in mapping_char_binary:
raise ierr.TypeGenError()
if len(type_argument_types) != 0:
raise ierr.TypeGenError()
if len(argument_types) != 2:
raise ierr.TypeGenError()
if not isinstance(argument_types[0], ts.CharType):
raise ierr.TypeGenError()
if not isinstance(argument_types[1], ts.CharType):
raise ierr.TypeGenError()
dname = tc.scope_man.new_func_name(f"dummy_func_{name}")
retty = ts.BoolType()
tc.code_blocks.append(CharTypeOpPrimitive(
dname,
name,
))
ft = ts.FunctionType(
dname,
retty,
do_not_copy_args = False,
)
return ft
@dataclass
class CharTypeOpPrimitive(Primitive):
mangled_name: str
op: str
def get_code(self):
def comp(opname):
return [
f"define dso_local i1 @{self.mangled_name}(i8 %0, i8 %1) {{",
f"\t%3 = icmp {opname} i8 %0, %1",
f"\tret i1 %3",
f"}}",
]
a,opname = mapping_int_binary[self.op]
return comp(opname)
# ---------------------------------------------------------------------
mapping_bool_binary = {
"__and__": "and",
"__or__": "or",
}
@add_method_to_list(func_methods)
def gen_bool_type_ops(
tc: TypingContext,
name: str,
type_argument_types: Tuple[ts.Type],
argument_types: Tuple[ts.Type],
):
if name not in mapping_bool_binary:
raise ierr.TypeGenError()
if len(type_argument_types) != 0:
raise ierr.TypeGenError()
if len(argument_types) != 2:
raise ierr.TypeGenError()
if not isinstance(argument_types[0], ts.BoolType):
raise ierr.TypeGenError()
if not isinstance(argument_types[1], ts.BoolType):
raise ierr.TypeGenError()
dname = tc.scope_man.new_func_name(f"dummy_func_{name}")
tc.code_blocks.append(BoolTypeOpPrimitive(
dname,
name,
))
ft = ts.FunctionType(
dname,
ts.BoolType(),
do_not_copy_args = False,
)
return ft
@dataclass
class BoolTypeOpPrimitive(Primitive):
mangled_name: str
op: str
def get_code(self):
return [
f"define dso_local i1 @{self.mangled_name}(i1 %0, i1 %1) {{",
f"\t%3 = {mapping_bool_binary[self.op]} i1 %0, %1",
f"\tret i1 %3",
f"}}",
]
# ---------------------------------------------------------------------
@add_method_to_list(func_methods)
def gen_bool_type_not(
tc: TypingContext,
name: str,
type_argument_types: Tuple[ts.Type],
argument_types: Tuple[ts.Type],
):
if name != '__not__':
raise ierr.TypeGenError()
if len(type_argument_types) != 0:
raise ierr.TypeGenError()
if len(argument_types) != 1:
raise ierr.TypeGenError()
if not isinstance(argument_types[0], ts.BoolType):
raise ierr.TypeGenError()
dname = tc.scope_man.new_func_name(f"dummy_func_{name}")
tc.code_blocks.append(BoolTypeNotPrimitive(
dname,
))
ft = ts.FunctionType(
dname,
ts.BoolType(),
do_not_copy_args = False,
)
return ft
@dataclass
class BoolTypeNotPrimitive(Primitive):
mangled_name: str
def get_code(self):
return [
f"define dso_local i1 @{self.mangled_name}(i1 %0) {{",
f"\t%2 = add i1 1, %0",
f"\tret i1 %2",
f"}}",
]
# ---------------------------------------------------------------------
| 26.98008 | 107 | 0.533816 | 767 | 6,772 | 4.439374 | 0.146023 | 0.103084 | 0.123348 | 0.108076 | 0.751248 | 0.741557 | 0.685756 | 0.661087 | 0.642291 | 0.642291 | 0 | 0.013667 | 0.297696 | 6,772 | 250 | 108 | 27.088 | 0.702271 | 0.051536 | 0 | 0.62069 | 0 | 0.009852 | 0.123266 | 0.025713 | 0 | 0 | 0 | 0 | 0 | 1 | 0.054187 | false | 0 | 0.039409 | 0.024631 | 0.211823 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c26efa1d42794617b5c67d334f2e516d9553e666 | 1,450 | py | Python | app/__init__.py | TylerJang27/Pikachooze | 1497e4e5b2bb5e8136c9cfea6e13260478fe7502 | [
"MIT"
] | 2 | 2021-10-20T16:44:23.000Z | 2021-11-29T04:54:02.000Z | app/__init__.py | TylerJang27/Pikachooze | 1497e4e5b2bb5e8136c9cfea6e13260478fe7502 | [
"MIT"
] | null | null | null | app/__init__.py | TylerJang27/Pikachooze | 1497e4e5b2bb5e8136c9cfea6e13260478fe7502 | [
"MIT"
] | null | null | null | from flask import Flask
from app.config import Config
from app.db import DB
from app.models.base import login, babel
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import subprocess
from os import getcwd, path
import uuid
from app.models.trainer_pokemon import TrainerPokemon
from app.models.trainer import Trainer
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
create_path = path.join(getcwd(), app.config['SQL_CREATE_PATH'])
process = subprocess.Popen(create_path, shell=True, stdout=subprocess.PIPE)
process.wait()
process.kill()
app.db = DB(app)
load_path = path.join(getcwd(), app.config['SQL_LOAD_PATH'])
subprocess.call([load_path])
engine = create_engine(Config.SQLALCHEMY_DATABASE_URI, echo=True) #TODO: GET FROM OTHER ONE
Session = sessionmaker(engine, expire_on_commit=True)
session = Session()
tps = session.query(TrainerPokemon).all()
for tp in tps:
if tp.uuid is None:
tp.uuid = uuid.uuid4()
session.add(tp)
ts = session.query(Trainer).all()
for t in ts:
if t.uuid is None:
t.uuid = uuid.uuid4()
session.add(t)
session.commit()
login.init_app(app)
babel.init_app(app)
from .index import bp as index_bp
app.register_blueprint(index_bp)
from .users import bp as user_bp
app.register_blueprint(user_bp)
return app
| 26.851852 | 95 | 0.695862 | 207 | 1,450 | 4.7343 | 0.342995 | 0.035714 | 0.039796 | 0.040816 | 0.108163 | 0.061224 | 0.061224 | 0 | 0 | 0 | 0 | 0.001744 | 0.208966 | 1,450 | 53 | 96 | 27.358491 | 0.852659 | 0.016552 | 0 | 0 | 0 | 0 | 0.019649 | 0 | 0 | 0 | 0 | 0.018868 | 0 | 1 | 0.02381 | false | 0 | 0.309524 | 0 | 0.357143 | 0.047619 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
c288b445d9effebdfee2f3b482f3af8554543ed7 | 178 | py | Python | PC/Model/add_lib_to_path.py | limvi-licef/GoalFormulationAssistanceAR | ed9c33c874a555b1b9e6638ac08d449a685488bc | [
"Apache-2.0"
] | null | null | null | PC/Model/add_lib_to_path.py | limvi-licef/GoalFormulationAssistanceAR | ed9c33c874a555b1b9e6638ac08d449a685488bc | [
"Apache-2.0"
] | null | null | null | PC/Model/add_lib_to_path.py | limvi-licef/GoalFormulationAssistanceAR | ed9c33c874a555b1b9e6638ac08d449a685488bc | [
"Apache-2.0"
] | 1 | 2020-08-14T06:40:28.000Z | 2020-08-14T06:40:28.000Z | # coding: utf-8
import sys
import os
FILE = os.path.abspath(__file__)
PATH, file = os.path.split(FILE)
PATH, contextual_assistance = os.path.split(PATH)
sys.path.append(PATH) | 16.181818 | 49 | 0.741573 | 29 | 178 | 4.37931 | 0.448276 | 0.141732 | 0.15748 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00641 | 0.123596 | 178 | 11 | 50 | 16.181818 | 0.807692 | 0.073034 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
c2987395b58ac18e74fc36d492ce3390722ba8ee | 571 | py | Python | Day 10-15 - Python CSV and Email/day10-working.py | sameem420/30-Days-of-Python | f74b2a02d7e13f4f686bf2f93f35039804ae26f8 | [
"MIT"
] | 1 | 2021-04-06T07:00:00.000Z | 2021-04-06T07:00:00.000Z | Day 10-15 - Python CSV and Email/day10-working.py | sameem420/30-Days-of-Python | f74b2a02d7e13f4f686bf2f93f35039804ae26f8 | [
"MIT"
] | null | null | null | Day 10-15 - Python CSV and Email/day10-working.py | sameem420/30-Days-of-Python | f74b2a02d7e13f4f686bf2f93f35039804ae26f8 | [
"MIT"
] | null | null | null | from smtplib import SMTP
host = "smtp.gmail.com"
port = 587
username = "example@gmail.com" # Your email address
password = "example" # Your password
from_email = username # email_address = username
to_list = ["example@gmail.com"] # List of users you want to send messages to.
server_connection = SMTP( host, port)
server_connection.ehlo_or_helo_if_needed()
server_connection.starttls()
server_connection.login(username, password)
server_connection.sendmail(from_email, to_list, "Welcome to Python Mailing!" )
print("Mail sent successfully!")
server_connection.quit()
| 30.052632 | 78 | 0.781086 | 79 | 571 | 5.455696 | 0.518987 | 0.222738 | 0.069606 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005952 | 0.117338 | 571 | 18 | 79 | 31.722222 | 0.849206 | 0.176883 | 0 | 0 | 0 | 0 | 0.223656 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.142857 | 0.071429 | 0 | 0.071429 | 0.071429 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
c2d7fb7560d2296d9941b4bc2b1ef33225e984df | 521 | py | Python | Rasp-main/cleanDatabase.py | ascuadrado/ISC | 0d3f623dabf40dc0057e8da0d3c75c8b2dd339e9 | [
"MIT"
] | 1 | 2020-11-18T12:22:09.000Z | 2020-11-18T12:22:09.000Z | Rasp-main/cleanDatabase.py | ascuadrado/ISC | 0d3f623dabf40dc0057e8da0d3c75c8b2dd339e9 | [
"MIT"
] | null | null | null | Rasp-main/cleanDatabase.py | ascuadrado/ISC | 0d3f623dabf40dc0057e8da0d3c75c8b2dd339e9 | [
"MIT"
] | null | null | null | import sqlite3
# File names
dbFile = 'ISC/Rasp-main/Database.db'
def clean_database():
conn = sqlite3.connect(dbFile)
c = conn.cursor()
c.execute('DELETE FROM general;', )
c.execute('DELETE FROM charger;', )
c.execute('DELETE FROM sevcon;', )
c.execute('DELETE FROM bms1;', )
c.execute('DELETE FROM bms2;', )
c.execute('DELETE FROM bms3;', )
# commit the changes to db
conn.commit()
# close the connection
conn.close()
if __name__ == '__main__':
clean_database() | 20.84 | 39 | 0.633397 | 67 | 521 | 4.776119 | 0.492537 | 0.15 | 0.2625 | 0.3375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012315 | 0.220729 | 521 | 25 | 40 | 20.84 | 0.775862 | 0.107486 | 0 | 0 | 0 | 0 | 0.309524 | 0.054113 | 0 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0.066667 | 0 | 0.133333 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c2e26458a9ab334aab77cd6da16c95a917948f62 | 759 | py | Python | node.py | monooso/udacity-nd256-project-four | 954b63f7bd6b04e4041b98c41895766bf67a8244 | [
"MIT"
] | 1 | 2019-08-12T14:49:15.000Z | 2019-08-12T14:49:15.000Z | node.py | monooso/udacity-nd256-project-four | 954b63f7bd6b04e4041b98c41895766bf67a8244 | [
"MIT"
] | null | null | null | node.py | monooso/udacity-nd256-project-four | 954b63f7bd6b04e4041b98c41895766bf67a8244 | [
"MIT"
] | null | null | null | class Node(object):
def __init__(self, id, x, y):
self.__id = id
self.__x = x
self.__y = y
self.reset()
@property
def id(self):
return self.__id
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@property
def total_distance_to_goal(self):
"""
Get the distance from the origin to the goal, via this node.
:returns: the total distance
"""
return self.distance_to_here + self.distance_to_goal
def reset(self):
"""Reset any mutable values."""
self.via = None
self.visited = False
self.distance_to_goal = float('inf')
self.distance_to_here = float('inf') | 22.323529 | 68 | 0.562582 | 98 | 759 | 4.081633 | 0.326531 | 0.125 | 0.14 | 0.09 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.337286 | 759 | 34 | 69 | 22.323529 | 0.795229 | 0.152833 | 0 | 0.173913 | 0 | 0 | 0.009885 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.26087 | false | 0 | 0 | 0.130435 | 0.478261 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.