blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
2cf58254ef5b110fe895e0ed4e45a86817ff8d00
Python
daniel-reich/ubiquitous-fiesta
/NJw4mENpSaMz3eqh2_17.py
UTF-8
191
2.75
3
[]
no_license
def is_undulating(n): if len(str(n)) < 3: return False if len(set(str(n))) != 2: return False s = str(n) for i in range(len(s)-1): if s[i] == s[i+1]: return False return True
true
9f0f17bb593e7451983d84bd56d552a131e84004
Python
jgrindal/dailyprogramming
/Challenge-HackerRank.py
UTF-8
611
3.40625
3
[]
no_license
#!/bin/python3 import sys import os # Complete the function below. def swap(a, l, r): temp = a[l] a[l] = a[r] a[r] = temp return a def moves(a): a.pop(0) l = 0 r = len(a) - 1 swaps = 0 while True: for num in a: if num % 2 == 1: l += 1 else: break for num in reversed(a): if num % 2 == 0: r -= 1 else: break if r < l: break a = swap(a, l, r) swaps += 1 return swaps print(moves([4, 13, 10, 21, 20]))
true
b8dbcdb9fd14fb1dd433a5591b82bd083b0b80f6
Python
byungjur96/Algorithm
/9095.py
UTF-8
187
3.34375
3
[]
no_license
t = int(input()) for _ in range(t): n = int(input()) case = [1, 1, 2] # 0, 1, 2 for i in range(3, n+1): case.append(case[i-1]+case[i-2]+case[i-3]) print(case[n])
true
faa954f92ee4ebf83dcf33948915f2098e041224
Python
AmatanHead/collective-blog
/s_markdown/extensions/cut.py
UTF-8
2,551
2.71875
3
[ "MIT" ]
permissive
"""Adds syntax for creating habracut""" from __future__ import absolute_import from __future__ import unicode_literals from markdown.extensions import Extension from markdown.preprocessors import Preprocessor import re from django.utils.deconstruct import deconstructible from django.utils.html import escape @deconstructible class CutExtension(Extension): def __init__(self, *args, **kwargs): """Adds habracut E.g. `----cut----` """ self.anchor = kwargs.pop('anchor', '') super(CutExtension, self).__init__(*args, **kwargs) def extendMarkdown(self, md, md_globals): """Add FencedBlockPreprocessor to the Markdown instance :param md: Current markdown instance. :param md_globals: Global markdown vars. """ md.registerExtension(self) if 'fenced_code_block' in md.preprocessors: md.preprocessors.add('cut', CutPreprocessor(md, anchor=self.anchor), ">fenced_code_block") else: md.preprocessors.add('cut', CutPreprocessor(md, anchor=self.anchor), ">normalize_whitespace") class CutPreprocessor(Preprocessor): def __init__(self, *args, **kwargs): """Main fenced code block renderer""" self.anchor = kwargs.pop('anchor', '') super(CutPreprocessor, self).__init__(*args, **kwargs) block_re = re.compile( r'-{4,}[ ]*' r'cut[ ]*(here)?[ ]*' r'(\{\{(?P<caption>[^\}]+)\}\})?' r'[ ]*-{4,}', re.MULTILINE | re.DOTALL | re.VERBOSE | re.IGNORECASE) def run(self, lines): """Match cut tags and store them in the htmlStash :param lines: Lines of code. """ text = '\n'.join(lines) m = self.block_re.search(text) if m is not None: if 'caption' in m.groupdict() and m.groupdict()['caption'] is not None: html = '<!-- cut here {{ %s }} -->' % escape(m.groupdict()['caption']) else: html = '<!-- cut here -->' if self.anchor: html += '<a name="%s"></a>' % escape(self.anchor) placeholder = self.markdown.htmlStash.store(html, safe=True) text = '%s\n%s\n%s' % (text[:m.start()], placeholder, text[m.end():]) return text.split('\n')
true
401730b8558f18b1a705e93a635cf64baa78446d
Python
rushill2/CS440SP21
/HMM/baseline.py
UTF-8
1,856
3.109375
3
[]
no_license
# mp4.py # --------------- # Licensing Information: You are free to use or extend this projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to the University of Illinois at Urbana-Champaign # # Created Fall 2018: Margaret Fleck, Renxuan Wang, Tiantian Fang, Edward Huang (adapted from a U. Penn assignment) # Modified Spring 2020: Jialu Li, Guannan Guo, and Kiran Ramnath # Modified Fall 2020: Amnon Attali, Jatin Arora # Modified Spring 2021 by Kiran Ramnath """ Part 1: Simple baseline that only uses word statistics to predict tags """ from collections import Counter def baseline(train, test): ''' input: training data (list of sentences, with tags on the tags) test data (list of sentences, no tags on the tags) output: list of sentences, each sentence is a list of (word,tag) pairs. E.g., [[(word1, tag1), (word2, tag2)], [(word3, tag3), (word4, tag4)]] ''' estimate = [] wtag_dict = {} for sentence in train: for w_tag in sentence: if w_tag[0] not in wtag_dict: wtag_dict[w_tag[0]] = {w_tag[1]: 1} elif w_tag[1] not in wtag_dict[w_tag[0]]: wtag_dict[w_tag[0]][w_tag[1]] = 1 else: wtag_dict[w_tag[0]][w_tag[1]] += 1 reduce_ = {} cnt = Counter() for w, t in wtag_dict.items(): high_p_tag = max(t, key = t.get) reduce_[w] = high_p_tag cnt += Counter(t) var = cnt.most_common(1) max_freq = var[0][0] for sentence in test: tagset = [] for w in sentence: if w in reduce_: tagset = [*tagset, (w, reduce_[w])] elif w not in reduce_: tagset = [*tagset, (w, max_freq)] estimate = [*estimate, tagset] return estimate
true
884da9cd8cc511c5d64a76cf9de1517a204614dc
Python
wandb/examples
/examples/pytorch-lightning/mnist.py
UTF-8
2,675
2.84375
3
[]
no_license
"""pytorch-lightning example with W&B logging. Based on this colab: https://colab.research.google.com/drive/1F_RNcHzTfFuQf-LeKvSlud6x7jXYkG31 """ import os import torch from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import transforms from torchvision.datasets import MNIST import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger class MNISTModel(pl.LightningModule): def __init__(self): super().__init__() # not the best model... self.l1 = torch.nn.Linear(28 * 28, 10) def prepare_data(self): # download MNIST data only once MNIST(os.getcwd(), train=True, download=True, transform=transforms.ToTensor()) MNIST(os.getcwd(), train=False, download=True, transform=transforms.ToTensor()) def forward(self, x): # called with self(x) return torch.relu(self.l1(x.view(x.size(0), -1))) def training_step(self, batch, batch_nb): # REQUIRED x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) self.log("train_loss", loss, on_step=True, on_epoch=False) return loss def validation_step(self, batch, batch_nb): # OPTIONAL x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) self.log("val_loss", loss, on_step=False, on_epoch=True) def test_step(self, batch, batch_nb): # OPTIONAL x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) self.log("test_loss", loss, on_step=False, on_epoch=True) def configure_optimizers(self): # REQUIRED # can return multiple optimizers and learning_rate schedulers # (LBFGS it is automatically supported, no need for closure function) return torch.optim.Adam(self.parameters(), lr=0.02) def train_dataloader(self): # REQUIRED return DataLoader( MNIST(os.getcwd(), train=True, download=False, transform=transforms.ToTensor()), batch_size=32 ) def val_dataloader(self): # OPTIONAL return DataLoader( MNIST(os.getcwd(), train=True, download=False, transform=transforms.ToTensor()), batch_size=32 ) def test_dataloader(self): # OPTIONAL return DataLoader( MNIST(os.getcwd(), train=True, download=False, transform=transforms.ToTensor()), batch_size=32 ) if __name__ == "__main__": wandb_logger = WandbLogger() mnist_model = MNISTModel() trainer = pl.Trainer(gpus=0, max_epochs=2, logger=wandb_logger) trainer.fit(mnist_model) trainer.test(mnist_model)
true
931ed16592ad3cccfe9e28737a732626d23252f0
Python
Lazysisphus/GDELT_DATA_COLLECTOR
/5_build_index.py
UTF-8
819
2.53125
3
[]
no_license
''' @Descripttion: @version: @Author: Zhang Xiaozhu @Date: 2020-03-26 20:06:30 @LastEditors: Zhang Xiaozhu @LastEditTime: 2020-04-07 23:40:42 ''' ''' 在已经导入数据库的表格上建立索引 ''' import pymysql table_name_list = [ 'week14' ] # 创建连接 conn = pymysql.connect(user='root', password='5991', database='gdelt', charset='utf8mb4') for table in table_name_list: with conn.cursor() as cursor: # event_fulltext、title_fulltext sql = "create fulltext index event_fulltext on " + table + " (Actor1Name, Actor2Name, Actor1Geo_FullName, Actor2Geo_FullName, ActionGeo_FullName, Title, Content);" cursor.execute(sql) # 没有设置默认自动提交,需要主动提交,以保存所执行的语句 conn.commit() print(table + "的索引建立完成!")
true
ee742767c544518e3f8e12e5502b17d7397a2144
Python
jml/flocker-tools
/flocker_tools/tests/test_json.py
UTF-8
1,459
2.578125
3
[]
no_license
from testtools import TestCase from flocker_tools._json import repair_json class TestRepairJSON(TestCase): def test_one_json_line(self): self.assertEqual([{'foo': 'bar'}], list(repair_json(['{"foo": "bar"}']))) def test_split_json_line(self): lines = ['{"foo":\n', ' "bar"}'] self.assertEqual([{'foo': 'bar'}], list(repair_json(lines))) def test_split_across_multiple_lines(self): lines = ['{"f\n', 'oo\n', '":\n', ' "ba\n', 'r"}'] self.assertEqual([{'foo': 'bar'}], list(repair_json(lines))) def test_begins_with_non_json(self): # We might have a log that starts with a line that's part of a wrapped # JSON expression. Just ignore it. lines = [ '"bar", "baz"], "qux": 3}\n', '{"foo":\n', '"bar"}\n', ] self.assertEqual([{'foo': 'bar'}], list(repair_json(lines))) def test_trailing_json(self): # We might have JSON at the very end that's never closed. lines = [ '{"foo":\n', ' "bar"}\n', '{"qu\n', ] self.assertEqual([{'foo': 'bar'}], list(repair_json(lines))) def test_interrupted_json(self): # We might have a JSON object that's interrupted and never finished. lines = [ '{"qu\n', '{"foo":\n', ' "bar"}\n', ] self.assertEqual([{'foo': 'bar'}], list(repair_json(lines)))
true
5e8839f46e95869f9306a1c5f6b5430f1b051c4f
Python
JollenWang/study
/python/demo100/40.py
UTF-8
281
3.5
4
[]
no_license
#!/usr/bin/python #-*- coding:utf-8 -*- #author : Jollen Wang #date : 2016/05/10 #version: 1.0 ''' 【程序40】 题目:将一个数组逆序输出。 ''' a = [1,2,3,4,5,6,7,8,9,0] l = len(a) print a for i in range(l/2): a[i], a[l - 1 -i] = a[l - 1 - i], a[i] print a
true
72c6e63c4ec474eba86b9eab39ae9d33163957e1
Python
lswq0808/Naive-Bayes-classifier
/new.py
UTF-8
5,609
3.171875
3
[]
no_license
import math import re import pandas as pd import codecs import jieba def load_formatted_data(): """ 加载格式化后的标签-路径列表 spam列为1代表是垃圾邮件,0代表普通邮件 path列代表该邮件路径 :return:(DataFrame)index """ # 加载数据集 index = pd.read_csv('index', sep=' ', names=['spam', 'path']) index.spam = index.spam.apply(lambda x: 1 if x == 'spam' else 0) index.path = index.path.apply(lambda x: x[1:]) return index def load_stop_word(): """ 读出停用词列表 :return: (List)_stop_words """ with codecs.open("stop", "r") as f: lines = f.readlines() _stop_words = [i.strip() for i in lines] return _stop_words def get_mail_content(path): """ 遍历得到每封邮件的词汇字符串 :param path: 邮件路径 :return:(Str)content """ with codecs.open(path, "r", encoding="gbk", errors="ignore") as f: lines = f.readlines() for i in range(len(lines)): if lines[i] == '\n': # 去除第一个空行,即在第一个空行之前的邮件协议内容全部舍弃 lines = lines[i:] break content = ''.join(''.join(lines).strip().split()) # print(content) return content def create_word_dict(content, stop_words_list): """ 依据邮件的词汇字符串统计词汇出现记录,依据停止词列表除去某些词语 :param content: 邮件的词汇字符串 :param stop_words_list:停止词列表 :return:(Dict)word_dict """ word_list = [] word_dict = {} # word_dict key:word, value:1 content = re.findall(u"[\u4e00-\u9fa5]", content) content = ''.join(content) word_list_temp = jieba.cut(content) for word in word_list_temp: if word != '' and word not in stop_words_list: word_list.append(word) for word in word_list: word_dict[word] = 1 return word_dict def train_dataset(dataset_to_train): """ 对数据集进行训练, 统计训练集中某个词在普通邮件和垃圾邮件中的出现次数 :param dataset_to_train: 将要用来训练的数据集 :return:Tuple(词汇出现次数字典_train_word_dict, 垃圾邮件总数spam_count, 正常邮件总数ham_count) """ _train_word_dict = {} # train_word_dict内容,训练集中某个词在普通邮件和垃圾邮件中的出现次数 for word_dict, spam in zip(dataset_to_train.word_dict, dataset_to_train.spam): # word_dict某封信的词汇表 spam某封信的状态 for word in word_dict: # 对每封信的每个词在该邮件分类进行出现记录 出现过为则记录数加1 未出现为0 _train_word_dict.setdefault(word, {0: 0, 1: 0}) _train_word_dict[word][spam] += 1 ham_count = dataset_to_train.spam.value_counts()[0] spam_count = dataset_to_train.spam.value_counts()[1] return _train_word_dict, spam_count, ham_count def predict_dataset(_train_word_dict, _spam_count, _ham_count, data): """ 测试算法 :param _train_word_dict:词汇出现次数字典 :param _spam_count:垃圾邮件总数 :param _ham_count:正常邮件总数 :param data:测试集 :return: """ total_count = _ham_count + _spam_count word_dict = data['word_dict'] # 先验概率 已经取了对数 ham_probability = math.log(float(_ham_count) / total_count) spam_probability = math.log(float(_spam_count) / total_count) for word in word_dict: word = word.strip() _train_word_dict.setdefault(word, {0: 0, 1: 0}) # 求联合概率密度 += log # 拉普拉斯平滑 word_occurs_counts_ham = _train_word_dict[word][0] # 出现过这个词的信件数 / 垃圾邮件数 ham_probability += math.log((float(word_occurs_counts_ham) + 1) / _ham_count + 2) word_occurs_counts_spam = _train_word_dict[word][1] # 出现过这个词的信件数 / 普通邮件数 spam_probability += math.log((float(word_occurs_counts_spam) + 1) / _spam_count + 2) if spam_probability > ham_probability: is_spam = 1 else: is_spam = 0 # 返回预测正确状态 if is_spam == data['spam']: return 1 else: return 0 def save_train_word_dict(train_word_dict): with codecs.open("train_word_dict", "w", encoding="gbk", errors="ignore") as f: f.write(train_word_dict) if __name__ == '__main__': index_list = load_formatted_data() stop_words = load_stop_word() # get_mail_content(index_list.path[0]) index_list['content'] = index_list.path.apply(lambda x: get_mail_content(x)) index_list['word_dict'] = index_list.content.apply(lambda x: create_word_dict(x, stop_words)) train_set = index_list.loc[:len(index_list) * 0.8] test_set = index_list.loc[len(index_list) * 0.8:] train_word_dict, spam_count, ham_count = train_dataset(train_set) save_train_word_dict(train_word_dict) test_mails_predict = test_set.apply( lambda x: predict_dataset(train_word_dict, spam_count, ham_count, x), axis=1) corr_count = 0 false_count = 0 for i in test_mails_predict.values.tolist(): if i == 1: corr_count += 1 if i == 0: false_count += 1 print("测试集样本总数", (corr_count + false_count)) print("正确预计个数", corr_count) print("错误预测个数", false_count) result = float(corr_count / (corr_count + false_count)) print('预测准确率:', result)
true
609e22551e0fb7ef371b69fa190ce0b1b6292f9e
Python
PedroGal1234/Unite5
/listDemo.py
UTF-8
272
4.375
4
[]
no_license
#Pedro Gallino #11/12/17 #listDemo.py - print out first and last words in a list words = input('Enter some words:').split(' ') # to print out the list one item per line for w in words: print(w) print('the first word was',words[0]) print('the last word was', words[-1])
true
b24bd43397603ea71a4c45579210106b57c99c2d
Python
prabodhtr/Data-Mining-assignment1
/k_means_algo_mod2.py
UTF-8
3,196
3.203125
3
[]
no_license
import math import random import numpy import graphToolKit as gtk def findDistance(obj1, obj2): distance = 0 for i in range(len(obj1)): distance += (obj1[i] - obj2[i])**2 return math.sqrt(distance) def findSquaredDistance(obj1, obj2): distance = 0 for i in range(len(obj1)): distance += (obj1[i] - obj2[i])**2 return distance def findCluster(obj1, cent1, cent2, cent3): distances = [] distances.append(findDistance(obj1, cent1)) distances.append(findDistance(obj1, cent2)) distances.append(findDistance(obj1, cent3)) return distances.index(min(distances)) + 1 def findMean(cluster): uval = wval = xval = yval = 0 for obj in cluster: uval += obj[0] wval += obj[1] xval += obj[2] yval += obj[3] size = len(cluster) return [(uval/size), (wval/size), (xval/size), (yval/size)] def findSSE(centroids, cluster1, cluster2, cluster3): sse = 0 for obj in cluster1: sse += findSquaredDistance(obj, centroids[0]) for obj in cluster2: sse += findSquaredDistance(obj, centroids[1]) for obj in cluster3: sse += findSquaredDistance(obj, centroids[2]) return sse # taking input from file dataSet = [] dataFile = open("iris.data", "r") for line in dataFile: obj = [] x = line.strip().split(",") for i in range(4): obj.append((float)(x[i])) dataSet.append(obj) random.shuffle(dataSet) # initialise clusters cluster1 = [] cluster2 = [] cluster3 = [] #loop till clusering is success while True: #initialise variables sseValues = [] flag = "all_good" i = 0 # initialize centroid values with random data points cent = numpy.array(random.sample(dataSet, 3)) #loop till final clusters are found i.e., till means are the same while True: cluster1.clear() cluster2.clear() cluster3.clear() for obj in dataSet: cluster = findCluster(obj, cent[0], cent[1], cent[2]) if cluster == 1: cluster1.append(obj) elif cluster == 2: cluster2.append(obj) else: cluster3.append(obj) if len(cluster1) == 0 or len(cluster2) == 0 or len(cluster3) == 0: flag == "empty_cluster" break newCent = numpy.array([findMean(cluster1), findMean(cluster2), findMean(cluster3)]) compare = cent == newCent #break of means remain the same => final clustering found if compare.all() and i >= 150: break else: cent = numpy.delete(cent,[0,1,2],0) cent = newCent newSSE = findSSE(cent, cluster1, cluster2, cluster3) sseValues.append(newSSE) i += 1 if(flag == "all_good"): break # add the final clusters into a dictionary clusters = {} clusters["cluster1"] = cluster1 clusters["cluster2"] = cluster2 clusters["cluster3"] = cluster3 # print the final clusters for cluster in clusters: print(cluster) print(clusters[cluster]) # plot the graphs gtk.plot3DGraph(clusters) gtk.plot4DGraph(clusters) gtk.plotSSEGraph(sseValues) gtk.plot2DGraph(clusters)
true
36b98a4d2e8d8a4e0d950d6f708d5baff587d8dc
Python
bclouser/photo
/getImageDimensions.py
UTF-8
1,686
2.609375
3
[]
no_license
#!/usr/bin/env python import os, glob import shutil import stat from PIL import ExifTags from PIL import Image import sys import traceback inputPath = './' paths = {} for path, dirs, files in os.walk(inputPath): # check that the path itself is not a hidden folder if not path.startswith('./.') or not path.startswith('.'): # Iterate through list of dirs and remove hidden dirs nonHiddenDirs = [ d for d in dirs if not (d.startswith('.') or d.startswith('./.')) ] # Iterate through list of files and remove of hidden files nonHiddenfiles = [ f for f in files if not (f.startswith('.') or f.startswith('./.')) ] paths[path] = (nonHiddenDirs, nonHiddenfiles) # Remove this script from that list try: paths[ './' ][1].remove( os.path.basename(__file__) ) except: pass # This is ok. If the script isn't in the list, that's what we want! print "" print "" print "##################################################################" print " Resizing Images, Generating Thumbnails, Rotating if necessary..." print "##################################################################" print "" pathsImageDict = {} # Reduce the files for path, dirsAndFiles in paths.iteritems(): dirs = dirsAndFiles[0] files = dirsAndFiles[1] if(files): imgDir = path lastDir = imgDir.split('/')[-1] for file in files: imgPath = os.path.join( imgDir, file ) print 'imgPath = ' + imgPath try: if ( file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.JPG') or file.endswith('.JPEG') ): image = Image.open( imgPath ) print(file + ": Width = " + str(image.size[0]) + ", Height = " + str(image.size[1])); except Exception as e: print e
true
8f52434ac352611686fa50ae3338beccd1b4a08f
Python
fhirschmann/tucan
/bin/tucan
UTF-8
2,569
2.703125
3
[ "MIT" ]
permissive
#!/usr/bin/env python from __future__ import print_function import os import argparse from netrc import netrc from hashlib import md5 from tucan import get_grades def mail(recipient, subject, body): import subprocess proc = subprocess.Popen(["mail", "-s", subject, recipient], stdin=subprocess.PIPE) proc.stdin.write(body) proc.stdin.close() def notify(msg): from subprocess import Popen Popen(['notify-send', msg]) def parse_netrc(): username, _, password = netrc().authenticators("www.tucan.tu-darmstadt.de") return username, password def update_db(db, grades): if os.path.isfile(db): with open(db) as db_fp: old_digests = set(db_fp.read().split(os.linesep)) else: old_digests = set() new_digests = {md5(repr(g)).hexdigest(): g for g in grades} if set(new_digests.keys()) != old_digests: with open(db, "w") as db_fp: db_fp.write(os.linesep.join(old_digests.union(new_digests.keys()))) return [v for k, v in new_digests.items() if k not in old_digests] return None if __name__ == "__main__": parser = argparse.ArgumentParser(description="TUCaN CLI", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--mail", "-m", type=str, help="send email to this address on changes") parser.add_argument("--db", type=str, default=os.path.expanduser("~/.tucandb"), help="database file") parser.add_argument("--new", help="print only new grades", action="store_true") parser.add_argument("--notify", "-n", action="store_true", help="send desktop notification on new grades") parser.add_argument("--json", "-j", help="output json", action="store_true") args = parser.parse_args() username, password = parse_netrc() grades = get_grades(username, password) if args.mail or args.new or args.notify: new_grades = update_db(args.db, grades) if new_grades: msg = os.linesep.join([g[0] + ": " + g[2] for g in new_grades]) if args.mail: mail(args.mail, "New Grade in TUCaN", msg) elif args.notify: notify(msg) else: print(msg) else: if args.json: import json print(json.dumps(list(grades))) else: for grade in grades: print(grade[0] + ": " + grade[2])
true
6efdce5a32565c8978623d7ccfb371ed14586543
Python
JayJagadeshwar/python_programming
/mypython/def_fuc.py
UTF-8
123
3.390625
3
[]
no_license
def function(): a, b = 1, 2 if a > b: print("jaddu") elif a == b: print("jaggu") else: print("jason") function()
true
f3f808fe8c3b77b4b42a62e84a39b02f5f8a42d8
Python
pycaret/pycaret
/pycaret/internal/preprocess/time_series/forecasting/preprocessor.py
UTF-8
12,435
2.609375
3
[ "MIT" ]
permissive
from typing import Optional, Union from sklearn.preprocessing import ( MaxAbsScaler, MinMaxScaler, RobustScaler, StandardScaler, ) from sktime.transformations.compose import ColumnwiseTransformer from sktime.transformations.series.adapt import TabularToSeriesAdaptor from sktime.transformations.series.boxcox import BoxCoxTransformer, LogTransformer from sktime.transformations.series.cos import CosineTransformer from sktime.transformations.series.exponent import ExponentTransformer, SqrtTransformer from sktime.transformations.series.impute import Imputer from pycaret.utils.time_series import TSExogenousPresent class TSForecastingPreprocessor: """Class for preprocessing Time Series Forecasting Experiments.""" def _imputation( self, numeric_imputation_target: Optional[Union[str, int, float]], numeric_imputation_exogenous: Optional[Union[str, int, float]], exogenous_present: TSExogenousPresent, ): # Impute target ---- if numeric_imputation_target is not None: self._add_imputation_steps( numeric_imputation=numeric_imputation_target, target=True ) # Impute Exogenous ---- # Only add exogenous pipeline steps if exogenous variables are present. if ( exogenous_present == TSExogenousPresent.YES and numeric_imputation_exogenous is not None ): self._add_imputation_steps( numeric_imputation=numeric_imputation_exogenous, target=False ) def _add_imputation_steps( self, numeric_imputation: Union[str, int, float], target: bool = True ): """Perform numeric imputation of missing values. Parameters ---------- numeric_imputation : Union[str, int, float] The method to be used for imputation. If str, then passed as is to the underlying `sktime` imputer. Allowed values are: "drift", "linear", "nearest", "mean", "median", "backfill", "bfill", "pad", "ffill", "random" If int or float, imputation method is set to "constant" with the given value. target : bool, optional If True, imputation is added to the target variable steps If False, imputation is added to the exogenous variable steps, by default True Raises ------ ValueError (1) `numeric_imputation` is of type str but not of one of the allowed values. (2) `numeric_imputation` is not of one of the allowed types. """ type_ = "Target" if target else "Exogenous" self.logger.info(f"Set up imputation for {type_} variable(s).") if isinstance(numeric_imputation, str): allowed_values = [ "drift", "linear", "nearest", "mean", "median", "backfill", "bfill", "pad", "ffill", "random", ] if numeric_imputation not in allowed_values: raise ValueError( f"{type_} Imputation Type '{numeric_imputation}' not allowed." ) num_estimator = Imputer(method=numeric_imputation, random_state=self.seed) elif isinstance(numeric_imputation, (int, float)): num_estimator = Imputer(method="constant", value=numeric_imputation) else: raise ValueError( f"{type_} Imputation Type '{type(numeric_imputation)}' is not of allowed type." ) if target: self.transformer_steps_target.extend([("numerical_imputer", num_estimator)]) else: self.transformer_steps_exogenous.extend( [("numerical_imputer", num_estimator)] ) def _transformation( self, transform_target: Optional[Union[str, int, float]], transform_exogenous: Optional[Union[str, int, float]], exogenous_present: TSExogenousPresent, ): # Impute target ---- if transform_target is not None: self._add_transformation_steps(transform=transform_target, target=True) # Impute Exogenous ---- # Only add exogenous pipeline steps if exogenous variables are present. if ( exogenous_present == TSExogenousPresent.YES and transform_exogenous is not None ): self._add_transformation_steps(transform=transform_exogenous, target=False) def _add_transformation_steps(self, transform: str, target: bool = True): """Power transform the data to be more Gaussian-like. Parameters ---------- transform : str The method to be used for transformation. Allowed values and corresponding transformers are: "box-cox": BoxCoxTransformer(), "log": LogTransformer(), "sqrt": SqrtTransformer(), "exp": ExponentTransformer(), "cos": CosineTransformer(), target : bool, optional If True, transformation is added to the target variable steps If False, transformation is added to the exogenous variable steps, by default True Raises ------ ValueError (1) `transform` is not of one of the allowed values. (2) `transform` is not of one of the allowed types. """ type_ = "Target" if target else "Exogenous" self.logger.info(f"Set up transformation for {type_} variable(s).") if isinstance(transform, str): transform_dict = { "box-cox": BoxCoxTransformer(), "log": LogTransformer(), "sqrt": SqrtTransformer(), "exp": ExponentTransformer(), "cos": CosineTransformer(), } if transform not in transform_dict: raise ValueError( f"{type_} transformation method '{transform}' not allowed." ) else: raise ValueError( f"{type_} transformation method '{type(transform)}' is not of allowed type." ) if target: transformer = transform_dict[transform] self.transformer_steps_target.extend([("transformer", transformer)]) else: transformer = ColumnwiseTransformer(transform_dict[transform]) self.transformer_steps_exogenous.extend([("transformer", transformer)]) def _scaling( self, scale_target: Optional[Union[str, int, float]], scale_exogenous: Optional[Union[str, int, float]], exogenous_present: TSExogenousPresent, ): # Scale target ---- if scale_target: self._add_scaling_steps(scale=scale_target, target=True) # Scale Exogenous ---- # Only add exogenous pipeline steps if exogenous variables are present. if exogenous_present == TSExogenousPresent.YES and scale_exogenous is not None: self._add_scaling_steps(scale=scale_exogenous, target=False) def _add_scaling_steps(self, scale: str, target: bool = True): """Scale the data. Parameters ---------- scale : str The method to be used for scaling. Allowed values and corresponding scalers are: "zscore": StandardScaler(), "minmax": MinMaxScaler(), "maxabs": MaxAbsScaler(), "robust": RobustScaler(), target : bool, optional If True, scaling is added to the target variable steps If False, scaling is added to the exogenous variable steps, by default True Raises ------ ValueError (1) `scale` is not of one of the allowed values. (2) `scale` is not of one of the allowed types. """ type_ = "Target" if target else "Exogenous" self.logger.info(f"Set up scaling for {type_} variable(s).") if isinstance(scale, str): scale_dict = { "zscore": StandardScaler(), "minmax": MinMaxScaler(), "maxabs": MaxAbsScaler(), "robust": RobustScaler(), } if scale not in scale_dict: raise ValueError(f"{type_} scale method '{scale}' not allowed.") scaler = TabularToSeriesAdaptor(scale_dict[scale]) else: raise ValueError( f"{type_} transformation method '{type(scale)}' is not of allowed type." ) if target: self.transformer_steps_target.extend([("scaler", scaler)]) else: self.transformer_steps_exogenous.extend([("scaler", scaler)]) def _feature_engineering( self, fe_exogenous: Optional[list], exogenous_present: TSExogenousPresent, ): """Add feature engineering steps to the pipeline. NOTE: Only Applied to Reduced regression models (see note in Setup). But in these models, target feature engineering is done internal to the model. Hence target feature engineering is not done here. Parameters ---------- fe_exogenous : Optional[list] Feature Engineering Transformer to apply to exogenous variables. exogenous_present : TSExogenousPresent TSExogenousPresent.YES if exogenous variables are present in the data, TSExogenousPresent.NO otherwise. Exogenous feature transformers are only added if this is set to TSExogenousPresent.YES. """ # Transform exogenous variables ---- # Only add exogenous pipeline steps if exogenous variables are present, # but this is an exception. We may not have exogenous variables, but # these could be created using fe_exogenous, so we do not explicitly check # for the presence of exogenous variables to add this to the pipeline. # if exogenous_present == TSExogenousPresent.YES and fe_exogenous is not None: if fe_exogenous is not None: self._add_feat_eng_steps( fe_exogenous=fe_exogenous, target=False, ) def _add_feat_eng_steps(self, fe_exogenous: list, target: bool = True): """Add feature engineering steps for the data. Parameters ---------- fe_exogenous : list Feature engineering transformations to be applied to exogenous variables. target : bool, optional If True, feature engineering steps are added to the target variable steps (This is not implemented yet - see note in _feature_engineering) If False, feature engineering steps are added to the exogenous variable steps, by default True Raises ------ ValueError `fe_exogenous` is not of the correct type. """ type_ = "Target" if target else "Exogenous" self.logger.info(f"Set up feature engineering for {type_} variable(s).") if not isinstance(fe_exogenous, list): raise ValueError( f"{type_} Feature Engineering input must be of a List or sktime transformers." f"You provided {fe_exogenous}" ) if target: # This is not implemented yet - see note in _feature_engineering pass else: self.transformer_steps_exogenous.extend(fe_exogenous) # def _feature_selection( # self, # feature_selection_method, # feature_selection_estimator, # n_features_to_select, # ): # """Select relevant features.""" # self.logger.info("Set up feature selection.") # # TODO: Maybe implement https://github.com/pycaret/pycaret/issues/2230 # # self.pipeline.steps.append(("feature_selection", feature_selector)) # def _add_custom_pipeline(self, custom_pipeline): # """Add custom transformers to the pipeline.""" # self.logger.info("Set up custom pipeline.") # for name, estimator in normalize_custom_transformers(custom_pipeline): # self.pipeline.steps.append((name, TransformerWrapper(estimator)))
true
303fdbb5cae608216228cd3fdc3f57b2ce7f8dca
Python
asanchez19/intro-progra-q2
/20210603_clase6/tuplas.py
UTF-8
391
3.984375
4
[]
no_license
# Listas amigos = ['Sebas', 'Kevin', 'Pablo'] print(amigos) amigos.append('Ericka') print(amigos, type(amigos)) # Tuplas tupla = ('Sebas', 'Kevin', 'Maria') print(tupla, type(tupla)) print(tupla[0]) lista_tuplas = [tupla, ('Alejandro', 'Javier')] print(lista_tuplas[0][2]) # Las tuplas no se pueden modificar. # tupla.append('Pedrito') tupla = tupla + ('Pedrito',) print(tupla)
true
8dc81b244a3fada66c9838d874c445b20a3615fc
Python
azznggu/FlaskProject
/FlaskWebProject/FlaskWebProject/app/app.py
UTF-8
1,275
2.78125
3
[]
no_license
""" This script runs the application using a development server. It contains the definition of routes and views for the application. """ from flask import Flask, url_for, request, render_template, redirect app = Flask(__name__) # Make the WSGI interface available at the top level so wfastcgi can get it. wsgi_app = app.wsgi_app @app.route('/') def index(): """Renders a sample page.""" return render_template('index.html') @app.route('/about') def about(): return render_template('about.html') @app.route('/home/') def home(): return redirect('/') @app.route('/login', methods = ['GET', 'POST']) def login(): if request.method == 'POST': return 'login post' else: return 'login get' @app.route('/user/<username>') def profile(username): return '{}\'s profile'.format(username) @app.route('/param/<param>') def param(param): return "param: %s" % param @app.route('/home/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name = name) if __name__ == '__main__': import os HOST = os.environ.get('SERVER_HOST', 'localhost') try: PORT = int(os.environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.run(HOST, PORT)
true
bff55550027f75b5303b737b91161ac6305fcad1
Python
AbdulProjects/tools
/en.py
UTF-8
1,292
3.171875
3
[ "Apache-2.0" ]
permissive
#!/bin/python3 import urllib.parse, base64, sys # Coded By Abdul # Trying my best to keep the code simple. # this tool does URL and base64 encoding and decoding. # Usage: # - urlencoding: # python3 en.py # # type whatever text to urlencode it or you can simply do : # # echo "TEXT" | python3 en.py # # - base64 encoding : # # python3 en.py # # before starting the actaul text to encode type "b64 " at the begining of the string. or you can simply do : # # echo "b64 TEXT" | python3 en.py # Decoding # add the option '-d' : # python3 en.py -d # # same procedure as encoding , no need to explain more. decode = False if len(sys.argv) >1 and sys.argv[1] == "-d": decode=True while True: output="" try: text = input().strip() # check if Base64 if(text.startswith("b64 ")): if decode == True: try: output = base64.b64decode(text[4:]) .decode('ascii') except (base64.binascii.Error,UnicodeDecodeError) as e: print("\n",e) else: output = base64.b64encode(text[4:].encode('ascii')).decode('ascii') else: if decode==True: output = urllib.parse.unquote(text) else: output = urllib.parse.quote(text) print("\n"+output) print("-"*30+"\n") except (KeyboardInterrupt,EOFError): break
true
cece14fe28c260c4904418f9c5b759f8d02de7aa
Python
Aasthaengg/IBMdataset
/Python_codes/p03438/s056199071.py
UTF-8
427
3.15625
3
[]
no_license
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) ret = [0] * n for i in range(n): ret[i] = b[i] - a[i] ret = sorted(ret) cnt = 0 for i, val in enumerate(ret): if val < 0: cnt += abs(val) ret[i] = 0 elif val % 2 == 1: cnt += 1 ret[i] += 1 for i, val in enumerate(ret): cnt -= val // 2 if cnt <= 0: print("Yes") else: print("No")
true
88a5f6c0d000a034d9530f48b3ca034d1e4d382b
Python
erminpour/junkcode
/Python/socketServer.py
UTF-8
1,127
3.078125
3
[]
no_license
#!/usr/bin/python -tt import socket import time def main(): ## Create server socket socketfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) hostname = '' portnum = 31337 ## set socket options before bind() socketfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) socketfd.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) socketfd.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 20) socketfd.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5) socketfd.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 6) ## bind() to hostname/port tuple socketfd.bind((hostname, portnum)) ## listen() and change form active to ## passive socket with backlog of 5 socketfd.listen(5) while True: clientfd, remoteAddress = socketfd.accept() IPADDR, PORT = remoteAddress print "Connected! IPADDR = %s, PORT = %d" % (IPADDR, PORT) clientfd.send("Connected! Sleeping...\n") time.sleep(10) # 1 minute clientfd.send("That's all folks!\n") clientfd.close() if __name__ == '__main__': main()
true
d4b54c7f5778929518c1429fa735710af624de6f
Python
RiEnRiu/rer_learning_code
/learn_tf/p076_conv2d.py
UTF-8
5,427
2.6875
3
[]
no_license
#-*-coding:utf-8-*- # book: <Neural Network Programming with Tensorflow> # authors: Manpreet Singh Ghotra, Rajdeep Dua import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np GPU_CONFIG = tf.ConfigProto() GPU_CONFIG.gpu_options.allow_growth=True sess = tf.Session(config=GPU_CONFIG) # conv2d: whether rotate kernel? def test_whether_rotate_kernel(): i = tf.constant([[1.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0]], dtype=tf.float32) k = tf.constant([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]], tf.float32) # kernel: kernel = tf.reshape(k, [3,3,1,1], name='kernel') # image: NHWC image = tf.reshape(i, [1,4,5,1], name='image') _strides = [1,1,1,1] res = tf.nn.conv2d(image, kernel, strides=_strides, padding='VALID') # with tf.Session(config=GPU_CONFIG) as sess: ri,rk,rc = sess.run([image,kernel,res]) print('image shape: {0}'.format(ri.shape)) print(np.squeeze(ri)) print('kernel shape: {0}'.format(rk.shape)) print(np.squeeze(rk)) print('ans shape: {0}'.format(rc.shape)) print(np.squeeze(rc)) print('conv2d: not rotate kernel.') def test_strides_and_padding(): i = tf.constant([ [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], [0.1, 1.1, 2.1, 3.1, 4.1, 5.1], [0.2, 1.2, 2.2, 3.2, 4.2, 5.2], [0.3, 1.3, 2.3, 3.3, 4.3, 5.3], [0.4, 1.4, 2.4, 3.4, 4.4, 5.4], [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]], dtype=tf.float32) k = tf.constant([ [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0]], tf.float32) # kernel: HWCN kernel = tf.reshape(k, [3,3,1,1], name='kernel') # image: NHWC image = tf.reshape(i, [1,6,6,1], name='image') _strides = [1,3,3,1] res_valid = tf.nn.conv2d(image, kernel, strides=_strides, padding='VALID') res_same = tf.nn.conv2d(image, kernel, strides=_strides, padding='SAME') with tf.Session(config=GPU_CONFIG) as sess: ri,rk,rcs,rcv = sess.run([image,kernel,res_same,res_valid]) print('image shape: {0}'.format(ri.shape)) print(np.squeeze(ri)) print('kernel shape: {0}'.format(rk.shape)) print(np.squeeze(rk)) print('ans(padding=SAME) shape: {0}'.format(rcs.shape)) print(np.squeeze(rcs)) print('ans(padding=VALID) shape: {0}'.format(rcv.shape)) print(np.squeeze(rcv)) print('conv2d(padding=SAME):') print(' 1. fill the image with 0 so that it can conv2d into the same shape') print(' 2. run conv2d') print(' 3. find the value according to the strides') print('conv2d(padding=VALID):') print(' 1. run conv2d') print(' 2. find the value according to the strides') def test_train_mnist(): batch_size = 50 learning_rate = 0.01 image = tf.placeholder(tf.float32,[batch_size,28,28,1]) label = tf.placeholder(tf.float32,[batch_size,10]) ker1 = tf.random_uniform([5, 5, 1, 12], minval=0.1, maxval=0.5, dtype=tf.float32) ker1 = tf.Variable(ker1) bias1 = tf.Variable(tf.zeros((1,1,1,12),tf.float32)) conv1 = tf.nn.conv2d(image, ker1, strides=[1,1,1,1], padding='SAME') relu1 = tf.nn.relu(conv1+bias1) pool1 = tf.nn.max_pool(relu1,(1,2,2,1),strides=(1,2,2,1),padding='SAME') ker2 = tf.random_uniform([5, 5, 12, 20], minval=0.1, maxval=0.5, dtype=tf.float32) ker2 = tf.Variable(tf.Variable(ker2)) bias2 = tf.zeros((1,1,1,20),tf.float32) conv2 = tf.nn.conv2d(pool1, ker2, strides=[1,1,1,1], padding='SAME') relu2 = tf.nn.relu(conv2+bias2) pool2 = tf.nn.max_pool(relu2,(1,2,2,1),strides=(1,2,2,1),padding='SAME') pool2 = tf.reshape(pool2,(batch_size,-1)) wfc1 = tf.random_uniform((980,100), minval=0.1, maxval=0.5, dtype=tf.float32) wfc1 = tf.Variable(wfc1) bfc1 = tf.Variable(tf.zeros((batch_size,100),tf.float32)) fc1 = tf.matmul(pool2,wfc1)+bfc1 relu3 = tf.nn.relu(fc1) wfc2 = tf.random_uniform((100,10), minval=0.1, maxval=0.5, dtype=tf.float32) wfc2 = tf.Variable(wfc2) bfc2 = tf.Variable(tf.zeros((batch_size,10),tf.float32)) fc2 = tf.matmul(relu3,wfc2)+bfc2 softmaxloss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=label,logits=fc2) step = tf.train.GradientDescentOptimizer(learning_rate).minimize(softmaxloss) # sess = tf.InteractiveSession() acct_mat = tf.equal(tf.arg_max(softmaxloss,1),tf.arg_max(label,1)) acct_ret = tf.reduce_sum(tf.cast(acct_mat,tf.float32)) sess.run(tf.global_variables_initializer()) data = input_data.read_data_sets('MNIST_data/',one_hot=True) for i in range(1000): batch_xs, batch_ys = data.train.next_batch(batch_size) batch_xs = batch_xs.reshape((batch_size,28,28,1)) sess.run(step, feed_dict={image:batch_xs,label:batch_ys}) if i%10000==0: res = sess.run(acct_ret,feed_dict={ image:data.test.images.reshape((-1,28,28,1))[:50],\ label:data.test.labels[:50]}) print(res) #test_whether_rotate_kernel() #print('') #test_strides_and_padding() #print('') test_train_mnist() print('') sess.close()
true
a657b5193a907fddc1e3040667f7ea8d9a0aa1f4
Python
plan-bug/LeetCode-Challenge
/microcephalus7/medium/1605.py
UTF-8
650
3.1875
3
[]
no_license
# 천천히 법칙을 보아야 한다 # class Solution: def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: res = [[0 for j in range(len(colSum))] for i in range(len(rowSum))] # 여기까지 풀었음 i = 0 j = 0 while i <len(rowSum) and j<len(colSum): res[i][j] = min(rowSum[i],colSum[j]) if rowSum[i] == colSum[j]: i += 1 j+=1 elif rowSum[i] > colSum[j]: rowSum[i]-=colSum[j] j+=1 else: colSum[j] -= rowSum[i] i += 1 return res
true
33cc218823db58b64ba0991f17b6298d169976d0
Python
amarmulyak/Python-Core-for-TA
/lessons/lesson04/examples4.py
UTF-8
3,085
3.25
3
[]
no_license
# # print("-" * 17) # # for i in range(10): # # # # print(f"|\t{i}\t|\t{i*2}\t| ") # # print("-"*17) # # a = 1 # b = 3 # h = 1 # # # x = a # # r = int((b-a)/h ) # # for x in range(r): # # x+=h # # import math # while x <=b: # si = 1 # s = 0 # k = 1 # while si > 10 ** (-5): # si = k * (k + 1) * (x ** k) # print(si) # s+=si # k+=1 # y = 2*x/((1-x)**3) # p = math.fabs((s-y)/y)*100 # print(f"|\t{x}\t|\t{s}\t|\t{y}\t|\t{p}\t|") # x+=h # # start = 0 # finish = 10 # while start < finish: # print(start) # start += 1 # else: # print ("The end") # l = [1,2,3] # # while len(l)>0: # print(l) # l.pop() # l = [1,2,3] # while l: # print(l) # l.pop() # l = "[1,2,3]" # while l: # print(l) # l = l[:-1] # l = 5 # while l: # print(l) # l -= 1 # else: # print(l) # a = 0 # while a < 10: # b = 0 # while b < 5: # print(a, b) # b += 1 # a += 1 # print(b) # a = "abc" # for i in a: # print(i) # for i in range(len(a)): # print(i, a[i]) # a = [1,2,3,4,5] # for i in a: # print(i) # i **= i # print(i) # print(a) # a = [[1, 2], 2, 3, 4, 5] # for i in a: # print(i) # if (isinstance(i, list)): # i.append("bvdj") # print(a) # a = [1, 2, 3, 4, 5] # for i in a: # print(i) # if i == 4: # a.insert(2, 9) # print(a) # a = [i for i in range(10)] # print(a) # a = [i for i in range(10, 30)] # print(a) # a = [i for i in range(10, 30, 5)] # print(a) # for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: # print(i) # n = 3 # for i in range(n): # print(f"n:{n}") # n += 1 # print(f"n:{n}") # print(f"i:{i}") # for i in range(10): # print(f"{i}") # if i % 2: # continue # print(f"i:{i}") # else: # print("end") # # i=0 # while i < 10: # print(f"{i}") # i+=1 # if i % 2: # continue # print(f"i:{i}") # else: # print("end") # for i in range(10): # print(f"{i}") # if i % 2: # break # print(f"i:{i}") # else: # print("end_for") # print("===========") # i = 0 # while i < 10: # print(f"{i}") # i += 1 # if i % 2: # break # print(f"i:{i}") # else: # print("end") # # for i in range(5): # for j in range(i, i+5): # print(f"{i}-{j}") # if j%3: # break # if True: # break # # for i in range(3): # #ToDo # "dfsd" # # 5! # 1*2*3*4*5 ##### ==3== # for n in range(1, 6): # print(f"{n * (n + 2)}x^{n}") # # x = 0.4 # S = 0 # s = 1 # n = 1 # while s > 10 ** (-5): # s = n * (n + 2) * (x ** n) # n += 1 # S += s # print(f"S:{S} s:{s}") # print(f"y={(x*(3-x))/((1-x)**3)}") import math a = 0.1 b = 0.55 h = 0.05 e = 10**(-5) print(a, b, h, e) x = a while x <= b: S = 1 s = 1 k = 0 # print(x) while s > e: # print(x) s=(3+2*k)*(x**(k+1)) S+=s k += 1 y = (1+x)/((1-x)**2) p = abs((S-y)/y)*100 print(f"\t{x:.2f}\t{S:.3f}\t{y:.3f}\t{p:.3f}") x += h
true
e8df0dbd0f9c5e1126b1dc4125cc86e8b96f0834
Python
patel/Advent-of-code
/2016/p23/solution.py
UTF-8
2,709
2.8125
3
[]
no_license
from pprint import pprint from itertools import chain def get_a_after_processing_instructions(instructions, a=0, b=0, c=0, d=0): registers = {'a': a, 'b': b, 'c': c, 'd': d} current_index = 0 while True: if current_index >= len(instructions): break instruction_line = instructions[current_index] instruction, params = instruction_line if instruction == 'cpy': param1, param2 = params.split(' ') if param1 in registers: registers[param2] = registers[param1] elif param2 in registers: registers[param2] = int(param1) if instruction == 'inc': registers[params] += 1 if instruction == 'dec': registers[params] -= 1 if instruction == 'jnz': param1, param2 = params.split(' ') jmp_cnt = registers[param2] if param2 in registers else int(param2) if (param1 in registers and registers[param1] != 0) or (param1 not in registers and param1 != '0'): current_index += jmp_cnt if jmp_cnt < 0: if all(map(lambda x: x[0] in ['inc', 'dec'], instructions[current_index:current_index-jmp_cnt])): for l_inst, l_param in instructions[current_index:current_index - jmp_cnt]: if l_param == param1: continue if l_inst == 'inc': registers[l_param] += abs(registers[param1]) else: registers[l_param] -= abs(registers[param1]) registers[param1] = 0 current_index -= (jmp_cnt) current_index += 1 continue if instruction == 'tgl': jmp_cnt = registers[params] if 0 <= current_index+jmp_cnt < len(instructions): instruction_toggle, params_toggle = instructions[current_index+jmp_cnt] params_list = params_toggle.split(' ') if len(params_list) == 1: instructions[current_index + jmp_cnt][0] = {'inc': 'dec'}.get(instruction_toggle, 'inc') if len(params_list) == 2: instructions[current_index + jmp_cnt][0] = {'jnz': 'cpy'}.get(instruction_toggle, 'jnz') current_index += 1 return registers['a'] ip = open('input.txt', 'r').read() f_ip = [l.split(' ', 1) for l in ip.split('\n')] print get_a_after_processing_instructions(f_ip, a=7) f_ip = [l.split(' ', 1) for l in ip.split('\n')] print get_a_after_processing_instructions(f_ip, a=12)
true
18270501d379a3ae3a71b55826aedc8de57e4ba9
Python
ChrisPolicheri/Survive2020
/main.py
UTF-8
3,634
3.46875
3
[]
no_license
print(''' .--""--.___.._ ( <__> ) `-. |`--..--'|'SOLD | | :| OUT' / | :|--""-./ `.__ __;' "" ''') print("WELCOME TO 2020") print("Your mission is to survive!") choice1 = input( 'Take that trip, you might live. Type "trip". Safely stay stuck at home. Type "home"\n' ).lower() if choice1 == "home": choice2 = input(''' ) ( ( .^. \) ) .'.^.'. (/ .'.'---'.'. _\)_ .'.'-------'.'. (__)() .'.'-,=======.-'.'. (_)__) .'.'---| | |---'.'. (__)_),'.'-----| | |-----'.'. ()__.'.'-------|___|___|-------'.'. (_.'.'---------------------------'.'. .'.'-------------------------------'.'. """""|====..====.=======.====..====|""""" ()_)| || |.-----.| || | (_)_| || || || || | (...|____||____||_____||____||____| (_)_(|----------| _____o|----------| (_)(_|----------|| ||----------| (__)(|----------||_____||----------| (_)(_|---------|"""""""""|---------| ()()(|--------|"""""""""""|--------| You\'re sitting at home. Type "blm" to get out in the crowds, support the movement! or Type "crafty" to stay at home.\n''' ).lower() if choice2 == "crafty": choice3 = input( 'Your craftiness consists of "painting", "sewing", or "knife throwing". Choose one.\n' ).lower() if choice3 == "painting": print( "You end up painting street sign designs on live animals for TikTok and get quite a following. You're Rich, you Win! Game Over" ) elif choice3 == "sewing": print( "You sew facemasks at a record rate saving millions. You're a Hero, you Win! Game Over" ) elif choice3 == "knife throwing": print( "Your awesome knife throwing skills make the Murder Hornets so jealous they end up just leaving Earth. You're a Hero, you Win! Game Over" ) else: print( "That wasn't even an option! You get Covid and die! Game Over") else: print(''' ________________ \ __ / __ \_____()_____/ / ) '============` / / #---\ /---# / / (# @\| |/@ #) / / \ (_) / / / |\ '---` /| / / _______/ \_____// \____/ o_| / \ / \ / / o_| / | o| / o_| / | _____ | / / \ \ You proudly protest with thousands and support the BLM movement but you were careful and masked up so you were fine... But then you decide to travel for Thanksgiving catch Covid and die. Game Over ''') else: print(''' mm###########mmm m####################m m#####`"#m m###"""'######m ######*" " " "mm####### m####" , m"#######m m#### m*" ,' ; , "########m ####### m* m |#m ; m ######## |######### mm# |#### #m##########| ###########| |######m############ "##########| |##################" "######### |## /##############" ########| # |/ m########### "####### ###########" You take that trip go to a giant beach party catch Covid and die! Game Over''' )
true
f80954be792db3da7281cc418d01a6c933ac88de
Python
JimOhman/FFR135-FIM720-Artificial-neural-networks
/Homework 3/Restricted Boltzmann machine/main.py
UTF-8
4,786
2.609375
3
[]
no_license
from network import RestrictedBoltzmanMachine from datasets import get_bar_stripes_dataset import matplotlib.pyplot as plt from copy import deepcopy import numpy as np import ray def get_probs_model(rbm, dataset, time_steps=20, num_samples=500): state_counts = np.zeros(len(dataset)) size = (num_samples, rbm.num_visible_units) random_states = np.random.choice([-1, 1], size) for n in range(num_samples): rbm.visible_units = random_states[n] for _ in range(time_steps): rbm.reconstruction_step() for idx, state in enumerate(dataset): recon_state = rbm.visible_units is_equal = np.array_equal(recon_state, state) if is_equal: state_counts[idx] += 1 break if is_equal: break probs_model = state_counts / num_samples return probs_model def estimate_kl_div(rbm, probs_data, dataset, time_steps=20, num_samples=500): probs_model = get_probs_model(rbm, dataset, time_steps, num_samples) kl_div = np.sum(probs_data * np.log(probs_data / (probs_model+10**(-8)))) return kl_div @ray.remote def run_cdk(rbm, dataset, epochs=100, learning_rate=0.01, k=100, metrics=[], verbose=False): rbm = deepcopy(rbm) metrics_data = {key: [] for key in metrics} for epoch in range(epochs): for state in dataset: rbm.update_weights(state, learning_rate, recon_steps=k) if metrics: if metrics_data.get('kl-divergence') is not None: kl_div = estimate_kl_div(rbm, probs_data, dataset) metrics_data['kl-divergence'].append(kl_div) if metrics_data.get('energy') is not None: energy = rbm.energy() metrics_data['energy'].append(energy) if verbose: print("-----epoch {}-----".format(epoch)) for key, values in metrics_data.items(): print(" {}: {:.3f}".format(key, values[-1])) print() return rbm, metrics_data def plot_results(results, figsize=(10, 5)): fig, axes = plt.figure(figsize=figsize), [] num_metrics = len(results[0][1]) for idx in range(num_metrics): axes.append(plt.subplot(1, num_metrics, idx+1)) for rbm, metrics_data in results: label = 'hidden neurons: {}'.format(rbm.num_hidden_units) for idx, (key, values) in enumerate(metrics_data.items()): axes[idx].plot(values, label=label) axes[idx].set_ylabel('{}'.format(key)) axes[idx].set_xlabel('epochs') axes[idx].legend() plt.tight_layout() plt.show() def print_results(results, dataset): print("\n-----final results-----\n") for rbm, metrics_data in results: probs_model = get_probs_model(rbm, dataset) print("{} hidden units".format(rbm.num_hidden_units)) for key, values in metrics_data.items(): print(" {}: {:.5f}".format(key, values[-1])) print() def show_pattern_completion(rbm, dataset, pattern_idx, figsize=(10, 5)): fig, ax = plt.subplots(nrows=2, ncols=11, figsize=figsize) ax[0, 0].set_ylabel('untrained', fontsize=12) ax[1, 0].set_ylabel('trained', fontsize=12) imshow_params = {'cmap': 'gray_r', 'vmin':-1, 'vmax':1} size = (rbm.num_hidden_units, rbm.num_visible_units) untrained_rbm = RestrictedBoltzmanMachine(*size, dataset) pattern = dataset[pattern_idx] distorted_pattern = pattern.copy().reshape(3,3) distorted_pattern[:, 1:] = 0 distorted_pattern = distorted_pattern.ravel() rbm.visible_units = distorted_pattern.copy() untrained_rbm.visible_units = distorted_pattern.copy() for t in range(11): ax[0, t].imshow(untrained_rbm.visible_units.reshape(3,3), **imshow_params) ax[1, t].imshow(rbm.visible_units.reshape(3,3), **imshow_params) rbm.reconstruction_step() untrained_rbm.reconstruction_step() for k in range(2): ax[k, t].axhline(y=0.5, c='white') ax[k, t].axhline(y=1.5, c='white') ax[k, t].axvline(x=0.5, c='white') ax[k, t].axvline(x=1.5, c='white') ax[k, t].set_xticks([]) ax[k, t].set_yticks([]) ax[k, t].set_title('t = {}'.format(t)) plt.subplots_adjust(hspace=-0.5) plt.show() if __name__ == '__main__': ray.init() dataset, probs_data = get_bar_stripes_dataset() cdk_params = {'k': 100, 'epochs': 500, 'learning_rate': 0.001, 'metrics': ['kl-divergence'], 'verbose': True} num_visible_units = dataset[0].size all_num_hidden_units = [8] all_rbms = [] for num_hidden_units in all_num_hidden_units: size = (num_hidden_units, num_visible_units) all_rbms.append(RestrictedBoltzmanMachine(*size, dataset)) results = ray.get([run_cdk.remote(rbm, dataset, **cdk_params) for rbm in all_rbms]) plot_results(results, figsize=(10, 5)) print_results(results, dataset) rbm = results[-1][0] show_pattern_completion(rbm, dataset, pattern_idx=-1)
true
7fcd8d8da391e49977905fe02047477a4eae5cfb
Python
smazanek/LifeGuard.IO
/Implementation/Conv3D_UCF11.py
UTF-8
9,462
2.640625
3
[]
no_license
from __future__ import print_function import sys import os import csv import numpy as np from random import randint from PIL import Image import imageio import cntk as C from cntk.logging import * from cntk.debugging import set_computation_network_trace_level # Paths relative to current python file. abs_path = os.path.dirname(os.path.abspath(__file__)) data_path = os.path.join(abs_path, "..", "VideoDataset", "DataSets", "UCF11 and OUR OWN DATASET") model_path = os.path.join(abs_path, "Models") # Define the reader for both training and evaluation action. class VideoReader(object): ''' A simple VideoReader: It iterates through each video and select 16 frames as stacked numpy arrays. Similar to http://vlg.cs.dartmouth.edu/c3d/c3d_video.pdf ''' def __init__(self, map_file, label_count, is_training, limit_epoch_size=sys.maxsize): ''' Load video file paths and their corresponding labels. ''' self.map_file = map_file self.label_count = label_count self.width = 112 self.height = 112 self.sequence_length = 16 self.channel_count = 3 self.is_training = is_training self.video_files = [] self.targets = [] self.batch_start = 0 map_file_dir = os.path.dirname(map_file) with open(map_file) as csv_file: data = csv.reader(csv_file) for row in data: self.video_files.append(os.path.join(map_file_dir, row[0])) target = [0.0] * self.label_count target[int(row[1])] = 1.0 self.targets.append(target) self.indices = np.arange(len(self.video_files)) if self.is_training: np.random.shuffle(self.indices) self.epoch_size = min(len(self.video_files), limit_epoch_size) def size(self): return self.epoch_size def has_more(self): if self.batch_start < self.size(): return True return False def reset(self): if self.is_training: np.random.shuffle(self.indices) self.batch_start = 0 def next_minibatch(self, batch_size): ''' Return a mini batch of sequence frames and their corresponding ground truth. ''' batch_end = min(self.batch_start + batch_size, self.size()) current_batch_size = batch_end - self.batch_start if current_batch_size < 0: raise Exception('Reach the end of the training data.') inputs = np.empty(shape=(current_batch_size, self.channel_count, self.sequence_length, self.height, self.width), dtype=np.float32) targets = np.empty(shape=(current_batch_size, self.label_count), dtype=np.float32) for idx in range(self.batch_start, batch_end): index = self.indices[idx] inputs[idx - self.batch_start, :, :, :, :] = self._select_features(self.video_files[index]) targets[idx - self.batch_start, :] = self.targets[index] self.batch_start += current_batch_size return inputs, targets, current_batch_size def _select_features(self, video_file): ''' Select a sequence of frames from video_file and return them as a Tensor. ''' video_reader = imageio.get_reader(video_file, 'ffmpeg') num_frames = len(video_reader) if self.sequence_length > num_frames: raise ValueError('Sequence length {} is larger then the total number of frames {} in {}.'.format(self.sequence_length, num_frames, video_file)) # select which sequence frames to use. step = 1 expanded_sequence = self.sequence_length if num_frames > 2*self.sequence_length: step = 2 expanded_sequence = 2*self.sequence_length seq_start = int(num_frames/2) - int(expanded_sequence/2) if self.is_training: seq_start = randint(0, num_frames - expanded_sequence) frame_range = [seq_start + step*i for i in range(self.sequence_length)] video_frames = [] for frame_index in frame_range: video_frames.append(self._read_frame(video_reader.get_data(frame_index))) return np.stack(video_frames, axis=1) def _read_frame(self, data): ''' Based on http://vlg.cs.dartmouth.edu/c3d/c3d_video.pdf We resize the image to 128x171 first, then selecting a 112x112 crop. ''' if (self.width >= 171) or (self.height >= 128): raise ValueError("Target width need to be less than 171 and target height need to be less than 128.") image = Image.fromarray(data) image.thumbnail((171, 128), Image.ANTIALIAS) center_w = image.size[0] / 2 center_h = image.size[1] / 2 image = image.crop((center_w - self.width / 2, center_h - self.height / 2, center_w + self.width / 2, center_h + self.height / 2)) norm_image = np.array(image, dtype=np.float32) norm_image -= 127.5 norm_image /= 127.5 # (channel, height, width) return np.ascontiguousarray(np.transpose(norm_image, (2, 0, 1))) # Creates and trains a feedforward classification model for UCF11 action videos def conv3d_ucf11(train_reader, test_reader, max_epochs=30): # Replace 0 with 1 to get detailed log. set_computation_network_trace_level(0) # These values must match for both train and test reader. image_height = train_reader.height image_width = train_reader.width num_channels = train_reader.channel_count sequence_length = train_reader.sequence_length num_output_classes = train_reader.label_count # Input variables denoting the features and label data input_var = C.input_variable((num_channels, sequence_length, image_height, image_width), np.float32) label_var = C.input_variable(num_output_classes, np.float32) # Instantiate simple 3D Convolution network inspired by VGG network # and http://vlg.cs.dartmouth.edu/c3d/c3d_video.pdf with C.default_options (activation=C.relu): z = C.layers.Sequential([ C.layers.Convolution3D((3,3,3), 64, pad=True), C.layers.MaxPooling((1,2,2), (1,2,2)), C.layers.For(range(3), lambda i: [ C.layers.Convolution3D((3,3,3), [96, 128, 128][i], pad=True), C.layers.Convolution3D((3,3,3), [96, 128, 128][i], pad=True), C.layers.MaxPooling((2,2,2), (2,2,2)) ]), C.layers.For(range(2), lambda : [ C.layers.Dense(1024), C.layers.Dropout(0.5) ]), C.layers.Dense(num_output_classes, activation=None) ])(input_var) # loss and classification error. ce = C.cross_entropy_with_softmax(z, label_var) pe = C.classification_error(z, label_var) # training config train_epoch_size = train_reader.size() train_minibatch_size = 2 # Set learning parameters lr_per_sample = [0.01]*10+[0.001]*10+[0.0001] lr_schedule = C.learning_rate_schedule(lr_per_sample, epoch_size=train_epoch_size, unit=C.UnitType.sample) momentum_time_constant = 4096 mm_schedule = C.momentum_as_time_constant_schedule([momentum_time_constant]) # Instantiate the trainer object to drive the model training learner = C.momentum_sgd(z.parameters, lr_schedule, mm_schedule, True) progress_printer = ProgressPrinter(tag='Training', num_epochs=max_epochs) trainer = C.Trainer(z, (ce, pe), learner, progress_printer) log_number_of_parameters(z) ; print() # Get minibatches of images to train with and perform model training for epoch in range(max_epochs): # loop over epochs train_reader.reset() while train_reader.has_more(): videos, labels, current_minibatch = train_reader.next_minibatch(train_minibatch_size) trainer.train_minibatch({input_var : videos, label_var : labels}) trainer.summarize_training_progress() # Test data for trained model epoch_size = test_reader.size() test_minibatch_size = 2 # process minibatches and evaluate the model metric_numer = 0 metric_denom = 0 minibatch_index = 0 test_reader.reset() while test_reader.has_more(): videos, labels, current_minibatch = test_reader.next_minibatch(test_minibatch_size) # minibatch data to be trained with metric_numer += trainer.test_minibatch({input_var : videos, label_var : labels}) * current_minibatch metric_denom += current_minibatch # Keep track of the number of samples processed so far. minibatch_index += 1 print("") print("Final Results: Minibatch[1-{}]: errs = {:0.2f}% * {}".format(minibatch_index+1, (metric_numer*100.0)/metric_denom, metric_denom)) print("") return metric_numer/metric_denom if __name__=='__main__': num_output_classes = 11 train_reader = VideoReader(os.path.join(data_path, 'train_map.csv'), num_output_classes, True) test_reader = VideoReader(os.path.join(data_path, 'test_map.csv'), num_output_classes, False) conv3d_ucf11(train_reader, test_reader)
true
16a2791035d9d0fcc18dda540417f2b6a08de7b3
Python
wiryawan46/Deep-Food
/TumFoodCam/classification/global_features/histogram.py
UTF-8
5,544
2.640625
3
[ "MIT" ]
permissive
import time import cv2 as cv from misc import utils from classification.feature_classifier import FeatureClassifier from misc.color_space import ColorSpace from misc.model_tester import ModelTester, get_mean_accuracy from data_io.testdata import TestData import numpy as np from math import sqrt import data_io.settings as Settings import logging class HistogramClassifier(FeatureClassifier): """Histogram classifier class that uses color information for classification. """ def __init__(self, testDataObj, svmType=None, name="", description=""): super(HistogramClassifier, self).__init__(svmType, Settings.H_SVM_PARAMS, testDataObj, name, grayscale=False, description=description, imageSize=Settings.H_IMAGE_SIZE) self.svmType = svmType self.__svms = {} #Segment the testData in tow parts (1 train, 1 test) self.testData.segment_test_data(Settings.H_TESTDATA_SEGMENTS) # 2 is a special case. In this case part the image in two pieces vertically if Settings.H_IMAGE_SEGMENTS == 2: self.imageCols = 2 self.imageRows = 1 else: self.imageCols = self.imageRows = sqrt(Settings.H_IMAGE_SEGMENTS) def train_and_evaluate(self, save=True): # create classifier tester to evaluate the results from the cross validation runs. self.tester = ModelTester(self) iterationResults = [] accuracies = [] confMatrices = [] while self.testData.new_segmentation(): start = time.clock() self.create_SVMs() self.trained = True computeTime = time.clock() - start # evaluate if Settings.G_EVALUATION_DETAIL_HIGH: results = self.tester.test_classifier(["trainSVM", "test"]) #extract interesting results trainSVMAccuracy = results["trainSVM"][0] trainSVMLoss = results["trainSVM"][1] else: results = self.tester.test_classifier(["test"]) trainSVMAccuracy = "?" trainSVMLoss = "?" iterationResults.append(results) testAccuracy = results["test"][0] testLoss = results["test"][1] row = [self.testData.crossValidationIteration, testLoss, testAccuracy, trainSVMLoss, trainSVMAccuracy, computeTime] accuracies.append(row) if Settings.G_EVALUATION_DETAIL_HIGH: confMatrices.append(self.tester.compute_confusion_matrix(export=False)) print "{0}/{1} Cross Validation Iteration: Accuracy: {2}".format(self.testData.crossValidationIteration, self.testData.crossValidationLevel, testAccuracy) header = ["Iteration", "test error", "test accuracy", "train error", "train accuracy", "compute time"] self.show_evaluation_results(accuracies, confMatrices, header) if save: self.export_evaluation_results(iterationResults, confMatrices) self.save() print "\nTraining of {0} done.".format(self.name) return get_mean_accuracy(accuracies) def create_feature_vector(self, image): """ Creates the feature vector out of histograms.""" # convert image depending on desired color space for the histogram temp = [] colors = ("b", "g", "r") try: if Settings.H_COLOR_SPACE == ColorSpace.HSV: temp = cv.cvtColor(image, cv.COLOR_BGR2HSV) colors = ("h", "s", "v") elif Settings.H_COLOR_SPACE == ColorSpace.RGB: temp = cv.cvtColor(image, cv.COLOR_BGR2RGB) colors = ("r", "g", "b") else: temp = image except: logging.exception("Could not convert image to {0}.".format(Settings.H_COLOR_SPACE)) cv.imshow("Error CV", image) utils.display_images([image], None, ["Error"], 1, 1) # split image into x different parts. imageParts = [] height, width = temp.shape[:2] partHeight = int(height / self.imageRows) partWidth = int(width / self.imageCols) scaleMaxPossibleValue = partWidth * partHeight # modify height and width in case partHeight and partWidth don't add up to the real width and height. # in this case the image would be cut into more than x parts because some leftover pixels would be included. height = int(partHeight * self.imageRows) width = int(partWidth * self.imageCols) for y in xrange(0, height, partHeight): for x in xrange(0, width, partWidth): imageParts.append(utils.crop_image(temp, x, y, partWidth, partHeight)) histogram = [] for img in imageParts: for i, color in enumerate(colors): hist = cv.calcHist([img], [i], None, [Settings.H_BINS], Settings.H_COLOR_RANGE) if Settings.H_SCALE_HIST: # max possible value is w * h of imagePart hist /= scaleMaxPossibleValue histogram.extend(hist) return np.array(np.concatenate(histogram)) def __str__(self): return "HIST"
true
38757300043a261a573b72d974f3f8f53fbb772f
Python
oftensmile/thunder
/python/thunder/utils/save.py
UTF-8
7,929
3.125
3
[ "Apache-2.0" ]
permissive
""" Utilities for saving data """ import os from scipy.io import savemat from numpy import std from math import isnan from numpy import array, squeeze, sum, shape, reshape, transpose, maximum, minimum, float16, uint8, savetxt, size, arange from matplotlib.pyplot import imsave from matplotlib import cm from thunder.utils.load import getdims, subtoind, isrdd, Dimensions def arraytoim(mat, filename, format="png"): """Write a 2D numpy array to a grayscale image. If mat is 3D, will separately write each image along the 3rd dimension Parameters ---------- mat : array (2D or 3D), dtype must be uint8 Pixel values for image or set of images to write filename : str Base filename for writing format : str, optional, default = "png" Image format to write (see matplotlib's imsave for options) """ dims = shape(mat) if len(dims) > 2: for z in range(0, dims[2]): cdata = mat[:, :, z] imsave(filename+"-"+str(z)+"."+format, cdata, cmap=cm.gray) elif len(dims) == 2: imsave(filename+"."+format, mat, cmap=cm.gray) else: raise NotImplementedError('array must be 2 or 3 dimensions for image writing') def rescale(data): """Rescale data to lie between 0 and 255 and convert to uint8 For strictly positive data, subtract the min and divide by max otherwise, divide by the maximum absolute value and center If each element of data has multiple entries, they will be rescaled separately """ if size(data.first()[1]) > 1: data = data.mapValues(lambda x: map(lambda y: 0 if isnan(y) else y, x)) else: data = data.mapValues(lambda x: 0 if isnan(x) else x) mnvals = data.map(lambda (_, v): v).reduce(minimum) mxvals = data.map(lambda (_, v): v).reduce(maximum) if sum(mnvals < 0) == 0: data = data.mapValues(lambda x: uint8(255 * (x - mnvals)/(mxvals - mnvals))) else: mxvals = maximum(abs(mxvals), abs(mnvals)) data = data.mapValues(lambda x: uint8(255 * ((x / (2 * mxvals)) + 0.5))) return data def subset(data, nsamples=100, thresh=None): """Extract subset of points from an RDD into a local array, filtering on the standard deviation Parameters ---------- data : RDD of (tuple, array) pairs The data to get a subset from nsamples : int, optional, default = 100 The number of data points to sample thresh : float, optional, default = None A threshold on standard deviation to use when picking points Returns ------- result : array A local numpy array with the subset of points """ if thresh is not None: result = array(data.values().filter(lambda x: std(x) > thresh).takeSample(False, nsamples)) else: result = array(data.values().takeSample(False, nsamples)) return result def pack(data, ind=None, dims=None, sorting=False, axis=None): """Pack an RDD into a dense local array, with options for sorting, reshaping, and projecting based on keys Parameters ---------- data : RDD of (tuple, array) pairs The data to pack into a local array ind : int, optional, default = None An index, if each record has multiple entries dims : Dimensions, optional, default = None Dimensions of the keys, for use with sorting and reshaping sorting : Boolean, optional, default = False Whether to sort the RDD before packing axis : int, optional, default = None Which axis to do maximum projection along Returns ------- result : array A local numpy array with the RDD contents """ if dims is None: dims = getdims(data) if axis is not None: nkeys = len(data.first()[0]) if axis > nkeys - 1: raise IndexError('only %g keys, cannot compute maximum along axis %g' % (nkeys, axis)) data = data.map(lambda (k, v): (tuple(array(k)[arange(0, nkeys) != axis]), v)).reduceByKey(maximum) dims.min = list(array(dims.min)[arange(0, nkeys) != axis]) dims.max = list(array(dims.max)[arange(0, nkeys) != axis]) sorting = True # will always need to sort because reduceByKey changes order if ind is None: result = data.map(lambda (_, v): float16(v)).collect() nout = size(result[0]) else: result = data.map(lambda (_, v): float16(v[ind])).collect() nout = size(ind) if sorting is True: data = subtoind(data, dims.max) keys = data.map(lambda (k, _): int(k)).collect() result = array([v for (k, v) in sorted(zip(keys, result), key=lambda (k, v): k)]) # reshape into a dense array of shape (b, x, y, z) or (b, x, y) or (b, x) # where b is the number of outputs per record out = transpose(reshape(result, ((nout,) + dims.count())[::-1])) # flip xy for spatial data if size(dims.count()) == 3: # (b, x, y, z) -> (b, y, x, z) out = out.transpose([0, 2, 1, 3]) if size(dims.count()) == 2: # (b, x, y) -> (b, y, x) out = out.transpose([0, 2, 1]) return squeeze(out) def save(data, outputdir, outputfile, outputformat, sorting=False, dimsmax=None, dimsmin=None): """ Save data to a variety of formats Automatically determines whether data is an array or an RDD and handle appropriately Parameters ---------- data : RDD of (tuple, array) pairs, or numpy array The data to save outputdir : str Output directory outputfile : str Output filename outputformat : str Output format ("matlab", "text", or "image") """ if not os.path.exists(outputdir): os.makedirs(outputdir) filename = os.path.join(outputdir, outputfile) if isrdd(data): nout = size(data.first()[1]) if dimsmax is not None: dims = Dimensions() dims.max = dimsmax if dimsmin is not None: dims.min = dimsmin else: dims.min = (1, 1, 1) elif dimsmin is not None: raise Exception('cannot provide dimsmin without dimsmax') else: dims = getdims(data) if (outputformat == "matlab") | (outputformat == "text"): if isrdd(data): if nout > 1: for iout in range(0, nout): result = pack(data, ind=iout, dims=dims, sorting=sorting) if outputformat == "matlab": savemat(filename+"-"+str(iout)+".mat", mdict={outputfile+str(iout): result}, oned_as='column', do_compression='true') if outputformat == "text": savetxt(filename+"-"+str(iout)+".txt", result, fmt="%.6f") else: result = pack(data, dims=dims, sorting=sorting) if outputformat == "matlab": savemat(filename+".mat", mdict={outputfile: result}, oned_as='column', do_compression='true') if outputformat == "text": savetxt(filename+".txt", result, fmt="%.6f") else: if outputformat == "matlab": savemat(filename+".mat", mdict={outputfile: data}, oned_as='column', do_compression='true') if outputformat == "text": savetxt(filename+".txt", data, fmt="%.6f") if outputformat == "image": if isrdd(data): data = rescale(data) if nout > 1: for iout in range(0, nout): result = pack(data, ind=iout, dims=dims, sorting=sorting) arraytoim(result, filename+"-"+str(iout)) else: result = pack(data, dims=dims, sorting=sorting) arraytoim(result, filename) else: arraytoim(data, filename)
true
7d32fa1b54ed4e201b95fbf140f75c834fe9608c
Python
shaunak/RiskBattleSim
/Battle.py
UTF-8
1,559
4.03125
4
[]
no_license
import random attackers = input("Enter number of attackers: ") defenders = input("Enter number of defenders: ") updates = input("Would you like soldier status after each battle? Y/N: ") if updates == "Y" or updates == "y": updates = True elif updates == "N" or updates == "n": updates = False else: print("Please type Y or N, try again") exit() try: attackers = int(attackers) defenders = int(defenders) except ValueError: print("non-integer value given, try again.") exit() def battle(attackers, defenders): if updates: print(str(attackers) + " attackers and " + str(defenders) + " defenders remaining") attacker_dice = [0, 0, 0] defender_dice = [0, 0] for i in range(len(attacker_dice)): attacker_dice[i] = random.randint(0, 7) for i in range(len(defender_dice)): defender_dice[i] = random.randint(0, 7) defender_dice = sorted(defender_dice) attacker_dice = sorted(attacker_dice) if attacker_dice[0] > defender_dice[0]: defenders -= 1 else: attackers -= 1 if defenders > 1 and attackers > 1: if attacker_dice[1] > defender_dice[1]: defenders -= 1 else: attackers -= 1 if attackers == 0 and defenders == 0: print("Its a tie??") return if attackers <= 0: print("The defending country has won!") return if defenders <= 0: print("The attackers have won!") return return battle(attackers, defenders) battle(attackers, defenders)
true
d4b14b75282da9c58d37ecc6c0b7df4f6775619f
Python
danielbociat/OAMK_IOT2021
/Data Analysis/Week2/W2E3.py
UTF-8
1,826
4.53125
5
[]
no_license
import math """ Write a function that converts from kilograms to pounds. Use the scalar conversion of 2.2 lbs per kilogram to make your conversion. Lastly, print the resulting array of weights in pounds in the main program. """ def kgTOlbs(array): for i in range(len(array)): array[i] *= 2.2 testArray1 = [1, 2, 10, 50, 100] kgTOlbs(testArray1) print(testArray1) """ Write a Python function to sum all the numbers in a list """ def sumOfElements(array): sum = 0 for i in range(len(array)): sum += array[i] return sum testArray2 = [1, 2, 10, 50, 100] print(sumOfElements(testArray2)) """ Write a Python function to check whether a number is in a given range. """ def numInRange(num, rangeStart, rangeStop, rangeStep): return num in range(rangeStart, rangeStop, rangeStep) print(numInRange(10, 0, 15, 5)) print(numInRange(2, 1, 15, 2)) """ Write a Python function that takes a number as a parameter and check the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself. """ def isPrime(num): if num < 2: return False for i in range(2, int(math.sqrt(num))+1): if num % i == 0: return False return True print(isPrime(7)) print(isPrime(9)) """ Write a Python function that checks whether a passed string is palindrome or not. Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. """ def isPalindrome(word): cpyword = word.replace(" ", "") reversed = cpyword[::-1] return reversed == cpyword; print(isPalindrome("nurses run")) print(isPalindrome("not a palindrome"))
true
38b0debe3bc60166d267a4ea71ea6b618d61a5e1
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/2272.py
UTF-8
645
3.171875
3
[]
no_license
import fileinput def last_tidy(n): i = 0 for i in xrange(len(n)-1): x = n[i] y = n[i+1] if x > y: n[i] = x - 1 for j in xrange(i+1, len(n)): n[j] = 9 # Since n[i] is now one less, then n[i-1] could be larger than n[i] j = i while j > 0: if n[j-1] > n[j]: n[j] = 9 n[j-1] = n[j-1] -1 j -= 1 else: break break n = map(str, n) n = ''.join(n) return int(n) it = fileinput.input() it.next() num = 1 for line in it: n = list(line.strip("\n")) n = map(int, n) print "Case #" + str(num) + ': ' + str(last_tidy(n)) num += 1
true
eda52ff22f09f8746fd990e1773080c3674a6ded
Python
pgniewko/Deep-Rock
/src/cnn/prepare_data.py
UTF-8
860
2.609375
3
[ "BSD-3-Clause" ]
permissive
#! /usr/bin/env python # # USAGE: # ./prepare_data.py FILES_LIST.txt ../../output/CNN/images.txt ../../output/CNN/values.txt import sys import numpy as np fin = open(sys.argv[1], "rU") fout1 = open(sys.argv[2], "w") fout2 = open(sys.argv[3], "w") for line in fin: pairs = line.split() file_1 = pairs[0] file_2 = pairs[1] file_3 = pairs[2] latt = np.loadtxt(file_1, dtype=np.dtype(int)) Lx, Ly = latt.shape s = "" for i in range(Lx - 1, -1, -1): for j in range(Ly - 1, -1, -1): s += str(latt[i][j]) + " " s += "\n" fout1.write(s) vals2 = np.loadtxt(file_2, dtype=np.dtype(float)) vals3 = np.loadtxt(file_3, dtype=np.dtype(float)) porosity = vals2[0] perc = vals2[1] permea = vals3[0] tau = vals3[1] fout2.write("{} {} {} {}\n".format(porosity, perc, permea, tau))
true
973bfb876881fc678b1f4d7b0be33502e88da690
Python
felmiran/smartERP
/clients/models.py
UTF-8
2,755
2.53125
3
[]
no_license
from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from django.core.exceptions import ValidationError def rut_validate(value): validador = [2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7] if len(value) == 10 and value.index('-') == 8 and value.count('-') == 1: rut = value elif len(value) == 9 and value.index('-') == 7 and value.count('-') == 1: rut = '0' + value else: raise ValidationError('Por favor ingrese el rut sin puntos y con guion. Ej. 11111111-1') spl_rut = rut.rsplit('-') if spl_rut[1] in ('k', 'K'): spl_rut.pop() spl_rut = spl_rut + ['10'] elif spl_rut[1] == '0': spl_rut.pop() spl_rut = spl_rut + ['11'] rut1 = list(map(int, spl_rut[0])) suma = 0 for i in range(len(spl_rut[0])): suma = suma + rut1[-(i+1)]*validador[i] if (11 - suma % 11) != int(spl_rut[1]): raise ValidationError('El rut que ha ingresado es incorrecto. Por favor intente nuevamente') # Create your models here. class Client(models.Model): client_rut = models.CharField(max_length=12, unique=True, verbose_name="RUT", validators=[rut_validate]) client_name = models.CharField(max_length=250, verbose_name="Nombre Cliente") client_giro = models.CharField(max_length=200, verbose_name="Giro") client_address = models.CharField(max_length=100, verbose_name="Direccion") client_comuna = models.CharField(max_length=50, verbose_name="Comuna") client_ciudad = models.CharField(max_length=50, verbose_name="Ciudad") client_region = models.CharField(max_length=50, verbose_name="Region") client_tel = models.CharField(max_length=20, blank=True, verbose_name="Telefono") client_email = models.EmailField(blank=True, verbose_name="E-mail") is_active = models.BooleanField(default=True, verbose_name="Activo") def get_absolute_url(self): return reverse('clients:client_list') class Meta: ordering = ['client_rut'] def __str__(self): return self.client_rut + ' - ' + self.client_name class ClientContact(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT, verbose_name="Cliente") contact_name = models.CharField(max_length=250, verbose_name="Nombre Contacto") contact_role = models.CharField(max_length=200, blank=True, verbose_name="Cargo") contact_tel = models.CharField(max_length=20, blank=True, verbose_name="Telefono") contact_email = models.EmailField(blank=True, verbose_name="E-Mail") def get_absolute_url(self): return reverse('clients:client_list') class Meta: ordering = ['contact_name'] def __str__(self): return self.contact_name
true
1d4f9330421c78e28186913ca38a6db7f73378eb
Python
petaldata/petaldata-python
/petaldata/storage/abstract_storage.py
UTF-8
641
2.875
3
[ "MIT" ]
permissive
import pandas as pd class AbstractStorage(object): @classmethod def if_enabled(cls,base_pickle_filename): if (cls.enabled == True): return cls(base_pickle_filename) else: return None def __init__(self,base_pickle_filename): """ Initializes storage, raising an exception if the storage isn't available. """ self.base_pickle_filename = base_pickle_filename assert(self.available()), "{} storage isn't available.".format(self.__class__) def available(self): pass def pickle_file_exists(self): pass @staticmethod def bytes_to_mb(bytes): return round(bytes/(1024*1024.0),2)
true
13382cb45cac505a326662ce6ef5b8a6039001ff
Python
corutopi/AtCorder_python
/AtCoderBeginnerContest/3XX/311/C.py
UTF-8
1,457
2.734375
3
[]
no_license
import sys sys.setrecursionlimit(10 ** 6) # # for pypy # import pypyjit # pypyjit.set_param('max_unroll_recursion=-1') # import bisect # from collections import deque # import string from math import ceil, floor inf = float('inf') mod = 10 ** 9 + 7 mod2 = 998244353 """ a <= b -> a <= b + EPS a < b -> a < b - EPS a == b -> abs(a - b) < EPS """ EPS = 10 ** -7 # from decorator import stop_watch # # # @stop_watch def solve(N, A): directed_graph = [[] for _ in range(N + 1)] edges = [0] * (N + 1) for i in range(N): directed_graph[i + 1].append(A[i]) edges[i + 1] += 1 edges[A[i]] += 1 ans = [] visited = [0] * (N + 1) start = 0 def dfs(now): if visited[now] == 1: return now visited[now] = 1 for dg in directed_graph[now]: tmp = dfs(dg) if tmp > 0: ans.append(now) if tmp == now: return 0 return tmp return 0 for e in edges: if e > 1: dfs(e) if len(ans) > 0: print(len(ans)) print(*ans[::-1]) break if __name__ == '__main__': N = int(input()) A = [int(i) for i in input().split()] solve(N, A) # # test # from random import randint # import string # import tool.testcase as tt # from tool.testcase import random_str, random_ints # solve()
true
d9f15e024c216216f8932001ff524b05d2f2f04d
Python
SUNAYANA2305/MultiThreadedWebServer-client
/client.py
UTF-8
2,016
2.890625
3
[]
no_license
# Name: Sunayana Ambakanti # SAU ID: 999901013 # import the socket module # import sys forcommandline functions # import time to calculate RTT from socket import * import time import sys import datetime #preparing the socket # IPV4 address, TCP stream ClientSocket = socket(AF_INET, SOCK_STREAM) # if port number is provided if (len(sys.argv)==4): IPaddress=str(sys.argv[1]) Portno=int(sys.argv[2]) filename=str(sys.argv[3]) # if port number is not provided default port is 8080 if (len(sys.argv)==3): IPaddress=str(sys.argv[1]) Portno=8080 filename=str(sys.argv[2]) ServerPort=Portno Host = IPaddress endtime=0 # connect to the Server ip with portno ClientSocket.connect((Host,ServerPort)) # Host Name of the server, socket family, socket type, protocol, timeout and get peer name print ("TimeStamp: ",datetime.datetime.now(),"Request to", (gethostbyaddr(ClientSocket.getpeername()[0]))[0],(gethostbyaddr(ClientSocket.getpeername()[0]))[2]) print ("Server Host Name:",(gethostbyaddr(ClientSocket.getpeername()[0]))[0]) print ("Server Socket Family:",ClientSocket.family) print ("Server Socket Type:",ClientSocket.type) print ("Server Protocol:", ClientSocket.proto) print ("Server Timeout:",ClientSocket.gettimeout()) print ("Server Socket get Peer Name:", ClientSocket.getpeername()) #initialize the output as null output="" url_params=(IPaddress+str(ServerPort),('/'+filename)) url=" ".join(url_params) # RTT start time starttime=time.time() temp = url+"\n" ClientSocket.send(temp.encode()) print("Request sent to Server:", url) while True: # receive the response from the server response=ClientSocket.recv(2048) # capture time for the 1st response if (endtime==0): endtime=time.time()# end time for RTT if response=="": break sys.stdout.write(response) #RTT calculation RTT=endtime-starttime print ("RTT is", RTT ,"Seconds") # closing the socket ClientSocket.close()
true
f99dccdb6492162d90cce9f78e659b93d1784cda
Python
anubhav-shukla/Learnpyhton
/more_about_list.py
UTF-8
568
4.4375
4
[]
no_license
# generate lists with range function # something more about pop method # index method # pass list to a function # python more_about_list.py numbers=list(range(1,11)) # print(numbers) # how to know what value are pop() print(numbers.pop()) #see result is 10 that is pop() # print(numbers) # 10 is removed from list # print(numbers.index(1,11,14) # it show position of element # index(value,start, end) def negative_list(l): negative = [] for i in l: negative.append(-i) return negative print(negative_list(numbers))
true
006366abe123cdfeda0d9e9855a0a5f43695af2e
Python
pyramidsnail/practice
/cf/practice/471c.py
UTF-8
268
3.234375
3
[]
no_license
n = int(raw_input()) def getNumberCards(f): return 3*f*(f+1)/2-f l = 0 h = 10000000 while l+1<h: m = (l+h)/2 if getNumberCards(m)>n: h = m else: l = m total = 0 while l: if (n+l)%3==0: total += 1 l -= 1 print total
true
334bc324982b0a6e54366876e8f8d5b5f37b7503
Python
GunsRoseSS/BD02
/main.py
UTF-8
4,992
4.0625
4
[]
no_license
# pseudocode BD02 Richard en Bas # # Opdracht 1: sorteer een lijst dmv decrease and conquer unsortedlist = [] #Opdracht 1A decrease and conquer def InsertionSort(A, i): current = A[i] #selecteert het huidige nummer dat vergeleken wordt met nummers in de lijst j = i - 1 while j >= 0 and A[j] > current: #vergelijk current met het nummer dat voor current in de lijst staat, en wissel deze om waar nodig. A[j + 1] = A[j] j -= 1 A[j + 1] = current return A B = [] #de sublijst die gesorteerd wordt def dsort(A, B): if len(A) == 0: #als er geen nummers meer zijn die gesorteerd worden, dan return de gesorteerde lijst return B else: B.append(A[0]) #voeg een nummer toe aan de sublijst A.pop(0) #verwijder het nummer uit de originele lijst B = InsertionSort(B, len(B) - 1) #voer de insertionsort iteratie uit return dsort(A, B) # print(dsort([88, 6, 4, 72, 1], B)) #voorbeeld uitwerking #Opdracht 1B divide and conquer def Merge(A, B): C = [] #dit wordt de samengevoegde lijst #voeg het kleinste getal als eerste in de lijst while len(A) > 0 and len(B) > 0: #totdat een van de lijsten leeg is: if A[0] > B[0]: C.append(B[0]) #het getal uit de lijst B is het kleinst, dus voeg deze toe aan C B.pop(0) #verwijder het getal uit B else: #als dit niet zo is, doe dit voor het getal uit de lijst A C.append(A[0]) A.pop(0) #nu is er nog één getal over uit de lijsten. if len(A) == 0: #als de lijst A leeg is, dan zitten er nog getallen in lijst B. while len(B) > 0: C.append(B[0]) B.pop(0) else: #anders zitten er nog getallen in lijst A. while len(A) > 0: C.append(A[0]) A.pop(0) #nu alle getallen gesorteerd en gemerged zijn kan de lijst gereturned worden. return C def MergeSort(A): if len(A) <= 1: #als de lengte van de lijst kleiner dan 1 is, return dan de lijst return A else: mergelist1 = A[:int(len(A)/2)] #maak de twee sublijsten mergelist2 = A[int(len(A)/2):] mergelist1 = MergeSort(mergelist1) #splits de lijsten verder op op een recursieve manier mergelist2 = MergeSort(mergelist2) print("List 1: " + str(mergelist1) + " List 2: " + str(mergelist2)) return Merge(mergelist1, mergelist2) #voeg de lijsten samen, sorteer deze en return deze #print(MergeSort([85,25,84,15,26,37,95,0,34])) #voorbeeld uitwerking #Opdracht 2 string van s letters omdraaien def LetterSort(s): if len(s) <= 1: #Als de string kleiner dan 2 letters is, dan return de string return s else: first = s[:1] #de eerste letter, die naar achteren moet last = s[len(s)-1:] #de laaste letter, die naar voren moet leftover = s[1:len(s)-1] #de rest van de string return last + LetterSort(leftover) + first #print(LetterSort("zuydhogeschool")) #voorbeeld uitwerking #Opdracht 3 Weegschaal balance1 = 0 balance2 = 0 def WeightSort(A, balance1, balance2): if len(A) == 0: return "Weegschaal 1: " + str(balance1) + " Weegschaal 2: " + str(balance2) else: A.sort() selectedweight = A.pop() if balance1 < balance2: balance1 += selectedweight else: balance2 += selectedweight return WeightSort(A, balance1, balance2) # print(WeightSort([1,5,6,7,3,2,6,6,3,2], balance1, balance2)) #voorbeeld uitwerking # Opdracht 4 Torens van Hanoi # Hulp gehad van https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/ # En http://pythontutor.com/visualize.html#mode=edit def Hanoi(disks, start, aid, destination): if disks == 1: print(start[0], "pin:", start[1], aid[0], "pin:", aid[1], destination[0], "pin:", destination[1]) destination[1].append(start[1].pop()) print(start[0], "pin:", start[1], aid[0], "pin:", aid[1], destination[0], "pin:", destination[1]) return start, aid, destination Hanoi(disks - 1, start, destination, aid) destination[1].append(start[1].pop()) print(start[0], "pin:", start[1], aid[0], "pin:", aid[1], destination[0], "pin:", destination[1]) return Hanoi(disks - 1, aid, start, destination) # Configuratie, # Disks is het aantal schijven op de start paal # de lijsten: start, aid en destination representateren de drie palen # In de lijsten representateert het meest rechtse getal de onderste schijf en # het meest linkse getal de bovenste schijf. # Dus van rechts naar links in de lijst is van onder naar boven op de pilaren. # disks = 5 # start = ["Start", []] # aid = ["Aid", []] # destination = ["Destination", []] # for i in range(disks, 0, -1): # start[1].append(i) # start, aid, destination = Hanoi(disks, start, aid, destination) # print("End result:", start[0], "pin:", start[1], aid[0], "pin:", # aid[1], destination[0], "pin:", destination[1])
true
6916273161aa9b31467e3ea2238f5d59ce7ea264
Python
andhrelja/adventofcode
/2020/day10.py
UTF-8
1,298
3.28125
3
[]
no_license
from utils import file_to_list DIFFERENCES = { 1: [], 2: [], 3: [] } def part1(jolts, previous_jolt=0): for jolt in jolts: for diff in range(1, 4): if jolt - diff == previous_jolt: previous_jolt = jolt DIFFERENCES[diff].append(jolt) DIFFERENCES[3].append(max(jolts) + 3) def get_initial_jolts(jolts): for i, jolt in enumerate(jolts[:3]): if jolt <= 3: yield i, jolt def find_options(current_jolt, jolts, options=[]): if len(jolts) == 1: return options for i, jolt in enumerate(jolts): if jolt - current_jolt <= 3: options.append() options += find_options(jolt, jolts[i + 1: ], options) def part2(jolts): arrangements = list() initial_jolts = get_initial_jolts(jolts) for start, initial_jolt in initial_jolts: options = find_options(initial_jolt, jolts[start + 1: ]) arrangements.append(options) return arrangements if __name__ == '__main__': lines = file_to_list("day10.txt", test=True, cast=int) lines = sorted(lines) part1(lines) result1 = len(DIFFERENCES[1]) * len(DIFFERENCES[3]) print("Day 10, part 1:", result1) result2 = part2(lines) print("Day 10, part 2:", result2)
true
c304d0899598a9178fea90c646858aee571d2b88
Python
AndrewChupin/gootax-mobile-ci
/std/error/data_error.py
UTF-8
802
2.671875
3
[]
no_license
from std.error.base_error import BaseError class DataError(BaseError): # Error codes not_found = 1 data_invalid = 2 bundle_invalid = 3 platform_invalid = 3 theme_not_json = 4 # Error messages not_found_mes = "Data with value {%s} is not founded" data_invalid_mes = "Data with value {%s} is invalid" version_invalid_mes = "Version number {%s} must be lower than 24 symbols" data_invalid_langs = "You need specify one or more language" bundle_invalid_mes = "Bundle with name {%s} is invalid" theme_json_mes = "Theme with data {%s} is not JSON" platform_mess = "Unknown platform" def __init__(self, subcode: int=0, data: str="Unknown data error"): BaseError.__init__(self, code=BaseError.DATA_CODE, subcode=subcode, data=data)
true
90a1217a53ccb75eb311b4a0f242dc706b41b2a8
Python
tinbie/obd_datalogger
/main.py
UTF-8
2,095
2.65625
3
[ "MIT" ]
permissive
#py2.7 utf8 import obd import sys from datetime import datetime import string from obd import OBDStatus from time import sleep commands = ['RPM', 'INTAKE_PRESSURE', 'ENGINE_LOAD', 'TIMING_ADVANCE', 'THROTTLE_POS'] # requested commands values = [] # holding responses if __name__ == "__main__": # get duration of logging if len(sys.argv) > 1: logging_duration = sys.argv[1] else: logging_duration = 120 print "####################################" print "OBD DATALOGGER - connecting..." print "####################################" # open instances obd_logger = obd.OBD() logging_time = datetime.now() # prepare file name logging_file_name = str(logging_time).replace(":", "_") logging_file_name = "obd_log_" + logging_file_name[:19] # open file logging_file = open(logging_file_name, "w") # connect to ECU while obd_logger.status() != OBDStatus.CAR_CONNECTED: sleep(5) obd_logger = obd.OBD() sys.stdout.flush() print "####################################" print "Requested Commands are: " for x in commands: print x, print "" print "####################################" print "Logging " + str(logging_duration) + " values" raw_input("Press Enter to start...") sys.stdout.flush() print "Logging started..." logging_duration = int(logging_duration) for cnt in range(logging_duration): # get rpm, engine load # timing, throttle pos for x in commands: obd_response = obd_logger.query(obd.commands[x]) # append if not empty if not obd_response.is_null(): values.append(obd_response.value) else: values.append(0) # add linefeed values.append("\n") # show process if cnt % 10 == 0: print cnt # write values to file for item in values: logging_file.write(str(item) + " ") logging_file.close() print "logging successfully saved"
true
39fb857e1010035a63e30e2cc78640fbca348253
Python
lhr0909/SimonsAlgo
/_peuler/100-200/123.py
UTF-8
495
3.515625
4
[]
no_license
#Related: Project Euler 120 #(a+1)^n == an+1 (mod a^2) #(a-1)^n == an-1 or 1-an (mod a^2) depending whether n is odd or even from MathLib import makePrimes p = makePrimes(250000) def funPowMod(n): a = p[n-1] #print (pow(a - 1, n, a*a) + pow(a + 1, n, a*a)) % (a*a) if n % 2 == 1: return ((a*n+1) + (a*n-1)) % (a*a) else: return ((a*n+1) + (1-a*n)) % (a*a) m = pow(10, 10) for i in xrange(7037, len(p)): if funPowMod(i) > m: print i break
true
433d70987d962530ac846fd3e7c9e6a65c00323b
Python
jetnew/UCSD-Data-Structures-and-Algorithms
/Course 1 - Algorithm Toolbox/Solutions/fractional_knapsack.py
UTF-8
903
3.5
4
[]
no_license
# Uses python3 import sys def get_optimal_value(capacity, weights, values): value = 0. weight = 0 # Get list of values per unit weight val_per_wgt = [] for i in range(len(weights)): val_per_wgt.append(values[i] / weights[i]) while val_per_wgt: i = val_per_wgt.index(max(val_per_wgt)) # Continue until item completely taken or full capacity while weights[i] > 0 and weight < capacity: weights[i] -= 1 weight += 1 value += val_per_wgt[i] del val_per_wgt[i] del weights[i] del values[i] return value if __name__ == "__main__": data = list(map(int, sys.stdin.read().split())) n, capacity = data[0:2] values = data[2:(2 * n + 2):2] weights = data[3:(2 * n + 2):2] opt_value = get_optimal_value(capacity, weights, values) print("{:.10f}".format(opt_value))
true
ca9565b33e7f3195046d33d3a362a78965fd1577
Python
Obliviour/turtleRobot
/HW11/FindRed.py
UTF-8
1,375
2.546875
3
[]
no_license
import time import roslib import rospy import sys import cv2 import numpy as np from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class ShowCamera(): def __init__(self): # initiliaze rospy.init_node('ShowCamera', anonymous=False) self.bridge = CvBridge() self.lower = np.array([10,1,100], dtype = "uint8") self.upper = np.array([38,15,255], dtype = "uint8") # rospy.init_node('CheckOdometry', anonymous=False) # we want a straight line with a phase of straight rgb = rospy.Subscriber('/camera/rgb/image_raw', Image, self.displayRGB) # tell user how to stop TurtleBot rospy.loginfo("To stop TurtleBot CTRL + C") rospy.spin() def displayRGB(self,msg): #rospy.loginfo("Received Image Data") try: image = self.bridge.imgmsg_to_cv2(msg, "bgr8") rospy.loginfo("Converted color to cv2 image") mask = cv2.inRange(image, self.lower, self.upper) #output = cv2.bitwise_and(image, image, mask = mask) cv2.imshow("RBG Window", mask) #cv2.imwrite('TestImage.png',image) cv2.waitKey(1) #cv2.destroyWindow("RGB Window") except CvBridgeError as e: print(e) if __name__ == '__main__': #try: ShowCamera()
true
736d3a76f21c91c05d097c2d18dbd3ae715ef518
Python
DiazRock/DiazHorrasch-GrammarAnalyzer
/GrammarAnalyzer/Parser.py
UTF-8
14,934
3.078125
3
[]
no_license
from GrammarAnalyzer.AuxiliarMethods import * from GrammarAnalyzer.Automaton import * class Parser: def __init__(self, grammar): self.inputSymbols = [FinalSymbol()] + grammar.terminals class PredictiveParser(Parser): def __init__(self, grammar): super().__init__(grammar) self.Firsts = CalculateFirst(grammar) for productions in grammar.nonTerminals.values(): for prod in productions: self.Firsts.update({prod: FirstsForBody(prod, self.Firsts)}) self.Follows = CalculateFollow(grammar,self.Firsts) class LL_Parser(PredictiveParser): def __init__(self, grammar): super().__init__(grammar) self.initialSymbol = grammar.initialSymbol self.symbolsForStack = grammar.nonTerminals self.table = self.buildTable() def buildTable(self): table = {(x,y):[] for x in self.symbolsForStack for y in self.inputSymbols} for X in self.symbolsForStack: for prod in self.symbolsForStack[X]: if len(prod) == 1 and prod[0] == Epsilon(): for t in self.Follows[X]: a = self.Asign(table, X, t, prod), Fail if isinstance (a, Fail):return a else: for t in self.Firsts[prod]: if t == Epsilon(): for terminal in self.Follows[X]: a = self.Asign(table, X, terminal, prod) if isinstance(a,Fail): return a else: a = self.Asign(table, X, t, prod) if isinstance(a, Fail) : return a return table def parse_tree(self, tokens): index_tokens= 0 index_node_tree= 0 derivation_tree = Tree(label = str (self.initialSymbol) + "_" + str(index_node_tree), children = [], parent = None) stack_symbols = [(self.initialSymbol, derivation_tree)] column_tracking= 1 row_tracking= 1 while(stack_symbols and index_tokens < len(tokens)): symbol, current_tree = stack_symbols.pop() if isinstance(symbol, Terminal): if not tokens[index_tokens] == symbol: return Fail("({0}, {1}): Syntax error at or near {2}".format(row_tracking, column_tracking, tokens[index_tokens])) index_tokens += 1 column_tracking += 1 if isinstance(symbol, NoTerminal): prod = self.table[symbol, tokens[index_tokens]] if not prod: return Fail("({0}, {1}): Syntax error at or near {2}".format(row_tracking, column_tracking, tokens[index_tokens])) index_node_tree += 1 node_to_push = Tree(label = str (prod) + '_' + str(index_node_tree), children = [], parent = current_tree) current_tree.children.append(node_to_push) for i in range(len(prod) - 1, -1, -1): if prod[i] != Epsilon(): stack_symbols.append((prod[i], node_to_push)) if symbol.name == '\n': row_tracking += 1 column_tracking = 1 if not (not stack_symbols and index_tokens == len(tokens)): return Fail("({0}, {1}): Syntax error at or near {2}".format(row_tracking, column_tracking, tokens[index_tokens])) return derivation_tree def printTable(self): print(end ='\t') for x in self.inputSymbols: print(x, end= '\t') print('\n') for y in self.symbolsForStack: print(y,end ='\t') for x in self.inputSymbols: print(self.table[y,x],end ='\t') print('\n') def Asign(self,table, symbolForStack, inputSymbol, prod): if not table[(symbolForStack,inputSymbol)]: table[(symbolForStack, inputSymbol)] = prod return True else: return Fail("Grammar is not LL(1):\nConflict between {0} y {1} for terminal {2}".format( (symbolForStack,table[(symbolForStack, inputSymbol)]), (symbolForStack, prod), inputSymbol)) class LR_Parser(PredictiveParser): def __init__(self, grammar, parse_type = 0): super().__init__(grammar) initialSymbol = NoTerminal(name = grammar.initialSymbol.name + "*") d = {initialSymbol : [tuple([grammar.initialSymbol])]} d.update(grammar.nonTerminals) self.augmentedGrammar = GrammarClass(initialSymbol = None, terminals = [], nonTerminals=[] ) self.augmentedGrammar.initialSymbol = initialSymbol self.augmentedGrammar.terminals = grammar.terminals self.augmentedGrammar.nonTerminals = d self.Firsts = CalculateFirst(self.augmentedGrammar) self.Follows = CalculateFollow(self.augmentedGrammar, self.Firsts) self.LR_Automaton = LR_Parser.canonical_LR(self, parse_type= parse_type ) self.table, self.conflict_info, self.was_conflict = LR_Parser.buildTable(self, parser_type = parse_type, automaton = self.LR_Automaton) def canonical_LR(self, parse_type = 'LR(0)'): initialState =canonical_State (label = "I{0}".format(0), setOfItems = [Item(label = {FinalSymbol()} if parse_type != 'SLR(1)' and parse_type != 'LR(0)' else None, grammar = self.augmentedGrammar, nonTerminal= self.augmentedGrammar.initialSymbol, point_Position = 0, production = self.augmentedGrammar.nonTerminals[self.augmentedGrammar.initialSymbol][0])], grammar = self.augmentedGrammar) canonical_states = [initialState] statesQueue = [canonical_states[0]] transition_table = {} while (statesQueue): otherCurrent = None if not isinstance(statesQueue[0], tuple): currentState = statesQueue.pop(0) else: currentState, otherCurrent = statesQueue.pop(0) currentState.setOfItems = (LR_Parser.closure(self, currentState.kernel_items)) symbols = [] [symbols.append (item.production[item.point_Position]) for item in \ currentState.setOfItems if item.point_Position < len(item.production)\ and not item.production[item.point_Position] in symbols ] for x in symbols: new_state = LR_Parser.goto(self, currentState, x, len(canonical_states)) if otherCurrent: if transition_table[(otherCurrent,x)] != new_state: return Fail("No se puede hacer la mezcla LALR, ya que hay indeterminismo para los estados {0}:{3} y {1}:{4} con el símbolo {2}".format(currentState, otherCurrent, x, new_state, transition_table[(otherCurrent, x)])) if parse_type == 'LR(1)': repeated_state = next (( i for i in canonical_states\ if new_state.equal_kernel_items_center(i) \ and new_state.equal_looksahead(i)), False) else: repeated_state = next ( (i for i in canonical_states if\ new_state.equal_kernel_items_center(i)), False) if repeated_state: if parse_type == 'LALR(1)': for i, item in enumerate(new_state.kernel_items): repeated_state.kernel_items[i].label.update(item.label) new_state= repeated_state else: canonical_states.append(new_state) statesQueue.append(new_state) transition_table.update({(currentState, x): new_state}) grammar_symbols = {x for x in self.augmentedGrammar.nonTerminals}.union(self.augmentedGrammar.terminals) return Automaton(states = canonical_states, symbols = grammar_symbols, initialState =canonical_states[0], FinalStates = canonical_states, transitions = transition_table ) def goto(self, current_state, grammar_symbol, index): new_state = canonical_State(label = "I{0}".format(index), setOfItems = [], grammar = self.augmentedGrammar) for item in current_state.setOfItems: if item.point_Position < len(item.production): if item.production[item.point_Position] == grammar_symbol: to_extend = Item(label = item.label.copy() if item.label else None, grammar = self.augmentedGrammar, nonTerminal = item.nonTerminal, point_Position = item.point_Position + 1, production = item.production) new_state.extend([to_extend]) return new_state def closure(self, kernel_items): closure = list(kernel_items) itemsQueue = list(kernel_items) while(itemsQueue): current = itemsQueue.pop(0) if current.point_Position < len(current.production): X = current.production[current.point_Position] if current.label: looks_ahead = set() for ahead_symbol in current.label: to_update = FirstsForBody(current.production[current.point_Position +1:] + tuple([ahead_symbol]), self.Firsts) looks_ahead.update(to_update) else: looks_ahead = None if looks_ahead and Epsilon() in looks_ahead: looks_ahead = {current.label} if (isinstance(X, NoTerminal)): itemsToQueue = [] for prod in self.augmentedGrammar.nonTerminals[X]: itemToAppend = Item(label = looks_ahead.copy() if looks_ahead else None, grammar = self.augmentedGrammar, nonTerminal= X, point_Position = 0, production = prod if prod != tuple([Epsilon()]) else ()) founded = False for item in closure: if item == itemToAppend: if item.label: item.label.update(itemToAppend.label) founded = True if not founded: itemsToQueue.append(itemToAppend) itemsQueue.extend(itemsToQueue) closure.extend(itemsToQueue) return closure def buildTable(self, parser_type, automaton): inputSymbols= self.augmentedGrammar.terminals + [FinalSymbol()] + [x for x in self.augmentedGrammar.nonTerminals if x != self.augmentedGrammar.initialSymbol] self.inputSymbols= inputSymbols table = {(state, symbol):[] for state in automaton.states for symbol in inputSymbols} conflict_info = {state:[] for state in automaton.states} was_conflict = False for state in automaton.states: for item in state.setOfItems: shift_reduce_conflict = [] reduce_reduce_conflict = [] if item.point_Position < len(item.production): symbol = item.production[item.point_Position] if table[(state, symbol)] and isinstance(table[state,symbol][-1], reduce): shift_reduce_conflict.append ((table[state,symbol][-1], symbol)) response_state = automaton.transitions[(state, symbol)] to_insert = shift(table_tuple = tuple([state,symbol]), response = response_state, label = "S" + response_state.label.partition('-')[0][1:] if isinstance(symbol, Terminal) else response_state.label.partition('-')[0][1:] ) if not to_insert in table[(state,symbol)]: table[(state,symbol)].append(to_insert) else: looks_ahead = self.Follows[item.nonTerminal] if parser_type == 'SLR(1)'\ else item.label if parser_type == 'LR(1)' or parser_type == 'LALR(1)'\ else self.augmentedGrammar.terminals + [FinalSymbol()] if parser_type == 'LR(0)' \ else [] for symbol in looks_ahead: to_insert= reduce(table_tuple = (state, symbol), response = len(item.production), label = item) if not to_insert in table[state,symbol]: if table[state, symbol]: if isinstance(table[state,symbol][-1], shift): shift_reduce_conflict.append((table[state,symbol][-1], symbol)) else: reduce_reduce_conflict.append((table[state,symbol][-1], symbol)) table[state,symbol].append(to_insert) if (parser_type == 'LR(0)' or symbol == FinalSymbol()) \ and (NoTerminal (self.augmentedGrammar.initialSymbol.name.rstrip("'")),) == item.production: to_insert = accept(table_tuple = (state, symbol), response = 'accept', label='ok') if not to_insert in table[state, symbol]: table[state, symbol].append (to_insert) if shift_reduce_conflict: was_conflict = True conflict_info[state] += [shift_reduce_fail(shift_decision = shc, reduce_decision = table[state,symbol], conflict_symbol = conflict_symbol, state= state.label) for shc, conflict_symbol in shift_reduce_conflict ] if reduce_reduce_conflict: was_conflict = True conflict_info[state] += [reduce_reduce_fail(reduce_decision1 = rdc, reduce_decision2 = table[state,symbol], conflict_symbol = conflict_symbol, state= state.label) for rdc, conflict_symbol in reduce_reduce_conflict ] return table, conflict_info, was_conflict def parse_tree(self, input_tokens): stack_states = [self.LR_Automaton.initialState] stack_trees = [] i = 0 tokens= input_tokens + [FinalSymbol()] index_node_tree= 0 row_tracker = 1 column_tracker= 1 while i < len (tokens): if tokens[i].name == '\n': row_tracker += 1 column_tracker = 1 else: column_tracker += 1 action = next( (act for act in self.table[(stack_states[-1], tokens[i])]), None) if not action: return Fail("({0}, {1}): Syntax error at or near {2}".format(row_tracker, column_tracker, tokens[i])) if isinstance (action, accept): break elif isinstance(action, shift): stack_states.append(action.response) index_node_tree += 1 stack_trees.append(Tree(label = str (tokens[i]) + "_" + str(index_node_tree))) i += 1 elif isinstance(action, reduce): children = [] for _ in range(action.response): stack_states.pop() children.append(stack_trees.pop()) stack_states.append(self.LR_Automaton.transitions[(stack_states[-1], action.label.nonTerminal)]) index_node_tree += 1 stack_trees.append(Tree(label = str (action.label.nonTerminal) + "_" + str(index_node_tree), children=children)) return stack_trees.pop() class Fail: def __init__(self, error_message): self.error_message = error_message def __repr__(self): return self.error_message __str__ = __repr__ class automaton_fail(Fail): def __init__(self, fail_type, decision1, decision2, conflict_symbol, state): self.decision1 = decision1 self.decision2 = decision2 self.conflict_symbol = conflict_symbol self.error_message = "State {4} symbol {2} : {3} between {0} and {1} ".format(decision1, decision2 , conflict_symbol, fail_type, state) class shift_reduce_fail(automaton_fail): def __init__(self, shift_decision, reduce_decision, conflict_symbol, state): super().__init__(fail_type = "shift-reduce", decision1= shift_decision, decision2 = reduce_decision, conflict_symbol = conflict_symbol, state= state) class reduce_reduce_fail(automaton_fail): def __init__(self, reduce_decision1, reduce_decision2, conflict_symbol, state): super().__init__(fail_type = "reduce-reduce", decision1= reduce_decision1, decision2 = reduce_decision2, conflict_symbol = conflict_symbol, state= state) class Action: def __init__(self, table_tuple, response, label): self.table_tuple = table_tuple self.response = response self.label = label def __repr__(self): return repr(self.label) def __eq__(self, other): return self.table_tuple == other.table_tuple and type(self.response) == type(other.response) and self.response == other.response and self.label == other.label def __hash__(self): return hash(self.response) + hash(self.label) + hash(self.table_tuple) class reduce(Action): pass class shift(Action): pass class accept(Action): def __repr__(self): return 'ok' pass class error(Action, Fail): pass
true
1209a76bc3f522f93ac95ed834ff1e0e660b72e1
Python
pamnesham/squares
/squares2.py
UTF-8
787
4.21875
4
[]
no_license
#!python3 import turtle #Pop-up window asks user for input determining square size lengthSide = turtle.numinput('','Enter a number for square size: ') #function for drawing a single square def drawsquare(arg): turtle.delay(0) turtle.forward(int(arg)) turtle.left(90) turtle.forward(int(arg)) turtle.left(90) turtle.forward(int(arg)) turtle.left(90) turtle.forward(int(arg)) turtle.left(90) #function that determines how many squares will be drawn def drawAll(amt): counter = 0 while counter < amt: counter = counter + 1 drawsquare(lengthSide) turtle.left(36) #Shows the turtle window and determines amount of squares to draw def main(): turtle.showturtle() drawAll(10) if __name__=='__main__': main()
true
91ef02e7b5aba8b26b294aa5960e8b5dabfe8e00
Python
RaskiTech/solitaire_bot
/bot.py
UTF-8
2,580
3.328125
3
[]
no_license
import solitare # Get the talon card with game.talon[-1] # 🪄 🪄 🪄 🪄 # pile: # 0 1 2 3 4 5 6 # ♦1 🃏 🃏 🃏 🃏 🃏 🃏 # ♦3 🃏 🃏 🃏 🃏 🃏 # ♦6 🃏 🃏 🃏 🃏 # ♦10 🃏 🃏 🃏 # ♣2 🃏 🃏 # ♣8 🃏 # ♥2 # # 🃏 ♥5 - pile 7 # Commands: # # setup() # shuffle(deck) # print_board() # put_to_foundations(from) # put_to_pile(from, to) # flip_the_talon() # get_from_stock() def solve(): game = solitare.Game(False) game.setup() game.take_from_foundations(1, 4) #game.print_board() not_done = True while not_done: not_done = False while can_change_pile(game): # Doesn't need to set not_done since it's the first one continue # and everything can still be done after while can_put_to_foundations(game):# if can_put_to_foundations(game): not_done = True continue # If can't move anything anymore, get from the pile if not not_done: # If can get something from the foundations so the stock card can be placed # If can get from the pile if game.get_from_stock(): #game.print_board() not_done = True #game.print_board() # Check if the board is complete for i in range(4): if game.foundations[i] != 13: break else: return True return False def can_change_pile(game): # Check if can move something in the piles for i in range(len(game.tableau)): # +1 for the talon for j in range(len(game.tableau)): if i == j: continue if game.put_to_pile(6 - i, 6 - j): #game.print_board() return True for i in range(len(game.tableau)): if game.put_to_pile(7, i): #game.print_board() return True return False def can_put_to_foundations(game): # Check if something can be put to the foundations for i in range(len(game.tableau) + 1): # +1 for the talon if game.put_to_foundations(i): #game.print_board() return True else: return False
true
b9dd84d0ae78a7fdc4e654e038df8aa5a72c9287
Python
kirigaikabuto/pythonlessons1400
/lesson1/hw1.py
UTF-8
55
3.015625
3
[]
no_license
a = 3 b = 4 print(a, b) # 3 4 # code print(a, b)# 4 3
true
37b5d7ae3a703a4eb15db539c915dc288e04dbe4
Python
amlsf/scrapy_workshop
/wine_example/spiders/L0_barespider.py
UTF-8
978
2.765625
3
[]
no_license
from scrapy import Request, Spider, Item, Field class WineItem(Item): all_html = Field() class DrunkSpider(Spider): name = 'bare_bones' # start_urls = ['http://www.wine.com/v6/wineshop/'] # start_requests() is set as default, no need to include. Could just use start_urls list def start_requests(self): """ :rtype: scrapy.http.Request """ for url in ['http://www.wine.com/v6/wineshop/']: # parse callback is set as default, no need to specify yield Request(url, callback=self.parse) def parse(self, response): """ :type response: scrapy.http.HtmlResponse """ self.log('YAY!!! successfully fetched URL: %s' % response.url) # wine_product = WineItem() # # html_selector = response.css('html') # html_str_list = html_selector.extract() # wine_product['all_html'] = html_str_list[0] # # yield wine_product
true
5fc62d7041963805eca2c953c91e7d9b520e4d06
Python
lenaindelaforetmagique/ProjectEuler
/Python/PE144-2.py
UTF-8
1,255
3.09375
3
[]
no_license
# Problem 144 #from rationnels import * from rationnels import Rationnel from vecteurs import Vecteur from time import time t00 = time() def nextP(A, B): """ A est un vecteur A.coord vaut [xa,ya] B est un vecteur B.coord vaut [xb,yb] > on retourne le point C (rebond du rayon AB sur l'ellipse) """ global a2, b2 V1 = B - A t = Vecteur([1, -1 * ((b2) / (a2)) * B.coord[0] / B.coord[1]]) n = Vecteur([((b2) / (a2)) * B.coord[0] / B.coord[1], 1]) V2 = ((V1 * t) * t) - ((V1 * n) * n) q1 = V2.coord[0] q2 = V2.coord[1] k = (-2 * q1 * B.coord[0] / (a2) - 2 * q2 * B.coord[1] / (b2)) / (q1 * q1 / a2 + q2 * q2 / b2) return B + k * V2 a = Rationnel(5) b = Rationnel(10) a2 = a * a b2 = b * b A = Vecteur([0, 10.1]) B = Vecteur([1.4, -9.6]) A = Vecteur([Rationnel(0), Rationnel(101, 10)]) B = Vecteur([Rationnel(14, 10), Rationnel(-96, 10)]) C = nextP(A, B) t0 = time() cpt = 1 xmin = Rationnel(-1, 100) xmax = Rationnel(1, 100) while not(C.coord[0] > xmin and C.coord[0] < xmax and C.coord[1] > 0): #print(cpt, time()-t0, len(str(C))) t0 = time() cpt += 1 A = Vecteur(B.coord) B = Vecteur(C.coord) C = nextP(A, B) # print(C) print(cpt) print(time() - t00)
true
1562f1e3431eff56a9f5bf5cb9b1bc5e1fcff605
Python
RodrigoFigueroaM/competitivePrograming
/searchInsert.py
UTF-8
863
3.46875
3
[]
no_license
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ try: return nums.index(target) except Exception as e: if len(nums) > 1: for i in range(0, len(nums) - 1): # print(nums[i], target , nums[i + 1], nums[i] < target < nums[i + 1]) if nums[i] < target < nums[i + 1]: return i + 1 if target > nums[-1]: return len(nums) elif target < nums[0]: return 0 if __name__ == '__main__': s = Solution() print(s.searchInsert([1,3,5,6], 5)) #2 print(s.searchInsert([1,3,5,6], 2)) #1 print(s.searchInsert([1,3,5,6], 7)) #4 print(s.searchInsert([1,3,5,6], 0)) #0 print(s.searchInsert([1], 0)) #0 print(s.searchInsert([1,3], 2)) # 1
true
9a67debf8d4f4af60b4ceb0720e4f071ed746509
Python
diogoaraujogit/MachineLearning
/Árvores de decisão e Florestas Aleatórias/12 - Árvores de decisões e Florestas aleatórias.py
UTF-8
1,055
3.015625
3
[]
no_license
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Dados kyphosis df = pd.read_csv('kyphosis.csv') # Análise exploratória de dados sns.pairplot(df,hue='Kyphosis',palette='Set1') # Divisão Treino-teste from sklearn.model_selection import train_test_split X = df.drop('Kyphosis',axis=1) y = df['Kyphosis'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30) # Árvore de decisão from sklearn.tree import DecisionTreeClassifier dtree = DecisionTreeClassifier() dtree.fit(X_train,y_train) #Previsão e Avaliação predictions = dtree.predict(X_test) from sklearn.metrics import classification_report,confusion_matrix print(classification_report(y_test,predictions)) print(confusion_matrix(y_test,predictions)) # Florestas Aleatórias from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(n_estimators=100) rfc.fit(X_train, y_train) rfc_pred = rfc.predict(X_test) print(confusion_matrix(y_test,rfc_pred)) print(classification_report(y_test,rfc_pred))
true
c24da36c7e736ef5d387f562312b0500cab7522e
Python
zhanghahaA/work
/b.py
UTF-8
188
2.9375
3
[]
no_license
class father: def myfn(self): print('调用父类方法') class child(father): def myfn(self): print('调用子类方法') s=child() s.myfn() super(child,s).myfn()
true
351fc71c8dedfd255dc0f3de761e30c6db00d3e6
Python
piopiop1178/algorithm_week2
/gyojin/05_가장긴증가하는부분수열.py
UTF-8
516
3.078125
3
[]
no_license
import sys n = int(sys.stdin.readline()) nums = list(map(int, sys.stdin.readline().split())) ans = [nums[0]] for i in range(1, n): if ans[-1] < nums[i]: ans.append(nums[i]) else: target = nums[i] low = 0 high = len(ans) - 1 while low <= high: mid = (low + high) // 2 dif = ans[mid] - target if dif >= 0: high = mid - 1 else: low = mid + 1 ans[low] = nums[i] print(len(ans))
true
b17a94522b0a62d9061099511600bdc2288383de
Python
Shin-jay7/LeetCode
/0483_smallest_good_base.py
UTF-8
626
3.1875
3
[]
no_license
from __future__ import annotations import math # n = k^m + k^(m-1) + ... + k + 1 # n > k^m # mth root of n > k # # n = k^m + ... + 1 < (k+1)^m ... # # K+1 > mth root of n > k # # k is a base and m = number of 1s - 1 # # m must be between 2 and log2n. Otherwise n - 1 class Solution: def smallestGoodBase(self, n: str) -> str: n = int(n) max_m = int(math.log(n, 2)) for m in range(max_m, 1, -1): k = int(n**m**-1) if (k**(m + 1) - 1) // (k - 1) == n: return str(k) return str(n - 1) # when m = 1, k is n-1 because (n-1)^1 + (n-1)^0 = n
true
3b60e3cb86977b6181a4458a1823168b21663fee
Python
mingyuchoo/locust-with-haralyzer
/haralyzerfile.py
UTF-8
927
2.546875
3
[ "MIT" ]
permissive
import json from haralyzer import HarParser def get_info_from_har(file_path): with open(file_path, 'r', encoding='UTF8') as f: har_parser = HarParser(json.loads(f.read())) method = har_parser.pages[0].actual_page['request']['method'] url = har_parser.pages[0].actual_page['request']['url'] headers = {} for header in har_parser.pages[0].actual_page['request']['headers']: key = header['name'] value = header['value'] headers[key] = value queryString = har_parser.pages[0].actual_page['request']['queryString'] cookies = har_parser.pages[0].actual_page['request']['cookies'] context = { 'method': method, 'url': url, 'headers': headers, 'queryString': queryString, 'cookies': cookies } return context file_path = 'resources/gatling.har' context = get_info_from_har(file_path)
true
ee332b72b8cd517a6a8363d628c4ef275ef00bde
Python
gabriellaec/desoft-analise-exercicios
/backup/user_014/ch147_2020_04_22_14_18_59_702047.py
UTF-8
488
3.546875
4
[]
no_license
def conta_ocorrencias (texto): contagem = {} for palavra in texto: if not palavra in contagem: contagem[palavra] = 1 else: contagem[palavra] += 1 return contagem def mais_frequente(texto): contagem = conta_ocorrencias(texto) maior = 0 mais_frequente = '' for palavra, cont in contagem.items(): if cont > maior: maior = cont mais_frequente = palavra return mais_frequente
true
f74644d191179f867e17c67ddd79ac3f58a5e4fd
Python
mirrorecho/rwestmusic-copper
/copper/machines/tools.py
UTF-8
9,843
3.046875
3
[]
no_license
import collections import abjad from calliope import bubbles from copy import copy, deepcopy # d = {} # b = None # print( set(dir(d)) - set(dir(b)) ) # TO DO EVENTUALLY... look into abjad tree data structures (or other tree structures)... may be useful here instead of reinventing the wheel class SetAttributeMixin(object): def __init__(self, **kwargs): super().__init__() for name, value in kwargs.items(): setattr(self, name, value) # MAY NEED THESE???? # def __str__(self): # my_string = "" # # TO DO... this is silly... # class DummyClass(object): # pass # for a in sorted(set(dir(self)) - set(dir(DummyClass()))): # my_string += a + "=" + str(getattr(self, a)) + " | " # return my_string # def copy(self): # return deepcopy(self) # deep copy probably not needed... but just to be safe... class Tree(SetAttributeMixin, abjad.datastructuretools.TreeContainer): children_type = None # sometimes items are moved arround... this can be used track where an element had been placed previously, which is often useful original_index = None original_depthwise_index = None # TO DO... consider making these IndexedData objects at the parent level? def index_children(self): for i, child in enumerate(self.children): child.original_index = i child.original_depthwise_index = child.depthwise_index # TO DO... this could get expensive @property def my_index(self): return self.parent.index(self) # return self.graph_order[-1] # NOTE... this does the same thing... which performs better?? @property def depthwise_index(self): """ Not sure how well this performs, but it works """ return self.root.depthwise_inventory[self.depth].index(self) def copy(self): new_self = deepcopy(self) # for child in self.children: # new_self.append(child.copy()) return new_self def branch(self, **kwargs): new_branch = self.children_type(**kwargs) self.append( new_branch ) return new_branch def __str__(self): my_return_string = self.__class__.__name__ + ":" + str(self.depthwise_index) if self.parent and self.parent is not self.root: my_return_string = str(self.parent) + " | " + my_return_string return my_return_string class IndexedData(SetAttributeMixin, collections.UserDict): """ behaves sort of like a cross between a list and a dictionary. """ default = None min_limit=0 limit=1 cyclic = True cyclic_start=0 over_limit_defaults=True # if False, then attempting to get by indices >= limit will throw an exception. (only applies if cyclic=False) items_type = object # WARNING, this must be defined at the class level # TO DO: implement this? # def keys(self): # return collections.abc.KeysView(range(self.limit)) def __init__(self, initialize_from=None, default=None, limit=None, **kwargs): super().__init__(**kwargs) self.default = default if default is not None else self.default self.limit = limit if limit is not None else self.limit if initialize_from: self.update(initialize_from) def get_default(self): if hasattr(self.default, "__call__"): return self.default() else: return self.default @classmethod def item(cls, **kwargs): return cls.items_type(**kwargs) # TO DO... + doesn't work right with multiple IndexedData objects (due to max methed in update) # TO DO... coerce items into a particular type? # TO DO... implement append, __mul__, insert, enumerate, items, make immutable? # TO DO... implement better slicing (e.g. slicing outside of limits) # TO DO... calling max... odd behavior (returns first item's value)... why? # TO DO?... force items type if defined? (i.e. throw exeption if type doesn't match?) # def __lt__(self, value, other): # print(value) # return value < other # NOTE: due to the iterable implementation, max(some_indexed_data) will return the max VALUE (not max key as a normal dictionary would), # so implementing this to get the max key def maxkey(self): if len(self.data) > 0: return max(self.data) def update(self, from_dict): if isinstance(from_dict, IndexedData): from_dict = from_dict.data for key in from_dict: assert isinstance(key, int), "key is not an integer: %s" % key # test for length 0, otherwise calling max on dict fails from_limit = 0 if len(from_dict) == 0 else max(from_dict) if self.limit <= from_limit: self.limit = from_limit + 1 super().update(from_dict) def __iadd__(self, other): if isinstance(other,collections.UserDict) or isinstance(other,dict): self.update(other) elif isinstance(other, tuple) or isintance(other, list): self.extend(other) else: raise TypeError("Cannot add object of type %s to IndexedData object" % type(other)) return self def copy(self): d = type(self)() # TO DO EVENTUALLY... could make this more elegant d.default = self.default d.min_limit=self.min_limit d.limit=self.limit d.cyclic = self.cyclic d.cyclic_start=self.cyclic_start d.over_limit_defaults=self.over_limit_defaults d += self return d def __add__(self, other): d = self.copy() d += other return d def flattened(self): """ if each item contains an iterable, this can create a combined, flattened list """ # CONFUSING! see: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python return [item for sublist in self for item in sublist] def non_default_items(self): return sorted(self.data.items()) def keylist(self): return sorted(list(self.data.keys())) def fillme(self, indices, value): if indices: if self.limit <= max(indices): self.limit = max(indices) + 1 for i in indices: if hasattr(value, "__call__"): # TO DO... better to call this over and over or set value once outside of loop? self[i] = value() else: self[i] = value else: print("WARNING: fillme with value '%s' will have no effect since no indices passed." % value) @classmethod def fill(cls, indices, value): me = cls() me.fillme(indices, value) return me def as_list(self): # TO DO: this is a little screwy and doesn't work for indices outside the limits or for min_limit !=0 return [self[i] for i in range(self.limit) ] def extend(self, values): extend_from = 0 if len(self.data) > 0: extend_from = max(self.data) + 1 for i, v in enumerate(values): self[i+extend_from]=v def __setitem__(self, key, value): assert isinstance(key, int), "key is not an integer: %s" % key if hasattr(value, "__call__"): self.data[key] = value() else: self.data[key] = value if self.limit <=key: self.limit = key + 1 def __len__(self): return self.limit def __getitem__(self, key): if isinstance(key, slice): # TO DO: this is a little screwy and doesn't work for indices outside the limits or for min_limit !=0 return self.as_list()[key] if self.cyclic: if self.cyclic_start > 0 and (key >= self.cyclic_start or key < 0): if key > 0: key = ( (key - self.cyclic_start) % (self.limit - self.cyclic_start) ) + self.cyclic_start else: key = (key % (self.limit - self.cyclic_start)) + self.cyclic_start else: key = key % self.limit if key in self: return self.data[key] elif key < self.limit or self.over_limit_defaults: return self.get_default() else: raise KeyError(key) def __iter__(self): for x in range(self.min_limit, self.limit): yield self[x] def __str__(self): def str_line(key, value): key_len = len(str(key)) spacing = " " * (8-key_len) if key_len<8 else "" return " |%s%s: %s\n" % (spacing, key, value) my_string = "<IndexedData object>\n" my_string += str_line("default", self.get_default()) for key, value in self.non_default_items(): if key < self.limit: my_string += str_line(key, value) my_string += str_line(self.limit, "MAX") return my_string class ID1(IndexedData): # just to save typing, since this is used often cyclic_start = 1 def by_logical_tie_group_rests(music): logical_ties = abjad.select(music).by_logical_tie() return_logical_ties = [] previous_rest_list = [] for logical_tie in logical_ties: if isinstance(logical_tie[0], abjad.Rest): previous_rest_list += [logical_tie[0]] else: if previous_rest_list: return_logical_ties += [abjad.selectiontools.LogicalTie( previous_rest_list )] previous_rest_list = [] return_logical_ties += [logical_tie] return return_logical_ties # d1 = IndexedData() # d2 = IndexedData(cyclic_start=2) # d1.extend(["a","b","c","d",'e']) # print(d1[5]) # d2.extend(["a","b","c","d",'e']) # print(d2[-4])
true
a24eec97673a5c11f8ec07bc0ede277e06639e77
Python
FoRavel/test-python
/variables.py
UTF-8
1,218
3.96875
4
[ "Unlicense" ]
permissive
#Exercice 4 t1=[100,28,31,1,31,30,31,31,30,31,30,31] #a)Compter nombre éléments non nuls compteur = 0 for i in range(len(t1)): if t1[i] != 0: compteur = compteur + 1 print(compteur) #b)Le plus grand élément max = max(t1) #c)La position p du plus petit élément plusPetit = min(t1) p = 0 for i in range(len(t1)): if t1[i] == plusPetit: p = i+1 #d) #Exercice 5 #Créer à partir de la liste t1, une liste qui contienne seulement les nombres pairs #et une qui contienne les nombres impairs print("EXERCICE 5") nbPairs=[] nbImpairs=[] for i in range(len(t1)): if (t1[i]%2)==0: nbPairs.append(t1[i]) else: nbImpairs.append(t1[i]) #Exercice 3 print("EXERCICE 3") for nombre in nbPairs: print(nombre,"", end="") #Exercice 6 prenom = ["Jean", "Maximilien", "Brigitte", "Shiny", "Cedric", "Joanna", "Salope"] moinsDe6carac = [] plusDe6carac =[] for i in range(len(prenom)): if(len(prenom[i])) < 6: moinsDe6carac.append(prenom[i]) else: plusDe6carac.append(prenom[i]) #Exercice 7 print("EXERCICE 7") nombres=list(range(1,10)) print(nombres) for i in range(1, len(nombres), 2): nombres[i] = nombres[i-1] print(nombres) for i in range(
true
020c7d118d7dfce549e52c67a7c44687bfb7d92e
Python
Funakai/dm_week4
/datasets.py
UTF-8
503
3.03125
3
[]
no_license
import numpy as np def load_linear_example1(): X = np.array([[1,4],[1,8],[1,13],[1,17]]) Y = np.array([7, 10, 11, 14]) return X, Y def load_nonlinear_example1(): X = np.array([[1,0.0], [1,2.0], [1,3.9], [1,4.0]]) Y = np.array([4.0, 0.0, 3.0, 2.0]) return X, Y def polynomial2_features(input): poly2 = input[:,1:]**2 return np.c_[input, poly2] def polynomial3_features(input): poly2 = input[:,1:]**2 poly3 = input[:,1:]**3 return np.c_[input, poly2, poly3]
true
1a22ac691a2dcf129a7f82ef4590087c9aaaf7f8
Python
dpsanders/metodos-computacionales
/progs/2010-05-24/archivos.py
UTF-8
155
2.875
3
[]
no_license
from numpy import * salida = open("cuad.dat", "w") for x in arange(0.5, 10, 0.5): salida.write("%f%20.10f\t%g\n" % (x, x**2, x**3) ) salida.close()
true
9efa327f7fded387e2edc84928cfce2e1960bf37
Python
AKROGIS/AGSbuilder
/publishable_doc.py
UTF-8
35,210
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- """ Definition for a document publishable as a web service. """ from __future__ import absolute_import, division, print_function, unicode_literals from io import open import json import os import logging import xml.dom.minidom import arcpy import requests import util logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) # broad exception catching will be logged; reraise-from is not available in Python2 # pylint: disable=broad-except,raise-missing-from class PublishException(Exception): """Raise when unable to Make a change on the server""" # object inheritance is maintained for Python2 compatibility # pylint: disable=useless-object-inheritance class Doc(object): """An ArcGIS document that is publishable as an ArcGIS Service.""" # pylint: disable=too-many-instance-attributes,too-many-arguments def __init__( self, path, folder=None, service_name=None, server=None, server_url=None, config=None, ): logger.debug( "Doc.__init__(path=%s, folder=%s, service_name=%s, server=%s, server_url=%s, config=%s", path, folder, service_name, server, server_url, config, ) self.__config = config self.__basename = None self.__ext = None self.__draft_file_name = None self.__sd_file_name = None self.__issues_file_name = None self.__is_image_service = False # All instance attributes should be defined in __init__() # (even if they are set in a property setter) self.__path = None # (re)set in path.setter self.__service_name = None # (re)set in path.setter self.path = path self.__folder = None # (re)set in folder.setter self.__service_folder_name = None # (re)set in folder.setter self.folder = folder if service_name is not None: self.__service_name = util.sanitize_service_name(service_name) self.__service_copy_data_to_server = False self.__service_server_type = None self.__service_connection_file_path = None self.__service_summary = None # or string self.__service_tags = None # or string with comma separated tags self.__have_draft = False self.__draft_analysis_result = None self.__have_service_definition = False self.__have_new_service_definition = False self.__service_is_live = None if server is not None: self.server = server else: try: self.server = self.__config.server except AttributeError: self.server = None if server_url is not None: self.server_url = server_url else: try: self.server_url = self.__config.server_url except AttributeError: self.server_url = None if self.server_url is None: if self.__service_connection_file_path is not None: logger.debug( "Server URL is undefined. Trying to get from connection file" ) self.server_url = util.get_service_url_from_ags_file( self.__service_connection_file_path ) # Read/Write Properties @property def path(self): """Return the filesystem path to this document.""" return self.__path @path.setter def path(self, new_value): """Make sure new_value is text or set to None Note: setting path will also set a default value for the service name, if you want a different service_name you must set it explicitly __after__ setting the path Files are based on ArcGIS Desktop mxd files and not ArcGIS Pro project files. ArcGIS Pro 2.0 does not support publishing to a local ArcGIS Server """ try: # FIXME: if this is an image service then it is a dataset a fgdb # (which isn't a real file) # TODO: set self.__is_image_service here if os.path.exists(new_value): self.__path = new_value base, ext = os.path.splitext(new_value) self.__basename = os.path.basename(base) self.__ext = ext # TODO: Allow draft and sd to be created in a new location from settings # (path may be read only) # TODO: This will not work for image services self.__draft_file_name = base + ".sddraft" self.__sd_file_name = base + ".sd" self.__issues_file_name = base + ".issues.json" self.service_name = self.__basename else: logger.warning( "Path (%s) Not found. This is an invalid document.", new_value ) except TypeError: logger.warning( "Path must be text. Got %s. This is an invalid document.", type(new_value), ) @property def folder(self): """Returns the name of the ArcGIS Services folder for this document.""" return self.__folder @folder.setter def folder(self, new_value): """Make sure new_value is text or set to None""" if new_value is None: self.__folder = None self.__service_folder_name = None return try: _ = new_value.isalnum() self.__folder = new_value self.__service_folder_name = util.sanitize_service_name(self.folder) except AttributeError: logger.warning( "Folder must be None, or text. Got %s. Using None.", type(new_value) ) self.__folder = None self.__service_folder_name = None @property def service_name(self): """Returns the name of the ArcGIS service for this document.""" return self.__service_name @service_name.setter def service_name(self, new_value): """Make sure new_value is text or set to None""" if new_value == self.__service_name: return try: _ = new_value.isalnum() self.__service_name = util.sanitize_service_name(new_value) except AttributeError: logger.warning( "Service name must be text. Got %s. Using default from path.", type(new_value), ) self.__service_name = util.sanitize_service_name(self.__basename) @property def server(self): """Return the server name.""" if self.__service_server_type == "MY_HOSTED_SERVICES": return self.__service_server_type return self.__service_connection_file_path @server.setter def server(self, new_value): """Set the server connection type/details Must be 'MY_HOSTED_SERVICES', or a valid file path. Any other value will default to 'MY_HOSTED_SERVICES'""" hosted = "MY_HOSTED_SERVICES" conn_file = "FROM_CONNECTION_FILE" # default self.__service_server_type = hosted self.__service_connection_file_path = None # if you want to do a case insensitive compare, be careful, # as new_value may not be text. if new_value is None or new_value == hosted: logger.debug( ( "Setting document %s service_server_type " "to %s and service_connection_file_path to %s" ), self.name, self.__service_server_type, self.__service_connection_file_path, ) return try: if os.path.exists(new_value): self.__service_server_type = conn_file self.__service_connection_file_path = new_value else: logger.warning( "Connection file (%s) not found. Using default.", new_value ) except TypeError: logger.warning( "Server must be None, '%s', or a file path. Got %s. Using default.", hosted, new_value, ) logger.debug( "Setting document %s service_server_type to %s and service_connection_file_path to %s", self.name, self.__service_server_type, self.__service_connection_file_path, ) # Read Only Properties @property def name(self): """Return the service name of this document.""" if self.folder is not None and self.__basename is not None: return self.folder + "/" + self.__basename return self.__basename @property def service_path(self): """Return the service path for this document.""" if self.__service_folder_name is not None and self.__service_name is not None: return self.__service_folder_name + "/" + self.__service_name return self.__service_name @property def is_live(self): "Return true if the service for this document exists." if self.__service_is_live is None: self.__service_is_live = self.__check_server_for_service() return self.__service_is_live @property def is_publishable(self): """ Check if a source is ready to publish to the server. Returns True or False, should not throw any exceptions. May need to create a draft service definition to analyze the file. Any exceptions will be swallowed. If there is an existing sd file newer than the source, then we are ready to publish, otherwise create a draft file (if necessary) and analyze. If there are no errors in the analysis then it is ready to publish. :return: Bool """ if not self.__is_image_service: if self.__file_exists_and_is_newer(self.__sd_file_name, self.path): logger.debug( "Service definition is newer than source, ready to publish." ) self.__have_service_definition = True return True # I need to create a sd file, so I need to check for/create a draft file if not self.__file_exists_and_is_newer(self.__draft_file_name, self.path): try: self.__create_draft_service_definition() except PublishException as ex: logger.warning("Unable to create draft service definition: %s", ex) return False # I may have a draft file, but it may not be publishable, make sure I have analysis results. if self.__draft_analysis_result is None: try: self.__analyze_draft_service_definition() except PublishException as ex: logger.warning("Unable to analyze the service: %s", ex) return False if self.__draft_analysis_result is None: logger.warning( "Unable to analyze service definition draft, NOT ready to publish." ) return False if ( "errors" in self.__draft_analysis_result and self.__draft_analysis_result["errors"] ): logger.debug("Service definition draft has errors, NOT ready to publish.") return False return True @property def all_issues(self): """Provide a list of errors, warning and messages about publishing this document The issues are created when a draft file is created or re-analyzed. Since the draft file is deleted when a sd file is created, the analysis results are cached. The cached copy is used if the sd file is newer than the map. If there is not cached copy, or the sd file is out of date, the draft file will be created or re-analyzed.""" if self.__draft_analysis_result is None: self.__get_analysis_result_from_cache() if self.__draft_analysis_result is None: try: self.__analyze_draft_service_definition() except PublishException as ex: logger.warning("Unable to analyze the service: %s", ex) if self.__draft_analysis_result is None: error = "ERRORS:\n " if self.path is None: return error + "Path to service source is not valid" return error + "Unable to get issues" return self.__stringify_analysis_results() @property def errors(self): """Return the errors (as text) that have occurred.""" issues = self.all_issues if "ERRORS:" not in issues: return "" return issues.split("ERRORS:")[1] # Public Methods def publish(self): """Publish the document to the server.""" self.__publish_service() def unpublish(self, dry_run=False): """Stop and delete a service that is already published If dry_run is true, then no changes are made to the server This requires Rest API URL, Admin credentials and the AGS Rest API The ags connection file cannot by used with arcpy to admin the server ref: http://resources.arcgis.com/en/help/rest/apiref/index.html of: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html """ # TODO: self.service_path is not valid if source path doesn't exist # (typical case for delete) logger.debug("Called unpublish %s on %s", self.service_path, self.server_url) if self.server_url is None or self.service_path is None: logger.warning( "URL to server, or path to service is unknown. Can't unpublish." ) return username = getattr(self.__config, "admin_username", None) password = getattr(self.__config, "admin_password", None) if username is None or password is None: logger.warning("No credentials provided. Can't unpublish.") return # TODO: check if service type is in the extended properties provided by the caller # (from CSV file) service_type = self.__get_service_type_from_server() if service_type is None: logger.warning("Unable to find service on server. Can't unpublish.") return token = self.__get_token(self.server_url, username, password) if token is None: logger.warning("Unable to login to server. Can't unpublish.") return url = ( self.server_url + "/admin/services/" + self.service_path + "." + service_type + "/delete" ) data = {"f": "json", "token": token} logger.debug("Unpublish command: %s", url) logger.debug("Unpublish data: %s", data) if dry_run: msg = "Prepared to delete {0} from the {1}" print(msg.format(self.service_path, self.server_url)) return try: logger.info("Attempting to delete %s from the server", self.service_path) response = requests.post(url, data=data) response.raise_for_status() except requests.exceptions.RequestException as ex: logger.error(ex) raise PublishException("Failed to unpublish: {0}".format(ex)) json_response = response.json() logger.debug("Unpublish Response: %s", json_response) # TODO: info or error Log response # TODO: If folder is empty delete it? # Private Methods def __create_draft_service_definition(self, force=False): """Create a service definition draft from a mxd/lyr Note: a *.sddraft file is deleted once it is used to create a *.sd file ref: http://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-functions/createimagesddraft.htm http://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-mapping/createmapsddraft.htm IMPORTANT NOTES * ArcGIS Pro has renamed the mapping module from arcpy.mapping to arcpy.mp * as of 2.0, arcpy.mp.CreateMapSDDraft only support MY_HOSTED_SERVICES. it does NOT support ArcGIS Server * arcpy.mp.MapDocument() does not exist, get the input to CreateMapSDDraft() from listMaps on a project (*.aprx) file or from arcpy.mp.LayerFile(r"....lyrx"). If you have an *.mxd, you must first import it into a project file to get a map object. """ logger.debug("Creating Draft Service Definition from %s", self.path) if self.path is None: raise PublishException( "This document cannot be published. There is no path to the source." ) if not os.path.exists(self.path): raise PublishException( "This document cannot be published. The source file is missing." ) if not force and self.__file_exists_and_is_newer( self.__draft_file_name, self.path ): logger.info("sddraft is newer than source document, skipping create") self.__have_draft = True return if os.path.exists(self.__draft_file_name): self.__delete_file(self.__draft_file_name) source = self.path if self.__is_image_service: create_sddraft = arcpy.CreateImageSDDraft else: create_sddraft = arcpy.mapping.CreateMapSDDraft try: source = arcpy.mapping.MapDocument(self.path) except Exception as ex: PublishException(ex) try: logger.info("Begin arcpy.createSDDraft(%s)", self.path) result = create_sddraft( source, self.__draft_file_name, self.__service_name, self.__service_server_type, self.__service_connection_file_path, self.__service_copy_data_to_server, self.__service_folder_name, self.__service_summary, self.__service_tags, ) logger.info("Done arcpy.createSDDraft()") self.__draft_analysis_result = result self.__have_draft = True self.__simplify_and_cache_analysis_results() except Exception as ex: raise PublishException( "Unable to create the draft service definition file: {0}".format(ex) ) if self.is_live: self.__create_replacement_service_draft() def __check_server_for_service(self): """Check if this source is already published on the server Requires parsing the server URl out of the binary *.ags file, or a server URL from config Need to use AGS Rest API (http://resources.arcgis.com/en/help/rest/apiref/index.html) """ logger.debug( "Check if %s exists on the server %s", self.service_path, self.server_url ) if self.server_url is None: logger.debug("Server URL is undefined. Assume service exists") return True url = self.server_url + "/rest/services?f=json" if self.__service_folder_name is not None: # Check if the folder is valid try: data = requests.get(url).json() # sample response: {..., "folders":["folder1","folder2"], ...} folders = [folder.lower() for folder in data["folders"]] except Exception as ex: logger.warning( "Failed to check for service, %s. Assume service exists", ex ) return True logger.debug("folders found: %s", folders) if self.__service_folder_name.lower() in folders: url = ( self.server_url + "/rest/services/" + self.__service_folder_name + "?f=json" ) else: logger.debug( "folder was not found on server, so service does not exist yet" ) return False logger.debug("looking for services at: %s", url) try: data = requests.get(url).json() # sample response: {..., "services": # [{"name": "WebMercator/DENA_Final_IFSAR_WM", "type": "ImageServer"}]} services = [service["name"].lower() for service in data["services"]] except Exception as ex: logger.warning("Failed to check for service, %s. Assume service exists", ex) return True logger.debug("services found: %s", services) return self.service_path.lower() in services def __analyze_draft_service_definition(self): """Analyze a Service Definition Draft (.sddraft) files for readiness to publish If asked to analyze the file, ignore any existing cached analysis results http://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-mapping/analyzeforsd.htm """ if not self.__have_draft: self.__create_draft_service_definition() if not self.__have_draft: logger.error("Unable to get a draft service definition to analyze") return # If we created a new draft service definition, then we have results. if self.__draft_analysis_result is not None: return try: logger.info("Begin arcpy.mapping.AnalyzeForSD(%s)", self.__draft_file_name) self.__draft_analysis_result = arcpy.mapping.AnalyzeForSD( self.__draft_file_name ) logger.info("Done arcpy.mapping.AnalyzeForSD()") except Exception as ex: raise PublishException( "Unable to analyze the draft service definition file: {0}".format(ex) ) self.__simplify_and_cache_analysis_results() def __simplify_and_cache_analysis_results(self): if self.__draft_analysis_result is not None: self.__simplify_analysis_results() try: with open(self.__issues_file_name, "w", encoding="utf-8") as out_file: out_file.write(json.dumps(self.__draft_analysis_result)) except Exception as ex: logger.warning("Unable to cache the analysis results: %s", ex) def __get_analysis_result_from_cache(self): if self.__file_exists_and_is_newer(self.__issues_file_name, self.path): try: with open(self.__issues_file_name, "r", encoding="utf-8") as in_file: self.__draft_analysis_result = json.load(in_file) except Exception as ex: logger.warning( "Unable to load or parse the cached analysis results %s", ex ) def __simplify_analysis_results(self): """self.__draft_analysis_result is not expressible as JSON (keys must be a string), This fixes that, and makes it a little simpler to 'stringify' for reporting input: {"warnings":{("msg",code):[layer, layer, ...]} output: {"warnings":[{"name":str,"code":int,"layers":["name1", "name2",...]},...]} """ simple_results = {} for key in ("messages", "warnings", "errors"): if key in self.__draft_analysis_result: issue_list = [] issues = self.__draft_analysis_result[key] for ((message, code), layerlist) in issues.items(): issue = { "text": message, "code": code, "layers": [layer.longName for layer in layerlist], } issue_list.append(issue) simple_results[key] = issue_list self.__draft_analysis_result = simple_results def __stringify_analysis_results(self): """This only works on the simplified version of the analysis results""" text = "" for key in ("messages", "warnings", "errors"): if key in self.__draft_analysis_result: issues = self.__draft_analysis_result[key] if issues: text += key.upper() + ":\n" for issue in issues: text += " {0} (code {1})\n".format( issue["text"], issue["code"] ) layers = issue["layers"] if layers: text += " applies to layers: {0}\n".format( ",".join(layers) ) return text def __create_service_definition(self, force=False): """Converts a service definition draft (.sddraft) into a service definition Once staged, the input draft service definition is deleted. Calling is_publishable will check for an existing *.sd file that is newer than source http://desktop.arcgis.com/en/arcmap/latest/tools/server-toolbox/stage-service.htm """ if force: self.__delete_file(self.__sd_file_name) if not self.is_publishable: raise PublishException( "Draft Service Definition has issues and is not ready to publish" ) if not self.__have_service_definition: # I do not have a service definition that is newer than the map/draft, # but I might have an old version # the arcpy method will fail if the sd file exists self.__delete_file(self.__sd_file_name) try: logger.info( "Begin arcpy.StageService_server(%s, %s)", self.__draft_file_name, self.__sd_file_name, ) arcpy.StageService_server(self.__draft_file_name, self.__sd_file_name) logger.info("Done arcpy.StageService_server()") self.__have_service_definition = True self.__have_new_service_definition = True except Exception as ex: raise PublishException( "Unable to create the service definition file: {0}".format(ex) ) def __create_replacement_service_draft(self): """Modify the service definition draft to overwrite the existing service The existing draft file is overwritten. Need to check if this is required before calling. """ logger.debug("Fixing draft file %s for replacement", self.__draft_file_name) new_type = "esriServiceDefinitionType_Replacement" file_name = self.__draft_file_name x_doc = xml.dom.minidom.parse(file_name) descriptions = x_doc.getElementsByTagName("Type") for desc in descriptions: if desc.parentNode.tagName == "SVCManifest": if desc.hasChildNodes(): logger.debug( "Update tag %s from %s to %s", desc.firstChild, desc.firstChild.data, new_type, ) desc.firstChild.data = new_type with open(file_name, "w", encoding="utf-8") as out_file: x_doc.writexml(out_file) logger.debug("Draft file fixed.") def __publish_service(self, force=False): # TODO: Support the optional parameters to UploadServiceDefinition_server """Publish Service Definition Uploads and publishes a GIS service to a specified GIS server based on a staged service definition (.sd) file. http://desktop.arcgis.com/en/arcmap/latest/tools/server-toolbox/upload-service-definition.htm arcpy.UploadServiceDefinition_server (in_sd_file, in_server, {in_service_name}, {in_cluster}, {in_folder_type}, {in_folder}, {in_startupType}, {in_override}, {in_my_contents}, {in_public}, {in_organization}, {in_groups}) server can be one of the following A name of a server connection in ArcCatalog; i.e. server = r'GIS Servers/arcgis on my_server (publisher)' A full path to an ArcGIS Server connection file (*.ags) created in ArcCatalog; i.e. server = r'C:/path/to/my/connection.ags' A relative path (relative to the cwd of the process running the script) to an ArcGIS Server connection file (*.ags) created in ArcCatalog 'My Hosted Services' to publish to AGOL or Portal (you must be signed in to one or the other for this to work.) sd_file (A service definition (.sd) contains all the information needed to publish a GIS service) can be A full path to an sd file A relative path (relative to the cwd of the process running the script) to an sd file A relative path (relative to the arcpy.env.workspace setting) to an sd file This will publish the sd_file to the server with the following defaults (can be overridden with additional parameters) the service will be created with the folder/name as specified in the sd_file the service will be assigned to the default cluster service will be started after publishing AGOL/Portal services will be shared per the settings in the sd_file """ if not self.__have_service_definition: self.__create_service_definition(force=force) if not self.__have_service_definition: raise PublishException( "Service Definition (*.sd) file is not ready to publish" ) if self.__service_connection_file_path is None: # conn = ' '.join([word.capitalize() for word in self.__service_server_type.split('_')]) conn = "My Hosted Services" else: conn = self.__service_connection_file_path # only publish if we need to. if force or not self.is_live or self.__have_new_service_definition: try: logger.info( "Begin arcpy.UploadServiceDefinition_server(%s, %s)", self.__sd_file_name, conn, ) arcpy.UploadServiceDefinition_server(self.__sd_file_name, conn) logger.info("Done arcpy.UploadServiceDefinition_server()") except Exception as ex: raise PublishException("Unable to upload the service: {0}".format(ex)) def __get_service_type_from_server(self): # TODO: Implement # if folder is None call /services?f=json # else: call /services/folder?f=json if folder is in /services?f=json resp['folders'] # find service in response['services'] # find service['serviceName'] = service, and grab the service['type'] # do case insensitive compares logger.debug( "Get service type from server %s, %s", self.server_url, self.service_path ) if self.server_url is None: logger.debug("Server URL is undefined.") return None url = self.server_url + "/rest/services?f=json" name = self.__service_name.lower() if self.__service_folder_name is not None: url = self.server_url + "/rest/services/folder?f=json" name = ( self.__service_folder_name.lower() + "/" + self.__service_name.lower() ) try: data = requests.get(url).json() logger.debug("Server response: %s", data) # sample response: {..., "services": # [{"name": "WebMercator/DENA_Final_IFSAR_WM", "type": "ImageServer"}]} services = [ service for service in data["services"] if service["name"].lower() == name ] except Exception as ex: logger.warning("Failed to get service list from server, %s", ex) return None logger.debug("services found: %s", services) if len(services) == 0: logger.info("Service %s not found on server", self.__service_name) return None try: service_type = services[0]["type"] except KeyError: logger.error("Response from server was invalid (no service type), %s") return None logger.debug("services type found: %s", services) return service_type # Private Class Methods @staticmethod def __delete_file(path): if not os.path.exists(path): return try: logger.debug("deleting %s", path) os.remove(path) except Exception: raise PublishException("Unable to delete {0}".format(path)) @staticmethod def __file_exists_and_is_newer(new_file, old_file): try: if new_file is None or not os.path.exists(new_file): return False if old_file is None or not os.path.exists(old_file): return True old_mtime = os.path.getmtime(old_file) new_mtime = os.path.getmtime(new_file) return old_mtime < new_mtime except Exception as ex: logger.warning( "Exception raised checking for file A newer than file B: %s", ex ) return False @staticmethod def __get_token(url, username, password): # TODO: use url/rest/info?f=json resp['authInfo']['tokenServicesUrl'] + generateTokens logger.debug("Generate admin token") path = "/admin/generateToken" # path = '/tokens/generateToken' requires https? data = { "f": "json", "username": username, "password": password, "client": "request_ip", "expiration": "60", } try: response = requests.post(url + path, data=data) response.raise_for_status() except requests.exceptions.RequestException as ex: logger.error(ex) return None json_response = response.json() logger.debug("Login Response: %s", json_response) try: if "token" in json_response: return json_response["token"] if "error" in json_response: logger.debug("Server response: %s", json_response) logger.error( "%s (%s)", json_response["error"]["message"], ";".join(json_response["error"]["details"]), ) else: raise TypeError except (TypeError, KeyError): logger.error( "Invalid server response while generating token: %s", json_response ) return None
true
6fa39e4ff55308b0429228679d0bdb20233bcb75
Python
Amrit-Raj-2506/Python-
/Linked List -2/swap two node (LL) .py
UTF-8
2,051
3.546875
4
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Node: def __init__(self, data): self.data = data self.next = None def swap_nodes(head, i, j): counti=0 countj=0 curr=head prev=None if(i<j): I=i J=j else: I=j J=i while curr is not None: if counti>I and countj>J: break if counti==I: ihead=curr if(curr.next is not None): iheadnext=curr.next else: iheadnext=None iprev=prev if countj==J: jhead=curr if(jhead.next is not None): jheadnext=jhead.next else: jheadnext=None jprev=prev counti+=1 countj+=1 prev=curr curr=curr.next if ihead == jprev: if iprev is not None: iprev.next=jhead jhead.next=ihead ihead.next=jheadnext return head else: jhead.next=ihead ihead.next=jheadnext return jhead if iprev is None: jprev.next=ihead jhead.next=iheadnext ihead.next=jheadnext return jhead iprev.next=jhead jprev.next=ihead jhead.next=iheadnext ihead.next=jheadnext return head ############################# # PLEASE ADD YOUR CODE HERE # ############################# pass def ll(arr): if len(arr)==0: return None head = Node(arr[0]) last = head for data in arr[1:]: last.next = Node(data) last = last.next return head def printll(head): while head: print(head.data, end=' ') head = head.next print() # Main # Read the link list elements including -1 arr=list(int(i) for i in input().strip().split(' ')) # Create a Linked list after removing -1 from list l = ll(arr[:-1]) i, j=list(int(i) for i in input().strip().split(' ')) l = swap_nodes(l, i, j) printll(l)
true
a26324188630c5fe1857332d716c7569317894fb
Python
shen-huang/selfteaching-python-camp
/exercises/1901100075/1001S02E05_array.py.py
UTF-8
1,139
4.15625
4
[]
no_license
a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] reverse=a[::-1] print('将数组 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 翻转==>',reverse) #翻转后的数组拼接成字符串 #调用''(空字符串)str类型的join方法可以连接列表里面的元素,用''(空字符串)表示连接的时候元素间不用字符隔开 #因为reserve里面都是int类型的元素,所以拼接之前要把reserve变成一个包含str类型元素的列表 join_str=''.join([str(i)for i in reverse]) print('翻转后的数组拼接成字符串==>',join_str) #⽤字符串切⽚的⽅式取出第三到第⼋个字符(包含第三和第⼋个字符) slice_str=join_str[2:8] print('⽤字符串切⽚的⽅式取出第三到第⼋个字符(包含第三和第⼋个字符)==>',slice_str) #将获得的字符串进⾏翻转 reserve_str=slice_str[::-1] print(reserve_str) #将结果转换为 int 类型 #分别转换成⼆进制,⼋进制,⼗六进制 int_value=int(reserve_str) print('转换为int类型==>',int_value) print('转换为二进制==>',bin(int_value)) print('转换为八进制==>',oct(int_value)) print('转换为十六进制==>',hex(int_value))
true
e41a52950ca8d64eb5f3b1e50bb6f11f4c2e865e
Python
AyelenDemaria/frro-soporte-2019-23
/practico_01/ejercicio-10.py
UTF-8
850
4.28125
4
[]
no_license
# Implementar las funciones superposicion_x(), que tomen dos listas y devuelva un booleano en base a # si tienen al menos 1 elemento en común. # se debe implementar utilizando bucles anidados. def superposicion_loop(lista_1, lista_2): b = 'F' for i in lista_1: for j in lista_2: if i == j: b = 'T' break if b == 'T': return True return False assert(superposicion_loop(['n',9,0],[1,5,'n'])) == True assert(superposicion_loop(['n',9,0],[1,5,7])) == False # se debe implementar utilizando conjuntos (sets). def superposicion_set(lista_1, lista_2): if (set(lista_1) & set(lista_2)) != set(): #set() es un conjunto vacio return True return False assert(superposicion_set(['n',9,0],[1,5,'n'])) == True assert(superposicion_set(['n',9,0],[1,5,7])) == False
true
d1ae09467b6d8a5c94e496503a6227f2beebc236
Python
shrikantpadhy18/INTERVIEW_QUESTIONS
/Leetcode/LIS.py
UTF-8
375
2.734375
3
[]
no_license
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: ps=[1]*(len(nums)) print(ps) for i in range(len(nums)-1): for j in range(i+1,len(nums)): if(nums[j]>nums[i] and ps[j]<ps[i]+1): ps[j]=ps[i]+1 if(ps==[]): return 0 return(max(ps))
true
32516d0f2bf72a52071e83f2b6992ea6fcff2332
Python
SupriyaMagare/test-demo
/If.py
UTF-8
778
4.1875
4
[]
no_license
# Example1 if ('Python' in ['Java','C#','Python']): print("Python is present in the list") if('C#' in ['Java','C#','Python']): print("C# is present in the list") if('Java' in ['Java','C#','Python']): print("Java is present in the list") # Example 2 Nested if print("Example2") num=-7 if (num!=0): if(num>0): print("Number is Positive") else: print("Number is Negative") else: print("number is zero") #Elif Ladder my_marks= int( input("Enter your Marks")) if(my_marks < 35): print("Sorry you are failed in the exam") elif(my_marks<60): print("Passed in the second class") elif(my_marks>60 and my_marks< 85): print("Passed in the first class") else: print('Passed in the distinction')
true
e707ae3ab39e3115c3bb823b9cfa6c8513270602
Python
xyztank/Appium_Test
/tests/test_api_demos_android.py
UTF-8
648
2.75
3
[]
no_license
""" Practicing automating different common mobile interactions in test app on Android """ from page_objects.Android.home_page_android import HomePageAndroid import datetime def test_change_date(driver_android_app): page = HomePageAndroid(driver_android_app) page.open_date_widgets_dialog() page.change_date() # Validating that changed date is tomorrow date: assert page.get_date() == str(datetime.date.today() + datetime.timedelta(days=1))[8:] def test_scrolling(driver_android_app): page = HomePageAndroid(driver_android_app) page.scroll_and_open_web_view() assert page.get_web_view_title() == "Views/WebView"
true
0d11ce2f75c89d57c3ee9c8a8f177208964c7ecf
Python
AccessibleAI/ailibrary
/tf2_deep_resnet50/resnet50.py
UTF-8
5,622
2.515625
3
[ "Apache-2.0" ]
permissive
""" All rights reserved to cnvrg.io http://www.cnvrg.io cnvrg.io - AI library Created by: Omer Liberman Last update: Jan 26th, 2020 Updated by: Omer Liberman resnet50.py ============================================================================== """ import argparse import tensorflow as tf from _src.tensor_trainer_utils import * from _src.tensorflow_trainer import * if __name__ == '__main__': parser = argparse.ArgumentParser(description="""ResNet50 Model""") parser.add_argument('--data', action='store', dest='data', required=True, help="""(String) (Required param) Path to a local directory which contains sub-directories, each for a single class. The data is used for training and validation.""") parser.add_argument('--data_test', action='store', dest='data_test', default=None, help="""(String) (Default: None) Path to a local directory which contains sub-directories, each for a single class. The data is used for testing.""") parser.add_argument('--project_dir', action='store', dest='project_dir', help="""String. (String) cnvrg.io parameter. NOT used by the user!""") parser.add_argument('--output_dir', action='store', dest='output_dir', help="""String. (String) cnvrg.io parameter. NOT used by the user!""") parser.add_argument('--test_mode', action='store', default=False, dest='test_mode', help="""--- For inner use of cnvrg.io ---""") parser.add_argument('--output_model', action='store', default="model.h5", dest='output_model', help="""(String) (Default: 'model.h5') The name of the output model file. It is recommended to use '.h5' file.""") parser.add_argument('--validation_split', action='store', default="0.", dest='test_size', help="""(float) (Default: 0.) The size of the validation set. If test set supplied, it represents the size of the validation set out of the data set given in --data. Otherwise, it represents the size of the test set out of the data set given in --data.""") parser.add_argument('--epochs', action='store', default="1", dest='epochs', help="""(int) (Default: 1) The number of epochs the algorithm performs in the training phase.""") parser.add_argument('--steps_per_epoch', action='store', default="None", help="""(int or None) (Default: None) If its None -> num of samples / batch_size, otherwise -> The number of batches done in each epoch.""") parser.add_argument('--batch_size', action='store', default="32", dest='batch_size', help="""(int) (Default: 32) The number of images the generator downloads in each step.""") parser.add_argument('--workers', action='store', default="1", dest='workers', help="""(int) (Default: 1) The number of workers which are used.""") parser.add_argument('--multi_processing', action='store', default="False", dest='multi_processing', help="""(boolean) (Default: False) Indicates whether to run multi processing.""") parser.add_argument('--verbose', action='store', default='1', dest='verbose', help="""(integer) (Default: 1) can be either 1 or 0.""") parser.add_argument('--image_color', action='store', dest='image_color', default='rgb', help="""(String) (Default: 'rgb') The colors of the images. Can be one of: 'grayscale', 'rgb'.""") parser.add_argument('--loss', action='store', dest='loss', default='cross_entropy', help="""(String) (Default: 'crossentropy') The loss function of the model. By default its binary_crossentropy or categorical_crossentropy, depended of the classes number.""") parser.add_argument('--dropout', action='store', dest='dropout', default='0.3', help="""(float) (Default: 0.3) The dropout of the added fully connected layers.""") parser.add_argument('--optimizer', action='store', dest='optimizer', default='adam', help="""(String) (Default: 'adam') The optimizer the algorithm uses. Can be one of: 'adam', 'adagrad', 'rmsprop', 'sgd'.""") parser.add_argument('--image_width', action='store', default="256", dest='image_width', help="""(int) (Default: 256) The width of the images.""") parser.add_argument('--image_height', action='store', default="256", dest='image_height', help="""(int) (Default: 256) The height of the images.""") parser.add_argument('--conv_width', action='store', default="3", dest='conv_width', help="""(int) (Default: 3) The width of the convolution window.""") parser.add_argument('--conv_height', action='store', default="3", dest='conv_height', help="""(int) (Default: 3) The height of the convolution window.""") parser.add_argument('--pooling_width', action='store', default="2", dest='pool_width', help="""(int) (Default: 2) The width of the pooling window.""") parser.add_argument('--pooling_height', action='store', default="2", dest='pool_height', help="""(int) (Default: 2) The height of the pooling window.""") parser.add_argument('--hidden_layer_activation', action='store', default='relu', dest='hidden_layer_activation', help="""(String) (Default: 'relu') The activation function of the hidden layers.""") parser.add_argument('--output_layer_activation', action='store', default='softmax', dest='output_layer_activation', help="""(String) (Default: 'softmax') The activation function of the output layer.""") args = parser.parse_args() args = cast_input_types(args) channels = 3 if args.image_color == 'rgb' else 1 base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False, input_shape=(args.image_height, args.image_width, channels)) trainer = TensorflowTrainer(args, 'resnet50', base_model) trainer.run()
true
7557f1d4a9193d85f31feeb314f9012276a8b577
Python
Sunghwan-DS/TIL
/Python/BOJ/BOJ_15684.py
UTF-8
1,174
2.703125
3
[]
no_license
def check(lst, res): global ans for j in range(N): x = j i = 0 while i < H: if x-1 >= 0 and lst[i][x-1]: x -= 1 elif x+1 <= N-1 and lst[i][x]: x += 1 i += 1 if j == x: pass else: return if ans > res: ans = res def order(idx, pre, save): if idx == 0: check(pre, idx) if idx == 1: check(pre, idx) if idx == 2: check(pre, idx) if idx == 3: check(pre, idx) return for i in range(save, H): for j in range(N-1): if pre[i][j]: continue if j+1 <= N-2 and pre[i][j+1]: continue if j-1 >= 0 and pre[i][j-1]: continue else: pre[i][j] = True order(idx+1, pre, i) pre[i][j] = False N, M, H = map(int,input().split()) arr = [[False] * (N-1) for _ in range(H)] for j in range(M): a, b = map(int,input().split()) arr[a-1][b-1] = True ans = 4 order(0, arr, 0) if ans == 4: print(-1) else: print(ans)
true
7c846889e8fe354fc2d92a2410bed62dddb868fb
Python
8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions
/Chapter04/0013_datetime_time_resolution.py
UTF-8
390
3.640625
4
[]
no_license
""" Listing 4.13 The resolution for time is limited to whole microseconds. Floating- point values for microseconds cause a TypeError """ import datetime def main(): for m in [1, 0, 0.1, 0.6]: try: print(f"{m:02.1f} {datetime.time(0, 0, 0, microsecond=m)}") except TypeError as err: print("ERROR:", err) if __name__ == "__main__": main()
true
82f8b2eeaa1304b0d2c592441aa8ee3e06d93160
Python
andymakespasta/Tactile_Reader
/pattern_speed_test/USBSerialSend.py
UTF-8
1,096
3.015625
3
[]
no_license
import serial, time, threading #globals check_input_wait = 0 #0 for never check #this is the actual sending function def port_power(port, power): ser.write(bytes([port%256])) # prefix b is required for Python 3.x, optional for Python 2.x ser.write(bytes([power%256])) #this function checks messages from the board, see global check_input_wait def check_input(): if(ser.inWaiting()>0): if check_input_wait != 0:#it uses a timer thread to repeatedly call itself check_thread.start() #tries the first ports for an active port port=0 while port < 10: try: ser = serial.Serial(port,9600,timeout=5) except: if port > 10: sys.exit() else: port = port + 1 print (ser.name) #this is the port name to save to settings in case if check_input_wait != 0: check_thread = threading.Timer(check_input_wait,check_input) while True: print("bump") port_power(0,8) time.sleep(1) data = ser.readline() print(data) port_power(1,7) time.sleep(1) data = ser.readline() print(data)
true
61beaf4b20f1b862943b526e5f791e76547b888f
Python
yamilmaud/Inmuebles
/Scraper.py
UTF-8
2,335
2.734375
3
[]
no_license
import re import Saver XPATH_PRECIO = '//h2[@class="ar15gris"]/b/text()' XPATH_TITULO1 = '//h2[@class="ar15gris"]/text()' XPATH_UBICACION = '//table[@class="ar13gris"]//text()' XPATH_DESCRIPCION = '//div[@id="infocompleta"]/text()' XPATH_MAPA = '//div[@id="divMapa"]/@onclick' REGEX_LOCATION = "(?:LatitudGM=)(.*?)(?:&LongitudGM=)(.*?)(?:')" REGEX_PRECIO = "\d.*,?" class Scraper: def __init__(self): self.__XPATH_MAPA = XPATH_MAPA self.__XPATH_PRECIO = XPATH_PRECIO self.__XPATH_UBICACION = XPATH_UBICACION self.__XPATH_TITULO1 = XPATH_TITULO1 self.__XPATH_DESCRIPCION = XPATH_DESCRIPCION def crear_dicc(self, parsed2, elemento, source, indice_link): objeto_mapa = parsed2.xpath(XPATH_MAPA) if len(objeto_mapa) > 0: # verifica que tenga mapa mapa = re.search(REGEX_LOCATION, objeto_mapa[0]) latitud = mapa.group(1) longitud = mapa.group(2) else: latitud = "Null" longitud = "Null" precio = re.findall(REGEX_PRECIO, (parsed2.xpath(XPATH_PRECIO)[1])) ubicacion = parsed2.xpath(XPATH_UBICACION) zona = parsed2.xpath(XPATH_TITULO1)[0] + parsed2.xpath(XPATH_PRECIO)[0].strip() colonia = parsed2.xpath(XPATH_TITULO1)[1].strip() + ' ' + ubicacion[3].strip() title = zona + ' ' + colonia description = parsed2.xpath(XPATH_DESCRIPCION)[0].strip() if indice_link%2 == 0: # verificar par o impar, para completar el diccionario land = "Null" construccion = "Null" else: land = ubicacion[7].strip() construccion = ubicacion[6].strip() dictionary = { "Price": precio, "Location": ubicacion[1].strip(), "Latitude": latitud.strip(), "Longitude": longitud.strip(), "Link": elemento, "Title": title.strip(), "Description": description.strip(), "Square Meter Land": land, "Square Meter Construction": construccion, "Bathroom": ubicacion[5].strip(), "Bedroom": ubicacion[4].strip(), "Source": source } file_name = "Inmobiliarias.csv" instancia_saver = Saver.Saver(file_name) instancia_saver.crear_csv(dictionary)
true
7eb39ac221258b6504524a95fefb13d384c9d95f
Python
hrkz/torchqg
/src/timestepper.py
UTF-8
2,675
3.109375
3
[ "MIT" ]
permissive
import math import torch class ForwardEuler: def __init__(self, eq): self.n = 1 self.S = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) def zero_grad(self): self.S.detach_() def step(self, m, sol, cur, eq, grid): dt = cur.dt t = cur.t eq.nonlinear_term(0, self.S, sol, dt, t, grid) self.S += eq.linear_term*sol.clone() sol += dt*self.S cur.step() class RungeKutta2: def __init__(self, eq): self.n = 2 self.S = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) self.rhs1 = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) self.rhs2 = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) def zero_grad(self): self.S.detach_() self.rhs1.detach_() self.rhs2.detach_() def step(self, m, sol, cur, eq, grid): dt = cur.dt t = cur.t # substep 1 eq.nonlinear_term(0, self.rhs1, sol, dt, t, grid) self.rhs1 += eq.linear_term*sol # substep 2 self.S = sol + self.rhs1 * dt*0.5 eq.nonlinear_term(1, self.rhs2, self.S, dt*0.5, t + dt*0.5, grid) self.rhs2 += eq.linear_term*self.S sol += dt*self.rhs2 cur.step() class RungeKutta4: def __init__(self, eq): self.n = 4 self.S = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) self.rhs1 = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) self.rhs2 = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) self.rhs3 = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) self.rhs4 = torch.zeros(eq.dim, dtype=torch.complex128, requires_grad=True).to(eq.device) def zero_grad(self): self.S.detach_() self.rhs1.detach_() self.rhs2.detach_() self.rhs3.detach_() self.rhs4.detach_() def step(self, m, sol, cur, eq, grid): dt = cur.dt t = cur.t # substep 1 eq.nonlinear_term(0, self.rhs1, sol, dt, t, grid) self.rhs1 += eq.linear_term*sol # substep 2 self.S = sol + self.rhs1 * dt*0.5 eq.nonlinear_term(1, self.rhs2, self.S, dt*0.5, t + dt*0.5, grid) self.rhs2 += eq.linear_term*self.S # substep 3 self.S = sol + self.rhs2 * dt*0.5 eq.nonlinear_term(2, self.rhs3, self.S, dt*0.5, t + dt*0.5, grid) self.rhs3 += eq.linear_term*self.S # substep 4 self.S = sol + self.rhs3 * dt eq.nonlinear_term(3, self.rhs4, self.S, dt, t + dt, grid) self.rhs4 += eq.linear_term*self.S sol += dt*(self.rhs1/6.0 + self.rhs2/3.0 + self.rhs3/3.0 + self.rhs4/6.0) cur.step()
true
53ce4dab09a1e7d6043955431234e621f8bb9500
Python
kmshelley/Mumbler
/get_ngrams.py
UTF-8
4,992
2.703125
3
[]
no_license
import urllib import os import zipfile import contextlib import ast def update_word_dict(old_dict,new_dict): #updates a dictionary of word counts for key in old_dict: if key not in new_dict: new_dict[key] = old_dict[key] else: for key2 in old_dict[key]: if key2 in new_dict[key]: new_dict[key][key2]+=old_dict[key][key2] else: new_dict[key][key2] = old_dict[key][key2] return new_dict def OLD_update_word_dict(old_dict,new_dict): #updates a dictionary of word counts for key in old_dict: if key not in new_dict: new_dict[key] = old_dict[key] else: new_dict[key]+=old_dict[key] return new_dict def get_2_grams(m,n,machine): for i in range(m,n): url = 'http://storage.googleapis.com/books/ngrams/books/googlebooks-eng-all-2gram-20090715-%s.csv.zip' % str(i) #my_dir = '/gpfs/gpfsfpo/letters/' my_dir = os.path.join(os.getcwd(),'letters') filename = os.path.join(my_dir,'googlebooks-eng-all-2gram-20090715-%s.csv.zip' % str(i)) urllib.urlretrieve(url,filename) z = zipfile.ZipFile(filename,allowZip64=True) for doc in z.namelist(): if doc.find('googlebooks-eng-all-2gram-20090715-%s.csv' % str(i)) > -1: with contextlib.closing(z.open(doc,'r')) as unzipped: words = {} #prev_word = None prev_letter = None for line in unzipped: if len(line.strip().split())==6: word1,word2,year,match_count,page_count,volume_count = line.lower().strip().split() letter = word1[0] if word1.isalpha() and word2.isalpha(): #if word1 <> prev_word and prev_word: if letter <> prev_letter and prev_letter: try: #z2 = zipfile.ZipFile('/gpfs/gpfsfpo/letters/%s_%s.zip' % (prev_letter,machine), mode='r',allowZip64=True, compression=zipfile.ZIP_DEFLATED) z2 = zipfile.ZipFile(os.path.join(my_dir,'%s_%s.zip' % (prev_letter,machine)),mode='r',allowZip64=True, compression=zipfile.ZIP_DEFLATED) old_words = ast.literal_eval(z2.read('%s' % prev_letter )) if old_words <> '': words = update_word_dict(old_words,words) z2.close() except: pass #z2 = zipfile.ZipFile('/gpfs/gpfsfpo/letters/%s_%s.zip' % (prev_letter,machine),mode='w',allowZip64=True, compression=zipfile.ZIP_DEFLATED) z2 = zipfile.ZipFile(os.path.join(my_dir,'%s_%s.zip' % (prev_letter,machine)),mode='w',allowZip64=True, compression=zipfile.ZIP_DEFLATED) z2.writestr('%s' % prev_letter, str(words)) words = {} #prev_word = word1 prev_letter = letter if word1 not in words: words[word1] = {} if word2 not in words[word1]: words[word1][word2] = 0.0 words[word1][word2]+=float(match_count) os.remove(filename) print "Done getting 2-grams!" get_2_grams(0,1,1)
true
d87cfbc4698fc634344ac925b2b03d49786ddd6e
Python
SurajGutti/CodingChallenges
/Trees/delNodesAndReturnForest.py
UTF-8
2,156
3.953125
4
[]
no_license
''' Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000. ''' ''' The question is composed of two requirements: To remove a node, the child need to notify its parent about the child's existance. To determine whether a node is a root node in the final forest, we need to know [1] whether the node is removed (which is trivial), and [2] whether its parent is removed (which requires the parent to notify the child) It is very obvious that a tree problem is likely to be solved by recursion. The two components above are actually examining interviewees' understanding to the two key points of recursion: passing info downwards -- by arguments passing info upwards -- by return value Fun fact I've seen this question in 2016 at a real newgrad interview. It was asked by a very well-known company and was a publicly known question at that time. I highly doubt that the company will ask this question again nowadays.''' class Solution(object): def delNodes(self, root, to_delete): to_delete = set(to_delete) res = [] def walk(root, parent_exist): if root is None: return None if root.val in to_delete: root.left = walk(root.left, parent_exist=False) root.right = walk(root.right, parent_exist=False) return None else: if not parent_exist: res.append(root) root.left = walk(root.left, parent_exist=True) root.right = walk(root.right, parent_exist=True) return root walk(root, parent_exist=False) return res
true
518261f0eeb81c1c11137450cf6640c91ec75e81
Python
xlcwzx/prj2doc
/prj2doc.py
UTF-8
12,358
2.609375
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Project to Document utility. Written by PWX <airyai@gmail.com> in Feb. 2012. This utility will collect project sources under current directory, highlight their syntax, and output as a whole document. ''' from __future__ import unicode_literals, print_function import os, sys, fnmatch import re, getopt import codecs #sys.setdefaultencoding('utf-8') import chardet from pygments import highlight from pygments.lexers import guess_lexer_for_filename from pygments.formatters import get_formatter_for_filename, HtmlFormatter from pygments.styles import get_style_by_name, get_all_styles from pygments.util import ClassNotFound # templates ALLOW_WHITESPACE_FILTER = set(('.c', '.cpp', '.cc', '.h', '.hpp', '.cs', '.vb', '.js', '.php', '.java')) DEFAULT_PATTERNS = ('Makefile*', '*.cpp', '*.cc', '*.hpp', '*.c', '*.h', '*.py', '*.pyw', '*.java', '*.cs', '*.vb', '*.js', '*.php*') DEFAULT_COMMENT_START = '//' COMMENT_STARTS = {} COMMENT_STARTS['Python'] = '#' COMMENT_STARTS['Makefile'] = '#' COMMENT_STARTS['VB.net'] = '\'' FILE_HEADER_TEMPLATE = ''' 文件:{filename} 语法:{language} 行数:{line} '''.strip() CURRENT_DIR_PREFIX = '.' + os.path.sep def generate_header(filename, language, line): if (filename.startswith(CURRENT_DIR_PREFIX)): filename = filename[len(CURRENT_DIR_PREFIX):] ret = FILE_HEADER_TEMPLATE.format(filename=filename, language=language, line=line).split('\n') width = 0 for l in ret: lw = 0 for c in l: if (ord(c) < 256): lw += 1 else: lw += 2 width = max(width, lw) cmstart = COMMENT_STARTS.get(language, DEFAULT_COMMENT_START) hr = '{0}{1}'.format(cmstart, '=' * (width+1)) ret = [hr] + ['{0} {1}'.format(cmstart, l) for l in ret] + [hr] return '\n'.join(ret) # utilities def readfile(path): with open(path, 'rb') as f: return f.read() def writefile(path, cnt): with open(path, 'wb') as f: f.write(codecs.BOM_UTF8) f.write(cnt.encode('utf-8')) # parse arguments SHORT_OPT_PATTERN = 'ho:s:m:l:' LONG_OPT_PATTERN = ('output=', 'style=', 'makefile=', 'help', 'list-style', 'linenos=') def usage(): print ('Usage: prj2doc [选项] ... [输入通配符] ...') print ('Written by 平芜泫 <airyai@gmail.com>。') print ('') print ('如果没有指定输入通配符,那么当前目录、以及子目录下的所有文件将被选择。\n' '否则将在当前目录和子目录下搜索所有符合通配符的文件。如果所有被选择的\n' '文件中存在 Makefile,那么文件的排列顺序将参照 Makefile 中第一次出现的\n' '顺序。') print ('') print (' -o, --output= 输出文档的路径。文档类型会根据扩展名猜测。') print (' 如果没有指定,则输出 project.html 和 project.doc。') print (' 支持的扩展名:html, doc, tex。') print (' 注:doc 只在 Windows 下可用,且转换后需要手工微调。') print (' -m, --makefile= 指定一个 Makefile 文件。') print (' -s, --style= 设定代码高亮的配色方案。默认为 colorful。') print (' --list-style 列出所有支持的配色方案。') print (' -l, --lineno=[on/off] 打开或关闭源文件每一行的行号。') print (' -h, --help 显示这个信息。') def listStyles(): print (' '.join(get_all_styles())) optlist, args = getopt.getopt(sys.argv[1:], SHORT_OPT_PATTERN, LONG_OPT_PATTERN) OUTPUT = [] MKPATTERN = '*Makefile*' MAKEFILE = None STYLE = 'colorful' LINENOS = True def GET_LINENOS(fmt): return True if LINENOS else False for (k, v) in optlist: if (k in ('-o', '--output=')): OUTPUT.append(v) elif (k in ('-s', '--style=')): STYLE = v elif (k in ('--list-style')): listStyles() sys.exit(0) elif (k in ('-l', '--lineno=')): LINENOS = (v == 'on') elif (k in ('-m', '--makefile=')): MKPATTERN = v elif (k in ('-h', '--help')): usage() sys.exit(0) PATTERNS = args if (len(PATTERNS) == 0): PATTERNS = DEFAULT_PATTERNS if (len(OUTPUT) == 0): OUTPUT = ['project.html'] if (sys.platform == 'win32'): OUTPUT.append('project.doc') # scan input files FORBIDS = ('prj2doc*', ) def scan_dir(path, file_list): global MAKEFILE dir_list = [] # first list all files under the directory for p in os.listdir(path): p2 = os.path.join(path, p) if (os.path.isdir(p2)): dir_list.append(p2) else: flag = True for pattern in FORBIDS: if (fnmatch.fnmatch(p, pattern)): flag = False if (not flag): continue for pattern in PATTERNS: if (fnmatch.fnmatch(p, pattern)): file_list.append(os.path.normcase(p2)) if (MAKEFILE is None and fnmatch.fnmatch(p, MKPATTERN)): MAKEFILE = os.path.normcase(p2) # then recursively scan for p2 in dir_list: scan_dir(p2, file_list) INPUTS = [] print ('正在扫描目录下的所有源文件...') scan_dir('.', INPUTS) # check Makefile phrase_map = {} if (MAKEFILE is not None): makefile = readfile(MAKEFILE) regex = re.compile('\\s+') phrases = regex.split(makefile.lower()) phrases.insert(0, MAKEFILE) phindex = 0 for p in phrases: p = os.path.normcase(p) if (os.path.isfile(p)): n = os.path.split(p)[1] n = os.path.splitext(n)[0] phrase_map.setdefault(n, phindex) phindex += 1 def ext_compare(x, y): if (x == '.h' and y == '.cpp'): return -1 elif (x == '.cpp' and y == '.h'): return 1 else: return cmp(x, y) def filename_compare(x, y): xx = os.path.splitext(os.path.split(x)[1]) yy = os.path.splitext(os.path.split(y)[1]) xi = phrase_map.get(xx[0], None) yi = phrase_map.get(yy[0], None) if (xi is not None and yi is not None): ret = cmp(xi, yi) if (ret != 0): return ret return ext_compare(xx[1], yy[1]) elif (xi is not None): return -1 elif (yi is not None): return 1 else: ret = cmp(xx[0], yy[0]) if (ret != 0): return ret return ext_compare(xx[1], yy[1]) INPUTS.sort(filename_compare) # convert via MS Office try: import win32com.client WIN32_SUPPORT = True except ImportError: WIN32_SUPPORT = False pass CONV_TEMP = None CONV_LIST = [] if WIN32_SUPPORT: # define convert function def html2doc(htmlPath, docPath): word = win32com.client.Dispatch('Word.Application') doc = word.Documents.Open(os.path.abspath(htmlPath).encode(sys.getfilesystemencoding())) doc.SaveAs(os.path.abspath(docPath).encode(sys.getfilesystemencoding()), FileFormat=0) doc.Close() word.Quit() # process list CONV_LIST = [] new_output = [] CONV_TEMP = 'prj2doc.temp.html' for i in range(0, len(OUTPUT)): if (os.path.splitext(OUTPUT[i])[1].lower() in ('.doc', )): CONV_LIST.append(OUTPUT[i]) else: new_output.append(OUTPUT[i]) if (len(CONV_LIST) > 0): new_output.append(CONV_TEMP) OUTPUT = new_output # create formatters & lexers for output files FORMATTERS = {} CONTENTS = {} LEXERS = {} print ('读取源文件,并载入代码高亮引擎...') try: STYLE = get_style_by_name(STYLE) except ClassNotFound: print ('未定义的配色方案 {0}。'.format(STYLE)) sys.exit(10) for o in OUTPUT: try: f = get_formatter_for_filename(o) f.style = STYLE f.encoding = 'utf-8' #f.noclasses = True #f.nobackground = True FORMATTERS[o] = f except ClassNotFound: print ('不支持的输出格式 {0}。'.format(o)) sys.exit(12) def front_tab_to_space(x): for i in range(0, len(x)): if (x[i] != '\t'): return ' ' * i + x[i:] return ' ' * len(x) for i in INPUTS: try: cnt = readfile(i) if (len(cnt) == 0): continue CONTENTS[i] = cnt except Exception as ex: print ('无法读取源文件 {0}:{1}。'.format(i, ex)) #sys.exit(11) try: l = guess_lexer_for_filename(i, readfile(i)) l.encoding = 'utf-8' LEXERS[i] = l except ClassNotFound: print ('不能确定源文件 {0} 的语法类型。'.format(i)) #sys.exit(13) if (len(CONTENTS) == 0): print ('没有找到任何非空输入文件。') sys.exit(0) # generating sources for each file CHARDET_REPLACE = {'gb2312': 'gb18030', 'gbk': 'gb18030'} def detect_encoding(cnt): ret = chardet.detect(cnt)['encoding'] if (ret is None): ret = sys.getfilesystemencoding() ret = ret.lower() return CHARDET_REPLACE.get(ret, ret) HIGHLIGHTS = {o:[] for o in OUTPUT} HIGHLIGHT_STYLES = {} for k in INPUTS: if (k not in CONTENTS or k not in LEXERS): continue print ('正在处理 {0} ...'.format(k)) lexer = LEXERS[k] cnt = CONTENTS[k] encoding = detect_encoding(cnt) if (encoding != 'gb18030' and encoding != 'utf-8'): encoding = sys.getfilesystemencoding() # Special hack!!! cnt = unicode(cnt, encoding) if (os.path.splitext(k)[1].lower() in ALLOW_WHITESPACE_FILTER): cnt = '\n'.join([front_tab_to_space(x) for x in cnt.split('\n')]) for o in OUTPUT: if (o not in FORMATTERS): continue f = FORMATTERS[o] header = generate_header(k, lexer.name, cnt.count('\n') + 1) # header f.linenos = False HIGHLIGHTS[o].append(unicode(highlight(header, lexer, f), 'utf-8')) # body f.linenos = GET_LINENOS(f) if (o != CONV_TEMP) else False f.nobackground = (o == CONV_TEMP) HIGHLIGHTS[o].append(unicode(highlight(cnt, lexer, f), 'utf-8')) # style if (o not in HIGHLIGHT_STYLES and hasattr(f, 'get_style_defs')): HIGHLIGHT_STYLES[o] = '\n'.join([f.get_style_defs('')]) # combining outputs COMBINE_TEMPLATE_HTML = ''' <html> <head> <title>Project Document</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8;" /> <style> pre {{ margin: 3px 2px; }} .linenodiv {{ background: #eeeeee; padding-right: 1px; margin-right: 2px; text-align: right; }} * {{ font-size: 13px; font-family: WenQuanYi Micro Hei Mono, 微软雅黑, Droid Sans, DejaVu Sans Mono, monospace; }} {style} </style> </head> <body> {body} </body> </html> '''.strip() def combine_html(outputs, path): ret = [] for i in range(0, len(outputs), 2): ret.append('<p>{0}\n{1}</p>'.format(outputs[i], outputs[i+1])) return COMBINE_TEMPLATE_HTML.format(body='\n<p>&nbsp;</p>\n'.join(ret), style=HIGHLIGHT_STYLES.get(path, '')) def combine_other(outputs, path): return '\n'.join(outputs) COMBINE_TABLE = {'.html': combine_html, '.htm': combine_html} print ('将结果写入指定的输出 ...') for o in OUTPUT: try: writefile(o, COMBINE_TABLE.get(os.path.splitext(o)[1].lower(), combine_other)(HIGHLIGHTS[o], o)) except Exception as ex: print ('写入文件 {0} 失败:{1}。'.format(o, ex)) # do office convert if (WIN32_SUPPORT and os.path.isfile(CONV_TEMP)): conv_body = unicode(readfile(CONV_TEMP), 'utf-8') for cv in CONV_LIST: try: html2doc(CONV_TEMP, cv) except Exception as ex: writefile(os.path.join(os.path.dirname(CONV_TEMP), cv + ".html"), conv_body) print ('转换文件为 {0} 失败,保留中间文件 {0}.html。'.format(cv)) os.remove(CONV_TEMP)
true
f53cd578470a806d033949001bfe9b8003bc7ec1
Python
CodingSmith/autoencoder-demo
/autoencoder.py
UTF-8
4,197
2.796875
3
[]
no_license
import tensorflow as tf #from utils import Mnist import tensorflow.examples.tutorials.mnist.input_data as input_data import os import datetime logdir = "tensorboard/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + "/" # Parameter learning_rate = 0.001 training_epochs = 500 batch_size = 256 display_step = 1 examples_to_show = 10 mnist = input_data.read_data_sets("/home/baofeng/project_code/GAN/Conditional-GAN/data/mnist", one_hot=True) # Network Parameters n_input = 784 # MNIST data input (img shape: 28*28) # hidden layer settings n_hidden_1 = 256 # 1st layer num features n_hidden_2 = 128 # 2nd layer num features n_hidden_3 = 64 # 3rd layer num features X = tf.placeholder(tf.float32, [None,n_input]) weights = { 'encoder_h1':tf.Variable(tf.random_normal([n_input,n_hidden_1])), 'encoder_h2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2])), 'encoder_h3': tf.Variable(tf.random_normal([n_hidden_2,n_hidden_3])), 'decoder_h1': tf.Variable(tf.random_normal([n_hidden_3,n_hidden_2])), 'decoder_h2': tf.Variable(tf.random_normal([n_hidden_2,n_hidden_1])), 'decoder_h3': tf.Variable(tf.random_normal([n_hidden_1, n_input])), } biases = { 'encoder_b1': tf.Variable(tf.random_normal([n_hidden_1])), 'encoder_b2': tf.Variable(tf.random_normal([n_hidden_2])), 'encoder_b3': tf.Variable(tf.random_normal([n_hidden_3])), 'decoder_b1': tf.Variable(tf.random_normal([n_hidden_2])), 'decoder_b2': tf.Variable(tf.random_normal([n_hidden_1])), 'decoder_b3': tf.Variable(tf.random_normal([n_input])), } # Building the encoder def encoder(x): # Encoder Hidden layer with sigmoid activation #1 layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1'])) # Decoder Hidden layer with sigmoid activation #2 layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2'])) layer_3 = tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['encoder_h3']), biases['encoder_b3'])) return layer_3 # Building the decoder def decoder(x): # Encoder Hidden layer with sigmoid activation #1 layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']), biases['decoder_b1'])) # Decoder Hidden layer with sigmoid activation #2 layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']), biases['decoder_b2'])) layer_3 = tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['decoder_h3']), biases['decoder_b3'])) return layer_3 # Construct model encoder_op = encoder(X) # 128 Features decoder_op = decoder(encoder_op) # 784 Features # Prediction y_pred = decoder_op # After # Targets (Labels) are the input data. y_true = X # Before # Define loss and optimizer, minimize the squared error print("y_true", y_true) print("y_pred", y_pred) cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2)) cost_scalar = tf.summary.scalar("cost", cost) merged_cost = tf.summary.merge([cost_scalar]) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) # Launch the graph with tf.Session() as sess: sess.run(tf.global_variables_initializer()) summary_writer = tf.summary.FileWriter(logdir, graph=sess.graph) total_batch = int(mnist.train.num_examples/batch_size) # Training cycle for epoch in range(training_epochs): # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) # max(x) = 1, min(x) = 0 # Run optimization op (backprop) and cost op (to get loss value) _, c = sess.run([optimizer, merged_cost], feed_dict={X: batch_xs}) summary_writer.add_summary(c, epoch) # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1)) # "cost=", cost.eval()) # print("Epoch:", (epoch+1)) print("cost=", cost) print("Optimization Finished!")
true
dc3705cb82661ed48553b3b2682d8c4e328d42d3
Python
gutsche/scripts
/FilesystemManipulations/compareChecksums.py
UTF-8
2,495
2.953125
3
[]
no_license
#!/usr/bin/env python import os,sys from optparse import OptionParser import json def main(): # initialization usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="verbose output") parser.add_option("-o", "--one", action="store", type="string", default=None, dest="one", help="First filename with chksums in JSON format") parser.add_option("-t", "--two", action="store", type="string", default=None, dest="two", help="Second filename with chksums in JSON format") (opts, args) = parser.parse_args() verbose=opts.verbose one = opts.one two = opts.two if one == None or two == None: parser.print_help() parser.error('Please specify two input filenames.') one_dict = json.load(open(one)) two_dict = json.load(open(two)) print '' print 'Number of entries in file:',one,':',len(one_dict.keys()) print 'Number of entries in file:',two,':',len(two_dict.keys()) files_in_one_but_not_in_two = [] files_in_two_but_not_in_one = [] checksum_mismatch = [] for file in one_dict.keys(): if file not in two_dict.keys(): files_in_one_but_not_in_two.append(file) else: if one_dict[file]['chksum'] != two_dict[file]['chksum']: checksum_mismatch.append(file) if verbose: print 'file:',one,':',file,one_dict[file]['chksum'],'file:',two,':',file,two_dict[file]['chksum'] for file in two_dict.keys(): if file not in one_dict.keys(): files_in_two_but_not_in_one.append(file) print '' print 'Number of entries in file:',one,'but not in file:',two,':',len(files_in_one_but_not_in_two) for missing_two in files_in_one_but_not_in_two: print 'entry:',os.path.join(one_dict[missing_two]['root'],missing_two) print '' print 'Number of entries in file:',two,'but not in file:',one,':',len(files_in_two_but_not_in_one) for missing_one in files_in_two_but_not_in_one: print 'entry:',missing_one print '' print 'Checksum mismatches:',len(checksum_mismatch) for mismatch in checksum_mismatch: print '' print 'mismatch from file:',one,':',mismatch,one_dict[mismatch]['chksum'] print 'mismatch from file:',two,':',mismatch,two_dict[mismatch]['chksum'] if __name__ == "__main__": main() sys.exit(0);
true
a160dfe921981c52a6edb1215e64a410b158e4d7
Python
oceanremotesensing/sensor-data-fusion-full-stack
/tests/test_kalman_one.py
UTF-8
3,274
2.71875
3
[]
no_license
# %% import os from sdf.kalman_one import gauss_add, gauss_multiply, plot_gaussian_pdf import matplotlib.pyplot as plt import numpy.random as random from matplotlib.animation import FuncAnimation state = (0, 10000) # Gaussian N(mu=0, var=insanely big) groundtruth = 0 velocity = 1 velocity_error = 0.05 sensor_error = 1.5 measurements = [ -2.07, # first is completely off # 5.05, 0.51, 3.47, 5.76, 0.93, # huge offset 6.53, 9.01, 7.53, 11.68, 9.15, # another offset 14.76, 19.45, 16.15, 19.05, 14.87, 7.90, 5.75, # extreme offset 7.16, 20.50, 21.75, 22.05, 23.5, 24.27, 25.0, 26.1, 26.9, 29.3, 29.15, 30, ] zs = [0] # measurements (locations) ps = [0] # filter outputs (locations) / added a 0 s.t. the ax1.legend() works ns = [0] # noise/error offset N = 30 dt = 1 def animate(frame): global dt, groundtruth, state, zs, ps, ns, N, measurements, ax1, ax2, fig # predict: we progress state with evolution model state = gauss_add(state[0], state[1], velocity * dt, velocity_error) # memorize for plotting later groundtruth = groundtruth + velocity * dt prediction_state = state Z = measurements[frame] zs.append(Z) # update: We correct the state using the measurement (as likelihood in Bayes manner) state = gauss_multiply(state[0], state[1], Z, sensor_error) ps.append(state[0]) # plot measurement ax1.plot(zs, color="orange", marker="o", label="measurement") ax1.set_xlim([0, N * 1.2]) ax1.set_ylim([-5, N * 1.2]) # plot filter output (state*likelihood) if len(ps) > 1: ax1.plot(ps, "green", label="filter") # plot the current filter output (a Gaussian) ax2.cla() plot_gaussian_pdf( state[0], state[1], xlim=[0, N * 1.2], ax=ax2, color="green", label="filtering" ) plot_gaussian_pdf( prediction_state[0], prediction_state[1], xlim=[0, N * 1.2], ax=ax2, color="blue", label="prediction", ) # debug print(groundtruth) # plot groundtruth ax2.axvline(x=int(groundtruth), color="red", label="groundtruth") ax2.set_ylim(0, 1) noise = Z - groundtruth ns.append(noise) print(noise) ax3.plot(ns, color="red", marker="o", label="measurement - groundtruth") ax3.set_xlim([0, N * 1.2]) ax3.set_ylim(-15, 15) # make things look nice if frame == 0: ax1.legend() ax1.grid() ax3.legend() ax3.grid() # ax2 gets cleared all the time, hence we redraw the legend and xlabel ax2.legend() ax2.grid() ax2.set(xlabel="location") fig.tight_layout() def init(): """This is a bug in matplotlib?""" pass fig = plt.figure(figsize=(25 / 2.54, 20 / 2.54)) ax1 = fig.add_subplot(311) ax1.set(ylabel="location", xlabel="time") ax2 = fig.add_subplot(312) ax3 = fig.add_subplot(313) animation = FuncAnimation(fig, animate, N, interval=750, init_func=init) # %% filename = "animation.gif" basename = os.path.splitext(filename)[0] animation.save(basename + ".mp4", writer="ffmpeg") os.system("ffmpeg -y -i {}.mp4 {}.gif".format(basename, basename)) os.remove(basename + ".mp4") # %%
true
5a3aedf86115f0370ff0c02b66402b53fee0d637
Python
maheshmohanust/LearnPython
/IfNameExample.py
UTF-8
127
2.984375
3
[]
no_license
def print_name(): print("Hello User") if __name__ == "__main__": print_name() else: print("You are in else part")
true
cefe25b76fc42b486190f0141e5d6db1f62f8265
Python
zubie7a/Algorithms
/HackerRank/Python_Learn/04_Sets/07_Set_Intersection.py
UTF-8
256
3.078125
3
[ "MIT" ]
permissive
# https://www.hackerrank.com/challenges/py-set-intersection-operation n = int(raw_input()) setA = set(map(int, raw_input().split())) m = int(raw_input()) setB = set(map(int, raw_input().split())) # print len(setA & setB) print len(setA.intersection(setB))
true
8d03d6878652b07b00d5554c18166ab8a77d1bde
Python
cHemingway/py_rmd_servo
/test_rmd_servo.py
UTF-8
4,561
2.71875
3
[]
no_license
import unittest import unittest.mock as mock # Class to be tested import rmd_servo class Test__parse_response_header(unittest.TestCase): def setUp(self): self.patcher = unittest.mock.patch( "rmd_servo.serial.Serial", autospec=True) self.mock_serial = self.patcher.start() self.servo = rmd_servo.RMD_Servo("test", 2) def test_wrong_len(self): self.assertIsNone(self.servo._parse_response_header(bytearray(4), 1), "Resp of length 4 should fail") self.assertIsNone(self.servo._parse_response_header(bytearray(6), 1), "Resp of length 6 should fail") def test_checksum(self): # Test command 0x04, data length 0 valid_data = bytearray([0x3E,0x04,0x02,0x00,0x44]) length = self.servo._parse_response_header(valid_data,0x04) self.assertEqual(length, 0) # Test command 0xFF, data length 5 valid_data = bytearray([0x3E,0xFF,0x02,0x05,0x45]) length = self.servo._parse_response_header(valid_data,0xFF) self.assertEqual(length, 5) # Test invalid checksum invalid_data = bytearray([0x3E,0xFF,0x02,0x05,0x46]) length = self.servo._parse_response_header(invalid_data,0xFF) self.assertIsNone(length) def test_wrong_command(self): # Test command 0x04, data length 0 data = bytearray([0x3E,0x04,0x02,0x00,0x44]) # Expect command 3, will not match length = self.servo._parse_response_header(data,0x03) self.assertIsNone(length) def test_wrong_id(self): # ID should be 2 (see setup) so send 0x12 to cause failure data = bytearray([0x3E, 0xaa, 0x12, 0x55, 0x50]) length = self.servo._parse_response_header(data,0xaa) self.assertIsNone(length) def tearDown(self): mock.patch.stopall() # Stop mocks, or else other tests are corrupted return super().tearDown() class Test__send_raw_command(unittest.TestCase): ''' Verify that __send_raw_command passes correct data to serial port ''' def setUp(self): self.patcher = unittest.mock.patch( "rmd_servo.serial.Serial", autospec=True) self.mock_serial = self.patcher.start() self.servo = rmd_servo.RMD_Servo("test", 2) self.mock_serial.assert_called_once_with( "test", baudrate=115200, timeout=0.5) # Mock individual serial functions self.servo.ser.read = mock.Mock() self.servo.ser.reset_input_buffer = mock.Mock() self.servo.ser.write = mock.Mock() def test_correct_tx_no_data(self): expected_tx = bytearray.fromhex("3E AA 02 00 EA") given_rx = expected_tx # Set a returned value self.servo.ser.read.return_value = given_rx # Call function and check it called mocks OK self.servo._send_raw_command(0xAA) self.servo.ser.reset_input_buffer.assert_called_once() self.servo.ser.write.assert_called_once_with(bytes(expected_tx)) def tearDown(self): mock.patch.stopall() # Stop mocks, or else other tests are corrupted return super().tearDown() class Test_move_closed_loop_speed(unittest.TestCase): ''' Tests that move_positive passes correct data to __send_raw_command ''' def setUp(self): self.mock_serial = mock.patch( "rmd_servo.serial.Serial").start() self.mock_send_raw_command = mock.patch( "rmd_servo.RMD_Servo._send_raw_command").start() self.servo = rmd_servo.RMD_Servo("test") def test_move_positive(self): # Verified in RMD Motor Assistant speed_hex = bytes.fromhex("10 34 02 00") # Call function, check it returned right value self.mock_send_raw_command.return_value = bytes.fromhex( "22 2003 0000 b80b") resp = self.servo.move_closed_loop_speed(1444) self.mock_send_raw_command.assert_called_once_with(0xA2, speed_hex) # Check response parsed properly self.assertDictEqual(resp, { "temperature": 34, "power": 800, "speed": 0, "position": 3000 } ) def tearDown(self): mock.patch.stopall() # Stop mocks, or else other tests are corrupted return super().tearDown() if __name__ == "__main__": unittest.main()
true
e8a8fca7e035bc666cbaee93666734b7569d3bc0
Python
pyliaorachel/reinforcement-learning-decipher
/decipher/dqn.py
UTF-8
11,141
3.140625
3
[]
no_license
""" Deep Q Network logics. The state is encoded with an LSTM controller over the history of observed inputs. The hidden state is fed to the Q-network for evaluation of each action. Two Q-networks are present, one target network, and one evaluation network. The evaluation network is updated frequently with random batches chosen from a pool of past experiences (memory), while the target network is less frequently updated by copying the parameters from the evaluation network directly. This technique helps stabilizing the learning process. """ import pickle import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import numpy as np from .utils import symbol_repr_hstack, symbol_repr_total_size, split_chunks, pad_zeros, to_idx_list, choose_action_from_dist class StateEncoder(nn.Module): """LSTM controller.""" def __init__(self, base, n_states, env_s_shape, symbol_repr_method='one_hot'): """ base: size of alphabet n_states: dimension of the encoded state env_s_shape: state shape from the environment symbol_repr_method: character (symbol) representation method """ super().__init__() self.symbol_repr_method = symbol_repr_method self.symbol_repr_sizes = env_s_shape # The input dimension depends on which character (symbol) representation used self.input_dim = symbol_repr_total_size(env_s_shape, method=symbol_repr_method) self.hidden_dim = n_states self.symbol_repr = lambda x: np.apply_along_axis(lambda a: symbol_repr_hstack(a, self.symbol_repr_sizes, method=symbol_repr_method), 2, x) # Adapt to varying shapes of different representations self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, batch_first=True) def forward(self, x): """ x: a series of observations from the environment """ x = Variable(torch.Tensor(self.symbol_repr(x))) lstm_out, (h, c) = self.lstm(x) return lstm_out class QNet(nn.Module): """Q-network.""" def __init__(self, base, n_states, n_actions, env_s_shape, env_a_shape, symbol_repr_method='one_hot', hidden_dim=None): """ base: size of alphabet n_states: dimension of the encoded state from LSTM n_actions: number of actions (discrete values flattened out) env_s_shape: state shape from the environment env_a_shape: action shape from the environment symbol_repr_method: character (symbol) representation method hidden_dim: dimension of the hidden layer, or no hidden layer if None """ super().__init__() # LSTM controller underlies Q-network self.state_encoder = StateEncoder(base, n_states, env_s_shape, symbol_repr_method=symbol_repr_method) self.n_states = n_states self.n_actions = n_actions self.hidden_dim = hidden_dim if hidden_dim is not None: # Can opt for a hidden layer in between the encoded state and the output self.fc1 = nn.Linear(n_states, hidden_dim) self.fc1.weight.data.normal_(0, 0.1) # initialization self.out = nn.Linear(hidden_dim, n_actions) else: self.out = nn.Linear(n_states, n_actions) self.out.weight.data.normal_(0, 0.1) # initialization def forward(self, x): """ x: a series of observations from the environment """ x = self.state_encoder(x) if self.hidden_dim is not None: x = self.fc1(x) x = F.relu(x) actions_value = self.out(x) return actions_value def get_hidden_state(self, x): """Simply retrieve the hidden state representation for the observation history. x: a series of observations from the environment """ return self.state_encoder(x).detach()[0].data.numpy() class DQN(object): """Deep Q Network with an evaluation and a target network.""" def __init__(self, base, n_states, n_actions, env_s_shape, env_a_shape, symbol_repr_method='one_hot', lr=0.01, gamma=0.9, epsilon=0.8, batch_size=32, memory_capacity=500, target_replace_iter=50, hidden_dim=None): """ base: size of alphabet n_states: dimension of the encoded state for LSTM n_actions: number of actions (discrete values flattened out) env_s_shape: state shape from the environment env_a_shape: action shape from the environment symbol_repr_method: character (symbol) representation method lr: learning rate of Q-learning gamma: reward discount factor epsilon: epsilon in epsilon-greedy policy; probability to choose an action based on the current optimal policy batch_size: batch size for learning from memory memory_capacity: memory storage capacity for experience replay target_replace_iter: number of iterations before the target network is updated hidden_dim: dimension of the hidden layer, or no hidden layer if None """ self.eval_net, self.target_net = QNet(base, n_states, n_actions, env_s_shape, env_a_shape, symbol_repr_method=symbol_repr_method, hidden_dim=hidden_dim), QNet(base, n_states, n_actions, env_s_shape, env_a_shape, symbol_repr_method=symbol_repr_method, hidden_dim=hidden_dim) self.base = base self.n_states = n_states self.n_actions = n_actions self.env_s_shape = env_s_shape self.env_a_shape = env_a_shape # Shapes may be a discrete value or box-like self.symbol_repr_method = symbol_repr_method self.lr = lr self.gamma = gamma self.epsilon = epsilon self.batch_size = batch_size self.memory_capacity = memory_capacity self.target_replace_iter = target_replace_iter self.learn_step_counter = 0 # For target updating self.optimizer = torch.optim.Adam(self.eval_net.parameters(), lr=lr) self.loss_func = nn.MSELoss() # Mean squared error loss self.prev_states = [] # Experience replay memory self.memory = np.zeros((memory_capacity, len(env_s_shape) * 2 + len(env_a_shape) + 1)) # [state, action, reward, next_state] self.memory_counter = 0 self.memory_ep_end_flags = [] # Memories of each episode is kept as one single replay memory # Evaluation mode self.eval_mode = False def choose_action(self, s): """ s: observed state from the environment """ self.prev_states.append(s) s = [self.prev_states[:]] # Unsqueeze batch_size # epsilon-greedy policy if self.eval_mode or np.random.uniform() < self.epsilon: # Choose action greedily actions_value = self.eval_net(s).detach()[0][0] action = choose_action_from_dist(actions_value.data.numpy(), self.env_a_shape) else: # Choose action randomly action = tuple([np.random.randint(0, a) for a in self.env_a_shape]) return action def store_transition(self, s, a, r, next_s, done): """ s: observed state from the environment a: chosen action r: reward received for performing the action next_s: next observed state from the environment done: whether the episode is finished """ a_idx = to_idx_list(a, self.env_a_shape) # Turn action into indices for ease of use in learning transition = np.hstack((s, a_idx, [r], next_s)) # Memory is a circular buffer i = self.memory_counter % self.memory_capacity self.memory[i, :] = transition self.memory_counter += 1 # Mark end of episode flag if done: if len(self.memory_ep_end_flags) > 0 and i <= self.memory_ep_end_flags[-1]: # Memory overflow l = self.memory_ep_end_flags old_mem = next(x[0] for x in enumerate(l) if x[1] > i) # Find first elem larger than i self.memory_ep_end_flags = self.memory_ep_end_flags[old_mem:] self.memory_ep_end_flags.append(i) self.prev_states = [] def learn(self): """Learn from experience replay.""" # Only learn after having enough experience if self.memory_counter < self.memory_capacity: return # Update target Q-network every several iterations (replace with eval Q-network's parameters) if self.learn_step_counter % self.target_replace_iter == 0: self.target_net.load_state_dict(self.eval_net.state_dict()) self.learn_step_counter += 1 # Sample batch transitions from memory l_states = len(self.env_s_shape) l_actions = len(self.env_a_shape) m = self.memory flags = self.memory_ep_end_flags a_shape = self.env_a_shape ## Random select series of memories, pad them to equal sequence length sample_idxs = np.random.choice(range(len(flags)-1), self.batch_size) memory_ranges = zip(flags[:-1], flags[1:]) memory_series = [m[s:e] if s <= e else (np.concatenate((m[s:], m[:e]))) for s, e in memory_ranges] seq_len = max([len(ms) for ms in memory_series]) memory_series = pad_zeros(memory_series, seq_len) # Pad 0s to make the seq len the same b_memory = memory_series[sample_idxs] ## Sample batch memory series b_s = b_memory[:, :, :l_states] b_a = Variable(torch.LongTensor(b_memory[:, :, l_states:l_states+l_actions].astype(int))) b_r = Variable(torch.FloatTensor(b_memory[:, :, l_states+l_actions:l_states+l_actions+1])) b_next_s = b_memory[:, :, -l_states:] # Update eval Q-network from loss against target Q-network q_eval = self.eval_net(b_s).gather(2, b_a) # Shape (batch, seq_len, l_actions) q_next = self.target_net(b_next_s).detach() # Detach from graph, don't backpropagate argmax_q_next = np.apply_along_axis(lambda x: to_idx_list(choose_action_from_dist(x, a_shape), a_shape), 2, q_next.data.numpy()) max_q_next = q_next.gather(2, Variable(torch.LongTensor(argmax_q_next))) q_target = b_r + self.gamma * max_q_next loss = self.loss_func(q_eval, q_target) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def eval(self): """Set network to evaluation mode.""" self.eval_mode = True def save_state_dict(self, file_path): """"Save model. file_path: output path to save model """ model = { 'eval_net': self.eval_net.state_dict(), 'target_net': self.target_net.state_dict() } with open(file_path, 'wb') as fout: pickle.dump(model, fout) def load_state_dict(self, file_path): """"Load model. file_path: input path to load model """ with open(file_path, 'rb') as fout: model = pickle.load(fout) self.eval_net.load_state_dict(model['eval_net']) self.target_net.load_state_dict(model['target_net'])
true
e4d23a589213301f3a95835465c49d7b8def5d8f
Python
justzino/algorithms
/Programmers/Stack-Queue/3-sol.py
UTF-8
1,802
3.578125
4
[]
no_license
from collections import deque DUMMY_TRUCK = 0 class Bridge: def __init__(self, length, weight): self._max_length = length self._max_weight = weight self._queue = deque() self._current_weight = 0 def push(self, truck_weight) -> bool: next_weight = self._current_weight + truck_weight # 다리가 꽉찬 경우 if next_weight <= self._max_weight and len(self._queue) < self._max_length: self._queue.append(truck_weight) self._current_weight = next_weight return True else: return False def pop(self): truck_weight = self._queue.popleft() self._current_weight -= truck_weight def __len__(self): return len(self._queue) def __repr__(self): return 'Bridge({}/{} : [{}])'.format(self._current_weight, self._max_weight, list(self._queue)) def solution(bridge_length, weight, truck_weights): bridge = Bridge(bridge_length, weight) trucks = deque(truck_weights) for _ in range(bridge_length): bridge.push(DUMMY_TRUCK) time = 0 # 트럭이 전부 다리에 진입 while trucks: print(bridge) bridge.pop() if bridge.push(trucks[0]): trucks.popleft() else: bridge.push(DUMMY_TRUCK) time += 1 # 트럭이 전부 다리에서 나옴 while bridge: bridge.pop() time += 1 return time def main(): case1 = solution(5, 5, [2, 2, 2, 2, 1, 1, 1, 1, 1]) # case2 = solution(10000, 10000, [1, 2, 3, 4, 5, 6, 7, 5000]) case3 = solution(10, 10, [7, 2, 1, 9]) case4 = solution(1, 10, [2, 3, 4, 5]) print(case1) # print(case2) print(case3) print(case4) if __name__ == '__main__': main()
true
022071b163f5bc4f4db175518391260e6cbaceb4
Python
emanoelmlsilva/Lista-IP
/exercicio03/Programa3,10.py
UTF-8
253
3.953125
4
[]
no_license
salario = float(input('Entre com o salario: ')) porcentagem = float(input('Informe a porcentagem: ')) aumento = salario * porcentagem novoSal = aumento + salario print('Valor do aumento %5.2f R$'%aumento) print('Valor do novo salario %4.2f R$'%novoSal)
true
e452a817115616424231f8c25ae59aeea78a0f75
Python
KoRReL12/Bfood
/database.py
UTF-8
12,667
2.75
3
[]
no_license
import logging import typing import requests import telegram from sqlalchemy import Column, ForeignKey, UniqueConstraint from sqlalchemy import Integer, BigInteger, String, Text, LargeBinary, DateTime, Boolean from sqlalchemy.ext.declarative import declarative_base, DeferredReflection from sqlalchemy.orm import relationship, backref import utils if typing.TYPE_CHECKING: from . import worker log = logging.getLogger(__name__) # Create a base class to define all the database subclasses TableDeclarativeBase = declarative_base() # Define all the database tables using the sqlalchemy declarative base class User(DeferredReflection, TableDeclarativeBase): """A Telegram user who used the bot at least once.""" # Telegram data user_id = Column(BigInteger, primary_key=True) first_name = Column(String, nullable=False) last_name = Column(String) username = Column(String) language = Column(String, nullable=False) # Current wallet credit credit = Column(Integer, nullable=False) # Extra table parameters __tablename__ = "users" def __init__(self, w: "worker.Worker", **kwargs): # Initialize the super super().__init__(**kwargs) # Get the data from telegram self.user_id = w.telegram_user.id self.first_name = w.telegram_user.first_name self.last_name = w.telegram_user.last_name self.username = w.telegram_user.username if w.telegram_user.language_code: self.language = w.telegram_user.language_code else: self.language = w.cfg["Language"]["default_language"] # The starting wallet value is 0 self.credit = 0 def __str__(self): """Describe the user in the best way possible given the available data.""" if self.username is not None: return f"@{self.username}" elif self.last_name is not None: return f"{self.first_name} {self.last_name}" else: return self.first_name def identifiable_str(self): """Describe the user in the best way possible, ensuring a way back to the database record exists.""" return f"user_{self.user_id} ({str(self)})" def mention(self): """Mention the user in the best way possible given the available data.""" if self.username is not None: return f"@{self.username}" else: return f"[{self.first_name}](tg://user?id={self.user_id})" def recalculate_credit(self): """Recalculate the credit for this user by calculating the sum of the values of all their transactions.""" valid_transactions: typing.List[Transaction] = [t for t in self.transactions if not t.refunded] self.credit = sum(map(lambda t: t.value, valid_transactions)) @property def full_name(self): if self.last_name: return f"{self.first_name} {self.last_name}" else: return self.first_name def __repr__(self): return f"<User {self.mention()} having {self.credit} credit>" class Product(DeferredReflection, TableDeclarativeBase): """A purchasable product.""" # Product id id = Column(Integer, primary_key=True) # Product name name = Column(String) # Product description description = Column(Text) # Product price, if null product is not for sale price = Column(Integer) # Categories categories = Column(Text) # Image data image = Column(LargeBinary) # Product has been deleted deleted = Column(Boolean, nullable=False) # Extra table parameters __tablename__ = "products" # No __init__ is needed, the default one is sufficient def text(self, w: "worker.Worker", *, style: str = "full", cart_qty: int = None): """Return the product details formatted with Telegram HTML. The image is omitted.""" if style == "short": return f"{cart_qty}x {utils.telegram_html_escape(self.name)} - {str(w.Price(self.price) * cart_qty)}" elif style == "full": if cart_qty is not None: cart = w.loc.get("in_cart_format_string", quantity=cart_qty) else: cart = '' return w.loc.get("product_format_string", name=utils.telegram_html_escape(self.name), description=utils.telegram_html_escape(self.description), categories=utils.telegram_html_escape(self.categories), price=str(w.Price(self.price)), cart=cart) else: raise ValueError("style is not an accepted value") def __repr__(self): return f"<Product {self.name}>" def send_as_message(self, w: "worker.Worker", chat_id: int) -> dict: """Send a message containing the product data.""" if self.image is None: r = requests.get(f"https://api.telegram.org/bot{w.cfg['Telegram']['token']}/sendMessage", params={"chat_id": chat_id, "text": self.text(w), "parse_mode": "HTML"}) else: r = requests.post(f"https://api.telegram.org/bot{w.cfg['Telegram']['token']}/sendPhoto", files={"photo": self.image}, params={"chat_id": chat_id, "caption": self.text(w), "parse_mode": "HTML"}) return r.json() def set_image(self, file: telegram.File): """Download an image from Telegram and store it in the image column. This is a slow blocking function. Try to avoid calling it directly, use a thread if possible.""" # Download the photo through a get request r = requests.get(file.file_path) # Store the photo in the database record self.image = r.content class Transaction(DeferredReflection, TableDeclarativeBase): """A greed wallet transaction. Wallet credit ISN'T calculated from these, but they can be used to recalculate it.""" # TODO: split this into multiple tables # The internal transaction ID transaction_id = Column(Integer, primary_key=True) # The user whose credit is affected by this transaction user_id = Column(BigInteger, ForeignKey("users.user_id"), nullable=False) user = relationship("User", backref=backref("transactions")) # The value of this transaction. Can be both negative and positive. value = Column(Integer, nullable=False) # Refunded status: if True, ignore the value of this transaction when recalculating refunded = Column(Boolean, default=False) # Extra notes on the transaction notes = Column(Text) # Payment provider provider = Column(String) # Transaction ID supplied by Telegram telegram_charge_id = Column(String) # Transaction ID supplied by the payment provider provider_charge_id = Column(String) # Extra transaction data, may be required by the payment provider in case of a dispute payment_name = Column(String) payment_phone = Column(String) payment_email = Column(String) # Order ID order_id = Column(Integer, ForeignKey("orders.order_id")) order = relationship("Order") # Extra table parameters __tablename__ = "transactions" __table_args__ = (UniqueConstraint("provider", "provider_charge_id"),) def text(self, w: "worker.Worker"): string = f"<b>T{self.transaction_id}</b> | {str(self.user)} | {w.Price(self.value)}" if self.refunded: string += f" | {w.loc.get('emoji_refunded')}" if self.provider: string += f" | {self.provider}" if self.notes: string += f" | {self.notes}" return string def __repr__(self): return f"<Transaction {self.transaction_id} for User {self.user_id}>" class Admin(DeferredReflection, TableDeclarativeBase): """A greed administrator with his permissions.""" # The telegram id user_id = Column(BigInteger, ForeignKey("users.user_id"), primary_key=True) user = relationship("User") # Permissions edit_products = Column(Boolean, default=False) receive_orders = Column(Boolean, default=False) create_transactions = Column(Boolean, default=False) display_on_help = Column(Boolean, default=False) is_owner = Column(Boolean, default=False) # Live mode enabled live_mode = Column(Boolean, default=False) # Extra table parameters __tablename__ = "admins" def __repr__(self): return f"<Admin {self.user_id}>" class Order(DeferredReflection, TableDeclarativeBase): """An order which has been placed by an user. It may include multiple products, available in the OrderItem table.""" # The unique order id order_id = Column(Integer, primary_key=True) # The user who placed the order user_id = Column(BigInteger, ForeignKey("users.user_id")) user = relationship("User") # Date of creation creation_date = Column(DateTime, nullable=False) # Date of delivery delivery_date = Column(DateTime) # Date of refund: if null, product hasn't been refunded refund_date = Column(DateTime) # Refund reason: if null, product hasn't been refunded refund_reason = Column(Text) # List of items in the order items: typing.List["OrderItem"] = relationship("OrderItem") # Extra details specified by the purchasing user notes = Column(Text) # Linked transaction transaction = relationship("Transaction", uselist=False) # Extra table parameters __tablename__ = "orders" def __repr__(self): return f"<Order {self.order_id} placed by User {self.user_id}>" def text(self, w: "worker.Worker", session, user=False): joined_self = session.query(Order).filter_by(order_id=self.order_id).join(Transaction).one() items = "" for item in self.items: items += item.text(w) + "\n" if self.delivery_date is not None: status_emoji = w.loc.get("emoji_completed") status_text = w.loc.get("text_completed") elif self.refund_date is not None: status_emoji = w.loc.get("emoji_refunded") status_text = w.loc.get("text_refunded") else: status_emoji = w.loc.get("emoji_not_processed") status_text = w.loc.get("text_not_processed") if user and w.cfg["Appearance"]["full_order_info"] == "no": return w.loc.get("user_order_format_string", status_emoji=status_emoji, status_text=status_text, items=items, notes=self.notes, value=str(w.Price(-joined_self.transaction.value))) + \ (w.loc.get("refund_reason", reason=self.refund_reason) if self.refund_date is not None else "") else: return status_emoji + " " + \ w.loc.get("order_number", id=self.order_id) + "\n" + \ w.loc.get("order_format_string", user=self.user.mention(), date=self.creation_date.isoformat(), items=items, notes=self.notes if self.notes is not None else "", value=str(w.Price(-joined_self.transaction.value))) + \ (w.loc.get("refund_reason", reason=self.refund_reason) if self.refund_date is not None else "") class OrderItem(DeferredReflection, TableDeclarativeBase): """A product that has been purchased as part of an order.""" # The unique item id item_id = Column(Integer, primary_key=True) # The product that is being ordered product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product = relationship("Product") # The order in which this item is being purchased order_id = Column(Integer, ForeignKey("orders.order_id"), nullable=False) # Extra table parameters __tablename__ = "orderitems" def text(self, w: "worker.Worker"): return f"{self.product.name} - {str(w.Price(self.product.price))}" def __repr__(self): return f"<OrderItem {self.item_id}>"
true
250324cbe33a45a3c7db9992018ff1ed5056c176
Python
jokercraft/MusicHunter
/main.py
UTF-8
4,593
2.6875
3
[]
no_license
from __future__ import unicode_literals import youtube_dl import requests from bs4 import BeautifulSoup import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QLabel from PyQt5.QtGui import QIcon, QImage, QPalette, QBrush, QPixmap from PyQt5.QtCore import pyqtSlot, QSize class App(QWidget): def __init__(self): super().__init__() self.title = 'Music Hunter' self.left = 100 self.top = 200 self.width = 800 self.height = 600 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) oImage = QImage("bg-python.jpg") sImage = oImage.scaled(QSize(800,600)) # resize Image to widgets size palette = QPalette() palette.setBrush(10, QBrush(sImage)) # 10 = Windowrole self.setPalette(palette) # Create button buttonSearch = QPushButton('Search', self) buttonSearch.setToolTip('Download the best songs of singer or band') buttonSearch.move(400,350) buttonSearch.resize(100,40) buttonSearch.clicked.connect(self.search) buttonDownload = QPushButton('MP3', self) buttonDownload.setToolTip('Download as mp3') buttonDownload.move(400,420) buttonDownload.resize(100,40) buttonDownload.clicked.connect(self.download) buttonDownload2 = QPushButton('MP4', self) buttonDownload2.setToolTip('Download as mp4') buttonDownload2.move(540,420) buttonDownload2.resize(100,40) buttonDownload2.clicked.connect(self.download_video) # Create textbox self.textboxSearch = QLineEdit(self) self.textboxSearch.move(100, 350) self.textboxSearch.resize(280,40) self.textboxSearch.setPlaceholderText('Type the name of the band or signer...') self.textboxDownload = QLineEdit(self) self.textboxDownload.move(100, 420) self.textboxDownload.resize(280,40) self.textboxDownload.setPlaceholderText('Paste Youtube link of the song...') self.show() @pyqtSlot() def search(self): name = self.textboxSearch.text() searc_music(name) self.textboxSearch.setText("") def download(self): link = self.textboxDownload.text() download_music(link) self.textboxDownload.setText("") def download_video(self): link = self.textboxDownload.text() download_as_video(link) self.textboxDownload.setText("") def download_music(link): try: ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: #ydl.download([link]) info = ydl.extract_info(link, download=True) song_name = info.get('title', None) except (youtube_dl.utils.PostProcessingError,youtube_dl.utils.DownloadError): pass def download_as_video(link): ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([link]) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) def searc_music(link): link = "https://www.youtube.com/results?q=" singer_name = input("The singer or band name: ") link = link + singer_name istek = requests.get(link) result_html = BeautifulSoup(istek.content,"html.parser") result = result_html.find_all('div',{"class" : "yt-lockup yt-lockup-tile yt-lockup-video vve-check clearfix"}) for x in result: d=str(x) d=d[94:107] print(d) try: ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } d=d[1:12] link="https://www.youtube.com/watch?v=" link=link+d with youtube_dl.YoutubeDL(ydl_opts) as ydl: #ydl.download([link]) info = ydl.extract_info(link, download=True) song_name = info.get('title', None) except (youtube_dl.utils.PostProcessingError,youtube_dl.utils.DownloadError): pass
true
eb4cb89236d32d34c5a0de8dc66d182fbfe89784
Python
MohammedGuniem/social-media-influence-analyzer
/src/classes/modelling/GraphModelling.py
UTF-8
2,875
2.640625
3
[]
no_license
from classes.modelling.TextClassification import TextClassifier from classes.modelling.Node import Node from classes.modelling.Edge import Edge class Graph: def __init__(self, mongo_db_connector, neo4j_db_connector, network_name, submissions_type, date): self.mongo_db_connector = mongo_db_connector self.neo4j_db_connector = neo4j_db_connector self.network_name = network_name self.submissions_type = submissions_type self.date = date self.text_classifier = TextClassifier( mongo_db_connector, network_name, submissions_type, date) model_status = self.text_classifier.prepare_model() if model_status == "data not found": raise Exception("training data not found") self.nodes = {} self.edges = {} def addOrUpdateEdge(self, from_node_id, relation_type, to_node_id, influence_area, group_name, interaction_score, activity_score, upvotes_score): edge_id = F"{from_node_id}_{relation_type}_{to_node_id}" if edge_id not in self.edges: edge = Edge(from_node_id, relation_type, to_node_id, [], [], interaction_score, activity_score, upvotes_score) else: edge = self.edges[edge_id] edge.influence_areas.append(influence_area) edge.group_names.append(group_name) edge.updateScore(interaction_score, activity_score, upvotes_score) self.edges[edge_id] = edge def save(self, graph_type): # Saving nodes in neo4j database graph. for node in self.nodes.values(): self.neo4j_db_connector.save_node( node_id=node.id, node_type=node.type, node_props=node.props, network_name=self.network_name, submissions_type=self.submissions_type, date=self.date ) # Saving edges in neo4j database graph. for edge in self.edges.values(): if edge.from_node in self.nodes and edge.to_node in self.nodes: self.neo4j_db_connector.save_edge( from_node=self.nodes[edge.from_node], to_node=self.nodes[edge.to_node], edge_type=edge.relation_type, edge_props=edge.getProps(), network_name=self.network_name, submissions_type=self.submissions_type, date=self.date ) # Calculate centralitites for user graph nodes if graph_type == "user_graph": for centrality in ["degree_centrality", "betweenness_centrality", "hits_centrality_"]: self.neo4j_db_connector.calculate_centrality( network_name=self.network_name, submissions_type=self.submissions_type, date=self.date, centrality=centrality)
true
ace9682ac7adee2e6f91633e6612d9df8b54af2a
Python
byterap/2019-1-10
/0csv文件中包含单引号.py
UTF-8
116
2.671875
3
[]
no_license
f = open("1.csv", "a+") # f.write("hello,world")#数据分割 f.write('"hello,world"') # 数据未分割 f.close()
true
414066fd8fd28866f4b0fa5f21480495724daf28
Python
savanmin/pythonfreq
/Loops/divisibleNum.py
UTF-8
334
4.28125
4
[]
no_license
""" Question: Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line""" for i in range(2000,3200): if (i%7 == 0) and (i%5!=0): print(int(i),end=",")
true
f7350d95f24ac8e84ac1fb539bf07c124a33f26b
Python
wgrand010/Assignment5
/scattertool.py
UTF-8
2,578
2.609375
3
[]
no_license
# keyRotationWithUI.py import maya.cmds as cmds import functools def createUI( pWindowTitle, pApplyCallback ): windowID = 'myWindowID' if cmds.window( windowID, exists=True ): cmds.deleteUI( windowID ) cmds.window( windowID, title=pWindowTitle, sizeable=True, resizeToFitChildren=True ) cmds.rowColumnLayout( numberOfColumns=2, columnWidth=[ (1,200), (2,200) ], columnOffset=[ (1,'right',3) ] ) cmds.text( label='Choose Object to be scattered from: ' ) startTimeField =cmds.button(label = object) cmds.text( label='Choose Object to be scattered to:' ) targetAttributeField = cmds.button(label = object) cmds.separator( h=10, style='none' ) cmds.separator( h=10, style='none' ) cmds.separator( h=10, style='none' ) cmds.separator( h=10, style='none' ) cmds.separator( h=10, style='none' ) cmds.button( label='Scatter', command=functools.partial( pApplyCallback, startTimeField, targetAttributeField ) ) cmds.showWindow() def keyFullRotation( pObjectName, pStartTime, pEndTime, pTargetAttribute ): cmds.cutKey( pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute ) cmds.setKeyframe( pObjectName, time=pStartTime, attribute=pTargetAttribute, value=0 ) cmds.setKeyframe( pObjectName, time=pEndTime, attribute=pTargetAttribute, value=360 ) cmds.selectKey( pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True ) cmds.keyTangent( inTangentType='linear', outTangentType='linear' ) def applyCallback( pStartTimeField, pEndTimeField, pTargetAttributeField, *pArgs ): # print 'Apply button pressed.' startTime = cmds.intField( pStartTimeField, query=True, value=True ) endTime = cmds.intField( pEndTimeField, query=True, value=True ) targetAttribute = cmds.textField( pTargetAttributeField, query=True, text=True ) print 'Start Time: %s' % ( startTime ) print 'End Time: %s' % ( endTime ) print 'Attribute: %s' % ( targetAttribute ) selectionList = cmds.ls( selection=True, type='transform' ) for objectName in selectionList: keyFullRotation( objectName, startTime, endTime, targetAttribute ) createUI( 'My Title', applyCallback )
true
1a0230ff6807664b71ea6a038eab7390734fedba
Python
GANESH0080/Python-Scripts
/IfOne.py
UTF-8
43
2.9375
3
[]
no_license
num = 25 if num<50: print(num, "True")
true
753d9d8758e881dd3e7241288c6ac9d6d0fe2d01
Python
tkoz0/problems-online-judge
/vol_002/p227.py
UTF-8
1,757
3.390625
3
[]
no_license
puzzlenum = 0 while True: puzzlenum += 1 puz = [] for z in range(5): try: puz.append(list(input())) except EOFError: break if len(puz) != 5: break # reached end of input assert len(puz) == 5 for z in puz: assert len(z) == 5, z moves = '' while True: # read move sequence until encountering the '0' moves += input() if moves[-1] == '0': break br, bc = -1, -1 # blank position for r in range(5): for c in range(5): if puz[r][c] == ' ': assert br == bc == -1 # only instance br, bc = r, c assert br != -1 and bc != -1 # space must exist if puzzlenum != 1: print() print('Puzzle #%d:'%puzzlenum) invalid = False # if invalid move occurs (no final configuration) for m in moves: if m == 'A': # br-1 if br == 0: invalid = True; break else: # swap and adjust blank position puz[br][bc], puz[br-1][bc] = puz[br-1][bc], puz[br][bc] br -= 1 elif m == 'B': # br+1 if br == 4: invalid = True; break else: puz[br][bc], puz[br+1][bc] = puz[br+1][bc], puz[br][bc] br += 1 elif m == 'L': # bc-1 if bc == 0: invalid = True; break else: puz[br][bc], puz[br][bc-1] = puz[br][bc-1], puz[br][bc] bc -= 1 elif m == 'R': # bc+1 if bc == 4: invalid = True; break else: puz[br][bc], puz[br][bc+1] = puz[br][bc+1], puz[br][bc] bc += 1 # else: assert m == '0' if invalid: print('This puzzle has no final configuration.') else: for z in puz: print(' '.join(z))
true
f1bde868df5529010b0b9e6d79bf87f273c0d824
Python
brendanleeper/codebookcipherchallenge
/stage2.py
UTF-8
848
3.03125
3
[ "MIT" ]
permissive
import re # caesar shift cipher ciphertext = "MHILY LZA ZBHL XBPZXBL MVYABUHL HWWPBZ JSHBKPBZ JHLJBZ KPJABT HYJHUBT LZA ULBAYVU" letters = list(ciphertext) orda = ord('A') # brute force it for shift in xrange(26): letters = list(ciphertext) for index, character in enumerate(letters): if(character != " "): letters[index] = chr(((ord(character) - orda) + shift) % 26 + orda) out = ''.join(letters) print 'shift: %s, text: %s' % (shift, out) # just the solution shift = 19 letters = list(ciphertext) for index, character in enumerate(letters): if(character != " "): letters[index] = chr(((ord(character) - orda) + shift) % 26 + orda) out = ''.join(letters) print 'plaintext: %s' % (out) # shift is at 19 # text is: FABER EST SUAE QUISQUE FORTUNAE APPIUS CLAUDIUS CAECUS DICTUM ARCANUM EST NEUTRON
true
55c6331861ca0fc70f059e9bc85f6251082017c2
Python
salaxavier/Network_Forensics_Tool
/file_hash.py
UTF-8
910
3.125
3
[]
no_license
# Script: file_hash.py # Desc: Generate file hash signature # Author: Petra L & Rich McF # modified: 2/12/18 (PEP8 compliance) # import sys import os import hashlib def get_hash(filename): """prints a hex hash signature of the file passed in as arg""" try: # Read File f=open(filename, 'rb') file=f.read() # Generate Hash Signature file_hashing = hashlib.md5(file) return file_hashing.hexdigest() except Exception as err: print(f'[-] {err}') finally: if 'f' in locals(): f.close() def main(): # Test case sys.argv.append(r'c:\temp\a_file.txt') # Check args if len(sys.argv) != 2: print('[-] usage: file_hash filename') sys.exit(1) filename = sys.argv[1] print(get_hash(filename)) if __name__ == '__main__': main()
true
64ab141d5dedcba188e02ab22fda747c9e80aa19
Python
aurelienmorgan/french_text_sentiment
/my_NLP_RNN_fr_lib/model/supercharger.py
UTF-8
10,023
2.640625
3
[]
no_license
import time, sys import pandas as pd import numpy as np from my_NLP_RNN_fr_lib.model.hyperparameters import get_new_hyperparameters from my_NLP_RNN_fr_lib.display_helper import format_vertical_headers from tqdm import tqdm import pickle from IPython.display import HTML, display #///////////////////////////////////////////////////////////////////////////////////// def best_nlp_models_hyperparameters( xgb_regressor , best_models_count , batch_models_count , NLP_predicted_val_rmse_threshold , show_batch_box_plots = False ) -> pd.core.frame.DataFrame : """ Iterative routine allowing to identify 'most promising' sets of NLP hyperparameter values, when evaluated by an XGBoost regressor. Each iteration (a.k.a. "WAVE") is made up of 'batch_models_count' sets of NLP hyperparameter values. The routine is interrupted : - either if the 'NLP_predicted_val_rmse_threshold' condition is met - or when the user commands it via a 'KeyboardInterrupt' event (smooth exit) Parameters : - xgb_regressor (xgboost.sklearn.XGBRegressor) : XGBoost regressor trained against an NLP models performance dataset. - best_models_count (int) : The number of 'predicted best performing' sets of NLP hyperparameters to be maintained and returned. - batch_models_count (int) : The number of randomly-generated set of NLP hyperparameters to be submitted to the XGBoost regressor for performance prediction at each iteration of the herein routine. - NLP_predicted_val_rmse_threshold (float) : value of predicted NLP performance measure, i.e. 'validation rmse' under which the herein routine shall automatically stop looping. When all "best_models_count" sets of NLP hyperparameters are predicted to perform better than that user-specified value, the routine is considered completed. - show_batch_box_plots (bool) : whether or not to display a 'predicted val_rmse' distribution boxplot for each "batch" (each loop). Result : - xgbR_best_hyperparameters (pandas.core.frame.DataFrame) : The 'predicted' best-performing sets of hyperparameters to be used when building an NLP model following the 'my_NLP_RNN_fr_lib.model.architecture.build_model' architecture. """ def row_index_n_bold_style(row_index_min: int) : """ return a style apply lambda function. If row index > row_index_min, the format of the cells is made green background & bold-weight font. """ def new_best_row_bold_style(row): if row.name > row_index_min : styles = {col: "font-weight: bold; background-color: lightgreen;" for col in row.index} else : styles = {col: "" for col in row.index} return styles return new_best_row_bold_style xgbR_best_hyperparameters = pd.DataFrame(columns = ['spatial_dropout_prop', 'recurr_units', 'recurrent_regularizer_l1_factor', 'recurrent_regularizer_l2_factor', 'recurrent_dropout_prop', 'conv_units', 'kernel_size_1', 'kernel_size_2', 'dense_units_1', 'dense_units_2', 'dropout_prop', 'lr', 'val_rmse (predicted)']) def get_best_hyperparameters( xgbR_best_hyperparameters ) : """ Parameters : - xgbR_best_hyperparameters (pd.DataFrame) : datafrm into which any new "best" set of NLP hyperparameters shall be inserted """ #################################### ## get 'batch_models_count' fresh ## ## sets of hyperparameters values ## #################################### try: hyperparameters = get_new_hyperparameters(verbose = 2, models_count = batch_models_count) except TimeoutError as e : print(e) raise e xgbR_X_new = hyperparameters.drop([ 'lr_decay_rate', 'lr_decay_step' ], axis=1) print("", end='\n', file=sys.stdout, flush=True) ####################################### ## get the associated ## ## predicted NLP models performances ## ####################################### print(f"Predict models performance :", end='\n', file=sys.stderr, flush=True) tic = time.perf_counter() chunk_size = 50_000 xgbR_y_pred = [] for i in tqdm(range(-(-xgbR_X_new.shape[0]//chunk_size)) , bar_format='{desc:<5.5}{percentage:3.0f}%|{bar:45}{r_bar}') : indices_slice = list(range(i*chunk_size, min((i+1)*chunk_size, xgbR_X_new.shape[0]))) #print("["+str(indices_slice[0])+"-"+str(indices_slice[-1])+"] - " + str(len(indices_slice))) xgbR_y_pred = \ np.append(xgbR_y_pred , xgb_regressor.predict(xgbR_X_new.iloc[indices_slice])) toc = time.perf_counter() print(f"Predicted performance of {xgbR_X_new.shape[0]:,} NLP models in {toc - tic:0.4f} seconds" , end='\n', file=sys.stderr, flush=True) ####################################### ## plot the distribution ## ## among the 'batch_models_count' ## ## predicted NLP models performances ## ####################################### if show_batch_box_plots : fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.boxplot(xgbR_y_pred , showfliers=False # not plotting outliers ) #ax.set_ylim(max(ax.get_ylim()[0], .5), ax.get_ylim()[1]) ax.set_title("NLP Model performance (rmse)") plt.show() ########################################################## ## isolate the sets of hyperparameters values ## ## associated to best predicted NLP models performances ## ########################################################## xgbR_hyperparameters = xgbR_X_new xgbR_hyperparameters["val_rmse (predicted)"] = xgbR_y_pred xgbR_hyperparameters = \ xgbR_hyperparameters.sort_values('val_rmse (predicted)', ascending=True) print("Processed " + "{:,}".format(xgbR_hyperparameters.shape[0]) + " new random sets of hyperparameter values " + "with below distribution of predicted NLP models rmse :" , end='\n', file=sys.stdout, flush=True) #format_vertical_headers(xgbR_hyperparameters[:best_models_count]) # "best_models_count" best "new" display( HTML(pd.DataFrame(xgbR_y_pred).describe(percentiles = [0.0001, 0.01,.25,.5,.75]).T \ .to_html(index=False)) ) # offset index, to make sure any value below "best_models_count" # is an historical "best" during the (following) merge operation => xgbR_hyperparameters.index = \ xgbR_hyperparameters.index + best_models_count # merge two dataframes (historical "best" and "batch_models_count" new) xgbR_best_hyperparameters = \ pd.concat( [xgbR_hyperparameters , xgbR_best_hyperparameters] , axis=0 , sort=False ).sort_values('val_rmse (predicted)', ascending=True)[:best_models_count] # indentify "new best" among "bests" by the "index" value of the rows new_best_count = xgbR_best_hyperparameters[ xgbR_best_hyperparameters.index > (best_models_count - 1) ].shape[0] print(str(new_best_count) + " new \"best\" hyperparameter values" + (" :" if new_best_count > 0 else "") , end='\n', file=sys.stdout, flush=True) if new_best_count > 0 : format_vertical_headers( xgbR_best_hyperparameters.style.apply( lambda df_row: row_index_n_bold_style(best_models_count-1)(df_row) , axis=1) ) xgbR_best_hyperparameters.reset_index(drop=True, inplace=True) return xgbR_best_hyperparameters loops_completed_count = 0 try: ###################################### ## loop until we have collected ## ## "best_models_count" sets ## ## of "best" hyperparameters values ## ###################################### while ( (xgbR_best_hyperparameters.shape[0] < best_models_count) | (xgbR_best_hyperparameters['val_rmse (predicted)'] > NLP_predicted_val_rmse_threshold).any() ) : print("WAVE #" + str(loops_completed_count+1), end='\n', file=sys.stdout, flush=True) xgbR_best_hyperparameters = \ get_best_hyperparameters(xgbR_best_hyperparameters) print("", end='\n', file=sys.stdout, flush=True) loops_completed_count += 1 #break except KeyboardInterrupt: sys.stderr.flush() print('\x1b[4;33;41m' + ' Interrupted by user ! ' + '\x1b[0m', end='\n', file=sys.stdout, flush=True) print('\033[1m' + '\033[4m' + '\033[96m' + "As per the prediction of the XGBoost regressor, " + f"out of the {loops_completed_count*batch_models_count:,} random sets of hyperparameters considered, " + f"here are the final {xgbR_best_hyperparameters[:best_models_count].shape[0]:,} predicted \"best\" :" + '\033[0m' , end='\n', file=sys.stdout, flush=True) format_vertical_headers(xgbR_best_hyperparameters[:best_models_count]) return xgbR_best_hyperparameters #/////////////////////////////////////////////////////////////////////////////////////
true