text stringlengths 38 1.54M |
|---|
pessoas = [['Joao', 10], ['Leandro', 27]]
for p in pessoas:
print(f'O {p[0]} tem {p[1]} anos de idade') |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate
from config import Config
db = SQLAlchemy()
mi = Migrate()
ma = Marshmallow()
def create_app(config=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
mi.init_app(app, db)
ma.init_app(db)
from api import api
app.register_blueprint(api, url_prefix='/api/')
return app
app = create_app()
from models import Empleado, Turno
@app.shell_context_processor
def make_shell_context():
return {'db':db, 'Empleado':Empleado, 'Turno':Turno}
|
import pandas as pd
from anytree import NodeMixin, RenderTree
from abc import ABC, abstractmethod
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
import numpy as np
class DataTypes:
BOOLEAN = 1
INTEGER = 2
FLOAT = 3
STRING = 4
CATEGORICAL = 5
DATE = 6
TIME = 7
DATETIME = 8
SHORT_TIME = 9
SHORT_DATETIME = 10
SECONDS: float = 11
MINUTES: float = 12
HOURS: float = 13
DAYS: float = 14
WEEKS: float = 15
YEARS: float = 16
EPOCH: float = 17
DEFAULT_DATE_FORMAT = '%d/%m/%Y' # Refer https://docs.python.org/3/library/datetime.html
DEFAULT_TIME_FORMAT = '%H:%M:%S'
DEFAULT_DATETIME_FORMAT = '%d/%m/%Y %H:%M:%S'
DEFAULT_SHORT_TIME_FORMAT = '%H:%M'
DEFAULT_SHORT_DATETIME_FORMAT = '%d/%m/%Y %H:%M'
class FieldTransform(NodeMixin):
function_name: str = None
scalar: object = None
scalar_type: str = None # This can be MinMaxScaler or StandardScaler
encoder: object = None
encoder_type: str = None # This can be OneHotEncoder or LabelEncoder
from_field: str = None # field name before transformation
to_fields: str = [] # field names after transformation
# class TypeTransformedData(ABC):
# data_type: int = None
# run: bool = True
# srs: pd.Series = None
# srs_out: pd.Series = None
# success_count: float = None
# percentage: float = None
# threshold: float = 80
# sample_size: float = 5
# iterations: int = 3
#
# def __init__(self, srs: pd.Series, run: bool = True, **kwargs):
# self.srs = srs
# self.run = self.run if run is None else run
# self._import_kwargs(**kwargs)
#
# def _import_kwargs(self, **kwargs):
# accepted_keys = set(['threshold', 'sample_size', 'iterations'])
# self.__dict__.update((key, value) for key, value in kwargs.items() if key in accepted_keys)
#
# @abstractmethod
# def is_my_type(self) -> bool:
# """
# :return:
#
# TODO:
# Identify if the series is of my type
# Set the following parameters of the object
# srs_out : transformed data to my type
# success_count: number of successfully transformed values to my type
# percentage: number of successfully transformed values to my type
# """
class DataTypeIdentifier:
srs: pd.Series = None
data_type: int = None
srs_out: pd.Series = None
percentage: float = None
explore_types: list = None
_transformed_srs: dict = {}
def __init__(self, srs: pd.Series, explore_types: list = None):
self.srs = srs
self.explore_types = explore_types if explore_types is not None else self.explore_types
def _is_boolean(self) -> bool:
"""
:param field_name:
:return: true or false
:set:
TODO:
Check if the given column is boolean.
The column can be of any type originally.
You can identify boolean fields by looking at data rather than the pandas data type.
Use the following for the first version any of the following can be converted to boolean.
string or boolean data {true, false}
string or any numeric data {0,1}
string {'yes','no'}
.
When string types are considered the values should not be case sensitive
None, Nan, ' ', '-'
"""
def _is_integer(self) -> bool:
"""
:return: true or false
TODO:
Check if the given column is integer
The interger values can be
"""
class DataSet:
data: pd.DataFrame = None
transformed_data: pd.DataFrame = None
field_transforms = {}
pipe_line = {} # This is a dictionary. There is a key for each
def __init__(self, data:pd.DataFrame):
self.data = data
def identify_data_types(self):
pass
def standardize_missing_data(self, data: pd.DataFrame = None):
"""
:param data:
:param field_name:
:return:
The data set can consist of many empty values represented in different formats.
Example:
NaN,None,'','-','NA', 'N/A', \spaces, \tabs
These can be string or in different cases
TODO:
Fill all missing data with NaN
update the following:
transformed_data
"""
|
from ..desktop import ConfigManager
import unittest
class TestConfigManager(unittest.TestCase):
def setUp(self):
self.c: ConfigManager = ConfigManager("test_data/cfg.json")
def test_intime(self):
self.c.setProperty("a", 5)
cfg = ConfigManager("test_data/cfg.json")
self.assertEqual(cfg.getProperty("a", 5000), 5)
def test_no_intime(self):
cfg = ConfigManager("test_data/cfg.json", intime=False)
cfg.setProperty("a", 10)
cfg = ConfigManager("test_data/cfg.json")
a=cfg.getProperty("a", 0)
self.assertEqual(a, 5)
|
from numpy import*
v = array(eval(input("Vetor:")))
i = 0
while (i < size(v)):
if(v[i]%2 != 0):
v[i] = 0
i = i + 1
print(v) |
list=[]
for i in range(123,568):
if i%5==0 or i%6==0:
list.append(i)
print(list)
print(len(list))
print("sum= ",sum(list))
|
from snippet_analyser import SnippetAnalyser
from snippet_matcher import SnippetMatcher
from snippet_analysis_helper import LanguageMode
import os
class SnippetController:
def __init__(self, snippet, task_arguments, task_comment, language_mode=LanguageMode.python, debug=False):
self.task_arguments = task_arguments
self.task_comment = task_comment
self.snippet = snippet
self.snippet_analyser = SnippetAnalyser(snippet, language_mode)
self.snippet_matcher = None
self.debug = debug
def analyze(self):
self.snippet_analyser.execute()
self.snippet_matcher = SnippetMatcher(self.snippet_analyser,
self.snippet,
self.task_arguments,
self.task_comment)
self.snippet_matcher.match_functions()
if self.debug:
print "Global types"
print self.snippet_analyser.global_type_dict
print "Local unique types"
print self.snippet_analyser.type_dict
print "==========="
print "Matched Functions"
print self.snippet_matcher.match_functions()
print "Detailed Function Info"
print self.snippet_matcher.functions
def clean(self):
to_clean = [self.snippet_analyser.helper.filename[:-3],
self.snippet_analyser.helper.filename + "c", self.snippet_analyser.helper.filename]
for temp_file in to_clean:
try:
os.remove(temp_file)
except OSError:
pass
def find_snippet(self):
self.analyze()
self.clean()
return self.snippet_matcher.match_functions(), self.snippet_matcher.functions
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
try:
from ._models_py3 import Annotation
from ._models_py3 import AnnotationError, AnnotationErrorException
from ._models_py3 import APIKeyRequest
from ._models_py3 import ApplicationInsightsComponent
from ._models_py3 import ApplicationInsightsComponentAnalyticsItem
from ._models_py3 import ApplicationInsightsComponentAnalyticsItemProperties
from ._models_py3 import ApplicationInsightsComponentAPIKey
from ._models_py3 import ApplicationInsightsComponentAvailableFeatures
from ._models_py3 import ApplicationInsightsComponentBillingFeatures
from ._models_py3 import ApplicationInsightsComponentDataVolumeCap
from ._models_py3 import ApplicationInsightsComponentExportConfiguration
from ._models_py3 import ApplicationInsightsComponentExportRequest
from ._models_py3 import ApplicationInsightsComponentFavorite
from ._models_py3 import ApplicationInsightsComponentFeature
from ._models_py3 import ApplicationInsightsComponentFeatureCapabilities
from ._models_py3 import ApplicationInsightsComponentFeatureCapability
from ._models_py3 import ApplicationInsightsComponentProactiveDetectionConfiguration
from ._models_py3 import ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions
from ._models_py3 import ApplicationInsightsComponentQuotaStatus
from ._models_py3 import ApplicationInsightsComponentWebTestLocation
from ._models_py3 import ComponentPurgeBody
from ._models_py3 import ComponentPurgeBodyFilters
from ._models_py3 import ComponentPurgeResponse
from ._models_py3 import ComponentPurgeStatusResponse
from ._models_py3 import ComponentsResource
from ._models_py3 import ErrorFieldContract
from ._models_py3 import ErrorResponse, ErrorResponseException
from ._models_py3 import InnerError
from ._models_py3 import LinkProperties
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import PrivateLinkScopedResource
from ._models_py3 import TagsResource
from ._models_py3 import WebTest
from ._models_py3 import WebTestGeolocation
from ._models_py3 import WebTestPropertiesConfiguration
from ._models_py3 import WebtestsResource
from ._models_py3 import Workbook
from ._models_py3 import WorkbookError, WorkbookErrorException
from ._models_py3 import WorkbookResource
from ._models_py3 import WorkItemConfiguration
from ._models_py3 import WorkItemConfigurationError, WorkItemConfigurationErrorException
from ._models_py3 import WorkItemCreateConfiguration
except (SyntaxError, ImportError):
from ._models import Annotation
from ._models import AnnotationError, AnnotationErrorException
from ._models import APIKeyRequest
from ._models import ApplicationInsightsComponent
from ._models import ApplicationInsightsComponentAnalyticsItem
from ._models import ApplicationInsightsComponentAnalyticsItemProperties
from ._models import ApplicationInsightsComponentAPIKey
from ._models import ApplicationInsightsComponentAvailableFeatures
from ._models import ApplicationInsightsComponentBillingFeatures
from ._models import ApplicationInsightsComponentDataVolumeCap
from ._models import ApplicationInsightsComponentExportConfiguration
from ._models import ApplicationInsightsComponentExportRequest
from ._models import ApplicationInsightsComponentFavorite
from ._models import ApplicationInsightsComponentFeature
from ._models import ApplicationInsightsComponentFeatureCapabilities
from ._models import ApplicationInsightsComponentFeatureCapability
from ._models import ApplicationInsightsComponentProactiveDetectionConfiguration
from ._models import ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions
from ._models import ApplicationInsightsComponentQuotaStatus
from ._models import ApplicationInsightsComponentWebTestLocation
from ._models import ComponentPurgeBody
from ._models import ComponentPurgeBodyFilters
from ._models import ComponentPurgeResponse
from ._models import ComponentPurgeStatusResponse
from ._models import ComponentsResource
from ._models import ErrorFieldContract
from ._models import ErrorResponse, ErrorResponseException
from ._models import InnerError
from ._models import LinkProperties
from ._models import Operation
from ._models import OperationDisplay
from ._models import PrivateLinkScopedResource
from ._models import TagsResource
from ._models import WebTest
from ._models import WebTestGeolocation
from ._models import WebTestPropertiesConfiguration
from ._models import WebtestsResource
from ._models import Workbook
from ._models import WorkbookError, WorkbookErrorException
from ._models import WorkbookResource
from ._models import WorkItemConfiguration
from ._models import WorkItemConfigurationError, WorkItemConfigurationErrorException
from ._models import WorkItemCreateConfiguration
from ._paged_models import AnnotationPaged
from ._paged_models import ApplicationInsightsComponentAPIKeyPaged
from ._paged_models import ApplicationInsightsComponentPaged
from ._paged_models import ApplicationInsightsComponentWebTestLocationPaged
from ._paged_models import OperationPaged
from ._paged_models import WebTestPaged
from ._paged_models import WorkbookPaged
from ._paged_models import WorkItemConfigurationPaged
from ._application_insights_management_client_enums import (
ApplicationType,
FlowType,
RequestSource,
PurgeState,
PublicNetworkAccessType,
FavoriteType,
WebTestKind,
ItemScope,
ItemType,
SharedTypeKind,
FavoriteSourceType,
ItemScopePath,
ItemTypeParameter,
CategoryType,
)
__all__ = [
'Annotation',
'AnnotationError', 'AnnotationErrorException',
'APIKeyRequest',
'ApplicationInsightsComponent',
'ApplicationInsightsComponentAnalyticsItem',
'ApplicationInsightsComponentAnalyticsItemProperties',
'ApplicationInsightsComponentAPIKey',
'ApplicationInsightsComponentAvailableFeatures',
'ApplicationInsightsComponentBillingFeatures',
'ApplicationInsightsComponentDataVolumeCap',
'ApplicationInsightsComponentExportConfiguration',
'ApplicationInsightsComponentExportRequest',
'ApplicationInsightsComponentFavorite',
'ApplicationInsightsComponentFeature',
'ApplicationInsightsComponentFeatureCapabilities',
'ApplicationInsightsComponentFeatureCapability',
'ApplicationInsightsComponentProactiveDetectionConfiguration',
'ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions',
'ApplicationInsightsComponentQuotaStatus',
'ApplicationInsightsComponentWebTestLocation',
'ComponentPurgeBody',
'ComponentPurgeBodyFilters',
'ComponentPurgeResponse',
'ComponentPurgeStatusResponse',
'ComponentsResource',
'ErrorFieldContract',
'ErrorResponse', 'ErrorResponseException',
'InnerError',
'LinkProperties',
'Operation',
'OperationDisplay',
'PrivateLinkScopedResource',
'TagsResource',
'WebTest',
'WebTestGeolocation',
'WebTestPropertiesConfiguration',
'WebtestsResource',
'Workbook',
'WorkbookError', 'WorkbookErrorException',
'WorkbookResource',
'WorkItemConfiguration',
'WorkItemConfigurationError', 'WorkItemConfigurationErrorException',
'WorkItemCreateConfiguration',
'OperationPaged',
'AnnotationPaged',
'ApplicationInsightsComponentAPIKeyPaged',
'ApplicationInsightsComponentPaged',
'WorkItemConfigurationPaged',
'ApplicationInsightsComponentWebTestLocationPaged',
'WebTestPaged',
'WorkbookPaged',
'ApplicationType',
'FlowType',
'RequestSource',
'PurgeState',
'PublicNetworkAccessType',
'FavoriteType',
'WebTestKind',
'ItemScope',
'ItemType',
'SharedTypeKind',
'FavoriteSourceType',
'ItemScopePath',
'ItemTypeParameter',
'CategoryType',
]
|
from django.apps import apps
from djangobmf.settings import CONTRIB_EMPLOYEE
from djangobmf.settings import CONTRIB_TEAM
def user_add_bmf(user):
"""
Adds ``djangobmf_employee`` and ``djangobmf_teams`` to the given
user instance.
"""
if not hasattr(user, 'djangobmf_employee'):
try:
employee = apps.get_model(CONTRIB_EMPLOYEE)
try:
setattr(
user,
'djangobmf_employee',
employee.objects.get(user=user)
)
except employee.DoesNotExist:
setattr(user, 'djangobmf_employee', None)
setattr(user, 'djangobmf_has_employee', True)
except LookupError:
setattr(user, 'djangobmf_employee', None)
setattr(user, 'djangobmf_has_employee', False)
if not hasattr(user, 'djangobmf_teams'):
try:
teams = apps.get_model(CONTRIB_TEAM)
setattr(
user,
'djangobmf_teams',
teams.objects.filter(members=getattr(user, 'djangobmf_employee')).values_list("id", flat=True),
)
except LookupError:
setattr(user, 'djangobmf_teams', [])
|
##encoding=utf-8
"""
This module is to teach you the basic use of wordsegmentation/tokenize (句子分词)
What is tokenize?
tokenize is to split sentence into word tokens and punctuations.
For example: I like obama. => ["I", "like", "obama", "."]
"""
from __future__ import print_function
from pprint import pprint
import nltk
def tokenize_example():
r"""
[EN]Usually the first step of natural language analysis is split sentence into word token.
To do this you need run nltk.download() and download:
tokenizers/punkt/english.pickle using NLTK downloader => Model => punkt
[CN]自然语言分析的第一步就是句子分词(将句子拆分成有独立语义的单词)
nltk.word_tokenize(text)是内置的方法。若要对英文进行分词则需要下载:
tokenizers/punkt/english.pickle 下载方法: NLTK downloader => Model => punkt
下载后的文件会被储存在中:
C:\Users\username\AppData\Roaming\nltk_data\tokenizers
"""
sentence = """At eight o'clock on Thursday morning ... Arthur didn't feel very good."""
tokens = nltk.word_tokenize(sentence)
pprint(tokens)
tokenize_example()
# nltk.download() |
from pypboy import BaseModule
from pypboy.modules.items import weapons
from pypboy.modules.items import apparel
from pypboy.modules.items import aid
from pypboy.modules.items import misc
from pypboy.modules.items import ammo
class Module(BaseModule):
label = "ITEMS"
GPIO_LED_ID = 16
def __init__(self, *args, **kwargs):
self.submodules = [
weapons.Module(self),
apparel.Module(self),
aid.Module(self),
misc.Module(self),
ammo.Module(self)
]
super(Module, self).__init__(*args, **kwargs)
|
# -*- coding: utf-8 -*-
import unittest
from mongoengine import NotUniqueError
from utils import AnellaTestCase
from anella.common import *
from anella.model.user import User
__all__ = ('UserTest', )
class UserTest(AnellaTestCase):
def test_user_save(self):
user = User(email='pepe@i2cat.net', auth_id=23)
user.save()
self.assertIsNotNone(user.pk)
with self.assertRaises(NotUniqueError):
user = User(email='pepe@i2cat.net')
user.save()
if __name__ == '__main__':
unittest.main()
|
from typing import List
from arg.qck.decl import QKUnit
from cache import load_from_pickle
# Unfiltered candidates from top BM25
def load_qk_candidate_train() -> List[QKUnit]:
return load_from_pickle("perspective_qk_candidate_train")
# Unfiltered candidates from top BM25
def load_qk_candidate_dev() -> List[QKUnit]:
return load_from_pickle("perspective_qk_candidate_dev") |
import shutil
from tqdm import tqdm
import numpy.random as npr
import numpy as np
import random
import glob
import cv2
import PIL.Image as Image
import os
from threading import Thread,currentThread
from multiprocessing import cpu_count
cnt=0
class MyWorker(Thread):
def __init__(self,imagelist,tgt,offset):
super().__init__()
self.imagelist=imagelist
self.tgt=tgt
self.offset=offset
def run(self):
name=currentThread().getName()
print(name,':data size:',len(self.imagelist))
createDetectDataSet(self.imagelist,self.tgt,offset=self.offset)
def createDetectDataSet(imglist,tgt,num=None,offset=0):
#imglist=glob.glob(src)
# random.shuffle(imglist)
if num:imglist=imglist[:num]
def decodeBox(imgname):
I=cv2.imread(imgname)
H,W,_=I.shape
W,H=Image.open(imgname).size
basename=os.path.basename(imgname)
sps=basename.split('-')
bbox=sps[2]
bbox=bbox.split('_')
pp1=bbox[0].split('&')
pp2=bbox[1].split('&')
x1,y1,x2,y2=int(pp1[0]),int(pp1[1]),int(pp2[0]),int(pp2[1])
cx,cy,w,h=(x1+x2)/2,(y1+y2)/2,(x2-x1+1),(y2-y1+1)
return cx/W,cy/H,w/W,h/H
for i,imgpath in enumerate(imglist):
##open file
cx,cy,w,h=decodeBox(imgpath)
content=' '.join(map(str,[0,cx,cy,w,h]))
tgt_img=os.path.join(tgt,'%d.jpg'%(offset+i))
tgt_label=os.path.join(tgt,'%d.txt'%(offset+i))
shutil.copy(imgpath,tgt_img)
with open(tgt_label,'w') as fs:
fs.write(content)
src_path='/home/zxk/AI/data/CCPD2019/ccpd_base/*.jpg'
imglist=glob.glob(src_path)
tgt_path='my'
cpus=cpu_count()
BATCH=int(np.ceil(len(imglist)/cpus))
threads=[]
for i in range(cpus):
t=MyWorker(imglist[i*BATCH:i*BATCH+BATCH],tgt_path,offset=i*BATCH)
threads.append(t)
t.start()
for t in threads:
t.join()
|
"""
NOTE: This file is currently FUBAR. Do not look at this for anything meaningful!
"""
import numpy as np
from gridworld import *
from mdp_solver import *
from sample_utils import sample_niw
class Observation(object):
def __init__(self, episode, state, reward, reward_stdev, goal = False):
self.episode = episode
self.state = state
self.reward = reward
self.reward_stdev = reward_stdev
self.goal = goal
class LinearGaussianRewardModel(object):
def __init__(self, num_colors, posterior_samples=3000, burn_in=500, thin=10, proposal_variance=0.1):
self.observations = []
self.posterior_samples = posterior_samples
self.burn_in = burn_in
self.thin = thin
self.proposal_variance = proposal_variance
self.weights_mean_size = num_colors * NUM_RELATIVE_CELLS
self.weights_cov_size = (self.weights_mean_size, self.weights_mean_size)
self.weights_size = self.weights_mean_size
# The parameters of the Normal-Inverse-Wishart prior (mu, lambda, nu, psi)
# I am trying to use very vague parameters here, to get close to an uninformed prior.
self.hyper_parameters = (np.zeros(self.weights_size), 1., self.weights_size, np.identity(self.weights_size) * 3.)
self.episodes = 0
self.bayes_estimates = (np.zeros(self.weights_size), np.identity(self.weights_size) * 3, np.zeros(self.weights_size))
def add_reward_observation(self, observation, update=True):
self.observations.append(observation)
if update:
self.update_beliefs()
def update_beliefs(self):
self.samples = self.calculate_posterior()
self.bayes_estimates = (np.mean(s, axis=0) for s in self.samples)
def calculate_posterior(self):
mean_samples = []
cov_samples = []
weight_samples = []
mean = np.zeros(self.weights_mean_size)
cov = np.identity(self.weights_mean_size)
weights = np.random.multivariate_normal(mean, cov)
for i in range(self.posterior_samples):
print i
mean,cov = self.gibbs_weights_mean_cov(weights)
weights = self.mcmc_weights(weights, mean, cov)
if i >= self.burn_in and i % self.thin == 0:
mean_samples.append(mean)
cov_samples.append(cov)
weight_samples.append(weights)
print 'Iteration {0}'.format(i)
print 'Phi: {0}'.format(mean)
print 'Sigma: {0}'.format(cov_samples)
print 'Weights: {0}'.format(weights)
print ''
return (mean_samples, cov_samples, weight_samples)
def gibbs_weights_mean_cov(self, weights):
avg_weights = weights #np.mean(weights, axis=0)
post_mean = (self.hyper_parameters[1] * self.hyper_parameters[0] + self.episodes * avg_weights) / (self.hyper_parameters[1] + self.episodes)
post_lambda = self.hyper_parameters[1] + self.episodes
post_nu = self.hyper_parameters[2] + self.episodes
deviation = avg_weights - self.hyper_parameters[0]
#post_psi = self.hyper_parameters[3] + np.sum([np.dot(w - avg_weights, np.transpose(w - avg_weights)) for w in weights]) \
post_psi = self.hyper_parameters[3] \
+ self.hyper_parameters[1] * self.episodes / (self.hyper_parameters[1] + self.episodes) \
* np.dot(deviation, np.transpose(deviation))
(sample_mean, sample_cov) = sample_niw(post_mean, post_lambda, post_nu, np.linalg.inv(post_psi))
return (sample_mean, sample_cov)
def mcmc_weights(self, prev_weights, mean, cov):
cur_weights = np.copy(prev_weights)
cur_likelihood = self.weights_likelihood(cur_weights, mean, cov)
for i in range(self.burn_in):
proposed = self.weights_proposal(cur_weights)
proposal_likelihood = self.weights_likelihood(proposed, mean, cov)
u = random.random()
if math.log(u) < (proposal_likelihood - cur_likelihood):
cur_weights = proposed
cur_likelihood = proposal_likelihood
return cur_weights
def weights_proposal(self, prev_weights):
return np.random.multivariate_normal(prev_weights, np.identity(self.weights_size) * self.proposal_variance)
def weights_likelihood(self, weights, mean, cov):
sum_rewards = sum([(x.reward - np.dot(np.transpose(weights), x.state)) ** 2 / (x.reward_stdev ** 2) for x in self.observations])
prior_term = np.dot(np.dot(np.transpose(weights - mean), np.linalg.inv(cov)), weights - mean)
return -0.5 * (sum_rewards + prior_term) # log prob
def predict_value(self, state):
return np.dot(self.bayes_estimates[0], state)
class SingleTaskBayesianAgent(Agent):
"""
A Bayesian RL agent that views all the domains as drawn from the same distribution.
"""
def __init__(self, width, height, num_colors, num_domains, name=None, steps_per_policy=1):
super(SingleTaskBayesianAgent, self).__init__(width, height, num_colors, num_domains, name)
self.model = LinearGaussianRewardModel(num_colors)
self.value_function = np.array((num_domains, width, height))
self.state_vector = np.array((num_domains, width, height, num_colors * NUM_RELATIVE_CELLS))
self.steps_per_policy = steps_per_policy
self.steps_since_update = 0
def episode_starting(self, idx, state):
super(SingleTaskBayesianAgent, self).episode_starting(idx, state)
self.steps_since_update = 0
mdp = self.sample_mdp()
def episode_over(self, idx):
super(SingleTaskBayesianAgent, self).episode_over(idx)
def get_action(self, idx):
pass
def set_state(self, idx, state):
super(SingleTaskBayesianAgent, self).set_state(idx, state)
def observe_reward(self, idx, r):
super(SingleTaskBayesianAgent, self).observe_reward(idx, r)
self.model.add_reward_observation(Observation(idx, ))
def sample_mdp(self):
# TODO: sample a MAP MDP
return np.zeros(self.num_colors * NUM_RELATIVE_CELLS)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#PIN configuration
pinOutControl = 40
pinPIR = 38
trigSR04 = 35
echoSR04 = 37
#Global Parameters
lengthCM_SR04 = 15 #距離SR04在幾公分以內, 才認定為正開始使用照護系統
timeLasted_SR04 = 5 #有人站在SR04面前持續了幾秒後, 才認定為要始用照護系統
nextWelcomeTimer = 60 #上次Welcome之後, 至少要隔多久才能再Welcome
#speakerName = ["Bruce", "Theresa", "Angela" "TW_LIT_AKoan", "TW_SPK_AKoan"]
#-------------------------------------------------
tmpTime_SR04 = 0 #開始計時時的秒數, 用於計算timeLasted_SR04
statusSR04 = 0
statusPIR = 0
tmpLastWelcomeTime = 0 #上次的歡迎時間
import RPi.GPIO as GPIO
import time
import timeit
import speechClass
import json
import os
import random
import pyaudio
import wave
import sys
import os.path
CHUNK_SIZE = 10240
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pinOutControl ,GPIO.OUT)
GPIO.setup(pinPIR ,GPIO.IN)
GPIO.setup(trigSR04 ,GPIO.OUT)
GPIO.setup(echoSR04 ,GPIO.IN)
GPIO.output(trigSR04, GPIO.LOW)
os.system("amixer set PCM -- 100%")
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def getWAV_1(vHour):
'''
a1 早安
a2 Good Morning
a3 早
a4 早上愉快
a5 Have a nice day.
b1 午安
b2 吃中餐了嗎?
b3 午餐時間快到了
b4 午安, 早上忙嗎?
b5 休息一下, 快中午了.
c1 午安.
c2 午安, 忙嗎?
c3 Good afternoon.
c4 Good afternoon. 午安.
c5 午安, 休息一下.
d1 Good evening, 晚安
d2 晚安, 要準備下班了嗎?
d3 您好, 今天忙嗎?
d4 晚安, 忙了一天, 請休息一下.
d5 晚安, 忙碌的一天又快結束了.
e1 很晚了, 還不準備下班嗎?
e2 晚安, 不要加班加太晚, 請早點下班,
e3 時間不早了, 忙了一天, 早點休息吧.
e4 晚安, 又是忙碌的一天, 辛苦了.
e5 晚安, 很晚了, 要準備下班了嗎?
f1 辛苦你了
f2 加班辛苦了
'''
if vHour>=5 and vHour<11:
wordArray_1 = ["a1", "a2", "a3", "a4", "a5"]
elif vHour>=11 and vHour<13:
wordArray_1 = ["b1", "b2", "b3", "b4", "b5"]
elif vHour>=13 and vHour<17:
wordArray_1 = ["c1", "c2", "c3", "c4", "c5"]
elif vHour>=17 and vHour<20:
wordArray_1 = ["d1", "d2", "d3", "d4", "d5"]
elif vHour>=20 and vHour<24:
wordArray_1 = ["e1", "e2", "e3", "e4", "e5"]
elif vHour>=0 and vHour<5:
wordArray_1 = ["f1", "f2"]
return random.choice(wordArray_1)
def getWAV_2():
'''
welcome1 歡迎使用福委會的員工照護系統
welcome2 歡迎您使用福委會員工照護系統
'''
wordArray_2 = ["welcome1", "welcome2"]
return random.choice(wordArray_2)
def speakWords(wordsSpeak, speakerName, frequency, speed):
nessContent = wordsSpeak
#print nessContent
newsArray = nessContent.split("|")
i=0
person = speechClass.TTSspech()
for newsSpeak in newsArray:
if(len(newsSpeak)>0):
#print len(newsSpeak)
print "(" + str(len(newsSpeak)) + ") " + newsSpeak
person.setWords("\"" + newsSpeak + "\"")
person.setSpeaker("\"" + speakerName + "\"") # Bruce, Theresa, Angela, MCHEN_Bruce, MCHEN_Jo$
person.setSpeed(speed)
id = int(person.createConvertID())
print "URL: " + person.getVoiceURL()
if(id>0):
#print person.getVoiceURL()
#while person.isBusySpeakingNow():time.sleep( 0.05 )
person.playVoice(frequency ,5)
def play_wav(wav_filename, chunk_size=CHUNK_SIZE):
'''
Play (on the attached system sound device) the WAV file
named wav_filename.
'''
try:
print 'Trying to play file ' + wav_filename
wf = wave.open(wav_filename, 'rb')
except IOError as ioe:
sys.stderr.write('IOError on file ' + wav_filename + '\n' + \
str(ioe) + '. Skipping.\n')
return
except EOFError as eofe:
sys.stderr.write('EOFError on file ' + wav_filename + '\n' + \
str(eofe) + '. Skipping.\n')
return
# Instantiate PyAudio.
p = pyaudio.PyAudio()
# Open stream.
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(chunk_size)
while len(data) > 0:
stream.write(data)
data = wf.readframes(chunk_size)
# Stop stream.
stream.stop_stream()
stream.close()
# Close PyAudio.
p.terminate()
def readSR04():
time.sleep(0.3)
GPIO.output(trigSR04, True)
time.sleep(0.00001)
GPIO.output(trigSR04, False)
# listen to the input pin. 0 means nothing is happening. Once a
# signal is received the value will be 1 so the while loop
# stops and has the last recorded time the signal was 0
# change this value to the pin you are using
# GPIO input = the pin that's connected to "Echo" on the sensor
while GPIO.input(echoSR04) == 0:
signaloff = time.time()
# listen to the input pin. Once a signal is received, record the
# time the signal came through
# change this value to the pin you are using
# GPIO input = the pin that's connected to "Echo" on the sensor
while GPIO.input(echoSR04) == 1:
signalon = time.time()
# work out the difference in the two recorded times above to
# calculate the distance of an object in front of the sensor
timepassed = signalon - signaloff
# we now have our distance but it's not in a useful unit of
# measurement. So now we convert this distance into centimetres
distance = timepassed * 17000
# return the distance of an object in front of the sensor in cm
return distance
def getDistance():
sampleCounts = 6 #要取幾次標本
count = 0
maxValue = 0
minValue = 99999
totalValue = 0
while(count<sampleCounts):
valueSR04 = readSR04()
if valueSR04>maxValue:
maxValue = valueSR04
if valueSR04<minValue:
minValue = valueSR04
totalValue += valueSR04
count += 1
return (totalValue-maxValue-minValue) / (sampleCounts-2)
while True:
dt = list(time.localtime())
nowHour = dt[3]
nowMinute = dt[4]
statusPIR = GPIO.input(pinPIR)
#如果有人站在前面
if getDistance()<lengthCM_SR04:
#如果是第一次發現有人, 則開始計時.
if statusSR04 == 0:
print "第一次發現有人, 則開始計時"
tmpTime_SR04 = timeit.default_timer()
statusSR04 = 1
else:
#如果在SR04前面站的時間夠久, 且距離上次Welcome時間也夠長了, 則開始Welcome
if (timeit.default_timer() - tmpTime_SR04) > timeLasted_SR04:
print "在SR04前面站的時間夠久"
if (tmpLastWelcomeTime == 0 or (timeit.default_timer() - tmpLastWelcomeTime)>nextWelcomeTimer):
print "距離上次Welcome時間也夠長"
tmpLastWelcomeTime = timeit.default_timer()
word_1 = getWAV_1(nowHour)
word_2 = getWAV_2()
play_wav("wav/man/"+word_1+".wav", CHUNK_SIZE)
#speaker = random.choice(speakerName)
#如果沒人站在前面
else:
#如果是剛離開
if statusSR04 == 1:
print "您站了" + str(timeit.default_timer() - tmpTime_SR04) + "秒鐘。"
statusSR04 = 0
tmpTime_SR04 = 0
|
#! /usr/bin/env python
import unittest
from sha2 import *
class SingleSHA256(unittest.TestCase):
def setUp(self):
self.f = sha256
def test_empty(self):
self.assertEqual(self.f('abc').hexdigest(),
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')
# ba7816bf
# 8f01cfea
# 414140de
# 5dae2223
# b00361a3
# 96177a9c
# b410ff61
# f20015ad
class SingleSHA512(unittest.TestCase):
def setUp(self):
self.f = sha512
def test_empty(self):
self.assertEqual(self.f('abc').hexdigest(),
'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a'+
'2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')
#ddaf35a1 #93617aba
#cc417349 #ae204131
#12e6fa4e #89a97ea2
#0a9eeee6 #4b55d39a
#2192992a #274fc1a8
#36ba3c23 #a3feebbd
#454d4423 #643ce80e
#2a9ac94f #a54ca49f
class TestSHA224(unittest.TestCase):
def setUp(self):
self.f = sha224
def test_empty(self):
self.assertEqual(self.f('').hexdigest(),
'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f')
def test_less_than_block_length(self):
self.assertEqual(self.f('abc').hexdigest(),
'23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')
def test_block_length(self):
self.assertEqual(self.f('a'*64).hexdigest(),
'a88cd5cde6d6fe9136a4e58b49167461ea95d388ca2bdb7afdc3cbf4')
def test_several_blocks(self):
self.assertEqual(self.f('a'*1000000).hexdigest(),
'20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67')
class TestSHA256(unittest.TestCase):
def setUp(self):
self.f = sha256
def test_empty(self):
self.assertEqual(self.f('').hexdigest(),
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
def test_less_than_block_length(self):
self.assertEqual(self.f('abc').hexdigest(),
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')
def test_block_length(self):
self.assertEqual(self.f('a'*64).hexdigest(),
'ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb')
def test_several_blocks(self):
self.assertEqual(self.f('a'*1000000).hexdigest(),
'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0')
class TestSHA384(unittest.TestCase):
def setUp(self):
self.f = sha384
def test_empty(self):
self.assertEqual(self.f('').hexdigest(),
'38b060a751ac96384cd9327eb1b1e36a21fdb71114be0743'+
'4c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b')
def test_less_than_block_length(self):
self.assertEqual(self.f('abc').hexdigest(),
'cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163'+
'1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7')
def test_block_length(self):
self.assertEqual(self.f('a'*128).hexdigest(),
'edb12730a366098b3b2beac75a3bef1b0969b15c48e2163c'+
'23d96994f8d1bef760c7e27f3c464d3829f56c0d53808b0b')
def test_several_blocks(self):
self.assertEqual(self.f('a'*1000000).hexdigest(),
'9d0e1809716474cb086e834e310a4a1ced149e9c00f24852'+
'7972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985')
class TestSHA512(unittest.TestCase):
def setUp(self):
self.f = sha512
def test_empty(self):
self.assertEqual(self.f('').hexdigest(),
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce'+
'47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e')
def test_less_than_block_length(self):
self.assertEqual(self.f('abc').hexdigest(),
'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a'+
'2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')
def test_block_length(self):
self.assertEqual(self.f('a'*128).hexdigest(),
'b73d1929aa615934e61a871596b3f3b33359f42b8175602e89f7e06e5f658a24'+
'3667807ed300314b95cacdd579f3e33abdfbe351909519a846d465c59582f321')
def test_several_blocks(self):
self.assertEqual(self.f('a'*1000000).hexdigest(),
'e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb'+
'de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b')
if __name__ == '__main__':
sha256_single = unittest.TestLoader().loadTestsFromTestCase(SingleSHA256)
sha512_single = unittest.TestLoader().loadTestsFromTestCase(SingleSHA512)
sha224_suite = unittest.TestLoader().loadTestsFromTestCase(TestSHA224)
sha256_suite = unittest.TestLoader().loadTestsFromTestCase(TestSHA256)
sha384_suite = unittest.TestLoader().loadTestsFromTestCase(TestSHA384)
sha512_suite = unittest.TestLoader().loadTestsFromTestCase(TestSHA512)
all_tests = unittest.TestSuite([sha224_suite,
sha256_suite,
sha384_suite,
sha512_suite])
#unittest.TextTestRunner(verbosity=2).run(all_tests)
#unittest.TextTestRunner(verbosity=2).run(sha256_single)
unittest.TextTestRunner(verbosity=2).run(sha512_single)
|
"""The Quality-time data model."""
from .meta.data_model import DataModel
from .metrics import METRICS
from .scales import SCALES
from .sources import SOURCES
from .subjects import SUBJECTS
DATA_MODEL = DataModel(scales=SCALES, metrics=METRICS, sources=SOURCES, subjects=SUBJECTS)
DATA_MODEL_JSON = DATA_MODEL.json(exclude_none=True)
|
import os
import sys
### Other Python Libraries
import itertools
import pdb
from operator import itemgetter
import multiprocessing as mp
### MST Imports
from .NAC_Graph import NAC_Graph
from .Kruskal_Class import Kruskal_MST as MST
### imports
import Core.Solvers.SAA.SAA_NAC as SAA_NAC
def NAC_Generator(Uncertain_Parameters, Scenarios, Scenario_Outcomes):
"""
Uncertain Parameters - a tuple (i.e. ('A','B','C')) of the Uncertain Parameter Classes
for the problem (Uncertain Parameter class is in UP_Class.py)
Scenarios- a list of scenario numbers i.e. [1,2,3,...S]
Scenario_Realizations is a dictionary mapping S to its outcome
i.e. { 1:(1,0,1)}, notice the realization of uncertain
parameters is a vector. The vector length should be equal to the
number of uncertain parameters
"""
Parameters = [str(Uncertain_Parameters[i].Name) for i in range(len(Uncertain_Parameters))]
####################################################################
### Generate set of order rules
####################################################################
Order_Rules = [[r,r.ROrder] for r in Uncertain_Parameters if r.ROrder != []]
####################################################################
### Generate set of possible cuts
####################################################################
cuts = []
"""
This code loops over each uncertain parameter, if the uncertain
parameter is realized instantaneously then the code appends the
name of the parameter to the list of cuts. If the realization is
gradual the code generates a set of cuts based on the way the
parameter is realized. Order Rules are updated to reflect the
gradual cuts.
"""
for up in Uncertain_Parameters:
if up.Realization_Type == 'instant':
cuts.append(up.Name)
else:
for grs in up.GROrderSets:
cname = up.Name + '_' + str(grs)
cbefore = [up.Name + '_' + str(pp) for pp in up.GROrderSets[:grs]]
cuts.append(cname)
Order_Rules.append([cname, cbefore])
####################################################################
### Generate initial MST
####################################################################
### Initialize Graph Object
graph = NAC_Graph()
### Add Verticies to Graph
for s in Scenarios:
graph.add_vertex(s)
### Generate All Edges
graph.all_edges()
### Calculate MST using Kruskal Algorithm
MST_Graph = MST(graph,Scenario_Outcomes)
mst = MST_Graph.mst
####################################################################
### Generate cut sets
####################################################################
C_List = itertools.permutations(cuts,len(cuts)-1)
C_List = tuple(C_List)
####################################################################
### Generate NACs
####################################################################
for c in C_List:
### Check the validity of the cut list
Valid = C_List_validation(c,Order_Rules)
if Valid == True:
sets = [Scenarios,]
i = 0
while i < len(c):
### This is for instantaneous realizations
if c[i] in Parameters:
idx = Parameters.index(c[i])
new_sets = []
### Generate Multi-Process Object and Run MST Subset Gen
if len(sets) < mp.cpu_count():
np = len(sets)
else:
np = mp.cpu_count()
### Create Pool
pool = mp.Pool(np)
### Run Pool
results = [pool.apply_async(Instant_Parallel_MST, args=(ss,idx,Scenario_Outcomes,mst)) for ss in sets]
pool.close()
pool.join()
### Consolodate Results
mst = mst.union(*[results[i][0]._value for i in range(len(results))])
sets = [*results[i][1]._value for i in range(len(results))]
### This is for gradual realizations
else:
cvar = c[i].split('_')
if cvar[0] in Parameters:
idx = Parameters.index(cvar[0])
new_sets = []
### Generate Multi-Process Object and Run MST Subset Gen
if len(sets) < mp.cpu_count():
np = len(sets)
else:
np = mp.cpu_count()
### Create Pool
pool = mp.Pool(np)
### Run Pool
results = [pool.apply_async(Gradual_Parallel_MST, args=(ss,idx,Scenario_Outcomes,mst)) for ss in sets]
pool.close()
pool.join()
### Consolodate Results
mst = mst.union(*[results[i][0]._value for i in range(len(results))])
sets = [*results[i][1]._value for i in range(len(results))]
i += 1
pdb.set_trace()
def Instant_Parallel_MST(ss,idx,Scenario_Outcomes,mst):
sortable = [(s,Scenario_Outcomes[s][idx]) for s in ss]
subsets = groupby_func(sortable, key=itemgetter(1))
new_sets.append(subsets)
### Generate Multi-Process Object and Run MST Subset Gen
if len(sets) < mp.cpu_count():
np = len(sets)
else:
np = mp.cpu_count()
### Create Pool
pool = mp.Pool(np)
### Run Pool
results = [pool.apply_async(Subset_MST, args=(ss,Scenario_Outcomes,mst)) for ss in subsets]
pool.close()
pool.join()
NAC_to_add = {}
NAC_to_add = NAC_to_add.union(*[results[i]._value for i in range(len(results))])
return NAC_to_add, subsets
def Gradual_Parallel_MST(ss,idx,Scenario_Outcomes,mst):
subsets = []
subset1 = [s for s in ss if str(scenario_outcomes[s][idx]) in list(cvar[1])]
subset2 = [s for s in ss if str(scenario_outcomes[s][idx]) not in list(cvar[1])]
if subset2 != []:
new_sets.append(subset2)
subsets.append(subset2)
if len(list(cvar[1])) > 1:
sortable = [(s,scenario_outcomes[s][idx]) for s in subset1]
subset3 = groupby_func(sortable, key=itemgetter(1))
if subset3 != []:
new_sets.append(subset3)
subsets.append(subset3)
else:
if subset1 != []:
new_sets.append(subset1)
subsets.append(subset1)
### generate multi-process object and run mst subset gen
if len(sets) < mp.cpu_count():
np = len(sets)
else:
np = mp.cpu_count()
### create pool
pool = mp.pool(np)
### run pool
results = [pool.apply_async(subset_mst, args=(ss,scenario_outcomes,mst)) for ss in subsets]
pool.close()
pool.join()
NAC_to_add = {}
NAC_to_add = NAC_to_add.union(*[results[i]._value for i in range(len(results))])
return NAC_to_add, subsets
def Subset_MST(subset,Scenario_Realizations,mst):
existing_connection = []
#### Get Old Edges
for (s,sp) in mst:
if (s,sp) in set(itertools.permutations(subset,2)):
existing_connection.append((s,sp))
if len(existing_connection) < len(subset) - 1:
### Create Graph for subset1
graph = NAC_Graph({})
for s in subset:
graph.add_vertex(s)
graph.all_edges()
### Find MST
MST_subset = MST(graph, Scenario_Realizations, existing_connection)
added_NACs = MST_subset.mst
else:
added_NACs = {}
return added_NACs
def C_List_validation(C_List,Order_Rules):
Valid = True
truth_table = []
for rules in Order_Rules:
for i in rules[1]:
if str(rules[0]) in C_List and str(i) in C_List and C_List.index(str(rules[0])) > C_List.index(str(i)):
truth_table.append(True)
elif str(rules[0]) not in C_List:
truth_table.append(True)
else:
truth_table.append(False)
if all(truth_table) and truth_table[0] == True:
pass
else:
Valid = False
return Valid
return Valid
def groupby_func(data, key=itemgetter(0)):
### Sort data
data = sorted(data, key=key)
### Generate subsets
subset = [list(group) for k,group in itertools.groupby(data,key)]
### Convert to useable form
subset_return = []
for subs in subset:
subset_return.append([a[0] for a in subs])
return subset_return
|
# Generated by Django 3.2 on 2021-05-24 09:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20210524_0857'),
]
operations = [
migrations.AddField(
model_name='user',
name='passcoord',
field=models.BinaryField(default=b''),
),
migrations.AlterField(
model_name='user',
name='password',
field=models.CharField(max_length=128, verbose_name='password'),
),
]
|
import httplib, urllib
import json
import uuid
P9SERVER = 'localhost:8080'
class APIException(Exception):
pass
import webrtc
config = {
iceServers: [
{ "url": "stun:stun.l.google.com:19302" },
{ "url": "stun:stun.services.mozilla.com" },
]
};
class P9PeerConnection(webrtc.WebRTCPeerConnection):
""" P9-specific peer connection; it streams the local configured file to the remote peer """
def __init__(p9, config = config, remoteId):
self.partnerID = remoteID
self.p9 = p9
return super(P9PeerConnection, self).__init__()
def process_message(self, msgtype, msgdata):
if msgtype == 'candidate':
self.remote_candidates.append(self._ICEAgent.candidate_decode(msgdata))
if msgtype == 'sdp':
# we got an offer
self.receive_offer(msgdata)
while msg
self.p9.client_postmessage('sdp', self.create_answer())
self.start_streaming()
class P9Client():
""" Client for P9-based websites; it provides registration, channel creation, offer/answer exchanges, and
disconnection from a signalling P9 server.
"""
@staticmethod
def _urlencode(data):
if data is None:
return None
fields = []
for i in data.keys():
fields += [ "%s=%s" % (urllib.quote_plus(unicode(i)), urllib.quote_plus(unicode(data[i]))) ]
return "&".join(fields)
assert _urlencode({}) == ""
assert _urlencode({'a':'b'}) == "a=b"
assert _urlencode({'a':'b', 'c':'d'}) == "a=b&c=d"
assert _urlencode({'&':'='}) == "%26=%3D", _urlencode({'&':'='})
def __init__(self):
self._cookies = []
self._peers = {}
def _xhr_call(self, method, url, data = None):
global _cookies
response = None
if data is not None and method not in ["POST", "PUT"]:
raise Exception("Are you trying to send data in a non-POST/PUT request")
try:
connection = httplib.HTTPConnection(P9SERVER)
headers = {'User-Agent': 'p9 client (Python)', 'Content-Type': 'application/x-www-form-urlencoded'}
if len(_cookies):
headers['Cookie'] = "; ".join(_cookies)
connection.request(method, url, _urlencode(data), headers)
response = connection.getresponse()
if response.status != 200:
if response.status >= 300 and response.status < 400:
print vars(response.msg)
raise APIException("Failed HTTP request: %s returned %d (%s)" % (url, response.status, response.read()))
# save any cookies
for h in response.getheaders():
if h[0].lower()=="set-cookie":
_cookies.append(h[1].split(";")[0])
return response.read()
finally:
connection.close()
def connect_setup(self):
return _xhr_call("GET", "/channelcreate")
def client_register(self):
import uuid
my_id = str(uuid.uuid4())
clients = json.loads(_xhr_call("POST", "/api/1.0/client?%s" % (_urlencode({'s' : my_id }) )))
for client in clients:
if client['s'] == my_id:
return my_id
raise Exception("failed: client_register")
def client_unregister(self, client_id):
raise Exception("fixme: client_unregister")
_lastmsgid = 0
def client_getmessages(self, client_id):
global _lastmsgid
return json.loads(_xhr_call("GET", "/api/1.0/message?%s" % (_urlencode({'s': client_id, 'since': _lastmsgid}))))
def client_postmessage(self, client_id, msgtype, msg):
def channel_register(client_id, name):
channels = json.loads(_xhr_call("POST", "/api/1.0/channel?%s" % (_urlencode({'s': client_id})), {'name': name, 'x': 0}))
print "Online channels:", channels
for channel in channels:
print channel
if name == channel['name']:
return channel['channel']
raise Exception("failed: channel_register")
def channel_unregister(channel_id):
channels = json.loads(_xhr_call("POST", "/api/1.0/channel?%s" % (_urlencode({'s': client_id})), {'channel': channel_id, 'x': 1}))
def channel_getrelays(channel_id):
relays = json.loads(_xhr_call("POST", "/api/1.0/channel/%s/relay?%s" % (channel_id, _urlencode({'s': client_id}))))
return relays
_inloop = False
def message_process(self, msg):
global _lastmsgid
if msg['c'] > _lastmsgid:
_lastmsgid = msg['c']
if not msg['s'] in self._peers:
self._peers[msg['s']] = P9PeerConnection(self, msg['s'])
self._peers[msg['s']].process_message(msg['t'], json.loads(msg['d']))
def main(p9):
client_id = p9.client_register()
print "registered client", client_id
name = "Test Channel"
channel_id = p9.channel_register(client_id, name)
global _inloop
_inloop = True
while _inloop:
try:
messagelist = p9.client_getmessages(client_id)
for i in messagelist:
p9.message_process(i)
except KeyboardInterrupt:
_inloop = False
p9.channel_unregister(client_id)
return
if __name__ == "__main__":
p9client = P9Client()
try:
p9client.connect_setup()
except APIException as e:
print "Connected, API error: ", e
except IOError, Exception:
print "Failed to connect to server"
raise
# we can connect, run the main code.
main(p9client)
|
#!/usr/bin/env python
import os,sys
import MySQLdb
import string
import re
from optparse import OptionParser
DBNAME = "postfix"
DBUSER = "aliaser"
# trick to read keyfile from same dir as actual script, even when called via symlink
keyfile = os.path.dirname(os.path.realpath(__file__))+"/postfix_alias.key"
f = open(keyfile, "r")
DBPASSWD = f.readline().rstrip()
f.close()
cache = {}
tree = {}
domcache = {}
rdomcache = {}
def expand_email(e):
return e if "@" in e else e+"@jongedemocraten.nl"
def parse_email(e):
# Split user@example.net to user and example.net
user, domain = re.split("@", expand_email(e), 1)
# Find domain id if example.net is a known domain
if domain in rdomcache:
domid = rdomcache[domain]
return user, domain, domid
else:
return user, domain, None
def get_tree(email, d = 0):
if d > 64: # Max recursion depth exceeded
return {email:["!"]}
global cache
global c
if not cache.has_key(email):
user, domain, domid = parse_email(email)
c.execute("SELECT destination FROM virtual_aliases WHERE sourceuser=%s AND sourcedomain=%s", (user, domid))
#c.execute("""SELECT destination FROM virtual_aliases WHERE sourceuser LIKE %s AND sourcedomain IN (
# SELECT parent FROM domain_clones WHERE child IN (
# SELECT id FROM virtual_domains WHERE name=%s ) )""", (user, domain) )
rows = c.fetchall()
cache[email] = set([r[0] for r in rows])
return (email, [get_tree(m, d+1) for m in cache[email]])
def del_link(user, domid, to_email):
global c
global db
c.execute("DELETE FROM virtual_aliases WHERE sourceuser=%s AND sourcedomain=%s AND destination=%s",
(user, domid, to_email))
affected_rows = db.affected_rows()
db.commit()
return affected_rows
def add_link(user, domid, to_email):
global c
global db
c.execute("INSERT INTO virtual_aliases (sourceuser, sourcedomain, destination) VALUES (%s, %s, %s)",
(user, domid, to_email))
affected_rows = db.affected_rows()
db.commit()
return affected_rows
def print_tree(tree, level=0, indent=" "):
if len(cache) <= 1:
print "Error: Address not found"
else:
print (level*indent)+tree[0]
for a in tree[1]:
print_tree(a, level+1)
def get_open_leaves():
global c
# mailman.jongedemocraten.nl is a virtual alias domain, but is delivered locally
c.execute("SELECT name FROM virtual_domains WHERE name != 'mailman.jongedemocraten.nl'")
rows = c.fetchall()
domains = set()
# Prefix all domains with @ for easy of use in later string.endswith
for r in rows:
domains.add("@%s" % r[0])
# INvsRE:
# When passing an array or comma-joined string as arg to "WHERE foo IN %s",
# MySqlDb adds too many escapes and intended effect is not achieved,
# use regexp as workaround "^(this|that|something|else)$"
expr = ".*(%s)" % "|".join(domains)
# Select all aliases that point to a virtual_alias_domain (i.e. another alias)
c.execute("SELECT destination FROM virtual_aliases WHERE destination REGEXP %s", expr)
rows = c.fetchall()
open_leaves = set()
for r in rows:
tree = get_tree(r[0]) # Get tree from the destination
subtrees = [tree]
leaves = set()
while subtrees:
tree = subtrees.pop()
if tree[1]: # has leaves
subtrees += tree[1]
else:
leaves.add(tree[0])
for l in leaves:
if l.endswith(tuple(domains)):
open_leaves.add(l)
return list(open_leaves)
def alias_copy(rows, fromdomid, todomid):
global c
global db
if len(rows) < 1:
print "Error: No unit aliases found"
return 0
newalias = {}
for r in rows:
# Replace function.unit with function
fromuser = r[0].rsplit(".", 1)[0]
newalias[fromuser] = "%s@%s" % (r[0], domcache[fromdomid])
# Only create new aliases if no existing alias exists yet
users = set(newalias.keys())
# See note: INvsRE
expr = "^(%s)$" % "|".join(users)
# Find existing aliases
c.execute("SELECT sourceuser FROM virtual_aliases WHERE sourceuser REGEXP %s and sourcedomain=%s", (expr, todomid))
rows = c.fetchall()
usrexist = set()
for r in rows:
usrexist.add(r[0])
usrmake = users - usrexist
if len(usrmake) < 1:
print "Info: Nothing to do"
return 0
a = []
for u in usrmake:
a.append( (u, todomid, newalias[u]) )
c.executemany("INSERT INTO virtual_aliases (sourceuser, sourcedomain, destination) VALUES (%s, %s, %s)", a)
# See note: INvsRE
expr = "^(%s)$" % "|".join(usrmake)
c.execute("SELECT sourceuser, sourcedomain, destination FROM virtual_aliases WHERE sourceuser REGEXP %s AND sourcedomain=%s", (expr, todomid))
rows = c.fetchall()
print "Will create following aliases:"
for r in rows:
print "%s@%s => %s" % (r[0], domcache[r[1]], r[2])
if raw_input("Proceed? [y/N] ").startswith(("y","Y","j","J")):
db.commit()
print "Info: Committed"
return 1
else:
db.rollback()
print "Info: Rolled back"
return 0
def alias_convert():
global c
global db
# If domain is an altname for a real domain, don't convert aliases
realdoms = set(domcache.keys()) & set(rdomcache.values())
for d in realdoms:
c.execute("""INSERT INTO virtual_aliases (sourceuser, sourcedomain, destination)
SELECT SUBSTRING_INDEX(source,'@',1), %s, destination FROM virtual_aliases_old WHERE source LIKE %s""", (d, "%@"+domcache[d]))
c.execute("SELECT * FROM virtual_aliases")
rows = c.fetchall()
print "Warning: Convert action designed for one-time use only"
for r in rows:
print "%d %24s@%-24s [%d] %48s" % (r[0], r[1], domcache[r[2]], r[2], r[3])
print "Warning: Convert action designed for one-time use only"
if raw_input("Proceed? [y/N] ").startswith(("y","Y","j","J")):
db.commit()
print "Info: Committed"
return 1
else:
db.rollback()
print "Info: Rolled back"
return 0
def make_units(unit):
global c
global db
# Lookup domid of primairy domain
fromdomid = rdomcache["jongedemocraten.nl"]
# Lookup domid of jdunit.nl
todomain = "jd%s.nl" % unit
if todomain in rdomcache:
todomid = rdomcache[todomain]
else:
print "Error: Domain not recognised, add domain first"
return 0
# Find all rows with format function.unit@jongedemocraten.nl
c.execute("SELECT sourceuser, sourcedomain, destination FROM virtual_aliases WHERE sourceuser LIKE %s AND sourcedomain=%s", ("%."+unit, fromdomid))
rows = c.fetchall()
# Make aliases to function@jdunit.nl
return alias_copy(rows, fromdomid, todomid)
def make_global(user, dest):
global c
global db
# Find already existing addresses
c.execute("SELECT DISTINCT sourcedomain FROM virtual_aliases WHERE sourceuser=%s", (user,))
rows = c.fetchall()
exist = set()
for r in rows:
exist.add(r[0])
# Only create for real domains (not altnames) that don't have the alias yet
make = set(rdomcache.values()) - exist
if len(make) < 1:
print "Info: Nothing to do"
return 0
a = []
for m in make:
a.append( (user, m, dest) )
c.executemany("INSERT INTO virtual_aliases (sourceuser, sourcedomain, destination) VALUES (%s, %s, %s)", a)
c.execute("SELECT sourceuser, sourcedomain, destination FROM virtual_aliases WHERE sourceuser=%s AND sourcedomain IN %s", (user, tuple(make)))
rows = c.fetchall()
print "Will create following aliases:"
for r in rows:
print "%s@%s => %s" % (r[0], domcache[r[1]], r[2])
if raw_input("Proceed? [y/N] ").startswith(("y","Y","j","J")):
db.commit()
print "Info: Committed"
return 1
else:
db.rollback()
print "Info: Rolled back"
return 0
def domain_cache():
global c
global domcache
global rdomcache
canoncache = {}
# Find all domains that are alternative names for another domain
c.execute("SELECT child, parent FROM domain_clones WHERE child!=parent")
for child, parent in c.fetchall():
canoncache[child] = parent
# Find all Postfix virtual_alias_domains
c.execute("SELECT id, name FROM virtual_domains")
for id, name in c.fetchall():
# Create cache of domain id to human-readable name
domcache[id] = name
# Create cache of human-readable name to canonical domain id
# No aliases should exist with a domid of an altname-domain
# If altname-domain, rdomcache value is id of real domain
rdomcache[name] = canoncache[id] if id in canoncache else id
return 1
def print_usage():
print """\
Usage:
postfix_alias
Finds and displays aliases that lead nowhere.
postfix_alias address@jongedemocraten.nl
Displays the alias tree for the specified address.
postfix_alias unit unitname
Creates jdunit.nl aliases, asks for confirmation first.
e.g. postfix_alias unit twente
postfix_alias add source@jongedemocraten.nl destination@jongedemocraten.nl
Adds a new alias.
postfix_alias del source@jongedemocraten.nl destination@jongedemocraten.nl
Removes an existing alias.
postfix_alias global sourceuser destination@jongedemocraten.nl
Creates aliases under each domain pointing sourceuser to destination
Useful for abuse/postmaster addresses"""
return
if __name__ == "__main__":
if not DBPASSWD:
DBPASSWD = raw_input("Password: ")
db = MySQLdb.connect(user=DBUSER, passwd=DBPASSWD, db=DBNAME)
c = db.cursor()
c.execute("START TRANSACTION")
domain_cache()
if len(sys.argv) == 1:
for l in get_open_leaves():
c.execute("SELECT sourceuser, sourcedomain FROM virtual_aliases WHERE destination=%s", (l,))
rows = c.fetchall()
for r in rows:
# output: alias@jdafdeling.nl doodlopend@jongedemocraten.nl
print "%s@%s %s" % (r[0], domcache[r[1]], l)
elif len(sys.argv) == 2:
# sys.argv[0] email
# print full tree
print_tree(get_tree(expand_email(sys.argv[1])))
sys.exit(0)
elif len(sys.argv) == 3:
if sys.argv[1] == "unit":
sys.exit( 0 if make_units(sys.argv[2]) else 1 )
# put under argv=3 to avoid collisions with potential address convert@
elif sys.argv[1] == "convert":
sys.exit( 0 if alias_convert() else 1 )
else:
print_usage()
sys.exit(127)
elif len(sys.argv) == 4:
# sys.argv[0] cmd source_email dest_email
# Add or remove the link between source_email and dest_email
if sys.argv[1] == "add":
user, domain, domid = parse_email(sys.argv[2])
if domid:
add_link(user, domid, expand_email(sys.argv[3]))
print "OK"
sys.exit(0)
else:
print "Error: Domain-part of email-address not recognised, add domain first"
sys.exit(1)
elif sys.argv[1] == "del":
user, domain, domid = parse_email(sys.argv[2])
if domid:
affected_rows = del_link(user, domid, expand_email(sys.argv[3]))
if not affected_rows:
print "Error: Alias does not contain this address"
sys.exit(0)
else:
print "Error: Domain-part of email-address not recognised, add domain first"
sys.exit(1)
elif sys.argv[1] == "global":
sys.exit ( 0 if make_global(sys.argv[2], sys.argv[3]) else 1 )
else:
print_usage()
sys.exit(127)
else:
print_usage()
sys.exit(127)
db.close()
|
import json
json_data = {}
def readjson(file_path):
f = open(file_path)
line = f.readline()
# print(line)
f.close()
array = json.loads(line)
return array
def readlist(index):
return json_data[str(index)]
json_data = readjson("json.txt")
# for i in range(0, nt):
# print(readlist(i))
def convection(n, u, u_old):
u_old = u.copy()
for i in range(1, nx):
u[i] = u_old[i] - u_old[i] * dt / dx * (u_old[i] - u_old[i-1])
line.set_data(x, u)
def my_convection(n,u,u_old):
u = readlist(n)
line.set_data(x, u)
u_old = u
anim = animation.FuncAnimation(fig, my_convection, fargs=(u,u_old), frames=nt)
HTML(anim.to_html5_video()) |
from bs4 import BeautifulSoup
import requests
import re
import requests_cache
def obter_pagina(link,links):
html = " "
try:
if permitido(link,links):
response = requests.get(link)
print("Baixando: %s" %link)
links.append(link)
html = BeautifulSoup(response.text, 'html5lib')
except ConnectionResetError:
print("Erro de conexão")
except:
print("Impossivel baixar")
return html
def obter_links(html):
links = []
try:
for link in html.find_all('a'):
try:
if link["href"].find("http") != -1:
links.append(link.get("href"))
except:
continue
except AttributeError:
print("Pagina não possue links")
return links
def permitido(link,links):
if len(links) == 0 or link not in links:
return True
return False
def busca(chave, link, profundidade, lista_links):
html = obter_pagina(link,lista_links)
links = obter_links(html)
inicio = []
fim = []
try:
for m in re.finditer('(.{1,64})(%s)(.{1,64})' % chave.upper(), html.text.upper()):
inicio.append(m.start())
fim.append(m.end())
except AttributeError as error:
print(error)
finally:
pass
if(len(inicio) > 0):
print("Ocorrenciar encontradas: ")
for i in range(len(inicio)):
print("{0:^20}".format(html.text[inicio[i]:fim[i]]))
if profundidade != 0:
for link in links:
busca(chave,link,profundidade -1, lista_links)
def main():
requests_cache.install_cache('cache_sites')
links = []
try:
busca(input("Digite a palavra a ser buscada: "), input("Digite o site "), int(input("Digite a profundidade da busca: ")), links)
except ValueError:
print("Digite um número válido para profundidade")
print("Quantidade de sites visitados: %s" % len(links))
if __name__ == '__main__':
main() |
print("--------------Replacing a string from the sentence--------------\n")
sentence = input("Enter a sentence:")
final_output = sentence.replace('python', 'pythons')
print(final_output) |
class Stack:
def __init__(self):
self.stack = []
self.len_stack = 0
def push(self, e):
self.stack.append(e)
self.len_stack += 1
def pop(self):
if not self.empty():
self.stack.pop(self.len_stack - 1)
self.len_stack -= 1
def top(self):
if not self.empty():
return self.stack[-1]
return None
def empty(self):
if self.len_stack == 0:
return True
return False
def length(self):
return self.len_stack
p = Stack()
print("Função push sendo utilizada para a inserção.")
p.push(1)
p.push(2)
p.push(3)
print(p.top())
print("\nFunção pop.")
p.pop()
print(p.top())
print("Função top já utilizada acima mostra o topo da pilha.")
print("\nFunção empty.")
print("A pilha está vazia ?", p.empty())
print("\nFunção length.")
print("A quantidade de elementos na pilha é ",p.length())
|
##By replacing the 1st digit of *3, it turns out that six of the nine possible
##values: 13, 23, 43, 53, 73, and 83, are all prime.
##By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit
##number is the first example having seven primes among the ten generated numbers,
##yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993.
##Consequently 56003, being the first member of this family, is the smallest
##prime with this property.
##Find the smallest prime which, by replacing part of the number (not necessarily
##adjacent digits) with the same digit, is part of an eight prime value family.
from Crazy import isprime
from Crazy import MutiR
from Crazy import primes
def maketem():
def m(x, y):
if x == 0 and y == 0:
yield ()
if x > 0:
for i in m(x - 1, y):
yield (True,) + i
if y > 0:
for i in m(x, y - 1):
yield (False,) + i
for i in m(3, 2):
yield i + (False,)
def ft(tem, s):
a = b = 0
j = 0
for i in range(len(tem)):
if tem[i]:
b = b + 10 ** (len(tem) - i - 1)
else:
a = a + s[j] * 10 ** (len(tem) - i - 1)
j = j + 1
return lambda x: b * x + a
def f(s):
## if s[2]==s[3]==0 and s[4]==1:
## print(s)
for tem in maketem():
f = ft(tem, s)
if tem[0]:
mr = 1
else:
mr = 0
if len([i for i in range(mr, 10) if isprime(f(i))]) >= 8:
print(tem, s)
return False
def fi():
return [f(s) for s in MutiR(range(1, 10), range(10), [1, 3, 7, 9])]
fi()
|
# Generated by Django 3.0.7 on 2020-06-30 00:27
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0018_auto_20200629_0314'),
]
operations = [
migrations.RemoveField(
model_name='records',
name='recording',
),
migrations.AlterField(
model_name='records',
name='datetime',
field=models.DateTimeField(default=datetime.datetime(2020, 6, 29, 17, 27, 19, 136518)),
),
]
|
# coding: utf-8
"""
对svn命令的包装
"""
import commands
import traceback
from tyserver.tyutils import tylog
try:
from lxml import etree
except:
tylog.error("import etree error")
def svnCmd(workingpath, cmd, *svnArgs):
tylog.debug('svnCmd <<| workingpath, svnCmd, svnArgs:',
workingpath, cmd, ' '.join(svnArgs))
parts = []
if workingpath:
parts.append('cd %s' % workingpath)
parts.append('LANG=en_US.UTF-8')
parts.append(' '.join(['svn', cmd, '--non-interactive'] + list(svnArgs)))
script = ';'.join(parts)
status, output = commands.getstatusoutput(script)
if status != 0:
tylog.error("svnCmd >>| Failed"
'|path, cmd:', workingpath, cmd,
'|script:', script,
'|status, output:', status, output,
)
else:
tylog.debug('svnCmd >>'
'|path, cmd:', workingpath, cmd,
#'|script:', script,
#'|status, output:', status, output
)
return script, status, output
def status(_file):
_, _, xmldoc = svnCmd('', "status", _file, '--xml')
status = etree.XML(xmldoc).xpath('//wc-status/@item')
if status:
return status[0]
return ""
def export(_file, dst, revision='HEAD'):
return svnCmd('', "export", '-r', revision, _file, dst, '--force')
def log(_file):
_, _, xmldoc = svnCmd('', "log", _file, '-l 5', '--xml')
selector = etree.XML(xmldoc).xpath('//msg|//date|//author')
logs = []
for i in selector:
revision = i.getparent().attrib['revision']
if not logs or logs[-1]['revision'] != revision:
logs.append({'revision': revision})
logs[-1][i.tag] = i.text
return logs
def commit(_file, commitLog):
if '\n' in commitLog: # 处理多行提交日志
commitLog = "$'%s'" % commitLog
_, status, output = svnCmd('', "commit", _file, '-m', commitLog)
return output
def revert(_file):
_, _, output = svnCmd('', 'revert', _file)
return output
def add(_file):
_, _, output = svnCmd('', 'add', _file)
return output
def test():
f = '/Users/windaoo/ty/tytrunk/tywebmgr/src/a.sh'
# revert(f)
# add(f)
# import random
# with open(f, 'w') as fp:
# fp.write(str(random.randint(0, 10000)) + '\n')
# commit(f, '中文日志\n第二行')
# print log(f)
# print log('/Users/windaoo/ty/tytrunk/team/testing/8/red_envelope/0.json')
# print status(f)
# export('/Users/windaoo/ty/tytrunk/team/testing/8/red_envelope/0.json',
# '/Users/windaoo/ty/tytrunk/team/testing/8/red_envelope/0.json.HEAD')
pass
if __name__ == '__main__':
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
test() |
#encoding=utf-8
import codecs
import batcher
import data
from collections import namedtuple
bin_path = "/home/bigdata/active_project/run_tasks/query_rewrite/stable/stable_single/copy_data_format/chunked/train*"
vocab_path = "/home/bigdata/active_project/run_tasks/text_sum/data/vocab/vocab.txt"
data_generater = data.example_generator(bin_path, single_pass=True)
def test_text(path):
f = codecs.open(path, "r", "utf-8")
lines = f.readlines()
print(lines[0])
print(type(lines[0]))
def test_batcher():
HPS = namedtuple("HPS", ["batch_size", "mode"])
hps = HPS(5, "train")
bx = batcher.Batcher(bin_path,vocab_path,hps, single_pass=True)
input_gen = bx.text_generator(data.example_generator(bx._data_path, bx._single_pass))
cnt = 0
while True:
x = input_gen.next()
print(x[0].decode("utf-8"))
print(x[1].decode("utf-8"))
cnt += 1
if cnt > 10:
break
if __name__ == "__main__":
test_batcher() |
import os
import csv
#find the file we want to read
file_path = os.path.join('Resources', 'budget_data.csv')
#declare everything before connecting to file
total_months = 0
past_total = 0
net_profits_loss = 0
greatest_increase = 0
greatest_decrease = 0
#create empty list to store data
total_change = []
date = []
#open file in read mode- gives access
with open (file_path) as csvfile:
info = csv.reader(csvfile, delimiter=',')
#next is a step down/drop to next row-we dont need to header details
first_row = next(info)
#loop through data
for row in info:
#number of rows equals number of months
total_months = total_months + 1
#find change in price
current_total = (int(row[1]))
change = current_total - past_total
total_change.append(change)
past_total = current_total
date.append(row[0])
#calculate net profit/net_profit_loss
net_profits_loss = net_profits_loss + current_total
max_value = max(total_change)
max_value_index = total_change.index(max_value)
greatest_change_month = date[max_value_index]
min_value = min(total_change)
min_value_index = total_change.index(min_value)
smallest_change_month = date[min_value_index]
average_change = round(sum(total_change)/len(total_change),2)
print('Financial Analysis')
print('------------------')
print(f'Total Months: {total_months}')
print(f'Average Change: $ {average_change}')
print(f'Total: $ {net_profits_loss}')
print(f'Greatest Increase in Profits: {greatest_change_month} $ {max_value}')
print(f'Greatest decrease in Profits: {smallest_change_month} $ {min_value}')
output_file = os.path.join('Analysis', 'Output.txt')
with open (output_file,'a') as text_file:
text_file.write('Financial Analysis''\n')
text_file.write('------------------''\n')
text_file.write(f'Total Months: {total_months}''\n')
text_file.write(f'Average Change: $ {average_change}''\n')
text_file.write(f'Total: $ {net_profits_loss}''\n')
text_file.write(f'Greatest Increase in Profits: {greatest_change_month} $ {max_value}''\n')
text_file.write(f'Greatest decrease in Profits: {smallest_change_month} $ {min_value}') |
import math
class Solution(object):
def countBits(self,num):
"""
:param num:
:return: List[int]
"""
if num==0:
return [0]
num_1s=[0]*(num+1)
for i in range(num+1):
binarys = bin(i)[2:]
print binarys
num_1 = 0
for j in range(len(binarys)):
if binarys[j]=='1':
num_1+=1
num_1s[i]=num_1
return num_1s
if __name__=="__main__":
sol = Solution()
print sol.countBits(8) |
from pymongo import MongoClient
import re
import datetime
collection_json = [
{
"col_name" : "ticket_goods",
"count" : 0,
"list": ""
},
{
"col_name" : "ticket_man",
"count" : 0,
"list": ""
}
]
collection_arr = ["ticket_goods", "ticket_man"]
# 방법1 - URI
mongodb_URI = "mongodb://localhost:27017/"
client = MongoClient(mongodb_URI)
db = client.test
collections = db.list_collection_names()
for col_json in collection_json:
for collection in collections:
if str(collection).find(col_json['col_name']) > -1:
print(col_json['col_name'] + ": " + collection)
col_json['count'] = col_json['count'] + 1
if str(collection) != "ticket_goods_inc":
col_json['list'] = col_json['list'] + str(collection) + ","
print(collection_json)
for collection in collection_json:
if collection['count'] > 3:
remove_list = collection['list'].split(",")
for num in range(0, len(remove_list) - 4):
now = datetime.datetime.now()
nowDate = now.strftime('%Y%m%d')
print(nowDate)
print(now - datetime.timedelta(1))
print(now - datetime.timedelta(2))
#db.drop_collection(remove_list[num]) |
"""Abstract base class from some SciUnit unit test cases"""
from sciunit import TestSuite
from sciunit.tests import RangeTest
from sciunit.models.examples import UniformModel
class SuiteBase(object):
"""Abstract base class for testing suites and scores"""
def setUp(self):
self.M = UniformModel
self.T = RangeTest
def prep_models_and_tests(self):
t1 = self.T([2, 3], name='test1')
t2 = self.T([5, 6])
m1 = self.M(2, 3)
m2 = self.M(5, 6)
ts = TestSuite([t1, t2], name="MySuite")
return (ts, t1, t2, m1, m2)
|
# Generated by Django 2.0.3 on 2018-05-31 06:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('SRTP', '0005_auto_20180531_0551'),
]
operations = [
migrations.AlterField(
model_name='srtp',
name='team',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='srtp_team', to='SRTP.team'),
),
]
|
# -*- mode: python -*-
import os
from openal.al_lib import lib
import platform
from ctypes.util import find_library
from ctypes import CDLL, c_void_p, c_int, c_char_p, byref, cast, POINTER, Structure
import PyInstaller.depend.bindepend as bd
block_cipher = None
# Assumes that the libraries under Linux are a system-wide installed ones residing in the system-wide library directory
if platform.system() == "Linux" and platform.architecture()[0] == "64bit":
class LINKMAP(Structure):
_fields_ = [
("l_addr", c_void_p),
("l_name", c_char_p)
]
libdl = CDLL(find_library('dl'))
dlinfo = libdl.dlinfo
dlinfo.argtypes = c_void_p, c_int, c_void_p
dlinfo.restype = c_int
def get_full_path(lib_name):
if lib_name.endswith(".so"):
lib = CDLL(lib_name)
else:
lib = CDLL(find_library(lib_name))
lmptr = c_void_p()
#2 equals RTLD_DI_LINKMAP, pass pointer by reference
dlinfo(lib._handle, 2, byref(lmptr))
return cast(lmptr, POINTER(LINKMAP)).contents.l_name.decode("utf-8")
additional_libs = (get_full_path("openal"), get_full_path("mod_spatialite.so"), get_full_path("vorbisfile"))
elif platform.system() == "Windows":
additional_libs = (lib._name, find_library("mod_spatialite"), find_library("libvorbisfile"), find_library("libvorbis"), find_library("libogg"))
toc = [(os.path.basename(name), name, "BINARY") for name in additional_libs]
toc_with_deps = bd.Dependencies(toc)
print(f"Toc with deps: {toc_with_deps}")
binaries = [(path, ".") for local_name, path, typ in toc_with_deps]
a = Analysis(['run_app.py'],
pathex=['C:\\Users\\lukas\\projekty\\feel the streets', r'c:\python3\lib\site-packages\pygeodesy'],
binaries=binaries,
datas=[("app/sounds", "sounds"), ("locale", "locale"), ("*.yml", ".")],
hiddenimports=["pkg_resources.py2_warn"],
hookspath=["hooks"],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='fts',
debug=False,
strip=False,
upx=True,
console=False )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=False,
name='fts')
|
# -*- coding: utf-8 -*-
import sys
from easykiwi import KiwiClient
# pylint: disable=invalid-name
body = ' '.join(sys.argv[1:]) or '___'
client = KiwiClient()
with client.connect('127.0.0.1') as comm:
# send message with different sender and subject
# listen by two subscriber
sendr = 'bob.jones'
subj = 'purchase.car'
comm.broadcast_send(body, sender=sendr, subject=subj)
# Filtered by filter subscriber because subject not matched with "purchase.*" pattern
# Therefore filterd.
sendr = 'bob.jones'
subj = 'sell.car'
comm.broadcast_send(body, sender=sendr, subject=subj)
|
def isAnagram(s, t):
# s1
# return sorted(t) == sorted(s)
# s2
# if len(s) != len(t):
# return False
# setS = dict()
# setT = dict()
# for i in range(len(s)):
# if (s[i] in setS):
# setS[s[i]] = setS[s[i]] + 1
# else:
# setS[s[i]] = 1
# if (t[i] in setT):
# setT[t[i]] = setT[t[i]] + 1
# else:
# setT[t[i]] = 1
# return setS == setT
# s3
if len(s) != len(t):
return False
listS = [0] * 26
listT = [0] * 26
for i in range(len(s)):
listS[ord(s[i]) - ord('a')] += 1
listT[ord(t[i]) - ord('a')] += 1
return listS == listT
print(isAnagram("anagram", "nagaram")) |
import urllib2
import json
import matplotlib.pyplot as plt
def getUser(username):
"""
function getUser parses json page with user information
returns page content in string format
"""
url = "http://forum.toribash.com/tori_stats.php?username=%26%2312579%3B"+username+"&format=json"
response = urllib2.urlopen(url)
html = response.read()
print username
return html
def getTC(inputFile, outputFile):
"""
function getTC converts string to json string, and finds tc balance for each user
takes txt file with usernames, one in a line
"""
stats_tc = open(outputFile, 'w')
usernamesFile = open(inputFile, 'r')
usernames = usernamesFile.readlines()
for username in usernames:
username = username.replace('\n','')
user_string = getUser(username)
user_json = json.loads(user_string)
stats_tc.write(str(user_json["tc"])+"\n")
getTC('usernamesR2R.txt', 'tc-stats.txt')
#reminder1: configure gathering stats for the plot from getTC outputs
#reminder2: split into 2 different modules
def plotTC():
"""
returns diagram of top 5 players for the first len(user<x>) days
"""
user1 = [5000, 8620, 9100, 12020, 17020, 25020, 33002, 44435, 55001, 68260, 99444, 102322, 101023, 111056, 123456]
user2 = [5000, 1220, 2000, 1100, 7020, 5000, 19002, 18435, 32001, 43260, 80444, 66322, 86123, 96056, 112345]
user3 = [5000, 12220, 19800, 22050, 43020, 42020, 39002, 45435, 3001, 8260, 9944, 56002, 54023, 62017, 73456]
user4 = [5000, 2900, 6700, 2020, 2020, 2020, 3300, 4999, 5501, 6860, 9944, 22322, 28023, 33156, 53456]
user5 = [5000, 6080, 7000, 14020, 15000, 4500, 17200, 14435, 15001, 18260, 19444, 22322, 21023, 31056, 33456]
user6 = [5000, 2343, 7235, 4020, 5000, 1400, 1200, 1445, 1501, 1860, 1944, 2222, 2103, 3156, 29456]
#user6 = [5000, 5000, 4000, 5020, 3000, 4400, 2200, 8445, 11501, 18860, 1944, 22222, 24003, 24003, 24003]
plt.plot(user1)
plt.plot(user2)
plt.plot(user3)
plt.plot(user4)
plt.plot(user5)
#plt.plot(user6)
plt.ylabel('Toricredits')
plt.xlabel('Days')
plt.title('Top 5 Earnings for the first 2 weeks')
plt.text(130, 10, r'$shevaroller$')
plt.axis([0, 14, 0, 150000])
plt.show()
|
# Generated by Django 3.2.5 on 2021-07-12 04:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bank', '0002_transfers'),
]
operations = [
migrations.RenameModel(
old_name='transfers',
new_name='transfer',
),
]
|
from django.contrib import admin
from django.db.models import Count
from drf_api_logger.utils import database_log_enabled
if database_log_enabled():
from drf_api_logger.models import APILogsModel
class APILogsAdmin(admin.ModelAdmin):
def added_on_time(self, obj):
return obj.added_on.strftime("%d %b %Y %H:%M:%S")
added_on_time.admin_order_field = 'added_on'
added_on_time.short_description = 'Added on'
list_per_page = 20
list_display = ('id', 'api', 'method', 'status_code', 'execution_time', 'added_on_time',)
list_filter = ('added_on', 'status_code', 'method',)
search_fields = ('body', 'response', 'headers', 'api',)
readonly_fields = (
'execution_time', 'client_ip_address', 'api',
'headers', 'body', 'method', 'response', 'status_code', 'added_on_time',
)
exclude = ('added_on',)
change_list_template = 'charts_change_list.html'
date_hierarchy = 'added_on'
def changelist_view(self, request, extra_context=None):
response = super(APILogsAdmin, self).changelist_view(request, extra_context)
filtered_query_set = response.context_data["cl"].queryset
analytics_model = filtered_query_set.values('added_on__date').annotate(total=Count('id')).order_by('total')
status_code_count_mode = filtered_query_set.values('id').values('status_code').annotate(
total=Count('id')).order_by('status_code')
status_code_count_keys = list()
status_code_count_values = list()
for item in status_code_count_mode:
status_code_count_keys.append(item.get('status_code'))
status_code_count_values.append(item.get('total'))
extra_context = dict(
analytics=analytics_model,
status_code_count_keys=status_code_count_keys,
status_code_count_values=status_code_count_values
)
response.context_data.update(extra_context)
return response
def has_add_permission(self, request, obj=None):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(APILogsModel, APILogsAdmin)
|
#!/usr/bin/env python
import re
import struct
import subprocess
import sys
def getsyms(fname):
rgx = re.compile("([0-9a-f]+) T idt_entry_0x([0-9a-f][0-9a-f])")
ret = {}
out = subprocess.check_output("$NM %s" % fname, shell=True)
for line in out.split("\n"):
mtch = rgx.match(line)
if mtch:
ret[int(mtch.group(2), 16)] = int(mtch.group(1), 16)
return ret
def genentry(arch, vector, syms):
p_dpl_type = 0x80 | 0 | 0x0e
if arch == "i686":
ist = 0
elif vector == 2: # NMI
# NMI can hit on the first instruction of a syscall handler
# AMD didn't define syscall to set a proper kernel stack
ist = 1
elif vector == 3: #DB
# If a hardware breakpoint is set on a syscall instruction that
# is in a mov-ss interrupt shadow it will hit in the kernel
ist = 2
elif vector == 8: #DF
# #DF is probably just a stack overflow, last ditch effort to recover
ist = 3
elif vector == 18: #MC
# MC can hit on the first instruction of a syscall handler
# AMD didn't define syscall to set a proper kernel stack
ist = 4
else:
ist = 0
kern_cs = 0x08
sym = syms[vector]
return struct.pack("<HHBBHII", sym & 0xffff, kern_cs, ist, p_dpl_type, (sym >> 16) & 0xffff, sym >> 32, 0)
def main():
arch = sys.argv[1]
syms = getsyms(sys.argv[2])
idt = open(sys.argv[3], "w")
for i in range(256):
idt.write(genentry(arch, i, syms))
idt.close()
return 0
if __name__ == "__main__":
sys.exit(main())
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import logging
import os
import time
import mshoot
# Set up logging
logging.basicConfig(filename='mpc_case3.log', filemode='w', level='DEBUG')
# Random seed
np.random.seed(12345)
# Paths
ms_file = os.path.join('examples', 'bs2019', 'measurements.csv')
fmu = os.path.join('examples', 'bs2019', 'case3', 'models', 'r1c1co2pid_dymola_1e-11.fmu')
# Simulation period
t0 = '2018-04-05 00:00:00'
t1 = '2018-04-08 00:00:00'
# Read measurements
ms = pd.read_csv(ms_file)
ms['datetime'] = pd.to_datetime(ms['datetime'])
ms = ms.set_index('datetime')
ms = ms.loc[t0:t1]
# Resample
ms = ms.resample('1h').mean().ffill().bfill()
# Assign model inputs
inp = ms[['solrad', 'Tout', 'occ']]
inp['time'] = (inp.index - inp.index[0]).total_seconds()
inp = inp.set_index('time')
inp.index = inp.index.astype(int)
constr = pd.read_csv('examples/bs2019/case3/results/mpc/h2/constr.csv', index_col=0)
constr.index = constr.index.astype(int)
inp['tstp'] = constr['Tmin']
inp['co2stp'] = constr['CO2max']
print(inp)
# Initial state
airT0 = 20. + 273.15
CO20 = 500.
x0 = [airT0, CO20]
# Parameters and working directory
par_file = os.path.join('examples', 'bs2019', 'case3', 'results', 'est',
'parameters.csv')
wdir = os.path.join('examples', 'bs2019', 'case3', 'results', 'pid')
# Skip the case, if results already there
if not os.path.exists(wdir):
os.makedirs(wdir)
# Read parameters and modify Tve to allow cooling
pm = pd.read_csv(par_file)
parameters = dict()
for p in pm:
parameters[p] = pm.iloc[0][p]
# parameters['Tve'] = 18. # In real building this temperature is higher.
# # Here, we assume that the air passes through the
# # rotary wheel HX (air preheated to around 18 degC),
# # but not through the heating coil.
# Instantiate emulation and control models
model_pid = mshoot.SimFMU(
fmu,
outputs=['T', 'Qr', 'vetot', 'vpos', 'dpos'],
states=['cair.T', 'co2.balance.CO2ppmv_i'],
parameters=parameters,
verbose=False)
# Run
ydf, xdf = model_pid.simulate(inp, x0)
# Save results
ydf.to_csv(os.path.join(wdir, 'ydf.csv'))
xdf.to_csv(os.path.join(wdir, 'xdf.csv'))
|
import os.path
import util.io
import util.preprocessor
# import util.postprocessor
import build as main
def out_name(inp, lang):
n, ext = os.path.splitext(inp)
if main.cfg.preserve_paths:
return os.path.join(main.cfg.out, os.path.relpath(n) + util.fmt_ext(lang.out_extension))
else:
return os.path.join(main.cfg.out, os.path.basename(n) + util.fmt_ext(lang.out_extension))
def build(inp, out=None):
n, ext = os.path.splitext(inp)
if ext not in main.langs:
return
lang = main.langs[ext]
if out is None:
out = out_name(inp, lang)
util.io.mkdir(os.path.dirname(out))
tmp = util.io.tmp()
util.preprocessor.process(lang, inp, tmp)
# tmp2 = util.io.tmp()
lang.build(lang, tmp, out)
# lang.build(lang, tmp, tmp2)
# util.postprocessor.process(lang, tmp2, out)
def pre_build_task(*args):
for file in util.io.walk(os.getcwd()):
build(file)
|
# -----------------------------
# File: Main
# Author: Yiting Xie
# Date: 2018.9.10
# E-mail: 369587353@qq.com
# -----------------------------
import gym
import numpy as np
import argparse
from agent_dqn import Agent,process_observation
'''
ENV_NAME = 'MsPacman-v0' # game name
EPISODES = 15000
ISTRAIN = True # False to test, true to train
'''
def main():
parse = argparse.ArgumentParser(description="Start program")
parse.add_argument("--episode", help="training frequency", type = int, default=15000)
parse.add_argument("--env_name", help="game name", default='MsPacman-v0')
parse.add_argument("--model_type", help="'dqn' is DQN, 'ddqn' is DDoubleQN", default='dqn')
parse.add_argument("--train", help="train or test model, False is test, True is train", default=True)
parse.add_argument("--load_network", help="load model True or False", default=False)
args = parse.parse_args()
EPISODES = args.episode
ENV_NAME = args.env_name
MODEL_TYPE = args.model_type
ISTRAIN = args.train
LOAD_NETWORK = args.load_network
env = gym.make(ENV_NAME)
# train model
if ISTRAIN:
# init agent
agent = Agent(env.action_space.n, ENV_NAME, load_network = LOAD_NETWORK, agent_model = MODEL_TYPE)
for _ in range(EPISODES):
game_status = False
# reset the state of the environment
last_observation = env.reset()
observation, _, _, _ = env.step(0)
state = agent.initial_state(observation, last_observation)
while not game_status:
last_observation = observation
action = agent.get_action(state)
observation, reward, game_status, _ = env.step(action)
#redraw a frame of the environment
env.render()
next_observation = process_observation(observation, last_observation)
state = agent.run_agent(action, reward, game_status, next_observation, state)
#test model
else:
agent = Agent(env.action_space.n, ENV_NAME, load_network = LOAD_NETWORK, agent_model = MODEL_TYPE)
for _ in range(EPISODES):
game_status = False
last_observation = env.reset()
observation, _, _, _ = env.step(0)
state = agent.initial_state(observation, last_observation)
while not game_status:
last_observation = observation
action = agent.get_action_test(state)
observation, _, game_status, _ = env.step(action)
env.render()
next_observation = process_observation(observation, last_observation)
state = np.append(state[: ,:, 1:], next_observation, axis = 2)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-09-18 12:55
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_auto_20170918_1252'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='address',
),
migrations.RemoveField(
model_name='userprofile',
name='address_2',
),
migrations.RemoveField(
model_name='userprofile',
name='city',
),
migrations.RemoveField(
model_name='userprofile',
name='state',
),
migrations.RemoveField(
model_name='userprofile',
name='zip',
),
]
|
from processCamFrame import processCamFrame
import numpy as np
def getPaperCoor(cap, paperScrnMat):
# read video frame
_, frame = cap.read()
# get the current white blob centroid
cX, cY = processCamFrame(frame)
if cX == 0 and cY == 0:
return (0,0)
else:
# find the nearest point that can be mapped to
dist_mat = ((cX - paperScrnMat[:,:,0])**2 + (cY - paperScrnMat[:,:,1])**2)**(1/2)
min_idx = np.where(dist_mat==dist_mat.min())
min_idx_x = min_idx[0][0]
min_idx_y = min_idx[1][0]
# from the paperScrnMat 3rd and 4th dimension, find the actual location of pen on paper
X = paperScrnMat[min_idx_x,min_idx_y,2]
Y = paperScrnMat[min_idx_x,min_idx_y,3]
return (X, Y)
|
import streamlit as st
from PIL import Image
import pickle
import numpy as np
pickle_in = open("forest_model1.pkl", "rb")
model = pickle.load(pickle_in)
def main():
img=Image.open('Billboard_Hot_100.jpg')
img=img.resize((267,176))
st.image(img, use_column_width=False)
st.title("BillBoard Hit Predictor")
st.text("Team B")
songname = st.text_input("song name")
instrumentalness = st.number_input("instrumentalness")
acousticness= st.number_input("acousticness")
duration_s = st.number_input("duration_s")
energy = st.number_input("energy")
loudness = st.number_input("loudness")
liveness = st.number_input("liveness")
valence = st.number_input("valence")
danceability = st.number_input("danceability")
Key = st.number_input("Key")
speechiness = st.number_input("speechiness")
tempo = st.number_input("tempo")
mode = st.number_input("mode")
if st.button("Submit"):
duration_ms = duration_s * 1000
duration_ms = np.log(duration_ms)
if mode == 0:
Key_mode_ratio = 0
else:
Key_mode_ratio = float(Key / mode)
prediction = model.predict([[danceability, energy, loudness, speechiness, acousticness, instrumentalness, liveness,valence, tempo,Key_mode_ratio,duration_ms]])
lc = [str(i) for i in prediction]
ans = int("".join(lc))
if ans == 0:
st.error("The song "+songname+" will not be a Billboard Hit")
else:
st.success("The song "+songname+" will be a Billboard Hit")
if __name__=='__main__':
main()
|
import numpy as np
def get_likelihood_singledataset(x,y,err_y,m,q):
L1 = 1
for err_y_i in err_y:
L1 = L1 * (1/(2*np.pi*err_y_i**2))**0.5
lnL1 = np.log(L1)
L2 = 0
for x_i,y_i,err_y_i in zip(x,y,err_y):
model_i = m*x_i + q
L2 = L2 + 0.5 * ((y_i - model_i)**2/err_y_i**2)
lnL = lnL1 - L2
return lnL
def get_likelihood_doubledataset(x1,y1,err_y1,m1,q1,x2,y2,err_y2,m2,q2):
L1 = 1
for err_y1_i in err_y1:
L1 = L1 * (1/(2*np.pi*err_y1_i**2))**0.5
for err_y2_i in err_y2:
L1 = L1 * (1/(2*np.pi*err_y2_i**2))**0.5
lnL1 = np.log(L1)
L2 = 0
for x1_i,y1_i,err_y1_i in zip(x1,y1,err_y1):
model1_i = m1*x1_i + q1
L2 = L2 + 0.5 * ((y1_i - model1_i)**2/err_y1_i**2)
for x2_i,y2_i,err_y2_i in zip(x2,y2,err_y2):
model2_i = m2*x2_i + q2
L2 = L2 + 0.5 * ((y2_i - model2_i)**2/err_y2_i**2)
lnL = lnL1 - L2
return lnL
def get_AICc_singledataset(x,y,err_y,m,q,k):
# m = slope of fit
# q = intercept of fit
# k = number of parameters in the model
lnL = get_likelihood_singledataset(x,y,err_y,m,q)
AIC = 2*k - 2*lnL
AICc = AIC + (2*k*(k+1))/(len(x)-k-1)
return AICc
def get_AICc_doubledataset(x1,y1,err_y1,m1,q1,x2,y2,err_y2,m2,q2,k):
# m = slope of fit
# q = intercept of fit
# k = number of parameters in the model
lnL = get_likelihood_doubledataset(x1,y1,err_y1,m1,q1,x2,y2,err_y2,m2,q2)
AIC = 2*k - 2*lnL
AICc = AIC + (2*k*(k+1))/(len(x1)+len(x2)-k-1)
return AICc
|
fileName = r'D:\Python\05Example\log02.txt'
str = 'Name:Lee Jack(李吉凯) \nPhoneNumber(手机号码):13600173445\n' #str类型
mem = str.encode('gbk').decode('iso-8859-1') #byte类型
with open(fileName,'w', encoding='iso-8859-1') as f:
f.write(mem)
print('写入成功!')
|
from Preprocessing import *
import matplotlib.pyplot as plt
dir = 'C:/Users/user/switchdrive/Wristband Comparison/Signals/'
######## E4 ###########################################################
# Read the raw file and create a file in the directory related to te session (e.g session 1 , 2 ,..) only with Time and EDA
for i in range(1,10):
file_e4 = dir + 'E4/' + str(i) + '/EDA.csv'
eda = signal_extraction(file_e4,'empatica','EDA')
eda_db = time_extraction(eda,'EDA')
eda_db.to_csv(dir + 'E4/' +str(i) + '/EDA_Time.csv',index = 0)
time = eda_db['Time'].values
plt.figure()
plt.ylabel('EDA')
plt.title('E4' + ' ' + 'Session' + ' ' + str(i))
plt.plot(eda_db['EDA'])
plt.savefig(dir + 'E4/' + str(i) + '/EDA.png')
print ("Folder %s beg %s end %s " % (i, time[0],time[len(time)-1]))
#Create a file with beginning and end of each sesssion
e4_timestamp_beg = pandas.to_datetime(['2017-08-28 16:25:45.00', '2017-08-28 23:08:39.00','2017-08-29 06:50:09.00', '2017-08-29 22:11:09.00',
'2017-08-30 06:41:19.00','2017-08-30 22:42:23.00','2017-08-31 22:56:39.00','2017-09-01 06:47:31.00',
'2017-09-02 09:24:37.00']).values
e4_timestamp_end = pandas.to_datetime(['2017-08-28 20:59:55.00', '2017-08-29 06:14:20.50','2017-08-29 19:02:10.00','2017-08-30 06:13:19.00',
'2017-08-30 19:40:50.00','2017-08-31 21:19:46.50','2017-09-01 06:14:16.00','2017-09-01 19:42:38.00',
'2017-09-02 21:56:09.50']).values
df = pandas.DataFrame({'Beginning':e4_timestamp_beg,'End':e4_timestamp_end})
df.to_csv(dir + 'E4/Time_sessions.csv',index=0)
################### Biovotion ##################################################################################
#Open the file with all the session and create n (n = number of sessions) file with EDA and Time in each folder
file_biovision = dir + 'Biovotion/raw.csv'
eda = signal_extraction(file_biovision,'biovotion','EDA')
eda.to_csv(dir + 'Biovotion/EDA_Time.csv',index = 0)
plt.plot(eda['EDA'])
# Timestamp of the sessions - Beginning
bio_timestamp_beg = pandas.to_datetime(['2017-08-28 15:57:23 ', '2017-08-28 22:52:19', '2017-08-29 06:47:37',
'2017-08-29 22:08:09', '2017-08-30 06:41:13', '2017-08-30 22:39:47', '2017-08-31 22:55:35', '2017-09-01 06:46:27',
'2017-09-02 09:23:27']).values
# Timestamp of the sessions - End
bio_timestamp_end = pandas.to_datetime(['2017-08-28 21:04:01' ,'2017-08-29 06:13:55', '2017-08-29 19:02:34' ,'2017-08-30 06:13:35',
'2017-08-30 19:40:20', '2017-08-31 21:04:25','2017-09-01 06:13:58', '2017-09-01 19:42:23', '2017-09-02 20:59:45']).values
# File with the session
df = pandas.DataFrame({'Beginning':bio_timestamp_beg,'End':bio_timestamp_end})
df.to_csv(dir + 'Biovotion/Time_sessions.csv',index=0)
# Divide the raw file in sessions according to the timestamp
for i in range(1, len(bio_timestamp_end)+1):
eda_part = part_div(eda['EDA'],eda['Time'],bio_timestamp_beg[i-1],bio_timestamp_end[i-1])
time_part = part_div(eda['Time'],eda['Time'],bio_timestamp_beg[i-1],bio_timestamp_end[i-1])
db = pandas.DataFrame({'EDA':eda_part,'Time':time_part})
db.to_csv(dir + 'Biovotion/' +str(i) + '/EDA_Time.csv',index = 0)
plt.figure()
plt.title('Biovotion' + ' ' + 'Session' + ' ' + str(i))
plt.ylabel('EDA')
plt.plot(eda_part)
plt.savefig(dir + 'Biovotion/' +str(i) + '/EDA.png')
print i
############### Comparison ##############################################################################################
shift = (e4_timestamp_beg - bio_timestamp_beg)/np.timedelta64(1,'s')
print ("The time difference for the beginning of each session is %s " % (shift))
shift_end = (e4_timestamp_end - bio_timestamp_end)/np.timedelta64(1,'s')
print ("The time difference for the end of each session is %s " % (shift_end))
|
'''思路是,每次添加一个岛屿的时候,我们就更新union find里的parent的记录,并且假设多了一个额外的岛屿count++
然后只有当这个岛屿相邻的四个方向上存在岛屿,才会trigger union的操作,将这些岛屿连在一起,count--
[0, 0]
'''
class UF():
def __init__(self, m, n):
self.parent = [-1] * (m * n)
self.size = [0] * (m * n)
self.count = 0
self.mRows = m
self.nCols = n
def findRoot(self, nodeA):
root = nodeA
while (root != self.parent[root]):
self.parent[root] = self.parent[self.parent[root]]
root = self.parent[root]
return root
def updateParent(self, newAdded):
'''only when this newly added islands coordinate is truly added first time, shall we update'''
x = newAdded[0]
y = newAdded[1]
if (self.parent[x*self.nCols + y] < 0):
self.parent[x * self.nCols + y] = x * self.nCols + y
self.size[x * self.nCols + y] = 1
self.count += 1
def union(self, nodeA, nodeB):
parentA = self.findRoot(nodeA)
parentB = self.findRoot(nodeB)
if (parentA != parentB):
if (self.size[parentA] >= self.size[parentB]):
self.parent[parentB] = parentA
self.size[parentA] += self.size[parentB]
else:
self.parent[parentA] = parentB
self.size[parentB] += self.size[parentA]
self.count -= 1
class Solution(object):
def numIslands2(self, m, n, positions):
"""
:type m: int
:type n: int
:type positions: List[List[int]]
:rtype: List[int]
"""
grid = [[0 for i in range(n)] for j in range(m)]
unionFind = UF(m,n)
directions = [[1,0],[-1,0],[0,1],[0,-1]]
ans = []
for whereAdded in positions:
unionFind.updateParent(whereAdded)
x = whereAdded[0]
y = whereAdded[1]
grid[x][y] = 1
nodeA = x * n + y
for dirs in directions:
newX = dirs[0] + x
newY = dirs[1] + y
if (newX >= 0 and newX < m and newY >= 0 and newY < n and grid[newX][newY] == 1):
nodeB = newX * n + newY
unionFind.union(nodeA, nodeB)
ans.append(unionFind.count)
return ans
|
"""
The ledger_closed method returns the unique
identifiers of the most recently closed ledger.
(This ledger is not necessarily validated and
immutable yet.)
"""
from dataclasses import dataclass, field
from xrpl.models.requests.request import Request, RequestMethod
from xrpl.models.required import REQUIRED
from xrpl.models.utils import require_kwargs_on_init
@require_kwargs_on_init
@dataclass(frozen=True)
class LedgerClosed(Request):
"""
The ledger_closed method returns the unique
identifiers of the most recently closed ledger.
(This ledger is not necessarily validated and
immutable yet.)
"""
method: RequestMethod = field(default=RequestMethod.LEDGER_CLOSED, init=False)
ledger_hash: str = REQUIRED # type: ignore
"""
This field is required.
:meta hide-value:
"""
ledger_index: int = REQUIRED # type: ignore
"""
This field is required.
:meta hide-value:
"""
|
# Generated by Django 3.1.3 on 2020-12-10 07:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('notesapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='notes',
old_name='createdtime',
new_name='created_at',
),
migrations.RenameField(
model_name='notes',
old_name='modifiedtime',
new_name='modified_at',
),
]
|
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for bernoulli_thomlson_sampling_policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.bandits.policies import bernoulli_thompson_sampling_policy as bern_thompson_sampling_policy
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.utils import test_utils
from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import # TF internal
def _prepare_alphas(action_spec, dtype=tf.float32):
num_actions = action_spec.maximum - action_spec.minimum + 1
alphas = [
tf.compat.v2.Variable(tf.ones([], dtype=dtype), name='alpha_{}'.format(k))
for k in range(num_actions)
]
return alphas
def _prepare_betas(action_spec, dtype=tf.float32):
num_actions = action_spec.maximum - action_spec.minimum + 1
betas = [
tf.compat.v2.Variable(tf.ones([], dtype=dtype), name='beta_{}'.format(k))
for k in range(num_actions)
]
return betas
@test_util.run_all_in_graph_and_eager_modes
class BernoulliThompsonSamplingPolicyTest(
parameterized.TestCase, test_utils.TestCase
):
def setUp(self):
super(BernoulliThompsonSamplingPolicyTest, self).setUp()
self._obs_spec = tensor_spec.TensorSpec([], tf.float32)
self._time_step_spec = ts.time_step_spec(self._obs_spec)
self._action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2)
def testBuild(self):
policy = bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec,
self._action_spec,
alpha=_prepare_alphas(self._action_spec),
beta=_prepare_betas(self._action_spec),
)
self.assertEqual(policy.time_step_spec, self._time_step_spec)
self.assertEqual(policy.action_spec, self._action_spec)
def testMultipleActionsRaiseError(self):
action_spec = [tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2)] * 2
with self.assertRaisesRegex(
NotImplementedError,
'action_spec can only contain a single BoundedTensorSpec',
):
bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec,
action_spec,
alpha=_prepare_alphas(self._action_spec),
beta=_prepare_betas(self._action_spec),
)
def testWrongActionsRaiseError(self):
action_spec = tensor_spec.BoundedTensorSpec((5, 6, 7), tf.float32, 0, 2)
with self.assertRaisesRegex(
NotImplementedError,
'action_spec must be a BoundedTensorSpec of integer type.*',
):
bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec,
action_spec,
alpha=_prepare_alphas(self._action_spec),
beta=_prepare_betas(self._action_spec),
)
def testWrongAlphaParamsSize(self):
tf.compat.v1.set_random_seed(1)
action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 10, 20)
alphas = [
tf.compat.v2.Variable(
tf.zeros([], dtype=tf.float32), name='alpha_{}'.format(k)
)
for k in range(5)
]
betas = [
tf.compat.v2.Variable(
tf.zeros([], dtype=tf.float32), name='beta_{}'.format(k)
)
for k in range(5)
]
with self.assertRaisesRegex(
ValueError,
r'The size of alpha parameters is expected to be equal to the number'
r' of actions, but found to be 5',
):
bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec, action_spec, alpha=alphas, beta=betas
)
def testWrongBetaParamsSize(self):
tf.compat.v1.set_random_seed(1)
action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 10, 20)
alphas = [
tf.compat.v2.Variable(
tf.zeros([], dtype=tf.float32), name='alpha_{}'.format(k)
)
for k in range(11)
]
betas = [
tf.compat.v2.Variable(
tf.zeros([], dtype=tf.float32), name='beta_{}'.format(k)
)
for k in range(5)
]
with self.assertRaisesRegex(
ValueError,
r'The size of alpha parameters is expected to be equal to the size of'
r' beta parameters',
):
bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec, action_spec, alpha=alphas, beta=betas
)
def testAction(self):
tf.compat.v1.set_random_seed(1)
policy = bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec,
self._action_spec,
alpha=_prepare_alphas(self._action_spec),
beta=_prepare_betas(self._action_spec),
)
time_step = ts.TimeStep(ts.StepType.FIRST, 0.0, 0.0, observation=1.0)
action_step = policy.action(time_step, seed=1)
self.assertEqual(action_step.action.shape.as_list(), [1])
self.assertEqual(action_step.action.dtype, tf.int32)
def testActionBatchSizeHigherThanOne(self):
tf.compat.v1.set_random_seed(1)
policy = bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec,
self._action_spec,
alpha=_prepare_alphas(self._action_spec),
beta=_prepare_betas(self._action_spec),
)
observations = tf.constant([[1], [1]], dtype=tf.float32)
time_step = ts.restart(observations, batch_size=2)
action_step = policy.action(time_step, seed=1)
self.assertEqual(action_step.action.shape.as_list(), [2])
self.assertEqual(action_step.action.dtype, tf.int32)
def testMaskedAction(self):
tf.compat.v1.set_random_seed(1)
action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2)
observation_spec = (
tensor_spec.TensorSpec([], tf.float32),
tensor_spec.TensorSpec([3], tf.int32),
)
time_step_spec = ts.time_step_spec(observation_spec)
def split_fn(obs):
return obs[0], obs[1]
policy = bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
time_step_spec,
action_spec,
alpha=_prepare_alphas(self._action_spec),
beta=_prepare_betas(self._action_spec),
observation_and_action_constraint_splitter=split_fn,
)
observations = (
tf.constant([[1], [1]], dtype=tf.float32),
tf.constant([[0, 0, 1], [1, 0, 0]], dtype=tf.int32),
)
time_step = ts.restart(observations, batch_size=2)
action_step = policy.action(time_step, seed=1)
self.assertEqual(action_step.action.shape.as_list(), [2])
self.assertEqual(action_step.action.dtype, tf.int32)
# Initialize all variables
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertAllEqual(self.evaluate(action_step.action), [2, 0])
@parameterized.named_parameters(
[('_tf.float32', tf.float32), ('_tf.float64', tf.float64)]
)
def testPredictedRewards(self, dtype):
tf.compat.v1.set_random_seed(1)
policy = bern_thompson_sampling_policy.BernoulliThompsonSamplingPolicy(
self._time_step_spec,
self._action_spec,
alpha=_prepare_alphas(self._action_spec, dtype=dtype),
beta=_prepare_betas(self._action_spec, dtype=dtype),
emit_policy_info=(
'predicted_rewards_mean',
'predicted_rewards_sampled',
),
)
time_step = ts.TimeStep(ts.StepType.FIRST, 0.0, 0.0, observation=1.0)
action_step = policy.action(time_step, seed=1)
self.assertEqual(action_step.action.shape.as_list(), [1])
self.assertEqual(action_step.action.dtype, tf.int32)
# Initialize all variables
self.evaluate(tf.compat.v1.global_variables_initializer())
predicted_rewards_expected_array = np.array([[0.5, 0.5, 0.5]])
p_info = self.evaluate(action_step.info)
self.assertAllClose(
p_info.predicted_rewards_mean, predicted_rewards_expected_array
)
self.assertEqual(list(p_info.predicted_rewards_sampled.shape), [1, 3])
if __name__ == '__main__':
tf.test.main()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 22:12:07 2020
@author: ingrida grigonyte
"""
def get_message(msg):
msgs = {
'msg_1': 'Érvénytelen bemenet!',
'msg_2': 'Kérem, írjon be egy számot!',
'msg_3': 'Kérjük, csak arab vagy római számot írjon be!',
'msg_4': 'Túl nagy a szám az arab-római szám konvertálásához!',
'msg_5': 'A rómaiaknak nulla nem volt! Nem csoda, hogy összeomlottak.',
'msg_6': 'A római számok érvénytelen kombinációja.',
'msg_7': 'A római szám: ',
'msg_8': 'Az arab szám: ',
'msg_10': 'Írjon be egy számot: ',
}
result = None
for i in msgs:
if i == msg:
result = msgs.get(msg)
return result
|
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),'..')))
from src import utils
class WeatherAlertTrigger:
def __init__(self,
json_dict=None,
event_id=None,
severities=None,
zones=None,
location=None):
self.event_id = event_id
if json_dict:
self.severities = json_dict['severities']
self.zones = json_dict['zones']
self.location = json_dict['location']
else:
self.severities = severities
self.zones = zones
self.location = location
# Hard coded query values
self.status = "actual"
self.message_type = "alert"
|
import numpy as np
from agent import BaseAgent
from abc import ABCMeta, abstractmethod
class ReplayBuffer:
def __init__(self, size, minibatch_size, seed):
"""
Args:
size (integer): The size of the replay buffer.
minibatch_size (integer): The sample size.
seed (integer): The seed for the random number generator.
"""
self.buffer = []
self.minibatch_size = minibatch_size
self.rand_generator = np.random.RandomState(seed)
self.max_size = size
def append(self, state, action, reward, terminal, next_state, timestep):
"""
Args:
state (Numpy array): The state.
action (integer): The action.
reward (float): The reward.
terminal (integer): 1 if the next state is a terminal state and 0 otherwise.
next_state (Numpy array): The next state.
"""
if len(self.buffer) == self.max_size:
del self.buffer[0]
self.buffer.append([state, action, reward, terminal, next_state, timestep])
def sample(self):
"""
Returns:
A list of transition tuples including state, action, reward, terinal, and next_state
"""
idxs = self.rand_generator.choice(np.arange(len(self.buffer)), size=self.minibatch_size)
return [self.buffer[idx] for idx in idxs]
def size(self):
return len(self.buffer)
class ReplayBufferAgent(BaseAgent):
__metaclass__ = ABCMeta
def init_replay_buffer(self, replay_buffer_size, minibatch_sz, seed, num_replay_updates_per_step):
# initialize replay buffer
self.replay_buffer = ReplayBuffer(
replay_buffer_size,
minibatch_sz,
seed
)
self.num_replay = num_replay_updates_per_step
@abstractmethod
def _agent_init(self, agent_config):
pass
# Work Required: No.
def agent_init(self, agent_config={}):
"""Setup variables to track state
"""
self.last_state = None
self.last_action = None
self.sum_rewards = 0
self.episode_steps = 0
self.train = True # whether or not to perform optimization
self._agent_init(agent_config)
self.init_replay_buffer(
agent_config['replay_buffer_size'],
agent_config['minibatch_sz'],
agent_config['seed'],
agent_config['num_replay_updates_per_step']
)
# Work Required: No.
def agent_start(self, state):
"""The first method called when the experiment starts, called after
the environment starts.
Args:
state (Numpy array): the state from the
environment's evn_start function.
Returns:
The first action the agent takes.
"""
self.sum_rewards = 0
self.episode_steps = 0
self.last_state = np.array([state])
self.last_action = self.policy(self.last_state)
return self.last_action
@abstractmethod
def policy(self, state):
"""
run this with provided state to get action
"""
pass
@abstractmethod
def agent_optimize(self, experiences):
"""
run this with provided experiences to run one step of optimization
"""
pass
@abstractmethod
def agent_pre_replay(self):
"""
run this to set things up before the replay buffer runs
"""
pass
@abstractmethod
def agent_post_replay(self):
"""
run this to cleanup after replay buffer runs finishes
"""
pass
# weights update using optimize_network, and updating last_state and last_action (~5 lines).
def agent_step(self, reward, state):
"""A step taken by the agent.
Args:
reward (float): the reward received for taking the last action taken
state (Numpy array): the state from the
environment's step based, where the agent ended up after the
last step
Returns:
The action the agent is taking.
"""
self.sum_rewards += reward
self.episode_steps += 1
# Make state an array of shape (1, state_dim) to add a batch dimension and
# to later match the get_action_values() and get_TD_update() functions
state = np.array([state])
# Select action
action = self.policy(state)
# Append new experience to replay buffer
self.replay_buffer.append(self.last_state, self.last_action, reward, False, state, self.episode_steps)
if self.train:
# Perform replay steps:
if self.replay_buffer.size() > self.replay_buffer.minibatch_size:
self.agent_pre_replay()
for _ in range(self.num_replay):
# Get sample experiences from the replay buffer
experiences = self.replay_buffer.sample()
self.agent_optimize(experiences)
self.agent_post_replay()
# Update the last state and last action.
self.last_state = state
self.last_action = action
# your code here
return action
# Work Required: Yes. Fill in the replay-buffer update and
# update of the weights using optimize_network (~2 lines).
def agent_end(self, reward):
"""Run when the agent terminates.
Args:
reward (float): the reward the agent received for entering the
terminal state.
"""
self.sum_rewards += reward
self.episode_steps += 1
# Set terminal state to an array of zeros
state = np.zeros_like(self.last_state)
# Append new experience to replay buffer
self.replay_buffer.append(self.last_state, self.last_action, reward, True, state, self.episode_steps)
if self.train:
# Perform replay steps:
if self.replay_buffer.size() > self.replay_buffer.minibatch_size:
self.agent_pre_replay()
for _ in range(self.num_replay):
# Get sample experiences from the replay buffer
experiences = self.replay_buffer.sample()
self.agent_optimize(experiences)
self.agent_post_replay() |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 23:12:08 2018
@author: Ramesh
"""
import pandas as pd
import numpy as np
#Import cds data file
data1 = pd.io.stata.read_stata('/Users/ramesh/Desktop/cds_spread5y_2001_2016.dta')
# convert cds data to csv file
data = data1.to_csv('/Users/ramesh/Desktop/cds_spread5y_2001_2016.csv')
# Import crsp data file
data2 = pd.read_csv("/Users/ramesh/Desktop/CRSP.csv")
# Match the column names in CDS data
df1 = data2.columns = data2.columns.str.replace('GVKEY', 'gvkey')
df1
df2 = data2.columns = data2.columns.str.replace('datadate', 'mdate')
df2
df3 = data2
df3
######################## PART 1 - CDS file
# Merge the files with gvkey
# This step is done to just to lookup the merged data file on only gvkey
data1['gvkey'] = data1['gvkey'].astype(float)
merged = data1.merge(df3, on='gvkey')
merged.to_csv("merged.csv", index=False)
data3 = pd.read_csv("/Users/ramesh/Desktop/merged_data.csv")
#Splitting the year, month, day from the date column from CDS file
data1['Date'] = pd.to_datetime(data1['mdate'])
data1['Year'],data1['Month'],data1['Day'] = data1.Date.dt.year, data1.Date.dt.month, data1.Date.dt.day
data1
#Assign quarters based on no.of months
data1['Q'] = "4"
data1['Q'] [data1['month'] > 9] = "4"
data1['Q'][(data1['month'] > 6) & (data1['month'] < 9)] = "3"
data1['Q'][(data1['month'] > 3) & (data1['month'] < 6)] = "2"
data1['Q'][data1['month'] < 3] = "1"
# To convert gvkey, Quarter and Year column to float
data1['gvkey'] = data1['gvkey'].astype(float)
data1['Q'] = data1['Q'].astype(float)
data1['Year'] = data1['Year'].astype(float)
# This step is done to enable merging with the CRSP file
###################### PART 2 - CRSP file
#Splitting the year, month, day from the date column from CRSP file
data2['Date'] = pd.to_datetime(data1['mdate'])
data2['Year'],data2['Month'],data2['Day'] = data2.Date.dt.year, data2.Date.dt.month, data2.Date.dt.day
data2
#Assign quarters based on no.of months
data2['Q'] = "4"
data2['Q'] [data2['Month'] > 9] = "4"
data2['Q'][(data2['Month'] > 6) & (data2['Month'] < 9)] = "3"
data2['Q'][(data2['Month'] > 3) & (data2['Month'] < 6)] = "2"
data2['Q'][data2['Month'] < 3] = "1"
# To convert gvkey, Quarter and Year column to float
data2['gvkey'] = data2['gvkey'].astype(float)
data2['Q'] = data2['Q'].astype(float)
data2['Year'] = data2['Year'].astype(float)
# This step is done to enable merging with the CRSP file
# To merge the columns selected from both the data files (CDS & CRSP)
merge_data = pd.merge(data1, data2, on = ['gvkey', 'Q', 'Year'])
merge_data
merge_data.to_csv("merged_output.csv", index=False)
###############################################################################
#####ASSIGNMENT - 6
import xgboost
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mse as mse
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mse as mse
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense
import numpy
# To impute missing values with median
merge_data = merge_data.fillna(merge_data.median())
# To keep only numerical variables
merge_data = merge_data.select_dtypes(include = ['number'])
# To remove missing variables
merge_data = merge_data.dropna(axis = 1, how = 'any')
merge_data
# 1. Split the sample to test and train (80% train)
X= merge_data.drop('spread5y', axis=1)
Y= merge_data ['spread5y']
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
X_train
# 2. Reduce the number of variables to something about 40. Choose any reduction technique that you would like.
# Removing features from train and test dataset
X_test = X_test.drop('Month_x', axis = 1)
X_test = X_test.drop('Month_y', axis = 1)
X_test = X_test.drop('Quarter', axis = 1)
X_test = X_test.drop('Year', axis = 1)
X_test = X_test.drop('gvkey', axis = 1)
X_train= X_train.drop('Month_x', axis = 1)
X_train= X_train.drop('Month_y', axis = 1)
X_train= X_train.drop('Quarter', axis = 1)
X_train= X_train.drop('Year', axis = 1)
X_train= X_train.drop('gvkey', axis = 1)
# 3. Standardize the variables.
scaler = StandardScaler()
scaler.fit(X_train)
StandardScaler(copy = True, with_mean = True, with_std = True)
X_train_1 = X_train
X_test_1 = X_test
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# 4. Run a Neural Network with Grid search. In your grid search try 3 different values for 3 parameters of your network (your choice).
# First Model
RF = RandomForestRegressor(n_estimators=10)
# Model is fit to training and scored to testindg data
RF.fit(X_train, Y_train)
RF.score(X_test, Y_test)
R_F = RF.predict(X_test)
# To select top 40 feature importance
FI = RF.feature_importances_
FI = pd.DataFrame(RF.feature_importances_, index = X_train.columns,
columns = ['importance']).sort_values('importance',
ascending = False)
FI_40 = FI.iloc[:40, :]
FI_40 = FI_40.index.tolist()
def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
mean_squared_error(Y_test,R_F)
mean_absolute_percentage_error(Y_test, R_F)
Filter_X_train=X_train_1[FI_40]
Filter_X_test=X_test_1[FI_40]
# Fit to the training data and filter
scaler.fit(Filter_X_train)
StandardScaler(copy=True, with_mean=True, with_std=True)
Filtered_X_train = scaler.transform(Filter_X_train)
Filtered_X_test = scaler.transform(Filter_X_test)
numpy.random.seed(7)
# To create MLP model
model1 = Sequential()
model1.add(Dense(32, input_dim=50, activation='relu'))
model1.add(Dense(8, activation='relu'))
model1.add(Dense(1, activation='linear'))
# To compile the model
model1.compile(loss = 'mse', optimizer = 'adam', metrics = ['accuracy'])
# To fit the model
model1.fit(Filter_X_train, Y_train, epochs = 100, batch_size = 10)
# Neural Network for Model 1
NN_1 = model1.predict(Filter_X_test)
mape_NN1 = mape(Y_test, NN_1)
mape_NN1
# Neural Network for Model 2
model2 = Sequential()
model2.add(Dense(32, input_dim = 50, activation = 'sigmoid'))
model2.add(Dense(8, activation = 'sigmoid'))
model2.add(Dense(1, activation = 'relu'))
model2.compile(loss = 'mse', optimizer = 'adam', metrics = ['accuracy'])
model2.fit(Filter_X_train, Y_train, epochs = 10, batch_size = 10)
# To predict the model
NN_2 = model2.predict(Filter_X_test)
mape_NN2 = mape(Y_test, NN_2)
mape_NN2
# Neural Network For Model 3
model3 = Sequential()
model3.add(Dense(32, input_dim = 50, activation = 'sigmoid'))
model3.add(Dense(8, activation = 'sigmoid'))
model3.add(Dense(1, activation = 'relu'))
model3.compile(loss = 'mse', optimizer = 'adam', metrics = ['accuracy'])
model3.fit(Filter_X_train, Y_train, epochs = 50, batch_size = 10)
NN_3 = model3.predict(Filter_X_test)
mape_NN3 = mape(Y_test, NN_3)
mape_NN3
# To print the best MAPE
print("The best MAPE as model no.3 ") |
list(map(lambda x: (5/9)*(x-32),F_temps))
#nâo da para executar esse comando pois não fiz ele completo,eu usei ele só para
#entender como funciona map() no lambda.
|
# RDMA PD Configuration Spec
meta:
id: MR_RDMA
# This count is initialized to 1000 for RTL runs
count : 16
useAdmin : True
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 20:27:19 2020
@author: slothfulwave612
Python module for i/o operations.
Modules Used(3):-
1. pandas -- data manipulation and analysis library.
2. datetime -- Python library for datetime manipulation.
3. json -- Python library to work with JSON data.
"""
import pandas as pd
from pandas.io.json import json_normalize
import datetime
import json
def get_competitions():
'''
Function for getting information about each and every
competitions.
Returns:
comp_df -- dataframe for competition data.
'''
comp_data = json.load(open('../Statsbomb/data/competitions.json'))
comp_df = pd.DataFrame(comp_data)
return comp_df
def flatten_json(sub_str):
'''
Function to take out values from nested dictionary present in
the json file, so to make a representable dataframe.
---> This piece of code was found on stackoverflow <--
Argument:
sub_str -- substructure defined in the json file.
Returns:
flattened out information.
'''
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(sub_str)
return out
def get_matches(comp_id, season_id):
'''
Function for getting matches for the given
competition id.
Arguments:
comp_id -- int, the competition id.
season_id -- int, the season id.
Returns:
matches_df -- dataframe object, containing all the matches
'''
## setting path to the file
path = '../Statsbomb/data/matches/{0}/{1}.json'.format(comp_id, season_id)
## loading up the data from json file
match_data = json.load(open(path))
## flattening the json file
match_flatten = [flatten_json(x) for x in match_data]
## creating a dataframe
match_df = pd.DataFrame(match_flatten)
return match_df
def renaming_columns(match_df_cols):
'''
Function for renaming match dataframe columns.
Argument:
match_df_cols -- columns of match dataframe.
Returns:
match_df_cols -- list with renamed column names.
'''
for i in range(len(match_df_cols)):
if match_df_cols[i].count('away_team') == 2:
## for away_team columns
match_df_cols[i] = match_df_cols[i][len('away_team_'):]
elif match_df_cols[i].count('_0') == 1:
## for _0 columns
match_df_cols[i] = match_df_cols[i].replace('_0', '')
elif match_df_cols[i].count('competition') == 2:
## for competition columns
match_df_cols[i] = match_df_cols[i][len('competition_'):]
elif match_df_cols[i].count('home_team') == 2:
## for away_team columns
match_df_cols[i] = match_df_cols[i][len('home_team_'):]
elif match_df_cols[i].count('season') == 2:
## for away_team columns
match_df_cols[i] = match_df_cols[i][len('season_'):]
return match_df_cols
def getting_match_id(match_df, req_home_team, req_away_team):
'''
Function for getting required match id.
Arguments:
match_df -- dataframe object, representing the match dataframe.
req_home_team -- str, required home team.
req_away_team -- str, required away team.
Returns:
match_id -- int, the required match id.
'''
for row_num, match in match_df.iterrows():
home_team = match['home_team_name']
away_team = match['away_team_name']
if home_team == req_home_team and away_team == req_away_team:
match_id_required = match['match_id']
return match_id_required
def make_event_df(match_id):
'''
Function for making event dataframe for given match id.
Argument:
match_id -- int, the required match id for which event data will be extracted.
Returns:
event_df -- dataframe object, the event dataframe for the particular match.
'''
## setting path for the required file
path = '../Statsbomb/data/events/{}.json'.format(match_id)
## reading in the json file
event_json = json.load(open(path, encoding='utf-8'))
## normalize the json data
df = json_normalize(event_json, sep='_')
return df
def convert_to_datetime(df):
'''
Function to convert a string pandas series to datetime object.
Argument:
df -- dataframe object.
Returns:
df -- dateframe object.
'''
df['match_date'] = pd.to_datetime(df['match_date'])
return df
def get_selected_match(match_df, start_date, end_date):
'''
Function to get only those matches between start_date and end_date.
Arguments:
match_df -- dataframe object, containing matches.
start_date -- str, the starting date(YYYY-MM-DD).
end_date -- str, the ending date(YYYY-MM-DD).
Returns:
requied_df -- dataframe object, containing required rows.
'''
## start date
start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
mask = (match_df['match_date'] > start_date) & (match_df['match_date'] <= end_date)
required_df = match_df.loc[mask].copy()
return required_df
def get_selected_events(scoring_df_ids):
'''
Function for making a dataframe which will have events for all the matches.
Arguments:
scoring_df_ids -- list, containing all required match ids.
Returns:
scoring_events -- dataframe object, containing all the required events.
'''
c = 0
for match_id in scoring_df_ids:
temp_df = make_event_df(match_id)
temp_shot = temp_df.loc[
(temp_df['type_name'] == 'Shot') & (temp_df['player_name'] == 'Lionel Andrés Messi Cuccittini')
& (temp_df['shot_outcome_name'] != 'Blocked') & (temp_df['shot_outcome_name'] != 'Wayward')
].copy()
if c == 0:
shots_df = temp_shot
c += 1
else:
shots_df = pd.concat([shots_df, temp_shot], sort=True)
shots_df.dropna(axis=1, inplace=True)
return shots_df
|
class Solution:
def maxScore(self, s: str) -> int:
zeros = 1 if s[0] == '0' else 0
ones = s[1:].count('1')
ans = zeros + ones
n = len(s)
for c in range(1, n-1):
if s[c] == '0':
zeros += 1
else:
ones -= 1
ans = max(ans, zeros + ones)
return ans
|
#!/usr/bin/python3
import requests
def retrieve_xml(url="", method="get", params=""):
method = method.lower()
if method == "get":
r = requests.get(url, params)
return r
if method == "post":
pass
if method == "put":
pass
if method == "delete":
pass
if method == "patch":
pass
else:
return None |
# 2019/08/09
n,m=map(int,input().split())
cnt=min(n,m//2)
m-=cnt*2
n-=cnt
if m//4>0:
cnt+=m//4
print(cnt)
|
#!/usr/bin/env python
# Handle all globals variables
def init():
# -----------------------------------------------------------------------------
# Setting GPIO allocation
global SERB_TOGGLE_BEC
SERB_TOGGLE_BEC = 24
global SERB_TOGGLE_GIMBAL
SERB_TOGGLE_GIMBAL = 23
global SERB_TOGGLE_LIGHT
SERB_TOGGLE_LIGHT = 17
global SERB_TOGGLE_LASER
SERB_TOGGLE_LASER = 18
# Setting Gimbal allocation
global PWM_GIMBAL_X
PWM_GIMBAL_X = 27
global PWM_GIMBAL_Y
PWM_GIMBAL_Y = 22
global PWM_GIMBAL_Z
PWM_GIMBAL_Z = 20
global PWM_GIMBAL_RESET
PWM_GIMBAL_RESET = 21
global PWM_GIMBAL_deadband # Joystick deadband
PWM_GIMBAL_deadband = 45
global PWM_GIMBAL_X_min_angle
PWM_GIMBAL_X_min_angle = -40
global PWM_GIMBAL_X_max_angle
PWM_GIMBAL_X_max_angle = 40
global PWM_GIMBAL_X_start_angle
PWM_GIMBAL_X_start_angle = 0.0
global PWM_GIMBAL_Y_min_angle
PWM_GIMBAL_Y_min_angle = -40
global PWM_GIMBAL_Y_max_angle
PWM_GIMBAL_Y_max_angle = 40
global PWM_GIMBAL_Y_start_angle
PWM_GIMBAL_Y_start_angle = 0.0
global PWM_GIMBAL_Z_min_angle
PWM_GIMBAL_Z_min_angle = -40
global PWM_GIMBAL_Z_max_angle
PWM_GIMBAL_Z_max_angle = 40
global PWM_GIMBAL_Z_start_angle
PWM_GIMBAL_Z_start_angle = 0.0
global I2C_arduino_i2cAddress
I2C_arduino_i2cAddress = 4
# The Register is where we send our 1 to tell our slave to read or a 0 to send data to.
global I2C_arduino_Register
I2C_arduino_Register = 0
# We need to identify the size of our message we are sending to the slave. So that we can send #the end of transmission bit.
global I2C_arduino_Data_Length
I2C_arduino_Data_Length = 7
# Hexapod Control
global SERB_START
SERB_START = 1 # bit3 - Start Button test
global SERB_SELECT
SERB_SELECT = 2 # bit0 - Select Button test
global SERB_L3
SERB_L3 = 3 # bit1 - L3 Button test
global SERB_L1
SERB_L1 = 4 # bit2 - L1 Button test
global SERB_L2
SERB_L2 = 5 # bit0 - L2 Button test
global SERB_R3
SERB_R3 = 6 # bit2 - R3 Button test (Horn)
global SERB_R1
SERB_R1 = 7 # bit3 - R1 Button test
global SERB_R2
SERB_R2 = 8 # bit1 - R2 Button test
global SERB_PAD_UP
SERB_PAD_UP = 9 # bit4 - Up Button test
global SERB_PAD_DOWN
SERB_PAD_DOWN = 10 # bit6 - Down Button test
global SERB_PAD_LEFT
SERB_PAD_LEFT = 11 # bit7 - Left Button test
global SERB_PAD_RIGHT
SERB_PAD_RIGHT = 12 # bit5 - Right Button test
global SERB_TRIANGLE
SERB_TRIANGLE = 13 # bit4 - Triangle Button test
global SERB_CIRCLE
SERB_CIRCLE = 14 # bit5 - Circle Button test
global SERB_CROSS
SERB_CROSS = 15 # bit6 - Cross Button test
global SERB_SQUARE
SERB_SQUARE = 16 # bit7 - Square Button test
global SER_RX
SER_RX = 6 # DualShock(3) - Right stick Left/right
global SER_RY
SER_RY = 5 # DualShock(4) - Right Stick Up/Down
global SER_LX
SER_LX = 4 # DualShock(5) - Left Stick Left/right
global SER_LY
SER_LY = 3 # DualShock(6) - Left Stick Up/Down
|
"""
7. По длинам трех отрезков, введенных пользователем, определить возможность
существования треугольника, составленного из этих отрезков. Если такой
треугольник существует, то определить, является ли он
разносторонним, равнобедренным или равносторонним.
"""
storona1 = int(input('Введите длину стороны 1: ', ))
storona2 = int(input('Введите длину стороны 2: ', ))
storona3 = int(input('Введите длину стороны 3: ', ))
if (storona1 + storona2) > storona3 and(storona1 + storona3) > storona2 and (storona2 + storona3) > storona1:
print('Такой треугольник существует')
if storona1 == storona2 and storona1 == storona3:
print('Треугольник является равносторонним')
elif storona1 == storona2 or storona1 == storona3 or storona2 == storona3:
print('Треугольник является равнобедренным')
else:
print('Такого треугольника не существует')
|
import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
# PART 1 ----------------------------------------------------------
# Building the blockchain
class Blockchain:
def __init__(self):
self.chain = []
self.transactions = []
self.create_block(proof = 1, prevHash = '0')
self.nodes = set()
def create_block(self, proof, prevHash):
block = {'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'proof': proof,
'prevHash': prevHash,
'transactions': self.transactions}
self.transactions = []
self.chain.append(block)
return block
def get_prev_block(self):
return self.chain[-1]
def proof_of_work(self, prevProof):
start = datetime.datetime.now()
newProof = 1
checkProof = False
while checkProof == False:
hashOperation = hashlib.sha256(str(newProof**2 - prevProof**2).encode()).hexdigest()
if hashOperation[:4] == '0000':
checkProof = True
end = datetime.datetime.now()
print('SUCCESS! This is the correct Hash Operation: ' + hashOperation)
print('Time elapsed: ' + str((end.microsecond - start.microsecond)/1000) + ' ms')
else:
newProof +=1
return newProof
def hash(self, block):
encodedBlock = json.dumps(block, sort_keys = True).encode()
return hashlib.sha256(encodedBlock).hexdigest()
def is_chain_valid(self, chain):
prevBlock = chain[0]
blockIndex = 1
isValid = True
while blockIndex < len(chain):
block = chain[blockIndex]
print('CHECKING BLOCK ' + str(block['index']))
if block['prevHash'] != self.hash(prevBlock):
isValid = False
return False
prevProof = prevBlock['proof']
proof = block['proof']
hashOperation = hashlib.sha256(str(proof**2 - prevProof**2).encode()).hexdigest()
if hashOperation[:4] != '0000':
isValid = False
return False
prevBlock = block
blockIndex += 1
if isValid == True:
print('VALID!')
else:
print('ERROR!')
return True
def add_transaction(self, sender, receiver, amount):
self.transactions.append({
'sender': sender,
'receiver': receiver,
'amount': amount})
prevBlock = self.get_prev_block()
return prevBlock['index'] + 1
def add_node(self, address):
parsedUrl = urlparse(address)
self.nodes.add(parsedUrl.netloc)
def replace_chain(self):
network = self.nodes
longestChain = None
maxLength = len(self.chain)
for node in network:
response = requests.get(f'http://{node}/get_chain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']
if length > maxLength and self.is_chain_valid(chain):
maxLength = length
longestChain = chain
if longestChain:
self.chain = longestChain
return True
else:
return False
# Create the Blockchain
blockchain = Blockchain()
# Create the web app
app = Flask(__name__)
# Create a NODE address
nodeAddress = str(uuid4()).replace('-', '')
# PART 2 ----------------------------------------------------------
# Mining the blockchain
@app.route('/mine_block', methods = ['GET'])
def mine_block():
prevBlock = blockchain.get_prev_block()
prevProof = prevBlock['proof']
proof = blockchain.proof_of_work(prevProof)
prevHash = blockchain.hash(prevBlock)
blockchain.add_transaction(sender = nodeAddress, receiver = 'Claire', amount = 5)
block = blockchain.create_block(proof, prevHash)
response = {'message': 'CONGRATS, BLOCK SUCCESSFULLY MINED',
'index': block['index'],
'timestamp': block['timestamp'],
'proof': block['proof'],
'prevHash': block['prevHash'],
'transactions': block['transactions']}
return jsonify(response), 200
print(proof)
# Get the full blockchain
@app.route('/get_chain', methods = ['GET'])
def get_chain():
response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200
# Checking if the Blockchain is valid
@app.route('/is_valid', methods = ['GET'])
def is_valid():
isValid = blockchain.is_chain_valid(blockchain.chain)
if isValid:
response = {'message': 'BLOCKCHAIN IS VALID'}
else:
response = {'message': 'WARNING!! BLOCKCHAIN IS CORRUPTED'}
return jsonify(response), 200
# Adding a transaction to the blockchain
@app.route('/add_transaction', methods = ['POST'])
def add_transaction():
json = request.get_json()
transactionKeys = ['sender', 'receiver', 'amount']
if not all (key in json for key in transactionKeys):
return 'ERROR: MISSING KEY IN TRANSACTIONS', 400
else:
index = blockchain.add_transaction(json['sender'], json['receiver'], json['amount'])
response = {'message': f'SUCCESS! This transaction will be added to Block {index}'}
return jsonify(response), 201
# Connecting new nodes
@app.route('/connect_node', methods = ['POST'])
def connect_node():
json = request.get_json()
nodes = json.get('nodes')
if nodes == None:
return 'ERROR: NO NODES FOUND', 400
else:
for node in nodes:
blockchain.add_node(node)
response = {
'message': 'SUCCESS! ALL NODES CONNECTED. LIST OF NODES: ',
'total nodes': list(blockchain.nodes)}
return jsonify(response), 201
# Replacing the chain by the longest chain, if needed
@app.route('/replace_chain', methods = ['GET'])
def replace_chain():
isChainReplaced = blockchain.replace_chain()
if isChainReplaced:
response = {'message': 'CHAIN UPDATED AND REPLACED', 'newChain': blockchain.chain}
else:
response = {'message': 'NO CHANGES, CHAIN IS THE LARGEST ALREADY', 'actualChain': blockchain.chain}
return jsonify(response), 200
# PART 3 ----------------------------------------------------------
# Decentralizing the blockchain
# Run the app
app.run(host = '0.0.0.0', port = 5002)
|
# Group Anagrams
# https://leetcode.com/problems/group-anagrams/
# 애너그램은 문자열을 재배열해서 다른 뜻을 가진 단어로 바꾸는 것을 말한다.
# 애너그램을 판별하는 방법은 정렬하여 비교하는 것이 가장 간단해 보인다. 정렬하는 방법은 sorted 함수를 사용해 준다.
# 정렬되어 나온 값은 리스트 형태이기 때문에 join 으로 합쳐서 이 값을 키로 딕셔너리를 만들어 준다.
# 만약 없는 키를 넣어줄 경우 keyerror가 생겨 에러가 나지 않도록 defaultdict()으로 정리하고,
# 매번 키 여부를 확인하지 않고 간단하게 해결한다.
import collections
def groupAnagrams(strs):
anagrams = collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return anagrams.values()
def test_solution():
assert groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) != [["bat"], ["nat","tan"], ["ate", "eat", "tea"]]
assert groupAnagrams([""]) != [[""]]
assert groupAnagrams(["a"]) != [["a"]] |
#!/usr/bin/env python
# notify_celery is referenced from manifest_delivery_base.yml, and cannot be removed
from app import notify_celery, create_app
application = create_app('delivery')
application.app_context().push()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 20:49:04 2017
@author: mmonforte
Next, implement the function getGuessedWord that takes in two parameters -
a string, secretWord, and a list of letters, lettersGuessed.
This function returns a string that is comprised of letters and underscores,
based on what letters in lettersGuessed are in secretWord. This shouldn't be
too different from isWordGuessed!
Example Usage:
>>> secretWord = 'apple'
>>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
>>> print(getGuessedWord(secretWord, lettersGuessed))
'_ pp_ e'
For this function, you may assume that all the letters in secretWord and lettersGuessed are lowercase.
"""
# Example parameters
secretWord = 'apple'
lettersGuessed = ['b', 'a', 'o', 'k', 'l', 's']
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
# Create an empty list, which will hold your guesses.
currentGuess_list = []
# Index through each letter in secretWord, in order.
for i in range(len(secretWord)):
# If that letter is in the list of guessed letters...
if secretWord[i] in lettersGuessed:
# Add it to the current guesses list.
currentGuess_list.append(secretWord[i] + ' ')
else:
# If not, add an underscore.
currentGuess_list.append('_ ')
# Concatenate all the items into a string.
currentGuess = ''.join(currentGuess_list)
return(currentGuess)
print(getGuessedWord(secretWord, lettersGuessed)) |
import random
random.SystemRandom()
items=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
thumon=random.sample(items,1)
print('Thu mon:',thumon)
items2=list(set(items)-set(thumon))
hauve=random.sample(items2,4)
print('Hau ve:',hauve)
items3=list(set(items2)-set(hauve))
tienve=random.sample(items3,4)
print('Tien ve:',tienve)
items4=list(set(items3)-set(tienve))
tiendao=random.sample(items4,2)
print('Tien dao:',tiendao)
|
def sum_of_nested_list(x):
if len(x) == 0:
return 0
else:
if isinstance(x[0], list):
return sum_of_nested_list(x[0]) + sum_of_nested_list(x[1:])
else:
return x[0] + sum_of_nested_list(x[1:])
print(sum_of_nested_list([1,2,3,[4,5]])) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#plot total wall clock time to complete AFNI_data6 https://afni.nimh.nih.gov/pub/dist/doc/htmldoc/background_install/unix_tutorial/misc/install.data.html
# s01.ap.simple
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#MacBook i5-8259U
#Ubuntu 3900X
#MacBook Air M1
df = pd.DataFrame({'CPU': ['8259U','3900X','M1-ARM'],
'Time': [440, 269, 174]})
sns.set()
sns.catplot(x="CPU", y="Time", kind="bar", data=df)
plt.savefig('afni.png', dpi=300)
|
import sys
import os
if not os.path.exists('Public'):
os.makedirs('Public')
if not os.path.exists('External'):
os.makedirs('External')
allFiles = set()
for root, directories, filenames in os.walk('Sources/'):
for filename in filenames:
# Matching only header files
if not filename.lower().endswith(".h"):
continue
# File logic path like im/actor/core/Messenger.h
path = os.path.join(root[8:], filename)
# Full directory of file like im/actor/core
dirName = os.path.split(os.path.join(root, filename))[0][8:] + '/'
# Source file full path like Sources/actor/core/Messenger.h
srcFile = os.path.join(root, filename)
# Converted File path like Sources2/actor/core/Messenger.h
destFile = os.path.join('Public', path)
externalFile = os.path.join('External', path)
allFiles.add(path)
# Auto Create directory
if not os.path.exists(os.path.dirname(destFile)):
os.makedirs(os.path.dirname(destFile))
if not os.path.exists(os.path.dirname(externalFile)):
os.makedirs(os.path.dirname(externalFile))
with open(srcFile, 'r') as f:
allLines = f.read()
destLines = ""
with open(externalFile, 'w') as d:
d.write(allLines)
for line in allLines.splitlines():
if (line.startswith("#include") or line.startswith("#import")) and '\"' in line:
start = line.index('\"')
end = line.index('\"', start + 1)
includedFile = line[start + 1:end]
if includedFile != 'objc/runtime.h':
localIncludePath = os.path.join("Sources/", includedFile)
if os.path.exists(localIncludePath):
line = line[0:start] + "<ActorSDK/" + includedFile + ">" + line[end+1:]
else:
line = line[0:start] + "<j2objc/" + includedFile + ">" + line[end+1:]
destLines = destLines + line + "\n"
isUpdated = True
if os.path.exists(destFile):
with open(destFile, 'rw') as d:
if d.read() == destLines:
# print "Not Updated"
isUpdated = False
if isUpdated:
with open(destFile, 'w') as d:
d.write(destLines)
isUmbrellaChanged = True
umbrellaContent = ""
for line in allFiles:
umbrellaContent += "#import <ActorSDK/" + line + ">\n"
if os.path.exists('Public/ActorCoreUmbrella.h'):
with open('Public/ActorCoreUmbrella.h', 'r') as d:
if d.read() == umbrellaContent:
isUmbrellaChanged = False
if isUmbrellaChanged:
with open('Public/ActorCoreUmbrella.h', 'w') as d:
d.write(umbrellaContent)
|
import random
import numpy as np
import nn
import copy
from collections import deque
class QLearn:
def __init__(self, puzzleSize, epsilon, alpha, gamma):
# exploration factor between 0-1 (chance of taking a random action)
self.epsilon = epsilon
# learning rate between 0-1 (0 means never update Q-values, 1 means discard old value)
self.alpha = alpha
# discount factor between 0-1 (higher means the algorithm looks farther into the future
# at 1 infinite rewards possible -> dont go to 1)
self.gamma = gamma
self.puzzleSize = puzzleSize
self.actionsSize = puzzleSize**2
self.actions = range(4)
self.inputSize = self.actionsSize**2
# create one nn per action:
self.networks = {}
for action in self.actions:
net = nn.nn(puzzleSize = self.puzzleSize, alpha = self.alpha)
self.networks[action] = copy.copy(net)
if puzzleSize == 2:
self.batchMaxSize = 50
#self.moveBatchMaxSize = 10
# self.learningSteps = 20
# self.learnSize = 10
if puzzleSize == 3:
self.batchMaxSize = 10002 # how many [state,action,reward,newstate] tuples to remember
#self.moveBatchMaxSize = 50 # how many tuples to remember where a change in the boardstate happened
# self.learningSteps = 200 # after how many actions should a batch be learned
# self.learnSize = 20 # how many of those tuples to randomly choose when learning
self.age = 0
self.batch = deque(maxlen=self.batchMaxSize)
# self.batchSize = 0
self.mem_count = 0
#self.moveBatch = []
#self.moveBatchSize = 0
#self.winBatch = []
#self.chosenActions = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}
# transform state representation using numbers from 0 to N^2-1 to representation using a vector on length N^2
# for each cell: for N = 2 solution state [[1,2],[3,0]] looks like [[[0,1,0,0],[0,0,1,0]],[[0,0,0,1],[1,0,0,0]]]
# which is simply represented as [0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0] and used as input for the NN
def transformState(self, state):
rep = np.full(self.inputSize, 0)
count = 0
for y in range(self.puzzleSize):
for x in range(self.puzzleSize):
num = state[y][x]
rep[count * self.actionsSize + num] = 1
count += 1
return rep
def doLearning(self, oneD_state, action, reward, oneD_newstate):
# Obtain the Q' values by feeding the new state through our network
# this was originally because there was one network for all actions, but we only wanted to change one action,
# so we ran it through and then only changed the targetQ value for the one action (=output)
#allQ = self.networks[action].sess.run(self.networks[action].Qout,
# feed_dict={self.networks[action].inputs: [oneD_state]})
#targetQ = allQ
targetQ = np.ndarray(shape=(1,1), dtype=float)
if oneD_newstate is not None:
# calculate Q1 for all actions and find maximum
qList = []
for a in self.actions:
Q1 = self.networks[a].sess.run(self.networks[a].Qout,
feed_dict={self.networks[a].inputs: [oneD_newstate]})
#qList.append(np.amax(Q1))
qList.append(Q1[0][0])
# Obtain maxQ' and set our target value for chosen action.
#maxQ1 = np.amax(Q1)
maxQ1 = max(qList)
targetQ[0] = reward + self.gamma * maxQ1
else:
targetQ[0] = reward
# Train network using target and predicted Q values
# _, W1 = self.sess.run([self.updateModel, self.W], feed_dict={self.inputs1: [oneD_state], self.nextQ: targetQ})
self.networks[action].sess.run(self.networks[action].updateModel,
feed_dict={self.networks[action].inputs: [oneD_state],
self.networks[action].nextQ: targetQ})
# Q-learning: Q(s, a) += alpha * (reward(s,a) + max(Q(s') - Q(s,a))
# documented reward += learning rate * (newly received reward + max possible reward for next state - doc reward)
# alpha ... learning rate between 0-1 (0 means never update Q-values)
# maxq ... highest reward for any action done in the new state = max(Q(s',a') (for any action in that mew state)
# maxq = max([self.getQ(newstate, a) for a in self.actions])
# qTarget = self.alpha * (reward + self.gamma * maxq)
# The nn returns a Q value for each action that could be taken in the new state
# the best action = the highest Q value represents how good the current state is
# add to that the reward that was received for entering that state and you have the states Q-value
# use Q-learning formula to update nn when an action is taken
# def learn_(self, state, action, reward, newstate, isSolved, hasMoved):
# oneD_state = self.transformState(state)
# if newstate is not None:
# oneD_newstate = self.transformState(newstate)
# else:
# oneD_newstate = None
#
# if self.batchSize >= self.batchMaxSize:
# self.batch.pop(0)
# else:
# self.batchSize += 1
# self.batch.append([oneD_state, action, reward, oneD_newstate])
#
# if hasMoved:
# if self.moveBatchSize >= self.moveBatchMaxSize:
# self.moveBatch.pop(0)
# else:
# self.moveBatchSize += 1
# self.moveBatch.append([oneD_state, action, reward, oneD_newstate])
#
# if isSolved:
# #chosenBatch = self.batch[:-self.learnSize:-1]
# chosenBatch = self.moveBatch[::-1]
# self.winBatch = copy.deepcopy(chosenBatch)
#
# #self.batch = []
# #self.batchSize = 0
# for i in range(len(chosenBatch)):
# b = chosenBatch[i]
# self.doLearning(b[0], b[1], b[2], b[3])
#
# self.moveBatch = []
# self.moveBatchSize = 0
#
# elif self.age % self.learningSteps == 0:
# #if self.batchSize < self.learnSize:
# chosenBatch = random.sample((self.batch + self.winBatch), min(self.batchSize, self.learnSize))
# #chosenBatch = random.sample(self.batch, self.batchSize)
# #else:
# # chosenBatch = random.sample((self.batch + self.winBatch), self.learnSize)
# #chosenBatch = random.sample(self.batch, self.learnSize)
# for i in range(len(chosenBatch)):
# b = chosenBatch[i]
# self.doLearning(b[0], b[1], b[2], b[3])
def learn(self, state, action, reward, newstate, isSolved, hasMoved):
if not hasMoved:
if random.random() > 0.1:
return # ignore 90% of non moves for learning
oneD_state = self.transformState(state)
self.mem_count += 1
if newstate is not None:
oneD_newstate = self.transformState(newstate)
else:
oneD_newstate = None
# if self.batchSize >= self.batchMaxSize:
# self.batch.pop(0)
# else:
# self.batchSize += 1
self.batch.append([oneD_state, action, reward, oneD_newstate])
if isSolved:
chosenBatch = list(self.batch)[::-1]
# higher lr when learning from successful batch
lr = self.alpha
self.alpha = lr * 10
for i in range(len(chosenBatch)):
b = chosenBatch[i]
# if b[3] is not None:
# maxqnew = max([self.getQ(b[3], a) for a in self.actions])
# maxqnew *= self.gamma
# else:
# maxqnew = None
self.doLearning(b[0], b[1], b[2], b[3])
self.alpha = lr
# self.batch=[]
# self.batchSize=0
# elif self.age % self.batchMaxSize == 0:
elif self.mem_count >= self.batchMaxSize:
print("-------------------------------------")
print("Max memory size reached (" + str(self.batchMaxSize) + ") -> learning")
print("-------------------------------------")
chosenBatch = list(self.batch)[::-1]
for i in range(len(chosenBatch)):
b = chosenBatch[i]
# if b[3] is not None:
# maxqnew = max([self.getQ(b[3], a) for a in self.actions])
# maxqnew *= self.gamma
# else:
# maxqnew = None
self.doLearning(b[0], b[1], b[2], b[3])
self.mem_count = 0
self.batch.clear()
#self.doLearning(oneD_state, action, reward, oneD_newstate)
# returns the best action based on knowledge in nn
# chance to return a random action = self.epsilon
def chooseAction(self, state):
self.age += 1
# Choose an action by greedily (with e chance of random action) from the Q-network
# epsilon = chance to choose a random action
if random.random() < self.epsilon:
action = random.choice(self.actions)
else:
# get max of all networks
oneD_state = self.transformState(state)
actList = []
for a in self.actions:
act, allQ = self.networks[a].sess.run([self.networks[a].predict, self.networks[a].Qout],
feed_dict={self.networks[a].inputs: [oneD_state]})
actList.append(allQ[0][0])
#action = actList.index(max(actList))
maxval = max(actList)
maxActions = [i for i, x in enumerate(actList) if x == maxval]
action = random.choice(maxActions)
#self.chosenActions[action] += 1
return action
|
#!/usr/bin/python
'''
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Saurabh Dingolia <dinsaurabh123@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
'''
import sys
import os
import re
import math
import itertools
from collections import Counter
def main():
args = sys.argv[1:] # Get the arguments
if not args or not len(args) == 4:
_exit()
if ( not args[0] == '--data' or not os.path.isfile(args[1]) or
not args[2] == '--sup' or not os.path.isfile(args[3]) ):
_exit()
# Define global variables
global output_patterns, sdc, out_file
output_patterns = [] # To hold the output frequent sequential patterns
out_file = os.path.abspath(os.path.join(args[3], os.pardir)) + '/result' + re.search(r'[\d-]+.txt', args[3]).group()
print out_file
# Read the data file
in_file = open(args[1], 'rU')
text = in_file.read();
in_file.close()
# Parse the data in_file to create nested list of data sequences
text = text.replace('<{', '').replace('}>', '')
sequences = text.split("\n")
sequences = [ sequence.split("}{") for sequence in sequences if sequence]
sequences = [[[item.strip() for item in itemset.split(",")] for itemset in sequence] for sequence in sequences]
# Read the support file
in_file = open(args[3], 'rU')
text = in_file.read()
in_file.close()
# Parse the support in_file to create support dict and retrieve support difference constraint
mis_values = { match[0]: float(match[1]) for match in re.findall(r'MIS\((\w+)\)\s+=\s+(\d*\.?\d*)', text) }
sdc = float(re.search(r'SDC\s=\s(\d*\.?\d*)', text).group(1))
# Run the Multiple Support Prefix Span algorithm
begin_msps(sequences, mis_values, sdc)
def _exit(message=None):
if message == None:
message = 'usage: --data datafile --sup supportfile'
print message
sys.exit(1)
def begin_msps(sequences, mis_values, sdc):
if ( sequences == None or len(sequences) == 0 or
mis_values == None or len(mis_values) == 0 ):
print 'Invalid data sequence or minimum support values'
return;
# Total no. of data sequences
sequence_count = len(sequences)
# Get the item support for each item i.e. sup(i)
global actual_supports
flattened_sequences = [ list(set(itertools.chain(*sequence))) for sequence in sequences ]
support_counts = dict(Counter(item for flattened_sequence in flattened_sequences for item in flattened_sequence))
actual_supports = {item:support_counts.get(item)/float(sequence_count) for item in support_counts.keys()}
del flattened_sequences
# Get the sorted list of frequent items i.e items with sup(i) >= MIS(i)
frequent_items = sorted([item for item in actual_supports.keys() if actual_supports.get(item) >= mis_values.get(item)],key=mis_values.get)
# print "FrequentItems:",frequent_items
# Iterate through frequent items to get sequential patterns
for item in frequent_items:
# Get the minimum item support count for item i.e count(MIS(item))
mis_count = int(math.ceil(mis_values.get(item)*sequence_count))
print "------------- Current item:",item,"MIS:",mis_count, "Sup:",support_counts.get(item),"-----------------"
# print "Seq:", [sequence for sequence in sequences if has_item(sequence, item)]
# Get the sequences containing that item and filter them to remove elements that do not satisfy SDC i.e. |sup(j) - sup(item)| > sdc
item_sequences = [sdc_filter_on_item(sequence, item, actual_supports.get(item), actual_supports, sdc) for sequence in sequences if has_item(sequence, item)]
print "ItemSeq:"
print "\n".join([str(sequence) for sequence in item_sequences])
# Run the restricted Prefix-Span to get sequential patterns
r_prefix_span(item, item_sequences, mis_count)
# Remove the item from original sequences
sequences = remove_item(sequences, item)
# End of the mining algorithm, print output
write_output(output_patterns)
def write_output(output_list):
output_list = sorted(output_list,key=pattern_length) # Sort the output based on pattern length
output_text = '' # Intialize empty string to append the output text
cur_length = 1 # Initialize current length as 1
while True: # Iterate until there are no patterns of specified length
# Get all the patterns of current length from output
cur_length_patterns = filter (lambda a: pattern_length(a) == cur_length, output_list)
if not cur_length_patterns: # Break from the loop if the list is empty
break
# Print the current length and number of patterns for current length
output_text += "The number of length " + str(cur_length) + " sequential patterns is " + str(len(cur_length_patterns)) + "\n"
# Print all the patterns with their support counts
for (pattern,sup_count) in cur_length_patterns:
str_pattern = "<{" + "}{".join([",".join(itemset) for itemset in pattern]) + "}>"
output_text += "Pattern: " + str_pattern + " Count: " + str(sup_count) + "\n"
cur_length += 1 # Increment the current length
output_text += "\n"
print output_text
output_file = open(out_file, 'w')
output_file.write(output_text)
output_file.close()
def pattern_length(output_tuple):
seq_pattern = output_tuple[0] # Get the sequential pattern
while isinstance(seq_pattern[0], list): # Chain it until all sub-lists are removed
seq_pattern = list(itertools.chain(*seq_pattern))
return len(seq_pattern) # Return the length of the pattern
def remove_item(source_list, item_to_del):
filtered_list = [] # Declare list to contain filter results
# Check to see if list has sub lists as items
if source_list and isinstance(source_list[0], list):
for child_list in source_list:
filtered_child_list = remove_item(child_list, item_to_del) # Recurse for filtering each child_list
if filtered_child_list: # Append only non-empty lists
filtered_list.append(filtered_child_list)
else: # Remove item from the list
filtered_list = filter (lambda a: a != item_to_del, source_list)
return filtered_list # Return the filtered list from current recursion
def sdc_filter_on_item(source_list, base_item, base_item_support, supports, sd_constraint):
filtered_list = [] # Declare list to contain filter results
# Check to see if list has sub lists as items
if source_list and isinstance(source_list[0], list):
for child_list in source_list:
filtered_child_list = sdc_filter_on_item(child_list, base_item, base_item_support, supports, sd_constraint) # Recurse for filtering each child_list
if filtered_child_list: # Append only the non-empty lists
filtered_list.append(filtered_child_list)
else: # Remove items that do not satisfy support difference constraint
for item in source_list:
# print "Item:",item,"Support:",item_supports.get(item),"Diff:",abs(item_supports.get(item) - base_item_support)
if not item == base_item and abs(supports.get(item) - base_item_support) > sd_constraint: # Item doesn't satisfy SDC
continue
else: # Item satisfies SDC
filtered_list.append(item)
return filtered_list # Return the filtered list from current recursion
def r_prefix_span(base_item, item_sequences, mis_count):
# Get the frequent items and construct length one frequent sequences from them
freq_item_sequences = remove_infrequent_items(item_sequences, mis_count)
frequent_items = list(set(itertools.chain(*(itertools.chain(*freq_item_sequences)))))
del freq_item_sequences
# Get length-1 frequent sequences
len_1_freq_sequences = [ [[item]] for item in frequent_items ]
# print len_1_freq_sequences
# Remove the infrequent items
item_sequences = remove_infrequent_items(item_sequences, mis_count)
# Add the base_item 1-length sequential pattern to the output database
if has_item(len_1_freq_sequences, base_item):
output_patterns.append(([[base_item]], support_count(item_sequences, base_item)))
# Run Prefix Span for each length-1 frequent sequential pattern
for freq_sequence in len_1_freq_sequences:
prefix_span(freq_sequence, item_sequences, base_item, mis_count)
def prefix_span(prefix, item_sequences, base_item, mis_count):
print "Prefix:",prefix
# Compute the projected database for the current prefix
projected_db = compute_projected_database(prefix, item_sequences, base_item, mis_count)
print "DB:"
print "\n".join([str(sequence) for sequence in projected_db])
# Find the prefix_length + 1 sequential patterns
if projected_db: # Check if the projected database has any sequences
# Initialize local variables
prefix_last_itemset = prefix[-1] # Last itemset in prefix
all_template_1_items = [] # To hold all items for template 1 match i.e {30, x} or {_, x}
all_template_2_items = [] # To hold all items for template 2 match i.e {30}{x}
for proj_sequence in projected_db:
itemset_index = 0
template_1_items = [] # To hold items for template 1 match from current sequence
template_2_items = [] # To hold items for template 2 match from current sequence
while itemset_index < len(proj_sequence): # Iterate through itemsets in sequence
cur_itemset = proj_sequence[itemset_index] # Current itemset in sequence
if has_item(cur_itemset, '_'): # Add the items following '_' to template 1 list if it's a {_, x} match
template_1_items += cur_itemset[1:]
# Itemset doesn't contain '_', check for other matches
else:
if contains_in_order(cur_itemset, prefix_last_itemset): # Check if current itemset contains last itemset of prefix i.e {30, x} match
template_1_items += cur_itemset[cur_itemset.index(prefix_last_itemset[-1])+1:] # Add the items following prefix's last itemset's last item from the current itemset
template_2_items += cur_itemset # Add all the items in current itemset to template 2 list i.e {30}{x} match
itemset_index += 1
# Add only the unique elements from both lists of current sequence to the main lists as each element is considered only once for a sequence
all_template_1_items += list(set(template_1_items))
all_template_2_items += list(set(template_2_items))
# print "Template 1 items:", all_template_1_items
# print "Template 2 items:", all_template_2_items
# Compute the total occurences of each element for each template i.e number of sequences it satisfied for a template match
dict_template_1 = dict(Counter(item for item in all_template_1_items))
dict_template_2 = dict(Counter(item for item in all_template_2_items))
print "Template 1 item support:", dict_template_1
print "Template 2 item support:", dict_template_2
freq_sequential_patterns = [] # Initialize empty list to contain obtained sequential patterns
# For both the template matches, generate freuqent sequential patterns i.e patterns having support count >= MIS count
for item, sup_count in dict_template_1.iteritems():
if sup_count >= mis_count:
# Add the item to the last itemset of prefix for obtaining the pattern
freq_sequential_patterns.append((prefix[:-1] + [prefix[-1] + [item]], sup_count)) # Add the pattern with its support count to frequent patterns list
for item, sup_count in dict_template_2.iteritems():
if sup_count >= mis_count:
# Append the item contained in a new itemset to the prefix
freq_sequential_patterns.append((prefix + [[item]], sup_count)) # Add the pattern with its support count to frequent patterns list
# print "Sequential Patterns Before SDC:", [pattern for pattern, sup_count in freq_sequential_patterns]
freq_sequential_patterns = [(pattern, sup_count) for pattern, sup_count in freq_sequential_patterns if is_sequence_sdc_satisfied(list(set(itertools.chain(*pattern))))]
# print "Sequential Patterns After SDC:", [pattern for pattern, sup_count in freq_sequential_patterns]
for (seq_pattern, sup_count) in freq_sequential_patterns: # Iterate through patterns obtained
if has_item(seq_pattern, base_item): # Add the pattern to the output list if it contains base item
output_patterns.append((seq_pattern, sup_count))
prefix_span(seq_pattern, item_sequences, base_item, mis_count) # Call prefix_span recursively with the pattern as prefix
def compute_projected_database(prefix, item_sequences, base_item, mis_count):
projected_db = []
# Populate the projected database with projected sequences
for sequence in item_sequences:
cur_pr_itemset = 0
cur_sq_itemset = 0
while cur_pr_itemset < len(prefix) and cur_sq_itemset < len(sequence):
if contains_in_order(sequence[cur_sq_itemset], prefix[cur_pr_itemset]): # Sequence itemset contains the prefix itemset, move to next prefix itemset
cur_pr_itemset += 1
if cur_pr_itemset == len(prefix): break # All prefix itemsets are present in the sequence
cur_sq_itemset += 1 # Move to next sequence itemset
if cur_pr_itemset == len(prefix): # Prefix was present in the current sequence
projected_sequence = project_sequence(prefix[-1][-1], sequence[cur_sq_itemset:]) # Get the projected sequence
if projected_sequence: # Non-empty sequence, add to projected database
projected_db.append(projected_sequence)
print "DB1:"
print "\n".join([str(sequence) for sequence in projected_db])
# Check if any frequent items are left
validation_db = remove_empty_elements([[[item for item in itemset if not item == '_'] for itemset in sequence] for sequence in projected_db])
if validation_db: # Non-empty database
# projected_db = sdc_filter(projected_db) # Remove sequences that do not satisfy SDC
return remove_empty_elements(projected_db) # Remove empty elements and return the projected database
else: # Empty database
return validation_db
def project_sequence(prefix_last_item, suffix):
suffix_first_itemset = suffix[0]
if prefix_last_item == suffix_first_itemset[-1]: # Template 2 projection, return suffix - current_itemset
return suffix[1:]
else: # Template 1 projection, remove items from first itemset of suffix that are before the index of prefix's last item and put '_' as first element
suffix[0] = ['_'] + suffix_first_itemset[suffix_first_itemset.index(prefix_last_item)+1:]
return suffix
def support_count(sequences, req_item):
flattened_sequences = [ list(set(itertools.chain(*sequence))) for sequence in sequences ]
support_counts = dict(Counter(item for flattened_sequence in flattened_sequences for item in flattened_sequence))
return support_counts.get(req_item)
def contains(big, small):
return len(set(big).intersection(set(small))) == len(small)
def contains_in_order(sq_itemset, pr_itemset):
if(contains(sq_itemset, pr_itemset)):
cur_pr_item = 0
cur_sq_item = 0
while cur_pr_item < len(pr_itemset) and cur_sq_item < len(sq_itemset):
if pr_itemset[cur_pr_item] == sq_itemset[cur_sq_item]:
cur_pr_item += 1
if cur_pr_item == len(pr_itemset): return True
cur_sq_item += 1
return False
def has_item(source_list, item):
if source_list:
while isinstance(source_list[0], list):
source_list = list(itertools.chain(*source_list))
return item in source_list
return False
#def sdc_filter(projected_database):
## filtered_database = [[itemset for itemset in sequence if is_sdc_satisfied(itemset)] for sequence in projected_database]
## filtered_database = [sequence for sequence in projected_database if is_sequence_sdc_satisfied(sequence)]
# flattened_sequences = [ list(set(itertools.chain(*sequence))) for sequence in projected_database ]
# filtered_database = [sequence for i,sequence in enumerate(projected_database) if is_sequence_sdc_satisfied(flattened_sequences[i])]
# return filtered_database
#def is_sdc_satisfied(itemset):
# if not itemset:
# return False
#
# for item1 in itemset:
# sup_item1 = actual_supports.get(item1)
# for item2 in itemset:
# if not item1 == '_' and not item2 == '_':
# if abs(sup_item1 - actual_supports.get(item2)) > sdc:
# return False
#
# return True
def is_sequence_sdc_satisfied(sequence):
if not sequence:
return False
if len(sequence) > 1:
for item1 in sequence:
sup_item1 = actual_supports.get(item1)
for item2 in sequence:
if not item1 == '_' and not item2 == '_' and not item1 == item2:
if abs(sup_item1 - actual_supports.get(item2)) > sdc:
return False
return True
#def is_sequence_sdc_satisfied(sequence):
# if not sequence:
# return False
#
# for itemset in sequence:
# for item1 in itemset:
# sup_item1 = actual_supports.get(item1)
# for item2 in itemset:
# if not item1 == '_' and not item2 == '_':
# if abs(sup_item1 - actual_supports.get(item2)) > sdc:
# return False
#
# return True
def remove_infrequent_items(item_sequences, min_support_count):
# Get the support count for each item in supplied sequence database
flattened_sequences = [ list(set(itertools.chain(*sequence))) for sequence in item_sequences ]
support_counts = dict(Counter(item for flattened_sequence in flattened_sequences for item in flattened_sequence))
# Remove the infrequent items from the sequence database
filtered_item_sequences = [[[item for item in itemset if support_counts.get(item) >= min_support_count or item == '_']for itemset in sequence] for sequence in item_sequences]
return remove_empty_elements(filtered_item_sequences) # Return the new sequence database
def remove_empty_elements(source_list):
filtered_list = [] # Declare list to contain filter results
# Check to see if list has sub lists as items
if source_list and isinstance(source_list[0], list):
for child_list in source_list:
filtered_child_list = remove_empty_elements(child_list) # Recurse for filtering each child_list
if filtered_child_list: # Append only non-empty lists
filtered_list.append(filtered_child_list)
else:
filtered_list = source_list
return filtered_list # Return the filtered list from current recursion
if __name__ == '__main__':
main()
|
"""
EJERCICIO 10
El programa tiene que pedir la nota de 15 alumnos
y sacar por pantalla cuantos han aprobado y cuantos
han suspendido.
"""
cant_aprob = 0;
cant_desaprob =0;
for contador in range (0,15):
nota = int (input (" Ingrese nota: "))
if nota >= 7:
cant_aprob =+1
print (f"Cantidad de aprobados: {cant_aprob} y desaprobados {15-cant_aprob}" )
|
# using random
import random
print(random.random()) # random number between 0 and 1
print(random.randint(5, 50)) # random int between 5 and 50
print(random.choice([1, 5, 10, 15, 20, 25])) # choose a random from this list
x = 50
y = 5.5
z = x + y + 5j
# printing the type of variables
print(x, type(x))
print(y, type(y))
print(z, type(z))
# using hex() and oct() functions
x = 10
print(hex(x))
print(oct(x))
|
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from os import environ
app = Flask(__name__)
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/bubbletea'
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
CORS(app)
# create a class item
class item(db.Model):
__tablename__ = 'item'
itemid = db.Column(db.String(10), primary_key=True)
itemname = db.Column(db.String(64), nullable=False)
price = db.Column(db.Float(precision=2), nullable=False)
type = db.Column(db.String(20), nullable=False)
def __init__(self, itemid, itemname, price,type):
self.itemid = itemid
self.itemname = itemname
self.price = price
self.type = type
def json(self):
return {"itemid": self.itemid, "itemname": self.itemname, "price": self.price, "type":self.type}
# retrive all items from itemdb
@app.route("/item")
def get_all():
return jsonify({"items": [item.json() for item in item.query.all()]})
# retrieve an item by itemid
@app.route("/item/<string:itemid>")
def find_by_itemid(itemid):
single_item = item.query.filter_by(itemid=itemid).first()
if item:
return jsonify(single_item.json())
return jsonify({"message": "Item not found."}), 404
# run docker to run itemdb
## docker pull ziying123/itemdb:1.0.0
## docker run -p 5000:5000 -e dbURL=mysql+mysqlconnector://is213@host.docker.internal:3306/bubbletea <dockerid>/itemdb:1.0.0
# port: 5000
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
|
import unittest
from src.calculator.calculator import Calculator
class CalculatorTestCase(unittest.TestCase):
def setUp(self) -> None:
self.calculator = Calculator()
def test_instantiate_calculator(self):
self.assertIsInstance(self.calculator, Calculator)
def test_result_is_zero_calculator(self):
self.assertEqual(self.calculator.result, 0)
|
import numpy as np
import time
from ACO import ACO
from MatrixGraph import MatrixGraph
mtxgraph = MatrixGraph()
distances = mtxgraph.encode_to_array('example.tsp')
aco = ACO(distances, 1, 1, 100, 0.95, alpha=1, beta=1)
mtxgraph.normalize_answer(shortest_path)
print("The shortest path in the graph is {} with length {}".format(
shortest_path[0], shortest_path[1]))
fd.close()
|
import time
# from time import timestamp
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
timestamp = time.time()
def genTokenSeq(expires):
s = Serializer(secret_key="123456789", salt="123456789", expires_in=expires)
return s.dumps({"user_id": "1614010432", "user_role": "1", "iat": timestamp})
print(genTokenSeq(10000), timestamp)
token = genTokenSeq(10000)
s1 = Serializer(secret_key="123456789", salt="123456789")
print(s1.loads(token))
|
from django.urls import path
from . import views
from . import course_views
from . import staff_views
app_name = 'cms'
urlpatterns =[
path('',views.index,name='index'),
path('add_news/',views.AddNewsView.as_view(),name='add_news'),
path('news_category/',views.news_category,name='news_category'),
path('news_lists/',views.NewsListView.as_view(),name='news_lists'),
path('edit_news/',views.EditNews.as_view(),name='edit_news'),
path('del_news/',views.del_news,name='del_news'),
path('add_category/',views.add_category,name='add_category'),
path('edit_category/',views.edit_category,name='edit_category'),
path('del_category/',views.del_category,name='del_category'),
path('upload_file/',views.upload_file,name='upload_file'),
path('banner/',views.banner,name='banner'),
path('banner_list/',views.banner_list,name='banner_list'),
path('addbanner/',views.addbanner,name='addbanner'),
path('editbanner/',views.edit_banner,name='editbanner'),
path('delete_banner/',views.delete_banner,name='delete_banner'),
path('comments/',views.comments,name='comments'),
path('qntoken/',views.qntoken,name='qntoken'),
]
#course路由
urlpatterns += [
path('add_course/',views.CourseView.as_view(),name='add_course'),
path('course_list/',views.course_lists,name='course_list'),
path('add_course_category/',views.AddCourseCategoryView.as_view(),name='add_course_category'),
path('del_course_category/',course_views.del_course_category,name='del_course_category'),
path('edit_course_category/',course_views.edit_category,name='edit_course_category'),
]
# staff路由
urlpatterns += [
path('staff/',staff_views.staff,name='staff'),
path('add_staff/',staff_views.AddStaffView.as_view(),name='add_staff')
]
|
from flask import json
from flask import Response
from contentful import Entry
from bson.objectid import ObjectId
from bson import json_util
from datetime import datetime
def to_json(document=None, code=200):
return Response(
json.dumps(document, sort_keys=True, default=json_formater),
status=code,
mimetype='application/json'
)
def json_formater(obj):
# if isinstance(obj, Entry):
# return obj.fields()
# if isinstance(obj, ObjectId):
# return str(obj)
if isinstance(obj, datetime):
return obj.isoformat()
return json_util.default(obj) |
def extended_euclidean(a, b):
r_prev, r = a, b
s_prev, s = 1, 0
t_prev, t = 0, 1
while r:
q = r_prev // r
r_prev, r = r, r_prev - q*r
s_prev, s = s, s_prev - q*s
t_prev, t = t, t_prev - q*t
return s_prev, t_prev
def find_inverse(x, p):
inv, _ = extended_euclidean(x, p)
return inv
class EllipticCurve:
"""Elliptic curve modulo p.
y^2 = x^3 + ax + b (mod p)
Elliptic curve is singular if its discriminant -16*(4a^3 + 27b^2)
is zero modulo p. If discriminant is zero polynomial has repeated
roots, cusps, etc.
"""
POINT_AT_INFINITY = (float('inf'), float('inf'))
def __init__(self, a, b, p):
discriminant = 16 * (4 * a**3 + 27 * b**2)
if discriminant % p == 0:
raise ValueError('singular elliptic curve')
self.a = a
self.b = b
self.p = p
def add(self, p1, p2):
"""Add two points p1 and p2."""
x1, y1 = p1
x2, y2 = p2
a, p = self.a, self.p
if p1 == self.POINT_AT_INFINITY:
return p2
elif p2 == self.POINT_AT_INFINITY:
return p1
elif x1 == x2 and y1 != y2:
# We can rewrite this condition as
# x1 == x2 and find_inverse(-y1, p) == y2
# but, y1 != y2 is more efficient.
# This is correct because vertical line intersects
# the elliptic curve in one or two points.
return self.POINT_AT_INFINITY
if p1 == p2:
m = (3 * x1**2 + a) * find_inverse(2 * y1, p) % p
else:
m = (y2 - y1) * find_inverse(x2 - x1, p) % p
x3 = (m**2 - x1 - x2) % p
y3 = (m * (x1 - x3) - y1) % p
result = (x3, y3)
return result
def pow(self, n, b):
"""Raise n to the power of b.
Note:
With "+" group operation this is the same as
"add point 'n' b times".
"""
num_bits = b.bit_length()
res = self.POINT_AT_INFINITY
for i in range(num_bits, -1, -1):
res = self.add(res, res)
if b & (1 << i):
res = self.add(res, n)
return res
curve = EllipticCurve(a=2, b=2, p=17)
a = (5, 1)
print(curve.pow(a, 2))
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tweetclass', '0006_query_data_hm_tweets'),
]
operations = [
migrations.CreateModel(
name='Test_tweet',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),
('tweet_text', models.CharField(max_length=140)),
('tweet_pol', models.CharField(max_length=4)),
],
),
]
|
import mysql.connector as sql
import pandas as pd
config = {
'user':'root',
'password':'AirQualityDB_2018',
'host':'localhost',
'database':'bom_data_test'
}
db_connection = sql.connect(**config)
df = pd.read_sql("SELECT * FROM bom_data_test.066062 LIMIT 1000",con=db_connection)
print(df) |
"""将所有重合的地方剔除掉只留下不重合的数据"""
char_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd']
sentence = 'Welcome Back to This Tutorial'
print(set(char_list)) # {'d', 'a', 'c', 'b'}
print(set(sentence))
# 大小写区分,空格区分
# {'r', 'T', 'm', 'l', 'o', 'h', 'e', 'a', ' ', 'i', 'W', 'B', 'k', 'u', 'c', 's', 't'}
"""下面这句话是错误的,不能在其中使用列表和列表的形式,只能使用单个的list或者是String"""
# print(set([char_list, sentence]))
unique_char = set(char_list)
unique_char.add('x')
print(unique_char) # 但是只是加入进去了并不是按照原有的顺序
# unique_char.add(['y', 'z'])
# 只能单独加上数字,不能向其中添加一个List
# unique_char.clear()
# set() 得到一个空的set
print(unique_char.remove('d'))
# remove函数就算是执行之后返回值还是none,要是想要查看结果仍然需要使用print函数
# 但是如果想要删除的函数是在list中不存在的,就会报错,但是如果使用的是discard函数也不会报错,并且返回的是原有的数据
print(unique_char.discard('d'))
print(unique_char)
"""difference函数的使用"""
set1 = unique_char
set2 = {'a', 'e', 'i'}
print(set1.difference(set2))
# 找相同的地方
print(set1.intersection(set2)) |
# -*- coding: utf-8 -*-
import urllib
import urllib2
from urllib2 import URLError, HTTPError
import json
import pdb
import os
import sys
import codecs
import re
p = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, p)
os.environ['DJANGO_SETTINGS_MODULE'] = "sefaria.settings"
from local_settings import *
from functions import *
sys.path.insert(0, SEFARIA_PROJECT_PATH)
from sefaria.model import *
from sefaria.model.schema import AddressTalmud
def goodTag(poss_siman, curr_siman, line, prev_line):
line = removeAllStrings(line).replace("\r", "").replace("\n", "")
return abs(poss_siman - curr_siman) <= 10 and len(line) <= 4
if __name__ == "__main__":
BY_values = {}
prev_line = ""
files = ["Even HaEzer/Bi Even HaEzer.txt", "Orach_Chaim/beit yosef orach chaim 1.txt", "Yoreh Deah/beit yosef yoreh deah.txt"]
for file in files:
print file
accum_text = ""
curr_siman = 0
for line in open(file):
line = line.decode('utf-8')
orig_line = line
line = line.split(" ")[0]
if line.find("@22") >= 0 or (line.find("@00") >= 0 and len(line) < 15):
if line.find("@22") >= 0:
poss_siman = re.findall(u"@22[\u05d0-\u05EA]+", line)
else:
poss_siman = re.findall(u"@00[\u05d0-\u05EA]+", line)
assert len(poss_siman) == 1, "Siman array off {}, {}".format(poss_siman, line.encode('utf-8'), prev_line.encode('utf-8'))
poss_siman = getGematria(poss_siman[0])
poss_siman = ChetAndHey(poss_siman, curr_siman)
if not goodTag(poss_siman, curr_siman, line, prev_line):
print line
continue
assert poss_siman > curr_siman, str(poss_siman) + " > " + str(curr_siman)
if curr_siman > 0:
convert = []
temp = [each_one for each_one in re.findall(u"\*?\([\u05D0-\u05EA]{1,2}\)", accum_text) if each_one.find(u"שם") == -1]
for each_one in temp:
convert += [getGematria(each_one)]
BY_values[curr_siman] = convert
curr_siman = poss_siman
prev_line = orig_line
accum_text = ""
accum_text += orig_line + "\n"
if file.find("Orach") >= 0:
new_file = codecs.open("orach chaim darchei moshe.txt", 'w', encoding='utf-8')
elif file.find("Ezer") >= 0:
new_file = codecs.open("even haezer darchei moshe.txt", 'w', encoding='utf-8')
elif file.find("Yoreh") >= 0:
new_file = codecs.open("yoreh deah darchei moshe.txt", 'w', encoding='utf-8')
new_file.write(json.dumps(BY_values))
new_file.close()
|
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
import PySimpleGUI as simpleGUI
import re
from PIL import Image
# from anticaptchaofficial.imagecaptcha import imagecaptcha
captcha_svgFile = './captcha/captcha.svg'
captcha_pngFile = './captcha/captcha.png'
captcha_gifFile = './captcha/captcha.gif'
def captcha_builder(resp):
with open(captcha_svgFile, 'w') as f:
f.write(re.sub('(<path d=)(.*?)(fill="none"/>)', '', resp['captcha']))
drawing = svg2rlg(captcha_svgFile)
renderPM.drawToFile(drawing, captcha_pngFile, fmt="PNG")
im = Image.open(captcha_pngFile)
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE)
im.save(captcha_gifFile)
layout = [[simpleGUI.Image(captcha_gifFile)],
[simpleGUI.Text("Enter Captcha Below")],
[simpleGUI.Input(key='input')],
[simpleGUI.Button('Submit', bind_return_key=True)]]
window = simpleGUI.Window('Enter Captcha', layout, finalize=True)
window.TKroot.focus_force() # focus on window
window.Element('input').SetFocus() # focus on field
event, values = window.read()
window.close()
return values['input']
# def captcha_builder_auto(resp, api_key):
# with open('captcha.svg', 'w') as f:
# f.write(re.sub('(<path d=)(.*?)(fill=\"none\"/>)', '', resp['captcha']))
#
# drawing = svg2rlg('captcha.svg')
# renderPM.drawToFile(drawing, "captcha.png", fmt="PNG")
#
#
# solver = imagecaptcha()
# solver.set_verbose(1)
# solver.set_key(api_key)
# captcha_text = solver.solve_and_return_solution("captcha.png")
#
# if captcha_text != 0:
# print(f"Captcha text: {captcha_text}")
# else:
# print(f"Task finished with error: {solver.error_code}")
#
# return captcha_text
|
# https://atcoder.jp/contests/abc271/tasks/abc271_c
# # def input(): return sys.stdin.readline().rstrip()
# # input = sys.stdin.readline
# from numba import njit
# from functools import lru_cache
import sys
input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10 ** 7)
N = int(input())
a = list(map(int, input().split()))
vol = [False] * (N+2)
sold = 0
for i in range(N):
if a[i]>N:
sold += 1
elif vol[a[i]]:
sold += 1
else:
vol[a[i]] = True
L = 1
R = N+1
while True:
while vol[L]: L += 1
while (R != 0 and vol[R] == False): R -= 1
if sold >= 2:
sold -= 2
vol[L] = True
else:
if L>=R: break
vol[R] = False
sold += 1
print(L-1)
|
import findspark
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
from pyspark.sql.functions import split
# ------------------------------------ TASK ------------------------------------
# 1- Given this yearly income ranges, <40k, 40-60k, 60-80k, 80-100k and 100k>.
# Generate a report that contains the average loan amount and an average term of the loan in months based on these 5 income ranges.
# Result file should be like “income range, avg amount, avg term”
# 2- In loans which are fully funded and loan amounts greater than $1000,
# what is the fully paid amount rate for every loan grade of the borrowers.
# Result file should be like “credit grade,fully paid amount rate”, eg.“A,%95”
# -------------------------------------------------------------------------------
spark = SparkSession.builder.getOrCreate()
findspark.init()
df = spark.read.format("csv").option("header", "true").load("loan.csv")
def task_1(df):
print("Task - 1 ")
df = df.withColumn('termInt', split(df['term'], ' ').getItem(1)).withColumn('termMonths', split(df['term'], ' ').getItem(2))
# "Income Range : 40k;
first = df.filter(df.annual_inc == 40000).agg({"loan_amnt": "avg", "termInt": "avg"}) \
.withColumnRenamed("avg(termInt)", "Average Term (40k)") \
.withColumnRenamed("avg(loan_amnt)", "Average Amount (40k)")
# "Income Range : 40k-60k;
second = df.filter((df.annual_inc > 40000) & (df.annual_inc < 60000)).agg({"loan_amnt": "avg", "termInt": "avg"}) \
.withColumnRenamed("avg(termInt)", "Average Term (40k-60k)") \
.withColumnRenamed("avg(loan_amnt)", "Average Amount (40k-60k)")
# "Income Range : 60k-80k;
third = df.filter((df.annual_inc > 60000) & (df.annual_inc < 80000)).agg({"loan_amnt": "avg", "termInt": "avg"}) \
.withColumnRenamed("avg(termInt)", "Average Term (60k-80k)") \
.withColumnRenamed("avg(loan_amnt)", "Average Amount (60k-80k)")
# "Income Range : 80k-100k;
forth = df.filter((df.annual_inc > 80000) & (df.annual_inc < 100000)).agg({"loan_amnt": "avg", "termInt": "avg"}).withColumnRenamed("avg(termInt)",
"Average Term (80k-100k)").withColumnRenamed(
"avg(loan_amnt)", "Average Amount (80k-100k)")
# "Income Range : 100k;
fifth = df.filter(df.annual_inc == 100000).agg({"loan_amnt": "avg", "termInt": "avg"}).withColumnRenamed("avg(termInt)", "Average Term (100k)").withColumnRenamed("avg(loan_amnt)",
"Average Amount (100k)")
allofThem = first.crossJoin(second).crossJoin(third).crossJoin(forth).crossJoin(fifth)
allofThem.show()
def task_2(df):
print("Task - 2")
normal = df.filter((df.loan_amnt > 1000) & (df.funded_amnt == df.loan_amnt))
fullyPaid = normal.filter(normal.loan_status == 'Fully Paid')
normal = normal.groupBy("grade").count().withColumnRenamed("count", "normalCount")
fullyPaid = fullyPaid.groupBy("grade").count().withColumnRenamed("count", "fullyPaidCount")
join = fullyPaid.join(normal, "grade", how="right").withColumn('fullyOverNormal', (f.col("fullyPaidCount") / f.col('normalCount')) * 100)
join.show()
task_1(df)
print()
task_2(df)
|
import sys
sys.stdin = open('input.txt', 'r')
N = int(input())
count = 0
for i in range(2, N+1, 2):
for j in range(1, N+1-i):
k = N - (i + j)
if k >= j+2 and k != 0:
count += 1
print(count)
|
import sys
import math
with open('./popular-names.txt', mode="r") as f:
n = int(sys.argv[1])
lines = [line.rstrip() for line in f]
n_split = math.ceil(len(lines) / float(n))
fs = [open(f"f_{i}.txt", mode="w") for i in range(n)]
i = 0
cnt = 0
for line in lines:
fs[i].write(line + "\n")
cnt += 1
if cnt == n_split:
i += 1
cnt = 0
for i in range(n):
fs[i].close() |
from pathlib import Path
project_root = Path(__file__).parent.absolute()
import os
import random
import math
from collections.abc import Sequence
from functools import partial
import torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks import Callback
from munch import Munch
import ray
from ray import tune
from ray.tune import Trainable, Experiment, SyncConfig, sample_from, grid_search
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.integration.wandb import WandbLogger
from pl_runner import pl_train
from utils import remove_postfix, dictconfig_to_munch, munch_to_dictconfig
HYDRA_TUNE_KEYS = ['_grid', '_sample', '_sample_uniform', '_sample_log_uniform']
def munchconfig_to_tune_munchconfig(cfg):
"""Convert config to one compatible with Ray Tune.
Entry as list whose first element is "_grid" is converted to ray.tune.grid_search.
"_sample" is converted to ray.tune.sample_from.
"_sample_uniform" is converted to ray.tune.sample_from with uniform distribution [min, max).
"_sample_log_uniform" is converted to ray.tune.sample_from with uniform distribution
exp(uniform(log(min), log(max)))
Examples:
lr=1e-3 for a specific learning rate
lr=[_grid, 1e-3, 1e-4, 1e-5] means grid search over those values
lr=[_sample, 1e-3, 1e-4, 1e-5] means randomly sample from those values
lr=[_sample_uniform, 1e-4, 3e-4] means randomly sample from those min/max
lr=[_sample_log_uniform, 1e-4, 1e-3] means randomly sample from those min/max but
distribution is log uniform: exp(uniform(log 1e-4, log 1e-3))
"""
def convert_value(v):
# The type is omegaconf.listconfig.ListConfig and not list, so we test if it's a Sequence
if not (isinstance(v, Sequence) and len(v) > 0 and v[0] in HYDRA_TUNE_KEYS):
return v
else:
if v[0] == '_grid':
# grid_search requires list for some reason
return grid_search(list(v[1:]))
elif v[0] == '_sample':
# Python's lambda doesn't capture the object, it only captures the variable name
# So we need extra argument to capture the object
# https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
# https://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture
# Switching back to not capturing variable since (i) ray 1.0 doesn't like that
# (ii) v isn't changing in this scope
return sample_from(lambda _: random.choice(v[1:]))
elif v[0] == '_sample_uniform':
min_, max_ = v[1:]
if isinstance(min_, int) and isinstance(max_, int):
return sample_from(lambda _: random.randint(min_, max_))
else:
return sample_from(lambda _: random.uniform(min_, max_))
elif v[0] == '_sample_log_uniform':
min_, max_ = v[1:]
return sample_from(lambda _: math.exp(random.uniform(math.log(min_), math.log(max_))))
else:
assert False
def convert(cfg):
return Munch({k: convert(v) if isinstance(v, Munch) else
convert_value(v) for k, v in cfg.items()})
return convert(cfg)
class TuneReportCheckpointCallback(Callback):
# We group train and val reporting into one, otherwise tune thinks there're 2 different epochs.
def on_epoch_end(self, trainer, pl_module):
results = {remove_postfix(k, '_epoch'): v for k, v in trainer.logged_metrics.items()
if (k.startswith('train_') or k.startswith('val_')) and not k.endswith('_step')}
results['mean_loss'] = results.get('val_loss', results['train_loss'])
if 'val_accuracy' in results:
results['mean_accuracy'] = results['val_accuracy']
# Checkpointing should be done *before* reporting
# https://docs.ray.io/en/master/tune/api_docs/trainable.html
with tune.checkpoint_dir(step=trainer.current_epoch) as checkpoint_dir:
trainer.save_checkpoint(os.path.join(checkpoint_dir,
f"{type(pl_module).__name__}.ckpt"))
tune.report(**results)
def on_test_epoch_end(self, trainer, pl_module):
results = {remove_postfix(k, '_epoch'): v for k, v in trainer.logged_metrics.items()
if k.startswith('test_') and not k.endswith('_step')}
tune.report(**results)
def pl_train_with_tune(cfg, pl_module_cls, checkpoint_dir=None):
cfg = munch_to_dictconfig(Munch(cfg))
checkpoint_path = (None if not checkpoint_dir
else os.path.join(checkpoint_dir, f"{pl_module_cls.__name__}.ckpt"))
trainer_extra_args = dict(
gpus=1 if cfg.gpu else None,
progress_bar_refresh_rate=0,
resume_from_checkpoint=checkpoint_path,
callbacks=[TuneReportCheckpointCallback()]
)
pl_train(cfg, pl_module_cls, **trainer_extra_args)
def ray_train(cfg, pl_module_cls):
# We need Munch to hold tune functions. DictConfig can only hold static config.
cfg = munchconfig_to_tune_munchconfig(dictconfig_to_munch(cfg))
ray_config={
'model': cfg.model,
'dataset': cfg.dataset,
'train': cfg.train,
'seed': cfg.seed,
'wandb': cfg.wandb,
'gpu': cfg.runner.gpu_per_trial != 0.0,
}
dataset_str = cfg.dataset._target_.split('.')[-1]
model_str = cfg.model._target_.split('.')[-1]
args_str = '_'
# If we're writing to dfs or efs already, no need to sync explicitly
# This needs to be a noop function, not just False. If False, ray won't restore failed spot instances
sync_to_driver = None if not cfg.runner.nfs else lambda source, target: None
experiment = Experiment(
name=f'{dataset_str}_{model_str}',
run=partial(pl_train_with_tune, pl_module_cls=pl_module_cls),
local_dir=cfg.runner.result_dir,
num_samples=cfg.runner.ntrials if not cfg.smoke_test else 1,
resources_per_trial={'cpu': 1 + cfg.dataset.num_workers, 'gpu': cfg.runner.gpu_per_trial},
# epochs + 1 because calling trainer.test(model) counts as one epoch
stop={"training_iteration": 1 if cfg.smoke_test else cfg.train.epochs + 1},
config=ray_config,
loggers=[WandbLogger],
keep_checkpoints_num=1, # Save disk space, just need 1 for recovery
# checkpoint_at_end=True,
# checkpoint_freq=1000, # Just to enable recovery with @max_failures
max_failures=-1,
sync_to_driver=sync_to_driver, # As of Ray 1.0.0, still need this here
)
if cfg.smoke_test or cfg.runner.local:
ray.init(num_gpus=torch.cuda.device_count())
else:
try:
ray.init(address='auto')
except:
try:
with open(project_root / 'ray_config/redis_address', 'r') as f:
address = f.read().strip()
with open(project_root / 'ray_config/redis_password', 'r') as f:
password = f.read().strip()
ray.init(address=address, _redis_password=password)
except:
ray.init(num_gpus=torch.cuda.device_count())
import warnings
warnings.warn("Running Ray with just one node")
if cfg.runner.hyperband:
scheduler = AsyncHyperBandScheduler(metric='mean_accuracy', mode='max',
max_t=cfg.train.epochs + 1,
grace_period=cfg.runner.grace_period)
else:
scheduler = None
trials = ray.tune.run(experiment,
scheduler=scheduler,
# sync_config=SyncConfig(sync_to_driver=sync_to_driver),
raise_on_failed_trial=False,
queue_trials=True)
return trials
|
#Complete code below to count number of letters
fav_word = "supercalifragilisticexpialidocious"
# Your code below
count = 0
for letter in fav_word:
if letter == 'i':
count = count + 1
print(count) |
if __name__ == '__main__':
my_number = 5
while True:
user_number = int(input("Guess a number - "))
if user_number == my_number:
print("Number guessed!")
break
elif user_number < my_number:
print("Cold")
elif user_number > my_number:
print("Hot")
|
# Generated by Django 3.2 on 2021-04-09 03:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('RatingCounter', '0007_auto_20210408_1648'),
]
operations = [
migrations.AddField(
model_name='ratingcountermodel',
name='updates_number',
field=models.IntegerField(blank=True, default=1, null=True),
),
]
|
from ..core import db
from ..models import FileModel
from ..models import CommentModel
from ..models import ProjectModel
from ..models import EnvironmentModel
# from ..models import ApplicationModel
import datetime
import json
from bson import ObjectId
class RecordModel(db.Document):
project = db.ReferenceField(ProjectModel, reverse_delete_rule=db.CASCADE, required=True)
# application = db.ReferenceField(ApplicationModel)
parent = db.StringField(max_length=256)# parent record id #db.ReferenceField(RecordModel, reverse_delete_rule=db.CASCADE)
label = db.StringField()
tags = db.ListField(db.StringField())
created_at = db.StringField(default=str(datetime.datetime.utcnow()))
updated_at = db.StringField(default=str(datetime.datetime.utcnow()))
system = db.DictField() # look into providing os version, gpu infos, compiler infos.
execution = db.DictField()
preparation = db.DictField() # What are the steps to get this ready to be recorded.
inputs = db.ListField(db.DictField())
outputs = db.ListField(db.DictField())
dependencies = db.ListField(db.DictField()) # check for c++ libs here. {'type':lib|compiler|interpretor|language|software|prorietary}
possible_status = ["starting", "started", "paused", "sleeping", "finished", "crashed", "terminated", "resumed", "running", "unknown"]
status = db.StringField(default="unknown", choices=possible_status)
environment = db.ReferenceField(EnvironmentModel, reverse_delete_rule=db.CASCADE)
cloned_from = db.StringField(max_length=256)
possible_access = ["private", "protected", "public"]
access = db.StringField(default="private", choices=possible_access)
resources = db.ListField(db.StringField()) #files ids
rationels = db.ListField(db.StringField()) #Why did you do this record. What is different from others.
comments = db.ListField(db.StringField()) #comments ids
extend = db.DictField()
def clone(self):
self.cloned_from = str(self.id)
del self.__dict__['_id']
del self.__dict__['_created']
del self.__dict__['_changed_fields']
self.id = ObjectId()
def save(self, *args, **kwargs):
self.updated_at = str(datetime.datetime.utcnow())
return super(RecordModel, self).save(*args, **kwargs)
def update_fields(self, data):
for k, v in self._fields.iteritems():
if not v.required:
if k != 'created_at':
yield k, v
def update(self, data):
for k, v in self.update_fields(data):
if k in data.keys():
if k == 'created_at':
#self.created_at = datetime.datetime.strptime(data[k], '%Y-%m-%d %X')
pass
else:
setattr(self, k, data[k])
del data[k]
self.save()
if data:
body, created = RecordBodyModel.objects.get_or_create(head=self)
body.data.update(data)
body.save()
# @property
# def files(self):
# from ..models import FileModel
# return FileModel.objects(record=self).order_by('+created_at')
@property
def body(self):
return RecordBodyModel.objects(head=self).first()
@property
def duration(self):
updated_strp = datetime.datetime.strptime(str(self.updated_at), '%Y-%m-%d %H:%M:%S.%f')
created_strp = datetime.datetime.strptime(str(self.created_at), '%Y-%m-%d %H:%M:%S.%f')
# try:
# updated_strp = datetime.datetime.strptime(str(self.updated_at), '%Y-%m-%d %H:%M:%S.%f')
# except:
# updated_strp = datetime.datetime.strptime(str(self.updated_at), '%Y-%m-%d %H:%M:%S')
# try:
# created_strp = datetime.datetime.strptime(str(self.created_at), '%Y-%m-%d %H:%M:%S.%f')
# except:
# created_strp = datetime.datetime.strptime(str(self.created_at), '%Y-%m-%d %H:%M:%S')
# print str(updated_strp-created_strp)
return updated_strp-created_strp
def info(self):
data = {}
data['head'] = {'updated':str(self.updated_at),
'id': str(self.id), 'project':str(self.project.id),
'label': self.label, 'created':str(self.created_at), 'status' : self.status, 'access':self.access}
data['head']['tags'] = self.tags
data['head']['comments'] = len(self.comments)
data['head']['resources'] = len(self.resources)
data['head']['inputs'] = len(self.inputs)
data['head']['outputs'] = len(self.outputs)
data['head']['dependencies'] = len(self.dependencies)
# if self.application != None:
# data['head']['application'] = str(self.application.id)
# else:
# data['head']['application'] = None
if self.environment != None:
data['head']['environment'] = str(self.environment.id)
else:
data['head']['environment'] = None
if self.parent != None:
data['head']['parent'] = self.parent
else:
data['head']['parent'] = None
if self.body != None:
data['body'] = str(self.body.id)
else:
data['body'] = None
return data
def _comments(self):
comments = []
for com_id in self.comments:
com = CommentModel.objects.with_id(com_id)
if com != None:
comments.append(com)
return comments
def _resources(self):
resources = []
for f_id in self.resources:
f = FileModel.objects.with_id(f_id)
if f != None:
resources.append(f)
return resources
def extended(self):
data = self.info()
data['head']['system'] = self.system
data['head']['execution'] = self.execution
data['head']['preparation'] = self.preparation
data['head']['inputs'] = self.inputs
data['head']['outputs'] = self.outputs
data['head']['dependencies'] = self.dependencies
data['head']['comments'] = [comment.extended() for comment in self._comments()]
data['head']['resources'] = [resource.extended() for resource in self._resources()]
data['head']['rationels'] = self.rationels
if self.environment != None:
if self.environment.application != None:
data['head']['application'] = self.environment.application.extended()
else:
data['head']['application'] = {}
else:
data['head']['application'] = {}
data['extend'] = self.extend
# if self.application != None:
# data['head']['application'] = self.application.info()
# else:
# data['head']['application'] = {}
if self.environment != None:
data['head']['environment'] = self.environment.extended()
else:
data['head']['environment'] = {}
if self.parent != '':
data['head']['parent'] = RecordModel.objects.with_id(self.parent).info()
else:
data['head']['parent'] = {}
if self.body != None:
data['body'] = self.body.extended()
else:
data['body'] = {}
return data
def to_json(self):
data = self.extended()
return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
def summary_json(self):
data = self.info()
data['head']['inputs'] = len(self.inputs)
data['head']['outputs'] = len(self.outputs)
data['head']['dependencies'] = len(self.dependencies)
data['head']['comments'] = len(self.comments)
data['head']['resources'] = len(self.resources)
data['head']['rationels'] = len(self.rationels)
return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
class RecordBodyModel(db.Document):
updated_at = db.StringField(default=str(datetime.datetime.utcnow()))
head = db.ReferenceField(RecordModel, reverse_delete_rule=db.CASCADE, unique=True, required=True)
data = db.DictField()
extend = db.DictField()
def info(self):
data = {}
data['head'] = str(self.head.id)
data['body'] = {'updated':str(self.updated_at), 'id':str(self.id), 'content':self.data}
return data
def extended(self):
data = self.info()
data['extend'] = self.extend
return data
def to_json(self):
data = self.extended()
return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
def summary_json(self):
data = self.info()
return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.