blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30 values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2 values | text stringlengths 12 5.47M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
04c7fb7da7b3cef7315dfef3c8c84ce244170359 | Python | tcflanagan/transport | /src/tools/stability.py | UTF-8 | 13,361 | 3.5625 | 4 | [] | no_license | """Classes to monitor stability in some value."""
from time import time
from src.tools.general import simpleLinearRegression
class StabilityTrend(object):
"""A class for tracking stability based on trend.
Parameters
----------
bufferSize : int
The number of data points of which to keep track.
tolerance : float
The maximum deviation from zero which the slope can have while still
being considered stable.
timeout : float
The maximum amount of time to monitor the system.
"""
def __init__(self, bufferSize, tolerance, timeout=None):
self._bufferSize = bufferSize
self._maxAllowed = abs(tolerance)
self._minAllowed = -1.0 * abs(tolerance)
if timeout is None:
self._timeout = float('inf')
else:
self._timeout = timeout
self._times = []
self._values = []
self._length = 0
self._max = None
self._min = None
self._slope = None
self._startTime = time()
def addPoint(self, value):
"""Add a point to the monitor.
Parameters
----------
value : float
The value to add to the monitor.
"""
newTime = time()
self._times.append(newTime)
self._values.append(value)
if self._length + 1 > self._bufferSize:
self._times.pop(0)
self._values.pop(0)
else:
self._length += 1
stats = simpleLinearRegression(self._times, self._values)
self._slope = stats[0]
self._min = stats[3]
self._max = stats[4]
def isStable(self):
"""Return whether the system is stable.
Returns
-------
bool
Whether the system is stable.
"""
return self._minAllowed < self._slope < self._maxAllowed
def isTimedOut(self):
"""Return whether the monitor has timed out.
Returns
-------
bool
Whether the system has passed the timeout.
"""
return time() - self._startTime > self._timeout
def isBufferFull(self):
"""Return whether the buffer is full.
Returns
-------
bool
Whether the monitor's buffer has been filled.
"""
return self._length >= self._bufferSize
def isFinished(self):
"""Return whether the wait for stability can end.
Returns
-------
bool
Whether the software can proceed, meaning either that the buffer
is full and the system is stable or that the monitor has timed out.
"""
return (self.isBufferFull() and self.isStable()) or self.isTimedOut()
def getTrend(self):
"""Return the slope of the line formed by the data.
Returns
-------
float
The slope of the line formed by the data.
"""
return self._slope
class StabilitySetpoint(object):
"""A class for tracking stability based on proximity to a setpoint.
Parameters
----------
bufferSize : int
The number of data points of which to keep track.
setpoint : float
The desired value for the system values.
tolerance : float
The maximum deviation from zero which the slope can have while still
being considered stable.
timeout : float
The maximum amount of time to monitor the system.
"""
def __init__(self, bufferSize, setpoint, tolerance, timeout=None):
self._bufferSize = bufferSize
self._maxAllowed = setpoint + abs(tolerance)
self._minAllowed = setpoint - abs(tolerance)
if timeout is None:
self._timeout = float('inf')
else:
self._timeout = timeout
self._times = []
self._values = []
self._length = 0
self._max = None
self._min = None
self._slope = None
self._startTime = time()
def addPoint(self, value):
"""Add a point to the monitor.
Parameters
----------
value : float
The value to add to the monitor.
"""
newTime = time()
self._times.append(newTime)
self._values.append(value)
if self._length + 1 > self._bufferSize:
self._times.pop(0)
self._values.pop(0)
else:
self._length += 1
stats = simpleLinearRegression(self._times, self._values)
self._slope = stats[0]
self._min = stats[3]
self._max = stats[4]
def isStable(self):
"""Return whether the system is stable.
Returns
-------
bool
Whether the system is stable.
"""
return self._minAllowed < self._min < self._max < self._maxAllowed
def isTimedOut(self):
"""Return whether the monitor has timed out.
Returns
-------
bool
Whether the system has passed the timeout.
"""
return time() - self._startTime > self._timeout
def isBufferFull(self):
"""Return whether the buffer is full.
Returns
-------
bool
Whether the monitor's buffer has been filled.
"""
return self._length >= self._bufferSize
def isFinished(self):
"""Return whether the wait for stability can end.
Returns
-------
bool
Whether the software can proceed, meaning either that the buffer
is full and the system is stable or that the monitor has timed out.
"""
return (self.isBufferFull() and self.isStable()) or self.isTimedOut()
def getTrend(self):
"""Return the slope of the line formed by the data.
Returns
-------
float
The slope of the line formed by the data.
"""
return self._slope
class StabilityTimer(object):
"""A timer for checking for stability.
Parameters
----------
duration : float
The time in seconds over which the values should be stable before
the timer asserts that it is finished.
stability : float
The largest separation between the maximum and minimum known values
for which the timer may consider itself to be stable.
timeout : float
The maximum time in seconds to wait for the values to become
stable.
"""
def __init__(self, duration, stability, timeout=None):
self._duration = duration
self._stability = stability
self._timeout = timeout
self._times = []
self._values = []
self._startTime = time()
self._max = float('inf')
self._min = float('-inf')
def addValue(self, newValue):
"""Associate a new value with the timer.
Parameters
----------
newValue : float
The value to add to the timer.
"""
self._times.append(time())
self._values.append(newValue)
if len(self._values) == 0:
self._max = newValue
self._min = newValue
elif newValue > self._max:
self._max = newValue
elif newValue < self._min:
self._min = newValue
if not self.isStable():
self._times = [self._times[-1]]
self._values = [self._values[-1]]
self._max = newValue
self._min = newValue
def isStable(self):
"""Return whether the values are stable.
Returns
-------
bool
Whether the values associated with the specified timer are
close enough to be considered stable.
"""
return self._max - self._min < self._stability
def getStableTime(self):
"""Return how long the timer has been stable.
Returns
-------
float
How long the values associated with the timer have been
close enough to be considered stable. If the values are
*not* stable, return -1.
"""
try:
return self._times[-1] - self._times[0]
except IndexError:
return -1
def isTimeoutElapsed(self):
"""Return whether the timer has timed out.
Returns
-------
bool
Whether the timer has timed out.
"""
if self._timeout is None:
return False
try:
return self._times[-1] - self._startTime >= self._timeout
except IndexError:
return False
def isFinished(self):
"""Return whether the desired conditions have been met.
Returns
-------
bool
Whether the desired conditions have been met. Return `True`
if either the timeout has elapsed or the value has remained
stable for the specified length of time. Otherwise, return
`False`.
"""
return self.getStableTime() >= self._duration or self.isTimeoutElapsed()
def getStats(self):
"""Return the maximum and minimum values and the slope of the line.
Note that whenever a new value is added to the timer, if the new
value is outside the stability range defined by previous values, the
arrays are cleared and the maximum and minimum values are both set to
the newly added value.
Returns
-------
float
The maximum known value.
float
The minimum known value.
float
The slope of the line formed by the known values and the times
at which the respective values were added, in units/s.
"""
slope = simpleLinearRegression(self._times, self._values)[0]
return (self._max, self._min, slope)
class BufferedStabilityTimer(object):
"""A timer for checking for stability, which keeps only new points.
Parameters
----------
stability : float
The largest separation between the maximum and minimum known values
for which the timer may consider itself to be stable.
bufferSize : int
The maximum number of points to keep at any given time.
timeout : float
The maximum time in seconds to wait for the values to become
stable.
"""
def __init__(self, stability, bufferSize, timeout=None):
self._stability = stability
self._bufferSize = bufferSize
self._timeout = timeout
self._times = []
self._values = []
self._startTime = time()
def addValue(self, newValue):
"""Associate a new value with the timer.
Parameters
----------
newValue : float
The value to add to the timer.
"""
self._times.append(time())
self._values.append(newValue)
if len(self._times) > self._bufferSize:
self._times.pop(0)
self._values.pop(0)
def isBufferFull(self):
"""Return whether the buffer is full.
Returns
-------
bool
Whether the buffer is full.
"""
return len(self._times) == self._bufferSize
def isStable(self):
"""Return whether the values are stable.
Returns
-------
bool
Whether the values associated with the specified timer are
close enough to be considered stable.
"""
return max(self._values) - min(self._values) < self._stability
def isTimeoutElapsed(self):
"""Return whether the timer has timed out.
Returns
-------
bool
Whether the timer has timed out.
"""
if self._timeout is None:
return False
try:
return self._times[-1] - self._startTime >= self._timeout
except IndexError:
return False
def isFinished(self):
"""Return whether the desired conditions have been met.
Returns
-------
bool
Whether the desired conditions have been met. Return `True`
if either the timeout has elapsed or the value has remained
stable for the specified length of time. Otherwise, return
`False`.
"""
return self.isBufferFull() or self.isTimeoutElapsed()
def getStats(self):
"""Return the maximum and minimum values and the slope of the line.
Note that whenever a new value is added to the timer, if the new
value is outside the stability range defined by previous values, the
arrays are cleared and the maximum and minimum values are both set to
the newly added value.
Returns
-------
float
The maximum known value.
float
The minimum known value.
float
The slope of the line formed by the known values and the times
at which the respective values were added, in units/s.
"""
slope = simpleLinearRegression(self._times, self._values)[0]
return (max(self._values), min(self._values), slope)
| true |
66b7d7c3b7b41633b88398c75c4455f03be3a6d7 | Python | puneet4840/Numpy | /Check shape of the array using shape attribute.py | UTF-8 | 245 | 3.609375 | 4 | [] | no_license | # shape attribute is used to chekc hte shape of any array
print()
import numpy as np
a1=np.array([1,2,3,4,5])
print(a1.shape)
a2=np.random.randint(1,21,20).reshape(4,5)
print(a2.shape)
a3=np.array([[[1,2,3],[4,5,6],[7,8,9]]])
print(a3.shape) | true |
6397506c718aa0bda693b1d3a2d67b4e3702f172 | Python | Empythy/Algorithms-and-data-structures | /杨辉三角.py | UTF-8 | 814 | 3.1875 | 3 | [] | no_license | from typing import List
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
ret = []
def helper(i, j):
try:
if ret[i - 1][j - 1]:
return ret[i - 1][j - 1]
except:
if j == 1 or i == j:
return 1
return helper(i - 1, j - 1) + helper(i - 1, j)
for i in range(1, numRows + 1):
tmp_ret = []
for j in range(1, i + 1):
tmp_ret.append(helper(i, j))
ret.append(tmp_ret)
return ret
def getRow(self, rowIndex: int) -> List[int]:
ret = self.generate(rowIndex)
print(ret)
print(ret[-1])
return ret[-1]
if __name__ == "__main__":
S = Solution()
s = S.getRow(3)
| true |
bd69e804bb4ae136194f84bdb68058372c460121 | Python | X-rayLaser/Hello-RNN | /loaders.py | UTF-8 | 1,550 | 3.171875 | 3 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | from wordfreq import word_frequency
class SequenceLoader:
def __init__(self, path, max_sequences):
self._path = path
self._sequences = []
self._max_seq = max_sequences
self.load()
def load(self):
sequences = []
with open(self._path) as f:
for index, line in enumerate(f):
s = line.rstrip()
seq = self.row_to_sequence(index, s)
if len(sequences) < self._max_seq and self.keep(index, seq):
sequences.append(seq)
self._sequences = self.post_process(sequences)
def get(self, n):
return self._sequences[:n]
def keep(self, index, seq):
return True
def row_to_sequence(self, index, row):
return row
def post_process(self, sequences):
return sequences
class VocabularyLoader(SequenceLoader):
def post_process(self, sequences):
words_n_freqs = []
for w in sequences:
f = word_frequency(word=w, lang='en')
words_n_freqs.append((w, f))
sorted_tuples = sorted(words_n_freqs, key=lambda t: t[1], reverse=True)
return [w for w, f in sorted_tuples]
class UserNameLoader(SequenceLoader):
def valid_text(self, text):
for ch in text:
if ord(ch) < 0 or ord(ch) >= 128:
return False
return True
def keep(self, index, seq):
return index > 0 and self.valid_text(seq)
def row_to_sequence(self, index, row):
return row.split(',')[0]
| true |
b04e4aba06bd8a562ca9adf5c95547ef75d6d97e | Python | someoneAlready/east-text-detection-with-mxnet | /data_iter/core.py | UTF-8 | 8,816 | 2.53125 | 3 | [] | no_license | #-*- coding: utf-8 -*-
import os
import json
import traceback
class ExceptionWrapper(object):
"Wraps an exception plus traceback to communicate across threads"
def __init__(self, exc_info):
self.exc_type = exc_info[0]
self.exc_msg = "".join(traceback.format_exception(*exc_info))
class VideoSample(object):
def __init__(self, video=None, video_url=None, cover_url=None, created_time=None, pl1_labels=None, pl2_labels=None, ml1_labels=None, ml2_labels=None, mvid=None):
super(VideoSample, self).__init__()
self.video = video
self.video_url = video_url
self.cover_url = cover_url
self.created_time = created_time
self.pl1_labels = pl1_labels
self.pl2_labels = pl2_labels
self.ml1_labels = ml1_labels
self.ml2_labels = ml2_labels
self.mvid = mvid
def update(self, tag_map=None):
if self.video is None and self.video_url is not None:
self.video = os.path.split(self.video_url)[-1]
if tag_map is not None:
# infer pl1 from pl2
if self.pl1_labels is None and self.pl2_labels is not None:
self.pl1_labels = map(lambda x: tag_map.pl2_to_pl1[x], self.pl2_labels)
# infer pl1 from ml1
if self.pl1_labels is None and self.ml1_labels is not None:
self.pl1_labels = map(lambda x: tag_map.ml1_to_pl1[x], self.ml1_labels)
# infer pl2 from ml2
if self.pl2_labels is None and self.ml2_labels is not None:
self.pl2_labels = map(lambda x: tag_map.ml2_to_pl2[x], self.ml2_labels)
# infer ml1 from pl1
if self.ml1_labels is None and self.pl1_labels is not None:
self.ml1_labels = map(lambda x: tag_map.pl1_to_ml1[x], self.pl1_labels)
# infer ml1 from pl2
if self.ml1_labels is None and self.pl2_labels is not None:
self.ml1_labels = map(lambda x: tag_map.ml2_to_ml1[tag_map.ml2_to_pl2[x]], self.pl2_labels)
# infer ml2 from pl2
if self.ml2_labels is None and self.pl2_labels is not None:
self.ml2_labels = map(lambda x: tag_map.pl2_to_ml2[x], self.pl2_labels)
class TagMap(object):
def __init__(self):
self.pl1_to_pl2 = {}
self.pl2_to_pl1 = {}
self.pl1_names = {}
self.pl2_names = {}
self.ml1_to_ml2 = {}
self.ml2_to_ml1 = {}
self.ml1_names = {}
self.ml2_names = {}
self.pl1_to_ml1 = {}
self.pl2_to_ml2 = {}
self.ml1_to_pl1 = {}
self.ml2_to_pl2 = {}
self.pl1_created_time = {}
self.pl2_created_time = {}
def load(self, filename):
def _transform_key_to_int(_dict):
return dict([(int(k), v) for k, v in _dict.iteritems()])
with open(filename, 'r') as fd:
s = json.loads(fd.read())
self.pl1_names = _transform_key_to_int(s['pl1_names'])
self.pl2_names = _transform_key_to_int(s['pl2_names'])
self.pl1_to_pl2 = _transform_key_to_int(s['pl1_to_pl2'])
self.pl2_to_pl1 = _transform_key_to_int(s['pl2_to_pl1'])
self.pl1_to_ml1 = _transform_key_to_int(s['pl1_to_ml1'])
self.pl2_to_ml2 = _transform_key_to_int(s['pl2_to_ml2'])
self.pl1_created_time = _transform_key_to_int(s['pl1_created_time'])
self.pl2_created_time = _transform_key_to_int(s['pl2_created_time'])
self._infer_mtags()
def save(self, filename):
with open(filename, 'w') as fd:
s = json.dumps({
'pl1_names': self.pl1_names,
'pl2_names': self.pl2_names,
'pl1_to_pl2': self.pl1_to_pl2,
'pl2_to_pl1': self.pl2_to_pl1,
'pl1_to_ml1': self.pl1_to_ml1,
'pl2_to_ml2': self.pl2_to_ml2,
'pl1_created_time': self.pl1_created_time,
'pl2_created_time': self.pl2_created_time,
},
indent=4,
ensure_ascii=False,
sort_keys=True)
fd.write(s)
def build_from_ptags(self, filename):
for line in open(filename).readlines():
t = line.strip().split()
assert(len(t) == 3)
l2, l1, name = int(t[0]), int(t[1]), t[2] # t[0] is level2, t[1] is level1
if l1 == '0':
# Level 1
# l2 is the true label
self.pl1_names[l2] = name
self.pl1_to_pl2[l2] = set()
else:
# Level 2
if l1 not in self.pl1_to_pl2:
self.pl1_to_pl2[l1] = set()
self.pl1_to_pl2[l1].add(l2)
if l2 not in self.pl2_to_pl1:
self.pl2_to_pl1[l2] = l1
else:
assert(self.pl2_to_pl1[l2] == l1)
if l2 not in self.pl2_names:
self.pl2_names[l2] = name
else:
assert(self.pl2_names[l2] == name)
l1_num = len(self.pl1_to_pl2.keys())
l2_num = len(self.pl2_to_pl1.keys())
self.pl1_to_ml1 = dict(zip(self.pl1_to_pl2.keys(), range(l1_num)))
self.pl2_to_ml2 = dict(zip(self.pl2_to_pl1.keys(), range(l2_num)))
self._infer_mtags()
def update_ptags(self, pl2_to_pl1, pl1_names, pl2_names, pl1_created_time, pl2_created_time):
self.pl1_created_time.update(pl1_created_time)
self.pl2_created_time.update(pl2_created_time)
for pl2, pl1 in pl2_to_pl1.iteritems():
self.pl2_to_pl1[pl2] = pl1
if pl1 not in self.pl1_to_pl2:
self.pl1_to_pl2[pl1] = []
self.pl1_to_pl2[pl1].append(pl2)
for pl1, name in pl1_names.iteritems():
self.pl1_names[pl1] = name
for pl2, name in pl2_names.iteritems():
self.pl2_names[pl2] = name
self._infer_mtags()
def update_ptom(self, pl1_to_ml1, pl2_to_ml2):
self.pl1_to_ml1.update(pl1_to_ml1)
self.pl2_to_ml2.update(pl2_to_ml2)
self._infer_mtags()
def _infer_mtags(self):
for pl1 in self.pl1_to_pl2.keys():
if pl1 not in self.pl1_to_ml1:
self.pl1_to_ml1[pl1] = len(self.pl1_to_ml1)
self.ml1_names[self.pl1_to_ml1[pl1]] = self.pl1_names[pl1]
for pl2 in self.pl2_to_pl1.keys():
if pl2 not in self.pl2_to_ml2:
self.pl2_to_ml2[pl2] = len(self.pl2_to_ml2)
self.ml2_names[self.pl2_to_ml2[pl2]] = self.pl2_names[pl2]
for pl1, pl2s in self.pl1_to_pl2.iteritems():
for pl2 in pl2s:
ml1 = self.pl1_to_ml1[pl1]
ml2 = self.pl2_to_ml2[pl2]
if ml1 not in self.ml1_to_ml2:
self.ml1_to_ml2[ml1] = []
self.ml1_to_ml2[ml1].append(ml2)
for pl2, pl1 in self.pl2_to_pl1.iteritems():
ml1 = self.pl1_to_ml1[pl1]
ml2 = self.pl2_to_ml2[pl2]
self.ml2_to_ml1[ml2] = ml1
for pl1, ml1 in self.pl1_to_ml1.iteritems():
self.ml1_to_pl1[ml1] = pl1
for pl2, ml2 in self.pl2_to_ml2.iteritems():
self.ml2_to_pl2[ml2] = pl2
def l1_num_classes(self):
return len(self.ml1_names)
def l2_num_classes(self):
return len(self.ml2_names)
def get_cmd_from_pid(pid):
cmd_file = '/proc/%d/cmdline' % pid
if not os.path.exists(cmd_file):
raise ValueError('%s doesn\'t exists!' % cmd_file)
return os.popen('cat %s | xargs -0 echo' % cmd_file).read().strip()
# info is the displayed message by executing "nvidia-smi"
def parse_gpu_usage_str(info):
# TODO
gpus = {}
is_gpu_list = True
gpu_id = None
lines = info.split('\n')
k = 7
while k < len(lines):
l = lines[k]
t = l.split()
if len(t) == 0:
is_gpu_list = False
if is_gpu_list:
try:
_id = int(t[1])
gpu_id = _id
t2 = lines[k+1].split()
used_gm = int(t2[-7][:-3])
gm = int(t2[-5][:-3])
usage = int(t2[-3][:-1])
gpus[gpu_id] = {
'used_memory': used_gm,
'memory': gm,
'usage': usage,
'process': [],
}
except:
pass
else:
try:
_id = int(t[1])
pid = int(t[2])
cmd = get_cmd_from_pid(pid)
gm_used = int(t[5][:-3])
gpus[_id]['process'].append((pid, cmd, gm_used))
except:
pass
k += 1
return gpus
| true |
e367690a8d4a0ae4064c6c75c960b0e34bf50c16 | Python | johndpope/qrypto | /qrypto/types.py | UTF-8 | 1,063 | 2.640625 | 3 | [] | no_license | from typing import Any, Dict, List, Optional, Union
import pandas as pd
Timestamp = Union[int, pd.Timestamp]
"""A Timestamp can be either an integer representing a unix timestamp, or the
pandas.Timestamp class.
"""
OHLC = Dict[str, Union[Timestamp, float]]
"""
{
'datetime': ...,
'open': ...,
'high': ...,
'low': ...,
'close': ...,
'volume': ...,
}
"""
Order = Dict[str, Any]
"""
{
'id': ...,
'status': ...,
'buy_sell': ...,
'ask_price': ...,
'volume': ...,
'fill_price': ...,
'trades': ...,
'fee': ...,
}
"""
MaybeOrder = Optional[Order]
"""A MaybeOrder is either an Order or None."""
OrderBook = Dict[str, List[Dict[str, float]]]
"""
{
'asks': [ { 'price': ..., 'amount': ... }, ... ],
'bids': [ { 'price': ..., 'amount': ... }, ... ]
}
"""
Trade = Dict[str, float]
"""
{
'id': ... ,
'timestamp': ...,
'price': ...,
'amount': ...,
}
"""
| true |
f15d97589f441c2b7af533ab18784d145bf59415 | Python | packetchaos/nessus | /nessus/plugins/stop.py | UTF-8 | 359 | 2.6875 | 3 | [] | no_license | import click
from .api_wrapper import request_data
@click.command(help="Stop a Scan by Scan_ID")
@click.argument('scanid')
def stop(scanid):
try:
request_data('POST', '/scans/{}/stop'.format(scanid))
print("\nStopping your scan {} now.\n".format(scanid))
except AttributeError:
click.echo("Scan is not in the running state")
| true |
0184c8487deed47149a79b022a630e1397db870a | Python | pedrogalan/log-monitor | /mail/Mail.py | UTF-8 | 817 | 2.6875 | 3 | [] | no_license | import sys
sys.path.append('../config')
from config.Config import Config
import smtplib
class Mail:
@staticmethod
def sendMail(body):
message = Mail.__buildMessage(body)
server = Mail.__configureServer()
server.sendmail(Config.get('mail.sender'), Config.get('mail.receiver'), message)
server.quit()
@staticmethod
def __configureServer():
mailserver = smtplib.SMTP(Config.get('mail.smtp.host'))
mailserver.starttls()
mailserver.login(Config.get('mail.smtp.username'), Config.get('mail.smtp.password'))
return mailserver
@staticmethod
def __buildMessage(body):
template = 'From: {0}\nTo: {1}\nSubject: Something went wrong!\n{2}'
return template.format(Config.get('mail.sender'), Config.get('mail.receiver'), body)
| true |
8780853b1328c8720b39b924f460667ebf09e6d1 | Python | Tr-1234/seahub | /tools/avatar_migration.py | UTF-8 | 1,906 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
"""
Migrate seahub avatar files from file system to MySQL.
Usage: ./avatar_migrate.py /home/user/seahub
Note: seahub database must be MySQL.
"""
import base64
import datetime
import hashlib
import os
import sys
import MySQLdb
if len(sys.argv) != 2:
seahub_root = raw_input("Please enter root path of seahub: ")
else:
seahub_root = sys.argv[1]
host = raw_input("Please enter MySQL host:(leave blank for localhost) ")
if not host:
host = 'localhost'
user = raw_input("Please enter MySQL user: ")
passwd = raw_input("Please enter password: ")
db = raw_input("Please enter seahub database: ")
'''Read user's avatar path from MySQL-avatar_avatar and avatar_groupavatar'''
db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cur = db.cursor()
cur.execute("(SELECT avatar FROM avatar_avatar) UNION (SELECT avatar FROM avatar_groupavatar)")
rows = cur.fetchall()
'''Fetch avatar file info from file system'''
records = []
for row in rows:
avatar_path = row[0]
avatar_full_path = os.path.join(seahub_root, 'media', avatar_path)
try:
statinfo = os.stat(avatar_full_path)
except OSError as e:
print e
continue
size = statinfo.st_size
mtime = statinfo.st_mtime
mtime_str = datetime.datetime.fromtimestamp(int(mtime)).strftime('%Y-%m-%d %H:%M:%S')
with file(avatar_full_path) as f:
avatar_path = avatar_path.replace('\\', '/')
avatar_path_md5 = hashlib.md5(avatar_path).hexdigest()
binary = f.read()
encoded = base64.b64encode(binary)
records.append((avatar_path, avatar_path_md5, encoded, size, mtime_str))
'''Write avatar file to MySQL-avatar_uploaded'''
for record in records:
sql = "INSERT INTO `avatar_uploaded`(`filename`, `filename_md5`, `data`, `size`, `mtime`) VALUES ('%s', '%s', '%s', %d, '%s')" % (record)
cur.execute(sql)
db.commit()
db.close()
| true |
4a637518815a8704993538c678beb403ba090720 | Python | MaeMilMook/SV_SocketClient | /src/presentation/FileListReceiverWithPickleSize.py | UTF-8 | 1,225 | 2.71875 | 3 | [] | no_license | '''
Created on 2014. 6. 13.
@author: cho
'''
class FileListReceiverWithPickleSize:
'''
classdocs
'''
def __init__(self):
pass
def receiveFileList(self, conn):
import struct, pickle
BUF_SIZE = 12;
LEN_SIZE_BYTE = 4
TOTAL_VIEW_SIZE = 0;
READ_SIZE = 0;
#recvData = b'' - b''는 바이트니까 b''.join 하면 같은 바이트 타입끼리 조인결성가능
recvData = []
TOTAL_VIEW_SIZE = struct.unpack('>i', conn.recv(LEN_SIZE_BYTE))[0]
while READ_SIZE < TOTAL_VIEW_SIZE:
restSize = TOTAL_VIEW_SIZE - READ_SIZE
if restSize > BUF_SIZE:
data = conn.recv(BUF_SIZE)
else:
data = conn.recv(restSize)
if not data:
break
READ_SIZE = READ_SIZE + len(data)
#recvData += data
recvData.append(data)
fileList = pickle.loads(b''.join(recvData))
#Tuple 타입(viewContent, fileListCount)으로 리턴
return (fileList, len(fileList))
| true |
7285da717644d0cf218a4e8202a3745d2bcc45a8 | Python | gammernut/04_journal_v0.5.1 | /journal.py | UTF-8 | 337 | 2.59375 | 3 | [] | no_license | import os
def load(name):
# add from file if it exists.
return []
def save(name, journal_data):
filename = os.path.abspath(os.path.join('./journals/', name + '.jrl'))
print(f"......saving to: {filename}")
file_output_string = open(filename, 'w')
def add_entry(text, journal_data):
journal_data.append(text)
| true |
502afb01d00c402aed7c26ac54f65142d184a349 | Python | osamascience96/CS50 | /python/loops.py | UTF-8 | 62 | 3.546875 | 4 | [] | no_license | name = "Osama"
for character in name:
print(character)
| true |
518bc578f5e7b8ca67e94b24b5fb71ae3022d07b | Python | reeeborn/py4e | /py4e/chapter11/ex11_01.py | UTF-8 | 448 | 3.9375 | 4 | [] | no_license | # Python for Everyone
# Chapter 11 exercise 1
# Create a grep-like program
import re
filename = input('Enter File Name: ')
try:
fhand = open(filename,'r')
except:
print('file not found:',filename)
exit()
regexp = input('Enter regular expression: ')
count = 0
for line in fhand:
if re.search(regexp,line):
line = line.rstrip()
print(line)
count += 1
print(filename,'had',count,'lines that matched',regexp)
| true |
47d0f250303c749b6345f76f2caa48b9a39364da | Python | AEC-Tech/Python-Programming | /remove.py | UTF-8 | 138 | 3.9375 | 4 | [] | no_license | text = input("Enter text ")
ch = input("Enter character to be removed ")
text = text.replace(ch,'')
print("After deletion text is ",text)
| true |
f0927dbe1f0a7f959f37346f7df1612c3ed4edfe | Python | rupaliasma/MLNT | /dataloader.py | UTF-8 | 6,963 | 2.546875 | 3 | [] | no_license | from torch.utils.data import Dataset, DataLoader, TensorDataset
from torch.utils.data.dataset import random_split
import torch
import torchvision.transforms as transforms
from customtransforms import RandomHorizontalFlipTensor, RandomVerticalFlipTensor
import random
import numpy as np
from PIL import Image
import torchvision
from tqdm import tqdm
def get_all_data(dataset, num_workers=30, shuffle=False):
dataset_size = len(dataset)
data_loader = DataLoader(dataset, batch_size=dataset_size,
num_workers=num_workers, shuffle=shuffle)
all_data = {}
for i_batch, sample_batched in tqdm(enumerate(data_loader)):
all_data = sample_batched
return all_data
def flip_label(y, pattern, ratio, one_hot=True):
#Origin: https://github.com/chenpf1025/noisy_label_understanding_utilizing/blob/master/data.py
#y: true label, one hot
#pattern: 'pair' or 'sym'
#p: float, noisy ratio
#convert one hot label to int
if one_hot:
y = np.argmax(y,axis=1)#[np.where(r==1)[0][0] for r in y]
n_class = max(y)+1
#filp label
for i in range(len(y)):
if pattern=='sym':
p1 = ratio/(n_class-1)*np.ones(n_class)
p1[y[i]] = 1-ratio
y[i] = np.random.choice(n_class,p=p1)
elif pattern=='asym':
y[i] = np.random.choice([y[i],(y[i]+1)%n_class],p=[1-ratio,ratio])
#convert back to one hot
if one_hot:
y = np.eye(n_class)[y]
return y
def get_class_subset(imgs, lbls, n_classes):
selectedIdx = lbls < n_classes
return imgs[selectedIdx], lbls[selectedIdx]
class CustomCIFAR(Dataset):
def __init__(self, subset, transform=None, target_transform=None):
self.subset = subset
self.transform = transform
self.target_transform = target_transform
def __getitem__(self, index):
img, target = self.subset[index]
if self.transform:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.subset)
class CustomTensorDataset(Dataset):
"""TensorDataset with support of transforms.
"""
def __init__(self, tensors, transform=None, target_transform=None):
assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors)
self.tensors = tensors
self.transform = transform
self.target_transform = target_transform
def __getitem__(self, index):
x = self.tensors[0][index]
y = self.tensors[1][index]
if self.transform:
x = self.transform(x)
if self.target_transform is not None:
y = self.target_transform(y)
return x, y
def __len__(self):
return self.tensors[0].size(0)
class DataLoadersCreator():
def __init__(self, batch_size, num_workers, shuffle, cifar_root=r'/media/HDD2TB/rupali/Work104/Dataset/CIFAR10',
noise_pattern='sym', noise_ratio=0.5, n_classes=None):
# def __init__(self, batch_size, num_workers, shuffle, cifar_root=r'F:\CIFAR10' /media/HDD_3TB2/rupali/Dataset/CIFAR10, noise_pattern='sym', noise_ratio=0.5):
#set noise_pattern to None if no noise is intended to be added in the trainset
#set n_classes to None if you want all the classes
self.batch_size = batch_size
self.num_workers = num_workers
self.shuffle = shuffle
self.cifar_root = cifar_root
self.noise_pattern = noise_pattern
self.noise_ratio = noise_ratio
self.n_classes = n_classes
def run(self):
self.transform_augments = transforms.Compose([
#transforms.RandomSizedCrop(224),
RandomHorizontalFlipTensor(),
]) # meanstd transformation
self.transform_noaugment = transforms.Compose([
#transforms.Resize(256),
#transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406),(0.229, 0.224, 0.225)),
])
trainval_dataset = torchvision.datasets.CIFAR10(self.cifar_root, train=True, transform=self.transform_noaugment, target_transform=None, download=True)
test_dataset = torchvision.datasets.CIFAR10(self.cifar_root, train=False, transform=self.transform_noaugment, target_transform=None, download=True)
lengths = [int(len(trainval_dataset)*0.8), int(len(trainval_dataset)*0.2)]
train_dataset, val_dataset = random_split(trainval_dataset, lengths)
train_imgs, train_targets = get_all_data(train_dataset, num_workers=self.num_workers)
if self.n_classes is not None:
train_imgs, train_targets = get_class_subset(train_imgs, train_targets, self.n_classes)
if self.noise_pattern is not None:
original_train_targets_np = train_targets.numpy()
train_targets_np = flip_label(original_train_targets_np.copy(), pattern=self.noise_pattern, ratio=self.noise_ratio, one_hot=False)
n_noisy_labels = original_train_targets_np.size - (original_train_targets_np==train_targets_np).sum()
print('no of noisy labels : '+str(n_noisy_labels))
train_targets = torch.from_numpy(train_targets_np)
train_dataset = CustomTensorDataset([train_imgs, train_targets], transform=self.transform_augments)
val_imgs, val_targets = get_all_data(val_dataset, num_workers=self.num_workers)
if self.n_classes is not None:
val_imgs, val_targets = get_class_subset(val_imgs, val_targets, self.n_classes)
val_dataset = TensorDataset(val_imgs, val_targets)
if self.n_classes is not None:
test_imgs, test_targets = get_all_data(test_dataset, num_workers=self.num_workers)
test_imgs, test_targets = get_class_subset(test_imgs, test_targets, self.n_classes)
test_dataset = TensorDataset(test_imgs, test_targets)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=self.batch_size,
shuffle=self.shuffle,
num_workers=self.num_workers)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers)
val_loader = DataLoader(
dataset=val_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers)
return train_loader, val_loader, test_loader
if __name__ == "__main__":
x=DataLoadersCreator(batch_size=10, num_workers=0, shuffle=True)
tr, te, v = x.run()
for i_batch, sample_batched in tqdm(enumerate(tr)):
print('d')
print('shit') | true |
51fcdbf499c16f971e958a12c00633c15a718f0a | Python | Server250/RoomLang.py | /roomlang.py | UTF-8 | 16,239 | 3.265625 | 3 | [
"MIT"
] | permissive | import os # Used for loading and saving room files
import re # Used for loading room files
"""
author: Cameron Gemmell
github: www.github.com/Server250/
description: Contains Room data structure, as well as a loader and a saver for the RoomLang standard. Documentation available at:
"""
# The data structure for holding a room.
class Room:
def __init__(self, roomId,wid,hei,n=None,e=None,s=None,w=None,addDeets=dict()):
"""
Initialise the "Room" class.
roomId - How the room shall be referenced (one char, a-zA-Z0-9)
w - width
h - height
n,e,s,w - north, east, south and west doors respectively
addDeets - additional room information the user wants to add
"""
self.id = roomId
self.width = int(wid)
self.height = int(hei)
self.north = n
self.east = e
self.south = s
self.west = w
self.details=addDeets
def log(self):
"""Print out helpful information about a room to the console."""
ljustsize = 15
rjustsize = 6
# Print the room's ID
print("Room ID:".ljust(ljustsize)+self.id.rjust(rjustsize))
# Print dimensions of the room
print("Dimensions:".ljust(ljustsize)+(str(self.width)+"x"+str(self.height)).rjust(rjustsize))
# Print the locations doors lead to
print("Doors:")
if (self.north): print("N -".rjust(8).ljust(ljustsize)+str(self.north).rjust(rjustsize))
if (self.east): print("E -".rjust(8).ljust(ljustsize)+str(self.east).rjust(rjustsize))
if (self.south): print("S -".rjust(8).ljust(ljustsize)+str(self.south).rjust(rjustsize))
if (self.west): print("W -".rjust(8).ljust(ljustsize)+str(self.west).rjust(rjustsize))
def move(self,d,source=None):
"""
Return the room that will be visited by moving in direction d (n,e,s,w), using source as the room list
"""
if (source==None): raise ValueError("No room set was supplied to 'move' function.")
if (str(d).lower()[0] in [str("n"),"e","s","w"]):
# if d is n,e,s,w
if (d.lower()[0]=="n") and (self.north!=None):
if(self.north in source):
print("MOVING NORTH\n")
return source.get(self.north)
if (d.lower()[0]=="e") and (self.east!=None):
if(self.east in source):
print("MOVING EAST\n")
return source.get(self.east)
if (d.lower()[0]=="s") and (self.south!=None):
if(self.south in source):
print("MOVING SOUTH\n")
return source.get(self.south)
if (d.lower()[0]=="w") and (self.west!=None):
if(self.west in source):
print("MOVING WEST\n")
return source.get(self.west)
# If a door hasn't activated, door doesn't exist. Return current room
return self
# If reaches this point, an incorrect direction was passed through
else: raise ValueError("A direction should be 'n', 'e', 's' or 'w'!")
def RoomLoader(fp):
"""Load a set of rooms from file fp and return it as a dict"""
print("RoomLang loading rooms...\t",end="") # Print success or error on same line
if (os.path.isfile(fp)):
#print("there is a file named that") # DEBUGGING CODE
rf = open(fp, "r") # Open the room file in readonly mode
if (rf.mode == "r"): # If successfully opened
lines = rf.read().split("\n")
lines.extend("\n") # Artificially add a blank line to the end, this means the end of the last room is found correctly
numLines = len(lines) # Store number of lines in file
start = 0 # Start of room assumed to be beginning of file
end = numLines # End of room assumed to be end of file
outputDict = dict()
allowedIdRegex = re.compile(r"[a-zA-Z0-9]")
allowedLineStarts = re.compile(r":") # Special line starts that mean something
extraInfoRegex = re.compile(r":([a-zA-Z ]+):([a-zA-Z ]+)") # Info for deconstructing additional room info
while True: # Start of do-while loop to find multiple rooms
# Variables for tracking properties of read room
newId = "" # Hold the id of the loaded room
newWid, newHei = 0,0 # Hold the height and width of the loaded room
newN, newE, newS, newW = None,None,None,None # Hold directions for doors loaded
addDict = dict() # Dictionary to hold loaded additional details
# Loop from the assumed start to the assumed end of the room
for i in range(start,end):
# Find the actual start of the next room (whitespace and comments should be allowed)
if (lines[i]): # Find out if there is a line there
if (re.match(allowedIdRegex,lines[i][0])): # If first char of a line is an id
start=i # The start of the next room is here
newId=lines[i][0] # The ID for the room has been found
# Find the actual end of the room, always assumes the end is eof for limiting
for j in range(start+1, numLines-1):
# If the first char of a line isn't a '#' or there isn't a line, this signals the end of the room
if not(lines[j+1]) or (j==numLines-2) or ((not(lines[j+1][0]=="#")) and (not(lines[j+1]) or (lines[j+1][0]==":"))): # Find the end of the room
end = j+1
# DO SIZE WORK HERE before end is repositioned
newHei, newWid = end-start, len(lines[start])
# Find the doors in the room
newN=re.search(allowedIdRegex, lines[start][1:]) # Find an ID on the first line of the room, missing the first char
if newN:
newN=newN[0]
newS=re.search(allowedIdRegex, lines[end-1]) # Find an ID on the last line of the room
if newS:
newS=newS[0]
# Loop through the lines of the room to find side doors
for x in range(start+1,end):
if (newW==None): # If not found a western door yet
newW=re.search(allowedIdRegex, lines[x][0]) # Should always be a character at left side, so if it is a id it is the door
if newW:
newW=newW[0]
if (len(lines[x])==newWid) and (newE==None): # If the line has characters all the way to the right (East) side and not found east door yet
newE=re.search(allowedIdRegex, lines[x][newWid-1])
if newE:
newE=newE[0]
# Check for any extra information included in the room
for k in range (end, numLines):
if lines[k] and (re.match(allowedLineStarts,lines[k][0])): # If not a newline and is a special line start
#print("DEALING WITH EXTRA INFO - " + lines[k]) # DEBUGGING
loadedDetail=re.search(extraInfoRegex,lines[k])
#print("LOADED: " + str(loadedDetail)) # DEBUGGING
addDict[loadedDetail[1]] = loadedDetail[2] # Load the new detail into the dictionary
end=k # Update end to after the additional details (as this is used as next start point)
else:
break
break
break
# Create the room object to be added to the Room List
loadedRoom = Room(newId, newWid, newHei, newN,newE,newS,newW, addDict)
outputDict[newId]=loadedRoom
if (end>=numLines-2): # End of do-while loop to detect eof (-2 to excuse whitespace used as allowances for other algorithms)
break
else: # If another room should be found, reset 'start' to after end line and 'end' to numLines to assume this is final room
start = end
end = numLines
print("Rooms loaded successfully.")
# RETURN HERE
return outputDict
else: raise ValueError("The file supplied to RoomLoader() does not exist. Make sure you include the file extension!")
# Utility function to save room to file
def RoomSave(f, r):
# Used for writing doors with correct padding
halfW = int(r.width/2)
halfH = int((r.height)/2)
#print("Room height: " + str(r.height) + "; Half height: " + str(halfH))
f.write(r.id)
if (r.north==None):
f.write(("#"*(r.width-1)) + "\n")
else:
f.write(("#"*(halfW)) + r.north + ("#"*((r.width-halfW)-2)) + "\n") # r.width - halfW used to make sure odd numbers written without being rounded twice/not at all
f.write(("#"+(" "*(r.width-2))+"#\n")*(halfH-1))
if (r.west==None):
f.write("#")
else:
f.write(r.west)
f.write(" "*(r.width-2))
if (r.east==None):
f.write("#")
else:
f.write(r.east)
f.write("\n")
f.write(("#" + " "*(r.width-2) + "#\n")*((r.height)-(halfH+2)))
if (r.south==None):
f.write(("#"*(r.width)) + "\n")
else:
f.write(("#"*(halfW)) + r.south + ("#"*((r.width-halfW)-1)) + "\n") # r.width - halfW used to make sure odd numbers written without being rounded twice/not at all
# Print additional info
for (k,v) in r.details.items():
f.write(":"+k+":"+v+"\n")
f.write("\n")
# Function for saving rooms to disk
def RoomSaver(roomList, location, mode):
"""
Save the rooms stored in roomList to a file at location. To overwrite an existing file, use "o"verwrite mode. To append to the end of the existing file, use "a"ppend mode. append by default
"""
# Validate the input of the mode
mode = str(mode)
if not (mode == "o" or mode == "a" or mode=="O" or mode=="A"): # If a valid mode not entered
raise ValueError("Invalid argument supplied to RoomSaver: Use either 'a' for append mode or 'o' for overwrite mode.")
# Check location to see if existing file
fileExists = os.path.isfile(location)
print("RoomLang loading rooms...\t",end="")
# Append mode will add to end so comments are intact
if ((mode=="a" or mode=="A") and (fileExists)):
print("Append Mode...\t",end="")
f = open(location,"r")
fids = list()
# Get existing IDs
fcontents = f.read().split("\n")
roomIdRegex = re.compile(r'[a-zA-Z0-9]+')
#print("FCONTENTS: " + str(fcontents))
for fl in range(len(fcontents)):
if fcontents[fl] and re.match(roomIdRegex,fcontents[fl][0]):
if (not(fcontents[fl][0] in fids)):
fids.extend(fcontents[fl][0])
f = open(location,"a+")
for rm in roomList:
if (not(rm in fids)):
print(rm)
r = roomList[rm]
# Used for writing doors with correct padding
halfW = int(r.width/2)
halfH = int((r.height)/2)
#print("Room height: " + str(r.height) + "; Half height: " + str(halfH))
f.write(r.id)
if (r.north==None):
f.write(("#"*(r.width-1)) + "\n")
else:
f.write(("#"*(halfW)) + r.north + ("#"*((r.width-halfW)-2)) + "\n") # r.width - halfW used to make sure odd numbers written without being rounded twice/not at all
f.write(("#"+(" "*(r.width-2))+"#\n")*(halfH-1))
if (r.west==None):
f.write("#")
else:
f.write(r.west)
f.write(" "*(r.width-2))
if (r.east==None):
f.write("#")
else:
f.write(r.east)
f.write("\n")
f.write(("#" + " "*(r.width-2) + "#\n")*((r.height)-(halfH+2)))
if (r.south==None):
f.write(("#"*(r.width)) + "\n")
else:
f.write(("#"*(halfW)) + r.south + ("#"*((r.width-halfW)-1)) + "\n") # r.width - halfW used to make sure odd numbers written without being rounded twice/not at all
# Print additional info
for (k,v) in r.details.items():
f.write(":"+k+":"+v+"\n")
f.write("\n")
# Overwrite mode will just make a whole new file
else: # Overwrite mode
print("Overwrite Mode...\t",end="")
# Open file
f = open(location,"w+") # '+' means if file doesn't exist then it'll be created
# Straight go down room list and save to file
for rm in roomList:
r = roomList[rm]
# Used for writing doors with correct padding
halfW = int(r.width/2)
halfH = int((r.height)/2)
#print("Room height: " + str(r.height) + "; Half height: " + str(halfH))
f.write(r.id)
if (r.north==None):
f.write(("#"*(r.width-1)) + "\n")
else:
f.write(("#"*(halfW)) + r.north + ("#"*((r.width-halfW)-2)) + "\n") # r.width - halfW used to make sure odd numbers written without being rounded twice/not at all
f.write(("#"+(" "*(r.width-2))+"#\n")*(halfH-1))
if (r.west==None):
f.write("#")
else:
f.write(r.west)
f.write(" "*(r.width-2))
if (r.east==None):
f.write("#")
else:
f.write(r.east)
f.write("\n")
f.write(("#" + " "*(r.width-2) + "#\n")*((r.height)-(halfH+2)))
if (r.south==None):
f.write(("#"*(r.width)) + "\n")
else:
f.write(("#"*(halfW)) + r.south + ("#"*((r.width-halfW)-1)) + "\n") # r.width - halfW used to make sure odd numbers written without being rounded twice/not at all
# Print additional info
for (k,v) in r.details.items():
f.write(":"+k+":"+v+"\n")
f.write("\n")
#print("ROOM PRINTED")
f.close() # Close the file
print("Rooms saved successfully.")
# Program Entry Point
if __name__=="__main__":
print("This module is intended to be imported by your project, not run itself.\n")
# Load rooms from file
testList = RoomLoader("rooms.txt")
# Log all loaded rooms
#for k in testList:
# testList[k].log()
# print("\n")
# Save rooms
RoomSaver(testList, "roomsSaved.txt", "a")
| true |
ccfbc9d23812706ee6668413d5b63417662067e0 | Python | SBU-BMI/quip_cnn_segmentation | /training-data-synthesis/draw_real.py | UTF-8 | 1,659 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | import numpy as np
from PIL import Image
from os import listdir
from os.path import isfile, join
size0 = 400;
size1 = 400;
npatch_per_tile = 3;
def sample_overlap(x, y, fx, fy, xlen, ylen):
if fx <= x and x <= fx+xlen and fy <= y and y <= fy+ylen:
return True;
if fx <= x+xlen and x+xlen <= fx+xlen and fy <= y and y <= fy+ylen:
return True;
if fx <= x and x <= fx+xlen and fy <= y+ylen and y+ylen <= fy+ylen:
return True;
if fx <= x+xlen and x+xlen <= fx+xlen and fy <= y+ylen and y+ylen <= fy+ylen:
return True;
return False;
def sample_xy_fxfy(size0, size1, xlen, ylen):
x, y, fx, fy = 0, 0, 0, 0;
while sample_overlap(x, y, fx, fy, xlen, ylen):
x, y = int(np.random.rand()*size0), int(np.random.rand()*size1);
fx, fy = int(np.random.rand()*size0), int(np.random.rand()*size1);
return x, y, fx, fy;
patn = 0;
tile_path = './nuclei_synthesis_40X_online/real_tiles/';
paths = [f for f in listdir(tile_path) if isfile(join(tile_path, f))];
fid = open('output/real_info.txt', 'w');
for path in paths:
full_tile = np.array(Image.open(join(tile_path, path)).convert('RGB'));
for n in range(npatch_per_tile):
x, y, fx, fy = sample_xy_fxfy(full_tile.shape[0]-size0, full_tile.shape[1]-size1, size0, size1);
patch0 = full_tile[x:x+size0, y:y+size1, :];
patch1 = full_tile[fx:fx+size0, fy:fy+size1, :];
Image.fromarray(patch0).save('./output/real/image0_{}.png'.format(patn));
Image.fromarray(patch1).save('./output/real/image1_{}.png'.format(patn));
fid.write('{} {}\n'.format(patn, path));
patn += 1;
fid.close();
| true |
f9287e90cb0d8a754722eb7d4da276e5f5edb667 | Python | leticiadedeus/learningPython | /Jokenpo.py | UTF-8 | 796 | 3.578125 | 4 | [] | no_license | import random
import time
print('0 - rock \n'
'1 - paper \n'
'2 - scissors ')
user = int(input('Choose your fighter: '))
pc = random.randint(0, 2)
print('JO')
time.sleep(0.6)
print('KEN')
time.sleep(0.6)
print('PÔ')
time.sleep(0.6)
if user == pc:
print('pc and user tied')
elif user == 0 and pc == 2:
print('User wins, user was rock and pc was scissors')
elif user == 1 and pc == 0:
print('User wins, user was paper and pc was rock')
elif user == 2 and pc == 1:
print('User wins, user was scissors and pc was paper')
elif pc == 0 and user == 2:
print('Pc wins, pc was rock and user was scissors')
elif pc == 1 and user == 0:
print('Pc wins, pc was paper and user was rock')
elif user == 2 and pc == 1:
print('Pc wins, pc was scissors and user was paper')
| true |
577a937c2036c825881a5d88454c34abb2e332c9 | Python | koenkeune/parchis_model | /testing/parchisTests.py | UTF-8 | 12,108 | 3.015625 | 3 | [] | no_license | from model.game import *
from scenarios import *
import copy
class RulesTester():
def __init__(self, game):
self.game = game
self.scenes = Scenarios()
def check_rule1(self):
numPlayers = len(self.game.players)
starts = []
for i in range(100):
starts.append(self.game.throwDiceForStart())
return(len(set(starts)) == numPlayers)
def check_rule2_case1(self, diceNumber):
pl = 0
self.game.board.filledBoard = copy.deepcopy(self.scenes.Test2_case1.BOARD) # deepcopy to be able to run it multiple times
self.game.players[pl].pawns = copy.deepcopy(self.scenes.Test2_case1.PLAYER0PAWNS)
self.game.players[pl].pawnsHome = self.scenes.Test2_case1.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test2_case1.PLAYER0PAWNSFINISHED
self.game.makeMove(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test2_case1.BOARDAFTER) # true for dicenumbers larger than 1
def check_rule2_case2(self):
pl = 3
self.game.board.filledBoard = self.scenes.Test2_case2.BOARD
self.game.players[pl].pawns = self.scenes.Test2_case2.PLAYER3PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test2_case2.PLAYER3PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test2_case2.PLAYER3PAWNSFINISHED
diceNumber = 3
self.game.makeMove(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test2_case2.BOARDAFTER)
def check_rule2_case3(self): # can't pass through own bridge
pl = 3
self.game.board.filledBoard = self.scenes.Test2_case3.BOARD
self.game.players[pl].pawns = self.scenes.Test2_case3.PLAYER3PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test2_case3.PLAYER3PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test2_case3.PLAYER3PAWNSFINISHED
diceNumber = 2
self.game.makeMove(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test2_case3.BOARDAFTER)
def check_rule3_case1(self):
pl = 2
self.game.board.filledBoard = self.scenes.Test3_case1.BOARD
self.game.players[pl].pawns = self.scenes.Test3_case1.PLAYER2PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test3_case1.PLAYER2PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test3_case1.PLAYER2PAWNSFINISHED
diceNumber = 2
self.game.playOneThrow(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test3_case1.BOARDAFTER)
def check_rule3_case2(self): # two captures in a row
pl = 2
self.game.board.filledBoard = self.scenes.Test3_case2.BOARD
self.game.players[pl].pawns = self.scenes.Test3_case2.PLAYER2PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test3_case2.PLAYER2PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test3_case2.PLAYER2PAWNSFINISHED
diceNumber = 2
self.game.playOneThrow(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test3_case2.BOARDAFTER)
def check_rule4(self):
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test4.BOARD
self.game.players[pl].pawns = self.scenes.Test4.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test4.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test4.PLAYER0PAWNSFINISHED
diceNumber = 5
self.game.makeMove(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test4.BOARDAFTER)
def check_rule4_1a(self):
pl = 1
self.game.board.filledBoard = self.scenes.Test4_1a.BOARD
self.game.players[pl].pawns = self.scenes.Test4_1a.PLAYER1PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test4_1a.PLAYER1PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test4_1a.PLAYER1PAWNSFINISHED
self.game.players[pl].strategy = 'furthest'
diceNumber = 5
self.game.makeMove(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test4_1a.BOARDAFTER)
def check_rule4_1b(self):
pl = 1
self.game.board.filledBoard = self.scenes.Test4_1b.BOARD
self.game.players[pl].pawns = self.scenes.Test4_1b.PLAYER1PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test4_1b.PLAYER1PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test4_1b.PLAYER1PAWNSFINISHED
self.game.players[pl].strategy = 'furthest'
diceNumber = 5
self.game.makeMove(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test4_1b.BOARDAFTER)
def check_rule4_2(self):
pl = 2
self.game.board.filledBoard = self.scenes.Test4_2.BOARD
self.game.players[pl].pawns = self.scenes.Test4_2.PLAYER2PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test4_2.PLAYER2PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test4_2.PLAYER2PAWNSFINISHED
self.game.players[pl].strategy = 'furthest'
diceNumber = 5
self.game.playOneThrow(pl, diceNumber)
return(self.game.board.filledBoard == self.scenes.Test4_2.BOARDAFTER)
def check_rule5(self):
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test5.BOARD
self.game.players[pl].pawns = self.scenes.Test5.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test5.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test5.PLAYER0PAWNSFINISHED
diceNumbers = [6, 3]
self.game.playOneTurn(pl, diceNumbers)
return(self.game.board.filledBoard == self.scenes.Test5.BOARDAFTER)
def check_rule5_1(self):
pl = 0
self.game.players[pl].pawnsHome = 0
return(self.game.determineStepsForward(pl, 6) == 7)
def check_rule5_2_case1(self):
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test5_2_case1.BOARD
self.game.players[pl].pawns = self.scenes.Test5_2_case1.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test5_2_case1.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test5_2_case1.PLAYER0PAWNSFINISHED
self.game.players[pl].strategy = 'furthest'
diceNumbers = [6, 1]
self.game.playOneTurn(pl, diceNumbers)
return(self.game.board.filledBoard == self.scenes.Test5_2_case1.BOARDAFTER)
def check_rule5_2_case2(self):
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test5_2_case2.BOARD
self.game.players[pl].pawns = self.scenes.Test5_2_case2.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test5_2_case2.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test5_2_case2.PLAYER0PAWNSFINISHED
self.game.players[pl].strategy = 'furthest'
diceNumbers = [6, 1]
self.game.playOneTurn(pl, diceNumbers)
return(self.game.board.filledBoard == self.scenes.Test5_2_case2.BOARDAFTER)
def check_rule5_3(self):
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test5_3.BOARD
self.game.players[pl].pawns = self.scenes.Test5_3.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test5_3.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test5_3.PLAYER0PAWNSFINISHED
diceNumbers = [6, 6, 6]
self.game.playOneTurn(pl, diceNumbers)
return(self.game.board.filledBoard == self.scenes.Test5_3.BOARDAFTER)
def check_rule5_3a_case1(self): # boundary test 1
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test5_3a_case1.BOARD
self.game.board.filledFinishLine = self.scenes.Test5_3a_case1.FINISHLINE
self.game.players[pl].pawns = self.scenes.Test5_3a_case1.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test5_3a_case1.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test5_3a_case1.PLAYER0PAWNSFINISHED
self.game.sixesThrown = 0
diceNumbers = [6, 6, 6]
self.game.playOneTurn(pl, diceNumbers)
return(self.game.board.filledBoard == self.scenes.Test5_3a_case1.BOARDAFTER and
self.game.board.filledFinishLine == self.scenes.Test5_3a_case1.FINISHLINEAFTER)
def check_rule5_3a_case2(self): # boundary test 2
pl = 0 # turn of player
self.game.board.filledBoard = self.scenes.Test5_3a_case2.BOARD
self.game.board.filledFinishLine = self.scenes.Test5_3a_case2.FINISHLINE
self.game.players[pl].pawns = self.scenes.Test5_3a_case2.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test5_3a_case2.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test5_3a_case2.PLAYER0PAWNSFINISHED
self.game.sixesThrown = 0
diceNumbers = [6, 6, 6]
self.game.playOneTurn(pl, diceNumbers)
return(self.game.board.filledBoard == self.scenes.Test5_3a_case2.BOARDAFTER and
self.game.board.filledFinishLine == self.scenes.Test5_3a_case2.FINISHLINEAFTER)
def check_rule6(self, diceNumber):
pl = 0 # turn of player
self.game.board.filledBoard = copy.deepcopy(self.scenes.Test6.BOARD)
self.game.board.filledFinishLine = copy.deepcopy(self.scenes.Test6.FINISHLINE)
self.game.players[pl].pawns = copy.deepcopy(self.scenes.Test6.PLAYER0PAWNS)
self.game.players[pl].pawnsHome = self.scenes.Test6.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = copy.deepcopy(self.scenes.Test6.PLAYER0PAWNSFINISHED)
self.game.players[pl].strategy = 'furthest'
self.game.playOneThrow(pl, diceNumber)
if diceNumber == 1:
return(self.game.board.filledBoard == self.scenes.Test6.BOARDAFTER1 and
self.game.board.filledFinishLine == self.scenes.Test6.FINISHLINEAFTER1)
if diceNumber == 2:
return(self.game.board.filledBoard == self.scenes.Test6.BOARDAFTER2 and
self.game.board.filledFinishLine == self.scenes.Test6.FINISHLINEAFTER2)
elif diceNumber == 3:
return(self.game.board.filledBoard == self.scenes.Test6.BOARDAFTER3 and
self.game.board.filledFinishLine == self.scenes.Test6.FINISHLINEAFTER3)
else:
return(False)
def check_rule7(self):
pl = 0
self.game.board.filledBoard = self.scenes.Test7.BOARD
self.game.board.filledFinishLine = self.scenes.Test7.FINISHLINE
self.game.players[pl].pawns = self.scenes.Test7.PLAYER0PAWNS
self.game.players[pl].pawnsHome = self.scenes.Test7.PLAYER0PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.Test7.PLAYER0PAWNSFINISHED
diceNumber = 2
self.game.playOneTurn(pl, [diceNumber])
assert self.game.board.filledFinishLine == self.scenes.Test7.FINISHLINEAFTER
assert self.game.someoneWon == True
assert self.game.winner == pl
def check_safe_strat(self):
pl = 2
self.game.board.filledBoard = self.scenes.TestSafe.BOARD
self.game.players[pl].pawns = self.scenes.TestSafe.PLAYER2PAWNS
self.game.players[pl].pawnsHome = self.scenes.TestSafe.PLAYER2PAWNSHOME
self.game.players[pl].pawnsFinished = self.scenes.TestSafe.PLAYER2PAWNSFINISHED
self.game.players[pl].strategy = 'safest'
diceNumber = 3
self.game.playOneTurn(pl, [diceNumber])
return(self.game.board.filledBoard == self.scenes.TestSafe.BOARDAFTER and
self.game.board.filledFinishLine == self.scenes.TestSafe.FINISHLINEAFTER)
| true |
6d2d14d4eba4e3a3f574a2c7734ed693105b455f | Python | Chuset21/Learning-Python | /basics/chapter-one/password_checker.py | UTF-8 | 310 | 3.734375 | 4 | [] | no_license | def main():
username = input('Enter your username: ')
password = input("Enter your password: ")
password_length = len(password)
hidden_password = '*' * password_length
print(f'{username}, your password {hidden_password}, is {password_length} characters long')
if __name__ == '__main__':
main()
| true |
e1461ebff27dd6df4ed5b73bb862b3bebfd826ad | Python | stivo32/python_wg | /8/At_work/bandit.py | UTF-8 | 704 | 4.03125 | 4 | [] | no_license | from random import choice, randint
class Cell(object):
def __init__(self, max_value):
self.max_value = max_value
def roll(self):
return randint(1, self.max_value)
class Bandit(object):
max_cell_value = 3
def __init__(self, cell_number=3):
self.cells = [
Cell(self.max_cell_value)
for _ in range(cell_number)
]
def _roll(self):
return [cell.roll() for cell in self.cells]
def action(self):
cell_values = self._roll()
x, y, z = cell_values
if x == y == z:
return 'You won', cell_values
else:
return 'You failed', cell_values
def main():
bandit = Bandit(cell_number=3)
result, values = bandit.action()
print result, values
if __name__ == '__main__':
main() | true |
59df8a26b17da31ce68dc879ebf1a2a27a804606 | Python | toru-ver4/sample_code | /2019/009_python_subprocess/subprocess_ctl.py | UTF-8 | 1,377 | 3.015625 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
subprocess を使って exe ファイルと通信する。
"""
# import libraries
import os
from subprocess import Popen, PIPE
from threading import Thread
import time
# define
STDOUT_THREAD_TIMEOUT_SEC = 1.0
def print_stdout(proc):
while True:
line = proc.stdout.readline()
print(line.decode('utf-8').rstrip())
if not line and proc.poll() is not None:
break
class SubprocessCtrl():
def __init__(self, cmd_args="./bin/subprocess.exe"):
self.proc = Popen(cmd_args, stdin=PIPE, stdout=PIPE)
self.stdout_thread = Thread(target=print_stdout, args=(self.proc,))
self.stdout_thread.start()
def exit(self):
self.stdout_thread.join(timeout=STDOUT_THREAD_TIMEOUT_SEC)
def send_str(self, strings=b"EOFEOF\n"):
"""
子プロセスの stdin に文字列を送る。
文字列はあらかじめ binary にしておくこと。
"""
self.proc.stdin.write(strings)
self.proc.stdin.flush()
if __name__ == '__main__':
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# check_communication_exe_files()
p = SubprocessCtrl()
p.send_str(b"omaehadareda\n")
time.sleep(2.0)
p.send_str(b"chikubi\n")
time.sleep(2.0)
p.send_str(b"EOFEOF\n")
time.sleep(2.0)
p.exit()
| true |
002fcdaefe2fde4aabdecad057ba666c9abb343c | Python | woutdenolf/spectrocrunch | /spectrocrunch/utils/listtools.py | UTF-8 | 4,307 | 2.984375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import collections
import operator
import itertools
import numpy as np
from . import instance
def flatten(l):
"""Flatten iterables
Args:
l(anything):
Returns:
list
"""
if instance.isiterable(l) and not instance.isstring(l):
try:
it = iter(l)
except TypeError:
yield l
else:
for el in it:
for el2 in flatten(el):
yield el2
else:
yield l
def numpy_flatten(l):
return np.asarray(list(flatten(l)))
def listadvanced_bool(lst, barr, bnot=False):
"""Advanced list indexing: boolean array
Args:
lst(list):
barr(array or bool): array of booleans
Returns:
list
"""
if bnot:
barr = map(operator.not_, barr)
return list(itertools.compress(lst, barr))
def listadvanced_int(lst, ind):
"""Advanced list indexing: integer array
Args:
lst(list):
ind(array):
Returns:
list
"""
return [lst[i] for i in ind]
def listadvanced(lst, ind):
"""Advanced list indexing: integer or bool array
Args:
lst(list):
ind(array):
Returns:
list
"""
if instance.isboolsequence(ind):
return listadvanced_bool(lst, ind)
else:
return listadvanced_int(lst, ind)
def where(lst, func):
"""Indices are particular elements
Args:
lst(list):
func(callable): one argument
Returns:
list
"""
return [i for i, l in enumerate(lst) if func(l)]
def sort2lists(list1, list2):
"""Sort list1 and list2 based on list1
Args:
list1(list):
list2(list):
Returns:
list,list
"""
return tuple(
list(t) for t in zip(*sorted(zip(list1, list2), key=operator.itemgetter(0)))
)
def unique2lists(list1, list2, add=False):
"""Unique list1 and list2 based on list1
Args:
list1(list):
list2(list):
add(Optional(bool)): add list2 elements with list1 duplicates
Returns:
list,list
"""
if add:
cntr = collections.Counter()
def cntr_add(x, y):
b = x not in cntr
cntr[x] += y
return b
list1 = [x1 for x1, x2 in zip(list1, list2) if cntr_add(x1, x2)]
list2 = [cntr[x1] for x1 in list1]
return list1, list2
else:
seen = set()
seen_add = seen.add
list1, list2 = tuple(
zip(
*[
[x1, x2]
for x1, x2 in zip(list1, list2)
if not (x1 in seen or seen_add(x1))
]
)
)
return list(list1), list(list2)
def sumrepeats(labels, counts):
"""
Args:
list1(list):
list2(list):
Returns:
list,list
"""
c = collections.Counter()
for l, cnt in zip(labels, counts):
c.update({l: cnt})
return c.keys(), c.values()
def swap(lst, i, j):
if i != j:
lst[i], lst[j] = lst[j], lst[i]
return lst
def roll(lst, n):
if n != 0:
n = abs(n)
lst = list(itertools.islice(itertools.cycle(lst), n, n + len(lst)))
return lst
def move(lst, i, j):
if i != j:
lst.insert(j, lst.pop(i))
return lst
def length(x):
try:
return len(x)
except TypeError:
return 1
def aslist(x):
try:
return list(x)
except:
return [x]
def filterfalse(predicate, iterable):
# filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
if predicate is None:
predicate = bool
for x in iterable:
if not predicate(x):
yield x
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
| true |
bbfc39b5c6767a8e0a88b281eaf0b38fd791bca2 | Python | Zer0101/colorize-nn | /app/lib/color/image.py | UTF-8 | 2,926 | 2.75 | 3 | [] | no_license | import tensorflow as tf
class ImageTransformer:
@staticmethod
def rgb_transform_filter():
transform_filter = tf.constant(
[[[
[0.299, -0.169, 0.499],
[0.587, -0.331, -0.418],
[0.114, 0.499, -0.0813]
]]], name="rgb_to_yuv_transform_filter"
)
return transform_filter
@staticmethod
def grb_bias():
bias = tf.constant([0., 0.5, 0.5], name="rgb_to_yuv_bias")
return bias
@staticmethod
def yuv_transform_filter():
transform_filter = tf.constant(
[[[
[1., 1., 1.],
[0., -0.34413999, 1.77199996],
[1.40199995, -0.71414, 0.]
]]], name="yuv_to_rgb_transform_filter"
)
return transform_filter
@staticmethod
def yuv_bias():
bias = tf.constant([-179.45599365, 135.45983887, -226.81599426], name="yuv_to_rgb_bias")
return bias
def from_rgb_to_yuv(self, rgb):
# Get RGB to YUV transform matrix
# transform_filter = tf.get_variable("rgb_to_yuv_transform_filter", initializer=self.rgb_transform_filter())
transform_filter = tf.constant(
[[[
[0.299, -0.169, 0.499],
[0.587, -0.331, -0.418],
[0.114, 0.499, -0.0813]
]]], name="rgb_to_yuv_transform_filter"
)
# Get transformation bias
# bias = tf.get_variable("rgb_to_yuv_bias", initializer=self.grb_bias())
bias = tf.constant([0., 0.5, 0.5], name="rgb_to_yuv_bias")
yuv = tf.nn.conv2d(rgb, transform_filter, [1, 1, 1, 1], 'SAME')
yuv = tf.nn.bias_add(yuv, bias)
return yuv
def from_yuv_to_rgb(self, yuv):
# Get YUV to RGB transform matrix
# transform_filter = tf.get_variable("yuv_to_rgb_transform_filter", initializer=self.yuv_transform_filter())
transform_filter = tf.constant(
[[[
[1., 1., 1.],
[0., -0.34413999, 1.77199996],
[1.40199995, -0.71414, 0.]
]]], name="yuv_to_rgb_transform_filter"
)
# Get transformation bias
# bias = tf.get_variable("yuv_to_rgb_bias", initializer=self.yuv_bias())
bias = tf.constant([-179.45599365, 135.45983887, -226.81599426], name="yuv_to_rgb_bias")
yuv = tf.multiply(yuv, 255)
rgb = tf.nn.conv2d(yuv, transform_filter, [1, 1, 1, 1], 'SAME')
rgb = tf.nn.bias_add(rgb, bias)
rgb = tf.maximum(rgb, tf.zeros(rgb.get_shape(), dtype=tf.float32))
rgb = tf.minimum(rgb, tf.multiply(tf.ones(rgb.get_shape(), dtype=tf.float32), 255))
rgb = tf.div(rgb, 255)
return rgb
def from_rgb_to_grayscale(self, image):
return tf.image.rgb_to_grayscale(image)
def from_grayscale_to_rgb(self, image):
return tf.image.grayscale_to_rgb(image)
| true |
77480e8c1e0861daeef541978035c619ddb6cfb4 | Python | jeisenma/ProgrammingConcepts | /05-drawing/moreCircles.pyde | UTF-8 | 848 | 4.25 | 4 | [] | no_license | # J Eisenmann 2013
# jeisenma@accad.osu.edu
greens = [] # a list to hold the green color values of each circle
numCircles = 12 # how many circles are there?
def setup():
global greens
size(400,400)
# create a bunch of random numbers that will represent to green values
for i in range(numCircles):
greens.append( random(255) )
def draw():
background(200)
# calculate the circle diameter based on screen width and number of circles
diam = float(width)/numCircles
# for every column...
for i,g in enumerate(greens):
# make the circles in this column a shade of green (based on the values in the "greens" list)
fill( 100, g, 100 )
# for every row
for j in range( numCircles ):
# draw a circle at the correct place
ellipse( i*diam+diam/2, j*diam+diam/2, diam, diam )
| true |
f7914165d39f0eb173921b80016dc522197e50d4 | Python | mns0/DNABindingModel | /helper.py | UTF-8 | 5,111 | 2.5625 | 3 | [] | no_license | import numpy as np
from multiprocessing import pool
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as mpatches
import math
import operator
import random
##globaly define path ##
t = np.arange(-0.3*np.pi,3.9*np.pi,np.pi/30)
x1 = 30*np.exp(0.14*t)*np.cos(t) - 9
y1 = 30*np.exp(0.14*t)*np.sin(t) + 15
x2 = 18*np.exp(0.15*t)*np.cos(t) - 7
y2 = 18*np.exp(0.15*t)*np.sin(t) + 12
xx = np.hstack((x2,x1[::-1]))
yy = np.hstack((y2,y1[::-1]))
z1 = zip(xx,yy)
codes = np.ones(len(xx))*Path.LINETO
codes[0] = Path.MOVETO
codes[-1] = Path.STOP
structPath = Path(z1,codes)
##########################
#initialization statement
def initStatement(trials,geo,windowTime,vel):
print('#####################')
print('# Running simulation#')
print('# trials: ' + str(trials) +' #')
print('# geometry: ' + str(geo) + ' #')
print('# Window Time: ' + str(windowTime) + ' ps #')
print('# Velocity: ' + str(vel) + ' #')
print('#####################')
#run the simulations
def runSimulations(trials,geo,windowTime,prob,vel):
stats = []
for trial in np.arange(trials):
stats.append(runSim(geo,windowTime,prob,vel))
return stats
#run single simulation
def runSim(geo,windowTime,prob,vel):
coor = getXY()
return calcExpectationTimeM1(coor,geo,windowTime,prob,vel);
#get initial location of nucleotide
def getXY():
return [np.random.uniform(low=-150,high=150),
np.random.uniform(low=-150,high=150)]
def inGeo(coor,geo):
global structPath
return structPath.contains_points([coor])
#calculate exectation time for trials
# entTime = time takes to enter into the pore
# general model:
# expectation Time =
# geometricFactor*windowTime
# + skipping penalty
# + time to entry
def calcExpectationTimeM1(coor,geo,windowTime,prob,vel):
pen = 0 #penalty
entDist = distanceFromEnt(coor,geo)
geoFac = getGeometricFactor(coor,geo,entDist)
timeEnt = 0
if inGeo(coor,geo) and coor != None:
dist = 0
else:
#idx, dist = distanceFromEnt2(coor,geo)
pen = windowTime
timeEnt = entTime(coor,geo,windowTime,vel)
#print(idx,dist)
skipTime = skipCalculation(geoFac,geo,windowTime,prob)
expTime = geoFac*windowTime+timeEnt + skipTime
return expTime
#distance from channel
#assume pushed -x
def distanceFromEnt(coor,geo):
global x1, y1
points = zip(x1,y1)
distArr = []
for x,y in points:
distArr.append(math.sqrt((x-coor[0])**2 + (y-coor[1])**2))
min_index, min_value = min(enumerate(distArr), key=operator.itemgetter(1))
#print(min_index,min_value)
return (min_index,min_value)
#assumed pushed -X
def distanceFromEnt2(coor,geo):
global x1, y1
minDist = 0
vals = (y1 <= coor[1]+5) & (y1 >= coor[1]-5)
idx = np.ravel(np.where(vals))
if len(idx) > 1:
idx, minDist = getSmallestIndex(coor,idx)
return (idx, minDist)
#calculate enterance time into the structure
#assume velocity here
def entTime(coor,geo,windowTime,vel):
distFromEnt = distanceFromEnt2(coor,geo)
travelDist = vel*windowTime
print('This is the distance from the ent: '+ str(distFromEnt))
print('This is the travel distance : '+ str(travelDist))
if travelDist < distFromEnt:
x = 0
return windowTime
#calculate minimum distance such that
def getSmallestIndex(coor,idx):
global x1, y1
minArray = 0
minDist = 9999
for i in idx:
if coor[0] > x1[i]:
dist = coor[0] - x1[i]
else:
dist = coor[0] + 150 + (150 - x1[i])
if dist < minDist:
minDist = dist
minArray = i
return (minArray, minDist)
def getGeometricFactor(coor,geo,entDist):
global x1, y1, t
x = t[entDist[0]]/(np.pi/2) + 1
y = t[entDist[0]]/(np.pi/2) + 1
#print('~~~~~~~~~~~~~~~~~~ ' + str(y))
return x
#analyze the data
def analyzeData(data):
return
def initSim(trials,geo,windowTime,vel):
initStatement(trials,geo,windowTime,vel)
#determines the penelty of skipping for the trial
def skipCalculation(geoFac,geo,windowTime,prob):
skipTime = 0
skipSeg = 0
for i in range(int(geoFac)):
m = 99
r = random.randint(0,100)
if m < r:
d = getNewGeoFactor(geoFac)
skipTime = getSkipTime(4,geo,windowTime,prob)
return skipTime
def getNewGeoFactor(geoFac):
# if geoFac >= 6:
# return None
return geoFac + 4
def getSkipTime(geoFac,geo,windowTime,prob):
skipTime = skipCalculation(geoFac,geo,windowTime,prob)
expTime = geoFac*windowTime+ skipTime
return expTime
#random guessing of time
def calcExpectationTimeM2(windowTime):
#probability of landing in spiral
extArea = 1.0 - 20470.0/33676
AddTime = 0
skipTime = 0
if (random.random() < extArea):
AddTime = 500
if (random.randint(1,10) == 1 ):
skipTime = 500
geoFactor = random.randint(1,10)
#print( geoFactor*windowTime + AddTime, math.exp(-16) )
return geoFactor*windowTime + AddTime
| true |
55f4e3c0ddd2be8ad41689ec850a3c4fdbfa9c6b | Python | zhouxzh/doa | /matrix_record.py | UTF-8 | 1,265 | 2.515625 | 3 | [] | no_license | #!/usr/bin/python3
from matrix_lite import led
import time
import pyaudio
import wave
def show_direction(angle):
print('The angle is {}'.format(angle))
direction = int(angle // (360/18))
image = ['blue']*led.length
image[direction] = 'red'
led.set(image)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 8
RATE = 16000
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
dev = p.get_device_info_by_index(i)
name = dev['name'].encode('utf-8')
print(i, name, dev['maxInputChannels'], dev['maxOutputChannels'])
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=3)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
#if __name__ == '__main__':
# find_audio_index()
| true |
1606a01f2ba3efec0f37cc2dac21114f0c889112 | Python | ryanalexmartin/fooji-twitter-scraper | /src/fooji_tracker_bot.py | UTF-8 | 2,428 | 2.609375 | 3 | [
"MIT"
] | permissive | import tweepy
from modules.csv_handler import CsvHandler
import pandas as pd
import csv
from webhook_send_tweet import send_tweet_to_discord_as_webhook
auth = tweepy.OAuthHandler('eHtXXHzhyXH7s8AJpLr1c08bf', 'MByI3bcuHR8bWc9Dh18e5ojKOtzjRp6zKCGEyq6CdmoKVUcO4L')
auth.set_access_token('1348767110441414663-AF1drc9dE0JR9LTfk0oSBeF8lO3Mu2', 'UhgS6VkPbhGFgSuw6fq8kvlRUX1faD40VaK1J5GO0wr9D')
try:
redirect_url = auth.get_authorization_url()
except tweepy.TweepError:
print('Error! Failed to get request token.')
api = tweepy.API(auth)
# api.update_status('tweepy + oauth!')
path = 'outputs/output.csv'
def read_csv_file():
return pd.read_csv(path, header=[0])
def add_tweet_to_csv(tweet):
mode_append = 'a'
with open(path, mode_append, newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(tweet)
existing_tweets = read_csv_file() # a LOT of wasted compute cycles... should extend init method
print('contents of outputs/output.csv will be checked against before sending Discord messages.')
print(existing_tweets)
class StreamListener(tweepy.StreamListener):
def on_status(self, status):
existing_tweets = read_csv_file() # a LOT of wasted compute cycles... should extend init method
hashtags = status.entities['hashtags']
hashtags_values = [d['text'] for d in hashtags]
urls = status.entities['urls']
urls_values = [d['display_url'] for d in urls]
tweet_info = [status.user.screen_name, status.user.name, status.created_at, \
status.text, f'https://twitter.com/{status.user.screen_name}/status/{status.id}', \
hashtags_values, urls_values]
#logic for our own filtering purposes
print(urls_values)
if urls_values:
if urls_values[0]:
if urls_values[0] not in existing_tweets:
print('\n')
print(tweet_info)
print('\n')
print('\n')
add_tweet_to_csv(tweet_info)
send_tweet_to_discord_as_webhook(tweet_info)
else:
print('Found tweet and ignored it as URL was found in .csv file.')
def on_error(self, status_code):
if status_code == 420:
return False
filters = 'fooji'
print('Listening for tweets containing: \"' + filters + '\"...')
stream_listener = StreamListener()
stream = tweepy.Stream(auth=api.auth, listener=stream_listener)
stream.filter(track=[filters], encoding='utf8')
| true |
1bd34561856d4fa450a250db607c9b46a8ff80f9 | Python | KalashnikovEgor/PythonProject | /for_tests.py | UTF-8 | 970 | 3.90625 | 4 | [] | no_license | import math
class Figure:
def perimeter(self):
raise NotImplementedError
class Circle(Figure):
def __init__(self,radius):
self.radius = radius
def perimeter(self):
return math.pi*2*self.radius
class Rectangle (Figure):
def __init__(self,a,b):
self.a = a
self.b = b
def perimeter(self):
return (self.a + self.b)*2
class Triangle(Rectangle):
def __init__(self, a, b):
self.a = a
self.b = b
self.c = math.sqrt(a**2 + b**2)
def perimeter(self):
return self.a + self.b + self.c
class Trapiciya(Figure):
def __init__(self,a,b,c,d):
self.a = a
self.b = b
self.c = c
self.d = d
def perimeter(self):
return self.a + self.b + self.d + self.c
class Romb(Figure):
def __init__(self,a):
self.a = a
def perimeter(self):
return 4*self.a
romb = Romb(4)
cir = Circle(5)
print(cir.perimeter())
| true |
1c00e8b83ece11ee0d34d54e71bcabe8314036f3 | Python | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3/p.oon/C. Coin Jam.py | UTF-8 | 3,554 | 2.609375 | 3 | [] | no_license | import re
import sys
import random
pp = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977]
# Miller-Rabin
def isp(x):
if x in pp:
return True
for i in pp:
if not x%i:
return False
s=x-1
t=0
while not (s&1):
s=s>>1
t+=1
for z in range(10):
a=random.randrange(2, x - 1)
v=pow(a,s,x)
if v!=1:
i=0
while v!=(x - 1):
if i == t-1:
return False
else:
i=i + 1
v=(v**2) % x
return True
def check(k,ina):
for i in range(2,11):
if(isp(int(ina,i))):
#print(ina+' = '+str(int(ina,i))+' failed at base '+str(i))
return False
return True
import fractions
# pollard-brent
def fct(z):
if z%2==0:
return 2
y,c,m = random.randint(1, z-1),random.randint(1, z-1),random.randint(1, z-1)
g,r,q = 1,1,1
cnt = 0
while g==1:
x = y
for i in range(r):
y = ((y*y)%z+c)%z
k = 0
while (k<r and g==1):
if cnt > 100000:
sys.stderr.write('IGNORE\n')
return -1
ys = y
for i in range(min(m,r-k)):
y = ((y*y)%z+c)%z
q = q*(abs(x-y))%z
cnt+=min(m,r-k)
g = fractions.gcd(q,z)
k = k + m
r = r*2
if g==z:
while True:
ys = ((ys*ys)%z+c)%z
g = fractions.gcd(abs(x-ys),z)
if g>1:
break
if(g>=z):
sys.stderr.write('DIE')
sys.exit(-1)
return g
def calc(n,j):
global pcz,pc3z
pcc = int(2**(n-2))
oo = []
trz = {}
while len(oo) < j:
for i in range(1):
inrn = random.randrange(pcc)
if inrn in trz:
continue
trz[inrn] = 1
inrn = '1'+bin(inrn)[2:].zfill(n-2)+'1'
if check(n-2,inrn):
ff=[]
for i in range(2,11):
fx=fct(int(inrn,i))
if fx==-1:
break
ff+=[fx]
else:
print(inrn,' '.join(str(i) for i in ff))
oo+=[inrn]
if not len(oo) % 10:
sys.stderr.write(str(len(oo))+'\n')
return
buf=[]
def scans():
global buf
while 1:
while len(buf) <= 0: buf=input().replace('\n',' ').split(' ')
o=buf.pop(0)
if o!='': break
return o
def scan(): return int(scans())
sys.stdin = open('input.txt')
ofg=1
if ofg:
sys.stdout = open('output.txt','w')
for i in range(scan()):
print('Case #%d:'%(i+1))
calc(scan(),scan())
if ofg:
sys.stdout.flush()
sys.stdout.close() | true |
1b3f883e1276974b7e2cff6f19c24073dcccb0cd | Python | phhuang191129/ocr-test | /crnn/pytorch/medicalRecord.py | UTF-8 | 1,600 | 3.234375 | 3 | [] | no_license | import re
class case:
"""
病例結構化輸出
"""
def __init__(self,result):
self.result = result
self.N = len(self.result)
self.res = {}
self.disease()
self.disposalConsideration()
def disease(self):
"""
病名、診斷
"""
disease = {'disease':''}
diseaseStart = diseaseEnd = None
for i in range(self.N):
txt = self.result[i][1].replace(' ','')
if '病名' or '診斷' in txt :
diseaseStart = i
if '醫師囑言' or '醫囑' in txt :
diseaseEnd = i
break
if diseaseStart and diseaseEnd:
for i in range(diseaseStart,diseaseEnd):
disease['disease'].join(self.result[i][1])
self.res.update(disease)
def disposalConsideration(self):
"""
醫囑
"""
disposalConsideration = {'disposalConsideration': ''}
disposalConsiderationStart = disposalConsiderationEnd = None
for i in range(self.N):
txt = self.result[i][1].replace(' ','')
if '醫師囑言' or '醫囑' in txt:
disposalConsiderationStart = i+1
if '以下空白' in txt :
disposalConsiderationEnd = i+1
if disposalConsiderationStart and disposalConsiderationEnd:
for i in range(disposalConsiderationStart,disposalConsiderationEnd):
disposalConsideration['disposalConsideration'].join(self.result[i][1])
self.res.update(disposalConsideration)
| true |
8fd5250f79533b6389d76a9e1200afdc844466b2 | Python | adwardlee/leetcode_solutions | /038_Count_and_Say.py | UTF-8 | 1,192 | 4.25 | 4 | [
"MIT"
] | permissive | '''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
'''
class Solution:
def countAndSay(self, n: int) -> str:
outstring = '1'
if n == 1:
return outstring
for i in range(n-1):
count = 1
outstr = ''
length = len(outstring)
for x in range(length-1):
if outstring[x] == outstring[x+1]:
count += 1
else:
outstr = outstr + str(count) + str(outstring[x])
count = 1
outstr = outstr + str(count) + str(outstring[-1])
outstring = outstr
return outstring
| true |
c7c00fe565860879dab9ee2e4b5c1017dc109039 | Python | shahdharm/PythonBasics | /tqble.py | UTF-8 | 104 | 3.6875 | 4 | [] | no_license | num =int(input("enter the number" ))
for i in range(1,11):
mul = num*i
print(f"{num}*{i}={mul}") | true |
0735d619d5d90f25c073886c49ce73470984f008 | Python | nicktao9/AgriculturalDiseaseClassification | /src/models/xception.py | UTF-8 | 5,063 | 2.65625 | 3 | [] | no_license | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from torchsummary import summary
class SeparableConv2d(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size = 1,stride = 1,padding = 0,dilation = 1,bias = False):
super(SeparableConv2d,self).__init__()
self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups = in_channels,bias =bias)
self.pointwise = nn.Conv2d(in_channels,out_channels,1,1,0,1,1,bias = bias)
def forward(self,x):
x = self.conv1(x)
x = self.pointwise(x)
return x
class Block(nn.Module):
def __init__(self,in_filters,out_filters,reps,strides = 1,start_with_relu = True,grow_first = True):
super(Block,self).__init__()
if out_filters != in_filters or strides != 1:
self.skip = nn.Conv2d(in_filters,out_filters,1,stride=strides,bias = False)
self.skipbn = nn.BatchNorm2d(out_filters)
else:
self.skip = None
self.relu = nn.ReLU(inplace = True)
rep = []
filters = in_filters
if grow_first:
rep.append(self.relu)
rep.append(SeparableConv2d(in_filters,out_filters,3,stride = 1,padding = 1,bias = False))
rep.append(nn.BatchNorm2d(out_filters))
filters = out_filters
for i in range(reps -1):
rep.append(self.relu)
rep.append(SeparableConv2d(filters,filters,3,stride = 1,padding = 1,bias = False))
rep.append(nn.BatchNorm2d(filters))
# each block have same architecture
if not grow_first:
rep.append(self.relu)
rep.append(SeparableConv2d(in_filters,out_filters,3,stride = 1,padding=1,bias = False))
rep.append(nn.BatchNorm2d(out_filters))
if not start_with_relu:
rep = rep[1:]
else:
rep[0] = nn.ReLU(inplace = False)
if strides != 1:
rep.append(nn.MaxPool2d(3,strides,1))
self.rep = nn.Sequential(*rep)
def forward(self,inp):
x = self.rep(inp)
if self.skip is not None:
skip = self.skip(inp)
skip = self.skipbn(skip)
else:
skip = inp
x = x + skip
return x
class Xception(nn.Module):
def __init__(self,num_classes = 1000):
super(Xception,self).__init__()
self.num_classes = num_classes
self.conv1 = nn.Conv2d(3,32,3,2,0,dilation= 1,groups=1,bias = False)
self.bn1 = nn.BatchNorm2d(32)
self.relu = nn.ReLU(inplace = True)
self.conv2 = nn.Conv2d(32,64,3,bias = False)
self.bn2 = nn.BatchNorm2d(64)
#do relu here
self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True)
self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True)
self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True)
self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True)
self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False)
self.conv3 = SeparableConv2d(1024,1536,3,1,1)
self.bn3 = nn.BatchNorm2d(1536)
# do relu
self.conv4 = SeparableConv2d(1536,2048,3,1,1)
self.bn4 = nn.BatchNorm2d(2048)
self.fc = nn.Linear(2048, num_classes)
def features(self,input):
x = self.conv1(input)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = self.block6(x)
x = self.block7(x)
x = self.block8(x)
x = self.block9(x)
x = self.block10(x)
x = self.block11(x)
x = self.block12(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu(x)
x = self.conv4(x)
x = self.bn4(x)
return x
def logits(self,features):
x = self.relu(features)
x = F.adaptive_avg_pool2d(x,(1,1))
x = x.view(x.size(0),-1)
x = self.fc(x)
return x
def forward(self,input):
x = self.features(input)
x = self.logits(x)
return x
if __name__ == "__main__":
model = Xception().cuda()
model.load_state_dict(torch.load("../xception-b429252d.pth"))
summary(model,(3,224,224))
# summary(model,(3,500,40))
| true |
d188873ddbf6411ab750d8cae8628955127f06ae | Python | Sapphirine/201912-14-Trending-Topics-Sentiment-Analysis-of-Twitter | /Django_js_web_app/website2/static/data/generate_example.py | UTF-8 | 2,156 | 2.796875 | 3 | [] | no_license | # import json
# import random
# topics = []
# with open('sample-topics.csv', 'r') as f:
# for line in f:
# topics.append(line.strip())
# with open('world-topo-min.json', 'r') as f, open('example-tweet-toptic.json', 'w') as w:
# data = json.load(f)
# geometries = data['objects']['countries']['geometries']
# countries = {}
# topics_len = len(topics)
# for geo in geometries:
# topic_ids = [random.randrange(0, topics_len) for i in range(3)]
# countries[geo['properties']['name']] = [{'topic':topics[topic_ids[0]], 'sentiment':'neutral'}, {'topic':topics[topic_ids[1]], 'sentiment':'negitive'}, {'topic':topics[topic_ids[2]], 'sentiment':'positive'}]
# json.dump(countries, w)
import json
import random
topics = []
# with open('sample-topics.csv', 'r') as f:
# for line in f:
# topics.append(line.strip())
# with open('world-topo-min.json', 'r') as f, open('example-tweet-toptic-big-query.json', 'w') as w:
# data = json.load(f)
# geometries = data['objects']['countries']['geometries']
# countries = []
# topics_len = len(topics)
# for geo in geometries:
# topic_ids = [random.randrange(0, topics_len) for i in range(3)]
# tmp = {}
# tmp['country_name'] = geo['properties']['name']
# tmp['topic_1'] = topics[topic_ids[0]]
# tmp['topic_2'] = topics[topic_ids[1]]
# tmp['topic_3'] = topics[topic_ids[2]]
# tmp['sentiment_1'] = 'neutral'
# tmp['sentiment_2'] = 'positive'
# tmp['sentiment_3'] = 'negitive'
# countries.append(tmp)
# #countries[geo['properties']['name']] = [{'topic':topics[topic_ids[0]], 'sentiment':'neutral'}, {'topic':topics[topic_ids[1]], 'sentiment':'negitive'}, {'topic':topics[topic_ids[2]], 'sentiment':'positive'}]
# json.dump(countries, w)
with open('world-topo-min.json', 'r') as f, open('country_list.json', 'w') as w:
data = json.load(f)
geometries = data['objects']['countries']['geometries']
countries = []
for geo in geometries:
countries.append(geo['properties']['name'])
json.dump(countries, w) | true |
15c7ce00255790dc41ed51ba8e178488a4cc13d1 | Python | Rosetta-PLSci/projects | /GlacierInterpretationVisualization.py | UTF-8 | 1,197 | 3.15625 | 3 | [] | no_license | import cv2
import numpy as np
import glob
import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns
# IMG COLOR RANGE --> 0,0,224,179,248,255
# total 42 main pictures
# TRANSFORM -->
"""
mainImagePath = glob.glob("ICE/*.jpg")
year = 0
for img in mainImagePath:
image = cv2.imread(img)
imageHSV = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
year += 1
lower = np.array([0, 0, 224])
upper = np.array([179, 248, 255])
mask = cv2.inRange(imageHSV, lower, upper)
result = cv2.bitwise_and(image, image, mask=mask)
cv2.imwrite(f"Cut{year}.jpg", result)
"""
# CREATING DATA -->
"""
mainImagePath = glob.glob("IceYear/*.jpg")
MeanList = []
for img in mainImagePath:
imgCut = cv2.imread(img)
MeanList.append(int(np.mean(imgCut)))
print(MeanList)
years = list(range(1979, 2021))
Data = pd.DataFrame({"YEARS": years, "MEAN": MeanList})
Data.to_csv("ICEMEAN.csv", index=False)
"""
# GRAPHIC
"""
Data = pd.read_csv("ICEMEAN.csv")
print(Data.describe())
print()
print(Data.info())
print()
print(Data.corr())
# corr --> year & mean = -0.31
print()
sns.pairplot(Data)
plt.show()
sns.lmplot(x="YEARS",y="MEAN",data=Data)
plt.show()
"""
| true |
7812cf0ba874bcfbefa776087156e1edba3a0af8 | Python | wisechengyi/pants | /tests/python/pants_test/util/test_objects.py | UTF-8 | 6,510 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.testutil.test_base import TestBase
from pants.util.objects import Exactly, SubclassesOf, SuperclassesOf, TypeConstraintError
class TypeConstraintTestBase(TestBase):
class A:
def __repr__(self):
return f"{type(self).__name__}()"
def __str__(self):
return f"(str form): {repr(self)}"
def __eq__(self, other):
return type(self) == type(other)
class B(A):
pass
class C(B):
pass
class BPrime(A):
pass
class SuperclassesOfTest(TypeConstraintTestBase):
def test_none(self):
with self.assertRaisesWithMessage(ValueError, "Must supply at least one type"):
SubclassesOf()
def test_str_and_repr(self):
superclasses_of_b = SuperclassesOf(self.B)
self.assertEqual("SuperclassesOf(B)", str(superclasses_of_b))
self.assertEqual("SuperclassesOf(B)", repr(superclasses_of_b))
superclasses_of_multiple = SuperclassesOf(self.A, self.B)
self.assertEqual("SuperclassesOf(A or B)", str(superclasses_of_multiple))
self.assertEqual("SuperclassesOf(A, B)", repr(superclasses_of_multiple))
def test_single(self):
superclasses_of_b = SuperclassesOf(self.B)
self.assertTrue(superclasses_of_b.satisfied_by(self.A()))
self.assertTrue(superclasses_of_b.satisfied_by(self.B()))
self.assertFalse(superclasses_of_b.satisfied_by(self.BPrime()))
self.assertFalse(superclasses_of_b.satisfied_by(self.C()))
def test_multiple(self):
superclasses_of_a_or_b = SuperclassesOf(self.A, self.B)
self.assertTrue(superclasses_of_a_or_b.satisfied_by(self.A()))
self.assertTrue(superclasses_of_a_or_b.satisfied_by(self.B()))
self.assertFalse(superclasses_of_a_or_b.satisfied_by(self.BPrime()))
self.assertFalse(superclasses_of_a_or_b.satisfied_by(self.C()))
def test_validate(self):
superclasses_of_a_or_b = SuperclassesOf(self.A, self.B)
self.assertEqual(self.A(), superclasses_of_a_or_b.validate_satisfied_by(self.A()))
self.assertEqual(self.B(), superclasses_of_a_or_b.validate_satisfied_by(self.B()))
with self.assertRaisesWithMessage(
TypeConstraintError,
"value C() (with type 'C') must satisfy this type constraint: SuperclassesOf(A or B).",
):
superclasses_of_a_or_b.validate_satisfied_by(self.C())
class ExactlyTest(TypeConstraintTestBase):
def test_none(self):
with self.assertRaisesWithMessage(ValueError, "Must supply at least one type"):
Exactly()
def test_single(self):
exactly_b = Exactly(self.B)
self.assertFalse(exactly_b.satisfied_by(self.A()))
self.assertTrue(exactly_b.satisfied_by(self.B()))
self.assertFalse(exactly_b.satisfied_by(self.BPrime()))
self.assertFalse(exactly_b.satisfied_by(self.C()))
def test_multiple(self):
exactly_a_or_b = Exactly(self.A, self.B)
self.assertTrue(exactly_a_or_b.satisfied_by(self.A()))
self.assertTrue(exactly_a_or_b.satisfied_by(self.B()))
self.assertFalse(exactly_a_or_b.satisfied_by(self.BPrime()))
self.assertFalse(exactly_a_or_b.satisfied_by(self.C()))
def test_disallows_unsplatted_lists(self):
with self.assertRaisesWithMessage(TypeError, "Supplied types must be types. ([1],)"):
Exactly([1])
def test_str_and_repr(self):
exactly_b = Exactly(self.B)
self.assertEqual("Exactly(B)", str(exactly_b))
self.assertEqual("Exactly(B)", repr(exactly_b))
exactly_multiple = Exactly(self.A, self.B)
self.assertEqual("Exactly(A or B)", str(exactly_multiple))
self.assertEqual("Exactly(A, B)", repr(exactly_multiple))
def test_checking_via_bare_type(self):
self.assertTrue(Exactly(self.B).satisfied_by_type(self.B))
self.assertFalse(Exactly(self.B).satisfied_by_type(self.C))
def test_validate(self):
exactly_a_or_b = Exactly(self.A, self.B)
self.assertEqual(self.A(), exactly_a_or_b.validate_satisfied_by(self.A()))
self.assertEqual(self.B(), exactly_a_or_b.validate_satisfied_by(self.B()))
with self.assertRaisesWithMessage(
TypeConstraintError,
"value C() (with type 'C') must satisfy this type constraint: Exactly(A or B).",
):
exactly_a_or_b.validate_satisfied_by(self.C())
class SubclassesOfTest(TypeConstraintTestBase):
def test_none(self):
with self.assertRaisesWithMessage(ValueError, "Must supply at least one type"):
SubclassesOf()
def test_str_and_repr(self):
subclasses_of_b = SubclassesOf(self.B)
self.assertEqual("SubclassesOf(B)", str(subclasses_of_b))
self.assertEqual("SubclassesOf(B)", repr(subclasses_of_b))
subclasses_of_multiple = SubclassesOf(self.A, self.B)
self.assertEqual("SubclassesOf(A or B)", str(subclasses_of_multiple))
self.assertEqual("SubclassesOf(A, B)", repr(subclasses_of_multiple))
def test_single(self):
subclasses_of_b = SubclassesOf(self.B)
self.assertFalse(subclasses_of_b.satisfied_by(self.A()))
self.assertTrue(subclasses_of_b.satisfied_by(self.B()))
self.assertFalse(subclasses_of_b.satisfied_by(self.BPrime()))
self.assertTrue(subclasses_of_b.satisfied_by(self.C()))
def test_multiple(self):
subclasses_of_b_or_c = SubclassesOf(self.B, self.C)
self.assertTrue(subclasses_of_b_or_c.satisfied_by(self.B()))
self.assertTrue(subclasses_of_b_or_c.satisfied_by(self.C()))
self.assertFalse(subclasses_of_b_or_c.satisfied_by(self.BPrime()))
self.assertFalse(subclasses_of_b_or_c.satisfied_by(self.A()))
def test_validate(self):
subclasses_of_a_or_b = SubclassesOf(self.A, self.B)
self.assertEqual(self.A(), subclasses_of_a_or_b.validate_satisfied_by(self.A()))
self.assertEqual(self.B(), subclasses_of_a_or_b.validate_satisfied_by(self.B()))
self.assertEqual(self.C(), subclasses_of_a_or_b.validate_satisfied_by(self.C()))
with self.assertRaisesWithMessage(
TypeConstraintError,
"value 1 (with type 'int') must satisfy this type constraint: SubclassesOf(A or B).",
):
subclasses_of_a_or_b.validate_satisfied_by(1)
| true |
64d7e5065dfbf177b6eb557c2c50ec3b3e5e35ab | Python | yashviradia/project_lpthw | /lpthw/ex31.1.py | UTF-8 | 3,198 | 4.09375 | 4 | [] | no_license | print("""This is the game of Space and changing the history of the humanity.
The Space race has begun.
What is your choice:
'Mars' or 'Moon'?""")
place = input("> ")
if place == 'Mars':
print("""You're sharing the vision with Elon Musk.
His vision is to create the human colony on the mars.
Do you agree with his idea?
'Yes' or 'No'?""")
answer = input("> ")
if answer == 'Yes':
print("""You could join the SpaceX team. Make your dream come true.
You'll need certain amount skill sets, american citizenship, which you might easily get if you're german citizen.
You can create your own idea and work with it. Find the problems in the society and get the solution.
You can also collaberate with SpaceX or buy its equity.""")
elif answer == 'No':
print("""There are other two giants in this race. You can join them. Or you can create your own idea.""")
else:
print("""Always try to solve other people's problem. They will reward you.
Develop the high income skills and develop the financial confidence.""")
elif place == 'Moon':
print("""You're the sharing the vision with Jeff Bezos, who's net worth is 150 Billion dollars.
His vision is: the people will be living in a capsule in the space. The capsule will be floating in the space.
Do you agree with his vision?
'Yes' or 'No'?""")
answer = input("> ")
if answer == 'Yes':
print("""You're with Jeff Bezos and want to go to Moon.
But, the moon has no atmosphere. But, the capsule concept may come true.
Anyways, it's your choice.
Develop the high income skills and gain the confidence.""")
elif answer == 'No':
print("""You can still join any of the other giants: Elon Musk or Richard Brandson.""")
else:
print("""Develop the financial confidence and it comes by developing the high income skills.
You can still join the space race by joining Elon Musk or Richard Brandson.""")
else:
print("""You can always go for a space travel. The Virgin Galactic is doing it.
Even SpaceX and Blue origin are doing that.
So there are three giants: Elon Musk, Jeff Bezos and Richard Brandson.
Would like to join the space race and mine the asteroids?
'Yes' or 'No'?""")
answer = input("> ")
if answer == 'Yes':
print("""Space travel is possible and many people can get benefit with this.
You can go from New York to HongKong in just 40Minutes.
That's the possibility of this outcome.""")
elif answer == 'No':
print("""So you don't want to go with Galactic Virgin.
Are you with 'Elon Musk' or 'Jeff Bezos'""")
person = input("> ")
if person == 'Elon Musk':
print("Great choice.")
elif person == 'Jeff Bezos':
print("""He's the richest man.
But everything has its limit and sky is the limit. Is it?
I don't think so. There are no limits.
When there are limits just push them.""")
else:
print("You can create your own company. First develop the financial confidence.")
else:
print("Kind of sounds like you don't like space. You can still do asteroid mining.")
| true |
661301d18cd5af2e7f006816a4d084154af81a38 | Python | SoftwareSystemsLaboratory/prime-json-converter | /clime_json_converter/main.py | UTF-8 | 2,663 | 2.8125 | 3 | [
"BSD-3-Clause"
] | permissive | from argparse import Namespace
from pathlib import Path
import pandas as pd
from pandas import DataFrame
from progress.spinner import MoonSpinner
from clime_json_converter.args import mainArgs
from clime_json_converter.version import version
def loadDataFrame(filename: str, filetype: str = ".json") -> DataFrame:
if filetype == ".json":
return pd.read_json(filename)
elif filetype == ".csv":
return pd.read_csv(filename, sep=",")
elif filename == ".tsv":
return pd.read_csv(filename, sep="\t")
else:
print("Unsupported input filetype")
return -1
def storeDataFrame(df: DataFrame, stem: str, filetypes: list) -> int:
with MoonSpinner(
message=f"Converting {stem} to different filetypes... "
) as spinner:
for ft in filetypes:
if ft == "clipboard":
df.to_clipboar
elif ft == "csv":
df.to_csv(stem + ".csv", sep=",", index=False)
elif ft == "excel":
df.to_excel(stem + ".xlsx", index=False)
elif ft == "feather":
df.to_feather(stem + ".feather")
elif ft == "hdf":
df.to_hdf(stem + ".hdf5", index=False)
elif ft == "html":
df.to_html(stem + ".html", index=False)
elif ft == "json":
df.to_json(stem + ".json", index=False, indent=4)
elif ft == "latex":
df.to_latex(stem + ".tex", index=False)
elif ft == "markdown":
df.to_markdown(stem + ".md")
elif ft == "parquet":
df.to_latex(stem + ".parquet", index=False)
elif ft == "pickle":
df.to_pickle(stem + ".pkl")
elif ft == "stata":
df.to_stata(stem + ".dta")
elif ft == "tsv":
df.to_csv(stem + ".tsv", sep="\t", index=False)
else:
return filetypes.index(ft)
spinner.next()
return -1
def main() -> None:
args: Namespace = mainArgs()
if args.version:
print(f"clime-json-converter version {version()}")
quit(0)
argsDict: dict = args.__dict__
file: Path = Path(args.input)
fn: str = file.stem
ft: str = file.suffix
df: DataFrame = loadDataFrame(filename=args.input, filetype=ft)
fts: list = []
key: str
for key in argsDict.keys():
if argsDict[key] == True:
fts.append(key)
store: int = storeDataFrame(df, stem=fn, filetypes=fts)
if store != -1:
print(f"Unsupported format: {fts[store]}")
if __name__ == "__main__":
main()
| true |
0234138e32309930eabe9b1b7b47b4edd67df975 | Python | fuzi1996/PythonScript | /auto2File/auto_file.py | UTF-8 | 1,347 | 3.078125 | 3 | [
"MIT"
] | permissive | import os
import datetime
"""
不支持文件名包含中文的文件
"""
# 要复制的目录
path = "D:\\Text"
cmd = "copy "
# 复制到一号机对应目录
out = " y:\输出物提交处\XXX\\test"
list = []
def copy_file(list):
for i in list:
if is_today(os.stat(i).st_mtime):
os.system(cmd+i+out)
print(cmd+i+out)
def list_all_file(path):
for i in os.listdir(path):
if is_file_or_dir(os.path.join(path,i)) == 1:
list.append(os.path.join(path,i))
elif is_file_or_dir(os.path.join(path,i)) == 2:
list_all_file(os.path.join(path,i))
def is_file_or_dir(absolute_path):
"""
:param absolute_path:
:return: retrun 1 if it's a file,return 2 if it's a dir
"""
if os.path.isdir(absolute_path):
return 2
elif os.path.isfile(absolute_path):
return 1
def is_today(tim):
"""
:param tim: type(tim) is time.struct_time ,is a timestamp,
os.stat(absolute_path).st_mtime
:return: if istoday by date return Ture else False
"""
date_now = datetime.datetime.now().date()
date = datetime.datetime.fromtimestamp(tim).date()
if date == date_now:
return True
return False
if __name__ == "__main__":
list_all_file(path)
copy_file(list) | true |
15b0d70a6030ad9f44b69ce0abca7ed8c1c1ce6e | Python | cliffordjorgensen/PYTHON | /dateConversion/dateFunc.py | UTF-8 | 1,818 | 4 | 4 | [] | no_license | #Cliff Jorgensen
#functions for Date conversion program
def convertMonth(mon): #changes month to upper case
mon = mon.upper()
if mon == "JAN": #changes month to number
return"01"
elif mon == "FEB":
return "02"
elif mon == "MAR":
return "03"
elif mon == "APR":
return "04"
elif mon == "MAY":
return "05"
elif mon == "JUNE":
return "06"
elif mon == "JULY":
return "07"
elif mon == "AUG":
return "08"
elif mon == "SEPT":
return "09"
elif mon == "OCT":
return "10"
elif mon == "NOV":
return "11"
elif mon == "DEC":
return "12"
elif mon == "01": #changes number to month
return "JAN"
elif mon == "02":
return "FEB"
elif mon == "03":
return "MAR"
elif mon == "04":
return "APR"
elif mon == "05":
return "MAY"
elif mon == "06":
return "JUNE"
elif mon == "07":
return "JULY"
elif mon == "08":
return "AUG"
elif mon == "09":
return "SEPT"
elif mon == "10":
return "OCT"
elif mon == "11":
return "NOV"
elif mon == "12":
return "DEC"
else:
mon = "00" #prints error message if month entry is invalid
print("\n *Unknown Month* (check spelling)")
return mon
def twoDigitDay(dayNum): #concatenates with 0 if only 1 digit
if len(dayNum) != 2:
dayNum = "0" + dayNum
return dayNum
def format(date):
date = date.strip() #remove leading or trailing blanks
while (date.find(" ")!= -1): #while there are blanks
date = date.replace(" ","")
while (date.find(" -") != -1): #while there is a blank before dash
date.replace(" -", "-")
return date
| true |
bf49ed946db56c7fd7539aae25cf30ed7120afd6 | Python | krab1k/CCL | /ccl/common.py | UTF-8 | 526 | 2.96875 | 3 | [] | no_license | """Common utility functions used within CCL"""
import os
from enum import Enum
from typing import Set
class NoValEnum(Enum):
"""Enum with simplified text representation"""
def __repr__(self) -> str:
return f'{self.__class__.__name__}.{self.name}'
def __str__(self) -> str:
return f'{self.value}'
ELEMENT_NAMES: Set[str] = set()
with open(os.path.join(os.path.dirname(__file__), 'elements.txt')) as elements_file:
for line in elements_file:
ELEMENT_NAMES.add(line.strip().lower())
| true |
6f9bd2a772fbb50563e10e2382ea415a5eb6b434 | Python | ShadowLogan/AlarmClock | /main.py | UTF-8 | 2,139 | 3.6875 | 4 | [] | no_license | import random
round_no = 0
comp_score = 0
player_score = 0
while True:
game_list = ["Rock", "Paper", "Scissors"]
comp_choice = random.choice(game_list)
if comp_choice in ["Rock", "rock", "r", "R"]:
comp_choice = "r"
if comp_choice in ["Scissors", "scissors", "s", "S"]:
comp_choice = "s"
if comp_choice in ["Paper", "paper", "p", "P"]:
comp_choice = "p"
round_no += 1
print("Round: " + str(round_no))
player_choice = input("Choose Rock, Paper or Scissors: ")
if player_choice in ["Rock", "rock", "r", "R"]:
player_choice = "r"
if player_choice in ["Scissors", "scissors", "s", "S"]:
player_choice = "s"
if player_choice in ["Paper", "paper", "p", "P"]:
player_choice = "p"
if player_choice == comp_choice:
print("It is a draw!")
if player_choice == "p":
if comp_choice == "r":
print("You chose Paper and the Computer chose rock. You win!")
player_score += 1
if comp_choice == "s":
print("You chose Paper and the Computer chose scissors. You lose!")
comp_score += 1
if player_choice == "s":
if comp_choice == "p":
print("You chose Scissors and the Computer chose paper. You win!")
player_score += 1
if comp_choice == "r":
print("You chose Scissors and the Computer chose rock. You lose!")
comp_score += 1
if player_choice == "r":
if comp_choice == "s":
print("You chose Rock and the Computer chose scissors. You win!")
player_score += 1
if comp_choice == "p":
print("You chose Rock and the Computer chose Paper. You lose!")
comp_score += 1
print("Computer: " + str(comp_score) + " " + "Player: " + str(player_score))
start = 1
replay = input('Continue? y/n:')
if start != 1:
print(replay)
elif replay == 'y':
pass
elif replay == 'n':
break
else:
print('Invalid input')
continue
| true |
0f80f1fb84bb09063cc2b021ebd9396ae7062024 | Python | detcitty/100DaysOfCode | /python/2021/other/practice.py | UTF-8 | 271 | 3.375 | 3 | [] | no_license | import numpy as np
import time
values = []
for i in range(0, 10):
values.append(i**i)
print(values)
print(time.strftime("%A", time.localtime()))
print(list(map(lambda x: 2**x, list(range(33)))))
sin_x = np.arange(100)
print(np.exp(sin_x))
print("Hello world")
| true |
d6a4e814b64fa645ddf475eaa5a21a96c769f780 | Python | TheAlgorithms/Python | /strings/snake_case_to_camel_pascal_case.py | UTF-8 | 1,621 | 4.09375 | 4 | [
"MIT",
"Giftware",
"LicenseRef-scancode-proprietary-license"
] | permissive | def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str:
"""
Transforms a snake_case given string to camelCase (or PascalCase if indicated)
(defaults to not use Pascal)
>>> snake_to_camel_case("some_random_string")
'someRandomString'
>>> snake_to_camel_case("some_random_string", use_pascal=True)
'SomeRandomString'
>>> snake_to_camel_case("some_random_string_with_numbers_123")
'someRandomStringWithNumbers123'
>>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True)
'SomeRandomStringWithNumbers123'
>>> snake_to_camel_case(123)
Traceback (most recent call last):
...
ValueError: Expected string as input, found <class 'int'>
>>> snake_to_camel_case("some_string", use_pascal="True")
Traceback (most recent call last):
...
ValueError: Expected boolean as use_pascal parameter, found <class 'str'>
"""
if not isinstance(input_str, str):
msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)
if not isinstance(use_pascal, bool):
msg = f"Expected boolean as use_pascal parameter, found {type(use_pascal)}"
raise ValueError(msg)
words = input_str.split("_")
start_index = 0 if use_pascal else 1
words_to_capitalize = words[start_index:]
capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize]
initial_word = "" if use_pascal else words[0]
return "".join([initial_word, *capitalized_words])
if __name__ == "__main__":
from doctest import testmod
testmod()
| true |
1868276378aaffa4f836453829131d697b5727d7 | Python | sergio88-perez/pachaqtecH7 | /Grupo6/martin/app/conexion.py | UTF-8 | 2,744 | 2.59375 | 3 | [] | no_license | import utils
log = utils.log("INIT")
# mongoDB
#import pymongo
import pymongo
from pymongo import MongoClient, errors
class conexionBDD:
def conexion(self):
url = 'mongodb://localhost:27017'
try:
conn = pymongo.MongoClient(url)
#db = conn[str(f"{database}")]
db = conn["Hackaton7Grupo6"]
db["curso"]
db["alumno"]
db["nota"]
return db
except Exception as error:
log.error(error)
return error
def insertarRegistro(self, collection, data):
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
res = doc.insert_one(data).inserted_id
return res
def insertarRegistros(self, collection, data):
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
res = doc.insert_many(data).inserted_ids
return res
def leerRegistro(self, collection, data):
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
res = doc.find_one(data)
return res
def leerRegistroPorId(self, collection, data):
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
res = doc.find_one(data)
return res
def leerRegistros(self, collection, data):
try:
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
res = doc.find(data)
return res
except Exception as error:
log.error(error)
def actualizarRegistro(self, collection, condicion, cambio):
try:
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
doc.update_one(condicion,{ '$set' : cambio } )
return doc
except Exception as error:
log.error(error)
def eliminarRegistro(self, collection, eliminar):
try:
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
doc.delete_one(eliminar)
return doc
except Exception as error:
log.error(error)
def eliminarRegistros(self, collection, eliminar):
try:
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
doc.delete_many(eliminar)
return doc
except Exception as error:
log.error(error)
def leerRegistrosTotal(self, collection):
try:
conexion = self.conexion()
doc = conexion[str(f"{collection}")]
res = doc.find()
return res
except Exception as error:
log.error(error) | true |
9c8be35a4f25020fbbd318ef8f564ce8b33276fd | Python | JfGitHub31/jianfeng7 | /t.py | UTF-8 | 220 | 3.1875 | 3 | [] | no_license | import re
a = '<p>Text</p><p>Text1<img src="url1">Text2<img src="url2">Text3</p><p><img src="url"></p>'
r = re.findall(r'>([^<>]+?)<|img src="([^<>]+?)"', a)
b = list(map(lambda i: i[0] if i[0] else i[1], r))
print(b)
| true |
88cf14f374900289bded3fce05cb636dd29378e4 | Python | htcondor/htcondor | /src/condor_tests/test_dagman_futile_nodes_efficiency.py | UTF-8 | 6,485 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env pytest
# test_futile_node_inefficiency.py
#
# LIGO discovered that with very large DAGs with many wide layers
# of nodes can result in DAGMan hanging on the recursive function
# that sets a nodes descendants to FUTILE status. This was due to
# the function being inefficient and always checking calling this
# function for all of its children when in theory if a child is
# already futile then we do not need to traverse its children.
# This test is to make sure a regression to this behavior does
# not occur.
# Author: Cole Bollig - 2023-07-21
from ornithology import *
import htcondor
import os
from math import ceil
#------------------------------------------------------------------
# Function to increment are name letter sequence indexes
def increment(seq=[], pos=-1):
if pos == -1:
return
seq[pos] = seq[pos] + 1
if seq[pos] == 26:
seq[pos] = 0
increment(seq, pos-1)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Function to generate a shiskabob DAG with various width layers and designated failure points (nodes)
def generate_dag(filename="", job_submit="", fail_script="", depth=1, layers={}, failure_points={}):
# Characters used for making a unique node name
ALPHA = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
# Open DAG file
with open(filename, "w") as f:
# Make node name sequence
node_seq = [0] * ceil(depth / 26)
fail_lines = []
# For each layer in the DAG cake
for i in range(depth):
node = ""
# Construct base node name for this layer
for n in range(len(node_seq)):
node = node + ALPHA[node_seq[n]]
# Layer is not multi nodes wide (i.e. single node)
if i not in layers.keys():
f.write(f"JOB {node} {job_submit}\n")
else:
# Layer has multi node width
for j in range(layers[i]):
# Append node number to make unique node name
node_i = node + str(j)
f.write(f"JOB {node_i} {job_submit}\n")
# Check if this layer has failure nodes
if i in failure_points.keys():
# Failure point is on a single node layer
if i not in layers.keys():
fail_lines.append(f"SCRIPT POST {node} {fail_script}\n")
else:
# Failure point is on a multi node layer
for j in range(layers[i]):
# Failure point can be list of node #'s, single node #, or 'ALL'
node_i = node + str(j)
if type(failure_points[i]) == list and j in failure_points[i]:
fail_lines.append(f"SCRIPT POST {node_i} {fail_script}\n")
elif failure_points[i] == "ALL" or failure_points[i] == j:
fail_lines.append(f"SCRIPT POST {node_i} {fail_script}\n")
# increment the node name sequence for next unique node name
increment(node_seq, len(node_seq)-1)
# write a break lins
f.write("\n")
# write all post scripts for failure points
for line in fail_lines:
f.write(line)
# write a break line
f.write("\n")
# Reset node sequence to start for parent/child relationships
for i in range(len(node_seq)):
node_seq[i] = 0
parents = []
# Write Parent/child relationships
for i in range(depth):
write = False
# Write out parents
if len(parents) > 0:
write = True
f.write("PARENT")
for parent in parents:
f.write(f" {parent}")
f.write(" CHILD")
# Empty parents because the children will become parents for next layer
parents.clear()
# Make node name
node = ""
for n in range(len(node_seq)):
node = node + ALPHA[node_seq[n]]
# Add node(s) to parents list for next line
# Also write nodes if we have written out their parents above
if i not in layers.keys():
if write:
f.write(f" {node}")
parents.append(node)
else:
for j in range(layers[i]):
node_i = node + str(j)
if write:
f.write(f" {node_i}")
parents.append(node_i)
if write:
f.write("\n")
increment(node_seq, len(node_seq)-1)
#------------------------------------------------------------------
# Write submit file to be used by all nodes in DAG
@action
def submit_file(test_dir, path_to_sleep):
path = os.path.join(str(test_dir), "job.sub")
with open(path,"w") as f:
f.write(f"""# Simple sleep job
executable = {path_to_sleep}
arguments = 0
log = job.log
queue""")
return path
#------------------------------------------------------------------
# Write a script that will cause specified nodes to fail
@action
def fail_script(test_dir):
path = os.path.join(str(test_dir), "fail.sh")
with open(path,"w") as f:
f.write("""#!/usr/bin/env python3
exit(1)""")
os.chmod(path, 0o777)
return path
#------------------------------------------------------------------
# Run test here: generate DAG based on parameters and files and submit DAG
@action
def submit_large_dag(default_condor, test_dir, submit_file, fail_script):
dag_file_path = os.path.join(str(test_dir), "generated.dag")
layers = { 0:2, 1:100, 3:100, 5:300, 7:100, 10:50, 15:50, 20:75, 30:100, 40:150, 50:300 }
failures = { 0:"ALL" }
generate_dag(dag_file_path, submit_file, fail_script, 52, layers, failures)
dag = htcondor.Submit.from_dag(dag_file_path)
return default_condor.submit(dag)
#==================================================================
class TestDAGManFutileNodesFnc:
def test_futile_node_efficiency(self, submit_large_dag):
# Make sure we are not taking a long time recursing because of re-traversal of nodes
# This will either finish fast or take a very long time
assert submit_large_dag.wait(condition=ClusterState.all_complete,timeout=80)
| true |
d835abc49bb21c6d84a7020f77013588675e2e5e | Python | johwiebe/stn | /instances/toy2struct.py | UTF-8 | 1,875 | 2.90625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Toy example of STN with degradation.
Units:
Heater
Reactor
Tasks:
Heating
Reaction_1
Reaction_2
Operating modes:
Slow
Normal
"""
import sys
import os
import dill
os.chdir(os.getcwd() + "/" + os.path.split(sys.argv[0])[0])
sys.path.append('..')
from stn import stnStruct # noqa
# create instance
stn = stnStruct()
# states
stn.state('F1', init=2000000) # Feed F1
stn.state('F2', init=2000000) # Feed F2
stn.state('P1', price=10, scost=9, prod=True) # Product P1
stn.state('P2', price=20, scost=5, prod=True) # Product P2
stn.state('I1', scost=15) # Product P2
# state to task arcs
stn.stArc('F1', 'Heating')
stn.stArc('F2', 'Reaction_1', rho=0.6)
stn.stArc('I1', 'Reaction_1', rho=0.4)
stn.stArc('P1', 'Reaction_2', rho=0.3)
stn.stArc('I1', 'Reaction_2', rho=0.7)
# task to state arcs
stn.tsArc('Heating', 'I1', rho=1.0)
stn.tsArc('Reaction_1', 'P1', rho=1.0)
stn.tsArc('Reaction_2', 'P2', rho=1.0)
# unit-task data
stn.unit('Heater', 'Heating', Bmin=40, Bmax=100, tm=2, rmax=80,
rinit=43, a=600, b=300)
stn.unit('Reactor', 'Reaction_1', Bmin=30, Bmax=140, tm=3, rmax=120,
rinit=50, a=600, b=300)
stn.unit('Reactor', 'Reaction_2', Bmin=30, Bmax=140, tm=3, rmax=120,
rinit=50, a=600, b=300)
# operating mode and degradation data
stn.opmode('Slow')
stn.opmode('Normal')
stn.ijkdata('Heating', 'Heater', 'Slow', 9, 5.5, 0.27*5.5)
stn.ijkdata('Heating', 'Heater', 'Normal', 6, 11, 0.27*11)
stn.ijkdata('Reaction_1', 'Reactor', 'Slow', 6, 7, 0.27*7)
stn.ijkdata('Reaction_1', 'Reactor', 'Normal', 4, 9, 0.27*9)
stn.ijkdata('Reaction_2', 'Reactor', 'Slow', 10, 5, 0.27*5)
stn.ijkdata('Reaction_2', 'Reactor', 'Normal', 6, 13, 0.27*13)
with open("../data/toy2.dat", "wb") as dill_file:
dill.dump(stn, dill_file)
| true |
78571cfbc1f6bdff1ac4e760dad6b1e871773923 | Python | UHM-PANDA/Mock-Interview-Problems | /Arrays/Pascals_Triangle/Python/main.py | UTF-8 | 436 | 3.203125 | 3 | [] | no_license | def pascal(n):
output = [[1], [1, 1]]
for i in range(2, n):
output.append([1 if j == 0 or j == len(output[i - 1]) else output[i - 1][j - 1] + output[i - 1][j] for j in range(len(output[i - 1]) + 1)])
return output[:n]
def pascal_not_scary(n):
output = [[1], [1, 1]]
for i in range(2, n):
new_level = []
for i in range(len(output[i - 1]) + 1):
new_level.append(
print(pascal(5))
| true |
2c917a234ba584c11d7220e765d67e8d68262ab9 | Python | kikihiter/LeetCode2 | /Everyday/No331.py | UTF-8 | 1,964 | 3.453125 | 3 | [] | no_license | class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
"""
"o,#,#"
"o,o,#,#,#"
"o,#,o,#,#"
"o,o,#,#,o,#,#"
"o,o,o,#,#,#,#"
"o,o,#,o,#,#,#"
"o,#,o,o,#,#,#"
"o,#,o,#,o,#,#"
"9,3,4,#,#,1,#,#,2,#,6,#,#"
"9,3,4,#,#,1,#,#,2,#,#"
"9,3,4,#,#,1,#,#,#"
"9,#,#"
对于每一个叶子节点,其序列号的表达式一定是o##的形式,替换每一个o##为#,不断摘除叶子节点,判断是否正确
"""
if ',' in preorder:
# 预处理,去除字符串中的',',并将数字替换掉
preorder = preorder.split(',')
for i, letter in enumerate(preorder):
if letter != '#':
preorder[i] = 'O'
preorder = ''.join(preorder)
if len(preorder)%2 == 0:
# 正常的序列长度不能被2整除,因为#的数目一定比数字多一个
return False
if preorder == "#":
# 全部叶子节点都被摘除了,只剩#
return True
if preorder[0] == '#':
# 第一个字符为#,根节点为空,却还有其他节点,不可能
return False
ans = ""
i = 0
while i < len(preorder)-2:
if preorder[i] != '#' and preorder[i+1] == '#' and preorder[i+2] == '#':
# 找到叶子节点,替换成'#'
i += 3
ans += '#'
continue
ans += preorder[i]
i += 1
while i < len(preorder):
ans += preorder[i]
i += 1
if ans == preorder:
# ans和preorder相同,证明其中没有叶子节点,显然不可能
return False
return self.isValidSerialization(ans) | true |
93a8ce30983b0f3cbb9a48271a64c84d5f71f1a8 | Python | sbrant/pdns | /bin/get_bl_lookup.py | UTF-8 | 1,305 | 2.5625 | 3 | [] | no_license | # --------------------------------------------------------------
#
# Example script to build a blacklist lookup from online sources.
# Please read the terms of use prior to using the MalwareDomains list:
# http://www.malwaredomains.com/?page_id=1508
#
# Grab and process the latest domain list from:
# http://www.malwaredomains.com/?page_id=66
#
# --------------------------------------------------------------
import csv
import urllib
import zipfile
src_url = 'http://malware-domains.com/files/domains.zip'
local_file = '/tmp/domains.zip'
def fetch_list():
urllib.urlretrieve(src_url, local_file)
def prep_lookup():
with zipfile.ZipFile(local_file, 'r') as zip_file:
ext_file = zip_file.extract('domains.txt', '/tmp/')
processedfile = open('/opt/splunk/etc/apps/pdns/lookups/domains.csv', 'w')
processedfile.write('domain,type,original_reference\n')
with open(ext_file, 'r') as rawfile:
domainreader = csv.reader(rawfile, delimiter='\t')
for row in domainreader:
if row[0] == '##':
continue
else:
processedfile.write(
row[2] + ',' + row[3] + ',' + row[4] + '\n')
processedfile.close()
def main():
fetch_list()
prep_lookup()
if __name__ == "__main__":
main()
| true |
ab25c9316ecac532f9d7e71bf23c412ca504a29d | Python | fedosu85nce/work | /zfrobisher-installer/src/ui/systemconfig/configcompleted.py | UTF-8 | 996 | 2.765625 | 3 | [] | no_license | #!/usr/bin/python
#
# IMPORTS
#
from snack import *
#
# CONSTANTS
#
#
# CODE
#
class ConfigCompleted:
"""
Last screen for the configuration application
"""
def __init__(self, screen):
"""
Constructor
@type screen: SnackScreen
@param screen: SnackScreen instance
"""
self.__screen = screen
self.__msg = TextboxReflowed(40, "The system configuration is completed. Exit from the configuration tool and log into the system.")
self.__buttonsBar = ButtonBar(self.__screen, [("Exit", "exit")])
self.__grid = GridForm(self.__screen, "IBM zKVM", 1, 2)
self.__grid.add(self.__msg, 0, 0)
self.__grid.add(self.__buttonsBar, 0, 1, (0,1,0,0))
# __init__()
def run(self):
"""
Draws the screen
@rtype: integer
@returns: sucess status
"""
self.__grid.run()
self.__screen.finish()
return 'exit'
# run()
# ConfigCompleted
| true |
cb24ba1abb2297821316132f88621fb84b1b1bdb | Python | sohailsayed990/Sayed-Sohail | /Gstprogram.py | UTF-8 | 619 | 3.578125 | 4 | [] | no_license | class product:
def __init__(self):
self.product_id=input("Enter the product id =")
self.product_name=input("Enter the product name =")
self.product_price=float(input("Enter the product price ="))
def product_info(self):
print("Product Id :",self.product_id)
print("Product name :",self.product_name)
print("Product price :",self.product_price)
class gst(product):
def __init__(self):
super().__init__()
def gst(self):
gst=self.product_price*0.02
self.product_price=self.product_price+gst
print("After Applying Gst Product Price is :",self.product_price)
g1=gst()
g1.product_info()
g1.gst() | true |
0c6103ae930567d8771eef34e588caf26f8259ae | Python | TebelloX/resolvelib | /tests/test_resolvers.py | UTF-8 | 3,417 | 2.78125 | 3 | [
"ISC"
] | permissive | import pytest
from resolvelib import (
AbstractProvider,
BaseReporter,
InconsistentCandidate,
Resolver,
)
def test_candidate_inconsistent_error():
requirement = "foo"
candidate = "bar"
class Provider(AbstractProvider):
def __init__(self, requirement, candidate):
self.requirement = requirement
self.candidate = candidate
def identify(self, requirement_or_candidate):
assert requirement_or_candidate is self.requirement
return requirement_or_candidate
def get_preference(self, **_):
return 0
def get_dependencies(self, **_):
return []
def find_matches(self, identifier, requirements, incompatibilities):
assert list(requirements[identifier]) == [self.requirement]
assert next(incompatibilities[identifier], None) is None
return [self.candidate]
def is_satisfied_by(self, requirement, candidate):
assert requirement is self.requirement
assert candidate is self.candidate
return False
resolver = Resolver(Provider(requirement, candidate), BaseReporter())
with pytest.raises(InconsistentCandidate) as ctx:
resolver.resolve([requirement])
assert str(ctx.value) == "Provided candidate 'bar' does not satisfy 'foo'"
assert ctx.value.candidate is candidate
assert list(ctx.value.criterion.iter_requirement()) == [requirement]
@pytest.mark.parametrize("specifiers", [["1", "12"], ["12", "1"]])
def test_candidate_depends_on_requirements_of_same_identifier(specifiers):
# This test ensures if a candidate has multiple dependencies under the same
# identifier, all dependencies of that identifier are correctly pulled in.
# The parametrization ensures both requirement ordering work.
# Parent depends on child twice, one allows v2, the other does not.
# Each candidate is a 3-tuple (name, version, dependencies).
# Each requirement is a 2-tuple (name, allowed_versions).
# Candidate v2 is in from so it is preferred when both are allowed.
all_candidates = {
"parent": [("parent", "1", [("child", s) for s in specifiers])],
"child": [("child", "2", []), ("child", "1", [])],
}
class Provider(AbstractProvider):
def identify(self, requirement_or_candidate):
return requirement_or_candidate[0]
def get_preference(self, **_):
return 0
def get_dependencies(self, candidate):
return candidate[2]
def find_matches(self, identifier, requirements, incompatibilities):
assert not list(incompatibilities[identifier])
return (
candidate
for candidate in all_candidates[identifier]
if all(candidate[1] in r[1] for r in requirements[identifier])
)
def is_satisfied_by(self, requirement, candidate):
return candidate[1] in requirement[1]
# Now when resolved, both requirements to child specified by parent should
# be pulled, and the resolver should choose v1, not v2 (happens if the
# v1-only requirement is dropped).
resolver = Resolver(Provider(), BaseReporter())
result = resolver.resolve([("parent", {"1"})])
assert set(result.mapping) == {"parent", "child"}
assert result.mapping["child"] == ("child", "1", [])
| true |
652ff19bdf92d96011181b9db4b685f17d5fd387 | Python | MarkF88/sudoku | /main.py | UTF-8 | 4,967 | 3.796875 | 4 | [] | no_license | """Represents a value on the Sudoku board, can either be an entered value or a clue
"""
class BaseSquare:
"""Base class for values on the board"""
def __init__(self, value=None):
self._value = None
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
if value is not None:
if value < 1 or value > 9:
raise ValueError("Invalid Value")
self._value = value
@property
def has_value(self):
return self.value is not None
class ClueSquare(BaseSquare):
""" Represents a clue on a Sudoku board, value cannot be changed once set"""
@property
def value(self):
return self._value
@BaseSquare.value.setter
def value(self, value):
if self.value is None:
# For some reason this Syntax is required to overide a setter property
super(ClueSquare, self.__class__).value.fset(self, value)
else:
raise ValueError("Cant set clue value once set")
class ValueSquare(BaseSquare):
"""Represents a guess on a Sudoku board, can be changed"""
def __init__(self, value=None):
super().__init__(value)
self._is_error = False
def clear_value(self):
self._value = None
@property
def is_error(self):
return self._is_error
@is_error.setter
def is_error(self, is_error):
self._is_error = is_error
class AreaChecker:
"""represents a line, column or area of nine squares and is used to check the compltion and correctness of an
area"""
def __init__(self):
self.__squares = []
def add_square(self, square):
self.__squares.append(square)
def set_error(self, square, value):
if isinstance(square, ValueSquare):
square.is_error = value
def check_area(self):
assert(len(self.__squares) ==9)
found_values = {}
for square in self.__squares:
if square.has_value:
if square.value in found_values:
self.set_error(square, True)
self.set_error(found_values[square.value], True)
else:
self.set_error(square, False)
found_values[square.value] = square
else:
self.set_error(square, False)
class Board:
"""Contains all the Sudoku game board values"""
def __init__(self):
# Create the 9 by 9 list for the board values
self.__values = [[None] * 9 for i in range(9)]
# Create all the areas to check
self._section_areas = []
self._row_areas = []
self._column_areas = []
def get_square(self, col, row):
return self.__values[row - 1][col - 1]
def _set_square(self, col, row, value):
self.__values[row - 1][col - 1] = value
def create_clue_square(self, col, row, value):
square = ClueSquare(value)
self._set_square(col, row, square)
def create_value_square(self, col, row, value):
square = ValueSquare(value)
self._set_square(col, row, square)
def get_value(self, col, row):
return self.get_square(col, row).value
def set_up_board(self, clues, values = None):
"""sets up a board with the previously entered values and clues"""
self.set_up_clues(clues)
#TODO Add code to enter the previosly set up values
self.set_up_value_squares()
def set_up_areas(self):
"""Create an rea for each 3*3 section of the board and each row and column"""
def is_clue_square(self, col, row):
square = self.get_square(col, row)
if isinstance(square, ClueSquare):
return True
else:
return False
def set_up_clues(self, clues):
# TODO Add code to check that all the values are here and the lengths are equal
values = clues["values"]
rows = clues["rows"]
columns = clues["columns"]
for x in range(len(values)):
self.create_clue_square(columns[x], rows[x], values[x])
def set_up_value_squares(self):
"""puts an empty value into each non-null square"""
for row in self.__values:
for x in range(len(row)):
if row[x] is None:
row[x] = ValueSquare()
def set_value(self, col, row, value):
if self.is_clue_square(col, row):
raise ValueError("Cant set Clue Square")
"""TODO Implement this
when a value is set the following occurs
Only set the value if the square is not a clue square
We check all the rows columns and areas to see if they are completed or are in error, if in error then flag the
squares that are in error.
If they are all completed then we have a win and flag a win condition"""
pass
if __name__ == '__main__':
pass
| true |
a89e227ce42286ccef739b299b33bb89936efe16 | Python | glycerine/numba | /numba/tests/math_tests/test_nopython_math.py | UTF-8 | 790 | 2.6875 | 3 | [
"BSD-2-Clause"
] | permissive | import math
import numpy as np
import unittest
#import logging; logging.getLogger().setLevel(1)
from numba import *
def exp_fn(a):
return math.exp(a)
def sqrt_fn(a):
return math.sqrt(a)
def log_fn(a):
return math.log(a)
class TestNoPythonMath(unittest.TestCase):
def test_sqrt(self):
self._template(sqrt_fn, np.sqrt)
def test_exp(self):
self._template(exp_fn, np.exp)
def test_log(self):
self._template(log_fn, np.log)
def _template(self, func, npfunc):
func_jitted = jit(argtypes=[f4], restype=f4, nopython=True)(func)
A = np.array(np.random.random(10), dtype=np.float32)
B = np.vectorize(func_jitted)(A)
self.assertTrue(np.allclose(B, npfunc(A)))
if __name__ == '__main__':
unittest.main()
| true |
e21f16915d3cdc2c74e167b06b66d3fe1666cef3 | Python | do5562/SLEDIMedO | /scrapers/scraper_mddsz.py | UTF-8 | 3,586 | 2.921875 | 3 | [
"MIT"
] | permissive | from bs4 import BeautifulSoup
import requests
import hashlib
import datetime
from database.dbExecutor import dbExecutor
'''
vse novice so zbrane na eni strani
'''
base_url = 'http://www.mddsz.gov.si'
full_url = 'http://www.mddsz.gov.si/si/medijsko_sredisce/sporocila_za_medije/page/' #kasneje dodas se cifro strani
headers = {
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 '
'Safari/537.36'}
def makeHash(title, date):
return hashlib.sha1((title + date).encode('utf-8')).hexdigest()
def isArticleNew(hash):
is_new = False
try:
f = open('article_list.txt', 'r+')
except FileNotFoundError:
f = open('article_list.txt', 'a+')
if hash not in f.read().split():
is_new = True
f.write(hash + '\n')
print('new article found')
f.close()
return is_new
def getLink(soup):
link = soup.select('h4 > a')
if link:
return link[0]['href']
print('link not found, update find() method')
return 'link not found'
def getDate(soup):
date = soup.find('time')
if date:
return ''.join(date.text.split())
print('date not found, update find() method')
return 'date not found'
def getTitle(soup):
title = soup.select('h4 > a')
if title:
return ' '.join(title[0].text.split())
print('title not found, update find() method')
return 'title not found'
def getContent(url, session):
print(url)
r = session.get(url, timeout=5)
soup = BeautifulSoup(r.text, 'lxml')
#znebi se script texta na strani, da ne bo del content-a
for script in soup(['script']):
script.decompose()
content = soup.find('div', class_='news news-single-item')
if content:
return ' '.join(content.text.split())
print('content not found, update select() method', url)
return 'content not found'
def formatDate(date):
#format date for consistent database
return '-'.join(reversed(date.split('.')))
def getArticlesOnPage(num_pages_to_check, session):
articles = []
for n in range(num_pages_to_check):
r = session.get(full_url + str(n+1), timeout=10)
soup = BeautifulSoup(r.text, 'lxml')
articles_on_page = soup.find('div', class_='news').find_all('table')
articles = articles + articles_on_page
return articles
def main():
num_pages_to_check = 3
num_new_articles = 0
with requests.Session() as session:
session.headers.update(headers)
articles = getArticlesOnPage(num_pages_to_check, session)
dates = []
titles = []
hashes = []
links = []
for x in articles:
title = getTitle(x)
date = getDate(x)
hash = makeHash(title, date)
if isArticleNew(hash):
titles.append(title)
dates.append(date)
hashes.append(hash)
links.append(getLink(x))
num_new_articles += 1
new_articles_tuples = []
for i in range(len(links)):
#tukaj popravi, da vneses v bazo
content = ' '.join(getContent(links[i], session).split())
tup = (str(datetime.date.today()), titles[i], content, formatDate(dates[i]), hashes[i], links[i], base_url)
new_articles_tuples.append(tup)
dbExecutor.insertMany(new_articles_tuples)
print(num_new_articles, 'new articles found,', num_pages_to_check, 'pages checked')
if __name__ == '__main__':
main() | true |
f8bf19b17c60f7526d5f88579ea223c56f3e90e4 | Python | Dullz95/BMI-calculator | /class ect.py | UTF-8 | 1,119 | 4.1875 | 4 | [] | no_license | # explanation
class Shapes:
def __init__(self, name, sides):
self.name=name
self.sides=sides
def Area(self):
print("I am a :" + self.name + "\n" + "I have " + self.sides + "Sides")
obj_shapes=Shapes("Shape", "so many ")
obj_shapes.Area()
class Rectangle(Shapes):
def __init__(self, len1, wid1):
self.length=len1
self.width=wid1
def Area(self):
result=self.length * self.width
return result
obj_book=Rectangle(10, 15)
print(obj_book.Area())
obj_screen=Rectangle(15,8)
print(obj_screen.Area())
class Triangle(Shapes):
def __init__(self, base, height):
self.base=base
self.height=height
def Area(self):
result = self.base / 2 *self.height
return result
obj_tri=Triangle(15, 10)
print(obj_tri.Area())
class Circle(Shapes):
def __init__(self, name, side, radius):
super().__init__(name, side)
self.radius=radius
def Area(self):
import math
result = math.pi * self.radius* self.radius
return result
obj_coin = Circle("name", "shape", 7)
print(obj_coin.Area())
| true |
ed5aadde35fcbc893b3d3db9681f3e5a4f256e8d | Python | tomwwjjtt/RJB | /crnn/demo_combine_pic.py | UTF-8 | 1,444 | 3.25 | 3 | [] | no_license | import PIL.Image as Image
import os
# 功能:拼接图像
IMAGES_PATH = 'G:/why_workspace/RJB/iam/tmp/images3/' # 图片集地址
IMAGES_FORMAT = ['.jpg', '.png'] # 图片格式
IMAGE_SIZE = 256 # 每张小图片的大小
IMAGE_ROW = 1 # 图片间隔,也就是合并成一张图后,一共有几行
IMAGE_COLUMN = 2 # 图片间隔,也就是合并成一张图后,一共有几列
IMAGE_SAVE_PATH = 'G:/why_workspace/RJB/iam/tmp/images4/final.png' # 图片转换后的地址
# 获取图片集地址下的所有图片名称
image_names = [name for name in os.listdir(IMAGES_PATH) for item in IMAGES_FORMAT if
os.path.splitext(name)[1] == item]
print(image_names)
# 简单的对于参数的设定和实际图片集的大小进行数量判断
if len(image_names) != IMAGE_ROW * IMAGE_COLUMN:
raise ValueError("合成图片的参数和要求的数量不能匹配!")
# 定义图像拼接函数
to_image = Image.new('RGB', (IMAGE_COLUMN * 120, IMAGE_ROW * 46)) # 创建一个新图
# 循环遍历,把每张图片按顺序粘贴到对应位置上
for y in range(1, IMAGE_ROW + 1):
for x in range(1, IMAGE_COLUMN + 1):
from_image = Image.open(IMAGES_PATH + image_names[IMAGE_COLUMN * (y - 1) + x - 1]).resize(
(120, 46), Image.ANTIALIAS)
to_image.paste(from_image, ((x - 1) * 120, (y - 1) * 46))
to_image.save(IMAGE_SAVE_PATH) # 保存新图
| true |
52081ebc834c007467c98955fd2d1e1a743daf7a | Python | Ahmad-Khalid97/TimeCalculator | /TimeCalculator/time_calculator.py | UTF-8 | 3,851 | 3.375 | 3 | [] | no_license | def add_time(start, duration, *day):
start_time = start.split(':')
duration_time = duration.split(':')
mins = start_time[1]
hr12 = ''
added_string = ''
weekday_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
if len(day) != 0:
weekday = (list(day))[0].capitalize()
if mins.endswith('PM'):
hr12 = 'PM'
mins = mins.replace('PM', '')
else:
hr12 = 'AM'
mins = mins.replace('AM', '')
new_hrs = int(start_time[0]) + int(duration_time[0])
new_mins = int(mins) + int(duration_time[1])
if new_mins > 60:
extra_mins = new_mins // 60
new_mins -= 60 * extra_mins
new_hrs += 1
if 12 < new_hrs < 24:
if hr12 == 'AM':
hr12 = 'PM'
else:
hr12 = 'AM'
if (new_hrs // 12) == 1:
added_string = ' (next day)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + 1]
else:
added_string = f' ({new_hrs // 12} days later)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + ((new_hrs // 12) % 7)]
extra_hrs = new_hrs // 12
new_hrs -= 12 * extra_hrs
if new_hrs == 12:
if hr12 == 'PM':
hr12 = 'AM'
if (new_hrs // 12) == 1:
added_string = ' (next day)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + 1]
else:
added_string = f' ({new_hrs // 12} days later)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + ((new_hrs // 12) % 7)]
else:
hr12 = 'PM'
if 24 < new_hrs < 36:
if (new_hrs // 24) == 1:
added_string = ' (next day)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + 1]
else:
added_string = f' ({new_hrs // 24} days later)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + ((new_hrs // 12) % 7)]
extra_hrs = new_hrs // 12
new_hrs -= 12 * extra_hrs
if new_hrs == 24:
if (new_hrs // 24) == 1:
added_string = ' (next day)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + 1]
else:
added_string = f' ({new_hrs // 24} days later)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + ((new_hrs // 12) % 7)]
new_hrs -= 12
if new_hrs == 36:
if hr12 == 'PM':
hr12 = 'AM'
if (new_hrs // 12) == 1:
added_string = ' (next day)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + 1]
else:
added_string = f' ({(new_hrs // 12) - 1} days later)'
if len(day) != 0:
weekday = weekday_list[weekday_list.index(weekday) + (((new_hrs // 12) - 1) % 7)]
else:
hr12 = 'PM'
new_hrs -= 24
if new_hrs == 474:
if hr12 == 'PM':
hr12 = 'AM'
added_string = f' ({new_hrs // 24 + 1} days later)'
if len(day) != 0:
weekday = weekday_list[0]
new_hrs -= (new_hrs // 12) * 12
if new_mins >= 10:
new_time = f'{new_hrs}:{new_mins} {hr12}'
if len(day) != 0:
new_time += f', {weekday}'
new_time += added_string
else:
new_time = f'{new_hrs}:0{new_mins} {hr12}'
if len(day) != 0:
new_time += f', {weekday}'
new_time += added_string
return new_time
| true |
a50b4dfd089d72a5dfca4d94824d47f3d94100ed | Python | mastansberry/LeftOvers | /decimal_between_AK.py | UTF-8 | 813 | 4.21875 | 4 | [] | no_license | from __future__ import print_function
def quiz_decimal(low, high):
'''Prints whether user's number is between low and high
low and high are numeric types
returns None
'''
# Prompt fpr the value
print('Type a number between '+str(low)+' and '+str(high)+': ',end='' )
user_value = float(raw_input())
# Int inputs get converted to float. Revert this!
if int(user_value) == user_value:
user_value = int(user_value)
# Test and report
if user_value < low:
print('No, ' + str(user_value) + ' is less than ' + str(low))
elif user_value > high:
print('No, ' + str(user_value) + ' is greater than ' + str(high))
else:
print('Good! ' + str(low) + ' < ' + str(user_value) + ' < '+ str(high))
| true |
10576128960e69e1545f3401686fb332f851dee0 | Python | soarskyforward/algorithms | /fundamental/sort/heap.py | UTF-8 | 768 | 3.6875 | 4 | [] | no_license | """ HEAPSORT
"""
def left(i):
return 2 * i
def right(i):
return 2 * i + 1
def max_heapify(A, size, i):
l = left(i)
r = right(i)
largest = l if l < size and A[l] > A[i] else i
largest = r if r < size and A[r] > A[largest] else largest
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, size, largest)
def build_max_heap(A, size):
n = size / 2
for i in range(n-1,-1,-1):
max_heapify(A, size, i)
def sort(A):
"""
>>> sort([43, 2, 15, 81, 49, 4, 56, 11, 51, 97])
[2, 4, 11, 15, 43, 49, 51, 56, 81, 97]
"""
n = len(A)
build_max_heap(A, n)
for i in range(n-1,0,-1):
A[0], A[i] = A[i], A[0]
n -= 1
max_heapify(A, n, 0)
return A
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
b5bf8a8f3783114d0479d12e4a48f1503eefdc22 | Python | Dan-Staff/ml_flask_tutorial | /ml_flask_tutorial/run.py | UTF-8 | 2,975 | 2.796875 | 3 | [] | no_license | import os
import shutil
from flask import Flask, abort, jsonify, request
from flaskext.zodb import ZODB
from ml_flask_tutorial.models import LinearRegression, DeepThought
def load_model(db, payload):
if payload.get('type') == 'LinearRegression':
new_model = LinearRegression().from_dict(payload)
elif payload.get('type') == 'DeepThought':
new_model = DeepThought().from_dict(payload)
else:
new_model = None
return new_model
def create_app(testing=False):
"""Create a new flask application using ZODB as a lightweight backend
ZODB is a lightweight database which can be treated like a python dictionary.
Note: A real application would use a more fully featured database
:param testing: set True when unit testing, defaults to False
:type testing: bool, optional
:return: database handle and app instance tuple
"""
app = Flask(__name__)
if testing:
if os.path.isdir('test_db'):
shutil.rmtree('test_db')
os.mkdir('test_db')
app.config['ZODB_STORAGE'] = 'file://test_db/test.fs'
app.config['TESTING'] = True
else:
if os.path.isdir('db'):
shutil.rmtree('db')
os.mkdir('db')
app.config['ZODB_STORAGE'] = 'file://db/app.fs'
db = ZODB(app)
@app.route('/v1/models')
def models():
return jsonify([model for model in db.get('model', [])])
@app.route('/v1/models/<name>', methods=['POST', 'GET', 'DELETE'])
def linear_regression(name):
models = db.get('model', None)
if models is None:
db['model'] = {}
if request.method == 'POST':
payload = request.json
new_model = load_model(db, payload)
if new_model is None:
return abort(400)
db['model'][name] = new_model.to_dict()
return jsonify(new_model.to_dict())
if request.method == 'GET':
model = db.get('model', {}).get(name)
if model is None:
abort(404)
return jsonify(model)
if request.method == 'DELETE':
if name is None:
abort(404)
model = db['model'][name]
del db['model'][name]
return ('', 204)
@app.route('/v1/models/<name>/fit', methods=['PUT'])
def fit_model(name):
kwargs = db.get('model', {}).get(name)
if kwargs is None:
abort(404)
model = load_model(db, kwargs)
if model is None:
return abort(400)
xs = request.json.get('xs', [])
ys = request.json.get('ys', [])
model.fit(xs, ys)
db['model'][name] = model.to_dict()
return jsonify(model.to_dict())
@app.route('/v1/models/<name>/predict', methods=['GET'])
def predict_model(name):
return jsonify({})
return app, db
if __name__ == '__main__':
app, db = create_app()
app.run()
| true |
3686887819296f1cd79076bb93b4c0ccbe0c0eea | Python | 891760188/pythonDemo | /test02.py | UTF-8 | 196 | 2.984375 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
#打开一个文件
fo = open("foo.txt",'w')
print '文件名',fo.name,fo.closed,fo.mode,fo.softspace
fo.write("www.runoob.com!\nVery good site!\n我哦我")
fo.close();
| true |
837c51d1ce37841e32b34a23ba80a07c58bd93fa | Python | fzachariah/Gluster-Dashboard | /glusterDashboard-master/gitlab/lib/python3.5/site-packages/perceval/backends/telegram.py | UTF-8 | 12,634 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors:
# Santiago Dueñas <sduenas@bitergia.com>
#
import functools
import json
import logging
import os
import requests
from ..backend import Backend, BackendCommand, metadata
from ..cache import Cache
from ..errors import CacheError
from ..utils import urljoin
logger = logging.getLogger(__name__)
TELEGRAM_URL = 'https://telegram.org'
DEFAULT_OFFSET = 1
def telegram_metadata(func):
"""Telegram metadata decorator.
This decorator takes an item and overrides `metadata` decorator
to add extra information related to Telegram.
Currently, it adds the 'offset' keyword.
"""
@functools.wraps(func)
def decorator(self, *args, **kwargs):
for item in func(self, *args, **kwargs):
item['offset'] = item['data']['update_id']
yield item
return decorator
class Telegram(Backend):
"""Telegram backend.
The Telegram backend fetches the messages that a Telegram bot can
receive. Usually, these messages are direct or private messages but
a bot can be configured to receive every message sent to a channel/group
where it is subscribed. Take into account that messages are removed
from the Telegram server 24 hours after they are sent. Moreover, once
they are fetched using an offset, these messages are also removed. This
means every time this backend is called, messages will be deleted.
Initialize this class passing the name of the bot and the authentication
token used by this bot. The authentication token is provided by Telegram
once the bot is created.
:param bot: name of the bot
:param bot_token: authentication token used by the bot
:param cache: cache object to store raw data
:param origin: identifier of the repository; when `None` or an
empty string are given, it will be set to the `TELEGRAM_URL`
plus the name of the bot; i.e 'http://telegram.org/mybot'.
"""
version = '0.2.0'
def __init__(self, bot, bot_token, cache=None, origin=None):
origin = origin if origin else urljoin(TELEGRAM_URL, bot)
super().__init__(origin, cache=cache)
self.bot = bot
self.client = TelegramBotClient(bot_token)
@telegram_metadata
@metadata
def fetch(self, offset=DEFAULT_OFFSET, chats=None):
"""Fetch the messages the bot can read from the server.
The method retrieves, from the Telegram server, the messages
sent with an offset equal or greater than the given.
A list of chats, groups and channels identifiers can be set
using the parameter `chats`. When it is set, only those
messages sent to any of these will be returned. An empty list
will return no messages.
:param offset: obtain messages from this offset
:param chats: list of chat names used to filter messages
:returns: a generator of messages
:raises ValueError: when `chats` is an empty list
"""
logger.info("Looking for messages of '%s' bot from offset '%s'",
self.bot, offset)
if chats is not None:
if len(chats) == 0:
logger.warning("Chat list filter is empty. No messages will be returned")
else:
logger.info("Messages which belong to chats %s will be fetched",
'[' + ','.join(str(ch_id) for ch_id in chats) + ']')
self._purge_cache_queue()
nmsgs = 0
while True:
raw_json = self.client.updates(offset=offset)
# Due to Telegram deletes the messages from the server
# when they are fetched, the backend stores these messages
# in the cache before doing anything.
self._push_cache_queue(raw_json)
self._flush_cache_queue()
messages = [msg for msg in self.parse_messages(raw_json)]
if len(messages) == 0:
break
for msg in messages:
offset = max(msg['update_id'], offset)
if not self._filter_message_by_chats(msg, chats):
logger.debug("Message %s does not belong to any chat; filtered",
msg['message']['message_id'])
continue
yield msg
nmsgs += 1
offset += 1
logger.info("Fetch process completed: %s messages fetched",
nmsgs)
@telegram_metadata
@metadata
def fetch_from_cache(self):
"""Fetch the messages from the cache.
It returns the messages stored in the cache object provided during
the initialization of the object. If this method is called but
no cache object was provided, the method will raise a `CacheError`
exception.
:returns: a generator of messages
:raises CacheError: raised when an error occurs accesing the
cache
"""
if not self.cache:
raise CacheError(cause="cache instance was not provided")
logger.info("Retrieving cached messages: '%s'", self.bot)
cache_items = self.cache.retrieve()
nmsgs = 0
for raw_json in cache_items:
messages = [msg for msg in self.parse_messages(raw_json)]
for msg in messages:
yield msg
nmsgs += 1
logger.info("Retrieval process completed: %s messages retrieved from cache",
nmsgs)
def _filter_message_by_chats(self, message, chats):
"""Check if a message can be filtered based in a list of chats.
This method returns `True` when the message was sent to a chat
of the given list. It also returns `True` when chats is `None`.
:param message: Telegram message
:param chats: list of chat, groups and channels identifiers
:returns: `True` when the message can be filtered; otherwise,
it returns `False`
"""
if chats is None:
return True
chat_id = message['message']['chat']['id']
return chat_id in chats
@staticmethod
def metadata_id(item):
"""Extracts the identifier from a Telegram item."""
return str(item['message']['message_id'])
@staticmethod
def metadata_updated_on(item):
"""Extracts and coverts the update time from a Telegram item.
The timestamp is extracted from 'date' field that is inside
of 'message' dict. This date is converted to UNIX timestamp
format.
:param item: item generated by the backend
:returns: a UNIX timestamp
"""
ts = item['message']['date']
ts = float(ts)
return ts
@staticmethod
def parse_messages(raw_json):
"""Parse a Telegram JSON messages list.
The method parses the JSON stream and returns an iterator of
dictionaries. Each one of this, contains a Telegram message.
:param raw_json: JSON string to parse
:returns: a generator of parsed messages
"""
result = json.loads(raw_json)
messages = result['result']
for msg in messages:
yield msg
class TelegramCommand(BackendCommand):
"""Class to run Telegram backend from the command line."""
def __init__(self, *args):
super().__init__(*args)
self.bot = self.parsed_args.bot
self.backend_token = self.parsed_args.backend_token
self.outfile = self.parsed_args.outfile
self.origin = self.parsed_args.origin
self.offset = self.parsed_args.offset
self.chats = self.parsed_args.chats
if not self.parsed_args.no_cache:
if not self.parsed_args.cache_path:
base_path = os.path.expanduser('~/.perceval/cache/')
else:
base_path = self.parsed_args.cache_path
cache_path = os.path.join(base_path, TELEGRAM_URL, self.bot)
cache = Cache(cache_path)
if self.parsed_args.clean_cache:
cache.clean()
else:
cache.backup()
else:
cache = None
self.backend = Telegram(self.bot,
self.backend_token,
cache=cache,
origin=self.origin)
def run(self):
"""Fetch and print the messages.
This method runs the backend to fetch the messages from the
Telegram server. Bugs are converted to JSON objects and printed
to the defined output.
"""
if self.parsed_args.fetch_cache:
messages = self.backend.fetch_from_cache()
else:
messages = self.backend.fetch(offset=self.offset, chats=self.chats)
try:
for msg in messages:
obj = json.dumps(msg, indent=4, sort_keys=True)
self.outfile.write(obj)
self.outfile.write('\n')
except IOError as e:
raise RuntimeError(str(e))
except Exception as e:
if self.backend.cache:
self.backend.cache.recover()
raise RuntimeError(str(e))
@classmethod
def create_argument_parser(cls):
"""Returns the Telegram argument parser."""
parser = super().create_argument_parser()
# Remove --from-date argument from parent parser
# because it is not needed by this backend
action = parser._option_string_actions['--from-date']
parser._handle_conflict_resolve(None, [('--from-date', action)])
# Backend token is required
action = parser._option_string_actions['--backend-token']
action.required = True
# Optional arguments
parser.add_argument('--offset', dest='offset',
type=int, default=0,
help='Offset to start fetching messages')
parser.add_argument('--chats', dest='chats',
nargs='+', type=int, default=None,
help='Fetch only the messages of these chat identifiers')
# Required arguments
parser.add_argument('bot',
help='Name of the bot')
return parser
class TelegramBotClient:
"""Telegram Bot API 2.0 client.
This class implements a simple client to retrieve those messages
sent to a Telegram bot. This includes personal messages or
messages sent to a channel (when privacy settings are disabled).
:param bot_token: token for the bot
"""
API_URL = "https://api.telegram.org/bot%(token)s/%(method)s"
UPDATES_METHOD = 'getUpdates'
OFFSET = 'offset'
def __init__(self, bot_token):
self.bot_token = bot_token
def updates(self, offset=None):
"""Fetch the messages that a bot can read.
When the `offset` is given it will retrieve all the messages
that are greater or equal to that offset. Take into account
that, due to how the API works, all previous messages will
be removed from the server.
:param offset: fetch the messages starting on this offset
"""
params = {}
if offset:
params[self.OFFSET] = offset
response = self._call(self.UPDATES_METHOD, params)
return response
def _call(self, method, params):
"""Retrive the given resource.
:param resource: resource to retrieve
:param params: dict with the HTTP parameters needed to retrieve
the given resource
"""
url = self.API_URL % {'token' : self.bot_token, 'method' : method}
logger.debug("Telegram bot calls method: %s params: %s",
method, str(params))
r = requests.get(url, params=params)
r.raise_for_status()
return r.text
| true |
de0c36610cfbfaf25f8aa6d176a64318a0ec4ceb | Python | hkim0991/Project | /Telco_Customer_Churn/2.2_telco_feature_engineering_onehotencoding.py | UTF-8 | 7,330 | 3.109375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 02:09:13 2018
@author: kimi
"""
# Import libraries & funtions ------------------------------------------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
print(os.getcwd())
#os.chdir('C:/Users/202-22/Documents/Python - Hyesu/Project/telco')
os.chdir('D:/Data/Python/project')
# Load dataset ----------------------------------------------------------------
train_path = "../data/telco/telco_data_preprocessed.csv"
train = pd.read_csv(train_path, engine='python')
train.shape # 7043 x 21
train.head()
train.info()
train.isnull().sum() # no missing value
train.describe()
# 20 predictor variables and 1 target variable('Churn')
train['Churn'].value_counts() # no:5174, yes:1869
# Modeling - Decision Tree Classification -------------------------------------
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
train2 = train.copy()
X_train = train2.drop('Churn',axis=1, inplace=True)
y_train = train['Churn']
X_tr, X_va, y_tr, y_va = train_test_split(X_train, y_train, test_size=0.3, random_state=0)
print(X_tr.shape, y_tr.shape)
print(X_va.shape, y_va.shape)
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_tr, y_tr)
# !! ISSUE !!: this model only consider numerical categorical featutres as categorical features.
# Solution 2 - One-hot encoding -----------------------------------------------
# gather only categorical features for one-hot encoding process
category = ['gender', 'SeniorCitizen', 'Partner', 'Dependents', 'PhoneService',
'MultipleLines', 'InternetService', 'OnlineSecurity', 'OnlineBackup',
'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies',
'Contract', 'PaperlessBilling', 'PaymentMethod']
cat_data = pd.DataFrame(data=train, columns=category)
cat_data.shape
print('features from original data: \n', list(cat_data.columns))
# apply 'get_dummies' function to cat_data
data_dummies = pd.get_dummies(cat_data)
print('features after get_dummies: \n', list(data_dummies.columns))
data_dummies.head()
# Back to Modeling - Decision Tree Classification -----------------------------
# Data combination: encoded categorical features + continuous features
continuous = ['tenure', 'MonthlyCharges', 'TotalCharges']
cond_data = pd.DataFrame(data=train, columns= continuous)
final_data = pd.concat([cond_data, data_dummies], axis=1)
final_data.info()
# write the data after one-hot-encoding into a csv
# final_data.to_csv('telco_data_after_onehotencoding.csv', index=False)
# Train/Test data partition ---------------------------------------------------
X_train = final_data
y_train = train['Churn']
X_tr, X_va, y_tr, y_va = train_test_split(X_train, y_train, test_size=0.3, random_state=0)
print(X_tr.shape, y_tr.shape)
print(X_va.shape, y_va.shape)
# Standarization of the features
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_tr)
X_tr_scaled = scaler.transform(X_tr)
X_va_scaled = scaler.transform(X_va)
# Modeling - Decision Tree Classification -------------------------------------
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_tr_scaled, y_tr)
print("train data accuracy: {:.3f}".format(tree.score(X_tr_scaled, y_tr))) # 0.997
print("test data accuracy: {:.3f}".format(tree.score(X_va_scaled, y_va))) # 0.733 -> overfitting
# Decision Tree visualization -------------------------------------------------
from sklearn.tree import export_graphviz
from IPython.display import Image
from graphviz import Source
import pydotplus
import graphviz
data_feature_names = final_data.columns.values.tolist()
dot_data = export_graphviz(tree, out_file=None,
feature_names= data_feature_names,
class_names='Churn')
graph = Source(dot_data)
png_bytes = graph.pipe(format='png')
with open ('dtree_pipe_onehot.png', 'wb') as f:
f.write(png_bytes)
Image(png_bytes)
#graph = pydotplus.graph_from_dot_data(dot_data)
#Image(graph.create_png())
# Feature importance ----------------------------------------------------------
print("feature importance:\n{}".format(tree.feature_importances_))
def plot_feature_importances_telco(model):
n_features = final_data.shape[1]
plt.barh(range(n_features), model.feature_importances_, align='center')
plt.yticks(np.arange(n_features), final_data.columns)
plt.xlabel("feature importance")
plt.ylabel('features')
plt.ylim(-1, n_features)
fig = plt.figure(figsize=(10,8))
plot_feature_importances_telco(tree)
## find out the most highest accuracy for test dataset ------------------------
max=0; numMax= 0; cnt= 0
l1 = []
lni = []
lnr = []
for i in range(5, 21):
for j in range(10, 51):
for n in range(2, 6, 1):
print("trial #:", cnt, "\n", "max_depth: ", i, "| max_leaf_nodes: ", j, "| min_samples_leaf: ", n)
tree = DecisionTreeClassifier(max_depth = i, # original model : 25
max_leaf_nodes = j,
min_samples_leaf = n,
random_state=0)
tree.fit(X_tr_scaled, y_tr)
treetest = tree.score(X_va_scaled, y_va)
print("train data accuracy: {:.3f}".format(tree.score(X_tr_scaled, y_tr)))
print("test data accuracy: {:.3f}".format(tree.score(X_va_scaled, y_va)))
lni.append(tree.score(X_tr_scaled, y_tr))
lnr.append(tree.score(X_va_scaled, y_va))
cnt += 1
l1.append(cnt)
if max < treetest:
max = treetest
numMax = cnt
print(max, numMax)
# 0.794131566493 69
# Ploting the results ---------------------------------------------------------
fig = plt.figure(figsize=(10,8))
plt.plot(lni, "--", label="train set", color="blue")
plt.plot(lnr, "-", label="test set", color="red")
plt.plot(numMax, max, "o")
ann = plt.annotate("is" % str(n))
plt.legend()
plt.show()
# Final model with tuning parameters ------------------------------------------
# trial #: 68
# max_depth: 5 | max_leaf_nodes: 27 | min_samples_leaf: 2
# train data accuracy: 0.809
# test data accuracy: 0.794
tree_final = DecisionTreeClassifier(max_depth=5,
max_leaf_nodes= 27,
min_samples_leaf = 2,
random_state=0)
tree_final.fit(X_tr_scaled, y_tr)
print("train data accuracy: {:.3f}".format(tree_final.score(X_tr_scaled, y_tr))) # 0.809
print("test data accuracy: {:.3f}".format(tree_final.score(X_va_scaled, y_va))) # 0.794
# Decision Tree Model Visualization after tuning ------------------------------
dot_data3 = export_graphviz(tree_final, out_file=None,
feature_names = data_feature_names,
class_names='Churn', filled=True)
graph = Source(dot_data3)
png_bytes = graph.pipe(format='png')
with open ('dtree_pipe_onehot_final.png', 'wb') as f:
f.write(png_bytes)
Image(png_bytes)
# Feature importance after tuning ---------------------------------------------
fig = plt.figure(figsize=(10,8))
plot_feature_importances_telco(tree_final)
| true |
8bb52ba0f4d738913805bc16702698b43671c119 | Python | ankitoct/Core-Python-Code | /21. Numpy One D Ones Function/1. onesFunction.py | UTF-8 | 511 | 4.46875 | 4 | [] | no_license | # 1D Array using ones Function Numpy
from numpy import *
a = ones(5)
#a = ones(5, dtype=int)
print("**** Accessing Individual Elements ****")
print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[4])
print()
print("**** Accessing by For Loop ****")
for el in a:
print(el)
print()
print("**** Accessing by For Loop with Index ****")
n = len(a)
for i in range(n):
print('index',i,'=',a[i])
print()
print("**** Accessing by While Loop ****")
n = len(a)
i = 0
while i < n:
print('index',i,'=',a[i])
i+=1 | true |
8ea8e43d465d8ea0d925b2691853668345b4bd08 | Python | colbydarrah/cis_202_book_examples | /CH9_serialized_objects.py | UTF-8 | 2,962 | 3.65625 | 4 | [] | no_license | # Colby Darrah
# 3/23/2021
# pg 506
# Serialized Objects
# 1. pickling object pg 506
# 2. unpickling object pg 507
# * serializing an object it is converted to a stream of bytes that can be easily stored
# in a file for later retrieval.
# * sets, dictionaries, lists, tuples, strings, integers, floating points.can all be serialized
# * This process is referred to as "pickling".
# * 'import pickle' module to perform steps to pickle an jobect.
# -open a file for binary writing.
# - call the pickle module's dump method to pickle object & write to specific file.
# - after all objects pickled and saved to file, close file.
def main():
# 1. ------ PICKLING OBJECTS TO A FILE ---------------------------------------------------------------
# statement opens a file named mydata.dat for binary writing.
outputfile = open('mydata.dat', 'wb') # use 'wb' as mode when opening a file for binary writing.
# once file is open for binary writing, call the 'pickle module's' dump function:
pickle.dump(object, file) #'object' = variable to pickle
# 'file' = is a variable that references a file object
#save as many pickled objects as you want, then use close method to close file.
#----EXAMPLE - EXAMPLE - EXAMPLE - EXAMPLE ----------
# import pickle module
import pickle
# create dictionary
phonebook = {'Chris':'444-3333', 'Katie': '111-2222', 'Joanne': '222-4444'}
# open a file named phonebook.dat for binary writing.
output_file = open('phonebook.dat', 'wb')
# call the pickle modules dump function to serialize phonebook dictionary
# and write it to the phonebook.dat file
pickle.dump(phonebook, output_file)
# close the phonebook.dat file
output_file.close()
# 2. ------ UNPICKLING / RETRIEVING OBJECTS TAHT HAVE BEEN PICKLED -----------------------------------
# open file for 'binary reading' = 'rb':
inputfile = open('mydata.dat', 'rb')
# call the pickle modules load function retrieve object and unpickle
object = pickle.load(file) # OBJECT is a variable
# FILE is variable that references a file object.
# you can unpickle as many objects as necessary from the file.
# once finished, close the the file.
# ---- EXAMPLE EXAMPLE EXAMPLE EXAMPLE ---
# inport pickle module
import pickle
# open file named phonebook.dat for binary reading
input_file = open('phonebook.dat', 'rb')
# calls pickle module's 'load function' to get and unpickle object from phonebook.dat file
# assign that object to variable 'pb'.
pb = pickle.load(inputfile)
pb
## pb now equals: {'Chris':'444-3333', 'Katie': '111-2222', 'Joanne': '222-4444'}
# close file
input_file.close()
# Call the main function
if __name__ == '__main__':
main() | true |
c0a9fd4d09506aa7cd4dba319b5c9ad069339cfb | Python | S-EmreCat/PythonKursuDersleri | /03-Obje ve Veri Yapıları/lists+3.13uygulama.py | UTF-8 | 782 | 4.09375 | 4 | [] | no_license |
# list=['one','two']
# list2=[3,4,5]
# list3=list+list2 # bu şekilde 2 liste toplanabilir listenin elemanları birbirinden fakrlı olabilir
# # print(len(list3)) # len metodu ile listede kaç eleman var bulunur
# #print(list3[3]) #3. elemanı bastırmak
# # kullanı bilgilerini ayrı eleman olarak bir listede tutma şekli
# k1=["Emre",23]
# k2=["Enes",17]
# kullanıcılar=[k1,k2]
# print(kullanıcılar[0][1]) #kullanıcılar dizisinden 1. elamanın 1. indisli elemanı
###### 3.13 UYGULAMA LISTS METHODS ########
list=['Bmw','Mercedes','Opel','Mazda']
# print(f"{len(list)} tane elemanı var")
# print(f"ilk elemanı {list[0]} son elemanı {list[-1]}")
# list[-1]="Totoya"
# print(list) 4
# if 'Mercedes' in list:
# print("Mercedes var") | true |
43c0cb57658a168bfb7951f6f3388917a528cf1a | Python | Inazuma110/atcoder | /cpp/icpcmogi2018/c/main.py | UTF-8 | 881 | 3.046875 | 3 | [] | no_license | import sys
sys.setrecursionlimit(1000000)
from operator import *
ops = {'+':lambda x1, x2: x1 | x2, '*': lambda x1, x2: x1 & x2, '^': lambda x1, x2: x1 ^ x2}
def f(op, s1, s2):
return ops[op](s1, s2)
def toN(s, numbers):
for abc, number in zip(letters, list(numbers)):
s = s.replace(abc, number)
return s
letters = list("abcd")
def solve(S, P):
origin = S
S = S.replace('[', 'f(')
S = S.replace(']', '),')
for k in ops.keys():
S = S.replace(k, "'" + k + "',")
for l in letters:
S = S.replace(l, l + ",")
transed = S
# print(S)
res = eval(toN(S, P))[0]
print(res, end=' ')
count = 0
for i in range(10000):
if res == eval(toN(S, "{:04d}".format(i)))[0]:
count += 1
print(count)
while True:
S = input()
if S == '.':
break
P = input()
solve(S, P) | true |
ebe192a8ffda5a2678cfc46c22f6860d4dbae3a6 | Python | chrisgorgo/ClimbingStats | /src/scrappers/route.py | UTF-8 | 3,071 | 2.5625 | 3 | [] | no_license | '''
Created on 21 Nov 2010
@author: Filo
'''
import urllib2, re
from lxml import etree
from StringIO import StringIO
from datetime import datetime
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data).strip()
def find_date(string):
p = re.compile("\d\d/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/\d\d")
date_str = p.search(string)
if date_str == None:
return date_str
return datetime.strptime(date_str.group(), "%d/%b/%y").date()
class Route(object):
'''
classdocs
'''
def __init__(self, id, crag_id):
'''
Constructor
'''
self.id = id
self.crag_id = crag_id
def scrap(self):
filehandle = urllib2.urlopen('http://www.ukclimbing.com/logbook/c.php?i=%d'%self.id)
content = filehandle.read()
parser = etree.HTMLParser()
tree = etree.parse(StringIO(content), parser)
self.name = tree.xpath(".//font[@size=5]/b")[0].text
grade_node = tree.xpath(".//td[@align='right']/b")[0]
grade_split = etree.tostring(grade_node, method="text").strip().split()
self.grade1 = grade_split[0]
if len(grade_split) == 2:
self.grade2 = grade_split[1]
else:
self.grade2 = None
log_entries = tree.xpath(".//table[@cellpadding='5']")[0]
log_entries_text = etree.tostring(log_entries)
self.log_entries = []
if log_entries_text.find("<i>This climb isn't in any logbooks") != -1:
self.log_entries = []
else:
self.log_entries = []
cur_com = None
cur_date = ""
log_entries_text = re.sub("This climb is in \d+ logbook[s]*, and on .* wishlist[s]*.", "", log_entries_text)
log_entries_text = log_entries_text.replace("PUBLIC LOGBOOKS","")
for bit in log_entries_text.split("<br />"):
if bit.startswith("<img src="):
cur_com = None
cur_date = ""
continue
elif bit.find('<font color="#666666"') != -1:
cur_date = find_date(bit)
self.log_entries.append((cur_com, cur_date))
cur_com = None
cur_date = ""
elif bit.find('Users with this climb on their wishlist are') != -1:
break
else:
cur_com = remove_html_tags(bit)
filehandle.close()
def save(self, c):
c.execute("INSERT OR REPLACE INTO routes (id, name, grade1, grade2, crag_id) VALUES (?,?,?,?,?)", (self.id, self.name, self.grade1, self.grade2, self.crag_id))
c.execute("DELETE FROM logs WHERE route_id = ?", (self.id,))
for log in self.log_entries:
c.execute("INSERT OR REPLACE INTO logs (date, comment, route_id) VALUES (?,?,?)", (log[1], log[0], self.id))
| true |
9d73396dd2eb31d384fafd6f81571e27e877d387 | Python | aayush-kushwaha/python_programming_practice | /Chapter-3/08_pr_04.py | UTF-8 | 119 | 3.859375 | 4 | [] | no_license | #Program to replace double space with single space
st = "I am Aayush Kushwaha"
st = st.replace(" ", " ")
print(st) | true |
0492feeeb2faefc255f07bde4e396829c3db9ac0 | Python | anqichen12/tweeTrend | /real-time/producer.py | UTF-8 | 1,822 | 2.75 | 3 | [] | no_license | import tweepy
import time
from kafka import KafkaConsumer, KafkaProducer
import jsonpickle
from kafka import SimpleProducer, KafkaClient
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
from datetime import datetime, timedelta
# twitter setup
consumer_key = "*"
consumer_secret = "*"
access_token = "*"
access_token_secret = "*"
# Creating the authentication object
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# Setting your access token and secret
auth.set_access_token(access_token, access_token_secret)
# Creating the API object by passing in auth information
api = tweepy.API(auth)
def normalize_timestamp(time):
mytime = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
mytime -= timedelta(hours=4) # the tweets are timestamped in GMT timezone, while I am in -4 timezone
return (mytime.strftime("%Y-%m-%d %H:%M:%S"))
topic_name = "twitter"
producer = KafkaProducer(bootstrap_servers='*',batch_size=100000,linger_ms=100)
class StdOutListener(StreamListener):
def on_status(self, status):
msg_info = {'text':status.text,'time':normalize_timestamp(str(status.created_at))}
producer.send(topic_name, json.dumps(msg_info))
def on_error(self, status_code):
if status_code == 420:
return False
if __name__ == "__main__":
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
artist_list = set()
with open('../data/lower-artist.csv', 'r') as f:
count =1
for i in f:
cur = i.split("\n")[0]
if count in range(400):
artist_list.add(cur)
count+=1
stream.filter(track=artist_list)
| true |
fa1b887d23a1c9155909b2b961f66d869dec1a93 | Python | AaronRodden/GameAI-FinalProject | /The_Game/classifiers/classifier.py | UTF-8 | 2,147 | 2.625 | 3 | [] | no_license | import keras
import numpy as np
import pandas as pd
import cv2
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D, Dense,Flatten, Dropout
from keras.datasets import mnist
import matplotlib.pyplot as plt
from keras.utils import np_utils
from keras.optimizers import SGD
# https://medium.com/analytics-vidhya/sign-language-recognition-using-cnn-and-opencv-beginner-level-72091ca35a19
# PREPROCESSING DATA ------------------------------------------------------------------
data_test = pd.read_csv("../../dataset/sign_mnist_test.csv")
data_train = pd.read_csv("../../dataset/sign_mnist_train.csv")
y_train = data_train['label'].values
y_test = data_test['label'].values
X_train = data_train.drop(['label'],axis=1)
X_test = data_test.drop(['label'], axis=1)
X_train = np.array(X_train.iloc[:,:])
X_train = np.array([np.reshape(i, (28,28)) for i in X_train])
X_test = np.array(X_test.iloc[:,:])
X_test = np.array([np.reshape(i, (28,28)) for i in X_test])
num_classes = 26
y_train = np.array(y_train).reshape(-1)
y_test = np.array(y_test).reshape(-1)
y_train = np.eye(num_classes)[y_train]
y_test = np.eye(num_classes)[y_test]
X_train = X_train.reshape((27455, 28, 28, 1))
X_test = X_test.reshape((7172, 28, 28, 1))
# CNN ---------------------------------------------------------------------
model = Sequential()
model.add(Conv2D(64, kernel_size=(3,3), activation = 'relu', input_shape=(28, 28 ,1) ))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Conv2D(64, kernel_size = (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Conv2D(64, kernel_size = (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Flatten())
model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.20))
model.add(Dense(num_classes, activation = 'softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=100)
accuracy = model.evaluate(x=X_test,y=y_test,batch_size=32)
print("Accuracy: ",accuracy[1])
model.save('CNNmodel.h5')
| true |
ea9a8725544eacb62cb70c867ffd3f3576b391a1 | Python | 5samuel/juego-samuel | /app.py | UTF-8 | 749 | 3.234375 | 3 | [] | no_license | import pygame
import sys
#constatnte
ancho= 800
alto= 600
color_rojo=(255,0,0)
#jugador
jugador_pos =[400,400]
jugador_size=50
#crear ventana
ventana = pygame.display.set_mode((ancho, alto))
game_over = False
#cerrar ventana
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
X= jugador_pos[0]
if event.hey == pygame.K_LEFT:
X -=jugador_size
if event.type== pygame.K_RIGHT:
x +=jugador_size
jugador_pos [0] = x
#Crear pensonaje
pygame.draw.rect(ventana, color_rojo, (jugador_pos[0],jugador_pos[1], jugador_size,jugador_size))
pygame.display.update() | true |
39f47ecca761ac07d5adee1e28aad5d44ccd4116 | Python | robertobadjio/xlsx-parser | /xlsx-parser.py | UTF-8 | 424 | 2.5625 | 3 | [] | no_license | from openpyxl import load_workbook
wb = load_workbook('')
sheet = wb.get_sheet_by_name('')
import peewee
from peewee import *
db = MySQLDatabase('test', user='root', password='root', host='localhost', port=3316)
Data1 = Table('table1', ('id', 'name'))
Data1 = Data1.bind(db)
maxCountRow = sheet.max_row
for i in range(2, maxCountRow):
value = sheet['C' + str(i)].value
Data1.insert(name=value).execute()
| true |
209e265a7011e82db97ab1c90606e2357cada13e | Python | N0NamedGuy/Bitcho | /plugins/console.py | UTF-8 | 1,956 | 2.859375 | 3 | [] | no_license | '''
Created on Nov 6, 2011
@author: David
'''
from plugin_base import PluginBase
from fun_thread import FunThread
import sys
class ConsolePlugin(PluginBase):
def work(self):
while True:
sys.stdout.write("> ")
line = sys.stdin.readline()
if line == "": return
line = line.rstrip("\r\n")
self.parse(line)
def parse(self, line):
if line == "": return
if line.startswith("/"):
line = line[1:]
print "Sending: '" + line + "'"
self.bot.send(line)
def plugin_init(self):
# TODO: Process more events
self.register_event("connect", self.run_it)
self.register_event("channel_msg", self.on_channel_msg)
self.register_event("priv_msg", self.on_priv_msg)
self.register_event("join", self.on_join)
self.register_event("part", self.on_part)
self.register_event("quit", self.on_quit)
self.register_event("numeric", self.on_numeric)
self.register_event("cmd_raw", self.on_raw_cmd)
def run_it(self):
FunThread(self.work, []).start()
def on_raw_cmd(self, user, channel, cmd, args):
self.parse(" ".join(args))
def on_join(self, user, channel):
print "* %s joined %s" % (user, channel)
def on_part(self, user, channel, msg):
print "* %s left %s (%s)" % (user, channel, msg)
def on_quit(self, user, reason):
print "* %s has quit (%s)" % (user, reason)
def on_channel_msg(self, user, channel, msg):
print "<%s@%s> %s" % (user, channel, msg)
def on_priv_msg(self, user, msg):
print "<%s> %s" % (user, msg)
def on_numeric(self, *tokens):
sys.stdout.write("* ")
for token in tokens:
sys.stdout.write("%s " % (str(token)))
sys.stdout.write("\n")
| true |
0b89ec81ff2a830a68a6da145d9baf378f90f337 | Python | Junga15/Keras2 | /keras2.0/keras10_mlp5_badtest.py | UTF-8 | 6,813 | 2.84375 | 3 | [] | no_license | <<<<<<< HEAD:keras2.0/keras10_mlp5_badtest.py
#keras10_mlp5_badtest.py 실습
#다:다 mlp(다대다 다층퍼셉트론)
#이해 안되는 부분: #3.훈련,평가부분 train size에 대한 주석(앞부분 공부미흡,20210105)
#실습:모델 완전히 쓰레기로 만들어보기
#목표 R2: 0.5이하 / 음수는 안됨
#조건 #2.모델구성부분 layer: 5개 이상,node: 각 10개 이상
#3.훈련,평가 부분 batch_size: 8개 이하, epochs: 30이상
'''
x_test,y_test에 대한 로스외의 값
loss: 0.01810389757156372
mae: 0.1155942901968956
RMSE: 23.285525356035976
R2: 0.31393543675679453
y_pred2값
[[399.54288 53.298798]]
하이퍼파라미터 튜닝: 그냥 제시된 조건대로만 적용하고, layer 한층추가함
'''
#1.데이터 구성
import numpy as np
x=np.array([range(100),range(301,401),range(1,101),range(100),range(301,401)])
y=np.array([range(711,811),range(1,101)])
print(x.shape) #(5,100)
print(y.shape) #(2,100)
x_pred2=np.array([100,402,101,100,401]) #shape (5,) 따라서 다음작업
#y_pred2는 811,101 나올 것이라 유추가능 (2,) [[811,101]]=>(1,2)로 나옴
print("x_pred2.shape:",x_pred2.shape) #transpose출력 전 #(5,)=>스칼라가 5개인 1차원=[1,2,3,4,5]
x=np.transpose(x)
y=np.transpose(y)
#x_pred2=np.transpose(x_pred2) #출력 후 값이 (5,)이므로 아래실행
x_pred2=x_pred2.reshape(1,5)
print(x.shape) #(100,5)
print(y.shape) #(100,2)
print(x_pred2.shape)
print("x_pred2.shape:",x_pred2.shape) #transpose출력 후 #(5,) -> #(1,5)=>행무시 input_dim=5인 [[1,2,3,4,5]]
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,shuffle=True,test_size=0.2,random_state=66) #행을 자르는 것
#위에 순서대로, 셔플은 섞는다(True)=>랜덤때문에 자꾸바뀜, 따라서, 랜덤단수를 고정함
print(x_test.shape) #(20,5)
print(y_test.shape) #(20,2)
#2.모델구성
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
#from keras.layers import Dense
model=Sequential()
model.add(Dense(10,input_dim=5)) #(100,5) 이므로 칼럼의 갯수인 dim=5
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(2)) #(100,2)이므로 나가는 y의 피쳐,칼럼,특성은 2개
#3.컴파일,훈련
model.compile(loss='mse',optimizer='adam',metrics=['mae'])
model.fit(x_train,y_train,epochs=30,batch_size=8,validation_split=0.2) #각 칼럼별로 20%, x중 1,2 and 11,12
#val_x_test(4,5),c
#train_size를 0.8로 정의했을 때 16
#print('x_validation:',x_validation): x_validation이 정의되지 않았음
# #val_x, val_y
#4.평가,예측
loss,mae=model.evaluate(x_test,y_test)
print('loss:',loss)
print('mae:',mae)
y_predict=model.predict(x_test) #y_test와 유사한 값=y_predict
print(y_predict)
from sklearn.metrics import mean_squared_error
def RMSE(y_test,y_predict):
return np.sqrt(mean_squared_error(y_test,y_predict))
print("RMSE:",RMSE(y_test,y_predict))
#print("mse:",mean_squared_error(y_test,y_predict))
#print("mse:",mean_squared_error(y_predict,y_test))
from sklearn.metrics import r2_score
r2=r2_score(y_test,y_predict)
print("R2:",r2)
y_pred2=model.predict(x_pred2)
=======
#keras10_mlp5_badtest.py 실습
#다:다 mlp(다대다 다층퍼셉트론)
#이해 안되는 부분: #3.훈련,평가부분 train size에 대한 주석(앞부분 공부미흡,20210105)
#실습:모델 완전히 쓰레기로 만들어보기
#목표 R2: 0.5이하 / 음수는 안됨
#조건 #2.모델구성부분 layer: 5개 이상,node: 각 10개 이상
#3.훈련,평가 부분 batch_size: 8개 이하, epochs: 30이상
'''
x_test,y_test에 대한 로스외의 값
loss: 0.01810389757156372
mae: 0.1155942901968956
RMSE: 23.285525356035976
R2: 0.31393543675679453
y_pred2값
[[399.54288 53.298798]]
하이퍼파라미터 튜닝: 그냥 제시된 조건대로만 적용하고, layer 한층추가함
'''
#1.데이터 구성
import numpy as np
x=np.array([range(100),range(301,401),range(1,101),range(100),range(301,401)])
y=np.array([range(711,811),range(1,101)])
print(x.shape) #(5,100)
print(y.shape) #(2,100)
x_pred2=np.array([100,402,101,100,401]) #shape (5,) 따라서 다음작업
#y_pred2는 811,101 나올 것이라 유추가능 (2,) [[811,101]]=>(1,2)로 나옴
print("x_pred2.shape:",x_pred2.shape) #transpose출력 전 #(5,)=>스칼라가 5개인 1차원=[1,2,3,4,5]
x=np.transpose(x)
y=np.transpose(y)
#x_pred2=np.transpose(x_pred2) #출력 후 값이 (5,)이므로 아래실행
x_pred2=x_pred2.reshape(1,5)
print(x.shape) #(100,5)
print(y.shape) #(100,2)
print(x_pred2.shape)
print("x_pred2.shape:",x_pred2.shape) #transpose출력 후 #(5,) -> #(1,5)=>행무시 input_dim=5인 [[1,2,3,4,5]]
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,shuffle=True,test_size=0.2,random_state=66) #행을 자르는 것
#위에 순서대로, 셔플은 섞는다(True)=>랜덤때문에 자꾸바뀜, 따라서, 랜덤단수를 고정함
print(x_test.shape) #(20,5)
print(y_test.shape) #(20,2)
#2.모델구성
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
#from keras.layers import Dense
model=Sequential()
model.add(Dense(10,input_dim=5)) #(100,5) 이므로 칼럼의 갯수인 dim=5
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(2)) #(100,2)이므로 나가는 y의 피쳐,칼럼,특성은 2개
#3.컴파일,훈련
model.compile(loss='mse',optimizer='adam',metrics=['mae'])
model.fit(x_train,y_train,epochs=30,batch_size=8,validation_split=0.2) #각 칼럼별로 20%, x중 1,2 and 11,12
#val_x_test(4,5),c
#train_size를 0.8로 정의했을 때 16
#print('x_validation:',x_validation): x_validation이 정의되지 않았음
# #val_x, val_y
#4.평가,예측
loss,mae=model.evaluate(x_test,y_test)
print('loss:',loss)
print('mae:',mae)
y_predict=model.predict(x_test) #y_test와 유사한 값=y_predict
print(y_predict)
from sklearn.metrics import mean_squared_error
def RMSE(y_test,y_predict):
return np.sqrt(mean_squared_error(y_test,y_predict))
print("RMSE:",RMSE(y_test,y_predict))
#print("mse:",mean_squared_error(y_test,y_predict))
#print("mse:",mean_squared_error(y_predict,y_test))
from sklearn.metrics import r2_score
r2=r2_score(y_test,y_predict)
print("R2:",r2)
y_pred2=model.predict(x_pred2)
>>>>>>> e4d20bf972fb001f76ae90d52362c18532f65c9e:keras10_mlp5_badtest.py
print(y_pred2) | true |
9ba3dee5c67258a7eb1df12639e1e300ad579016 | Python | Aasthaengg/IBMdataset | /Python_codes/p00002/s324384362.py | UTF-8 | 108 | 2.78125 | 3 | [] | no_license | import fileinput
for line in fileinput.input():
a, b = map(int, line.split())
print(len(str(a + b))) | true |
dd13f5db75027378796c5f2f7df518adf5a18149 | Python | niwanowa/Information_Theory | /nattobit.py | UTF-8 | 148 | 2.796875 | 3 | [] | no_license | import math
def main():
nat = float(input("nat : "))
bit = nat * math.log2(math.e)
print(bit)
if __name__ == '__main__':
main()
| true |
44388d063f1af6e1ba9f1fba83580b265c9e43fa | Python | m-den-i/bot-server | /channel/contacts.py | UTF-8 | 473 | 2.6875 | 3 | [] | no_license | from typing import Dict
from channel.exceptions import ContactNotFoundException
class Contact:
def id(self):
raise NotImplementedError()
class AddressBook:
def __init__(self):
self.contacts: Dict[str, Contact] = {}
def find_contact(self, search_term: str) -> Contact:
if search_term in self.contacts:
return self.contacts[search_term]
raise ContactNotFoundException('Contact {} not found'.format(search_term))
| true |
6b5abd87a32a158a25cef67e0ac35a1769d0aa53 | Python | ahwinemman/ai_ml_uwaterloo | /ECE 657/Spring 2021/Assignment_2/A2_Q3.py | UTF-8 | 6,809 | 2.6875 | 3 | [] | no_license | import SimpSOM as sps
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from minisom import MiniSom
from sklearn.metrics import mean_squared_error
from sklearn.cluster import KMeans
from random import seed
from random import randint
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.losses import MSE
# from rbflayer import RBFLayer, InitCentersRandom
# from kmeans_initializer import InitCentersKMeans
# from initializer import InitFromFile
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras.initializers import RandomUniform, Initializer, Constant
import numpy as np
from tensorflow.keras.initializers import Initializer
from sklearn.cluster import KMeans
class InitCentersRandom(Initializer):
""" Initializer for initialization of centers of RBF network
as random samples from the given data set.
# Arguments
X: matrix, dataset to choose the centers from (random rows
are taken as centers)
"""
def __init__(self, X):
self.X = X
super().__init__()
def __call__(self, shape, dtype=None):
assert shape[2:] == self.X.shape[2:] # check dimension
# np.random.randint returns ints from [low, high) !
idx = np.random.randint(self.X.shape[0], size=shape[0])
return self.X[idx, :]
class RBFLayer(Layer):
""" Layer of Gaussian RBF units.
# Example
```python
model = Sequential()
model.add(RBFLayer(10,
initializer=InitCentersRandom(X),
betas=1.0,
input_shape=(1,)))
model.add(Dense(1))
```
# Arguments
output_dim: number of hidden units (i.e. number of outputs of the
layer)
initializer: instance of initiliazer to initialize centers
betas: float, initial value for betas
"""
def __init__(self, output_dim, initializer=None, betas=1.0, **kwargs):
self.output_dim = output_dim
# betas is either initializer object or float
if isinstance(betas, Initializer):
self.betas_initializer = betas
else:
self.betas_initializer = Constant(value=betas)
self.initializer = initializer if initializer else RandomUniform(
0.0, 1.0)
super().__init__(**kwargs)
def build(self, input_shape):
self.centers = self.add_weight(name='centers',
shape=(self.output_dim, input_shape[1]),
initializer=self.initializer,
trainable=True)
self.betas = self.add_weight(name='betas',
shape=(self.output_dim,),
initializer=self.betas_initializer,
# initializer='ones',
trainable=True)
super().build(input_shape)
def call(self, x):
C = tf.expand_dims(self.centers, -1) # inserts a dimension of 1
H = tf.transpose(C-tf.transpose(x)) # matrix of differences
return tf.exp(-self.betas * tf.math.reduce_sum(H**2, axis=1))
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
def get_config(self):
# have to define get_config to be able to use model_from_json
config = {
'output_dim': self.output_dim
}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
class InitCentersKMeans(Initializer):
""" Initializer for initialization of centers of RBF network
by clustering the given data set.
# Arguments
X: matrix, dataset
"""
def __init__(self, X, max_iter=100):
self.X = X
self.max_iter = max_iter
super().__init__()
def __call__(self, shape, dtype=None):
assert shape[1:] == self.X.shape[1:]
n_centers = shape[0]
km = KMeans(n_clusters=n_centers, max_iter=self.max_iter, verbose=0)
km.fit(self.X)
return km.cluster_centers_
class InitFromFile(Initializer):
""" Initialize the weights by loading from file.
# Arguments
filename: name of file, should by .npy file
"""
def __init__(self, filename):
self.filename = filename
super().__init__()
def __call__(self, shape, dtype=None):
with open(self.filename, "rb") as f:
X = np.load(f, allow_pickle=True) # fails without allow_pickle
assert tuple(shape) == tuple(X.shape)
return X
def get_config(self):
return {
'filename': self.filename
}
# Create a list for X1
sample = []
for _ in range(441):
value = randint(-2, 2)
sample.append(value)
# sample = tuple(sample)
# create a list for X2
sample2 = []
for _ in range(441):
value = randint(-2, 2)
sample2.append(value)
# sample2 = tuple(sample2)
# Create a list for the labels
sample3 = []
for a,b in zip(sample,sample2):
if a^2+b^2<=1:
value = 1
else:
value = -1
sample3.append(value)
df = pd.DataFrame.from_dict({'X1':sample,'X2':sample2, 'y':sample3})
data = df.to_numpy()
X = data[:, :-1] # except last column
y = data[:, -1] # last column only
# choose random 150 centres from training data. Uncomment this for the second part of question 2 (random 150 and K-means)
# X = X[np.random.choice(len(X), size=150, replace=False)]
# y = y[np.random.choice(len(y), size=150, replace=False)]
def test(X, y, initializer):
title = f" test {type(initializer).__name__} "
print("-"*20 + title + "-"*20)
# create RBF network as keras sequential model. Change the spread using the betas parameter
model = Sequential()
rbflayer = RBFLayer(10,
initializer=initializer,
betas=1,
input_shape=(2,))
outputlayer = Dense(1, use_bias=False)
model.add(rbflayer)
model.add(outputlayer)
model.compile(loss='mean_squared_error',
optimizer=RMSprop())
# fit and predict
model.fit(X, y,
batch_size=441,
epochs=2000,
verbose=0)
y_pred = model.predict(X)
# calculate and print MSE
y_pred = y_pred.squeeze()
print(f"MSE: {MSE(y, y_pred):.4f}")
if __name__ == "__main__":
# test simple RBF Network with random setup of centers
test(X, y, InitCentersRandom(X))
# test simple RBF Network with centers set up by k-means
test(X, y, InitCentersKMeans(X)) | true |
799c760bc5caab7853b1497b4c56c76d327e1c00 | Python | vstadnytskyi/caproto-sandbox | /caproto_sandbox/io_camera_server.py | UTF-8 | 2,351 | 2.9375 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python3
import termios
import fcntl
import sys
import os
import threading
import atexit
from time import time,sleep
from datetime import datetime
from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run
from numpy import zeros, random
image_shape = (3960,3960)
class Device(object):
dt = 1
def start_io_interrupt_monitor(self,new_value_callback):
'''
This function monitors the terminal it was run in for keystrokes.
On each keystroke, it calls new_value_callback with the given keystroke.
This is used to simulate the concept of an I/O Interrupt-style signal from
the EPICS world. Those signals depend on hardware to tell EPICS when new
values are available to be read by way of interrupts - whereas we use
callbacks here.
'''
while True:
image = random.randint(0,256,image_shape).flatten()
new_value_callback({'image':image})
sleep(self.dt)
class IOInterruptIOC(PVGroup):
arr = zeros(image_shape)
f_arr = arr.flatten()
image = pvproperty(value = f_arr, dtype = float)
@image.startup
async def image(self, instance, async_lib):
# This method will be called when the server starts up.
print('* t1 method called at server startup')
queue = async_lib.ThreadsafeQueue()
# Start a separate thread that monitors keyboard input, telling it to
# put new values into our async-friendly queue
thread = threading.Thread(target=device.start_io_interrupt_monitor,
daemon=True,
kwargs=dict(new_value_callback=queue.put))
thread.start()
# Loop and grab items from the queue one at a time
while True:
value = await queue.async_get()
if 'image' in list(value.keys()):
await self.image.write(value['image'])
print('image in ioc:',self.image.value.mean(),self.image.value.max(),self.image.value.min())
device = Device()
if __name__ == '__main__':
ioc_options, run_options = ioc_arg_parser(
default_prefix='camera:',
desc='Run an IOC that updates via I/O interrupt on key-press events.')
ioc = IOInterruptIOC(**ioc_options)
print(ioc.image)
run(ioc.pvdb, **run_options)
| true |
fb2c41301b19c146be4d348e56506d48660f4f35 | Python | ravi4all/Python_Aug_4-30 | /CorePythonAgain/Applications/01-Calculator/02-MenuDrivenCalculator.py | UTF-8 | 707 | 3.9375 | 4 | [] | no_license | def add(x,y):
return x + y
def sub(x,y):
return x - y
def mul(x,y):
return x * y
def div(x,y):
return x/y
def errHandler(x,y):
print("Wrong Choice")
def main():
while True:
print("""
1. Add
2. Sub
3. Mul
4. Div
5. Quit
""")
user_choice = input("Enter your choice : ")
num_1 = int(input("Enter first number : "))
num_2 = int(input("Enter second number : "))
todo = {
"1" : add,
"2" : sub,
"3" : mul,
"4" : div,
"5" : quit
}
calc = todo.get(user_choice, errHandler)(num_1, num_2)
print(calc)
main()
| true |
355f7358472f7847db15586db22093ca37535520 | Python | mcohenmcohen/NLP-Recommender | /applicants.py | UTF-8 | 3,791 | 2.78125 | 3 | [] | no_license | import pandas as pd
from lxml import etree, objectify
from StringIO import StringIO
import dataio
dbutils = dataio.DataUtils()
_applicant_df = ''
def get_applicant_data():
'''
Retrieve all relevant user data from the database and preprocess
'''
global _applicant_df
if type(_applicant_df) == pd.DataFrame:
return _applicant_df
query = """
SELECT u.id, u.first_name, u.last_name,
ap.parsed_resume_xml, ap.passions, ap.introduction,
ujt.job_tag_id, ujt.tag_type
FROM users u
LEFT JOIN applicant_profiles ap ON ap.user_id=u.id
LEFT JOIN user_job_tags ujt ON ujt.user_id=u.id
"""
print 'Getting user and applicant data...'
import time
t1 = time.time()
df = dbutils.run_query(query)
t2 = time.time()
print "- Time: " + str((t2 - t1)) + "\n"
# For each user, pull relevant data out of their resume,
# place in a list and add to the DataFrame
elements = ['ExecutiveSummary', 'Description', 'title',
'Competency', 'Degree']
print 'Processing user resume data...'
t1 = time.time()
l = []
es = []
ds = []
ti = []
cm = []
dg = []
for i in range(df.shape[0]):
xml = df.iloc[i]['parsed_resume_xml']
try:
p = tokenize_xml(xml, elements)
except Exception, e:
print 'Tokenize failed for user id %s, error: %s' % (df.iloc[i]['id'], e)
es.append(p.get('ExecutiveSummary'))
ds.append(p.get('Description'))
ti.append(p.get('title'))
cm.append(p.get('Competency'))
dg.append(p.get('Degree'))
l.append(p)
t2 = time.time()
print "- Time: " + str((t2 - t1)) + "\n"
df['resume_elements'] = l
df['res_executiveSummary'] = es
df['res_description'] = ds
df['res_title'] = ti
df['res_competency'] = cm
df['res_degree'] = dg
print 'Done.'
_applicant_df = df
return _applicant_df
def tokenize_xml(xml_string, *elements):
'''
Input
xml_string - XML as a string
elements - list of elements
Output
list of words. Or dict?
'''
# dict to capture resume items to return
resume_element_dict = {}
if not xml_string:
return resume_element_dict
if elements:
elements = elements[0]
else:
# Default data from the user resume xml
elements = ['ExecutiveSummary', 'Description', 'title',
'Competency', 'Degree']
tree = etree.parse(StringIO(xml_string))
root = tree.getroot()
# Remove namespaces
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'): continue # (1)
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i+1:]
objectify.deannotate(root, cleanup_namespaces=True)
for name in elements:
s = "//" + name
elems = tree.findall(s)
data = []
#print 's: %s, elems: %s' % (s, elems)
for elem in elems:
#print '- elem: %s, text: %s' % (elem, elem.text)
#print '- elem.attrib: %s' % elem.attrib
if elem.text:
elem_str = elem.text.strip()
else:
elem_str = ''
if len(elem_str) > 0:
if elem.text:
val = elem.text
if val not in data:
data.append(val)
else:
for val in elem.attrib.itervalues():
if val not in data:
data.append(val)
if len(data) > 0:
data_as_str = ', '.join(data)
resume_element_dict[name] = data_as_str
return resume_element_dict
class User(object):
def __init__(self):
pass
| true |
255126a4c29f0be78353ba4f616f6603b8ec9150 | Python | krasznaa/acts-seedfinder-development | /Visualisation/drawSpacePointGroup.py | UTF-8 | 2,271 | 3.265625 | 3 | [] | no_license | #!/usr/bin/env python3
#
# Script drawing bottom-middle-top spacepoints corresponding to the same
# SpacePoint group.
#
# Import the necessary module(s).
import argparse
import csv
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
# Parse the command line argument(s).
parser = argparse.ArgumentParser( description = 'Space point drawer script' )
parser.add_argument( '-b', '--bottom',
help = 'Input file with the "bottom" spacepoints' )
parser.add_argument( '-m', '--middle',
help = 'Input file with the "middle" spacepoints' )
parser.add_argument( '-t', '--top',
help = 'Input file with the "top" spacepoints' )
args = parser.parse_args()
print( 'Using input files:' )
print( ' - bottom: %s' % args.bottom )
print( ' - middle: %s' % args.middle )
print( ' - top : %s' % args.top )
# Function used to read in one CSV file.
def readSpacePointFile( inputFile ):
x = []
y = []
z = []
with open( inputFile, 'r' ) as csvFile:
spReader = csv.reader( csvFile, delimiter = ' ' )
for row in spReader:
if row[ 0 ] == '#':
continue
elif row[ 0 ] == 'lxyz':
x += [ float( row[ 2 ] ) ]
y += [ float( row[ 3 ] ) ]
z += [ float( row[ 4 ] ) ]
else:
x += [ float( row[ 0 ] ) ]
y += [ float( row[ 1 ] ) ]
z += [ float( row[ 2 ] ) ]
pass
pass
assert len( x ) == len( y )
assert len( x ) == len( z )
print( 'Read in %i spacepoints from %s' % ( len( x ), inputFile ) )
return ( x, y, z )
# Read in the spacepoints.
bottomSPs = readSpacePointFile( args.bottom )
middleSPs = readSpacePointFile( args.middle )
topSPs = readSpacePointFile( args.top )
# Create a 3D scatter plot with all 3 types.
fig = plt.figure()
plot = fig.add_subplot( 111, projection = '3d' )
plot.scatter( bottomSPs[ 0 ], bottomSPs[ 1 ], bottomSPs[ 2 ],
c = 'b', marker = 'o' )
plot.scatter( middleSPs[ 0 ], middleSPs[ 1 ], middleSPs[ 2 ],
c = 'g', marker = 'o' )
plot.scatter( topSPs[ 0 ], topSPs[ 1 ], topSPs[ 2 ],
c = 'r', marker = 'o' )
plot.set_xlabel( 'X' )
plot.set_ylabel( 'Y' )
plot.set_zlabel( 'Z' )
plt.show()
| true |
6e6b77f5ef5ab3ee120e67d19d73dbe4fd93b18e | Python | brian15co/internetPoints | /cloudTools/mainStuff.py | UTF-8 | 247 | 2.890625 | 3 | [] | no_license | '''
This is hopefully something that will work. Hours have been spent
'''
import numpy as np
a = np.array([2,3,4,5])
print a
b = np.append([a], [[3,6,7,7]], axis=0)
print b
for item in b:
for i in item:
print i, | true |
f41b36ad6235f74e532f9f12d1662ffeee4573c6 | Python | FinagleLord/Binance-python-toolkit | /RSIemaCross.py | UTF-8 | 2,094 | 2.796875 | 3 | [
"MIT"
] | permissive | from helper import *
import time, tulipy, os, ctypes, config
from ansicolors import bg, fg, clp
import ansicolors as ac
os.system('cls||clear')
inpos = False
pair = input('What pair: ')
clp('valid intervals - 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M', fg.magenta)
interval = input('What interval: ')
quantity = input('What quantity: ')
testing = config.testing
def strat(pair, quantity, interval):
global inpos
while True:
# get data
Get_kline(pair, interval)
closes = Get_kline.closes
# indicators
rsi = tulipy.rsi(closes,14)
rsiema = tulipy.ema(rsi,22)
last_rsi = rsi[-1]
last_rsiema = rsiema[-1]
# Buy
if last_rsi > last_rsiema and last_rsi > 50 and inpos == False:
if testing == False:
print(f'Buying {quantity} {pair}')
price = Get_price(pair)
order_succeded = Limit_buy(pair, quantity, price)
if order_succeded:
inpos = True
print(f'{fg.yellow}sucess{ac.clear}')
# Sell
elif inpos and last_rsi < last_rsiema or last_rsi < 50:
if testing == False:
print(f'Selling {quantity} {pair}')
price = Get_price(pair)
balance = Asset_balance(pair)
if balance > quantity:
order_succeded = Limit_sell(pair, quantity, price)
if balance < quantity:
order_succeded = Limit_sell(pair, balance, price)
if order_succeded:
print(f'{fg.yellow}sucess{ac.clear}')
time.sleep(3600)
inpos = False
price = Get_price(pair)
print(f'{pair}: {round(price, 2)}')
time.sleep(1)
ctypes.windll.kernel32.SetConsoleTitleW(f"RSIemaCross: {pair}")
strat(pair,quantity,interval)
| true |
4de0cbd31f432a39bb98219b2e3598b8ee6521d6 | Python | webclinic017/mik-trader | /tests/test_bot.py | UTF-8 | 2,517 | 2.640625 | 3 | [] | no_license | import pytest
from decorators import *
@timer_decorator
def test_available_budget(bot_budget):
available_budget = bot_budget.calculate_available_budget()
assert available_budget["available day trading budget"] == 175
assert available_budget["available hodl budget"] == 0
@timer_decorator
def test_reading_active_stop_losses(bot_stop_loss):
bot_stop_loss.set_active_stop_losses()
assert bot_stop_loss.active_stop_losses["RSI Dips"]["ethusdt"].highest == 3000
assert bot_stop_loss.active_stop_losses["Bol Bands"]["ethusdt"].trail == 2850
@timer_decorator
def test_analysing_data(dataset1, dataset2):
bot2 = dataset2[0]
action1 = dataset1[0].analyse_new_data(dataset1[1], "ETHUSDT", dataset1[0].strategies[0])
action2 = dataset2[0].analyse_new_data(dataset2[1], "ETHUSDT", dataset2[0].strategies[2])
assert action1 == "buy"
assert bot2.active_stop_losses[bot2.strategies[2].name]["ETHUSDT"].trail == dataset2[1]["Price"].iloc[-1] * 0.95
assert action2 == "sell"
@timer_decorator
def test_determine_investment_amount(bot_budget):
bot_budget.available_to_invest = bot_budget.calculate_available_budget()
investment_hodl = bot_budget.determine_investment_amount(bot_budget.strategies[0])
investment_rsi = bot_budget.determine_investment_amount(bot_budget.strategies[1])
assert investment_rsi == 175
assert investment_hodl is None
@timer_decorator
def test_prepare_order(bot_budget):
bot_budget.available_to_invest = bot_budget.calculate_available_budget()
investment = bot_budget.prepare_order("btcusdt", bot_budget.strategies[1], "buy")
sell_quantity = bot_budget.prepare_order("btcusdt", bot_budget.strategies[0], "sell")
do_nothing = bot_budget.prepare_order("btcusdt", bot_budget.strategies[0], None)
assert investment == 175
assert sell_quantity == 1
assert do_nothing is None
@timer_decorator
def test_place_order(test_bot):
receipt = test_bot.place_order("BTCUSDT", 25000, "buy")
receipt2 = test_bot.place_order("BTCUSDT", 0.1, "sell")
assert receipt["status"].lower() == "filled"
assert receipt2["status"].lower() == "filled"
assert receipt2["side"].lower() == "sell"
@timer_decorator
def test_removing_stop_losses(dataset2):
bot = dataset2[0]
del bot.active_stop_losses["Bol Bands"]["BTCUSDT"]
with pytest.raises(KeyError):
print(bot.active_stop_losses["Bol Bands"]["BTCUSDT"])
assert isinstance(bot.active_stop_losses["Bol Bands"]["ETHUSDT"], object) is True
| true |
07dacdab0a2533d41f34f77244d89e74bf68bb68 | Python | defneikiz/MIS3640 | /session02/demo-02.py | UTF-8 | 309 | 3.625 | 4 | [] | no_license | # print('Hello,world')
# print('Hey Jude, Don\'t make it bad')
# print('The sum is', 2+2+2+2)
# print('Hello, {}'.format('world'))
# name= ('Defne')
# print('Congratulations, {:s}, you won {:d}th Academy award.'.format(name, 90))
print('Coordinates of Babson: {lat}, {lon}'.format(lon='71.27W', lat='42.30N')) | true |
c1f6376255fbbe07412076e341b78eaa665ff213 | Python | sontek/sqlalchemy_traversal | /sqlalchemy_traversal/resources.py | UTF-8 | 7,300 | 2.515625 | 3 | [
"MIT"
] | permissive | from sqlalchemy_traversal import get_session
from sqlalchemy_traversal import get_base
from sqlalchemy_traversal import TraversalMixin
from sqlalchemy_traversal import ModelCollection
from sqlalchemy_traversal import filter_query_by_qs
from sqlalchemy_traversal import get_prop_from_cls
from sqlalchemy_traversal import parse_key
from sqlalchemy_traversal import filter_query
from sqlalchemy.orm import contains_eager
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.exc import DataError
import urllib
class QueryGetItem(object):
"""
This is used so that if we haven't ended our traversal we can pass
unexecuted queries around to limit the amount of queries we actually
run during traversal
"""
def __init__(self, cls, query, request, old_gi):
self.cls = cls
self.query = query
self.request = request
self.session = get_session(self.request)
self.old_gi = old_gi
def __call__(self, item):
cls = get_prop_from_cls(self.cls, item)
if self.request.path.endswith(item):
self.query = self.query.outerjoin(item)
self.query = self.query.options(contains_eager(item))
self.query = filter_query_by_qs(
self.session,
cls,
self.request.GET,
existing_query = self.query
)
try:
if self.request.method == 'POST':
return cls()
parent = self.query.one()
to_return = ModelCollection(
[x for x in getattr(parent, item)]
)
except ProgrammingError:
raise KeyError
return to_return
new_sa_root = SQLAlchemyRoot(self.request, cls, table_lookup=item)
new_sa_root.__parent__ = self.__parent__
return new_sa_root
class SQLAlchemyRoot(object):
"""
This is a resource factory that wraps a SQL Alchemy class and will set a
_request attribute on the instance during traversal so that the instance
may check items on the request such as the method or query string
"""
def __init__(self, request, cls, table_lookup=None):
self.request = request
self.session = get_session(self.request)
self.cls = cls
if table_lookup == None:
self.table_lookup = self.cls.__tablename__
else:
self.table_lookup = table_lookup
def __getitem__(self, k):
try:
key = getattr(self.cls, self.cls._traversal_lookup_key)
result = self.session.query(self.cls).filter(key == k)
# This is the final object we want, so lets return the result
# if its not, lets return the query itself
# if self.request.path.split('/')[-2] == self.table_lookup:
try:
result = filter_query_by_qs(self.session, self.cls,
self.request.GET
, existing_query = result
)
result = result.one()
except (ProgrammingError, DataError):
raise KeyError
# getitem = QueryGetItem(self.cls, result,
# self.request, result.__getitem__
# )
#
# getitem.__parent__ = self
# result.__getitem__ = getitem
# we need give the SQLAlchemy model an instance of the request
# so that it can check if we are in a PUT or POST
result._request = self.request
result.__parent__ = self
return result
except NoResultFound as e:
# POSTing to the URL with ID already set?
if self.request.method == 'POST' and self.cls != None:
cls = self.cls()
cls.__parent__ = self
raise KeyError
class TraversalRoot(object):
"""
This is the root factory to use on a traversal route:
config.add_route('api', '/api/*traverse', factory=TraversalRoot)
You may use it as a standalone factory, you just register your base
SQLAlchemy object in the pyramid registry with ISABase and your Session
should be registered with ISASession
config.registry.registerUtility(base_class, ISABase)
config.registry.registerUtility(DBSession, ISASession)
"""
__name__ = None
__parent__ = None
def __init__(self, request):
self.request = request
self.base = get_base(request)
self.session = get_session(request)
self.tables = {}
# Loop through all the tables in the SQLAlchemy registry
# and store them if they subclass the TraversalMixin
for key, table in self.base._decl_class_registry.iteritems():
if isinstance(table, type) and issubclass(table, TraversalMixin):
table.__parent__ = self
self.tables[table.__tablename__] = table
def get_class(self, key):
"""
This function just returns the class directly without running any
logic
"""
return self.tables[key]
def __getitem__(self, key):
"""
This is used in traversal to get the correct item. If the path ends
with a tablename such as "user" then we will return a list of all the
rows in table wrapped in a ModelCollection.
If the request is a PUT or POST we will assume that you want to create
or update the object and will just return an instance of the model.
If we are in a GET request and don't end with a tablename then we will
root a SQLAlchemyFactory that will keep track of which node we are
currently at.
"""
filters = parse_key(key)
cls = self.tables[filters['table']]
to_return = None
# Do we have the table registered as a traversal object?
if cls == None:
raise KeyError
# This is used to shortcircuit the traversal, if we are ending
# on a model, for instance /api/user then we should either be creating
# a new instance or querying the table
path = urllib.unquote(self.request.path)
if path.endswith(key):
if self.request.method == 'GET':
#query = filter_query_by_qs(self.session, cls,
# self.request.GET
#)
query = self.session.query(cls)
query = filter_query(filters, query, cls)
try:
to_return = ModelCollection(
[x for x in query.all()]
, request=self.request
)
except ProgrammingError:
raise KeyError
elif self.request.method == 'POST' or self.request.method == 'PUT':
to_return = cls()
# If we haven't found something to return in the traversal tree yet,
# it means we want to continue traversing the SQLAlchemy objects,
# so lets return an SQLAlchemyRoot
if not to_return:
to_return = SQLAlchemyRoot(self.request, cls)
to_return.__parent__ = self
return to_return
| true |
2240250cb3a3d6b438520f77d137b368e798f377 | Python | balanand003/balanand003 | /len21.py | UTF-8 | 77 | 2.859375 | 3 | [] | no_license | P=input()
Q=P[0]
for i in P:
if (P.count(Q)<=P.count(i)):
Q=i
print(Q)
| true |
fee3efc0691c3030c8e1ed554333e8609667b20c | Python | askoj/foulisrandallstudies | /qogpsi/reporting/logs.py | UTF-8 | 762 | 3.28125 | 3 | [] | no_license |
def log_title(title="Insert A Title Here", **kwargs):
indent = kwargs.get('indent', "")
if kwargs.get('new_line', False):
print("\n")
print("%s-------- %s --------" % (indent, title))
def log_subtitle(subtitle="Insert A Subtitle Here", **kwargs):
indent = kwargs.get('indent', "")
if kwargs.get('new_line', False):
print("\n")
print("%s ---- %s ----" % (indent, subtitle))
def log_dictionary(dictionary={}, **kwargs):
indent = kwargs.get('indent', "")
if kwargs.get('new_line', False):
print("\n")
if (dictionary != {}):
for k,v in dictionary.items():
print("%s\t%s : %s" % (indent, k, v))
def log_text(text, **kwargs):
indent = kwargs.get('indent', "")
if kwargs.get('new_line', False):
print("\n")
print("%s%s" % (indent, text)) | true |
3e48019aac0b951de112c82da2ab797b8fd8f9ea | Python | HoYaStudy/Python_Study | /playground/pyqt/QThread/worker.py | UTF-8 | 951 | 2.65625 | 3 | [] | no_license | from PyQt5.QtCore import QThread, QWaitCondition, QMutex, pyqtSignal
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QLabel, QLineEdit
class Worker(QThread):
changed_value = pyqtSignal(int)
def __init__(self):
super().__init__()
self._status = True
self.cond = QWaitCondition()
self.mutex = QMutex()
self.cnt = 0
def __del__(self):
self.wait()
def run(self):
while True:
self.mutex.lock()
if not self._status:
self.cond.wait(self.mutex)
if 100 == self.cnt:
self.cnt = 0
self.cnt += 1
self.changed_value.emit(self.cnt)
self.msleep(100)
self.mutex.unlock()
def toggle_status(self):
self._status = not self._status
if self._status:
self.cond.wakeAll()
@property
def get_status(self):
return self._status
| true |
0bc528e261710c085b47d739ad96378da0e06ac4 | Python | ADL175/http-server | /src/test_servers.py | UTF-8 | 2,832 | 2.65625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""Test HTTP server."""
import pytest
# # Echo server tests
# LESS_THAN_BUFFER_LENGTH_TABLE = [
# ('yes yes', 'yes yes'),
# ('no no', 'no no'),
# ('what what', 'what what')
# ]
#
# LONGER_THAN_SEVERAL_BUFFER_LENGTHS_TABLE = [
# ('here is a string that is long', 'here is a string that is long'),
# ('and here is another string that is very long', 'and here is another string that is very long')
# ]
#
# EXACT_BUFFER_LENGTH_TABLE = [
# ('here is a string', 'here is a string'),
# ('12345678', '12345678'),
# ('1234567812345678', '1234567812345678')
# ]
#
# NON_ASCII_CHAR_TABLE = [
# ('!@#$%^&', '!@#$%^&'),
# ('?:;<>$@', '?:;<>$@')
# ]
#
# @pytest.mark.parametrize('message_sent, message_received', LESS_THAN_BUFFER_LENGTH_TABLE)
# def test_client_less_than_buffer_length(message_sent, message_received):
# """This tests the echo server with less than one buffer length."""
# from client import client
# assert client(message_sent) == message_received
#
#
# @pytest.mark.parametrize('message_sent, message_received', LONGER_THAN_SEVERAL_BUFFER_LENGTHS_TABLE)
# def test_client_longer_than_several_buffer_lengths(message_sent, message_received):
# """This tests the echo server with longer than several buffer lengths."""
# from client import client
# assert client(message_sent) == message_received
#
#
# @pytest.mark.parametrize('message_sent, message_received', EXACT_BUFFER_LENGTH_TABLE)
# def test_client_exact_buffer_length(message_sent, message_received):
# """This tests the echo server with exact buffer length."""
# from client import client
# assert client(message_sent) == message_received
#
#
# @pytest.mark.parametrize('message_sent, message_received', NON_ASCII_CHAR_TABLE)
# def test_client_non_ascii(message_sent, message_received):
# """This tests the echo server with non ascii characters."""
# from client import client
# assert client(message_sent) == message_received
# Step 1 tests
def test_response_ok():
"""Assert if response_ok() returns a valid HTTP response."""
valid = True
from server import response_ok
response = response_ok()
if response.startswith(b'HTTP/1.1 200 OK'):
response_list = response.split(b'\r\n')
response_list = response_list[1:]
response_list = [line for line in response_list if line is not b'']
for line in response_list:
if not (line.startswith(b'Date:') or line.startswith(b'Content-Type') or line.startswith(b'Content-Length')):
valid = False
assert valid
def test_response_error():
"""Asssert if response_error() returns a valid HTTP error response"""
from server import response_error
assert response_error() == b'HTTP/1.1 500 Internal Server Error\r\n\r\n' | true |
16cee799a36300bcc5111abcce45275c08a7aa21 | Python | WachirawitV-code/code-python | /shape.py | UTF-8 | 176 | 3.234375 | 3 | [] | no_license | def calCircle(radius):
return 22/7*(radius**2)
def calTriangle(width,height):
return 1/2*width*height
def calRectangle(width,heigth):
return width*height
| true |
2feb3e361c48080f33df37e5469ad72c2f49d607 | Python | Ayushi13598/PDF-Extraction | /pdf_extractor.py | UTF-8 | 1,098 | 2.859375 | 3 | [] | no_license | import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
def extract_text_from_pdf(pdf_path):
resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = TextConverter(resource_manager, fake_file_handle)
page_interpreter = PDFPageInterpreter(resource_manager, converter)
with open(pdf_path, 'rb') as fh:
for page in PDFPage.get_pages(fh,
caching=True,
check_extractable=True):
page_interpreter.process_page(page)
text = fake_file_handle.getvalue()
# close open handles
converter.close()
fake_file_handle.close()
if text:
return text
def write_text_to_file(text):
File_object = open("a.txt","w+")
File_object.write(text)
if __name__ == '__main__':
write_text_to_file(extract_text_from_pdf('pdfFormExampleFilled.pdf')) | true |
a63f0b6215d8061dd5a3712ef3469a73dfe8acbb | Python | wmakaben/AdventOfCode | /d06.py | UTF-8 | 596 | 3.15625 | 3 | [] | no_license | file = open("input/d06.txt", 'r')
count = 0
group = 0
questions = {}
def getQuestionCount (questionMap, groupCount):
c = 0
for qCount in questionMap.values():
if qCount == group:
c += 1
return c
for line in file:
line = line.rstrip()
if line == "":
count += getQuestionCount(questions, group)
questions.clear()
group = 0
else:
group += 1
for q in line:
if q not in questions:
questions[q] = 0
questions[q] += 1
count += getQuestionCount(questions, group)
print(count) | true |
9f06cb82378d170ec689b08f7ab892b8658e3c37 | Python | mouroboros/python_exercises | /Roman/roman_testcases.py | UTF-8 | 674 | 3.890625 | 4 | [] | no_license |
import unittest
def roman (number):
numeral = ''
if number < 5 :
for x in range(number) :
numeral += "I"
else : numeral = "V"
return numeral
class roman_numeral_testcases (unittest.TestCase) :
# notice the roman numeral is a string.
# so you need to build strings
# "I" + "I" -> "II"
def test_1_is_I(self):
self.assertEqual(roman(1), 'I')
def test_2_is_II(self):
self.assertEqual(roman(2), 'II')
def test_3_is_III(self):
self.assertEqual(roman(3), 'III')
def test_5_is_V(self):
self.assertEqual(roman(5), 'V')
# what next ??
unittest.main()
| true |