id
stringlengths 2
8
| text
stringlengths 16
264k
| dataset_id
stringclasses 1
value |
---|---|---|
1815980
|
<gh_stars>0
from sentry_sdk.hub import Hub
from sentry_sdk._types import MYPY
from sentry_sdk import _functools
if MYPY:
from typing import Any
def patch_views():
# type: () -> None
from django.core.handlers.base import BaseHandler
from sentry_sdk.integrations.django import DjangoIntegration
old_make_view_atomic = BaseHandler.make_view_atomic
@_functools.wraps(old_make_view_atomic)
def sentry_patched_make_view_atomic(self, *args, **kwargs):
# type: (Any, *Any, **Any) -> Any
callback = old_make_view_atomic(self, *args, **kwargs)
# XXX: The wrapper function is created for every request. Find more
# efficient way to wrap views (or build a cache?)
hub = Hub.current
integration = hub.get_integration(DjangoIntegration)
if integration is not None and integration.middleware_spans:
@_functools.wraps(callback)
def sentry_wrapped_callback(request, *args, **kwargs):
# type: (Any, *Any, **Any) -> Any
with hub.start_span(
op="django.view", description=request.resolver_match.view_name
):
return callback(request, *args, **kwargs)
else:
sentry_wrapped_callback = callback
return sentry_wrapped_callback
BaseHandler.make_view_atomic = sentry_patched_make_view_atomic
|
StarcoderdataPython
|
9794850
|
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A script to dump a trie from a validator DFA."""
import multiprocessing
import optparse
import sys
import traceback
import dfa_parser
import dfa_traversal
import trie
import validator
NOP = 0x90
def PadToBundleSize(byte_list):
"""Return bytes appended with NOPs to form a full bundle."""
assert len(byte_list) <= validator.BUNDLE_SIZE
return byte_list + [NOP] * (validator.BUNDLE_SIZE - len(byte_list))
# All the conditions for an x86_64 instruction under which it may be valid.
# Any register might be restricted. None is included because it indicates
# that no register is restricted coming into the instruction.
ALL_CONDITIONS = set(validator.ALL_REGISTERS + [None])
def CheckAndFormatRRInfo(input_rr_set, output_rr):
"""Formats restricted register information in order to store them in a trie.
Args:
input_rr_set: The set of allowed input restricted registers. This is
either an individual register that is required to be restriced (or
encodes that RSP/RBP cannot be restricted). Not empty.
output_rr: An output restricted register produced (or None)
Returns:
input_rr_str: A string version encoding the input restricted register.
output_rr_str: A string version encoding the output restricted register.
Raises:
ValueError: If input_rr_set or output_rr is invalid.
"""
assert input_rr_set
input_rr_str = None
# If multiple different restricted registers cause the instruction to be
# validated, then essentially any nonspecial register should be allowed.
# Notably, this means for example that either '%r13' or '%r12' being
# restricted incoming would cause the instruction to be valid but '%r8'
# being restricted on the input would cause an invalid instruction.
if len(input_rr_set) > 1:
if (input_rr_set != (ALL_CONDITIONS - set((validator.NC_REG_RSP,
validator.NC_REG_RBP)))):
raise ValueError('Invalid input rr set', input_rr_set)
input_rr_str = 'any_nonspecial'
else:
input_rr_str = validator.REGISTER_NAMES[input_rr_set.pop()]
if output_rr == validator.NC_REG_R15:
raise ValueError('Instruction produces R15 as a restricted register.')
if output_rr is None:
output_rr_str = 'None'
else:
output_rr_str = validator.REGISTER_NAMES[output_rr]
return input_rr_str, output_rr_str
def ValidateInstructionAndGetRR(bitness, instruction, validator_inst):
"""Verify the byte list against the DFA and get restricted register info.
Even though walking the DFA might result in instruction being accepted,
the instruction might actually get rejected by a DFA action. So, we run
the byte sequence through the validator to actually ensure that the bytes
are accepted before passing them onto a trie. Additionally, extract
restricted register information for the byte sequence.
Args:
bitness: [32 or 64]
instruction: byte list obtained from walking accept states of the DFA.
validator_inst: instance of the x86 validator loaded with DFA+actions.
Returns:
valid: True/False about whether the byte sequence is actually accepted.
input_rr: Incoming restricted registers that are allowed to accept the
sequence. Always empty for the x86-32 case.
output_rr: Outgoing condition that is generated by the DFA.
Always empty for the x86-32 case.
Raises:
ValueError: If instruction generates multiple output restricted registers.
"""
bundle = ''.join(map(chr, PadToBundleSize(instruction)))
if bitness == 32:
result = validator_inst.ValidateChunk(bundle, bitness)
return (result, '', '')
else:
# Walk through all of the conditions of different registers being input
# restricted, as well as no input rrs being restricted and see if any of
# them cause the byte sequence to be validated. We need to do this
# because we are processing an instruction at a time and not a bundle
# at a time.
valid_input_rrs = set()
valid_output_rrs = set()
for initial_rr in ALL_CONDITIONS:
valid, final_rr = validator_inst.ValidateAndGetFinalRestrictedRegister(
bundle, len(instruction), initial_rr)
if valid:
valid_input_rrs.add(initial_rr)
valid_output_rrs.add(final_rr)
# If no input RRs are allowed then instruction is not valid.
if not valid_input_rrs:
return (False, '', '')
# All valid input RRs should produce one unique output RR (could be None).
# i.e the produced output rr should not vary based on input RR.
if len(valid_output_rrs) != 1:
raise ValueError('Multiple output RRs produced', instruction,
valid_output_rrs)
known_final_rr = valid_output_rrs.pop()
input_rr_str, output_rr_str = CheckAndFormatRRInfo(
valid_input_rrs, known_final_rr)
return (True, input_rr_str, output_rr_str)
class WorkerState(object):
"""Maintains an uncompressed subtrie while receiving accepting instructions.
The main thread will compress this subtrie into the main trie when this
worker is done. This is because it's inefficient (and difficult to maintain
threadsafety) to compress nodes into a common node cache in the workers
themselves.
"""
def __init__(self, validator):
self.total_instructions = 0
self.num_valid = 0
self.validator = validator
self.sub_trie = trie.Node()
self.node_cache = trie.NodeCache()
def ReceiveInstruction(self, byte_list):
"""Update trie if sequence passes validator and sandboxing checks."""
self.total_instructions += 1
# This is because even though the state is accepting with regards to the
# DFA, extra DFA actions or other validator rules might make the sequence
# invalid.
is_valid, input_rr, output_rr = ValidateInstructionAndGetRR(
options.bitness, byte_list, self.validator)
if is_valid:
self.num_valid += 1
trie.AddToUncompressedTrie(
self.sub_trie, map(str, byte_list),
trie.AcceptInfo(input_rr=input_rr, output_rr=output_rr))
def Worker((dfa_prefix, dfa_state_index)):
"""Traverse a portion of the DFA, and compute the associated subtrie."""
worker_state = WorkerState(worker_validator)
try:
dfa_traversal.TraverseTree(
dfa.states[dfa_state_index],
final_callback=worker_state.ReceiveInstruction,
prefix=dfa_prefix,
anyfield=0)
except Exception:
traceback.print_exc() # because multiprocessing imap swallows traceback
raise
worker_state.sub_trie = worker_state.node_cache.Merge(
worker_state.node_cache.empty_node, worker_state.sub_trie)
return (
worker_state.total_instructions,
worker_state.num_valid,
worker_state.sub_trie)
def ParseOptions():
"""Parse command line options."""
parser = optparse.OptionParser(usage='%prog [options] xmlfile')
parser.add_option('--bitness',
choices=['32', '64'],
help='The subarchitecture: 32 or 64')
parser.add_option('--validator_dll',
help='Path to librdfa_validator_dll')
parser.add_option('--decoder_dll',
help='Path to librdfa_decoder_dll')
parser.add_option('--trie_path',
help='Path to write the output trie to')
options, args = parser.parse_args()
options.bitness = int(options.bitness)
if not options.trie_path:
parser.error('specify an output path to a trie')
if len(args) != 1:
parser.error('specify one xml file')
xml_file, = args
return options, xml_file
def main():
# We keep these global to share state graph between workers spawned by
# multiprocess. Passing it every time is slow.
global options, xml_file
global dfa
global worker_validator
options, xml_file = ParseOptions()
dfa = dfa_parser.ParseXml(xml_file)
worker_validator = validator.Validator(
validator_dll=options.validator_dll,
decoder_dll=options.decoder_dll)
assert dfa.initial_state.is_accepting
assert not dfa.initial_state.any_byte
sys.stderr.write('%d states\n' % len(dfa.states))
num_suffixes = dfa_traversal.GetNumSuffixes(dfa.initial_state)
num_instructions = sum(
num_suffixes[t.to_state]
for t in dfa.initial_state.forward_transitions.values())
sys.stderr.write('%d instructions\n' % num_instructions)
tasks = dfa_traversal.CreateTraversalTasks(dfa.states,
dfa.initial_state)
sys.stderr.write('%d tasks\n' % len(tasks))
pool = multiprocessing.Pool()
results = pool.imap_unordered(Worker, tasks)
total = 0
num_valid = 0
node_cache = trie.NodeCache()
full_trie = node_cache.empty_node
# The individual workers create subtries that we merge in and compress here.
for count, valid_count, sub_trie, in results:
total += count
num_valid += valid_count
full_trie = node_cache.Merge(full_trie, sub_trie)
sys.stderr.write('%.2f%% completed\n' % (total * 100.0 / num_instructions))
sys.stderr.write('%d instructions were processed\n' % total)
sys.stderr.write('%d valid instructions\n' % num_valid)
trie.WriteToFile(options.trie_path, full_trie)
if __name__ == '__main__':
main()
|
StarcoderdataPython
|
4911343
|
<reponame>doctoryes/project_euler
# A permutation is an ordered arrangement of objects.
# For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are:
# 012 021 102 120 201 210
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
import itertools
all_numbers = itertools.permutations('0123456789')
sorted_numbers = sorted(all_numbers)
print sorted_numbers[999999]
|
StarcoderdataPython
|
149152
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Pytorch MNIST example running on Kubeflow Pipelines
Run this script to compile pipeline
"""
import kfp.dsl as dsl
import kfp.gcp as gcp
@dsl.pipeline(
name='dlrs-mnist-pipeline',
description='A pipeline to train and serve the Pytorch MNIST example.'
)
def mnist_pipeline(model_bucket='your-gs-bucket-name', gcloud_access_token='your-access-token'):
"""
Pipeline with three stages:
1. Train a MNIST handwritten digit classifier
2. Deploy a model server to the cluster
3. Deploy a web-ui to interact with it
"""
train = dsl.ContainerOp(
name='train',
image='REGISTRY/dlrs-train-TYPE',
arguments=[
"-cb", model_bucket,
"-s", "train",
"-t", gcloud_access_token
]
)
serve = dsl.ContainerOp(
name='serve',
image='REGISTRY/dlrs-pipelines-deployer',
arguments=[
"-cb", model_bucket,
"-s", "serve",
"-t", gcloud_access_token
]
)
serve.after(train)
web_ui = dsl.ContainerOp(
name='web-ui',
image='REGISTRY/dlrs-pipelines-deployer'
arguments=[
"-s", "website"
]
)
web_ui.after(serve)
steps = [train, serve, web_ui]
for step in steps:
step.apply(gcp.use_gcp_secret('user-gcp-sa'))
if __name__ == '__main__':
import kfp.compiler as compiler
compiler.Compiler().compile(mnist_pipeline, __file__ + '.tar.gz')
|
StarcoderdataPython
|
30092
|
from __future__ import print_function
import pylab as plt
import numpy as np
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, QueryDict
from django.shortcuts import render_to_response, get_object_or_404, redirect, render
from django.template import Context, RequestContext, loader
from astrometry.net.models import *
from astrometry.util.resample import *
from astrometry.net.tmpfile import *
def simple_histeq(pixels, getinverse=False, mx=256):
assert(pixels.dtype in [np.uint8, np.uint16])
if not getinverse:
h = np.bincount(pixels, minlength=mx)
# pixel value -> quantile map.
# If you imagine jittering the pixels so there are no repeats,
# this assigns the middle quantile to a pixel value.
quant = h * 0.5
cs = np.cumsum(h)
quant[1:] += cs[:-1]
quant /= float(cs[-1])
# quant = np.cumsum(h / float(h.sum()))
return quant[pixels]
# This inverse function has slightly weird properties -- it
# puts a ramp across each pixel value, so inv(0.) may produce
# values as small as -0.5, and inv(1.) may produce 255.5
h = np.bincount(pixels.astype(int)+1, minlength=mx+1)
quant = h[1:] * 0.5
cs = np.cumsum(h)
quant[1:] += cs[1:-1]
quant /= float(cs[-1])
# interp1d is fragile -- remove duplicate "yy" values that
# otherwise cause nans.
yy = cs / float(cs[-1])
xx = np.arange(mx + 1) - 0.5
I = np.append([0], 1 + np.flatnonzero(np.diff(yy)))
print('mx:', mx)
print('xx:', len(xx))
print('yy:', len(yy))
print('I:', I.min(), I.max())
yy = yy[I]
xx = xx[I]
xx[-1] = mx-0.5
# print 'yy', yy[0], yy[-1]
# print 'xx', xx[0], xx[-1]
inv = interp1d(yy, xx, kind='linear')
return quant[pixels], inv
def enhanced_ui(req, user_image_id=None):
ui = UserImage.objects.get(id=user_image_id)
job = ui.get_best_job()
return enhanced_image(req, job_id=job.id, size='display')
def enhanced_image(req, job_id=None, size=None):
job = get_object_or_404(Job, pk=job_id)
ui = job.user_image
cal = job.calibration
tan = cal.raw_tan
nside,hh = get_healpixes_touching_wcs(tan)
tt = 'hello %s, job %s, nside %s, hh %s' % (ui, job, nside, hh)
ver = EnhanceVersion.objects.get(name='v4')
print('Using', ver)
EIms = EnhancedImage.objects.filter(version=ver)
ens = []
for hp in hh:
en = EIms.filter(nside=nside, healpix=hp, version=ver)
if len(en):
ens.extend(list(en))
for dnside in range(1, 3):
if len(ens) == 0:
bignside = nside / (2**dnside)
nil,hh = get_healpixes_touching_wcs(tan, nside=bignside)
tt += 'bigger healpixes: %s: %s' % (bignside, hh)
for hp in hh:
en = EIms.filter(nside=bignside, healpix=hp)
if len(en):
ens.extend(list(en))
tt = tt + ', EnhancedImages: ' + ', '.join('%s'%e for e in ens)
img = ui.image
W,H = img.width, img.height
tt = tt + 'image size %ix%i' % (W,H)
#return HttpResponse(tt)
targetwcs = tan.to_tanwcs()
#print 'Target WCS:', targetwcs
#print 'W,H', W,H
logmsg('wcs:', str(targetwcs))
if size == 'display':
scale = float(ui.image.get_display_image().width)/ui.image.width
logmsg('scaling:', scale)
targetwcs = targetwcs.scale(scale)
logmsg('scaled wcs:', str(targetwcs))
H,W = targetwcs.get_height(), targetwcs.get_width()
img = ui.image.get_display_image()
print(tt)
ee = np.zeros((H,W,3), np.float32)
imgdata = None
df = img.disk_file
ft = df.file_type
fn = df.get_path()
if 'JPEG' in ft:
print('Reading', fn)
I = plt.imread(fn)
print('Read', I.shape, I.dtype)
if len(I.shape) == 2:
I = I[:,:,np.newaxis].repeat(3, axis=2)
assert(len(I.shape) == 3)
if I.shape[2] > 3:
I = I.shape[:,:,:3]
# vertical FLIP to match WCS
I = I[::-1,:,:]
imgdata = I
mapped = np.zeros_like(imgdata)
for en in ens:
logmsg('Resampling %s' % en)
wcs = en.wcs.to_tanwcs()
try:
Yo,Xo,Yi,Xi,nil = resample_with_wcs(targetwcs, wcs, [], 3)
except OverlapError:
continue
#logmsg(len(Yo), 'pixels')
enI,enW = en.read_files()
#print 'Cals included in this Enhanced image:'
#for c in en.cals.all():
# print ' ', c
#logmsg('en:', enI.min(), enI.max())
if imgdata is not None:
mask = (enW[Yi,Xi] > 0)
for b in range(3):
enI[:,:,b] /= enI[:,:,b].max()
if imgdata is not None:
idata = imgdata[Yo[mask],Xo[mask],b]
DI = np.argsort((idata + np.random.uniform(size=idata.shape))/255.)
EI = np.argsort(enI[Yi[mask], Xi[mask], b])
Erank = np.zeros_like(EI)
Erank[EI] = np.arange(len(Erank))
mapped[Yo[mask],Xo[mask],b] = idata[DI[Erank]]
else:
# Might have to average the coverage here...
ee[Yo,Xo,b] += enI[Yi,Xi,b]
# ee[Yo[mask],Xo[mask],b] += enI[Yi[mask],Xi[mask],b]
tempfn = get_temp_file(suffix='.png')
if imgdata is not None:
im = mapped
else:
im = np.clip(ee, 0., 1.)
dpi = 100
figsize = [x / float(dpi) for x in im.shape[:2][::-1]]
fig = plt.figure(figsize=figsize, frameon=False, dpi=dpi)
plt.clf()
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.imshow(im, interpolation='nearest')
# rdfn = job.get_rdls_file()
# rd = fits_table(rdfn)
# ok,x,y = targetwcs.radec2pixelxy(rd.ra, rd.dec)
# plt.plot(x, y, 'o', mec='r', mfc='none', ms=10)
plt.savefig(tempfn)
print('Wrote', tempfn)
f = open(tempfn)
res = HttpResponse(f)
res['Content-Type'] = 'image/png'
return res
|
StarcoderdataPython
|
9796719
|
<gh_stars>0
frase = 'Curso em Video Python'
print(frase.replace('Python', 'Android'))
print(frase)
print('Curso' in frase)
print(frase.lower().find('video'))
print(frase.split())
dividido = frase.split()
print(dividido)
|
StarcoderdataPython
|
3352506
|
<gh_stars>0
#!/usr/bin/env python3
"""
Low level OpenGL vertex array wrapper
"""
# External, non built-in modules
import OpenGL.GL as GL # standard Python OpenGL wrapper
import numpy as np # all matrix manipulations & OpenGL args
class VertexArray:
""" helper class to create and self destroy OpenGL vertex array objects."""
def __init__(self, attributes, index=None, usage=GL.GL_STATIC_DRAW):
""" Vertex array from attributes and optional index array. Vertex
Attributes should be list of arrays with one row per vertex. """
# create vertex array object, bind it
self.glid = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self.glid)
self.buffers = [] # we will store buffers in a list
nb_primitives, size = 0, 0
# load buffer per vertex attribute (in list with index = shader layout)
for loc, data in enumerate(attributes):
if data is not None:
# bind a new vbo, upload its data to GPU, declare size and type
self.buffers += [GL.glGenBuffers(1)]
data = np.array(data, np.float32, copy=False) # ensure format
nb_primitives, size = data.shape
GL.glEnableVertexAttribArray(loc)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[-1])
GL.glBufferData(GL.GL_ARRAY_BUFFER, data, usage)
GL.glVertexAttribPointer(loc, size, GL.GL_FLOAT, False, 0, None)
# optionally create and upload an index buffer for this object
self.draw_command = GL.glDrawArrays
self.arguments = (0, nb_primitives)
if index is not None:
self.buffers += [GL.glGenBuffers(1)]
index_buffer = np.array(index, np.int32, copy=False) # good format
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.buffers[-1])
GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, index_buffer, usage)
self.draw_command = GL.glDrawElements
self.arguments = (index_buffer.size, GL.GL_UNSIGNED_INT, None)
# cleanup and unbind so no accidental subsequent state update
GL.glBindVertexArray(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0)
def execute(self, primitive):
""" draw a vertex array, either as direct array or indexed array """
GL.glBindVertexArray(self.glid)
self.draw_command(primitive, *self.arguments)
GL.glBindVertexArray(0)
def __del__(self): # object dies => kill GL array and buffers from GPU
GL.glDeleteVertexArrays(1, [self.glid])
GL.glDeleteBuffers(len(self.buffers), self.buffers)
|
StarcoderdataPython
|
3548499
|
<reponame>dcabatin/manim
from functools import reduce
import itertools as it
import operator as op
import copy
import numpy as np
import random
from manimlib.imports import *
from kuratowski.our_discrete_graph_scene import *
class MainGraph(Graph):
def construct(self):
self.vertices = [
# main cycle
(-2, 0, 0),
(-1, 1.5, 0),
(1, 1.5, 0),
(2, 0, 0),
(1, -1.5, 0),
(-1, -1.5, 0),
# hacky extras
(-1, 1.5, 0),
(1, 1.5, 0),
(1, -1.5, 0),
(-1, -1.5, 0),
# inner
(-1, 0, 0),
(1, 0, 0),
(0, 0, 0),
# obstructions
(-1.5, 1.15, 0),
(1.5, 1.15, 0),
(1.5, -1.15, 0)
]
self.edges = [
# inner loop (0:6)
(0,1),
(1,2),
(2,3),
(3,4),
(4,5),
(5,0),
# outer loops (6:10)
(0,3),
(6,7),
(7,8),
(8,9),
# hacky lines (10:14)
(1,6),
(2,7),
(4,8),
(5,9),
# obstruction 1 (14), with vertices 13,15
(13, 15),
# obstruction 2 (15:18), with vertices 12,14,15
(0, 12),
(12, 14),
(12, 15),
# obstruction 3 (18:23), with vertices 10,11
(0, 10),
(10, 11),
(11, 3),
(11, 2),
(10, 4),
# obstruction 4 (23:26), with vertex 12
(12, 0),
(12, 3),
(12, 2),
(12, 4),
# complete path uv (27)
(0,3),
# reverse of complete path vu (28)
(3,0),
# vivj drawn inside C
(2,4)
]
self.eclasses = [CURVE_OUT]*6 + [CURVE_OUT_HUGE_RED] + [CURVE_OUT_HUGE]*2 + [CURVE_OUT_HUGE] + [Line]*17 + [CURVE_OUT] + [CURVE_OUT] + [Line]
class MainProofScene(OurGraphTheory):
def construct(self):
self.graph = MainGraph()
super().construct()
self.shift_graph(3*LEFT)
self.wait(4)
f1 = TextMobject("Take the edge $uv$ from the previous statement, \\\\ and consider the graph $G - uv$ obtained by removing it.")
f1.scale(1).shift(UP*2)
self.play(Write(f1))
self.wait(3)
f2 = TextMobject("$G - uv$ is planar by minimality.")
f2.scale(1).next_to(f1, DOWN*3)
self.play(Write(f2))
self.wait(3)
f3 = TextMobject("$G - uv$ is 2-connected, \\\\ so there is a cycle containing $u,v$.")
f3.scale(1).next_to(f2, DOWN*3)
self.play(Write(f3))
self.wait(3)
self.play(*[FadeOut(e) for e in [f1,f2,f3]])
self.wait()
u,v = self.vertices[0], self.vertices[3]
self.draw([u,v])
v_label, u_label = (TextMobject("$v$").scale(0.8).next_to(v, RIGHT*0.5),
TextMobject("$u$").scale(0.8 ).next_to(u, LEFT*0.5))
self.play(Write(u_label), Write(v_label))
instr = TextMobject("Embed maximal cycle $C$ \\\\ containing $u, v$.", alignment="\\justify")
instr.scale(0.75)
instr.shift(RIGHT*3.5)
self.play(Write(instr, run_time=0.75))
self.wait(4)
self.draw(self.edges[:6])
self.draw(self.edges[-3:-1])
cycle = self.trace_arc_cycle_with_edges([self.edges[i] for i in [0,1,2,28]])
self.play(*[FadeOut(c, run_time=0.5) for c in cycle])
cycle = self.trace_arc_cycle_with_edges([self.edges[i] for i in [27,28]])
self.play(*[FadeOut(c, run_time=0.5) for c in cycle])
cycle = self.trace_arc_cycle_with_edges(self.edges[:6], color=GREEN)
self.play(*[FadeOut(c, run_time=0.5) for c in cycle])
self.erase_copy(self.edges[-3:-1])
C_label = TextMobject("$C$").scale(0.8).next_to(self.edges[1], DOWN*.3)
self.play(Write(C_label))
self.wait(9)
instr2 = TextMobject("Loop along upper \\\\ part of $C$?", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw upper vertices and the edge
upper_vertices = [1,2,6,7]
self.draw([self.vertices[i] for i in upper_vertices])
self.draw(self.edges[7])
instr2 = TextMobject("Contradiction: \\\\ larger cycle.", alignment="\\justify", color=RED)
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# trace bad cycle
cycle = self.trace_cycle([0,1,6,7,2,3,4,5])
self.wait(0.5)
# fadeout upper vertices and the edge
self.play(*[FadeOut(c, run_time=0.5) for c in cycle])
anims = self.erase_copy(self.edges[7], play=False)
anims += self.erase_copy([self.vertices[i] for i in upper_vertices], play=False)
self.play(*anims)
instr2 = TextMobject("Loop along lower \\\\ part of $C$?", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw lower vertices and the edge
lower_vertices = [4,5,8,9]
self.draw([self.vertices[i] for i in lower_vertices])
self.draw(self.edges[9])
instr2 = TextMobject("Contradiction: \\\\ larger cycle.", alignment="\\justify", color=RED)
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# trace bad cycle
cycle = self.trace_cycle([0,1,2,3,4,8,9,5])
self.wait(1.5)
# fadeout lower vertices and the edge
self.play(*[FadeOut(c, run_time=0.5) for c in cycle])
anims = self.erase_copy(self.edges[9], play=False)
anims += self.erase_copy([self.vertices[i] for i in lower_vertices], play=False)
self.play(*anims)
self.wait(1)
instr2 = TextMobject("$G$ is nonplanar, \\\\ so we need an \\\\ obstruction to $uv$ \\\\ on the outside of $C$." , alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw bad uv edge
self.draw(self.edges[6])
self.wait(6)
instr2 = TextMobject("There must exist \\\\ a path $v_i v_j$ \\\\ that blocks $uv$.", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
p_vertices = [2,7,4,8]
vi, vj = self.vertices[2], self.vertices[4]
self.draw([self.vertices[i] for i in p_vertices])
vi_label, vj_label = (TextMobject("$v_i$").scale(0.8).next_to(vi, UP*0.5),
TextMobject("$v_j$").scale(0.8 ).next_to(vj, DOWN*0.5))
self.play(Write(vi_label), Write(vj_label))
self.draw(self.edges[8])
self.erase_copy(self.edges[6])
self.wait(8)
# ---------------- OBSTRUCTIONS ------------------------------------------
instr2 = TextMobject("The inside of $C$ must \\\\ contain an obstruction \\\\ to $uv$ and to $v_i v_j$.", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
self.wait(18)
instr2 = TextMobject("Obstructions", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
self.wait(4)
instr2 = TextMobject("Obstruction 1:", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw obs1 vertices and edges
obstruction_vertices = [13,15]
obstruction_edges = range(14,15)
self.draw([self.vertices[i] for i in obstruction_vertices])
self.draw([self.edges[i] for i in obstruction_edges])
self.wait(2)
self.draw(self.edges[27])
self.wait(4)
k33 = TextMobject("$G$ contains $K_{3,3}$.", alignment="\\justify", color=RED)
k33.scale(0.75)
k33.next_to(instr, DOWN)
self.play(Write(k33))
# highlight K33
red_verts = [13,3,8]
green_verts = [0,7,15]
colors = [RED]*3 + [GREEN]*3
self.accent_vertices([self.vertices[i] for i in red_verts + green_verts], colors=colors, run_time=3)
self.wait(3)
# fadeout obs1 vertices and edges
anims = self.erase_copy([self.edges[i] for i in obstruction_edges], play=False)
anims += self.erase_copy([self.vertices[i] for i in obstruction_vertices], play=False)
anims += self.erase_copy(self.edges[27], play=False)
anims += [FadeOut(k33)]
self.play(*anims)
self.wait()
instr2 = TextMobject("Obstruction 2:", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw obs2 vertices and edges
obstruction_vertices = [12,14,15]
obstruction_edges = range(15,18)
self.draw([self.vertices[i] for i in obstruction_vertices])
self.draw([self.edges[i] for i in obstruction_edges])
self.play(Write(k33))
# highlight K33
self.draw(self.edges[27])
red_verts = [12,8,3]
green_verts = [0,14,15]
self.accent_vertices([self.vertices[i] for i in red_verts + green_verts], colors=colors, run_time=3)
# fadeout obs2 vertices and edges
anims = self.erase_copy([self.edges[i] for i in obstruction_edges], play=False)
anims += self.erase_copy([self.vertices[i] for i in obstruction_vertices], play=False)
anims += self.erase_copy(self.edges[27], play=False)
anims += [FadeOut(k33)]
self.play(*anims)
instr2 = TextMobject("Obstruction 3:", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw obs3 vertices and edges
obstruction_vertices = [10,11]
obstruction_edges = range(18,23)
self.draw([self.vertices[i] for i in obstruction_vertices])
self.draw([self.edges[i] for i in obstruction_edges])
self.play(Write(k33))
# highlight K33
self.draw(self.edges[27])
red_verts = [0,11,8]
green_verts = [10,7,3]
self.accent_vertices([self.vertices[i] for i in red_verts + green_verts], colors=colors, run_time=3)
# fadeout obs3 vertices and edges
anims = self.erase_copy([self.edges[i] for i in obstruction_edges], play=False)
anims += self.erase_copy([self.vertices[i] for i in obstruction_vertices], play=False)
anims += self.erase_copy(self.edges[27], play=False)
anims += [FadeOut(k33)]
self.play(*anims)
instr2 = TextMobject("Obstruction 4:", alignment="\\justify")
instr2.scale(0.8)
instr2.shift(RIGHT*3.5)
self.play(Transform(instr, instr2))
# draw obs4 vertices and edges
obstruction_vertices = [12]
obstruction_edges = range(23,27)
self.draw([self.vertices[i] for i in obstruction_vertices])
self.draw([self.edges[i] for i in obstruction_edges])
k5 = TextMobject("$G$ contains $K_{5}$.", alignment="\\justify", color=RED)
k5.scale(0.75)
k5.next_to(instr, DOWN)
self.play(Write(k5))
# highlight K33
self.draw(self.edges[27])
self.wait(1)
# fadeout obs4 vertices and edges
anims = self.erase_copy([self.edges[i] for i in obstruction_edges], play=False)
anims += self.erase_copy([self.vertices[i] for i in obstruction_vertices], play=False)
anims += self.erase_copy(self.edges[27], play=False)
anims += [FadeOut(k5)]
self.play(*anims)
self.wait(1)
erase_anims = []
erase_anims += self.erase(op.itemgetter(0,1,2,3,4,5,8)(self.edges), play=False)
erase_anims += self.erase(op.itemgetter(0,2,3,4,7,8)(self.vertices), play=False)
erase_anims += [FadeOut(e) for e in [instr, vi_label, vj_label, C_label, u_label, v_label]]
self.play(*erase_anims)
f1 = TextMobject("Result: $G$ always contains a subgraph \\\\ which is a subdivision of $K_5$ or $K_{3,3}$.")
f1.scale(1).shift(UP*2)
self.play(Write(f1))
self.wait(3)
f2 = TextMobject("Contradiction! We assumed that this was not the case.")
f2.scale(1).next_to(f1, DOWN*3)
self.play(Write(f2))
self.wait(5)
self.play(*[FadeOut(e) for e in [f1,f2]])
self.wait(2)
class KuratowskiResultScene(Scene):
def construct(self):
super().construct()
self.wait(3)
f1 = TextMobject("Kuratowski's Theorem: \\\\ A graph is nonplanar $\\Longleftrightarrow$ it has a subgraph \\\\ which is a subdivision of $K_5$ or $K_{3,3}$")
f1.shift(UP*2.5)
f1.scale(1)
self.play(Write(f1))
f2 = TextMobject("This allows us to describe \\emph{exactly} which graphs \\\\ can and cannot be embedded in the plane!")
f2.scale(1).next_to(f1, DOWN*4)
self.play(Write(f2))
self.wait(4)
f3 = TextMobject("Which graphs can be embedded into \\\\ other topological spaces?")
f3.scale(1).next_to(f2, DOWN*4)
self.play(Write(f3))
self.wait(14)
self.play(*[FadeOut(e) for e in [f1,f2,f3]])
self.wait(1)
|
StarcoderdataPython
|
12852369
|
# tests for narps code
# - currently these are all just smoke tests
import pytest
import os
import pandas
from narps import Narps
from AnalyzeMaps import mk_overlap_maps,\
mk_range_maps, mk_std_maps,\
mk_correlation_maps_unthresh, analyze_clusters,\
plot_distance_from_mean, get_thresh_similarity
from MetaAnalysis import get_thresholded_Z_maps
from ThreshVoxelStatistics import get_thresh_voxel_stats,\
get_zstat_diagnostics
from GetMeanSimilarity import get_similarity_summary
# Use a fixed base dir so that we can
# access the results as a circleci artifact
@pytest.fixture(scope="session")
def narps():
basedir = '/tmp/data'
assert os.path.exists(basedir)
narps = Narps(basedir)
narps.load_data()
narps.metadata = pandas.read_csv(
os.path.join(narps.dirs.dirs['metadata'], 'all_metadata.csv'))
return(narps)
# tests
# AnalyzeMaps
def test_mk_overlap_maps(narps):
# create maps showing overlap of thresholded images
mk_overlap_maps(narps)
def test_mk_range_maps(narps):
mk_range_maps(narps)
def test_mk_std_maps(narps):
mk_std_maps(narps)
def test_unthresh_correlation_analysis(narps):
# conbine these into a single test
# since they share data
corr_type = 'spearman'
dendrograms, membership = mk_correlation_maps_unthresh(
narps, corr_type=corr_type)
_ = analyze_clusters(
narps,
dendrograms,
membership,
corr_type=corr_type)
def test_plot_distance_from_mean(narps):
plot_distance_from_mean(narps)
def test_get_thresh_similarity(narps):
get_thresh_similarity(narps)
# this was created for ALE but we do it earlier here
def test_thresh_zmap(narps):
# create thresholded versions of Z maps
narps = get_thresholded_Z_maps(
narps)
def test_thresh_voxel_stats(narps):
get_zstat_diagnostics(narps)
get_thresh_voxel_stats(narps.basedir)
def test_mean_similarity(narps):
_ = get_similarity_summary(narps)
|
StarcoderdataPython
|
308943
|
#!/usr/bin/python3
import boto3
import datetime
#from subprocess import call
import os
debug_on = True
today = datetime.date.today()
bucket_name = 'halimer-dns-analytics'
log_folder_name = '/var/log/'
tmp_dir = '/tmp/'
prefix = 'd=' + str(today) + '/'
pihole_log_file = 'pihole.log'
clean_log_name = 'clean_dns.log'
#print clean_log_name
def debug(title,item):
if(debug_on):
print(title)
print(item)
return
def get_private_words():
with open('donotanalyze.txt') as private_txt:
private_txt.seek(0)
private_raw = private_txt.read()
print(private_raw)
split_word_list = private_raw.split('\n')
private_word_list =[]
for word in split_word_list:
if word != '':
private_word_list.append(word)
return private_word_list
def remove_private_words():
words_to_scrub = get_private_words()
current_log_file=pihole_log_file
number_of_words = len(words_to_scrub)
debug("Number of Blacklist Words",number_of_words)
word_counter = 0
grep_string="egrep -v '"
for word in words_to_scrub:
grep_string+=word
word_counter += 1
if(word_counter < len(words_to_scrub)):
grep_string+='|'
grep_string += "' " + log_folder_name + current_log_file +" > " + tmp_dir + clean_log_name
print(grep_string)
os.system(grep_string)
def delete_old_log_files():
os.system('pihole -f')
os.system('rm ' + tmp_dir + clean_log_name)
def upload_log_to_s3():
client = boto3.client('s3')
s3 = boto3.resource('s3')
response = s3.meta.client.upload_file(tmp_dir + clean_log_name,bucket_name, prefix + clean_log_name)
debug("Response is :", response)
words = get_private_words()
debug("Words",words)
number_of_words = len(words)
debug("Number of Blacklist Words",number_of_words)
debug("Prefix is: ", prefix)
remove_private_words()
upload_log_to_s3()
delete_old_log_files()
|
StarcoderdataPython
|
3511006
|
import pytest
import requests
from requests import HTTPError
from dcos_test_utils.helpers import Url
from dcos_test_utils.jobs import Jobs
class MockResponse:
def __init__(self, json: dict, status_code: int):
self._json = json
self._status_code = status_code
def json(self):
return self._json
def raise_for_status(self):
"""Throw an HTTPErrer based on status code."""
if self._status_code >= 400:
raise HTTPError('Throwing test error', response=self)
@property
def status_code(self):
return self._status_code
class MockEmitter:
"""Emulates a Session and responds with a queued response for each
request made. If no responses are queued, the request will raise
an error.
A history of requests are held in a request cache and can be
reviewed.
"""
def __init__(self, mock_responses: list):
self._mock_responses = mock_responses
self._request_cache = list()
def request(self, *args, **kwargs):
self._request_cache.append((args, kwargs))
return self._mock_responses.pop(0)
def queue(self, response: list):
"""Add responses to the response queue.
:param response: A list of responses
:type response: list
"""
self._mock_responses.extend(response)
@property
def headers(self):
return dict()
@property
def cookies(self):
return dict()
@property
def debug_cache(self):
"""Return the list of requests made during this session.
Items in the cache are formatted:
((Method, URL), params)
:return: a list of requests made to this session
:rtype: list
"""
return self._request_cache
@pytest.fixture
def replay_session(monkeypatch):
"""A mocked session that sends back the configured responses in
order.
"""
mock_session = MockEmitter(list())
monkeypatch.setattr(requests, 'Session',
lambda *args, **kwargs: mock_session)
yield mock_session
print('Actual session requests:')
print(mock_session.debug_cache)
@pytest.fixture
def mock_url():
"""A URL that is accepted by DcosApiSession."""
return Url('https',
'localhost',
'service/metronome',
'', '',
port=443)
def test_jobs_create(mock_url, replay_session):
"""Create should return JSON of the created Job."""
job_payload = {'id': 'app1'}
resp_json = {'id': 'response'}
exp_method = 'POST'
exp_url = 'https://localhost:443/service/metronome/v1/jobs'
replay_session.queue([MockResponse(resp_json, 201)])
j = Jobs(default_url=mock_url)
assert j.create(job_payload) == resp_json
assert len(replay_session.debug_cache) == 1
assert replay_session.debug_cache[0] == (
(exp_method, exp_url), {'json': job_payload})
def test_jobs_create_raise_error(mock_url, replay_session):
replay_session.queue([MockResponse({}, 500)])
j = Jobs(default_url=mock_url)
with pytest.raises(HTTPError):
j.create({'id': 'app1'})
def test_jobs_destroy(mock_url, replay_session):
"""Destroy sends a DELETE and does not return anything."""
exp_method = 'DELETE'
exp_url = 'https://localhost:443/service/metronome/v1/jobs/myapp1'
replay_session.queue([MockResponse({}, 200)])
j = Jobs(default_url=mock_url)
j.destroy('myapp1')
assert replay_session.debug_cache[0] == (
(exp_method, exp_url),
{'params': {'stopCurrentJobRuns': 'true'}})
def test_jobs_destroy_raise_error(mock_url, replay_session):
replay_session.queue([MockResponse({}, 500)])
j = Jobs(default_url=mock_url)
with pytest.raises(HTTPError):
j.destroy('myapp1')
def test_jobs_start(mock_url, replay_session):
"""Test the `start` method and verify the returned JSON."""
job_payload = {'id': 'myrun1'}
exp_method = 'POST'
exp_url = 'https://localhost:443/service/metronome/v1/jobs/myapp1/runs'
replay_session.queue([MockResponse(job_payload, 201)])
j = Jobs(default_url=mock_url)
assert job_payload == j.start('myapp1')
# verify HTTP method and URL
assert replay_session.debug_cache[0] == (
(exp_method, exp_url), {})
def test_jobs_start_raise_error(mock_url, replay_session):
replay_session.queue([MockResponse({}, 500)])
j = Jobs(default_url=mock_url)
with pytest.raises(HTTPError):
j.start('myapp1')
def test_jobs_run(mock_url, replay_session):
"""Test the `run` method, which is a mixture of `start`
and waiting (looping) on the run to complete.
"""
run_payload = {'id': 'myrun1'}
job_payload = {'id': 'myjob',
'history': {'successfulFinishedRuns': [run_payload],
'failedFinishedRuns': []}}
# 2 200's to test timeout=1
mock_replay = list((
MockResponse(run_payload, 201),
MockResponse({}, 200),
MockResponse({}, 404), # break the wait loop (run over)
MockResponse(job_payload, 200),
MockResponse(job_payload, 200),
))
replay_session.queue(mock_replay)
j = Jobs(default_url=mock_url)
success, run, job = j.run('myapp1')
assert success is True
assert run == run_payload
assert job == job_payload
assert len(replay_session.debug_cache) == 5
def test_jobs_run_failed_run(mock_url, replay_session):
"""Test the `run` method, which is a mixture of `start`
and waiting (looping) on the run to complete.
This test expects the Run to appear in the failed run list.
"""
run_payload = {'id': 'myrun1'}
job_payload = {'id': 'myjob',
'history': {'successfulFinishedRuns': [],
'failedFinishedRuns': [run_payload]}}
# 2 200's to test timeout=1
mock_replay = list((
MockResponse(run_payload, 201),
MockResponse({}, 404),
MockResponse(job_payload, 200),
MockResponse(job_payload, 200),
))
replay_session.queue(mock_replay)
j = Jobs(default_url=mock_url)
success, run, job = j.run('myapp1')
assert success is False
assert run == run_payload
assert job == job_payload
assert len(replay_session.debug_cache) == 4
def test_jobs_run_timeout(mock_url, replay_session):
run_payload = {'id': 'myrun1'}
job_payload = {'id': 'myjob',
'history': {'successfulFinishedRuns': [run_payload],
'failedFinishedRuns': []}}
# lots of responses, but only a few will trigger before timeout
mock_replay = list((
MockResponse(run_payload, 201),
MockResponse({}, 200),
MockResponse({}, 200),
MockResponse({}, 200), # should timeout here
MockResponse({}, 200),
MockResponse({}, 200),
MockResponse({}, 404),
MockResponse(job_payload, 200),
))
replay_session.queue(mock_replay)
j = Jobs(default_url=mock_url)
with pytest.raises(Exception):
j.run('myapp1', timeout=2)
assert len(replay_session.debug_cache) == 4
def test_jobs_run_history_not_available(mock_url, replay_session):
run_payload = {'id': 'myrun1'}
job_payload = {'id': 'myjob',
'history': {'successfulFinishedRuns': [],
'failedFinishedRuns': []}}
exp_err_msg = 'Waiting for job run myrun1 to be finished, but history for that job run is not available'
# lots of responses, but only a few will trigger before timeout
mock_replay = list((
MockResponse(run_payload, 201),
MockResponse({}, 404),
MockResponse(job_payload, 200),
MockResponse({}, 404),
MockResponse(job_payload, 200),
MockResponse({}, 404),
MockResponse(job_payload, 200),
MockResponse({}, 404),
MockResponse(job_payload, 200)
))
replay_session.queue(mock_replay)
j = Jobs(default_url=mock_url)
with pytest.raises(Exception) as error:
j.run('myapp1', timeout=2)
assert str(error.value) == exp_err_msg
def test_jobs_run_unknown_error(mock_url, replay_session):
run_payload = {'id': 'myrun1'}
exp_err_msg = 'Waiting for job run myrun1 to be finished, but getting HTTP status code 500'
mock_replay = list((
MockResponse(run_payload, 201),
MockResponse({}, 500),
))
replay_session.queue(mock_replay)
j = Jobs(default_url=mock_url)
with pytest.raises(HTTPError) as http_error:
j.run('myapp1')
assert str(http_error.value) == exp_err_msg
assert len(replay_session.debug_cache) == 2
def test_jobs_run_details(mock_url, replay_session):
run_payload = {'id': 'myrun1', 'foo': 'bar'}
exp_method = 'GET'
exp_url = 'https://localhost:443/service/metronome/v1/jobs/myjob' \
'/runs/myrun1'
replay_session.queue([MockResponse(run_payload, 200)])
j = Jobs(default_url=mock_url)
r = j.run_details('myjob', 'myrun1')
assert r == run_payload
assert replay_session.debug_cache[0] == (
(exp_method, exp_url), {})
def test_jobs_run_stop(mock_url, replay_session):
exp_method = 'POST'
exp_url = 'https://localhost:443/service/metronome/v1/jobs/myjob' \
'/runs/myrun1/actions/stop'
replay_session.queue([MockResponse({}, 200)])
j = Jobs(default_url=mock_url)
j.run_stop('myjob', 'myrun1')
assert replay_session.debug_cache[0] == (
(exp_method, exp_url), {})
|
StarcoderdataPython
|
283666
|
<filename>srsran_controller/common/utils.py
from contextlib import contextmanager
from subprocess import Popen, PIPE
@contextmanager
def shutdown_on_error(instance):
try:
yield instance
except Exception:
instance.shutdown()
raise
def run_as_sudo(command, password, stdout=PIPE, stderr=PIPE):
sudo = ['sudo', '-S'] + command
with Popen(sudo, stdin=PIPE, stdout=stdout, stderr=stderr) as proc:
proc.communicate(password.encode())
|
StarcoderdataPython
|
9754676
|
<reponame>lsst-camera-dh/ts3-analysis<filename>read_lims_db.py
import pickle
input = open('my_fakelims.db')
db = pickle.load(input)
|
StarcoderdataPython
|
12819507
|
<filename>zoonado/recipes/sequential.py
from __future__ import unicode_literals
import logging
import re
import uuid
from tornado import gen
from zoonado import exc, WatchEvent
from .recipe import Recipe
log = logging.getLogger(__name__)
sequential_re = re.compile(r'.*[0-9]{10}$')
class SequentialRecipe(Recipe):
def __init__(self, base_path):
super(SequentialRecipe, self).__init__(base_path)
self.guid = uuid.uuid4().hex
self.owned_paths = {}
def sequence_number(self, sibling):
return int(sibling[-10:])
def determine_znode_label(self, sibling):
return sibling.rsplit("-", 2)[0]
def sibling_path(self, path):
return "/".join([self.base_path, path])
@gen.coroutine
def create_unique_znode(self, znode_label, data=None):
path = self.sibling_path(znode_label + "-" + self.guid + "-")
try:
created_path = yield self.client.create(
path, data=data, ephemeral=True, sequential=True
)
except exc.NoNode:
yield self.ensure_path()
created_path = yield self.client.create(
path, data=data, ephemeral=True, sequential=True
)
self.owned_paths[znode_label] = created_path
@gen.coroutine
def delete_unique_znode(self, znode_label):
try:
yield self.client.delete(self.owned_paths[znode_label])
except exc.NoNode:
pass
@gen.coroutine
def analyze_siblings(self):
siblings = yield self.client.get_children(self.base_path)
siblings = [name for name in siblings if sequential_re.match(name)]
siblings.sort(key=self.sequence_number)
owned_positions = {}
for index, path in enumerate(siblings):
if self.guid in path:
owned_positions[self.determine_znode_label(path)] = index
raise gen.Return((owned_positions, siblings))
@gen.coroutine
def wait_on_sibling(self, sibling, time_limit=None):
log.debug("Waiting on sibling %s", sibling)
path = self.sibling_path(sibling)
unblocked = self.client.wait_for_event(WatchEvent.DELETED, path)
if time_limit:
unblocked = gen.with_timeout(time_limit, unblocked)
exists = yield self.client.exists(path=path, watch=True)
if not exists:
unblocked.set_result(None)
try:
yield unblocked
except gen.TimeoutError:
raise exc.TimeoutError
|
StarcoderdataPython
|
9643526
|
<filename>Color.py<gh_stars>0
class Color:
def __init__(self, hue:int, vividness:int, brightness:int) -> None:
if hue > 29:
raise ValueError("Hue value cannot be larger than 30")
if vividness > 14:
raise ValueError("Vividness value cannot be larger than 15")
if brightness > 14:
raise ValueError("Brightness value cannot be larger than 15")
self.hue = hue
self.vividness = vividness
self.brightness = brightness
def __repr__ (self) -> str:
return f"hue: {self.hue} vividness: {self.vividness} brightness: {self.brightness}"
@staticmethod
#This method is pretty much just copied from https://github.com/Thulinma/ACNLPatternTool/blob/bf2fd35a7a1c841b267f968ddfcfa043b4aaaa29/src/libs/ACNHFormat.js
#and translated into python
def from_rgb(r:int, g:int, b:int) -> 'tuple[int]':
Sinc = 6.68
Vstart = 7.843
Vinc = 5.58
r /= 255
g /= 255
b /= 255
M = max(r, g, b)
m = min(r, g, b)
C = M - m
h = 0
if C == 0:
h = 0
elif M == r:
h = ((g - b) / C) % 6
elif M == g:
h = (b - r) / C + 2
else:
h = (r - g) / C + 4
if h < 0:
h += 6
if M == 0:
s = 0
else:
s = (C/M) * 100
v = M * 100
values = (max(0, min(29, round(h * 5))),
max(0, min(14, round(s / Sinc))),
max(0, min(14, round((v - Vstart) / Vinc))))
return Color(values[0], values[1], values[2])
|
StarcoderdataPython
|
5111966
|
import argparse
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import scipy as sp
import scipy.stats
import pyemma
from pyemma.util.contexts import settings
import MDAnalysis as mda
# My own functions
from pensa import *
# -------------#
# --- MAIN --- #
# -------------#
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ref_file_a", type=str, default='traj/rhodopsin_arrbound_receptor.gro')
parser.add_argument("--trj_file_a", type=str, default='traj/rhodopsin_arrbound_receptor.xtc')
parser.add_argument("--ref_file_b", type=str, default='traj/rhodopsin_gibound_receptor.gro')
parser.add_argument("--trj_file_b", type=str, default='traj/rhodopsin_gibound_receptor.xtc')
parser.add_argument("--label_a", type=str, default='Sim A')
parser.add_argument("--label_b", type=str, default='Sim B')
parser.add_argument("--out_plots", type=str, default='plots/rhodopsin_receptor' )
parser.add_argument("--out_results", type=str, default='results/rhodopsin_receptor' )
parser.add_argument("--out_frames_a", type=str, default='clusters/rhodopsin_arrbound_receptor' )
parser.add_argument("--out_frames_b", type=str, default='clusters/rhodopsin_gibound_receptor' )
parser.add_argument("--start_frame", type=int, default=0 )
parser.add_argument("--feature_type", type=str, default='bb-torsions' )
parser.add_argument("--algorithm", type=str, default='kmeans' )
parser.add_argument("--max_num_clusters", type=int, default=12 )
parser.add_argument("--write_num_clusters", type=int, default=2 )
parser.add_argument('--write', dest='write', action='store_true')
parser.add_argument('--no-write', dest='write', action='store_false')
parser.add_argument('--wss', dest='wss', action='store_true')
parser.add_argument('--no-wss', dest='wss', action='store_false')
parser.set_defaults(write=True, wss=True)
args = parser.parse_args()
# -- FEATURES --
# Load Features
feat_a, data_a = get_structure_features(args.ref_file_a, args.trj_file_a, args.start_frame, cossin=True)
feat_b, data_b = get_structure_features(args.ref_file_b, args.trj_file_b, args.start_frame, cossin=True)
# Report dimensions
print('Feature dimensions from', args.trj_file_a)
for k in data_a.keys():
print(k, data_a[k].shape)
print('Feature dimensions from', args.trj_file_b)
for k in data_b.keys():
print(k, data_b[k].shape)
# -- CLUSTERING THE COMBINED DATA --
ftype = args.feature_type
# Calculate clusters from the combined data
cc = obtain_combined_clusters(data_a[ftype], data_b[ftype], args.label_a, args.label_b, args.start_frame,
args.algorithm, max_iter=100, num_clusters=args.write_num_clusters, min_dist=12,
saveas=args.out_plots+'_combined-clusters_'+ftype+'.pdf')
cidx, cond, oidx, wss, centroids = cc
# Write indices to results file
np.savetxt(args.out_results+'_combined-cluster-indices.csv',
np.array([cidx, cond, oidx], dtype=int).T,
delimiter=',', fmt='%i',
header='Cluster, Condition, Index within condition')
# Write out frames for each cluster for each simulation
if args.write:
write_cluster_traj(cidx[cond==0], args.ref_file_a, args.trj_file_a,
args.out_frames_a, args.start_frame )
write_cluster_traj(cidx[cond==1], args.ref_file_b, args.trj_file_b,
args.out_frames_b, args.start_frame )
# -- Within-Sum-of-Squares (WSS) analysis --
if args.wss:
wss_avg, wss_std = wss_over_number_of_combined_clusters(data_a[ftype], data_b[ftype],
label_a=args.label_a, label_b=args.label_b,
start_frame=args.start_frame,
algorithm=args.algorithm,
max_iter = 100, num_repeats = 5,
max_num_clusters = args.max_num_clusters,
plot_file = args.out_plots+'_wss_'+ftype+'.pdf')
|
StarcoderdataPython
|
11212180
|
"""Module that contains exceptions handled in config parsing and loading."""
import traceback
from typing import Any, Optional
class IniError(Exception):
"""Exception caused by error in INI file syntax."""
def __init__(self,
line: int,
message: str,
original_exc: Optional[Exception] = None) -> None:
"""Create an instance of the exception.
Arguments:
line: Line number on which the error occured
message: A string describing the nature of the error
original_exc (optional): An exception that caused this exception
to be thrown
"""
super().__init__()
self.line = line
self.message = message
self.original_exc = original_exc
def __str__(self) -> str:
"""Convert this exception to string."""
msg = "Error on line {}: {}".format(self.line, self.message)
if self.original_exc is not None:
trc = "".join(traceback.format_list(traceback.extract_tb(
self.original_exc.__traceback__)))
msg += "\nTraceback:{}".format(trc)
return msg
class ConfigInvalidValueException(Exception):
def __init__(self, value: Any, message: str) -> None:
"""Create an instance of the exception.
Arguments:
value: The invalid value
message: String that describes the nature of the error
"""
super().__init__()
self.value = value
self.message = message
def __str__(self) -> str:
"""Convert this exception to string."""
return "Error in configuration of {}: {}".format(self.value,
self.message)
class ConfigBuildException(Exception):
"""Exception caused by error in loading the model."""
def __init__(self, object_name: str,
original_exception: Exception) -> None:
"""Create an instance of the exception.
Arguments:
object_name: The name of the object that has failed to build
original_exception: The exception that caused the failure
"""
super().__init__()
self.object_name = object_name
self.original_exception = original_exception
def __str__(self) -> str:
"""Convert this exception to string."""
trc = "".join(traceback.format_list(traceback.extract_tb(
self.original_exception.__traceback__)))
return "Error while loading '{}': {}\nTraceback: {}".format(
self.object_name, self.original_exception, trc)
|
StarcoderdataPython
|
4971213
|
<gh_stars>0
# Anagram check: O(NLogN)
def is_anagram(str1, str2):
print(str1)
print(str2)
if len(str1) != len(str2):
print('False')
return False
str1 = sorted(str1)
print(str1)
str2 = sorted(str2)
print(str2)
for i in range(len(str1)):
if str1[i] != str2[i]:
print('False')
return False
print('String is Anagram')
return True
if __name__ == '__main__':
str1 = 'rowda'
str2 = 'dowry'
is_anagram(str1, str2)
|
StarcoderdataPython
|
347432
|
"""
Handles assembler functionality, powered by the Keystone engine.
:author: <NAME>
:license: MIT
"""
from __future__ import absolute_import
import logging
import re
from chiasm_shell.backend import Backend
l = logging.getLogger('chiasm_shell.assembler')
try:
import keystone as ks
except ImportError as e:
l.error("*** KEYSTONE IMPORT FAILURE ***")
l.error("If you thought you'd already installed keystone-engine,")
l.error("please ensure that you've got CMake and any other")
l.error("Keystone dependencies installed on your system and")
l.error("then try and build it/pip install it again.")
l.error("Consult http://www.keystone-engine.org/docs/ for specifics.")
raise e
class Assembler(Backend):
"""
Assembler - uses keystone to print opcodes from assembly input
"""
def __init__(self):
"""
Create a new Assembler instance.
"""
self._ks = None
self._last_encoding = None
self._arch = None
self.mode = None
self.modes = None
self.valid_archs = None
Backend.__init__(self)
def _init_backend(self):
"""
_init_backend is responsible for setting the prompt, custom init stuff.
"""
self.prompt = 'asm> '
self._build_dicts()
self._arch = ('x86', '32')
self._set_arch(*self._arch)
self._last_encoding = None
def _build_dicts(self):
"""
Build dicts of valid arch and known mode values.
"""
regex_arch = re.compile(r'^KS_ARCH_\S+$')
regex_mode = re.compile(r'^KS_MODE_\S+$')
d = ks.__dict__
self.valid_archs = {a: d[a] for a in d.keys()
if re.match(regex_arch, a) and ks.ks_arch_supported(d[a])}
self.modes = {m: d[m] for m in d.keys() if re.match(regex_mode, m)}
def clear_state(self):
self._last_encoding = None
def _set_arch(self, arch, *modes):
"""
Try and set the current architecture
"""
try:
a = self.valid_archs[''.join(['KS_ARCH_', arch.upper()])]
if a is None:
l.error("Invalid architecture selected - run lsarch for valid options")
return False
ms = [self.modes[''.join(['KS_MODE_', m.upper()])] for m in modes]
except KeyError:
l.error("ERROR: Invalid architecture or mode string specified")
return False
try:
_ks = ks.Ks(a, sum(ms))
self._arch = (arch, modes)
l.debug("Architecture set to %s, mode(s): %s", arch, ', '.join(modes))
self._ks = _ks
except ks.KsError as e:
l.error("ERROR: %s", e)
return False
return True
def get_arch(self):
return "{}, mode(s): {}".format(self._arch[0], ', '.join(self._arch[1]))
def default(self, line):
"""
Default behaviour - if no other commands are detected,
try and assemble the current input according to the
currently set architecture.
:param line: Current line's text to try and assemble.
"""
try:
encoding, dummy_insn_count = self._ks.asm(line)
self._last_encoding = encoding
l.info("".join('\\x{:02x}'.format(opcode) for opcode in encoding))
except ks.KsError as e:
l.error("ERROR: %s", e)
def do_lsarch(self, dummy_args):
"""
Lists the architectures available in the installed version of keystone.
"""
for a in self.valid_archs:
l.info(a[8:].lower())
def do_setarch(self, args):
"""
Set the current architecture.
:param args: Lowercase string representing the requested architecture.
"""
a = args.split()
if len(a) < 2:
l.error("Need to specify at least arch and one mode")
return
arch = a[0]
modes = a[1:]
if self._set_arch(arch, *modes) is True:
l.info("Architecture set to %s, mode(s): %s", arch, ', '.join(modes))
def do_lsmodes(self, dummy_args):
"""
Lists the known modes across all architectures.
Note that not all modes apply to all architectures.
"""
for a in sorted(self.modes):
l.info(a[8:].lower())
def do_count(self, dummy_args):
"""
Prints the number of bytes emitted by the last successful encoding
(or nothing if no successful encodings have occurred yet.)
"""
if self._last_encoding is not None:
l.info(len(self._last_encoding))
|
StarcoderdataPython
|
1683559
|
<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import sys
import os
import unittest
import re
import web
from paste.fixture import TestApp
#from nose.tools import *
import logging
import karesansui
import karesansui.urls
username = "ja@localhost"
password = "password"
class TestRestAPI(unittest.TestCase):
def setUp(self):
middleware = []
self.logger = logging.getLogger('restapi')
urls = karesansui.urls.urls
app = web.application(urls, globals(), autoreload=False)
from karesansui.app import load_sqlalchemy_karesansui,load_sqlalchemy_pysilhouette
app.add_processor(load_sqlalchemy_karesansui)
app.add_processor(load_sqlalchemy_pysilhouette)
self.prefix = ""
if karesansui.config['application.url.prefix']:
mapping = (karesansui.config['application.url.prefix'], app)
app = web.subdir_application(mapping)
self.prefix = karesansui.config['application.url.prefix']
self.app = TestApp(app.wsgifunc(*middleware))
self.headers = {}
if username != None and password != None:
from base64 import b64encode
base64string =b64encode("%s:%s" % (username, password))
self.headers = {"Authorization": "Basic %s" % base64string}
return True
def tearDown(self):
return True
def test_dummy(self):
self.assertEqual(True,True)
def test_get_index(self):
r = self.app.get("%s/" % self.prefix,headers=self.headers)
assert_equal(r.status, 200)
r.mustcontain('Now Loading')
def test_get_host_1_index(self):
r = self.app.get("%s/host/1/" % self.prefix,headers=self.headers)
assert_equal(r.status, 200)
r.mustcontain('Now Loading')
def test_get_host_1_json(self):
r = self.app.get("%s/host/1.json" % self.prefix,headers=self.headers)
assert_equal(r.status, 200)
r.mustcontain('other_url')
def test_get_host_1_guest_2_index(self):
r = self.app.get("%s/host/1/guest/2/" % self.prefix,headers=self.headers)
assert_equal(r.status, 200)
r.mustcontain('Now Loading')
def test_get_host_1_guest_2_json(self):
r = self.app.get("%s/host/1/guest/2.json" % self.prefix,headers=self.headers)
assert_equal(r.status, 200)
r.mustcontain('other_url')
def test_post_host_1_guest(self):
params = {}
params['domain_name'] = 'foobar'
params['m_name'] = 'foobar'
params['icon_filename'] = ''
params['m_hypervisor'] = '1'
params['note_title'] = 'title'
params['note_value'] = 'value'
params['tags'] = ''
params['nic_type'] = 'phydev'
params['phydev'] = 'xenbr0'
params['virnet'] = 'default'
params['xen_disk_size'] = '4096'
params['xen_extra'] = ''
params['xen_initrd'] = '/var/ftp/images/xen/initrd.img'
params['xen_kernel'] = '/var/ftp/images/xen/vmlinuz'
params['xen_mac'] = '00:16:3e:4e:4d:e2'
params['xen_mem_size'] = '256'
params['xen_graphics_port'] = '5910'
upload_files=None
r = self.app.post("%s/host/1/guest.part" % self.prefix,params=params,headers=self.headers,upload_files=upload_files)
assert_equal(r.status, 200)
r.mustcontain('other_url')
def test_del_host_1_guest_2(self):
r = self.app.delete("%s/host/1/guest/2" % self.prefix,headers=self.headers)
assert_equal(r.status, 200)
r.mustcontain('other_url')
class SuiteRestAPI(unittest.TestSuite):
def __init__(self):
tests = ['test_dummy',
'test_get_index',
'test_get_host_1_index',
'test_get_host_1_json',
'test_get_host_1_guest_2_index',
'test_get_host_1_guest_2_json',
'test_post_host_1_guest',
]
unittest.TestSuite.__init__(self,map(TestRestAPI, tests))
def all_suite_restapi():
return unittest.TestSuite([SuiteRestAPI()])
def main():
unittest.TextTestRunner(verbosity=2).run(all_suite_restapi())
if __name__ == '__main__':
main()
|
StarcoderdataPython
|
11305769
|
<reponame>grepleria/SnitchDNS<gh_stars>100-1000
from app.lib.notifications.managers.type_manager import NotificationTypeManager
from app.lib.notifications.managers.subscription_manager import NotificationSubscriptionManager
from app.lib.notifications.managers.log_manager import NotificationLogManager
from app.lib.notifications.managers.provider_manager import NotificationProviderManager
from app.lib.notifications.managers.webpush_manager import WebPushManager
from app.lib.notifications.instances.subscriptions import NotificationSubscriptionCollection
class NotificationManager:
def __init__(self):
self.types = NotificationTypeManager()
self.subscriptions = NotificationSubscriptionManager()
self.logs = NotificationLogManager()
self.providers = NotificationProviderManager()
self.webpush = WebPushManager()
def save_zone_subscription(self, zone_id, type_name, enabled=None, data=None, last_query_log_id=None):
type = self.types.get(name=type_name)
if not type:
raise Exception("Coding Error: Invalid `type_name` parameter: {0}".format(type_name))
subscription = self.subscriptions.get(zone_id=zone_id, type_id=type.id)
if not subscription:
# Create one.
subscription = self.subscriptions.create(zone_id=zone_id, type_id=type.id)
if enabled is not None:
subscription.enabled = True if enabled else False
if data is not None:
subscription.data = data
if last_query_log_id is not None:
subscription.last_query_log_id = last_query_log_id
subscription.save()
return subscription
def get_zone_subscriptions(self, zone_id):
self.create_missing_subscriptions(zone_id)
collection = NotificationSubscriptionCollection()
subscriptions = self.subscriptions.all(zone_id=zone_id)
for subscription in subscriptions:
type_name = self.types.get_type_name(subscription.type_id)
if type_name is False:
continue
collection.add(type_name, subscription)
return collection
def create_missing_subscriptions(self, zone_id):
# Get all types.
types = self.types.all()
# Find types that don't exist.
for type in types:
subscription = self.subscriptions.get(zone_id=zone_id, type_id=type.id)
if subscription:
continue
# Create them.
subscription = self.subscriptions.create(zone_id=zone_id, type_id=type.id)
subscription.enabled = False
subscription.data = ''
subscription.last_query_log_id = 0
subscription.save()
return True
|
StarcoderdataPython
|
4990623
|
<gh_stars>10-100
from copy import copy
import types
import functools
def copy_func(f, new_funcs):
"""
Based on http://stackoverflow.com/a/6528148/190597
by <NAME>
>>> def f(a, b, c): return a + b + c
>>> g = copy_func(f, {})
>>> g is not f
True
>>> f(1, 2, 3) == g(1, 2, 3)
True
>>> import numpy as np
>>> isinstance(np.sin, np.ufunc)
True
>>> copy_func(np.sin, {})
<ufunc 'sin'>
"""
if not hasattr(f, '__globals__'):
return f
globs = copy(f.__globals__)
globs.update(new_funcs)
g = types.FunctionType(
f.__code__, globs, name=f.__name__,
argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
if __name__ == '__main__':
import pytest
pytest.main([__file__])
|
StarcoderdataPython
|
1873481
|
#Activity 2 (Connectivity)
import mysql.connector as mc
connectMySQL = mc.connect(host = 'localhost', user = 'root', password = '<PASSWORD>', database = 'mydb')
cursor = connectMySQL.cursor(buffered = True)
def insert_values():
item_code = input("Enter the ItemCode: ")
item_name = input("Enter the ItemName: ")
price = float(input("Enter the Price: "))
sql = f"insert into ITEM values ('{item_code}', '{item_name}', {price})"
cursor.execute(sql)
connectMySQL.commit()
def display_records():
sql = "select * from ITEM"
cursor.execute(sql)
result = cursor.fetchall()
for i in result:
print(i)
def search():
item_code = input("Enter the ItemCode: ")
sql = "select * from ITEM where Itemcode = '{item_code}'"
cursor.execute(sql)
result = cursor.fetchone()
print(result)
|
StarcoderdataPython
|
11235036
|
<filename>pkgs/dask-0.8.1-py27_0/lib/python2.7/site-packages/dask/array/numpy_compat.py
from __future__ import absolute_import, division, print_function
import numpy as np
import warnings
try:
isclose = np.isclose
except AttributeError:
def isclose(*args, **kwargs):
raise RuntimeError("You need numpy version 1.7 or greater to use "
"isclose.")
try:
full = np.full
except AttributeError:
def full(shape, fill_value, dtype=None, order=None):
"""Our implementation of numpy.full because your numpy is old."""
if order is not None:
raise NotImplementedError("`order` kwarg is not supported upgrade "
"to Numpy 1.8 or greater for support.")
return np.multiply(fill_value, np.ones(shape, dtype=dtype),
dtype=dtype)
# Taken from scikit-learn:
# https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/fixes.py#L84
try:
with warnings.catch_warnings():
if (not np.allclose(np.divide(.4, 1, casting="unsafe"),
np.divide(.4, 1, casting="unsafe", dtype=np.float))
or not np.allclose(np.divide(1, .5, dtype='i8'), 2)
or not np.allclose(np.divide(.4, 1), .4)):
raise TypeError('Divide not working with dtype: '
'https://github.com/numpy/numpy/issues/3484')
divide = np.divide
except TypeError:
# Divide with dtype doesn't work on Python 3
def divide(x1, x2, out=None, dtype=None):
"""Implementation of numpy.divide that works with dtype kwarg.
Temporary compatibility fix for a bug in numpy's version. See
https://github.com/numpy/numpy/issues/3484 for the relevant issue."""
x = np.divide(x1, x2, out)
if dtype is not None:
x = x.astype(dtype)
return x
|
StarcoderdataPython
|
6645609
|
<gh_stars>0
first_set = {2, 'd', 4, 3.23232, 'hehe'}
print(f'{first_set =}')
for items in first_set:
print(items)
|
StarcoderdataPython
|
4848799
|
class TreeNode(object):
def __init__(self, val: str):
if val.isalnum():
self.val = val
self.children = [None]*26
class Solution(object):
def __init__(self):
self.root = TreeNode('0')
self.result = ""
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
words = list(set(words))
for word in words:
word = word.lower()
self.insert(word)
self.find_longest_word(self.root, [], words)
if len(self.result) <= 0:
return None
return self.result
def insert(self, word):
curr = self.root
for w in word:
if curr.children[ord(w) - ord('a')] is None:
tmp = TreeNode(w)
curr.children[ord(w) - ord('a')] = tmp
curr = curr.children[ord(w) - ord('a')]
def find_longest_word(self, node, curr, words):
ret = ''.join(curr)
if ret in "" or ret in words:
if len(ret) > len(self.result):
self.result = ret
for x in node.children:
if x is not None:
if ret in "" or ret in words:
curr.append(x.val)
self.find_longest_word(x, curr, words)
curr.pop()
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
s = Solution()
print(s.longestWord(words))
|
StarcoderdataPython
|
11239387
|
def test_ast_to_code():
from robotframework_interactive.ast_to_code import ast_to_code
from robot.api import get_model
code = (
"*** Settings ***\n"
"Library lib WITH NAME foo\n"
"\n"
"*** Comments ***\n"
"some comment\n"
"\n"
"*** Test Cases ***\n"
"Test\n"
" [Documentation] doc\n"
" [Tags] sometag\n"
" Pass\n"
" Keyword\n"
" One More\n"
" Multiline check1\n"
" ... check2\n"
)
model = get_model(code)
assert ast_to_code(model) == code
def test_ast_to_code_trim_lines_at_end():
from robotframework_interactive.ast_to_code import ast_to_code
from robot.api import get_model
code = (
"*** Test Cases ***\n"
"Test\n"
" Keyword Call\n"
" \n"
" \n"
" \n"
" \n"
)
expected_code = "*** Test Cases ***\n" "Test\n" " Keyword Call\n"
model = get_model(code)
assert ast_to_code(model) == expected_code
|
StarcoderdataPython
|
231709
|
<filename>crypto_app/msb_app/models/SigVarsModel.py
from sqlalchemy import ForeignKey
from .. import db
from crypto_utils.conversions import SigConversion
class SigVarsModel(db.Model):
__tablename__ = 'sigvars'
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.Integer)
u_ = db.Column(db.String)
d_ = db.Column(db.String)
s1_ = db.Column(db.String)
s2_ = db.Column(db.String)
user_id = db.Column(db.Integer, ForeignKey('users.id'))
def __init__(self, timestamp, u, d, s1, s2, user_id):
"""
:param timestamp: POSIX timestamp
:param u: Element.Integer mod q
:param d: Element.Integer mod q
:param s1: Element.Integer mod q
:param s2: Element.Integer mod q
:param user_id: integer representing the user in the CP's system database
"""
self.timestamp = timestamp
self.user_id = user_id
self.u_ = SigConversion.modint2strlist(u)
self.d_ = SigConversion.modint2strlist(d)
self.s1_ = SigConversion.modint2strlist(s1)
self.s2_ = SigConversion.modint2strlist(s2)
def __repr__(self):
return "<UserSigVars(user_id='%s', u='%s', d='%s', s1='%s', s2='%s')>" % \
(self.user_id, self.u, self.d, self.s1, self.s2)
@property
def u(self):
return SigConversion.strlist2modint(self.u_)
@property
def d(self):
return SigConversion.strlist2modint(self.d_)
@property
def s1(self):
return SigConversion.strlist2modint(self.s1_)
@property
def s2(self):
return SigConversion.strlist2modint(self.s2_)
@property
def get_timestamp(self):
return self.timestamp
def save_to_db(self):
db.session.add(self)
db.session.commit()
|
StarcoderdataPython
|
1696254
|
<reponame>domwillcode/home-assistant
"""Tests for ZHA integration init."""
import pytest
from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH
from homeassistant.components.zha.core.const import (
CONF_BAUDRATE,
CONF_RADIO_TYPE,
CONF_USB_PATH,
DOMAIN,
)
from homeassistant.const import MAJOR_VERSION, MINOR_VERSION
from homeassistant.setup import async_setup_component
from tests.async_mock import AsyncMock, patch
from tests.common import MockConfigEntry
DATA_RADIO_TYPE = "deconz"
DATA_PORT_PATH = "/dev/serial/by-id/FTDI_USB__-__Serial_Cable_12345678-if00-port0"
@pytest.fixture
def config_entry_v1(hass):
"""Config entry version 1 fixture."""
return MockConfigEntry(
domain=DOMAIN,
data={CONF_RADIO_TYPE: DATA_RADIO_TYPE, CONF_USB_PATH: DATA_PORT_PATH},
version=1,
)
@pytest.mark.parametrize("config", ({}, {DOMAIN: {}}))
@patch("homeassistant.components.zha.async_setup_entry", AsyncMock(return_value=True))
async def test_migration_from_v1_no_baudrate(hass, config_entry_v1, config):
"""Test migration of config entry from v1."""
config_entry_v1.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, config)
assert config_entry_v1.data[CONF_RADIO_TYPE] == DATA_RADIO_TYPE
assert CONF_DEVICE in config_entry_v1.data
assert config_entry_v1.data[CONF_DEVICE][CONF_DEVICE_PATH] == DATA_PORT_PATH
assert CONF_BAUDRATE not in config_entry_v1.data[CONF_DEVICE]
assert CONF_USB_PATH not in config_entry_v1.data
assert config_entry_v1.version == 2
@patch("homeassistant.components.zha.async_setup_entry", AsyncMock(return_value=True))
async def test_migration_from_v1_with_baudrate(hass, config_entry_v1):
"""Test migration of config entry from v1 with baudrate in config."""
config_entry_v1.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_BAUDRATE: 115200}})
assert config_entry_v1.data[CONF_RADIO_TYPE] == DATA_RADIO_TYPE
assert CONF_DEVICE in config_entry_v1.data
assert config_entry_v1.data[CONF_DEVICE][CONF_DEVICE_PATH] == DATA_PORT_PATH
assert CONF_USB_PATH not in config_entry_v1.data
assert CONF_BAUDRATE in config_entry_v1.data[CONF_DEVICE]
assert config_entry_v1.data[CONF_DEVICE][CONF_BAUDRATE] == 115200
assert config_entry_v1.version == 2
@patch("homeassistant.components.zha.async_setup_entry", AsyncMock(return_value=True))
async def test_migration_from_v1_wrong_baudrate(hass, config_entry_v1):
"""Test migration of config entry from v1 with wrong baudrate."""
config_entry_v1.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_BAUDRATE: 115222}})
assert config_entry_v1.data[CONF_RADIO_TYPE] == DATA_RADIO_TYPE
assert CONF_DEVICE in config_entry_v1.data
assert config_entry_v1.data[CONF_DEVICE][CONF_DEVICE_PATH] == DATA_PORT_PATH
assert CONF_USB_PATH not in config_entry_v1.data
assert CONF_BAUDRATE not in config_entry_v1.data[CONF_DEVICE]
assert config_entry_v1.version == 2
@pytest.mark.skipif(
MAJOR_VERSION != 0 or (MAJOR_VERSION == 0 and MINOR_VERSION >= 112),
reason="Not applicaable for this version",
)
@pytest.mark.parametrize(
"zha_config",
(
{},
{CONF_USB_PATH: "str"},
{CONF_RADIO_TYPE: "ezsp"},
{CONF_RADIO_TYPE: "ezsp", CONF_USB_PATH: "str"},
),
)
async def test_config_depreciation(hass, zha_config):
"""Test config option depreciation."""
await async_setup_component(hass, "persistent_notification", {})
with patch(
"homeassistant.components.zha.async_setup", return_value=True
) as setup_mock:
assert await async_setup_component(hass, DOMAIN, {DOMAIN: zha_config})
assert setup_mock.call_count == 1
|
StarcoderdataPython
|
9776619
|
<reponame>chriszhou0916/czai4art<filename>trainer/callbacks/__init__.py
from trainer.callbacks.copy_keras_models import CopyKerasModel
from trainer.callbacks.log_code import LogCode
from trainer.callbacks.generate_images import GenerateImages
from trainer.callbacks.start_tensorboard import StartTensorBoard
from trainer.callbacks.multi_modelcheckpoint import MultiModelCheckpoint
from trainer.callbacks.multi_reducelrscheduler import MultiLRScheduler
|
StarcoderdataPython
|
5106005
|
<gh_stars>0
from django.db import models
from base.models import EONBaseModel, Topic
class BlogManager(models.Manager):
"""Create descriptive filter names for easier to read view"""
def published(self):
return self.filter(published=True)
class Blog(EONBaseModel):
title = models.CharField(max_length=100)
content = models.TextField()
topics = models.ManyToManyField(Topic, related_name='blogs')
date = models.DateField()
published = models.BooleanField(default=False) # TODO Choices Yes No
objects = BlogManager()
class Meta:
ordering = ['date']
unique_together = 'title', 'date'
def __str__(self):
return '{date} - {title}; Published: {published}'.format(
date=self.date.strftime('%m/%d/%Y'),
title=self.title,
published=self.published,
)
|
StarcoderdataPython
|
9636966
|
<filename>qualtrics/client.py
"""
Qualtrics API Client
"""
# Local imports
from qualtrics.api import QualtricsAPI
from qualtrics import components
class QualtricsClient(QualtricsAPI):
"""
Ties in functionality of individual components
"""
def __init__(self, data_center, api_key):
super().__init__(data_center, api_key)
@property
def survey(self) -> components.survey.SurveyComponent:
return components.survey.SurveyComponent(self.config['data_center'],
self.config['api_key'])
|
StarcoderdataPython
|
9733943
|
<reponame>BhavyeMathur/goopylib
from goopylib.imports import *
window = Window(title="B-Spline Curve Example Program", height=600, width=600)
control_points = [[70, 350], [200, 250], [400, 470], [300, 500], [230, 450], [120, 570]]
spline_points = []
resolution = 0.1
Line(*control_points, outline=RED).draw()
for point in control_points:
Circle(point, 5, fill=RED, outline_width=0).draw()
for t in range(0, int(1 / resolution) * len(control_points)):
t *= resolution
spline_point = list(uniform_bspline(t, control_points, 2, is_open=False))
spline_points.append(Circle(spline_point, 3, outline_width=0, layer=1).draw())
Line(*map(Circle.get_anchor, spline_points), outline=CHROME_YELLOW).draw()
while window.is_open():
window.update()
|
StarcoderdataPython
|
9602765
|
# Copyright 2016 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import abc
import functools
import re
import six
from oslo_log import log as logging
from trove.common import cfg
from trove.common import exception
from trove.common.i18n import _
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta)
class ModuleDriver(object):
"""Base class that defines the contract for module drivers.
Note that you don't have to derive from this class to have a valid
driver; it is purely a convenience. Any class that adheres to the
'interface' as dictated by this class' abstractmethod decorators
(and other methods such as get_type, get_name and configure)
will work.
"""
def __init__(self):
super(ModuleDriver, self).__init__()
# This is used to store any message args to be substituted by
# the output decorator when logging/returning messages.
self._module_message_args = {}
self._message_args = None
self._generated_name = None
@property
def message_args(self):
"""Return a dict of message args that can be used to enhance
the output decorator messages. This shouldn't be overridden; use
self.message_args = <dict> instead to append values.
"""
if not self._message_args:
self._message_args = {
'name': self.get_name(),
'type': self.get_type()}
self._message_args.update(self._module_message_args)
return self._message_args
@message_args.setter
def message_args(self, values):
"""Set the message args that can be used to enhance
the output decorator messages.
"""
values = values or {}
self._module_message_args = values
self._message_args = None
@property
def generated_name(self):
if not self._generated_name:
# Turn class name into 'module type' format.
# For example: DoCustomWorkDriver -> do_custom_work
temp = re.sub('(.)[Dd]river$', r'\1', self.__class__.__name__)
temp2 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', temp)
temp3 = re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp2)
self._generated_name = temp3.lower()
return self._generated_name
def get_type(self):
"""This is used when setting up a module in Trove, and is here for
code clarity. It just returns the name of the driver by default.
"""
return self.get_name()
def get_name(self):
"""Use the generated name based on the class name. If
overridden, must be in lower-case.
"""
return self.generated_name
@abc.abstractmethod
def get_description(self):
"""Description for the driver."""
pass
@abc.abstractmethod
def get_updated(self):
"""Date the driver was last updated."""
pass
@abc.abstractmethod
def apply(self, name, datastore, ds_version, data_file, admin_module):
"""Apply the module to the guest instance. Return status and message
as a tuple. Passes in whether the module was created with 'admin'
privileges. This can be used as a form of access control by having
the driver refuse to apply a module if it wasn't created with options
that indicate that it was done by an 'admin' user.
"""
return False, "Not a concrete driver"
@abc.abstractmethod
def remove(self, name, datastore, ds_version, data_file):
"""Remove the module from the guest instance. Return
status and message as a tuple.
"""
return False, "Not a concrete driver"
def configure(self, name, datastore, ds_version, data_file):
"""Configure the driver. This is particularly useful for adding values
to message_args, by having a line such as: self.message_args = <dict>.
These values will be appended to the default ones defined
in the message_args @property.
"""
pass
def output(log_message=None, success_message=None,
fail_message=None):
"""This is a decorator to trap the typical exceptions that occur
when applying and removing modules. It returns the proper output
corresponding to the error messages automatically. If the function
returns output (success_flag, message) then those are returned,
otherwise success is assumed and the success_message returned.
Using this removes a lot of potential boiler-plate code, however
it is not necessary.
Keyword arguments can be used in the message string. Default
values can be found in the message_args @property, however a
driver can add whatever it see fit, by setting message_args
to a dict in the configure call (see above). Thus if you set
self.message_args = {'my_key': 'my_key_val'} then the message
string could look like "My key is '$(my_key)s'".
"""
success_message = success_message or "Success"
fail_message = fail_message or "Fail"
def output_decorator(func):
"""This is the actual decorator."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Here's where we handle the error messages and return values
from the actual function.
"""
log_msg = log_message
success_msg = success_message
fail_msg = fail_message
if isinstance(args[0], ModuleDriver):
# Try and insert any message args if they exist in the driver
message_args = args[0].message_args
if message_args:
try:
log_msg = log_msg % message_args
success_msg = success_msg % message_args
fail_msg = fail_msg % message_args
except Exception:
# if there's a problem, just log it and drive on
LOG.warning(_("Could not apply message args: %s") %
message_args)
pass
if log_msg:
LOG.info(log_msg)
success = False
try:
rv = func(*args, **kwargs)
if rv:
# Use the actual values, if there are some
success, message = rv
else:
success = True
message = success_msg
except exception.ProcessExecutionError as ex:
message = (_("%(msg)s: %(err)s") %
{'msg': fail_msg, 'err': ex.stderr})
LOG.exception(message)
except exception.TroveError as ex:
message = (_("%(msg)s: %(err)s") %
{'msg': fail_msg, 'err': ex._error_string})
LOG.exception(message)
except Exception as ex:
message = (_("%(msg)s: %(err)s") %
{'msg': fail_msg, 'err': ex.message})
LOG.exception(message)
return success, message
return wrapper
return output_decorator
|
StarcoderdataPython
|
5171753
|
import numpy as np
from flaml import AutoML
def test_forecast_automl(budget=5):
# using dataframe
import statsmodels.api as sm
data = sm.datasets.co2.load_pandas().data['co2'].resample('MS').mean()
data = data.fillna(data.bfill()).to_frame().reset_index().rename(
columns={'index': 'ds', 'co2': 'y'})
num_samples = data.shape[0]
time_horizon = 12
split_idx = num_samples - time_horizon
df = data[:split_idx]
X_test = data[split_idx:]['ds']
y_test = data[split_idx:]['y']
automl = AutoML()
settings = {
"time_budget": budget, # total running time in seconds
"metric": 'mape', # primary metric
"task": 'forecast', # task type
"log_file_name": 'CO2_forecast.log', # flaml log file
"eval_method": "holdout",
"label": ('ds', 'y'),
}
'''The main flaml automl API'''
try:
automl.fit(dataframe=df, **settings, period=time_horizon)
except ImportError:
print("not using FBProphet due to ImportError")
automl.fit(dataframe=df, **settings, estimator_list=[
'arima', 'sarimax'], period=time_horizon)
''' retrieve best config and best learner'''
print('Best ML leaner:', automl.best_estimator)
print('Best hyperparmeter config:', automl.best_config)
print(f'Best mape on validation data: {automl.best_loss}')
print(f'Training duration of best run: {automl.best_config_train_time}s')
print(automl.model.estimator)
''' pickle and save the automl object '''
import pickle
with open('automl.pkl', 'wb') as f:
pickle.dump(automl, f, pickle.HIGHEST_PROTOCOL)
''' compute predictions of testing dataset '''
y_pred = automl.predict(X_test)
print('Predicted labels', y_pred)
print('True labels', y_test)
''' compute different metric values on testing dataset'''
from flaml.ml import sklearn_metric_loss_score
print('mape', '=', sklearn_metric_loss_score('mape', y_pred, y_test))
from flaml.data import get_output_from_log
time_history, best_valid_loss_history, valid_loss_history, config_history, metric_history = \
get_output_from_log(filename=settings['log_file_name'], time_budget=budget)
for config in config_history:
print(config)
print(automl.prune_attr)
print(automl.max_resource)
print(automl.min_resource)
X_train = df['ds']
y_train = df['y']
automl = AutoML()
try:
automl.fit(X_train=X_train, y_train=y_train, **settings, period=time_horizon)
except ImportError:
print("not using FBProphet due to ImportError")
automl.fit(X_train=X_train, y_train=y_train, **settings, estimator_list=[
'arima', 'sarimax'], period=time_horizon)
def test_numpy():
X_train = np.arange('2014-01', '2021-01', dtype='datetime64[M]')
y_train = np.random.random(size=72)
automl = AutoML()
try:
automl.fit(
X_train=X_train[:60], # a single column of timestamp
y_train=y_train, # value for each timestamp
period=12, # time horizon to forecast, e.g., 12 months
task='forecast', time_budget=3, # time budget in seconds
log_file_name="test/forecast.log")
print(automl.predict(X_train[60:]))
print(automl.predict(12))
except ValueError:
print("ValueError for FBProphet is raised as expected.")
except ImportError:
print("not using FBProphet due to ImportError")
automl = AutoML()
automl.fit(
X_train=X_train[:72], # a single column of timestamp
y_train=y_train, # value for each timestamp
period=12, # time horizon to forecast, e.g., 12 months
task='forecast', time_budget=1, # time budget in seconds
estimator_list=['arima', 'sarimax'],
log_file_name="test/forecast.log")
print(automl.predict(X_train[72:]))
# an alternative way to specify predict steps for arima/sarimax
print(automl.predict(12))
if __name__ == "__main__":
test_forecast_automl(60)
|
StarcoderdataPython
|
79030
|
<filename>templates/commonfilters.py
import re
import pandocfilters as pf
def lb(s):
return pf.RawBlock('latex', s)
def li(s):
return pf.RawInline('latex', s)
def fig(name, props, anim):
return li('\\includegraphics%s[%s]{%s}\n' %
('<' + anim + '>' if len(anim) > 0 else '', props, name))
def latexstringify(x):
result = []
def go(key, val, format, meta):
if key == 'Str':
result.append(val)
elif key == 'Code':
result.append(val[1])
elif key == 'Math':
result.append('$' + val[1] + '$')
elif key == 'LineBreak':
result.append(" ")
elif key == 'Space':
result.append(" ")
elif key == 'RawInline' and val[0] == 'tex':
result.append(val[1])
pf.walk(x, go, "", {})
return ''.join(result).replace('%', '\\%')
# Supported syntax:
# : figures
#
# *: starred figure environment (normally spans 2 columns)
# <anim>: beamer animation specification
# <option>: latex figure options, use the shortcuts `h` (horizontal fill),
# `v` (vertical fill), `f` (fill) and `s` (slide fill) to do the Right Thing
#
# If multiple animation/option settings are defined next to the caption,
# they get spread across the figures. Paragraphs that only consist of
# figures with the same caption get collapsed into one float.
#
# Examples:
# ![]{figure}: basic figure, no float
# ![caption]{figure}: basic figure, put into a float
# ![*caption]{figure}: basic figure, put into a column-spanning float
# ![{options}caption]{figure}: basic figure in float, custom options
# ![{options}caption]{figure1,figure2}: two figures in one float, custom options for all
# ![{options1}{options2}caption]{figure1,figure2}: two figures in one float, custom options per figure
# ![caption]{{options1}figure1,{options2}figure2}: two figures in one float, custom options per figure
# ![<1><2>caption]{figure1,figure2}: two figures in one float, with animation
# ![<1><2>caption]{figure1}![<1><2>caption]{figure2}: two figures with same caption in one paragraph get collapsed into one float
class HeaderWatcher:
def __init__(self):
self._sections = []
def update(self, k, v, f, m):
if k == 'Header':
unnumbered = pf.Header(v[0], ('', ['unnumbered'], []), v[2])
if v[0] == 1:
self._sections = [unnumbered]
elif v[0] == 2:
self._sections = [self._sections[0], unnumbered]
def betweenframes(self, s):
return self._sections + [s]
class ImageWalker:
def __init__(self):
self._watcher = HeaderWatcher()
def filter(self, k, v, f, m):
self._watcher.update(k, v, f, m)
if k == 'Image' and v[1][1] == 'fig:':
return Image(v, f, m).render(self._watcher, True)
if k == 'Para' and all(vv['t'] in ['Image', 'Space'] for vv in v):
images = [Image(vv['c'], f, m) for vv in v if vv['t'] == 'Image']
if len(images) > 0 and images[0].merge(images[1:]):
return images[0].render(self._watcher, False)
class Image:
def __init__(self, v, f, m):
if len(v) > 2: # pandoc >=1.16
v = v[1:]
self._figtype = 'figure'
self._rawcaption = latexstringify(v[0])
self._caption = ''
self._captionanims = []
self._captionoptions = []
self._anims = []
self._options = []
self._filenames = []
self._parse_caption(self._rawcaption)
self._parse_filenames(v[1][0].replace('%20', ' '))
self._anims = self._spread(self._captionanims, self._anims)
self._options = self._spread(self._captionoptions, self._options)
def render(self, watcher, inline):
result = []
betweenframes = False
for i, f in enumerate(self._filenames):
anim = self._anims[i]
[options, slide] = self._mangleoptions(self._options[i])
if slide:
result.append(li('\\slidefig{%s}{%s}' % ('<' + anim + '>' if len(anim) > 0 else '', f)))
betweenframes = True
continue
if i == 0 and len(self._caption) > 0:
result.append(li('\\begin{%s}\n' % self._figtype))
if i == 0 and len(self._caption) == 0 and not inline:
result.append(li('{\\centering'))
result.append(fig(f, options, anim))
if i + 1 == len(self._filenames) and len(self._caption) > 0:
result.extend([li('\\caption{'), li(self._caption), li('}\n')])
result.append(li('\\end{%s}' % self._figtype))
if i + 1 == len(self._filenames) and len(self._caption) == 0 and not inline:
result.append(li('\par}'))
if inline:
if betweenframes:
return pf.Str('Unable to return paragraph when in inline mode')
return result
result = pf.Para(result)
return watcher.betweenframes(result) if betweenframes else result
''' Merge consecutive images with the same caption, recalculate anims and options '''
def merge(self, others):
if any(self._rawcaption != o._rawcaption for o in others):
return False
for o in others:
self._anims.extend(o._anims)
self._options.extend(o._options)
self._filenames.extend(o._filenames)
self._anims = self._spread(self._captionanims, self._anims)
self._options = self._spread(self._captionoptions, self._options)
return True
def _spread(self, tospread, pattern):
if len(tospread) == 0:
return pattern
if len(tospread) == 1:
return [tospread[0]] * len(pattern)
return [tospread[i] if i < len(tospread) else p for i, p in enumerate(pattern)]
def _mangleoptions(self, o):
[o, slide] = re.subn(r'(^|,)s($|,)', '', o)
o = re.sub(r'(^|,)h($|,)', r'\1width=\\textwidth\2', o)
o = re.sub(r'(^|,)v($|,)', r'\1height=0.72\\textheight\2', o)
o = re.sub(r'(^|,)f($|,)', r'\1width=\\textwidth,height=0.72\\textheight,keepaspectratio\2', o)
return [o, slide > 0]
def _parse_caption(self, v):
pos = 0
l = len(v)
while pos < l:
[pos] = self._parse_captionpart(v, pos, l)
def _parse_captionpart(self, v, pos, l):
if pos < l and v[pos] == '*':
self._figtype = 'figure*'
return [pos + 1] # +1 because of *
if pos < l and v[pos] == '<':
[pos, anim] = self._parse_anim(v, pos + 1, l) # +1 because of initial <
self._captionanims.append(anim)
return [pos]
if pos < l and v[pos] == '{':
[pos, option] = self._parse_option(v, pos + 1, l) # +1 because of initial {
self._captionoptions.append(option)
return [pos]
self._caption = v[pos:]
return [l]
def _parse_filenames(self, v):
pos = 0
l = len(v)
while pos < l:
[pos] = self._parse_filename(v, pos, l)
def _parse_filename(self, v, pos, l):
if pos < l and v[pos] == '<':
[pos, anim] = self._parse_anim(v, pos + 1, l) # +1 because of initial <
else:
anim = ''
if pos < l and v[pos] == '{':
[pos, option] = self._parse_option(v, pos + 1, l) # +1 because of initial {
else:
option = ''
[pos, name] = self._parse_name(v, pos, l)
self._anims.append(anim)
self._options.append(option)
self._filenames.append(name)
return [pos + 1] # +1 because of comma between items
def _parse_anim(self, v, pos, l):
startpos = pos
while pos < l and v[pos] != '>':
pos = pos + 1
return [pos + 1, v[startpos:pos]] # +1 because of closing >
def _parse_option(self, v, pos, l):
startpos = pos
braces = 0
while pos < l and (v[pos] != '}' or braces > 0):
if v[pos] == '{':
braces = braces + 1
elif v[pos] == '}':
braces = braces - 1
pos = pos + 1
return [pos + 1, v[startpos:pos]] # +1 because of closing }
def _parse_name(self, v, pos, l):
startpos = pos
while pos < l and v[pos] != ',':
pos = pos + 1
return [pos, v[startpos:pos]]
|
StarcoderdataPython
|
1945783
|
<filename>7day/UL2/01_naver_home/02_naver_adjust_bs4.py
import urllib.request
import bs4
url = "https://www.naver.com/"
html = urllib.request.urlopen(url)
bs_obj = bs4.BeautifulSoup(html, "html.parser")
print(bs_obj)
|
StarcoderdataPython
|
8094969
|
# Copyright (c) 2020 - present <NAME> <https://github.com/VitorOriel>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from ..utils.consts import *
def checkForSubdomainFuzz(url: str) -> bool:
"""Checks if the fuzzing tests will occur on subdomain
@type url: str
@param url: The target URL
@returns bool: The subdomain fuzzing flag
"""
if ('.' in url and FUZZING_MARK in url) and url.index(FUZZING_MARK) < url.index('.'):
return True
return False
class RequestParser:
"""Class that handle with request arguments parsing
Attributes:
payload: The payload used in the request
"""
def __init__(self):
self.__payload = ''
def getMethod(self, method: dict) -> str:
"""The new method getter
@type method: dict
@param method: The method dictionary
@returns str: The new target method
"""
return method['content'] if not method['fuzzingIndexes'] else self.__getAjustedContentByIndexes(method)
def getUrl(self, url: dict) -> str:
"""The new url getter
@type url: dict
@param url: The URL dictionary
@returns str: The new target URL
"""
return url['content'] if not url['fuzzingIndexes'] else self.__getAjustedContentByIndexes(url)
def getHeader(self, headers: dict) -> dict:
"""The new HTTP Header getter
@type httpHeder: dict
@param headers: The HTTP Header
@returns dict: The new HTTP Header
"""
return headers['content'] if not headers['payloadKeys'] else self.__getAjustedHeader(headers)
def getData(self, data: dict) -> dict:
"""The new data getter
@type data: dict
@param data: The request parameters
@returns dict: The new request parameters
"""
return {
'PARAM': {} if not data['PARAM'] else self.__getAjustedData(data['PARAM']),
'BODY': {} if not data['BODY'] else self.__getAjustedData(data['BODY'])
}
def setPayload(self, payload: str) -> None:
"""The payload setter
@type payload: str
@param payload: The payload used in the request
"""
self.__payload = payload
def __getAjustedContentByIndexes(self, content: dict) -> str:
"""Put the payload into the given content
@type content: dict
@param content: The target content dictionary
@returns str: The new content
"""
ajustedContent = content['content']
for i in content['fuzzingIndexes']:
head = ajustedContent[:i]
tail = ajustedContent[(i+1):]
ajustedContent = head + self.__payload + tail
return ajustedContent
def __getAjustedHeader(self, header: dict) -> dict:
"""Put the payload in the header value that contains the fuzzing mark
@type header: dict
@param header: The HTTP Header dictionary
@returns dict: The new HTTP Header
"""
ajustedHeader = {}
for key, value in header['content'].items():
ajustedHeader[key] = value
for key in header['payloadKeys']:
result = ''
value = ajustedHeader[key]
for i in range(len(value)-1):
result += value[i] + self.__payload
result += value[-1]
ajustedHeader[key] = result.encode('utf-8')
return ajustedHeader
def __getAjustedData(self, data: dict) -> dict:
"""Put the payload into the Data requestParameters dictionary
@type data: dict
@param dara: The request parameters
@returns dict: The new request parameters
"""
ajustedData = {}
for key, value in data.items():
if value:
ajustedData[key] = value
else:
ajustedData[key] = self.__payload
return ajustedData
requestParser = RequestParser()
|
StarcoderdataPython
|
1856463
|
import abjad
from presentation import *
import abjadext.rmakers
rmakers = abjadext.rmakers
def rotate(l, n):
return l[-n:] + l[:-n]
### PRE ###
def show_demo():
divisions = [(3, 8), (5, 4), (1, 4), (13, 16)]
score = abjad.Score()
counts = [1, 2, 3]
selector = abjad.select().tuplets()[:-1]
selector = selector.map(abjad.select().note(-1))
for i in range(12):
my_talea = rmakers.talea(
counts, # counts
16, # denominator
extra_counts=[0, 1, 1]
)
voice = abjad.Voice()
talea_rhythm_maker = rmakers.stack(
my_talea,
rmakers.force_rest(abjad.select().logical_ties().get([0, -1]),),# Silences first and last logical ties.
#rmakers.tie(selector), # Ties across divisions.
rmakers.beam(),
rmakers.extract_trivial(),
rmakers.rewrite_meter(),
)
selections = talea_rhythm_maker(divisions)
voice.append(selections)
staff = abjad.Staff(lilypond_type='RhythmicStaff', name=str(i))
staff.append(voice)
score.append(staff)
divisions = rotate(divisions, 1)
counts = rotate(counts, 1)
lilypond_file = make_sketch_lilypond_file(score)
abjad.show(lilypond_file)
#show_demo()
### EXAMPLE ONE ###
note_rhythm_maker = rmakers.stack(rmakers.note(),) # abjadext.rmakers is implicit: rmakers = abjadext.rmakers
divisions = [(3, 8), (5, 4), (1, 4), (13, 16)]
selections = note_rhythm_maker(divisions)
staff = abjad.Staff(selections, lilypond_type='RhythmicStaff')
sketch = make_sketch(selections, divisions)
#abjad.show(sketch)
divisions_b = [(5, 16), (3, 8), (3, 8), (5, 8), (1, 4)]
sketch = make_sketch(selections, divisions_b)
#abjad.show(sketch)
divisions_b *= 20
selections = note_rhythm_maker(divisions_b)
sketch = make_sketch(selections, divisions_b)
#abjad.show(sketch)
import random
random_numerators = [random.randrange(1, 16 + 1) for x in range(100)]
random_divisions = [(x, 32) for x in random_numerators]
selections = note_rhythm_maker(random_divisions)
sketch = make_sketch(selections, random_divisions)
#abjad.show(sketch)
### EXAMPLE TWO ###
### INITIAL TALEA RHYTHM-MAKER
my_talea = rmakers.talea(
[1, 2, 3], # counts
16, # denominator
)
talea_rhythm_maker = rmakers.stack(
my_talea, rmakers.beam(), rmakers.extract_trivial(),
)
#You can see that the Talea creates a cycle of durations:
#for i in range(20):
#print(i, my_talea[i])
#Next, we give this Talea to a stack:
talea_rhythm_maker = rmakers.stack(
my_talea,
rmakers.beam(),
rmakers.extract_trivial(),
)
selections = talea_rhythm_maker(divisions)
sketch = make_sketch(selections, divisions)
#abjad.show(sketch)
### SPECIFIERS
selector = abjad.select().tuplets()[:-1]
selector = selector.map(abjad.select().note(-1))
talea_rhythm_maker = rmakers.stack(
my_talea,
rmakers.beam(),
rmakers.extract_trivial(),
rmakers.tie(selector), # Ties across divisions.
)
my_talea = rmakers.talea(
[1, 2, 3], # counts
16, # denominator
extra_counts=[0, 1, 1]
)
selector = abjad.select().tuplets()[:-1]
selector = selector.map(abjad.select().note(-1))
talea_rhythm_maker = rmakers.stack(
my_talea,
rmakers.force_rest(abjad.select().logical_ties().get([0, -1]),),# Silences first and last logical ties.
rmakers.beam(),
rmakers.extract_trivial(),
rmakers.rewrite_meter(),
rmakers.tie(selector), # Ties across divisions.
)
selections = talea_rhythm_maker(divisions)
sketch = make_sketch(selections, divisions)
#abjad.show(sketch)
### EXAMPLE THREE ###
score = abjad.Score()
def rotate(l, n):
return l[-n:] + l[:-n]
counts = [1, 2, 3]
selector = abjad.select().tuplets()[:-1]
selector = selector.map(abjad.select().note(-1))
for i in range(12):
my_talea = rmakers.talea(
counts, # counts
16, # denominator
extra_counts=[0, 1, 1]
)
voice = abjad.Voice()
talea_rhythm_maker = rmakers.stack(
my_talea,
rmakers.force_rest(abjad.select().logical_ties().get([0, -1]),),# Silences first and last logical ties.
#rmakers.tie(selector), # Ties across divisions.
rmakers.beam(),
rmakers.extract_trivial(),
rmakers.rewrite_meter(),
)
selections = talea_rhythm_maker(divisions)
voice.append(selections)
staff = abjad.Staff(lilypond_type='RhythmicStaff', name=str(i))
staff.append(voice)
score.append(staff)
divisions = rotate(divisions, 1)
counts = rotate(counts, 1)
sketch = make_sketch_lilypond_file(score)
#abjad.show(sketch)
|
StarcoderdataPython
|
12842004
|
<filename>app/user/tests/test_user_api.py
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse('user:me')
def create_user(**params):
return get_user_model().objects.create_user(**params)
# endpoints that do not require authentication
class PublicUserApiTests(TestCase):
"""Test the users API (public)"""
def setUp(self):
self.client = APIClient()
def test_create_valid_user_success(self):
"""Test creating user with valid payload is successful"""
payload = {
'email': '<EMAIL>',
'password': '<PASSWORD>',
'name': 'Example User'
}
response = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
user = get_user_model().objects.get(**response.data)
self.assertTrue(user.check_password(payload['password']))
# making sure password is never returned in the response
self.assertNotIn('password', response.data)
def test_user_exists(self):
"""Test creating an user that already exists fails"""
payload = {
'email': '<EMAIL>',
'password': '<PASSWORD>',
'name': 'Example User'
}
create_user(**payload)
response = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_password_too_short(self):
"""Test that the passwordm u be more than 5 characters."""
payload = {
'email': '<EMAIL>',
'password': '<PASSWORD>',
'name': 'Example User'
}
response = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
user_exists = get_user_model().objects.filter(email=payload['email']).exists()
self.assertFalse(user_exists)
def test_create_token_for_user(self):
payload = {
'email': '<EMAIL>',
'password': '<PASSWORD>',
'name': 'Example User'
}
create_user(**payload)
response = self.client.post(TOKEN_URL, payload)
self.assertIn('token', response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_create_token_invalid_credentials(self):
"""Token is not created if invalid credentials are passed."""
payload = {
'email': '<EMAIL>',
'password': '<PASSWORD>',
'name': 'Example User'
}
create_user(**payload)
payload['password'] = '<PASSWORD>'
response = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', response.data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_token_no_user(self):
"""Test that token is not created if user does not exist."""
response = self.client.post(TOKEN_URL, {'email': 'w', 'password': 'w'})
self.assertNotIn('token', response.data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
class PrivateUserApiTests(TestCase):
def setUp(self):
self.user = create_user(
email='<EMAIL>',
password='<PASSWORD>',
name='Example User'
)
self.client = APIClient()
self.client.force_authenticate(user=self.user)
def test_retrieve_user_profile_unauthorized(self):
"""Test that authentication is required for users."""
self.client.force_authenticate(user=None, token=None)
response = self.client.get(ME_URL)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_retrieve_user_profile_success(self):
"""Test retrieving user profile for logged in users."""
response = self.client.get(ME_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, {
'name': self.user.name,
'email': self.user.email
})
def test_post_me_not_allowed(self):
"""Test that POST is not allowed on me url."""
response = self.client.post(ME_URL)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
|
StarcoderdataPython
|
207005
|
from arm.logicnode.arm_nodes import *
class RandomColorNode(ArmLogicTreeNode):
"""Generates a random color."""
bl_idname = 'LNRandomColorNode'
bl_label = 'Random Color'
arm_version = 1
def init(self, context):
super(RandomColorNode, self).init(context)
self.add_output('NodeSocketColor', 'Color')
|
StarcoderdataPython
|
4907431
|
<gh_stars>0
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pva
import numpy as np
import test_utils as tu
from tensorflow.compiler.tests import xla_test
from tensorflow.python.compiler.xla import xla
from tensorflow.python.platform import googletest
from tensorflow.python.framework import ops
from tensorflow.python.ipu.config import IPUConfig
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import nn
class UpdateOpDependenciesTest(xla_test.XLATestCase):
def testDontOutlineInplaceExpression(self):
cfg = IPUConfig()
report_helper = tu.ReportHelper()
report_helper.set_autoreport_options(cfg)
cfg.ipu_model.compile_ipu_code = False
cfg.configure_ipu_system()
with self.session() as sess:
with ops.device("/device:IPU:0"):
pa = array_ops.placeholder(np.float32, [])
pb = array_ops.placeholder(np.float32, [])
pc = array_ops.placeholder(np.float32, [])
pd = array_ops.placeholder(np.float32, [])
e = pa + pb - pc + pd
fd = {pa: 1, pb: 2, pc: 3, pd: 4}
result = sess.run(e, fd)
self.assertAllClose(result, 4)
self.assert_num_reports(report_helper, 0)
def tesInplaceAddCopyWithInplacePeer(self):
cfg = IPUConfig()
report_helper = tu.ReportHelper()
report_helper.set_autoreport_options(cfg)
cfg.ipu_model.compile_ipu_code = False
cfg.configure_ipu_system()
with self.session() as sess:
data_a = np.array([[10, -20], [5, 1]])
data_b = np.array([[-12, 11], [12, -13]])
with ops.device("/device:IPU:0"):
pa = array_ops.placeholder(np.float32, [2, 2])
pb = array_ops.placeholder(np.float32, [2, 2])
c = array_ops.transpose(pa)
d = pa + pb
e = c / d
fd = {
pa: data_a,
pb: data_b,
}
result = sess.run(e, fd)
np_result = np.transpose(data_a) / (data_a + data_b)
self.assertAllClose(result, np_result)
report = pva.openReport(report_helper.find_report())
ok = [
'__seed*', 'host-exchange-local-copy-',
'Copy_XLA_Args/arg0.*_to_transpose/transpose', 'add/add.*/AddTo',
'truediv/divide.*/Op/Divide'
]
self.assert_all_compute_sets_and_list(report, ok)
def tesInplaceAddCopyWithInplacePeer2(self):
cfg = IPUConfig()
report_helper = tu.ReportHelper()
report_helper.set_autoreport_options(cfg)
cfg.ipu_model.compile_ipu_code = False
cfg.configure_ipu_system()
with self.session() as sess:
data_a = np.array([[10, -10], [-5, 5]])
data_b = np.array([[-15, 15], [25, -25]])
data_c = 2
with ops.device("/device:IPU:0"):
pa = array_ops.placeholder(np.float32, [2, 2])
pb = array_ops.placeholder(np.float32, [2, 2])
pc = array_ops.placeholder(np.float32, [])
a = array_ops.transpose(pa)
b = pa + pb * pc
c = a * pb + pc
d = b / c
fd = {
pa: data_a,
pb: data_b,
pc: data_c,
}
np_result = (data_a + data_b * data_c) / (np.transpose(data_a) * data_b +
data_c)
result = sess.run(d, fd)
self.assertAllClose(result, np_result)
report = pva.openReport(report_helper.find_report())
ok = [
'__seed*', 'Copy_XLA_Args/arg0.*_to_transpose/transpose'
'mul/multiply.*/Op/Multiply', 'add/add.*/AddTo',
'mul_1/multiply.*/Op/Multiply', 'add_1/add.*/AddTo',
'truediv/divide.*/Op/Divide'
]
self.assert_all_compute_sets_and_list(report, ok)
def testInplaceOpAddCopyWithInplaceParent(self):
cfg = IPUConfig()
report_helper = tu.ReportHelper()
report_helper.set_autoreport_options(cfg)
cfg.ipu_model.compile_ipu_code = False
cfg.configure_ipu_system()
with self.session() as sess:
with ops.device("/device:IPU:0"):
pa = array_ops.placeholder(np.float32, [3])
pb = array_ops.placeholder(np.float32, [3])
pc = array_ops.placeholder(np.float32, [])
c = array_ops.slice(pa, [0], [2])
d = array_ops.slice(pb, [0], [2])
e = c + d
f = e / pc
g = array_ops.slice(pa, [1], [2])
h = f + g
fd = {
pa: [1, 2, 3],
pb: [5, 6, 7],
pc: 2,
}
result = sess.run(h, fd)
self.assertAllClose(result, [5, 7])
report = pva.openReport(report_helper.find_report())
ok = [
'__seed*', 'truediv/*/expression/Op/Add',
'truediv/*/expression/Op/Divide', 'add_1/add.*/Add',
'host-exchange-local-copy'
]
self.assert_all_compute_sets_and_list(report, ok)
def testInplaceTuple(self):
cfg = IPUConfig()
report_helper = tu.ReportHelper()
report_helper.set_autoreport_options(cfg)
cfg.ipu_model.compile_ipu_code = False
cfg.configure_ipu_system()
with self.session() as sess:
def my_net(x):
def cond(i, x, y):
del x
del y
return i < 1
def body(i, x, y):
i = i + 1
x = nn.tanh(x)
y = nn.tanh(y)
return (i, x, y)
i = 0
return control_flow_ops.while_loop(cond, body, (i, x, x), name='')[1:]
with ops.device('cpu'):
x = array_ops.placeholder(np.float32, [4])
with ops.device("/device:IPU:0"):
r = xla.compile(my_net, inputs=[x])
x, y = sess.run(r, {x: np.full([4], 2)})
self.assertAllClose(x, np.full([4], np.tanh(2)))
self.assertAllClose(y, np.full([4], np.tanh(2)))
report = pva.openReport(report_helper.find_report())
ok = [
'__seed*', 'Copy_*_to_*', 'Tanh/tanh*/Op/Tanh', 'Tanh_1/tanh*/Op/Tanh'
]
self.assert_all_compute_sets_and_list(report, ok)
if __name__ == "__main__":
os.environ['TF_XLA_FLAGS'] = ('--tf_xla_min_cluster_size=1 ' +
os.environ.get('TF_XLA_FLAGS', ''))
googletest.main()
|
StarcoderdataPython
|
325819
|
# Developed by Redjumpman for Redbot.
# Inspired by Spriter's work on a modded economy.
# Creates 1 json file, 1 log file per 10mb, and requires tabulate.
# STD Library
import asyncio
import gettext
import logging
import logging.handlers
import os
import random
from copy import deepcopy
from fractions import Fraction
from operator import itemgetter
from datetime import datetime, timedelta
# Discord imports
import discord
from .utils import checks
from .utils.dataIO import dataIO
from discord.ext import commands
from __main__ import send_cmd_help
# Third Party Libraries
from tabulate import tabulate
from dateutil import parser
try:
l_path = "data/JumperCogs/casino/data/languages.json"
lang_data = dataIO.load_json(l_path)
lang_default = lang_data["Language"]
language_set = gettext.translation('casino', localedir='data/JumperCogs/casino/data',
languages=[lang_default])
language_set.install()
except FileNotFoundError:
_ = lambda s: s
# Default settings that is created when a server begin's using Casino
server_default = {"System Config": {"Casino Name": "Redjumpman", "Casino Open": True,
"Chip Name": "Jump", "Chip Rate": 1, "Default Payday": 100,
"Payday Timer": 1200, "Threshold Switch": False,
"Threshold": 10000, "Credit Rate": 1, "Transfer Limit": 1000,
"Transfer Cooldown": 30, "Version": 1.715
},
"Memberships": {},
"Players": {},
"Games": {"Dice": {"Multiplier": 2.2, "Cooldown": 5, "Open": True, "Min": 50,
"Max": 500, "Access Level": 0},
"Coin": {"Multiplier": 1.5, "Cooldown": 5, "Open": True, "Min": 10,
"Max": 10, "Access Level": 0},
"Cups": {"Multiplier": 2.2, "Cooldown": 5, "Open": True, "Min": 50,
"Max": 500, "Access Level": 0},
"Blackjack": {"Multiplier": 2.2, "Cooldown": 5, "Open": True,
"Min": 50, "Max": 500, "Access Level": 0},
"Allin": {"Multiplier": 2.2, "Cooldown": 43200, "Open": True,
"Access Level": 0},
"Hi-Lo": {"Multiplier": 1.5, "Cooldown": 5, "Open": True,
"Min": 20, "Max": 20, "Access Level": 0},
"War": {"Multiplier": 1.5, "Cooldown": 5, "Open": True,
"Min": 20, "Max": 20, "Access Level": 0},
}
}
new_user = {"Chips": 100,
"Membership": None,
"Pending": 0,
"Played": {"Dice Played": 0, "Cups Played": 0, "BJ Played": 0, "Coin Played": 0,
"Allin Played": 0, "Hi-Lo Played": 0, "War Played": 0},
"Won": {"Dice Won": 0, "Cups Won": 0, "BJ Won": 0, "Coin Won": 0, "Allin Won": 0,
"Hi-Lo Won": 0, "War Won": 0},
"Cooldowns": {"Dice": 0, "Cups": 0, "Coin": 0, "Allin": 0, "Hi-Lo": 0, "War": 0,
"Blackjack": 0, "Payday": 0, "Transfer": 0}
}
# Deck used for blackjack, and a dictionary to correspond values of the cards.
main_deck = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] * 4
bj_values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 10,
'Queen': 10, 'King': 10}
war_values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 11,
'Queen': 12, 'King': 13, 'Ace': 14}
c_games = ["Blackjack", "Coin", "Allin", "Cups", "Dice", "Hi-Lo", "War"]
class CasinoError(Exception):
pass
class UserAlreadyRegistered(CasinoError):
pass
class UserNotRegistered(CasinoError):
pass
class InsufficientChips(CasinoError):
pass
class NegativeChips(CasinoError):
pass
class SameSenderAndReceiver(CasinoError):
pass
class BotNotAUser(CasinoError):
pass
class CasinoBank:
"""Holds all of the Casino hooks for integration"""
def __init__(self, bot, file_path):
self.memberships = dataIO.load_json(file_path)
self.bot = bot
self.patch = 1.715
def create_account(self, user):
server = user.server
path = self.check_server_settings(server)
if user.id not in path["Players"]:
default_user = deepcopy(new_user)
path["Players"][user.id] = default_user
path["Players"][user.id]["Name"] = user.name
self.save_system()
membership = path["Players"][user.id]
return membership
else:
raise UserAlreadyRegistered()
def membership_exists(self, user):
try:
self.get_membership(user)
except UserNotRegistered:
return False
return True
def chip_balance(self, user):
account = self.get_membership(user)
return account["Chips"]
def can_bet(self, user, amount):
account = self.get_membership(user)
if account["Chips"] >= amount:
return True
else:
raise InsufficientChips()
def set_chips(self, user, amount):
if amount < 0:
raise NegativeChips()
account = self.get_membership(user)
account["Chips"] = amount
self.save_system()
def deposit_chips(self, user, amount):
amount = int(round(amount))
if amount < 0:
raise NegativeChips()
account = self.get_membership(user)
account["Chips"] += amount
self.save_system()
def withdraw_chips(self, user, amount):
if amount < 0:
raise NegativeChips()
account = self.get_membership(user)
if account["Chips"] >= amount:
account["Chips"] -= amount
self.save_system()
else:
raise InsufficientChips()
def transfer_chips(self, sender, receiver, amount):
if amount < 0:
raise NegativeChips()
if sender is receiver:
raise SameSenderAndReceiver()
if receiver == self.bot.user:
raise BotNotAUser()
if self.membership_exists(sender) and self.membership_exists(receiver):
sender_acc = self.get_membership(sender)
if sender_acc["Chips"] < amount:
raise InsufficientChips()
self.withdraw_chips(sender, amount)
self.deposit_chips(receiver, amount)
else:
raise UserNotRegistered()
def wipe_caisno_server(self, server):
self.memberships["Servers"].pop(server.id)
self.save_system()
def wipe_casino_members(self, server):
self.memberships["Servers"][server.id]["Players"] = {}
self.save_system()
def remove_membership(self, user):
server = user.server
self.memberships["Servers"][server.id]["Players"].pop(user.id)
self.save_system()
def get_membership(self, user):
server = user.server
path = self.check_server_settings(server)
try:
return path["Players"][user.id]
except KeyError:
raise UserNotRegistered()
def get_all_servers(self):
return self.memberships["Servers"]
def get_casino_server(self, server):
return self.memberships["Servers"][server.id]
def get_server_memberships(self, server):
if server.id in self.memberships["Servers"]:
members = self.memberships["Servers"][server.id]["Players"]
return members
else:
return []
def save_system(self):
dataIO.save_json("data/JumperCogs/casino/casino.json", self.memberships)
def check_server_settings(self, server):
if server.id not in self.memberships["Servers"]:
self.memberships["Servers"][server.id] = server_default
self.save_system()
print(_("Creating default casino settings for Server: {}").format(server.name))
path = self.memberships["Servers"][server.id]
return path
else:
path = self.memberships["Servers"][server.id]
try:
if path["System Config"]["Version"] < self.patch:
self.casino_patcher(path)
path["System Config"]["Version"] = self.patch
except KeyError:
path["System Config"]["Version"] = self.patch
self.casino_patcher(path)
return path
def casino_patcher(self, path):
if path["System Config"]["Version"] < 1.706:
self.patch_1581(path)
self.patch_1692(path)
self.patch_1694(path)
self.patch_16(path)
if path["System Config"]["Version"] < 1.712:
self.patch_1712(path)
if path["System Config"]["Version"] < 1.715:
self.patch_1715(path)
# Save changes and return updated dictionary.
self.save_system()
def name_fix(self):
servers = self.get_all_servers()
removal = []
for server in servers:
try:
server_obj = self.bot.get_server(server)
self.name_bug_fix(server_obj)
except AttributeError:
removal.append(server)
logger.info("WIPED SERVER: {} FROM CASINO".format(server))
print(_("Removed server ID: {} from the list of servers, because the bot is no "
"longer on that server.").format(server))
for x in removal:
self.memberships["Servers"].pop(x)
self.save_system()
def name_bug_fix(self, server):
players = self.get_server_memberships(server)
for player in players:
mobj = server.get_member(player)
try:
# noinspection PyTypeChecker
if mobj.name != players[player]["Name"]:
players[player]["Name"] = mobj.name
except AttributeError:
print(_("Error updating name! {} is no longer on this server.").format(player))
def patch_games(self, path):
# Check if player data has the war game, and if not add it.
for player in path["Players"]:
if "War Played" not in path["Players"][player]["Played"]:
path["Players"][player]["Played"]["War Played"] = 0
if "War Won" not in path["Players"][player]["Won"]:
path["Players"][player]["Won"]["War Won"] = 0
if "War" not in path["Players"][player]["Cooldowns"]:
path["Players"][player]["Cooldowns"]["War"] = 0
self.save_system()
def patch_1715(self, path):
"""Fix transfer issues"""
for player in path["Players"]:
path["Players"][player]["Cooldowns"] = {}
path["Players"][player]["Cooldowns"]["Allin"] = 0
path["Players"][player]["Cooldowns"]["Blackjack"] = 0
path["Players"][player]["Cooldowns"]["Coin"] = 0
path["Players"][player]["Cooldowns"]["Cups"] = 0
path["Players"][player]["Cooldowns"]["Dice"] = 0
path["Players"][player]["Cooldowns"]["Hi-Lo"] = 0
path["Players"][player]["Cooldowns"]["Payday"] = 0
path["Players"][player]["Cooldowns"]["Transfer"] = 0
path["Players"][player]["Cooldowns"]["War"] = 0
self.save_system()
def patch_1712(self, path):
"""Fixes older players in the casino who didn't have war or hi-lo"""
hilo_data = {"Played": {"Hi-Lo Played": 0}, "Won": {"Hi-Lo Won": 0},
"Cooldown": {"Hi-Lo": 0}}
war_data = {"Played": {"War Played": 0}, "Won": {"War Won": 0}, "Cooldown": {"War": 0}}
for player in path["Players"]:
if "Hi-Lo Played" not in path["Players"][player]["Played"]:
self.player_update(path["Players"][player], hilo_data)
if "War Played" not in path["Players"][player]["Played"]:
self.player_update(path["Players"][player], war_data)
self.save_system()
def player_update(self, player_data, new_game, path=None):
"""Helper function to add new data into the player's data"""
if path is None:
path = []
for key in new_game:
if key in player_data:
if isinstance(player_data[key], dict) and isinstance(new_game[key], dict):
self.player_update(player_data[key], new_game[key], path + [str(key)])
elif player_data[key] == new_game[key]:
pass
else:
raise Exception(_("Conflict at {}").format("".join(path + [str(key)])))
else:
player_data[key] = new_game[key]
self.save_system()
def patch_1694(self, path):
"""This patch aimed at converting the old cooldown times into unix time."""
print(_("patch_1694 ran"))
for player in path["Players"]:
try:
for cooldown in path["Players"][player]["Cooldowns"]:
s = path["Players"][player]["Cooldowns"][cooldown]
convert = datetime.utcnow() - timedelta(seconds=s)
path["Players"][player]["Cooldowns"][cooldown] = convert.isoformat()
except TypeError:
pass
self.save_system()
def patch_1692(self, path):
"""Issues with memberships storing keys that are lower case.
Fire bombing everyones memberships so I don't have nightmares.
"""
path["Memberships"] = {}
self.save_system()
def patch_16(self, path):
if "Transfer Limit" not in path["System Config"]:
transfer_dict = {"Transfer Limit": 1000, "Transfer Cooldown": 30}
path["System Config"].update(transfer_dict)
for x in path["Players"]:
if "Transfer" not in path["Players"][x]["Cooldowns"]:
path["Players"][x]["Cooldowns"]["Transfer"] = 0
self.save_system()
def patch_1581(self, path):
# Fixes the name bug for older versions
self.name_fix()
# Add hi-lo to older versions
if "Hi-Lo" not in path["Games"]:
hl = {"Hi-Lo": {"Multiplier": 1.5, "Cooldown": 0, "Open": True, "Min": 20,
"Max": 20}}
path["Games"].update(hl)
# Add war to older versions
if "War" not in path["Games"]:
war = {"War": {"Multiplier": 1.5, "Cooldown": 0, "Open": True, "Min": 50,
"Max": 100}}
path["Games"].update(war)
# Add membership changes from patch 1.5 to older versions
trash = ["Membership Lvl 0", "Membership Lvl 1", "Membership Lvl 2",
"Membership Lvl 3"]
new = {"Threshold Switch": False, "Threshold": 10000, "Default Payday": 100,
"Payday Timer": 1200}
for k, v in new.items():
if k not in path["System Config"]:
path["System Config"][k] = v
if "Memberships" not in path:
path["Memberships"] = {}
# Game access levels added
for x in path["Games"].values():
if "Access Level" not in x:
x["Access Level"] = 0
if "Min" in path["Games"]["Allin"]:
path["Games"]["Allin"].pop("Min")
if "Max" in path["Games"]["Allin"]:
path["Games"]["Allin"].pop("Max")
for x in trash:
if x in path["System Config"]:
path["System Config"].pop(x)
for x in path["Players"]:
if "CD" in path["Players"][x]:
path["Players"][x]["Cooldowns"] = path["Players"][x].pop("CD")
raw = [(x.split(" ", 1)[0], y) for x, y in
path["Players"][x]["Cooldowns"].items()]
raw.append(("Payday", 0))
new_dict = dict(raw)
path["Players"][x]["Cooldowns"] = new_dict
if "Membership" not in path["Players"][x]:
path["Players"][x]["Membership"] = None
if "Pending" not in path["Players"][x]:
path["Players"][x]["Pending"] = 0
self.save_system()
class PluralDict(dict):
"""This class is used to plural strings
You can plural strings based on the value input when using this class as a dictionary.
"""
def __missing__(self, key):
if '(' in key and key.endswith(')'):
key, rest = key.split('(', 1)
value = super().__getitem__(key)
suffix = rest.rstrip(')').split(',')
if len(suffix) == 1:
suffix.insert(0, '')
return suffix[0] if value <= 1 else suffix[1]
raise KeyError(key)
class Casino:
"""Play Casino minigames and earn chips that integrate with Economy!
Any user can join casino by using the casino join command. Casino uses hooks from economy to
cash in/out chips. You are able to create your own casino name and chip name. Casino comes with
7 mini games that you can set min/max bets, multipliers, and access levels. Check out all of the
admin settings by using commands in the setcasino group. For additional information please
check out the wiki on my github.
"""
__slots__ = ['bot', 'file_path', 'version', 'legacy_available', 'legacy_path', 'legacy_system',
'casino_bank', 'cycle_task']
def __init__(self, bot):
self.bot = bot
try: # This allows you to port accounts from older versions of casino
self.legacy_path = "data/casino/casino.json"
self.legacy_system = dataIO.load_json(self.legacy_path)
self.legacy_available = True
except FileNotFoundError:
self.legacy_available = False
self.file_path = "data/JumperCogs/casino/casino.json"
self.casino_bank = CasinoBank(bot, self.file_path)
self.version = "1.7.15"
self.cycle_task = bot.loop.create_task(self.membership_updater())
@commands.group(pass_context=True, no_pm=True)
async def casino(self, ctx):
"""Casino Group Commands"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
@casino.command(name="language", pass_context=True, hidden=True)
@checks.is_owner()
async def _language_casino(self, ctx):
"""Changes the output language in casino.
Default is English
"""
author = ctx.message.author
languages = {_("English"): "en", _("Spanish"): "es", _("Brazilian-Portuguese"): "br",
_("Danish"): "da", _("Malaysian"): "zsm", _("German"): "de",
_("Mandarin"): "cmn"}
l_out = ", ".join(list(languages.keys())[:-2] + [" or ".join(list(languages.keys())[-2:])])
await self.bot.say(_("I can change the language to \n{}\nWhich language would you prefer? "
"\n*Note this change will affect every server.*").format(l_out))
response = await self.bot.wait_for_message(timeout=15, author=author)
if response is None:
return await self.bot.say(_("No response. Cancelling language change."))
if response.content.title() in languages:
language = languages[response.content.title()]
lang = gettext.translation('casino', localedir='data/JumperCogs/casino/data',
languages=[language])
lang.install()
fp = "data/JumperCogs/casino/data/languages.json"
l_data = dataIO.load_json(fp)
l_data["Language"] = language
dataIO.save_json(fp, l_data)
await self.bot.say(_("The language is now set to {}").format(response.content.title()))
else:
return await self.bot.say(_("That language is not supported."))
@casino.command(name="purge", pass_context=True)
@checks.is_owner()
async def _purge_casino(self, ctx):
"""Removes all servers that the bot is no longer on.
If your JSON file is getting rather large, utilize this
command. It is possible that if your bot is on a ton of
servers, there are many that it is no longer running on.
This will remove them from the JSON file.
"""
author = ctx.message.author
servers = self.casino_bank.get_all_servers()
purge_list = [x for x in servers if self.bot.get_server(x) is None]
if not purge_list:
return await self.bot.say("There are no servers for me to purge at this time.")
await self.bot.say(_("I found {} server(s) I am no longer on. Would you like for me to "
"delete their casino data?").format(len(purge_list)))
response = await self.bot.wait_for_message(timeout=15, author=author)
if response is None:
return await self.bot.say(_("You took too long to answer. Canceling purge."))
if response.content.title() == _("Yes"):
for x in purge_list:
servers.pop(x)
self.casino_bank.save_system()
await self.bot.say(_("{} server entries have been erased.").format(len(purge_list)))
else:
return await self.bot.say(_("Incorrect response. This is a yes or no question."))
@casino.command(name="forceupdate", pass_context=True)
@checks.is_owner()
async def _forceupdate_casino(self, ctx):
"""Force applies older patches
This command will attempt to update your JSON with the
new dictionary keys. If you are having issues with your JSON
having a lot of key errors, namely Cooldown, then try using
this command. THIS DOES NOT UPDATE CASINO
"""
server = ctx.message.server
settings = self.casino_bank.check_server_settings(server)
self.casino_bank.patch_1581(settings)
self.casino_bank.patch_16(settings)
self.casino_bank.patch_games(settings)
self.casino_bank.patch_1694(settings)
await self.bot.say(_("Force applied three previous JSON updates. Please reload casino."))
@casino.command(name="memberships", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _memberships_casino(self, ctx):
"""Shows all memberships on the server."""
server = ctx.message.server
settings = self.casino_bank.check_server_settings(server)
memberships = settings["Memberships"].keys()
if memberships:
await self.bot.say(_("Available Memberships:```\n{}```").format('\n'.join(memberships)))
else:
await self.bot.say(_("There are no memberships."))
@casino.command(name="join", pass_context=True)
async def _join_casino(self, ctx):
"""Grants you membership access to the casino"""
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
try:
self.casino_bank.create_account(user)
except UserAlreadyRegistered:
return await self.bot.say(_("{} already has a casino membership").format(user.name))
else:
name = settings["System Config"]["Casino Name"]
await self.bot.say(_("Your membership has been approved! Welcome to {} Casino!\nAs a "
"first time member we have credited your account with 100 free "
"chips.\nHave fun!").format(name))
@casino.command(name="transfer", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _transfer_casino(self, ctx, user: discord.Member, chips: int):
"""Transfers chips to another player"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
chip_name = settings["System Config"]["Chip Name"]
limit = settings["System Config"]["Transfer Limit"]
if not self.casino_bank.membership_exists(author):
return await self.bot.say("{} is not registered to the casino.".format(author.name))
if not self.casino_bank.membership_exists(user):
return await self.bot.say("{} is not registered to the casino.".format(user.name))
if chips > limit:
return await self.bot.say(_("Your transfer cannot exceed the server limit of {} {} "
"chips.").format(limit, chip_name))
chip_name = settings["System Config"]["Chip Name"]
cooldown = self.check_cooldowns(user, "Transfer", settings, triggered=True)
if not cooldown:
try:
self.casino_bank.transfer_chips(author, user, chips)
except NegativeChips:
return await self.bot.say(_("An amount cannot be negative."))
except SameSenderAndReceiver:
return await self.bot.say(_("Sender and Reciever cannot be the same."))
except BotNotAUser:
return await self.bot.say(_("You can send chips to a bot."))
except InsufficientChips:
return await self.bot.say(_("Not enough chips to transfer."))
else:
logger.info("{}({}) transferred {} {} to {}({}).".format(author.name, author.id,
chip_name, chips,
user.name, user.id))
await self.bot.say(_("{} transferred {} {} to {}.").format(author.name, chip_name,
chips, user.name))
else:
await self.bot.say(cooldown)
@casino.command(name="acctransfer", pass_context=True)
async def _acctransfer_casino(self, ctx):
"""Transfers account info from old casino. Limit 1 transfer per user"""
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
if not self.casino_bank.membership_exists(user):
msg = _("I can't transfer data if you already have an account with the new casino.")
elif not self.legacy_available:
msg = _("No legacy file was found. Unable to perform membership transfers.")
elif user.id in self.legacy_system["Players"]:
await self.bot.say(_("Account for {} found. Your casino data will be transferred to "
"the {} server. After your data is transferred your old data will "
"be deleted. I can only transfer data **one time**.\nDo you wish "
"to transfer?").format(user.name, user.server.name))
response = await self.bot.wait_for_message(timeout=15, author=user)
if response is None:
msg = _("No response, transfer cancelled.")
elif response.content.title() == _("No"):
msg = _("Transfer cancelled.")
elif response.content.title() == _("Yes"):
old_data = self.legacy_system["Players"][user.id]
transfer = {user.id: old_data}
settings["Players"].update(transfer)
self.legacy_system["Players"].pop(user.id)
dataIO.save_json(self.legacy_path, self.legacy_system)
self.casino_bank.patch_1581(settings)
self.casino_bank.patch_16(settings)
self.casino_bank.patch_games(settings)
self.casino_bank.patch_1694(settings)
self.casino_bank.save_system()
msg = _("Data transfer successful. You can now access your old casino data.")
else:
msg = _("Improper response. Please state yes or no. Cancelling transfer.")
else:
msg = _("Unable to locate your previous data.")
await self.bot.say(msg)
@casino.command(name="leaderboard", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _leaderboard_casino(self, ctx, sort="top"):
"""Displays Casino Leaderboard"""
user = ctx.message.author
self.casino_bank.check_server_settings(user.server)
members = self.casino_bank.get_server_memberships(user.server)
if sort not in ["top", "bottom", "place"]:
sort = "top"
if members:
players = [(x["Name"], x["Chips"]) for x in members.values()]
pos = [x + 1 for x, y in enumerate(players)]
if sort == "bottom":
style = sorted(players, key=itemgetter(1))
rev_pos = list(reversed(pos))
players, chips = zip(*style)
data = list(zip(rev_pos, players, chips))
elif sort == "place":
style = sorted([[x["Name"], x["Chips"]] if x["Name"] != user.name
else ["[" + x["Name"] + "]", x["Chips"]]
for x in members.values()], key=itemgetter(1), reverse=True)
players, chips = zip(*style)
data = list(zip(pos, players, chips))
else:
style = sorted(players, key=itemgetter(1), reverse=True)
players, chips = zip(*style)
data = list(zip(pos, players, chips))
headers = [_("Rank"), _("Names"), _("Chips")]
msg = await self.table_split(user, headers, data, sort)
else:
msg = _("There are no casino players to show on the leaderboard.")
await self.bot.say(msg)
@casino.command(name="exchange", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _exchange_casino(self, ctx, currency: str, amount: int):
"""Exchange chips for credits and credits for chips"""
# Declare all variables here
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
bank = self.bot.get_cog('Economy').bank
currency = currency.title()
chip_rate = settings["System Config"]["Chip Rate"]
credit_rate = settings["System Config"]["Credit Rate"]
chip_multiple = Fraction(chip_rate).limit_denominator().denominator
credit_multiple = Fraction(credit_rate).limit_denominator().denominator
chip_name = settings["System Config"]["Chip Name"]
casino_name = settings["System Config"]["Casino Name"]
# Logic checks
if not self.casino_bank.membership_exists(user):
return await self.bot.say(_("You need to register to the {} Casino. To register type "
"`{}casino join`.").format(casino_name, ctx.prefix))
if currency not in [_("Chips"), _("Credits")]:
return await self.bot.say(_("I can only exchange chips or credits, please specify "
"one."))
# Logic for choosing chips
elif currency == _("Chips"):
if amount <= 0 and amount % credit_multiple != 0:
return await self.bot.say(_("The amount must be higher than 0 and "
"a multiple of {}.").format(credit_multiple))
try:
self.casino_bank.can_bet(user, amount)
except InsufficientChips:
return await self.bot.say(_("You don't have that many chips to exchange."))
else:
self.casino_bank.withdraw_chips(user, amount)
credits = int(amount * credit_rate)
bank.deposit_credits(user, credits)
return await self.bot.say(_("I have exchanged {} {} chips into {} credits.\nThank "
"you for playing at {} Casino."
"").format(amount, chip_name, credits, casino_name))
# Logic for choosing Credits
elif currency == _("Credits"):
if amount <= 0 and amount % chip_multiple != 0:
return await self.bot.say(_("The amount must be higher than 0 and a multiple "
"of {}.").format(chip_multiple))
elif bank.can_spend(user, amount):
bank.withdraw_credits(user, amount)
chip_amount = int(amount * chip_rate)
self.casino_bank.deposit_chips(user, chip_amount)
await self.bot.say(_("I have exchanged {} credits for {} {} chips.\nEnjoy your "
"time at {} Casino!").format(amount, chip_amount, chip_name,
casino_name))
else:
await self.bot.say(_("You don't have that many credits to exchange."))
@casino.command(name="stats", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _stats_casino(self, ctx):
"""Shows your casino play stats"""
# Variables
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
chip_name = settings["System Config"]["Chip Name"]
casino_name = settings["System Config"]["Casino Name"]
# Check for a membership and build the table.
try:
chip_balance = self.casino_bank.chip_balance(author)
except UserNotRegistered:
await self.bot.say(_("You need to register to the {} Casino. To register type "
"`{}casino join`.").format(casino_name, ctx.prefix))
else:
pending_chips = settings["Players"][author.id]["Pending"]
player = settings["Players"][author.id]
wiki = "[Wiki](https://github.com/Redjumpman/Jumper-Cogs/wiki/Casino)"
membership, benefits = self.get_benefits(settings, author.id)
b_msg = (_("Access Level: {Access}\nCooldown Reduction: {Cooldown Reduction}\n"
"Payday: {Payday}").format(**benefits))
description = (_("{}\nMembership: {}\n{} Chips: "
"{}").format(wiki, membership, chip_name, chip_balance))
color = self.color_lookup(benefits["Color"])
# Build columns for the table
games = sorted(settings["Games"])
played = [x[1] for x in sorted(player["Played"].items(), key=lambda tup: tup[0])]
won = [x[1] for x in sorted(player["Won"].items(), key=lambda tup: tup[0])]
cool_items = sorted(games + ["Payday"])
cooldowns = self.stats_cooldowns(settings, author, cool_items)
# Build embed
embed = discord.Embed(colour=color, description=description)
embed.title = _("{} Casino").format(casino_name)
embed.set_author(name=str(author), icon_url=author.avatar_url)
embed.add_field(name=_("Benefits"), value=b_msg)
embed.add_field(name=_("Pending Chips"), value=pending_chips, inline=False)
embed.add_field(name=_("Games"), value="```Prolog\n{}```".format("\n".join(games)))
embed.add_field(name=_("Played"),
value="```Prolog\n{}```".format("\n".join(map(str, played))))
embed.add_field(name=_("Won"),
value="```Prolog\n{}```".format("\n".join(map(str, won))))
embed.add_field(name=_("Cooldown Items"),
value="```CSS\n{}```".format("\n".join(cool_items)))
embed.add_field(name=_("Cooldown Remaining"),
value="```xl\n{}```".format("\n".join(cooldowns)))
await self.bot.say(embed=embed)
@casino.command(name="info", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _info_casino(self, ctx):
"""Shows information about the server casino"""
# Variables
server = ctx.message.server
settings = self.casino_bank.check_server_settings(server)
players = len(self.casino_bank.get_server_memberships(server))
memberships = len(settings["Memberships"])
chip_exchange_rate = settings["System Config"]["Chip Rate"]
credit_exchange_rate = settings["System Config"]["Credit Rate"]
games = settings["Games"].keys()
if settings["System Config"]["Threshold Switch"]:
threshold = settings["System Config"]["Threshold"]
else:
threshold = "None"
# Create the columns through list comprehensions
multiplier = [subdict["Multiplier"] for subdict in settings["Games"].values()]
min_bet = [subdict["Min"] if "Min" in subdict else "None"
for subdict in settings["Games"].values()]
max_bet = [subdict["Max"] if "Max" in subdict else "None"
for subdict in settings["Games"].values()]
cooldown = [subdict["Cooldown"] for subdict in settings["Games"].values()]
cooldown_formatted = [self.time_format(x) for x in cooldown]
# Determine the ratio calculations for chips and credits
chip_ratio = str(Fraction(chip_exchange_rate).limit_denominator()).replace("/", ":")
credit_ratio = str(Fraction(credit_exchange_rate).limit_denominator()).replace("/", ":")
# If a fraction reduces to 1, we make it 1:1
if chip_ratio == "1":
chip_ratio = "1:1"
if credit_ratio == "1":
credit_ratio = "1:1"
# Build the table and send the message
m = list(zip(games, multiplier, min_bet, max_bet, cooldown_formatted))
m = sorted(m, key=itemgetter(0))
t = tabulate(m, headers=["Game", "Multiplier", "Min Bet", "Max Bet", "Cooldown"])
msg = (_("```Python\n{}\n\nCredit Exchange Rate: {}\nChip Exchange Rate: {}\n"
"Casino Members: {}\nServer Memberships: {}\nServer Threshold: "
"{}```").format(t, credit_ratio, chip_ratio, players, memberships, threshold))
await self.bot.say(msg)
@casino.command(name="payday", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _payday_casino(self, ctx):
"""Gives you some chips"""
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
casino_name = settings["System Config"]["Casino Name"]
chip_name = settings["System Config"]["Chip Name"]
if not self.casino_bank.membership_exists(user):
await self.bot.say("You need to register to the {} Casino. To register type `{}casino "
"join`.".format(casino_name, ctx.prefix))
else:
cooldown = self.check_cooldowns(user, "Payday", settings, triggered=True)
if not cooldown:
if settings["Players"][user.id]["Membership"]:
membership = settings["Players"][user.id]["Membership"]
amount = settings["Memberships"][membership]["Payday"]
self.casino_bank.deposit_chips(user, amount)
msg = _("You received {} {} chips.").format(amount, chip_name)
else:
payday = settings["System Config"]["Default Payday"]
self.casino_bank.deposit_chips(user, payday)
msg = _("You received {} {} chips. Enjoy!").format(payday, chip_name)
else:
msg = cooldown
await self.bot.say(msg)
@casino.command(name="balance", pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def _balance_casino(self, ctx):
"""Shows your number of chips"""
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
chip_name = settings["System Config"]["Chip Name"]
casino_name = settings["System Config"]["Casino Name"]
try:
balance = self.casino_bank.chip_balance(user)
except UserNotRegistered:
await self.bot.say(_("You need to register to the {} Casino. To register type "
"`{}casino join`.").format(casino_name, ctx.prefix))
else:
await self.bot.say(_("```Python\nYou have {} {} chips.```").format(balance, chip_name))
@commands.command(pass_context=True, no_pm=True, aliases=["hl", "hi-lo"])
@commands.cooldown(1, 5, commands.BucketType.user)
async def hilo(self, ctx, choice: str, bet: int):
"""Pick High, Low, Seven. Lo is < 7 Hi is > 7. 6x payout on 7"""
# Declare variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
chip_name = settings["System Config"]["Chip Name"]
choice = choice.title()
choices = [_("Hi"), _("High"), _("Low"), _("Lo"), _("Seven"), "7"]
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "Hi-Lo", choice, choices)
if check:
msg = check
else: # Run the game when the checks return None
self.casino_bank.withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["Hi-Lo Played"] += 1
await self.bot.say(_("The dice hit the table and slowly fall into place..."))
die_one = random.randint(1, 6)
die_two = random.randint(1, 6)
result = die_one + die_two
outcome = self.hl_outcome(result)
await asyncio.sleep(2)
# Begin game logic to determine a win or loss
msg = (_("The dice landed on {} and {} \n").format(die_one, die_two))
if choice in outcome:
msg += (_("Congratulations! The outcome was "
"{} ({})!").format(result, outcome[0]))
settings["Players"][user.id]["Won"]["Hi-Lo Won"] += 1
# Check for a 7 to give a 12x multiplier
if outcome[0] == _("Seven"):
amount = bet * 6
msg += _("\n**BONUS!** 6x multiplier for Seven!")
else:
amount = int(round(bet * settings["Games"]["Hi-Lo"]["Multiplier"]))
# Check if a threshold is set and withold chips if amount is exceeded
if self.threshold_check(settings, amount):
settings["Players"][user.id]["Pending"] = amount
msg += (_("```Your winnings exceeded the threshold set on this server. "
"The amount of {} {} chips will be withheld until reviewed and "
"released by an admin. Do not attempt to play additional games "
"exceeding the threshold until this has been cleared.```"
"").format(amount, chip_name, user.id))
logger.info("{}({}) won {} chips exceeding the threshold. Game "
"details:\nPlayer Choice: {}\nPlayer Bet: {}\nGame "
"Outcome: {}\n[END OF REPORT]"
"".format(user.name, user.id, amount, choice.ljust(10),
str(bet).ljust(10), str(result).ljust(10)))
else:
self.casino_bank.deposit_chips(user, amount)
msg += _("```Python\nYou just won {} {} chips.```").format(amount, chip_name)
else:
msg += _("Sorry. The outcome was {} ({}).").format(result, outcome[0])
# Save the results of the game
self.casino_bank.save_system()
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
@commands.command(pass_context=True, no_pm=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def cups(self, ctx, cup: int, bet: int):
"""Pick the cup that is hiding the gold coin. Choose 1, 2, 3, or 4"""
# Declare variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
choice = cup
choices = [1, 2, 3, 4]
chip_name = settings["System Config"]["Chip Name"]
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "Cups", choice, choices)
if check:
msg = check
else: # Run the game when the checks return None
self.casino_bank.withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["Cups Played"] += 1
outcome = random.randint(1, 4)
await self.bot.say(_("The cups start shuffling along the table..."))
await asyncio.sleep(3)
# Begin game logic to determine a win or loss
if cup == outcome:
amount = int(round(bet * settings["Games"]["Cups"]["Multiplier"]))
settings["Players"][user.id]["Won"]["Cups Won"] += 1
msg = _("Congratulations! The coin was under cup {}!").format(outcome)
# Check if a threshold is set and withold chips if amount is exceeded
if self.threshold_check(settings, amount):
settings["Players"][user.id]["Pending"] = amount
msg += (_("Your winnings exceeded the threshold set on this server. "
"The amount of {} {} chips will be withheld until reviewed and "
"released by an admin. Do not attempt to play additional games "
"exceeding the threshold until this has been cleared."
"").format(amount, chip_name, user.id))
logger.info("{}({}) won {} chips exceeding the threshold. Game "
"details:\nPlayer Cup: {}\nPlayer Bet: {}\nGame "
"Outcome: {}\n[END OF REPORT]"
"".format(user.name, user.id, amount, str(cup).ljust(10),
str(bet).ljust(10), str(outcome).ljust(10)))
else:
self.casino_bank.deposit_chips(user, amount)
msg += _("```Python\nYou just won {} {} chips.```").format(amount, chip_name)
else:
msg = _("Sorry! The coin was under cup {}.").format(outcome)
# Save the results of the game
self.casino_bank.save_system()
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
@commands.command(pass_context=True, no_pm=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def coin(self, ctx, choice: str, bet: int):
"""Bet on heads or tails"""
# Declare variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
choice = choice.title()
choices = [_("Heads"), _("Tails")]
chip_name = settings["System Config"]["Chip Name"]
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "Coin", choice, choices)
if check:
msg = check
else: # Run the game when the checks return None
self.casino_bank.withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["Coin Played"] += 1
outcome = random.choice([_("Heads"), _("Tails")])
await self.bot.say(_("The coin flips into the air..."))
await asyncio.sleep(2)
# Begin game logic to determine a win or loss
if choice == outcome:
amount = int(round(bet * settings["Games"]["Coin"]["Multiplier"]))
msg = _("Congratulations! The coin landed on {}!").format(outcome)
settings["Players"][user.id]["Won"]["Coin Won"] += 1
# Check if a threshold is set and withold chips if amount is exceeded
if self.threshold_check(settings, amount):
settings["Players"][user.id]["Pending"] = amount
msg += (_("\nYour winnings exceeded the threshold set on this server. "
"The amount of {} {} chips will be withheld until reviewed and "
"released by an admin. Do not attempt to play additional games "
"exceeding the threshold until this has been cleared."
"").format(amount, chip_name, user.id))
logger.info("{}({}) won {} chips exceeding the threshold. Game "
"details:\nPlayer Choice: {}\nPlayer Bet: {}\nGame "
"Outcome: {}\n[END OF REPORT]"
"".format(user.name, user.id, amount, choice.ljust(10),
str(bet).ljust(10), outcome[0].ljust(10)))
else:
self.casino_bank.deposit_chips(user, amount)
msg += _("```Python\nYou just won {} {} chips.```").format(amount, chip_name)
else:
msg = _("Sorry! The coin landed on {}.").format(outcome)
# Save the results of the game
self.casino_bank.save_system()
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
@commands.command(pass_context=True, no_pm=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def dice(self, ctx, bet: int):
"""Roll 2, 7, 11 or 12 to win."""
# Declare variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
chip_name = settings["System Config"]["Chip Name"]
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "Dice", 1, [1])
if check:
msg = check
else: # Run the game when the checks return None
self.casino_bank.withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["Dice Played"] += 1
await self.bot.say(_("The dice strike the back of the table and begin to tumble into "
"place..."))
die_one = random.randint(1, 6)
die_two = random.randint(1, 6)
outcome = die_one + die_two
await asyncio.sleep(2)
# Begin game logic to determine a win or loss
msg = _("The dice landed on {} and {} \n").format(die_one, die_two)
if outcome in [2, 7, 11, 12]:
amount = int(round(bet * settings["Games"]["Dice"]["Multiplier"]))
settings["Players"][user.id]["Won"]["Dice Won"] += 1
msg += _("Congratulations! The dice landed on {}.").format(outcome)
# Check if a threshold is set and withold chips if amount is exceeded
if self.threshold_check(settings, amount):
settings["Players"][user.id]["Pending"] = amount
msg += (_("\nYour winnings exceeded the threshold set on this server. "
"The amount of {} {} chips will be withheld until reviewed and "
"released by an admin. Do not attempt to play additional games "
"exceeding the threshold until this has been cleared."
"").format(amount, chip_name, user.id))
logger.info("{}({}) won {} chips exceeding the threshold. Game "
"details:\nPlayer Bet: {}\nGame "
"Outcome: {}\n[END OF FILE]".format(user.name, user.id, amount,
str(bet).ljust(10),
str(outcome[0]).ljust(10)))
else:
self.casino_bank.deposit_chips(user, amount)
msg += _("```Python\nYou just won {} {} chips.```").format(amount, chip_name)
else:
msg += _("Sorry! The result was {}.").format(outcome)
# Save the results of the game
self.casino_bank.save_system()
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
@commands.command(pass_context=True, no_pm=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def war(self, ctx, bet: int):
"""Modified War Card Game."""
# Declare Variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "War", 1, [1])
if check:
msg = check
else: # Run the game when the checks return None
self.casino_bank.withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["War Played"] += 1
deck = main_deck[:] # Make a copy of the deck so we can remove cards that are drawn
outcome, player_card, dealer_card, amount = await self.war_game(user, settings, deck,
bet)
msg = self.war_results(settings, user, outcome, player_card, dealer_card, amount)
await self.bot.say(msg)
@commands.command(pass_context=True, no_pm=True, aliases=["bj", "21"])
@commands.cooldown(1, 5, commands.BucketType.user)
async def blackjack(self, ctx, bet: int):
"""Modified Blackjack."""
# Declare variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "Blackjack", 1, [1])
if check:
msg = check
else: # Run the game when the checks return None
self.casino_bank.withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["BJ Played"] += 1
deck = main_deck[:] # Make a copy of the deck so we can remove cards that are drawn
dhand = self.dealer(deck)
ph, dh, amt = await self.blackjack_game(dhand, user, bet, deck)
msg = self.blackjack_results(settings, user, amt, ph, dh)
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
@commands.command(pass_context=True, no_pm=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def allin(self, ctx, multiplier: int):
"""It's all or nothing. Bets everything you have."""
# Declare variables for the game.
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
chip_name = settings["System Config"]["Chip Name"]
if not self.casino_bank.membership_exists(user):
return await self.bot.say(_("You need to register. Type "
"{}casino join.").format(ctx.prefix))
# Run a logic check to determine if the user can play the game.
check = self.game_checks(settings, ctx.prefix, user, 0, "Allin", 1, [1])
if check:
msg = check
else: # Run the game when the checks return None.
# Setup the game to determine an outcome.
settings["Players"][user.id]["Played"]["Allin Played"] += 1
amount = int(round(multiplier * settings["Players"][user.id]["Chips"]))
balance = self.casino_bank.chip_balance(user)
outcome = random.randint(0, multiplier + 1)
self.casino_bank.withdraw_chips(user, balance)
await self.bot.say(_("You put all your chips into the machine and pull the lever..."))
await asyncio.sleep(3)
# Begin game logic to determine a win or loss.
if outcome == 0:
self.casino_bank.deposit_chips(user, amount)
msg = _("```Python\nJackpot!! You just won {} {} "
"chips!!```").format(amount, chip_name)
settings["Players"][user.id]["Won"]["Allin Won"] += 1
else:
msg = (_("Sorry! Your all or nothing gamble failed and you lost "
"all your {} chips.").format(chip_name))
# Save the results of the game
self.casino_bank.save_system()
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
@casino.command(name="version")
@checks.admin_or_permissions(manage_server=True)
async def _version_casino(self):
"""Shows current Casino version"""
await self.bot.say(_("You are currently running Casino version {}.").format(self.version))
@casino.command(name="cdreset", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _cdreset_casino(self, ctx):
"""Resets all cooldowns on the server"""
server = ctx.message.server
settings = self.casino_bank.check_server_settings(server)
for player in settings["Players"]:
for cd in settings["Players"][player]["Cooldowns"]:
settings["Players"][player]["Cooldowns"][cd] = 0
self.casino_bank.save_system()
await self.bot.say(_("Cooldowns have been reset for all users on this server."))
@casino.command(name="removemembership", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _removemembership_casino(self, ctx, *, membership):
"""Remove a casino membership"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if membership in settings["Memberships"]:
settings["Memberships"].pop(membership)
msg = _("{} removed from the list of membership.").format(membership)
else:
msg = _("Could not find a membership with that name.")
await self.bot.say(msg)
@casino.command(name="createmembership", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _createmembership_casino(self, ctx):
"""Add a casino membership to reward continued play"""
# Declare variables
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
cancel = ctx.prefix + _("cancel")
requirement_list = [_("Days On Server"), _("Credits"), _("Chips"), _("Role")]
colors = {_("blue"): "blue", _("red"): "red", _("green"): "green", _("orange"): "orange",
_("purple"): "purple", _("yellow"): "yellow", _("turquoise"): "turquoise",
_("teal"): "teal", _("magenta"): "magenta", _("pink"): "pink",
_("white"): "white"}
server_roles = [r.name for r in ctx.message.server.roles if r.name != "Bot"]
# Various checks for the different questions
check1 = lambda m: m.content.isdigit() and int(m.content) > 0 or m.content == cancel
check2 = lambda m: m.content.isdigit() or m.content == cancel
check3 = lambda m: m.content.title() in requirement_list or m.content == cancel
check4 = lambda m: m.content.isdigit() or m.content in server_roles or m.content == cancel
check5 = lambda m: m.content.lower() in colors or m.content == cancel
start = (_("Welcome to the membership creation process. This will create a membership to "
"provide benefits to your members such as reduced cooldowns and access levels.\n"
"You may cancel this process at anytime by typing {}cancel. Let's begin with "
"the first question.\n\nWhat is the name of this membership? Examples: Silver, "
"Gold, and Diamond.").format(ctx.prefix))
# Begin creation process
await self.bot.say(start)
name = await self.bot.wait_for_message(timeout=35, author=author)
if name is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if name.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
if name.content.title() in settings["Memberships"]:
await self.bot.say(_("A membership with that name already exists. "
"Cancelling creation."))
return
await self.bot.say(_("What is the color for this membership? This color appears in the "
"{}casino stats command.\nPlease pick from these colors: "
"```{}```").format(ctx.prefix, ", ".join(colors)))
color = await self.bot.wait_for_message(timeout=35, author=author, check=check5)
if color is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if color.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
await self.bot.say(_("What is the payday amount for this membership?"))
payday = await self.bot.wait_for_message(timeout=35, author=author, check=check1)
if payday is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if payday.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
await self.bot.say(_("What is the cooldown reduction for this membership in seconds? 0 for "
"none"))
reduction = await self.bot.wait_for_message(timeout=35, author=author, check=check2)
if reduction is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if reduction.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
await self.bot.say(_("What is the access level for this membership? 0 is the default "
"access level for new members. Access levels can be used to restrict "
"access to games. See `{}setcasino access` for more "
"info.").format(ctx.prefix))
access = await self.bot.wait_for_message(timeout=35, author=author, check=check1)
if access is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if access.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
if int(access.content) in [x["Access"] for x in settings["Memberships"].values()]:
await self.bot.say(_("You cannot have memberships with the same access level. "
"Cancelling creation."))
return
await self.bot.say(_("What is the requirement for this membership? Available options are:"
"```Days on server, Credits, Chips, or Role```Which would you "
"like set? You can always remove and add additional requirements "
"later using `{0}setcasino addrequirements` and "
"`{0}setcasino removerequirements`.").format(ctx.prefix))
req_type = await self.bot.wait_for_message(timeout=35, author=author, check=check3)
if req_type is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if req_type.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
await self.bot.say(_("What is the number of days, chips, credits or role name you would "
"like to set?"))
req_val = await self.bot.wait_for_message(timeout=35, author=author, check=check4)
if req_val is None:
await self.bot.say(_("You took too long. Cancelling membership creation."))
return
if req_val.content == cancel:
await self.bot.say(_("Membership creation cancelled."))
return
else:
if req_val.content.isdigit():
req_val = int(req_val.content)
else:
req_val = req_val.content
params = [name.content, color.content, payday.content, reduction.content,
access.content, req_val]
msg = (_("Membership successfully created. Please review the details below.\n"
"```Name: {0}\nColor: {1}\nPayday: {2}\nCooldown Reduction: {3}\n"
"Access Level: {4}\n").format(*params))
msg += _("Requirement: {} {}```").format(req_val, req_type.content.title())
memberships = {"Payday": int(payday.content), "Access": int(access.content),
"Cooldown Reduction": int(reduction.content),
"Color": colors[color.content.lower()],
"Requirements": {req_type.content.title(): req_val}}
settings["Memberships"][name.content.title()] = memberships
self.casino_bank.save_system()
await self.bot.say(msg)
@casino.command(name="reset", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _reset_casino(self, ctx):
"""Resets casino to default settings. Keeps user data"""
user = ctx.message.author
settings = self.casino_bank.check_server_settings(user.server)
await self.bot.say(_("This will reset casino to it's default settings and keep player data."
"\nDo you wish to reset casino settings?"))
response = await self.bot.wait_for_message(timeout=15, author=user)
if response is None:
msg = _("No response, reset cancelled.")
elif response.content.title() == _("No"):
msg = _("Cancelling reset.")
elif response.content.title() == _("Yes"):
settings["System Config"] = server_default["System Config"]
settings["Games"] = server_default["Games"]
self.casino_bank.save_system()
msg = _("Casino settings reset to default.")
else:
msg = _("Improper response. Cancelling reset.")
await self.bot.say(msg)
@casino.command(name="toggle", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _toggle_casino(self, ctx):
"""Opens and closes the casino"""
server = ctx.message.server
settings = self.casino_bank.check_server_settings(server)
casino_name = settings["System Config"]["Casino Name"]
if settings["System Config"]["Casino Open"]:
settings["System Config"]["Casino Open"] = False
msg = _("The {} Casino is now closed.").format(casino_name)
else:
settings["System Config"]["Casino Open"] = True
msg = _("The {} Casino is now open!").format(casino_name)
self.casino_bank.save_system()
await self.bot.say(msg)
@casino.command(name="approve", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _approve_casino(self, ctx, user: discord.Member):
"""Approve a user's pending chips."""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
chip_name = settings["System Config"]["Chip Name"]
if self.casino_bank.membership_exists(user):
amount = settings["Players"][user.id]["Pending"]
if amount > 0:
await self.bot.say(_("{} has a pending amount of {}. Do you wish to approve this "
"amount?").format(user.name, amount))
response = await self.bot.wait_for_message(timeout=15, author=author)
if response is None:
await self.bot.say(_("You took too long. Cancelling pending chip approval."))
return
if response.content.title() in [_("No"), _("Cancel"), _("Stop")]:
await self.bot.say(_("Cancelling pending chip approval."))
return
if response.content.title() in [_("Yes"), _("Approve")]:
await self.bot.say(_("{} approved the pending chips. Sending {} {} chips to "
" {}.").format(author.name, amount, chip_name, user.name))
self.casino_bank.deposit_chips(user, amount)
else:
await self.bot.say(_("Incorrect response. Cancelling pending chip approval."))
return
else:
await self.bot.say(_("{} does not have any chips pending.").format(user.name))
@casino.command(name="removeuser", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _removeuser_casino(self, ctx, user: discord.Member):
"""Remove a user from casino"""
author = ctx.message.author
self.casino_bank.check_server_settings(author.server)
if not self.casino_bank.membership_exists(user):
msg = _("This user is not a member of the casino.")
else:
await self.bot.say(_("Are you sure you want to remove player data for {}? Type {} to "
"confirm.").format(user.name, user.name))
response = await self.bot.wait_for_message(timeout=15, author=author)
if response is None:
msg = _("No response. Player removal cancelled.")
elif response.content.title() == user.name:
self.casino_bank.remove_membership(user)
msg = _("{}\'s casino data has been removed by {}.").format(user.name, author.name)
else:
msg = _("Incorrect name. Cancelling player removal.")
await self.bot.say(msg)
@casino.command(name="wipe", pass_context=True)
@checks.is_owner()
async def _wipe_casino(self, ctx, *, servername: str):
"""Wipe casino server data. Case Sensitive"""
user = ctx.message.author
servers = self.casino_bank.get_all_servers()
server_list = [self.bot.get_server(x).name for x in servers
if hasattr(self.bot.get_server(x), 'name')]
fmt_list = ["{}: {}".format(idx + 1, x) for idx, x in enumerate(server_list)]
try:
server = [self.bot.get_server(x) for x in servers
if self.bot.get_server(x).name == servername][0]
except AttributeError:
msg = (_("A server with that name could not be located.\n**List of "
"Servers:**"))
if len(fmt_list) > 25:
fmt_list = fmt_list[:25]
msg += "\n\n{}".format('\n'.join(fmt_list))
msg += _("\nThere are too many server names to display, displaying first 25.")
else:
msg += "\n\n{}".format('\n'.join(fmt_list))
return await self.bot.say(msg)
await self.bot.say(_("This will wipe casino server data.**WARNING** ALL PLAYER DATA WILL "
"BE DESTROYED.\nDo you wish to wipe {}?").format(server.name))
response = await self.bot.wait_for_message(timeout=15, author=user)
if response is None:
msg = _("No response, casino wipe cancelled.")
elif response.content.title() == _("No"):
msg = _("Cancelling casino wipe.")
elif response.content.title() == _("Yes"):
await self.bot.say(_("To confirm type the server name: {}").format(server.name))
response = await self.bot.wait_for_message(timeout=15, author=user)
if response is None:
msg = _("No response, casino wipe cancelled.")
elif response.content == server.name:
self.casino_bank.wipe_caisno_server(server)
msg = _("Casino wiped.")
else:
msg = _("Incorrect server name. Cancelling casino wipe.")
else:
msg = _("Improper response. Cancelling casino wipe.")
await self.bot.say(msg)
@commands.group(pass_context=True, no_pm=True)
async def setcasino(self, ctx):
"""Configures Casino Options"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
@setcasino.command(name="transferlimit", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _xferlimit_setcasino(self, ctx, limit: int):
"""This is the limit of chips a player can transfer at one time.
Remember, that without a cooldown, a player can still use this command
over and over. This is just to prevent a transfer of outrageous amounts.
"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if limit > 0:
settings["System Config"]["Transfer Limit"] = limit
msg = _("{} set transfer limit to {}.").format(author.name, limit)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
self.casino_bank.save_system()
else:
msg = _("Limit must be higher than 0.")
await self.bot.say(msg)
@setcasino.command(name="transfercd", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _xcdlimit_setcasino(self, ctx, seconds: int):
"""Set the cooldown for transferring chips.
There is already a five second cooldown in place. Use this to prevent
users from circumventing the transfer limit through spamming. Default
is set to 30 seconds.
"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if seconds > 0:
settings["System Config"]["Transfer Cooldown"] = seconds
time_fmt = self.time_format(seconds)
msg = _("{} set transfer cooldown to {}.").format(author.name, time_fmt)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
self.casino_bank.save_system()
else:
msg = _("Seconds must be higher than 0.")
await self.bot.say(msg)
@setcasino.command(name="threshold", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _threshold_setcasino(self, ctx, threshold: int):
"""Players that exceed this amount require an admin to approve the payout"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if threshold > 0:
settings["System Config"]["Threshold"] = threshold
msg = _("{} set payout threshold to {}.").format(author.name, threshold)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
self.casino_bank.save_system()
else:
msg = _("Threshold amount needs to be higher than 0.")
await self.bot.say(msg)
@setcasino.command(name="thresholdtoggle", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _threshholdtoggle_setcasino(self, ctx):
"""Turns on a chip win limit"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if settings["System Config"]["Threshold Switch"]:
msg = _("{} turned the threshold OFF.").format(author.name)
settings["System Config"]["Threshold Switch"] = False
else:
msg = _("{} turned the threshold ON.").format(author.name)
settings["System Config"]["Threshold Switch"] = True
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
self.casino_bank.save_system()
await self.bot.say(msg)
@setcasino.command(name="payday", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _payday_setcasino(self, ctx, amount: int):
"""Set the default payday amount with no membership
This amount is what users who have no membership will receive. If the
user has a membership it will be based on what payday amount that was set
for it.
"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
chip_name = settings["System Config"]["Chip Name"]
if amount >= 0:
settings["System Config"]["Default Payday"] = amount
self.casino_bank.save_system()
msg = _("{} set the default payday to {} {} "
"chips.").format(author.name, amount, chip_name)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
else:
msg = _("You cannot set a negative number to payday.")
await self.bot.say(msg)
@setcasino.command(name="paydaytimer", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _paydaytimer_setcasino(self, ctx, seconds: int):
"""Set the cooldown on payday
This timer is not affected by cooldown reduction from membership.
"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if seconds >= 0:
settings["System Config"]["Payday Timer"] = seconds
self.casino_bank.save_system()
time_set = self.time_format(seconds)
msg = _("{} set the default payday to {}.").format(author.name, time_set)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
else:
msg = (_("You cannot set a negative number to payday timer. That would be like going "
"back in time. Which would be totally cool, but I don't understand the "
"physics of how it might apply in this case. One would assume you would go "
"back in time to the point in which you could receive a payday, but it is "
"actually quite the opposite. You would go back to the point where you were "
"about to claim a payday and thus claim it again, but unfortunately your "
"total would not receive a net gain, because you are robbing from yourself. "
"Next time think before you do something so stupid."))
await self.bot.say(msg)
@setcasino.command(name="multiplier", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _multiplier_setcasino(self, ctx, game: str, multiplier: float):
"""Sets the payout multiplier for casino games"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if game.title() not in c_games:
msg = _("This game does not exist. Please pick from: {}").format(", ".join(c_games))
elif multiplier > 0:
multiplier = float(abs(multiplier))
settings["Games"][game.title()]["Multiplier"] = multiplier
self.casino_bank.save_system()
msg = _("Now setting the payout multiplier for {} to {}").format(game, multiplier)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
else:
msg = _("Multiplier needs to be higher than 0.")
await self.bot.say(msg)
@setcasino.command(name="access", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _access_setcasino(self, ctx, game: str, access: int):
"""Set the access level for a game. Default is 0. Used with membership."""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
game = game.title()
if game not in c_games:
msg = _("This game does not exist. Please pick from: {}").format(", ".join(c_games))
elif access >= 0:
settings["Games"][game.title()]["Access Level"] = access
self.casino_bank.save_system()
msg = _("{} changed the access level for {} to {}.").format(author.name, game, access)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
else:
msg = _("Access level must be higher than 0.")
await self.bot.say(msg)
@setcasino.command(name="reqadd", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _reqadd_setcasino(self, ctx, *, membership):
"""Add a requirement to a membership"""
# Declare variables
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
cancel_message = _("You took too long to respond. Cancelling requirement addition.")
requirement_options = {_("Days On Server"): "Days On Server", _("Credits"): "Credits",
_("Chips"): "Chips", _("Role"): "Role"}
server_roles = [r.name for r in ctx.message.server.roles if r.name != "Bot"]
# Message checks
check1 = lambda m: m.content.title() in requirement_options
check2 = lambda m: m.content.isdigit() and int(m.content) > 0
check3 = lambda m: m.content in server_roles
# Begin logic
if membership not in settings["Memberships"]:
await self.bot.say(_("This membership does not exist."))
else:
await self.bot.say(_("Which of these requirements would you like to add to the {} "
" membership?```{}.```NOTE: You cannot have multiple requirements "
"of the same "
"type.").format(membership, ', '.join(requirement_options)))
rsp = await self.bot.wait_for_message(timeout=15, author=author, check=check1)
if rsp is None:
await self.bot.say(cancel_message)
return
else:
# Determine amount for DoS, Credits, or Chips
if rsp.content.title() != _("Role"):
name = rsp.content.split(' ', 1)[0]
await self.bot.say(_("How many {} are required?").format(name))
reply = await self.bot.wait_for_message(timeout=15, author=author, check=check2)
if reply is None:
await self.bot.say(cancel_message)
return
else:
await self.bot.say(_("Adding the requirement of {} {} to the membership "
"{}.").format(reply.content, rsp.content, membership))
reply = int(reply.content)
# Determine the role for the requirement
else:
await self.bot.say(_("Which role would you like set? This role must already be "
"set on server."))
reply = await self.bot.wait_for_message(timeout=15, author=author, check=check3)
if reply is None:
await self.bot.say(cancel_message)
return
else:
await self.bot.say(_("Adding the requirement role of {} to the membership "
"{}.").format(reply.content, membership))
reply = reply.content
# Add and save the requirement
key = requirement_options[rsp.content.title()]
settings["Memberships"][membership]["Requirements"][key] = reply
self.casino_bank.save_system()
@setcasino.command(name="reqremove", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _reqremove_setcasino(self, ctx, *, membership):
"""Remove a requirement to a membership"""
# Declare variables
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if membership not in settings["Memberships"]:
await self.bot.say(_("This membership does not exist."))
else: # Membership was found.
current_requirements = settings["Memberships"][membership]["Requirements"].keys()
if not current_requirements:
return await self.bot.say(_("This membership has no requirements."))
check = lambda m: m.content.title() in current_requirements
await self.bot.say(_("The current requirements for this membership are:\n```{}```Which "
"would you like to remove?").format(", ".join(current_requirements)))
resp = await self.bot.wait_for_message(timeout=15, author=author, check=check)
if resp is None:
return await self.bot.say(_("You took too long. Cancelling requirement removal."))
else:
settings["Memberships"][membership]["Requirements"].pop(resp.content.title())
self.casino_bank.save_system()
await self.bot.say(_("{} requirement removed from {}.").format(resp.content.title(),
membership))
@setcasino.command(name="balance", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _balance_setcasino(self, ctx, user: discord.Member, chips: int):
"""Sets a Casino member's chip balance"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
chip_name = settings["System Config"]["Chip Name"]
casino_name = settings["System Config"]["Casino Name"]
try:
self.casino_bank.set_chips(user, chips)
except NegativeChips:
return await self.bot.say(_("Chips must be higher than 0."))
except UserNotRegistered:
return await self.bot.say(_("You need to register to the {} Casino. To register type "
"`{}casino join`.").format(casino_name, ctx.prefix))
else:
logger.info("SETTINGS CHANGED {}({}) set {}({}) chip balance to "
"{}".format(author.name, author.id, user.name, user.id, chips))
await self.bot.say(_("```Python\nSetting the chip balance of {} to "
"{} {} chips.```").format(user.name, chips, chip_name))
@setcasino.command(name="exchange", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _exchange_setcasino(self, ctx, rate: float, currency: str):
"""Sets the exchange rate for chips or credits"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if rate <= 0:
msg = _("Rate must be higher than 0. Default is 1.")
elif currency.title() == _("Chips"):
settings["System Config"]["Chip Rate"] = rate
logger.info("{}({}) changed the chip rate to {}".format(author.name, author.id, rate))
self.casino_bank.save_system()
msg = _("Setting the exchange rate for credits to chips to {}.").format(rate)
elif currency.title() == _("Credits"):
settings["System Config"]["Credit Rate"] = rate
logger.info("SETTINGS CHANGED {}({}) changed the credit rate to "
"{}".format(author.name, author.id, rate))
self.casino_bank.save_system()
msg = _("Setting the exchange rate for chips to credits to {}.").format(rate)
else:
msg = _("Please specify chips or credits")
await self.bot.say(msg)
@setcasino.command(name="name", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _name_setcasino(self, ctx, *, name: str):
"""Sets the name of the Casino."""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
settings["System Config"]["Casino Name"] = name
self.casino_bank.save_system()
msg = _("Changed the casino name to {}.").format(name)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
await self.bot.say(msg)
@setcasino.command(name="chipname", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _chipname_setcasino(self, ctx, *, name: str):
"""Sets the name of your Casino chips."""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
settings["System Config"]["Chip Name"] = name
self.casino_bank.save_system()
msg = ("Changed the name of your chips to {0}.\nTest Display:\n"
"```Python\nCongratulations, you just won 50 {0} chips.```".format(name))
logger.info("SETTINGS CHANGED {}({}) chip name set to "
"{}".format(author.name, author.id, name))
await self.bot.say(msg)
@setcasino.command(name="cooldown", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _cooldown_setcasino(self, ctx, game, seconds: int):
"""Set the cooldown period for casino games"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
if game.title() not in c_games:
msg = _("This game does not exist. Please pick from: {}").format(", ".join(c_games))
else:
settings["Games"][game.title()]["Cooldown"] = seconds
time_set = self.time_format(seconds)
self.casino_bank.save_system()
msg = _("Setting the cooldown period for {} to {}.").format(game, time_set)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
await self.bot.say(msg)
@setcasino.command(name="min", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _min_setcasino(self, ctx, game, minbet: int):
"""Set the minimum bet to play a game"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
min_games = [x for x in c_games if x != "Allin"]
if game.title() not in min_games:
msg = _("This game does not exist. Please pick from: {}").format(", ".join(min_games))
elif minbet < 0:
msg = _("You need to set a minimum bet higher than 0.")
elif minbet < settings["Games"][game.title()]["Max"]:
settings["Games"][game.title()]["Min"] = minbet
chips = settings["System Config"]["Chip Name"]
self.casino_bank.save_system()
msg = (_("Setting the minimum bet for {} to {} {} "
"chips.").format(game.title(), minbet, chips))
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
else:
maxbet = settings["Games"][game.title()]["Max"]
msg = (_("The minimum bet can't bet set higher than the maximum bet of "
"{} for {}.").format(maxbet, game.title()))
await self.bot.say(msg)
@setcasino.command(name="max", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _max_setcasino(self, ctx, game, maxbet: int):
"""Set the maximum bet to play a game"""
author = ctx.message.author
settings = self.casino_bank.check_server_settings(author.server)
max_games = [x for x in c_games if x != "Allin"]
if game.title() not in max_games:
msg = _("This game does not exist. Please pick from: {}").format(", ".join(max_games))
elif maxbet <= 0:
msg = _("You need to set a maximum bet higher than 0.")
elif maxbet > settings["Games"][game.title()]["Min"]:
settings["Games"][game.title()]["Max"] = maxbet
chips = settings["System Config"]["Chip Name"]
self.casino_bank.save_system()
msg = (_("Setting the maximum bet for {} to {} {} "
"chips.").format(game.title(), maxbet, chips))
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
else:
minbet = settings["Games"][game.title()]["Min"]
msg = _("The max bet needs be higher than the minimum bet of {}.").format(minbet)
await self.bot.say(msg)
async def table_split(self, user, headers, data, sort):
groups = [data[i:i + 20] for i in range(0, len(data), 20)]
pages = len(groups)
if sort == "place":
name = "[{}]".format(user.name)
page = next((idx for idx, sub in enumerate(groups) for tup in sub if name in tup), None)
if not page:
page = 0
table = tabulate(groups[page], headers=headers, numalign="left")
msg = (_("```ini\n{}``````Python\nYou are viewing page {} of {}. "
"{} casino members.```").format(table, page + 1, pages, len(data)))
return msg
elif pages == 1:
page = 0
table = tabulate(groups[page], headers=headers, numalign="left")
msg = (_("```ini\n{}``````Python\nYou are viewing page 1 of {}. "
"{} casino members```").format(table, pages, len(data)))
return msg
await self.bot.say(_("There are {} pages of high scores. "
"Which page would you like to display?").format(pages))
response = await self.bot.wait_for_message(timeout=15, author=user)
if response is None:
page = 0
table = tabulate(groups[page], headers=headers, numalign="left")
msg = (_("```ini\n{}``````Python\nYou are viewing page {} of {}. "
"{} casino members.```").format(table, page + 1, pages, len(data)))
return msg
else:
try:
page = int(response.content) - 1
table = tabulate(groups[page], headers=headers, numalign="left")
msg = (_("```ini\n{}``````Python\nYou are viewing page {} of {}. "
"{} casino members.```").format(table, page + 1, pages, len(data)))
return msg
except ValueError:
await self.bot.say("Sorry your response was not a number. Defaulting to page 1")
page = 0
table = tabulate(groups[page], headers=headers, numalign="left")
msg = (_("```ini\n{}``````Python\nYou are viewing page 1 of {}. "
"{} casino members```").format(table, pages, len(data)))
return msg
async def membership_updater(self):
"""Updates user membership based on requirements every 5 minutes"""
await self.bot.wait_until_ready()
try:
await asyncio.sleep(15)
bank = self.bot.get_cog('Economy').bank
while True:
servers = self.casino_bank.get_all_servers()
for server in servers:
try:
server_obj = self.bot.get_server(server)
settings = self.casino_bank.check_server_settings(server_obj)
except AttributeError:
continue
else:
user_path = self.casino_bank.get_server_memberships(server_obj)
users = [server_obj.get_member(user) for user in user_path
if server_obj.get_member(user) is not None] # Check for None
if users:
for user in users:
membership = self.gather_requirements(settings, user, bank)
settings["Players"][user.id]["Membership"] = membership
else:
continue
self.casino_bank.save_system()
await asyncio.sleep(300) # Wait 5 minutes
except asyncio.CancelledError:
pass
async def war_game(self, user, settings, deck, amount):
player_card, dealer_card, pc, dc = self.war_draw(deck)
multiplier = settings["Games"]["War"]["Multiplier"]
await self.bot.say(_("The dealer shuffles the deck and deals 1 card face down to the "
"player and the dealer..."))
await asyncio.sleep(2)
await self.bot.say(_("**FLIP!**"))
await asyncio.sleep(1)
if pc > dc:
outcome = "Win"
amount = int(amount * multiplier)
elif dc > pc:
outcome = "Loss"
else:
check = lambda m: m.content.title() in [_("War"), _("Surrender"), _("Ffs")]
await self.bot.say(_("The player and dealer are both showing a **{}**!\nTHIS MEANS "
"WAR! You may choose to surrender and forfeit half your bet, or "
"you can go to war.\nYour bet will be doubled, but you will only "
"win on half the bet, the rest will be "
"pushed.").format(player_card))
choice = await self.bot.wait_for_message(timeout=15, author=user, check=check)
if choice is None or choice.content.title() in [_("Surrender"), _("Ffs")]:
outcome = "Surrender"
amount = int(amount / 2)
elif choice.content.title() == _("War"):
self.casino_bank.withdraw_chips(user, amount)
player_card, dealer_card, pc, dc = self.burn_three(deck)
await self.bot.say(_("The dealer burns three cards and deals two cards "
"face down..."))
await asyncio.sleep(3)
await self.bot.say(_("**FLIP!**"))
if pc >= dc:
outcome = "Win"
amount = int(amount * multiplier + amount)
else:
outcome = "Loss"
else:
await self.bot.say(_("Improper response. You are being forced to forfeit."))
outcome = "Surrender"
amount = int(amount / 2)
return outcome, player_card, dealer_card, amount
async def blackjack_game(self, dh, user, amount, deck):
# Setup dealer and player starting hands
ph = self.draw_two(deck)
count = self.count_hand(ph)
# checks used to ensure the player uses the correct input
check = lambda m: m.content.title() in [_("Hit"), _("Stay"), _("Double")]
check2 = lambda m: m.content.title() in [_("Hit"), _("Stay")]
# End the game if the player has 21 in the starting hand.
if count == 21:
return ph, dh, amount
msg = (_("{}\nYour cards: {}\nYour score: {}\nThe dealer shows: "
"{}\nHit, stay, or double?").format(user.mention, ", ".join(ph), count, dh[0]))
await self.bot.say(msg)
choice = await self.bot.wait_for_message(timeout=15, author=user, check=check)
# Stop the blackjack game if the player chooses stay or double.
if choice is None or choice.content.title() == _("Stay"):
return ph, dh, amount
elif choice.content.title() == _("Double"):
# Create a try/except block to catch when people are dumb and don't have enough chips
try:
self.casino_bank.withdraw_chips(user, amount)
amount = amount * 2
ph = self.draw_card(ph, deck)
count = self.count_hand(ph)
return ph, dh, amount
except InsufficientChips:
await self.bot.say(_("Not enough chips. Please choose hit or stay."))
choice2 = await self.bot.wait_for_message(timeout=15, author=user, check=check2)
if choice2 is None or choice2.content.title() == _("Stay"):
return ph, dh, amount
elif choice2.content.title() == _("Hit"):
# This breaks PEP8 for DRY but I didn't want to create a sperate coroutine.
while count < 21:
ph = self.draw_card(ph, deck)
count = self.count_hand(ph)
if count >= 21:
break
msg = (_("{}\nYour cards: {}\nYour score: {}\nThe dealer shows: "
"{}\nHit or stay?").format(user.mention, ", ".join(ph), count,
dh[0]))
await self.bot.say(msg)
resp = await self.bot.wait_for_message(timeout=15, author=user,
check=check2)
if resp is None or resp.content.title() == _("Stay"):
break
else:
continue
# Return player hand & dealer hand when count >= 21 or the player picks stay.
return ph, dh, amount
# Continue game logic in a loop until the player's count is 21 or bust.
elif choice.content.title() == _("Hit"):
while count < 21:
ph = self.draw_card(ph, deck)
count = self.count_hand(ph)
if count >= 21:
break
msg = (_("{}\nYour cards: {}\nYour score: {}\nThe dealer shows: "
"{}\nHit or stay?").format(user.mention, ", ".join(ph), count, dh[0]))
await self.bot.say(msg)
response = await self.bot.wait_for_message(timeout=15, author=user, check=check2)
if response is None or response.content.title() == _("Stay"):
break
else:
continue
# Return player hand and dealer hand when count is 21 or greater or player picks stay.
return ph, dh, amount
def war_results(self, settings, user, outcome, player_card, dealer_card, amount):
chip_name = settings["System Config"]["Chip Name"]
msg = (_("======**{}**======\nPlayer Card: {}"
"\nDealer Card: {}\n").format(user.name, player_card, dealer_card))
if outcome == "Win":
settings["Players"][user.id]["Won"]["War Won"] += 1
# Check if a threshold is set and withold chips if amount is exceeded
if self.threshold_check(settings, amount):
settings["Players"][user.id]["Pending"] = amount
msg += (_("Your winnings exceeded the threshold set on this server. "
"The amount of {} {} chips will be withheld until reviewed and "
"released by an admin. Do not attempt to play additional games "
"exceeding the threshold until this has been cleared."
"").format(amount, chip_name, user.id))
logger.info("{}({}) won {} chips exceeding the threshold. Game "
"details:\nPlayer Bet: {}\nGame "
"Outcome: {}\n[END OF FILE]".format(user.name, user.id, amount,
str(amount).ljust(10),
str(outcome[0]).ljust(10)))
else:
self.casino_bank.deposit_chips(user, amount)
msg += (_("**\*\*\*\*\*\*Winner!\*\*\*\*\*\***\n```Python\nYou just won {} {} "
"chips.```").format(amount, chip_name))
elif outcome == "Loss":
msg += _("======House Wins!======")
else:
self.casino_bank.deposit_chips(user, amount)
msg = (_("======**{}**======\n:flag_white: Surrendered :flag_white:\n=================="
"\n{} {} chips returned.").format(user.name, amount, chip_name))
# Save results and return appropriate outcome message.
self.casino_bank.save_system()
return msg
def blackjack_results(self, settings, user, amount, ph, dh):
chip_name = settings["System Config"]["Chip Name"]
dc = self.count_hand(dh)
pc = self.count_hand(ph)
msg = (_("======**{}**======\nYour hand: {}\nYour score: {}\nDealer's hand: {}\nDealer's "
"score: {}\n").format(user.name, ", ".join(ph), pc, ", ".join(dh), dc))
if dc > 21 and pc <= 21 or dc < pc <= 21:
settings["Players"][user.id]["Won"]["BJ Won"] += 1
total = int(round(amount * settings["Games"]["Blackjack"]["Multiplier"]))
# Check if a threshold is set and withold chips if amount is exceeded
if self.threshold_check(settings, total):
settings["Players"][user.id]["Pending"] = total
msg = (_("Your winnings exceeded the threshold set on this server. "
"The amount of {} {} chips will be withheld until reviewed and "
"released by an admin. Do not attempt to play additional games "
"exceeding the threshold until this has been cleared."
"").format(total, chip_name, user.id))
logger.info("{}({}) won {} chips exceeding the threshold. Game "
"details:\nPlayer Bet: {}\nGame\n"
"[END OF FILE]".format(user.name, user.id, total, str(total).ljust(10)))
else:
msg += (_("**\*\*\*\*\*\*Winner!\*\*\*\*\*\***\n```Python\nYou just "
"won {} {} chips.```").format(total, chip_name))
self.casino_bank.deposit_chips(user, total)
elif pc > 21:
msg += _("======BUST!======")
elif dc == pc and dc <= 21 and pc <= 21:
msg += (_("======Pushed======\nReturned {} {} chips to your "
"account.").format(amount, chip_name))
amount = int(round(amount))
self.casino_bank.deposit_chips(user, amount)
elif dc > pc and dc <= 21:
msg += _("======House Wins!======").format(user.name)
# Save results and return appropriate outcome message.
self.casino_bank.save_system()
return msg
def draw_two(self, deck):
hand = random.sample(deck, 2)
deck.remove(hand[0])
deck.remove(hand[1])
return hand
def draw_card(self, hand, deck):
card = random.choice(deck)
deck.remove(card)
hand.append(card)
return hand
def count_hand(self, hand):
count = sum([bj_values[x] for x in hand if x in bj_values])
count += sum([1 if x == 'Ace' and count + 11 > 21 else 11
if x == 'Ace' and hand.count('Ace') == 1 else 1
if x == 'Ace' and hand.count('Ace') > 1 else 0 for x in hand])
return count
def dealer(self, deck):
dh = self.draw_two(deck)
count = self.count_hand(dh)
# forces hit if ace in first two cards
if 'Ace' in dh:
dh = self.draw_card(dh, deck)
count = self.count_hand(dh)
# defines maximum hit score X
while count < 16:
self.draw_card(dh, deck)
count = self.count_hand(dh)
return dh
def war_draw(self, deck):
player_card = random.choice(deck)
deck.remove(player_card)
dealer_card = random.choice(deck)
pc = war_values[player_card]
dc = war_values[dealer_card]
return player_card, dealer_card, pc, dc
def burn_three(self, deck):
burn_cards = random.sample(deck, 3)
for x in burn_cards:
deck.remove(x)
player_card = random.choice(deck)
deck.remove(player_card)
dealer_card = random.choice(deck)
pc = war_values[player_card]
dc = war_values[dealer_card]
return player_card, dealer_card, pc, dc
def gather_requirements(self, settings, user, bank):
# Declare variables
path = settings["Memberships"]
memberships = settings["Memberships"]
memberships_met = []
# Loop through the memberships and their requirements
for membership in memberships:
req_switch = False
for req in path[membership]["Requirements"]:
# If the requirement is a role, run role logic
if req == "Role":
role = path[membership]["Requirements"]["Role"]
if role in [r.name for r in user.roles]:
req_switch = True
else:
req_switch = False
# If the requirement is a credits, run credit logic
elif req == "Credits":
if bank.account_exists(user):
user_credits = bank.get_balance(user)
if user_credits >= int(path[membership]["Requirements"]["Credits"]):
req_switch = True
else:
req_switch = False
else:
req_switch = False
# If the requirement is a chips, run chip logic
elif req == "Chips":
balance = self.casino_bank.chip_balance(user)
if balance >= int(path[membership]["Requirements"][req]):
req_switch = True
else:
req_switch = False
# If the requirement is a DoS, run DoS logic
elif req == "Days On Server":
dos = (datetime.utcnow() - user.joined_at).days
if dos >= path[membership]["Requirements"]["Days On Server"]:
req_switch = True
else:
req_switch = False
# You have to meet all the requirements to qualify for the membership
if req_switch:
memberships_met.append((membership, path[membership]["Access"]))
# Returns the membership with the highest access value
if memberships_met:
try:
membership = max(memberships_met, key=itemgetter(1))[0]
return membership
except (ValueError, TypeError):
return
else: # Returns none if the user has not qualified for any memberships
return
def get_benefits(self, settings, player):
payday = settings["System Config"]["Default Payday"]
benefits = {"Cooldown Reduction": 0, "Access": 0, "Payday": payday, "Color": "grey"}
membership = settings["Players"][player]["Membership"]
if membership:
if membership in settings["Memberships"]:
benefits = settings["Memberships"][membership]
else:
settings["Players"][player]["Membership"] = None
self.casino_bank.save_system()
membership = None
return membership, benefits
def threshold_check(self, settings, amount):
if settings["System Config"]["Threshold Switch"]:
if amount > settings["System Config"]["Threshold"]:
return True
else:
return False
else:
return False
def hl_outcome(self, dicetotal):
if dicetotal in list(range(1, 7)):
return [_("Low"), _("Lo")]
elif dicetotal == 7:
return [_("Seven"), _("7")]
else:
return [_("High"), _("Hi")]
def minmax_check(self, bet, game, settings):
mi = settings["Games"][game]["Min"]
mx = settings["Games"][game]["Max"]
if mi <= bet <= mx:
return None
else:
if mi != mx:
msg = (_("Your bet needs to be {} or higher, but cannot exceed the "
"maximum of {} chips.").format(mi, mx))
else:
msg = (_("Your bet needs to be exactly {}.").format(mi))
return msg
def stats_cooldowns(self, settings, user, cd_list):
cooldowns = []
for method in cd_list:
msg = self.check_cooldowns(user, method, settings, triggered=False, brief=True)
if not msg:
cooldowns.append(_("<<Ready to Play!"))
else:
cooldowns.append(msg)
return cooldowns
def check_cooldowns(self, user, method, settings, triggered=False, brief=False):
user_time = settings["Players"][user.id]["Cooldowns"][method]
user_membership = settings["Players"][user.id]["Membership"]
try:
reduction = settings["Memberships"][user_membership]["Cooldown Reduction"]
except KeyError:
reduction = 0
# Find the base cooldown by method
if method in c_games:
base = settings["Games"][method]["Cooldown"]
elif method == "Payday":
reduction = 0
base = settings["System Config"]["Payday Timer"]
else:
reduction = 0
base = settings["System Config"]["Transfer Cooldown"]
print(reduction)
# Begin cooldown logic calculation
if user_time == 0: # For new accounts
if triggered:
settings["Players"][user.id]["Cooldowns"][method] = datetime.utcnow().isoformat()
self.casino_bank.save_system()
return None
elif int((datetime.utcnow() - parser.parse(user_time)).total_seconds()) + reduction < base:
diff = int((datetime.utcnow() - parser.parse(user_time)).total_seconds())
seconds = base - diff - reduction
if brief:
remaining = self.time_format(seconds, True)
msg = remaining
else:
remaining = self.time_format(seconds, False)
msg = _("{} is still on a cooldown. You still have: {}").format(method, remaining)
return msg
else:
if triggered:
settings["Players"][user.id]["Cooldowns"][method] = datetime.utcnow().isoformat()
self.casino_bank.save_system()
return None
def time_converter(self, units):
return sum(int(x) * 60 ** i for i, x in enumerate(reversed(units.split(":"))))
def time_format(self, seconds, brief=False):
# Calculate the time and input into a dict to plural the strings later.
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
data = PluralDict({'hour': h, 'minute': m, 'second': s})
# Determine the remaining time.
if not brief:
if h > 0:
fmt = "{hour} hour{hour(s)}"
if data["minute"] > 0 and data["second"] > 0:
fmt += ", {minute} minute{minute(s)}, and {second} second{second(s)}"
if data["second"] > 0 == data["minute"]:
fmt += ", and {second} second{second(s)}"
msg = fmt.format_map(data)
elif h == 0 and m > 0:
if data["second"] == 0:
fmt = "{minute} minute{minute(s)}"
else:
fmt = "{minute} minute{minute(s)}, and {second} second{second(s)}"
msg = fmt.format_map(data)
elif m == 0 and h == 0 and s > 0:
fmt = "{second} second{second(s)}"
msg = fmt.format_map(data)
else:
msg = "None"
# Return remaining time.
else:
if h > 0:
msg = "{0}h"
if m > 0 and s > 0:
msg += ", {1}m, and {2}s"
elif s > 0 and m == 0:
msg += "and {2}s"
elif h == 0 and m > 0:
if s == 0:
msg = "{1}m"
else:
msg = "{1}m and {2}s"
elif m == 0 and h == 0 and s > 0:
msg = "{2}s"
else:
msg = "None"
return msg.format(h, m, s)
def access_calculator(self, settings, user):
user_membership = settings["Players"][user.id]["Membership"]
if user_membership is None:
return 0
else:
if user_membership in settings["Memberships"]:
access = settings["Memberships"][user_membership]["Access"]
return access
else:
settings["Players"][user.id]["Membership"] = None
self.casino_bank.save_system()
return 0
def game_checks(self, settings, prefix, user, bet, game, choice, choices):
casino_name = settings["System Config"]["Casino Name"]
game_access = settings["Games"][game]["Access Level"]
# Allin does not require a minmax check, so we set it to None if Allin.
if game != "Allin":
minmax_fail = self.minmax_check(bet, game, settings)
else:
minmax_fail = None
bet = int(settings["Players"][user.id]["Chips"])
# Check for membership first.
try:
self.casino_bank.can_bet(user, bet)
except UserNotRegistered:
msg = (_("You need to register to the {} Casino. To register type `{}casino "
"join`.").format(casino_name, prefix))
return msg
except InsufficientChips:
msg = _("You do not have enough chips to cover the bet.")
return msg
user_access = self.access_calculator(settings, user)
# Begin logic to determine if the game can be played.
if choice not in choices:
msg = _("Incorrect response. Accepted response are:\n{}").format(", ".join(choices))
return msg
elif not settings["System Config"]["Casino Open"]:
msg = _("The {} Casino is closed.").format(casino_name)
return msg
elif game_access > user_access:
msg = (_("{} requires an access level of {}. Your current access level is {}. Obtain a "
"higher membership to play this game."))
return msg
elif minmax_fail:
msg = minmax_fail
return msg
else:
cd_check = self.check_cooldowns(user, game, settings, triggered=True)
# Cooldowns are checked last incase another check failed.
return cd_check
def color_lookup(self, color):
color = color.lower()
colors = {"blue": 0x3366FF, "red": 0xFF0000, "green": 0x00CC33, "orange": 0xFF6600,
"purple": 0xA220BD, "yellow": 0xFFFF00, "teal": 0x009999, "magenta": 0xBA2586,
"turquoise": 0x00FFFF, "grey": 0x666666, "pink": 0xFE01D1, "white": 0xFFFFFF}
color = colors[color]
return color
def __unload(self):
self.cycle_task.cancel()
self.casino_bank.save_system()
def check_folders():
if not os.path.exists("data/JumperCogs/casino"):
print("Creating data/JumperCogs/casino folder...")
os.makedirs("data/JumperCogs/casino")
def check_files():
system = {"Servers": {}}
f = "data/JumperCogs/casino/casino.json"
if not dataIO.is_valid_json(f):
print(_("Creating default casino.json..."))
dataIO.save_json(f, system)
def setup(bot):
global logger
check_folders()
check_files()
logger = logging.getLogger("red.casino")
if logger.level == 0:
logger.setLevel(logging.INFO)
# Rotates to a new file every 10mb, up to 5
handler = logging.handlers.RotatingFileHandler(filename='data/JumperCogs/casino/casino.log',
encoding='utf-8', backupCount=5,
maxBytes=100000)
handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(message)s',
datefmt="[%d/%m/%Y %H:%M]"))
logger.addHandler(handler)
bot.add_cog(Casino(bot))
|
StarcoderdataPython
|
4916364
|
# Import python modules
import readline
import sys
# Import core modules
from core.module_manager import ModuleManager
from core import colors
from core import command_handler
mm = ModuleManager
def run(scf):
global mm
scriptline = 0
ch = command_handler.Commandhandler(mm, False)
while True:
try:
if scriptline == len(scf):
sys.exit(0)
command = scf[scriptline][0]
scriptline += 1
ch.handle(command)
except KeyboardInterrupt:
print()
sys.exit(0)
|
StarcoderdataPython
|
5192103
|
from django.urls import reverse
from django.conf import settings
from django.test import TestCase
from rest_framework.test import APIClient
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.contrib.auth.tokens import default_token_generator
import json
import pytest
from ..models import User
class TestUserRegistrationView(TestCase):
def setUp(self):
self.client = APIClient()
self.user = {
"user": {
"username": "Jajcob",
"email": "<EMAIL>",
"password": "<PASSWORD>",
}
}
self.user2 = User.objects.create(
username="Jajcob", email="<EMAIL>", is_superuser=False
)
def test_register_password_without_capital_letter(self):
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["password"][0],
"Password should contain at least one Upper Case letter",
)
def test_register_password_without_atleast_one_lower_letter(self):
self.user["user"]["password"] = "<PASSWORD>"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["password"][0],
"Password should contain at least one lower Case letter",
)
def test_register_password_without_non_alphanumeric_password(self):
self.user["user"]["password"] = "Password"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["password"][0],
"Password should be alpha Numeric",
)
def test_register_password_with_length_less_than_8_characters(self):
self.user["user"]["password"] = "<PASSWORD>"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["password"][0],
"Ensure this field has at least 8 characters.",
)
def test_register_with_duplicate_user(self):
self.client.force_authenticate(self.user2)
self.user["user"]["password"] = "<PASSWORD>"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["username"][0],
"user with this username already exists.",
)
self.assertEqual(
response.data["errors"]["email"][0],
"user with this email already exists.",
)
def test_register_without_password(self):
self.user["user"]["password"] = ""
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["password"][0],
"This field may not be blank.",
)
def test_register_with_space_character_in_username(self):
self.user["user"]["username"] = "Kalmsi c123"
self.user["user"]["email"] = "<EMAIL>"
self.user["user"]["password"] = "<PASSWORD>"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data["errors"]["username"][0],
"Username cannot contain a space",
)
def test_register_a_user_successfully(self):
self.user["user"]["password"] = "<PASSWORD>"
self.user["user"]["email"] = "<EMAIL>"
self.user["user"]["username"] = "kalsmic"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.data["email"], "<EMAIL>")
self.assertEqual(response.data["username"], "kalsmic")
self.assertIn("token",response.data)
def test_register_with_password_similar_to_username(self):
self.user["user"]["password"] = "<PASSWORD>"
self.user["user"]["email"] = "<EMAIL>"
self.user["user"]["username"] = "Password123"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
print(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data['errors']['error'][0], "Your password should not be the same as or contain your username")
def test_register_with_password_containing_username(self):
self.user["user"]["password"] = "<PASSWORD>"
self.user["user"]["email"] = "<EMAIL>"
self.user["user"]["username"] = "Password123"
response = self.client.post(
"/api/users/",
content_type="application/json",
data=json.dumps(self.user),
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data['errors']['error'][0], "Your password should not be the same as or contain your username")
def test_succesful_user_activation(self):
'''
Ensure that a user is succesfully activated
'''
uid = self.user2.id
kwargs = {
"uidb64": urlsafe_base64_encode(force_bytes(uid)).decode(),
"token": default_token_generator.make_token(self.user2)
}
activation_url = reverse("activate_user_account", kwargs=kwargs)
self.assertFalse(self.user2.is_active)
response = self.client.get(
activation_url,
content_type="application/json",
)
self.assertEqual(response.data, "Activation successful")
def test_user_activation_with_non_existent_user(self):
'''
Ensures that a user who does not exist cannot be activated
'''
uid = 10
kwargs = {
"uidb64": urlsafe_base64_encode(force_bytes(uid)).decode(),
"token": default_token_generator.make_token(self.user2)
}
activation_url = reverse("activate_user_account", kwargs=kwargs)
self.assertFalse(self.user2.is_active)
response = self.client.get(
activation_url,
content_type="application/json",
)
self.assertEqual(response.data, "Activation failed")
def test_user_activation_expiry(self):
'''
Ensures that an activation can expire
'''
uid = self.user2.id
kwargs = {
"uidb64": urlsafe_base64_encode(force_bytes(uid)).decode(),
"token": default_token_generator.make_token(self.user2)
}
activation_url = reverse("activate_user_account", kwargs=kwargs)
self.assertFalse(self.user2.is_active)
settings.PASSWORD_RESET_TIMEOUT_DAYS = -1
response = self.client.get(
activation_url,
content_type="application/json",
)
self.assertEqual(response.data, "Activation link has expired")
|
StarcoderdataPython
|
1635640
|
from random import randint, seed
seed(10) # Set random seed to make examples reproducible
random_dictionary = {i: randint(1, 10) for i in range(5)}
print(random_dictionary) # {0: 10, 1: 1, 2: 7, 3: 8, 4: 10}
|
StarcoderdataPython
|
6536331
|
#!/usr/local/bin/python3.6
import random
import time
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
from tqdm import tqdm
import os
os.environ["CUDA_VISIBLE_DEVICES"]="4"
tf.logging.set_verbosity(tf.logging.ERROR)
train_list = "/home/neillu/BPCSE/train_spec_noisy_list_train.txt"
dev_list = "/home/neillu/BPCSE/train_spec_noisy_list_dev.txt"
test_list = "/mnt/Data/user_vol_2/user_neillu/BPCSE/ts_timit"
ppg_path = "/mnt/Data/user_vol_2/user_neillu/ppg_feat/broad_manner/"
btn_path = "/mnt/Data/user_vol_2/user_neillu/btn_feat/"
pretrain_name = "broad_manner_savemodel/"
result_name = "broad_manner_savemodel/"
result_path = os.path.join(btn_path,result_name)
save_path = os.path.join(btn_path,"models/",result_name)
pretrain_path = os.path.join(btn_path,"models/",pretrain_name) + "model-0"
pretrain = False
if not os.path.exists(result_path):
os.makedirs(result_path)
class Autoencoder:
def __init__(self, n_features, learning_rate=0.5, n_hidden=[1000, 500, 250, 2], alpha=0.0):
self.n_features = n_features
self.weights = None
self.biases = None
self.graph = tf.Graph() # initialize new grap
self.build(n_features, learning_rate, n_hidden, alpha) # building graph
self.sess = tf.Session(graph=self.graph) # create session by the graph
def build(self, n_features, learning_rate, n_hidden, alpha):
with self.graph.as_default():
### Input
self.train_features = tf.placeholder(tf.float32, shape=(None, n_features))
self.train_targets = tf.placeholder(tf.float32, shape=(None, n_features))
### Optimalization
# build neurel network structure and get their predictions and loss
self.y_, self.original_loss, _ = self.structure(
features=self.train_features,
targets=self.train_targets,
n_hidden=n_hidden)
# regularization loss
# weight elimination L2 regularizer
self.regularizer = \
tf.reduce_sum([tf.reduce_sum(
tf.pow(w, 2)/(1+tf.pow(w, 2))) for w in self.weights.values()]) \
/ tf.reduce_sum(
[tf.size(w, out_type=tf.float32) for w in self.weights.values()])
# total loss
self.loss = self.original_loss + alpha * self.regularizer
# define training operation
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.train_op = self.optimizer.minimize(self.loss)
### Prediction
self.new_features = tf.placeholder(tf.float32, shape=(None, n_features))
self.new_targets = tf.placeholder(tf.float32, shape=(None, n_features))
self.new_y_, self.new_original_loss, self.new_encoder = self.structure(
features=self.new_features,
targets=self.new_targets,
n_hidden=n_hidden)
self.new_loss = self.new_original_loss + alpha * self.regularizer
### Initialization
self.init_op = tf.global_variables_initializer()
def structure(self, features, targets, n_hidden):
### Variable
if (not self.weights) and (not self.biases):
self.weights = {}
self.biases = {}
n_encoder = [self.n_features]+n_hidden
for i, n in enumerate(n_encoder[:-1]):
self.weights['encode{}'.format(i+1)] = \
tf.Variable(tf.truncated_normal(
shape=(n, n_encoder[i+1]), stddev=0.1), dtype=tf.float32)
self.biases['encode{}'.format(i+1)] = \
tf.Variable(tf.zeros(shape=(n_encoder[i+1])), dtype=tf.float32)
n_decoder = list(reversed(n_hidden))+[self.n_features]
for i, n in enumerate(n_decoder[:-1]):
self.weights['decode{}'.format(i+1)] = \
tf.Variable(tf.truncated_normal(
shape=(n, n_decoder[i+1]), stddev=0.1), dtype=tf.float32)
self.biases['decode{}'.format(i+1)] = \
tf.Variable(tf.zeros(shape=(n_decoder[i+1])), dtype=tf.float32)
### Structure
activation = tf.nn.relu
encoder = self.get_dense_layer(features,
self.weights['encode1'],
self.biases['encode1'],
activation=activation)
for i in range(1, len(n_hidden)-1):
encoder = self.get_dense_layer(
encoder,
self.weights['encode{}'.format(i+1)],
self.biases['encode{}'.format(i+1)],
activation=activation,
)
encoder = self.get_dense_layer(
encoder,
self.weights['encode{}'.format(len(n_hidden))],
self.biases['encode{}'.format(len(n_hidden))],
)
decoder = self.get_dense_layer(encoder,
self.weights['decode1'],
self.biases['decode1'],
activation=activation)
for i in range(1, len(n_hidden)-1):
decoder = self.get_dense_layer(
decoder,
self.weights['decode{}'.format(i+1)],
self.biases['decode{}'.format(i+1)],
activation=activation,
)
y_ = self.get_dense_layer(
decoder,
self.weights['decode{}'.format(len(n_hidden))],
self.biases['decode{}'.format(len(n_hidden))],
activation=tf.nn.sigmoid,
)
loss = tf.reduce_mean(tf.pow(targets - y_, 2))
return (y_, loss, encoder)
def get_dense_layer(self, input_layer, weight, bias, activation=None):
x = tf.add(tf.matmul(input_layer, weight), bias)
if activation:
x = activation(x)
return x
def fit(self, X, Y, epochs=10, validation_data=None, test_data=None, batch_size=None):
X = self._check_array(X)
Y = self._check_array(Y)
N = X.shape[0]
random.seed(9000)
if not batch_size:
batch_size = N
self.sess.run(self.init_op)
with self.graph.as_default():
self.saver = tf.train.Saver()
for epoch in range(epochs):
print('Epoch %2d/%2d: ' % (epoch+1, epochs))
start_time = time.time()
# mini-batch gradient descent
index = [i for i in range(N)]
random.shuffle(index)
while len(index) > 0:
index_size = len(index)
batch_index = [index.pop() for _ in range(min(batch_size, index_size))]
feed_dict = {self.train_features: X[batch_index, :],
self.train_targets: Y[batch_index, :]}
_, loss = self.sess.run([self.train_op, self.loss], feed_dict=feed_dict)
print('[%d/%d] loss = %9.4f ' % (N-len(index), N, loss), end='\r')
# evaluate at the end of this epoch
msg_valid = ''
if validation_data is not None:
val_loss = self.evaluate(validation_data[0], validation_data[1])
msg_valid = ', val_loss = %9.4f' % (val_loss)
train_loss = self.evaluate(X, Y)
print('[%d/%d] %ds loss = %9.4f %s' % (N, N, time.time()-start_time,
train_loss, msg_valid))
# save at the end of this epoch
if not os.path.exists(save_path):
os.makedirs(save_path)
self.saver.save(self.sess, save_path + 'model', global_step=0)
if test_data is not None:
test_loss = self.evaluate(test_data[0], test_data[1])
print('test_loss = %9.4f' % (test_loss))
def encode(self, X):
X = self._check_array(X)
return self.sess.run(self.new_encoder, feed_dict={self.new_features: X})
def predict(self, X):
X = self._check_array(X)
return self.sess.run(self.new_y_, feed_dict={self.new_features: X})
def evaluate(self, X, Y):
X = self._check_array(X)
return self.sess.run(self.new_loss, feed_dict={self.new_features: X,
self.new_targets: Y})
def _check_array(self, ndarray):
ndarray = np.array(ndarray)
if len(ndarray.shape) == 1:
ndarray = np.reshape(ndarray, (1, ndarray.shape[0]))
return ndarray
def load_ppg_spectrum(ppg_path):
#TODO: read name ppg_data in ppg_path files
ppg_data = {}
ppg_dim = 0
for root, dirs, files in os.walk(ppg_path):
for ppg_file in files:
if ".scp" in ppg_file:
continue
with open(os.path.join(root,ppg_file),'r') as fp:
lines = fp.readlines()
name = ""
start_id = 0
end_id =0
for idx, line in enumerate(tqdm(lines)):
if '[' in line:
name = line.split()[0]
start_id = idx + 1
if ppg_dim == 0:
ppg_dim = len(lines[start_id].split(" ")[2:-1])
if start_id != None and "]" in line:
end_id = idx
ppg_spec = [[float(ele) for ele in line.split(" ")[2:-1]] for line in lines[start_id:end_id+1]]
# ppg_spec = np.array([np.array([float(ele) for ele in line.split(" ")[2:-1]]) for line in lines[start_id:end_id+1]])
# ppg_spec = ppg_spec.astype(np.float32)
ppg_data[name] = ppg_spec
return ppg_data, ppg_dim
def make_ppg(n_list,name_type,ppg_data):
n_files = np.array([x[:-1] for x in open(n_list).readlines()])
# result_array = np.empty((0, ppg_dim))
result_array = []
#use n_files to append data
for i,n_ in enumerate(tqdm(n_files)):
if name_type == "train":
# name = n_.split('/')[-1].split('_')[0] + '_' + n_.split('/')[-1].split('_')[1]
# ppg_spec = ppg_data[name.upper()]
name = n_.split('/')[-1].split('.')[0] + '_' + n_.split('/')[-3].split('.')[0] + '_' + n_.split('/')[-2]
ppg_spec = ppg_data[name]
else:
name = n_.split('/')[-1].split('.')[0] + '_' + n_.split('/')[-3] + '_' + n_.split('/')[-2]
ppg_spec = ppg_data[name]
result_array += ppg_spec
# result_array = np.append(result_array, ppg_spec, axis=0)
return np.array(result_array)
#TODO: MAKE SURE DATA IS IN CORRECT FILE
def write_btn(encode_data,n_list,name_type,ppg_data,btn_path):
n_files = np.array([x[:-1] for x in open(n_list).readlines()])
current_index = 0
#use n_files to load data
for i,n_ in enumerate(tqdm(n_files)):
if name_type == "train":
name = n_.split('/')[-1].split('_')[0] + '_' + n_.split('/')[-1].split('_')[1]
cur_len = len(ppg_data[name.upper()])
btn_file = n_.split('/')[-1].split('.')[0] + ".txt"
else:
name = n_.split('/')[-1].split('.')[0] + '_' + n_.split('/')[-3] + "_" + n_.split('/')[-2]
cur_len = len(ppg_data[name])
btn_file = name + ".txt"
np.savetxt(os.path.join(btn_path,btn_file), encode_data[current_index: current_index + cur_len])
current_index += cur_len
if encode_data.shape[0] != current_index:
print("encode_data num:",encode_data.shape[0],"writed data:",current_index)
assert(encode_data.shape[0] == current_index)
if __name__ == '__main__':
print('Loading ppg Data ...')
ppg_data, ppg_dim = load_ppg_spectrum(ppg_path)
print('Making ppg Data ...')
train_data = make_ppg(train_list,"train",ppg_data)
valid_data = make_ppg(dev_list,"train",ppg_data)
test_data = make_ppg(test_list,"test",ppg_data)
print('Start training ...')
model_2 = Autoencoder(
n_features=ppg_dim,
learning_rate=0.0005,
n_hidden=[512,256,96],
alpha=0.0001,
)
# #load
if pretrain == True:
with model_2.graph.as_default():
saver = tf.train.Saver()
saver.restore(model_2.sess, pretrain_path)
else:
model_2.fit(
X=train_data,
Y=train_data,
epochs=20,
validation_data=(valid_data, valid_data),
test_data=(test_data, test_data),
batch_size=8,
)
### get code
train_encode = model_2.encode(train_data)
valid_encode = model_2.encode(valid_data)
test_encode = model_2.encode(test_data)
if tf.gfile.Exists(result_path):
print('Folder already exists: {}\n'.format(result_path))
else:
tf.gfile.MkDir(result_path)
print('Write bottleneck ...')
write_btn(train_encode,train_list,"train",ppg_data,result_path)
write_btn(valid_encode,dev_list,"train",ppg_data,result_path)
write_btn(test_encode,test_list,"test",ppg_data,result_path)
|
StarcoderdataPython
|
5102674
|
from django.db import models
from django.db.models.deletion import DO_NOTHING
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.search import index
from author.models import AuthorPage
from home.models import HomePage
# Create your models here.
class ArticleIndexPage(Page):
intro=RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('intro', classname="full")
]
class ArticlePage(Page):
intro = models.CharField(max_length=250)
banner=models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.DO_NOTHING,
)
body = RichTextField(blank=True)
head_foot=models.ForeignKey(HomePage,blank=True,null=True,related_name='head_foot',on_delete=DO_NOTHING)
author_info = models.ForeignKey(AuthorPage,blank=True,null=True,related_name='author_info',on_delete=DO_NOTHING)
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
FieldPanel('intro'),
FieldPanel('author_info'),
FieldPanel('head_foot'),
ImageChooserPanel('banner'),
FieldPanel('body', classname="full"),
]
|
StarcoderdataPython
|
9608725
|
<reponame>ptracton/ExperimentalPython
import PyQt5
import PyQt5.QtWidgets
class UI_CommonInfo(PyQt5.QtWidgets.QDialog):
"""
Display Common Player Information
"""
def __init__(self, parent=None):
super(UI_CommonInfo, self).__init__(parent)
self.topLayout = PyQt5.QtWidgets.QVBoxLayout()
self.hbox1 = PyQt5.QtWidgets.QHBoxLayout()
idLabel = PyQt5.QtWidgets.QLabel("ID Number:")
self.playerID = PyQt5.QtWidgets.QLabel("")
self.hbox1.addWidget(idLabel)
self.hbox1.addWidget(self.playerID)
birthDateLabel = PyQt5.QtWidgets.QLabel("Birthdate:")
self.playerBirthDate = PyQt5.QtWidgets.QLabel("")
self.hbox1.addWidget(birthDateLabel)
self.hbox1.addWidget(self.playerBirthDate)
heightLabel = PyQt5.QtWidgets.QLabel("Height:")
self.playerHeight = PyQt5.QtWidgets.QLabel("")
self.hbox1.addWidget(heightLabel)
self.hbox1.addWidget(self.playerHeight)
weightLabel = PyQt5.QtWidgets.QLabel("Weight:")
self.playerWeight = PyQt5.QtWidgets.QLabel("")
self.hbox1.addWidget(weightLabel)
self.hbox1.addWidget(self.playerWeight)
self.hbox2 = PyQt5.QtWidgets.QHBoxLayout()
seasonLabel = PyQt5.QtWidgets.QLabel("Season:")
self.playerSeason = PyQt5.QtWidgets.QLabel("")
self.hbox2.addWidget(seasonLabel)
self.hbox2.addWidget(self.playerSeason)
jerseyLabel = PyQt5.QtWidgets.QLabel("Jersey:")
self.playerJersey = PyQt5.QtWidgets.QLabel("")
self.hbox2.addWidget(jerseyLabel)
self.hbox2.addWidget(self.playerJersey)
positionLabel = PyQt5.QtWidgets.QLabel("Position:")
self.playerPosition = PyQt5.QtWidgets.QLabel("")
self.hbox2.addWidget(positionLabel)
self.hbox2.addWidget(self.playerPosition)
self.topLayout.addLayout(self.hbox1)
self.topLayout.addLayout(self.hbox2)
return
def getLayout(self):
return self.topLayout
|
StarcoderdataPython
|
1709926
|
from django.urls import path
from system.views import login_view, UserPasswordUpdateView, logout_view, UserInfo, UserLogout,Menu
app_name = "system"
urlpatterns = [
path('login', login_view, name="login"),
path('password_update', UserPasswordUpdateView.as_view(), name="password_update"),
path('logout', logout_view, name="logout"),
path('api/user_info', UserInfo.as_view()),
path('api/logout', UserLogout.as_view()),
path('menu',Menu.as_view())
]
|
StarcoderdataPython
|
11219109
|
import signal
import asyncio
import logging
import aiohttp
class Client(object):
def __init__(self, loop, handler, max_connections=30):
self.loop = loop
self.handler = handler
self.sem = asyncio.Semaphore(max_connections)#For preventing accidental DOS
self.queue = asyncio.PriorityQueue()
self.processing = set()
self.done = set()
self.failed = set()
self.active = True
self.log = logging.getLogger(__name__)
self.log.addHandler(logging.NullHandler())
def enqueue(self, priority, url):
if self.active:
self.queue.put_nowait((priority,url))
@asyncio.coroutine
def get_html(self,url):
html = None
err = None
self.log.info("Requesting: " + url)
resp = yield from aiohttp.get(url)
if resp.status == 200:
html = yield from resp.read()
else:
if resp.status == 404:
err = aiohttp.web.HTTPNotFound
else:
err = aiohttp.HttpProcessingError(
code=resp.status, message=resp.reason,
headers=resp.headers)
resp.close()
if(err):
raise err
return html
@asyncio.coroutine
def process_page(self, url):
self.log.info("Processing: " + url)
self.processing.add(url)
try:
with (yield from self.sem):#Limits number of concurrent requests
html = yield from self.get_html(url)
except aiohttp.HttpProcessingError as e:
self.log.error('{}: {} {}'.format(url,e.code,e.message))
self.failed.add(url)
else:
success = self.handler.handle(url, html)
if success:
self.done.add(url)
else:
self.failed.add(url)
# finally:
# self.processing.remove(url)
@asyncio.coroutine
def batch_request(self):
while True:
try:
priority, url = yield from asyncio.wait_for(self.queue.get(),5)
self.loop.create_task(self.process_page(url))
except asyncio.TimeoutError:
self.log.info("No more requests.")
break
while self.processing:
self.log.debug("{} tasks still processing.".format(len(self.processing)))
yield from asyncio.sleep(5)
def launch(self, urls):
# queue up initial urls
for url in urls:
self.enqueue(*url)
task = self.loop.create_task(self.batch_request())
try:
self.loop.add_signal_handler(signal.SIGINT, self.shutdown)
except RuntimeError:
pass
try:
self.loop.run_until_complete(task)
except asyncio.CancelledError:
pass
def shutdown(self):
self.log.warning("Shutdown initiated.")
self.active = False
try:
while True:
self.queue.get_nowait()
except asyncio.QueueEmpty:
pass
for task in asyncio.Task.all_tasks():
task.cancel()
|
StarcoderdataPython
|
11221889
|
<filename>deeplearning/data.py
#!/usr/bin/python
from __future__ import print_function
import os
import numpy as np
import random
import cv2
data_path = '/data/octirfseg/round3/final/'
image_rows = 432
image_cols = 32
batchsize = 149*8
def create_valid_data():
valid_data_path = os.path.join(data_path, 'valid')
images = os.listdir(valid_data_path)
total = len(images) / 2
print(total)
total = batchsize * int(total/batchsize)
imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
imgs_mask = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
i = 0
print('-'*30)
print('Creating validing images...')
print('-'*30)
for image_name in images:
if 'mask' in image_name:
continue
if i == total:
break
image_mask_name = image_name.split('.')[0] + '_mask.png'
img = cv2.imread(os.path.join(valid_data_path, image_name), cv2.IMREAD_GRAYSCALE)
img_mask = cv2.imread(os.path.join(valid_data_path, image_mask_name), cv2.IMREAD_GRAYSCALE)
img = np.array([img])
img_mask = np.array([img_mask])
imgs[i] = img
imgs_mask[i] = img_mask
if i % 100 == 0:
print('Done: {0}/{1} images'.format(i, total))
i += 1
print('Loading done.')
np.save('/data/octirfseg/round3/imgs_valid.npy', imgs)
np.save('/data/octirfseg/round3/imgs_mask_valid.npy', imgs_mask)
print('Saving to .npy files done.')
def load_valid_data():
imgs_valid = np.load('/data/octirfseg/imgs_valid.npy')
imgs_mask_valid = np.load('/data/octirfseg/imgs_mask_valid.npy')
imgs_valid = np.reshape(imgs_valid, (imgs_valid.shape[0], imgs_valid.shape[2], imgs_valid.shape[3], 1))
imgs_mask_valid = np.reshape(imgs_mask_valid, (imgs_mask_valid.shape[0], imgs_mask_valid.shape[2], imgs_mask_valid.shape[3], 1))
return imgs_valid, imgs_mask_valid
def create_train_data():
train_data_path = os.path.join(data_path, 'train')
images = os.listdir(train_data_path)
total = len(images) / 2
total = batchsize * int(total/batchsize)
maxvol = batchsize*100
imgs = np.ndarray((maxvol, 1, image_rows, image_cols), dtype=np.uint8)
imgs_mask = np.ndarray((maxvol, 1, image_rows, image_cols), dtype=np.uint8)
gi = 0
i = 0
print('-'*30)
print('Creating training images...')
print('-'*30)
for image_name in images:
if 'mask' in image_name:
continue
if i == maxvol:
print('Saving into shard...')
np.save("/data/octirfseg/round3/npyarrays/imgs_train-%03d.npy" % gi, imgs)
np.save("/data/octirfseg/round3/npyarrays/imgs_mask_train-%03d.npy" % gi, imgs_mask)
i = 0
gi += 1
image_mask_name = image_name.split('.')[0] + '_mask.png'
img = cv2.imread(os.path.join(train_data_path, image_name), cv2.IMREAD_GRAYSCALE)
img_mask = cv2.imread(os.path.join(train_data_path, image_mask_name), cv2.IMREAD_GRAYSCALE)
img = np.array([img])
img_mask = np.array([img_mask])
imgs[i] = img
imgs_mask[i] = img_mask
if i % 100 == 0:
print('Done: {0}/{1} images, {2} vols'.format(gi*maxvol + i, total, gi))
i += 1
print('Loading done.')
def find_max_vol_id():
maxid = 0
for f in os.listdir("/data/octirfseg/npyarrays/"):
if "train-" in f:
volid = int(f.split("-")[-1].split(".")[0])
if maxid < volid:
maxid = volid
return maxid
def generate_arrays_from_file(mean,std,batchsize):
maxvolid = find_max_vol_id()
while True:
vols = range(0, maxvolid)
random.shuffle(vols)
for volid in vols:
imgs_train, imgs_mask_train = load_train_data(volid)
imgs_train -= mean
imgs_train /= std
for i in range(0, imgs_train.shape[0], batchsize):
batch_x = imgs_train[i:i+batchsize]
batch_y = imgs_mask_train[i:i+batchsize]
batch_x = np.reshape(batch_x, (batch_x.shape[0], batch_x.shape[2], batch_x.shape[3], 1))
batch_y = np.reshape(batch_y, (batch_y.shape[0], batch_y.shape[2], batch_y.shape[3], 1))
yield (batch_x, batch_y)
def load_train_data(vol):
imgs_train = np.load("/data/octirfseg/npyarrays/imgs_train-%03d.npy" % vol)
imgs_train = imgs_train.astype('float32')
imgs_mask_train = np.load("/data/octirfseg/npyarrays/imgs_mask_train-%03d.npy" % vol)
imgs_mask_train = imgs_mask_train.astype('float32')
imgs_mask_train /= 255. # scale masks to [0, 1]
return imgs_train, imgs_mask_train
if __name__ == '__main__':
create_valid_data()
create_train_data()
|
StarcoderdataPython
|
11386898
|
"""
This module provides a Python API to shell functions coming
from a sourced shell script.
"""
from .core import config
__version__ = '0.2.1'
# Expose only specific stuff
__all__ = ['config']
|
StarcoderdataPython
|
3377559
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup
VERSION = "0.1.10"
URL = "https://github.com/chainsquad/graphene-healthchecker"
setup(
name="graphene-healthchecker",
version=VERSION,
description="Python library for RPC-healthchecking for graphene blockchains",
download_url="{}/tarball/{}".format(URL, VERSION),
author="ChainSquad GmbH",
author_email="<EMAIL>",
maintainer="<NAME>",
maintainer_email="<EMAIL>",
url=URL,
keywords=["graphene", "blockchain", "health", "api", "rpc"],
packages=["graphene_health"],
classifiers=[
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: Financial and Insurance Industry",
"Topic :: Office/Business :: Financial",
],
entry_points={"console_scripts": ["graphenehealth = graphene_health.cli:main"]},
install_requires=open("requirements.txt").readlines(),
setup_requires=["pytest-runner"],
tests_require=["pytest"],
include_package_data=True,
)
|
StarcoderdataPython
|
388157
|
<filename>notes/design/low-level/case-studies/parking-lot/parking_lot/commands/CommandStatus.py
from commands.AbstractCommand import AbstractCommand
class CommandStatus(AbstractCommand):
def execute(self):
return self.parking_lot.get_status()
|
StarcoderdataPython
|
1996162
|
<reponame>avineshpvs/vldb2018-sherlock
#!/usr/bin/python
# ---------------------------------------------------------------------------
# File: populate.py
# Version 12.8.0
# ---------------------------------------------------------------------------
# Licensed Materials - Property of IBM
# 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
# Copyright IBM Corporation 2009, 2017. All Rights Reserved.
#
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with
# IBM Corp.
# ---------------------------------------------------------------------------
"""
Reading a MIP problem and generating multiple solutions.
To run this example, command line arguments are required:
python populate.py <filename>
"""
from __future__ import print_function
import sys
import cplex
from cplex.exceptions import CplexSolverError
epszero = 1e-10
def populate(filename):
c = cplex.Cplex(filename)
# set the solution pool relative gap parameter to obtain solutions
# of objective value within 10% of the optimal
c.parameters.mip.pool.relgap.set(0.1)
try:
c.populate_solution_pool()
except CplexSolverError:
print("Exception raised during populate")
return
print()
# solution.get_status() returns an integer code
print("Solution status = ", c.solution.get_status(), ":", end=' ')
# the following line prints the corresponding string
print(c.solution.status[c.solution.get_status()])
numcols = c.variables.get_num()
# Print information about the incumbent
print()
print("Objective value of the incumbent = ",
c.solution.get_objective_value())
x = c.solution.get_values()
for j in range(numcols):
print("Incumbent: Column %d: Value = %10f" % (j, x[j]))
# Print information about other solutions
print()
numsol = c.solution.pool.get_num()
print("The solution pool contains %d solutions." % numsol)
numsolreplaced = c.solution.pool.get_num_replaced()
print("%d solutions were removed due to the solution pool "
"relative gap parameter." % numsolreplaced)
numsoltotal = numsol + numsolreplaced
print("In total, %d solutions were generated." % numsoltotal)
meanobjval = c.solution.pool.get_mean_objective_value()
print("The average objective value of the solutions is %.10g." %
meanobjval)
# write out the objective value of each solution and its
# difference to the incumbent
names = c.solution.pool.get_names()
print()
print("Solution Objective Number of variables")
print(" value that differ compared to")
print(" the incumbent")
for i in range(numsol):
objval_i = c.solution.pool.get_objective_value(i)
x_i = c.solution.pool.get_values(i)
# compute the number of variables that differ in solution i
# and in the incumbent
numdiff = 0
for j in range(numcols):
if abs(x_i[j] - x[j]) > epszero:
numdiff = numdiff + 1
print("%-15s %-10g %d / %d" %
(names[i], objval_i, numdiff, numcols))
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: populate.py filename")
print(" filename Name of a file, with .mps, .lp, or .sav")
print(" extension, and a possible, additional .gz")
print(" extension")
sys.exit(-1)
populate(sys.argv[1])
|
StarcoderdataPython
|
11295001
|
# -*- coding: utf-8 -*-
import scrapy
from urllib import parse
import re
import json
import datetime
import logging
from w3lib.html import remove_tags
from items import WeiboVMblogsItem, WeiboVCommentsItem
class WeiboVSpider(scrapy.Spider):
name = 'weibo_v'
logger = logging.getLogger(name)
allowed_domains = ['www.weibo.com', 'www.weibo.cn']
start_urls = ['http://v6.bang.weibo.com/czv/domainlist?luicode=40000050/']
headers = {
"Accept": "application/json, text/plain, */*",
"X-Requested-With": "XMLHttpRequest",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.8",
"Connection": "keep-alive",
"Host": "m.weibo.cn",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
}
mblog_pages = 2
def input_process(self, value):
value = remove_tags(value)
value = value.replace("...全文", "")
value = value.replace("\u200b", "")
return value
def extract_num(self, text, prefix=""):
# 从字符串中提取出数字,可指定数字的前缀字符串
match_re = re.match(".*%s?(\d+).*" % prefix, text)
if match_re:
nums = int(match_re.group(1))
else:
nums = 0
return nums
def extract_json(self, text):
# 从字符串中提取出JSON
match_re = re.match(".*?({.*}).*", text)
if match_re:
json_data = match_re.group(1)
else:
json_data = {}
return json_data
def parse(self, response):
self.logger.debug('parse url: {0}'.format(response.url))
domains = response.css('.clearfix>li>a')
for domain in domains:
domain_url = domain.css("::attr(href)").extract_first("")
domain_name = domain.css("::text").extract_first("")
next_url = parse.urljoin(response.url, domain_url)
yield scrapy.Request(url=next_url, meta={"domain": domain_name}, dont_filter=True, callback=self.parse_domain)
def parse_domain(self, response):
self.logger.debug('parse_domain url: {0}'.format(response.url))
domain = response.meta.get("domain", "")
relink = '"uid":"(.*?)"'
v_ids = re.findall(relink, response.text)
for v_id in v_ids:
next_url = "https://m.weibo.cn/api/container/getIndex?type=uid&value={0}&containerid=107603{1}".format(v_id, v_id)
headers = self.headers
headers.update({"Referer": "https://m.weibo.cn/u/{0}".format(v_id)})
meta_dict = {"domain": domain, "uid": v_id}
for i in range(self.mblog_pages):
next_page_url = "{0}&page={1}".format(next_url, i+11)
yield scrapy.Request(url=next_page_url, meta=meta_dict, headers=headers, dont_filter=True, callback=self.parse_mblog)
def parse_mblog(self, response):
self.logger.debug('parse_mblog url: {0}'.format(response.url))
domain = response.meta.get("domain","")
uid = response.meta.get("uid", "")
json_data = json.loads(self.extract_json(response.text.strip()))
if json_data["ok"]:
for card in json_data["cards"]:
if "mblog" in card:
item = WeiboVMblogsItem()
item["domain"] = domain
item["uid"] = uid
mblog_id = card["mblog"]["id"]
item["mblog_id"] = mblog_id
mblog_content = card["mblog"]["text"]
if "retweeted_status" in card["mblog"]:
retweeted_text = card["mblog"]["retweeted_status"]["text"]
mblog_content = "//".join([mblog_content, retweeted_text])
item["mblog_content"] = self.input_process(mblog_content)
item["created_time"] = card["mblog"]["created_at"]
item["crawled_time"] = datetime.datetime.now()
yield item
next_url = "https://m.weibo.cn/api/comments/show?id={0}&page=1".format(mblog_id)
headers = self.headers
headers.update({"Referer": "https://m.weibo.cn/status/{0}".format(mblog_id)})
yield scrapy.Request(url=next_url, headers=headers, dont_filter=True, callback=self.parse_comm)
def parse_comm(self, response):
self.logger.debug('parse_comm url: {0}'.format(response.url))
page = self.extract_num(response.url, prefix="page=")
mblog_id = self.extract_num(response.url, prefix="id=")
json_data = json.loads(self.extract_json(response.text.strip()))
if json_data["ok"]:
for entry in json_data["data"]:
content = remove_tags(entry["text"])
if content:
item = WeiboVCommentsItem()
item["mblog_id"] = mblog_id
item["uid"] = entry["user"]["id"]
item["comment_id"] = entry["id"]
item["comment_content"] = remove_tags(entry["text"])
item["created_time"] = entry["created_at"]
item["crawled_time"] = datetime.datetime.now()
yield item
next_url = response.url.replace("page={0}".format(page), "page={0}".format(page+1))
headers = self.headers
headers.update({"Referer": "https://m.weibo.cn/status/{0}".format(mblog_id)})
yield scrapy.Request(url=next_url, headers=headers, dont_filter=True, callback=self.parse_comm)
|
StarcoderdataPython
|
94113
|
import six
class InvalidPaddingError(Exception):
pass
class Padding(object):
"""Base class for padding and unpadding."""
def __init__(self, block_size):
self.block_size = block_size
def pad(self, value):
raise NotImplementedError('Subclasses must implement this!')
def unpad(self, value):
raise NotImplementedError('Subclasses must implement this!')
class PKCS5Padding(Padding):
"""Provide PKCS5 padding and unpadding."""
def pad(self, value):
if not isinstance(value, six.binary_type):
value = value.encode()
padding_length = (self.block_size - len(value) % self.block_size)
padding_sequence = padding_length * six.b(chr(padding_length))
value_with_padding = value + padding_sequence
return value_with_padding
def unpad(self, value):
# Perform some input validations.
# In case of error, we throw a generic InvalidPaddingError()
if not value or len(value) < self.block_size:
# PKCS5 padded output will always be at least 1 block size
raise InvalidPaddingError()
if len(value) % self.block_size != 0:
# PKCS5 padded output will be a multiple of the block size
raise InvalidPaddingError()
if isinstance(value, six.binary_type):
padding_length = value[-1]
if isinstance(value, six.string_types):
padding_length = ord(value[-1])
if padding_length == 0 or padding_length > self.block_size:
raise InvalidPaddingError()
def convert_byte_or_char_to_number(x):
return ord(x) if isinstance(x, six.string_types) else x
if any([padding_length != convert_byte_or_char_to_number(x)
for x in value[-padding_length:]]):
raise InvalidPaddingError()
value_without_padding = value[0:-padding_length]
return value_without_padding
class OneAndZeroesPadding(Padding):
"""Provide the one and zeroes padding and unpadding.
This mechanism pads with 0x80 followed by zero bytes.
For unpadding it strips off all trailing zero bytes and the 0x80 byte.
"""
BYTE_80 = 0x80
BYTE_00 = 0x00
def pad(self, value):
if not isinstance(value, six.binary_type):
value = value.encode()
padding_length = (self.block_size - len(value) % self.block_size)
one_part_bytes = six.b(chr(self.BYTE_80))
zeroes_part_bytes = (padding_length - 1) * six.b(chr(self.BYTE_00))
padding_sequence = one_part_bytes + zeroes_part_bytes
value_with_padding = value + padding_sequence
return value_with_padding
def unpad(self, value):
value_without_padding = value.rstrip(six.b(chr(self.BYTE_00)))
value_without_padding = value_without_padding.rstrip(
six.b(chr(self.BYTE_80)))
return value_without_padding
class ZeroesPadding(Padding):
"""Provide zeroes padding and unpadding.
This mechanism pads with 0x00 except the last byte equals
to the padding length. For unpadding it reads the last byte
and strips off that many bytes.
"""
BYTE_00 = 0x00
def pad(self, value):
if not isinstance(value, six.binary_type):
value = value.encode()
padding_length = (self.block_size - len(value) % self.block_size)
zeroes_part_bytes = (padding_length - 1) * six.b(chr(self.BYTE_00))
last_part_bytes = six.b(chr(padding_length))
padding_sequence = zeroes_part_bytes + last_part_bytes
value_with_padding = value + padding_sequence
return value_with_padding
def unpad(self, value):
if isinstance(value, six.binary_type):
padding_length = value[-1]
if isinstance(value, six.string_types):
padding_length = ord(value[-1])
value_without_padding = value[0:-padding_length]
return value_without_padding
class NaivePadding(Padding):
"""Naive padding and unpadding using '*'.
The class is provided only for backwards compatibility.
"""
CHARACTER = six.b('*')
def pad(self, value):
num_of_bytes = (self.block_size - len(value) % self.block_size)
value_with_padding = value + num_of_bytes * self.CHARACTER
return value_with_padding
def unpad(self, value):
value_without_padding = value.rstrip(self.CHARACTER)
return value_without_padding
PADDING_MECHANISM = {
'pkcs5': PKCS5Padding,
'oneandzeroes': OneAndZeroesPadding,
'zeroes': ZeroesPadding,
'naive': NaivePadding
}
|
StarcoderdataPython
|
248179
|
import random
import argparse
import wordcloud
from wordcloud import WordCloud
def generate_background_image(words, out="output_image.png", layout_color="black", width=1200, height=800, step_size=50, bias=10):
'''
Generate an image of words in a given string using wordcloud module.
Argument:
words -- string of words separated by comma
out -- path to output image
layout_color -- background color
width -- width of image
height -- height of image
step_size -- difference between freqencies of words
bias -- lowest initial frequency of a word
Returns:
None
'''
word_list = words.split(',')[::-1]
text_list = []
for i, word in enumerate(word_list):
for j in range(i*step_size+bias):
text_list.append(word)
random.shuffle(text_list)
text_corpus = " ".join(text_list)
image = WordCloud(background_color=layout_color, height=height, width=width).generate(text_corpus)
image.to_file(out)
print("Image successfully saved to {}".format(out))
|
StarcoderdataPython
|
3205474
|
import django
from django.forms import MultiValueField, CharField
from attributesjsonfield.widgets import AttributesJSONWidget
class AttributesJSONField(MultiValueField):
""" """
widget = AttributesJSONWidget
def __init__(self, *args, attributes=None, require_all_fields=False, **kwargs):
self.attributes = attributes
self.clean_attributes = []
if self.attributes:
for attr in self.attributes:
is_dict = type(attr) == dict
field = attr["field"] if is_dict else attr
if is_dict:
label = attr.get("verbose_name", field)
required = attr.get("required", True)
else:
label = field
required = True
self.clean_attributes.append(
{
"field": field,
"label": label,
"name": field,
"choices": attr.get("choices") if is_dict else None,
"required": required,
"default": attr.get("default") if is_dict else None,
"data_type": attr.get("data_type") if is_dict else None,
}
)
else:
self.clean_attributes = None
fields = [
CharField(
label=attr["label"],
initial=attr.get("default"),
required=attr["required"],
)
for attr in self.clean_attributes
]
self.widget = AttributesJSONWidget(attributes_json=self.clean_attributes)
if django.VERSION >= (3, 1):
# MultiValueField does not receive as kwargs the encoder or decoder
kwargs.pop("encoder")
kwargs.pop("decoder")
super().__init__(fields=fields, require_all_fields=require_all_fields, **kwargs)
def compress(self, data_list):
if data_list:
data = {}
for i, attribute in enumerate(self.clean_attributes):
data[attribute["name"]] = data_list[i]
return data
return None
|
StarcoderdataPython
|
3548298
|
<reponame>jabozzo/delta_sigma_pipe_lascas_2020
#! /usr/bin/env python
import parsec as psc
def lexme(parser):
return parser << psc.spaces()
def int_number(self):
'''Parse int number.'''
return psc.regex(r'-?(0|[1-9][0-9]*)').parsecmap(int)
def float_number(self):
'''Parse float number.'''
return psc.regex('-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][+-]?[0-9]+)?').parsecmap(float)
def word(self):
return psc.many1(psc.letter()).parsecmap(lambda x: ''.join(x))
def words(self, n=1):
return psc.separated(self.word(), psc.spaces(), n, n, end=False).parsecmap(lambda x: ' '.join(x))
|
StarcoderdataPython
|
101655
|
import string
class Automata:
"""Class automaton"""
def __init__(self, filename=""):
if filename is "":
self.symboles = []
self.states = {}
self.initialStates = []
self.finalStates = []
else:
self.symboles = []
self.states = {}
self.initialStates = []
self.finalStates = []
try:
content, transition, initial, final = self.read_automaton_from_file(filename)
except Exception as e:
print("Error loading the automata from file")
raise e
self.set_symboles(content[0])
self.add_number_state(content[1])
self.add_initials(initial)
self.add_finals(final)
self.add_transitions(transition)
def set_symboles(self, size: int):
for i in range(size):
self.symboles.append(string.ascii_lowercase[i])
def add_finals(self, final_list: list):
for state in final_list:
self.add_final(int(state))
def add_final(self, finalState: int):
if finalState not in self.finalStates:
if finalState in self.states:
self.finalStates.append(int(finalState))
else:
print(finalState + "state not in States of the FA")
else:
print(str(finalState) + "state already final")
def remove_final(self, finalRemove):
if finalRemove in self.finalStates:
self.finalStates.remove(finalRemove)
else:
print(finalRemove + " not in final states")
def add_initials(self, initial_list: list):
for state in initial_list:
self.initialStates.append(int(state))
def add_number_state(self, size: int):
self.states = dict.fromkeys(range(size))
for state in self.states:
self.states[state] = {}
def add_transition(self, state: int, char, end_state: int):
if char in self.states[state]:
self.states[state][char].append(end_state)
else:
self.states[state][char] = [end_state]
def add_transitions(self, transitions: list):
for trans in transitions:
self.add_transition(trans[0], trans[1], trans[2])
def has_state(self, testState:int):
return (testState in self.states)
def has_symbol(self, testSymbol:str):
return (testSymbol in self.symboles)
def has_initialState(self, testInitialState:str):
return (testInitialState in self.initialStates)
def has_finalStates(self, testFinalState:str):
return (testFinalState in self.finalStates)
def read_automaton_from_file(self, filename: str):
with open("../res/" + filename) as f:
content = f.readlines()
content = list(map(lambda s: s.strip(), content))
# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
if len(content) < 6:
content = None
raise Exception("Abort ! File is too small.")
try:
content[0] = int(content[0])
except ValueError as e:
content = None
print("Can't read number of symbols in alphabet !")
print("Error: " + str(e))
try:
content[1] = int(content[1])
except ValueError as e:
content = None
raise Exception("Can't read number of states in alphabet ! Error: " + str(e))
initial = content[2].split(" ")
if int(initial[0]) == len(initial) - 1:
del initial[0]
else:
initial = None
raise Exception("Incorrect initial states!")
final = content[3].split(" ")
if int(final[0]) == len(final) - 1:
del final[0]
else:
final = None
raise Exception("Incorrect final states!")
transitions = []
for i in range(5, len(content)):
transitions.append((int(content[i][0]), content[i][1], int(content[i][2])))
return content, transitions, initial, final
def __str__(self):
return ("States:" + str(self.states) +
"\nAlphabet: " + str(self.symboles) +
"\nInitial states: " + str(self.initialStates) +
"\nFinal states: " + str(self.finalStates))
def toFile(self, output="../output.txt"):
with open(output, "w") as f:
f.write(str(len(self.symboles)) + "\n")
f.write(str(len(self.states)) + "\n")
f.write(str(len(self.initialStates)) + " ")
for state in self.initialStates:
f.write(str(state) + " ")
f.write("\n")
f.write(str(len(self.finalStates)) + " ")
for state in self.finalStates:
f.write(str(state) + " ")
f.write("\n")
f.write(str(len(self.states)) + "\n")
for state in self.states:
for char in self.states[state]:
for sta in self.states[state][char]:
f.write(str(state) + str(char) + str(sta) + "\n")
def toUML(self, output="output.txt"):
# TODO
pass
|
StarcoderdataPython
|
337768
|
<reponame>OutHereVR/c4d-prototype-converter
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import c4d
import collections
from .utils import UndoHandler, find_root
class Error(Exception):
'''
This exception is generally raised if an exception in a modeling
function occurred. For instance, if the required preconditions for
the "Current State to Object" command are not met, it will return no
object in which case this exception is raised.
'''
class Kernel(object):
'''
The *Kernel* class provides all modeling functionality. Some
modeling functions require a document to operate in, others may
even require it to be the active Cinema 4D document as it may use
:func:`c4d.CallCommand` to achieve its goal. Yet, the *Kernel*
does not necessarily be initialized with a document. You will be
able to use all functions that do not require it. Some methods are
even static as they require no specialised context.
To create a temporary document, you should use the
:class:`nr.c4d.utils.TemporaryDocument` class.
'''
def __init__(self, doc=None):
super(Kernel, self).__init__()
self._doc = doc
if doc is not None and not isinstance(doc, c4d.documents.BaseDocument):
raise TypeError('<doc> must be BaseDocument', type(doc))
@staticmethod
def triangulate(obj):
'''
Triangulates the PolygonObject *obj* in place.
:raise TypeError: If *obj* is not a PolygonObject.
:raise Error: When an unexpected error occurs.
'''
if not isinstance(obj, c4d.PolygonObject):
raise TypeError("<obj> must be a PolygonObject", type(obj))
result = c4d.utils.SendModelingCommand(c4d.MCOMMAND_TRIANGULATE, [obj])
if not result:
raise Error("Triangulate failed")
@staticmethod
def untriangulate(obj, angle_rad=None):
'''
Untriangulates the PolygonObject *obj* in place.
:param obj: The :class:`c4d.PolygonObject` to untriangulate.
:param angle_rad: The untriangulate angle radius. Defaults to 0.1°.
:raise TypeError: If *obj* is not a PolygonObject.
:raise Error: When an unexpected error occurs.
'''
if not isinstance(obj, c4d.PolygonObject):
raise TypeError("<obj> must be a PolygonObject", type(obj))
if angle_rad is None:
angle_rad = c4d.utils.Rad(0.1)
bc = c4d.BaseContainer()
bc.SetFloat(c4d.MDATA_UNTRIANGULATE_ANGLE_RAD, angle_rad)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_UNTRIANGULATE, [obj], doc=None, bc=bc)
if not result:
raise Error("Untriangulate failed")
@staticmethod
def optimize(obj, tolerance=0.01, points=True, polygons=True,
unused_points=True):
'''
Optimizes the PolygonObject *obj* using the Cinema 4D
"Optimize" command. The parameters to this method reflect
the parameters of the Cinema 4D command.
:raise TypeError: If *obj* is not a PolygonObject.
:raise Error: When an unexpected error occurs.
'''
if not isinstance(obj, c4d.PolygonObject):
raise TypeError("<obj> must be a PolygonObject", type(obj))
bc = c4d.BaseContainer()
bc.SetFloat(c4d.MDATA_OPTIMIZE_TOLERANCE, tolerance)
bc.SetBool(c4d.MDATA_OPTIMIZE_POINTS, points)
bc.SetBool(c4d.MDATA_OPTIMIZE_POLYGONS, polygons)
bc.SetBool(c4d.MDATA_OPTIMIZE_UNUSEDPOINTS, unused_points)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_OPTIMIZE, [obj], doc=None, bc=bc)
if not result:
raise Error("Optimize failed")
def _assert_doc(self, method):
'''
Private. Raises a :class:`RuntimeError` if the *Kernel* was
not initialized with a Cinema 4D document. '''
if self._doc is None:
raise RuntimeError(
"Kernel method '{0}' requires a Cinema 4D document but "
"the Kernel was initialized with None".format(method))
assert isinstance(self._doc, c4d.documents.BaseDocument)
def current_state_to_object(self, obj):
'''
Executes the Cinema 4D "Current State to Object" on *obj* and
returns the resulting object. The object will be temporarily
moved into the document the *Kernel* was initialized with. If
you want to keep links (eg. texture tag material links), the
*Kernel* should have been initialized with the objects document.
.. note:: All parent objects of *obj* will be moved with it as
it may have influence on the outcome (eg. deformers applied
on a hierarchy in a Null-Object).
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized
with a document.
:raise TypeError: If *obj* is not a BaseObject.
:raise Error: When an unexpected error occurs.
'''
self._assert_doc('current_state_to_object')
if not isinstance(obj, c4d.BaseObject):
raise TypeError("<obj> must be a BaseObject", type(obj))
doc = self._doc
root = find_root(obj)
with UndoHandler() as undo:
undo.location(root)
root.Remove()
doc.InsertObject(root)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_CURRENTSTATETOOBJECT, [obj], doc=doc)
if not result:
raise Error("Current State to Object failed")
return result[0]
def connect_objects(self, objects):
'''
Joins all PolygonObjects and SplineObjects the list *objects*
into a single object using the Cinema 4D "Connect Objects"
command.
This method will move *all* objects to the internal document
temporarily before joining them into one object.
:param objects: A list of :class:`c4d.BaseObject`.
:return: The new connected object.
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized
with a document.
:raise TypeError:
- If *objects* is not iterable
- If an element of *objects* is not a BaseObject
:raise Error: When an unexpected error occurs.
.. important:: The returned object axis is located at the world
center. If you want to mimic the real "Connect Objects" command
in that it positions the axis at the location of the first
object in the list, use the :func:`nr.c4d.utils.move_axis`
function.
'''
self._assert_doc('connect_objects')
if not isinstance(objects, collections.Iterable):
raise TypeError("<objects> must be iterable", type(objects))
doc = self._doc
root = c4d.BaseObject(c4d.Onull)
with UndoHandler() as undo:
undo.location(root)
doc.InsertObject(root)
# Move all objects under the new root object temporarily.
for obj in objects:
if not isinstance(obj, c4d.BaseObject):
message = "element of <objects> must be BaseObject"
raise TypeError(message, type(obj))
undo.location(obj)
undo.matrix(obj)
mg = obj.GetMg()
obj.Remove()
obj.InsertUnder(root)
obj.SetMl(mg)
result = c4d.utils.SendModelingCommand(
c4d.MCOMMAND_JOIN, root.GetChildren(), doc=doc)
if not result:
raise Error("Connect Objects failed")
result[0].SetMl(c4d.Matrix())
return result[0]
def polygon_reduction(self, obj, strength, meshfactor=1000,
coplanar=True, boundary=True, quality=False):
'''
Uses the Cinema 4D "Polygon Reduction" deformer to create a
copy of *obj* with reduced polygon count. The parameters to
this function reflect the parameters in the "Polygon Reduction"
deformer. :meth:`current_state_to_object` is used to obtain
the deformed state of *obj*.
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized with a document.
:raise TypeError: If *obj* is not a BaseObject.
:raise Error: When an unexpected error occurs.
.. important:: In rare cases, the returned object can be a null
object even though the input object was a polygon object. In that
case, the null object contains the reduced polygon object as a
child.
'''
self._assert_doc('polygon_reduction')
if not isinstance(obj, c4d.BaseObject):
raise TypeError("<obj> must be BaseObject", type(obj))
root = c4d.BaseObject(c4d.Onull)
deformer = c4d.BaseObject(c4d.Opolyreduction)
deformer.InsertUnder(root)
deformer[c4d.POLYREDUCTIONOBJECT_STRENGTH] = strength
deformer[c4d.POLYREDUCTIONOBJECT_MESHFACTOR] = meshfactor
deformer[c4d.POLYREDUCTIONOBJECT_COPLANAR] = coplanar
deformer[c4d.POLYREDUCTIONOBJECT_BOUNDARY] = boundary
deformer[c4d.POLYREDUCTIONOBJECT_QUALITY] = quality
doc = self._doc
with UndoHandler() as undo:
undo.location(root)
undo.location(obj)
undo.matrix(obj)
doc.InsertObject(root)
obj.Remove()
obj.InsertAfter(deformer)
root = self.current_state_to_object(root)
# Root will definetely be a Null-Object, so we need to go
# down one object at least.
result = root.GetDown()
if not result:
raise Error("Polygon Reduction failed")
result.Remove()
return result
def boole(self, obja, objb, boole_type, high_quality=True,
single_object=False, hide_new_edges=False, break_cut_edges=False,
sel_cut_edges=False, optimize_level=0.01):
'''
Uses the Cinema 4D "Boole Object" to perform a boolean
volumetric operation on *obja* and *objb* and returns the
resulting object hierarchy. The method parameters reflect
the "Boole Object" parameters.
:param obja: The first object for the boole operation.
:param objb: The second object for the boole operation.
:param boole_type: One of the boole modes:
- :data:`c4d.BOOLEOBJECT_TYPE_UNION`
- :data:`c4d.BOOLEOBJECT_TYPE_SUBTRACT`
- :data:`c4d.BOOLEOBJECT_TYPE_INTERSECT`
- :data:`c4d.BOOLEOBJECT_TYPE_WITHOUT`
:param high_quality: See Boole Object documentation.
:param single_object: See Boole Object documentation.
:param hide_new_edges: See Boole Object documentation.
:param break_cut_edges: See Boole Object documentation.
:param sel_cut_edges: See Boole Object documentation.
:param optimize_level: See Boole Object documentation.
:return: The result of the Boole operation converted using
:meth:`current_state_to_object`.
:requires:
- The *Kernel* must be initialized with a document.
:raise RuntimeError: If the *Kernel* was not initialized
with a document.
:raise TypeError: If *obja* or *objb* is not a BaseObject.
:raise ValueError: If *boole_type* is invalid.
:raise Error: When an unexpected error occurs.
'''
self._assert_doc('boole')
choices = (
c4d.BOOLEOBJECT_TYPE_UNION, c4d.BOOLEOBJECT_TYPE_SUBTRACT,
c4d.BOOLEOBJECT_TYPE_INTERSECT, c4d.BOOLEOBJECT_TYPE_WITHOUT)
if boole_type not in choices:
raise ValueError("unexpected value for <boole_type>", boole_type)
if not isinstance(obja, c4d.BaseObject):
raise TypeError("<obja> must be BaseObject", type(obja))
if not isinstance(obja, c4d.BaseObject):
raise TypeError("<objb> must be BaseObject", type(objb))
boole = c4d.BaseObject(c4d.Oboole)
boole[c4d.BOOLEOBJECT_TYPE] = boole_type
boole[c4d.BOOLEOBJECT_HIGHQUALITY] = high_quality
boole[c4d.BOOLEOBJECT_SINGLE_OBJECT] = single_object
boole[c4d.BOOLEOBJECT_HIDE_NEW_EDGES] = hide_new_edges
boole[c4d.BOOLEOBJECT_BREAK_CUT_EDGES] = break_cut_edges
boole[c4d.BOOLEOBJECT_SEL_CUT_EDGES] = sel_cut_edges
boole[c4d.BOOLEOBJECT_OPTIMIZE_LEVEL] = optimize_level
with UndoHandler() as undo:
undo.location(boole)
undo.location(obja)
undo.location(objb)
undo.matrix(obja)
undo.matrix(objb)
mga, mgb = obja.GetMg(), objb.GetMg()
obja.Remove(), objb.Remove()
obja.InsertUnder(boole), objb.InsertUnderLast(boole)
obja.SetMg(mga), objb.SetMg(mgb)
self._doc.InsertObject(boole)
return self.current_state_to_object(boole)
|
StarcoderdataPython
|
3540554
|
<filename>grid_cell_model_uniform.py
# Standard library imports
import errno
import os
import random
import time
import cPickle as pickle
import matplotlib.pyplot as plt
import numpy as np
import utilities as util
from pyNN.random import RandomDistribution, NumpyRNG
from pyNN.space import Grid2D
from pyNN.utility.plotting import Figure, Panel
import spynnaker8 as p
"""
Grid cell model with periodic boundary constraints
Connectivity: uniform
Broad feedforward input: i_offset
Velocity input: none
"""
p.setup(1) # simulation timestep (ms)
runtime = 30000 # ms
n_row = 50
n_col = 50
n_neurons = n_row * n_row
p.set_number_of_neurons_per_core(p.IF_curr_exp, 255)
self_connections = False # allow self-connections in recurrent grid cell network
rng = NumpyRNG(seed=77364, parallel_safe=True)
synaptic_weight = 0.05 # synaptic weight for inhibitory connections
synaptic_radius = 10 # inhibitory connection radius
centre_shift = 2 # number of neurons to shift centre of connectivity by
# Grid cell (excitatory) population
gc_neuron_params = {
"v_thresh": -50.0,
"v_reset": -65.0,
"v_rest": -65.0,
"i_offset": 0.8, # DC input
"tau_m": 20, # membrane time constant
"tau_refrac": 1.0,
}
exc_grid = Grid2D(aspect_ratio=1.0, dx=1.0, dy=1.0, x0=0, y0=0, z=0, fill_order='sequential')
# exc_space = p.Space(axes='xy', periodic_boundaries=((-n_col / 2, n_col / 2), (-n_row / 2, n_row / 2)))
v_init = RandomDistribution('uniform', low=-65, high=-55, rng=rng)
pop_exc_gc = p.Population(n_neurons,
p.IF_curr_exp(**gc_neuron_params),
cellparams=None,
initial_values={'v': v_init},
structure=exc_grid,
label="Excitatory grid cells"
)
# Create recurrent inhibitory connections
loop_connections = list()
for pre_syn in range(0, n_neurons):
presyn_pos = (pop_exc_gc.positions[pre_syn])[:2]
dir_pref = np.array(util.get_dir_pref(presyn_pos))
# Shift centre of connectivity in appropriate direction
shifted_centre = util.shift_centre_connectivity(presyn_pos, dir_pref, centre_shift, n_row, n_col)
for post_syn in range(0, n_neurons):
# If different neurons
if pre_syn != post_syn or self_connections:
postsyn_pos = (pop_exc_gc.positions[post_syn])[:2]
dist = util.get_neuron_distance_periodic(n_col, n_row, shifted_centre, postsyn_pos)
# Establish connection
if np.all(dist <= synaptic_radius):
# delay = util.normalise(dist, 1, 5)
delay = 1.0
singleConnection = (pre_syn, post_syn, synaptic_weight, delay)
loop_connections.append(singleConnection)
# Create inhibitory connections
proj_exc = p.Projection(
pop_exc_gc, pop_exc_gc, p.FromListConnector(loop_connections, ('weight', 'delay')),
p.StaticSynapse(),
receptor_type='inhibitory',
label="Excitatory grid cells inhibitory connections")
"""
RUN
"""
pop_exc_gc.record(['v', 'gsyn_inh', 'spikes'])
p.run(runtime)
"""
WRITE DATA
"""
# Write data to files
data_dir = "data/" + time.strftime("%Y-%m-%d_%H-%M-%S") + "/"
# Create directory
try:
os.makedirs(os.path.dirname(data_dir))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
# Excitatory population
# pickle.dump(pop_exc.get_data().segments[0].filter(name='v')[0],
# open(data_dir + "pop_exc_v.pkl", 'wb'),
# protocol=pickle.HIGHEST_PROTOCOL)
# pickle.dump(pop_exc.get_data().segments[0].filter(name='gsyn_exc')[0],
# open(data_dir + "pop_exc_gsyn_exc.pkl", 'wb'),
# protocol=pickle.HIGHEST_PROTOCOL)
# pickle.dump(pop_exc.get_data().segments[0].filter(name='gsyn_inh')[0],
# open(data_dir + "pop_exc_gsyn_inh.pkl", 'wb'),
# protocol=pickle.HIGHEST_PROTOCOL)
pickle.dump(pop_exc_gc.get_data().segments[0].spiketrains,
open(data_dir + "pop_exc_gc_spiketrains.pkl", 'wb'),
protocol=pickle.HIGHEST_PROTOCOL)
pickle.dump(pop_exc_gc.label, open(data_dir + "pop_exc_gc_label.pkl", 'wb'),
protocol=pickle.HIGHEST_PROTOCOL)
pickle.dump(pop_exc_gc.positions, open(data_dir + "pop_exc_gc_positions.pkl", 'wb'),
protocol=pickle.HIGHEST_PROTOCOL)
pickle.dump(gc_neuron_params, open(data_dir + "pop_exc_gc_parameters.pkl", 'wb'),
protocol=pickle.HIGHEST_PROTOCOL)
f = open(data_dir + "params.txt", "w")
f.write("Single population grid cell (periodic) model")
f.write("\nruntime=" + str(runtime))
f.write("\nn_row=" + str(n_row))
f.write("\nn_col=" + str(n_col))
f.write("\nsyn_weight=" + str(synaptic_weight))
f.write("\nsyn_radius=" + str(synaptic_radius))
f.write("\norientation_pref_shift=" + str(centre_shift))
f.write("\npop_exc=" + str(pop_exc_gc.describe()))
f.close()
rand_neurons = random.sample(range(0, n_neurons), 4)
neuron_sample = p.PopulationView(pop_exc_gc, rand_neurons)
# Plot
F = Figure(
# plot data for postsynaptic neuron
Panel(neuron_sample.get_data().segments[0].filter(name='v')[0],
ylabel="Membrane potential (mV)",
xlabel="Time (ms)",
data_labels=[neuron_sample.label], yticks=True, xticks=True, xlim=(0, runtime)
),
)
plt.savefig(data_dir + "sample_v.eps", format='eps')
plt.show()
F = Figure(
Panel(neuron_sample.get_data().segments[0].filter(name='gsyn_inh')[0],
ylabel="inhibitory synaptic conduction (nA)",
xlabel="Time (ms)",
data_labels=[neuron_sample.label], yticks=True, xticks=True, xlim=(0, runtime)
),
)
plt.savefig(data_dir + "sample_gsyn_inh.eps", format='eps')
plt.show()
F = Figure(
Panel(neuron_sample.get_data().segments[0].spiketrains,
yticks=True, xticks=True, markersize=2, xlim=(0, runtime)
),
)
rand_neurons = map(str, rand_neurons)
plt.yticks(np.arange(4), rand_neurons)
plt.savefig(data_dir + "sample_spikes.eps", format='eps')
plt.show()
# util.plot_gc_inh_connections([1325, 1275, 1326, 1276], pop_exc_gc.positions, synaptic_weight, loop_connections,
# n_col, n_row, synaptic_radius, orientation_pref_shift, data_dir)
# util.plot_neuron_init_order(pop_exc_gc.positions, data_dir)
gsyn_inh = pop_exc_gc.get_data().segments[0].filter(name='gsyn_inh')[0]
print("Max gsyn_inh=" + str(util.get_max_value_from_pop(gsyn_inh)))
# print("Min gsyn_inh=" + str(util.get_min_value_from_pop(gsyn_inh)))
print("Avg gsyn_inh=" + str(util.get_avg_gsyn_from_pop(gsyn_inh)))
print("Mean spike count: " + str(pop_exc_gc.mean_spike_count(gather=True)))
print("Max spike count: " + str(util.get_max_firing_rate(pop_exc_gc.get_data().segments[0].spiketrains)))
p.end()
print(data_dir)
|
StarcoderdataPython
|
9715458
|
import pandas as pd
import sklearn
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.decomposition import IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
if __name__ =='__main__':
dt_heart = pd.read_csv('./data/heart.csv')
print(dt_heart.head(5))
dt_features = dt_heart.drop(['target'], axis =1)
dt_target = dt_heart['target']
dt_features = StandarScaler().fit_tranform(dt_features)
X_train, X_test, y_train, y_test = train_test_split(dt_features, dt_target, test_size =0.3, random_state =42)
# Esto nos da la forma de la tabla para que tengan un mismo tamaño.
print(X_train.shape)
print(Y_train.shape)
|
StarcoderdataPython
|
156844
|
<filename>ChutesandLadders.py
import numpy as np
import copy
import time
# The dictionary of chutes and ladder.
chutes_ladders = {1: 38, 4: 14, 16: 6, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100, 98: 78, 95: 75, 93: 73, 87: 24, 64: 60, 62: 19, 56: 53, 49: 11, 48: 26}
cd_list = list(chutes_ladders.keys())
# Vector to solve for our result later
b = np.ones(101)
b[100] = 0
# Dictionary of dices: key is a face of that dice and value is its corresponding probability
black = {4:2/3, 0:1/3}
red = {6:1/3, 2:2/3}
green = {5:1/2, 1:1/2}
blue = {3:1}
def row_calculator(board, square_no, dice):
faces = list(dice.keys())
# blue dice only has one face on it, so I design a specific part for it
#since we flip the side of the equation, most of them are subtracted
#from the original value that specific point in the matrix
if dice == blue:
f1 = faces[0]
p1 = dice[f1]
if square_no + 3 < 100:
if square_no + f1 in cd_list:
board[square_no][chutes_ladders[square_no + f1]] -= p1
else:
board[square_no][square_no + f1] -= p1
else:
board[square_no][100] = -1
# for other dices
else:
#get the dice value
f1 = faces[0]
f2 = faces[1]
p1 = dice[f1]
p2 = dice[f2]
#algorithm
if square_no + f1 < 100:
if square_no+ f1 in cd_list:
board[square_no][chutes_ladders[square_no+f1]] -= p1
else:
board[square_no][square_no+f1] -= p1
if square_no+f2 in cd_list:
board[square_no][chutes_ladders[square_no+f2]] -= p2
else:
board[square_no][square_no+f2] -= p2
elif square_no + f2 < 100:
board[square_no][100] = -p1
if square_no + f2 in cd_list:
board[square_no][chutes_ladders[square_no + f2]] -= p2
else:
board[square_no][square_no + f2] -= p2
else:
board[square_no][100] = -1
def update(board, square_no, dice):
#initialize the value of the square to be 1
board[square_no][square_no] = 1
if square_no == 100:
return
#run the calculation based on the picked dice. 0 denotes black, 1 denotes red, 2 denotes green, and 3 denotes blue
if dice == 0:
row_calculator(board, square_no, black)
if dice == 1:
row_calculator(board, square_no, red)
if dice == 2:
row_calculator(board, square_no, green)
if dice == 3:
row_calculator(board, square_no, blue)
def number_of_moves(board, policy):
#update the board
for i in range(101):
update(board, i, policy[i])
try:
x = np.linalg.solve(board, b)
return x
# since we can not use blue dice on square 53 (which leads to infinite loop), the matrix lines from 53
#created by blue dice contain all 0.
# which leads to singular matrix and can not be solved. Return a valid value when an error is reached.
except np.linalg.LinAlgError as err:
if 'Singular matrix' in str(err):
return [float('inf')]
def update_policy(policy, x):
#check if the new policy makes the x value smaller
#compute bottom up
for i in range(99, -1, -1):
for j in range(4):
new_board = np.zeros((101, 101))
policy_new = copy.deepcopy(policy)
policy_new[i] = j
x_matrix = number_of_moves(new_board, policy_new)
x2 = x_matrix[0]
#if new policy improve optimal moves, get new policy and optimal moves
if x2 < x:
policy[i] = j
x = x2
return policy, x
def main():
start = time.time()
#use the green dice as the first set of policy, tests showing that initialize a all green dice policy results in best value
policy = [2 for i in range(101)]
moves = float('inf')
#number of trials
trials = 1
policy_old = copy.deepcopy(policy)
policy, moves = update_policy(policy, moves)
while policy_old != policy:
policy_old = copy.deepcopy(policy)
policy, moves = update_policy(policy, moves)
trials += 1
end = time.time()
time_run = end - start
print("Optimal Average Number of Moves Expected to Complete the Game: ",moves)
print(f"Execution time of the program is {time_run} seconds with {trials} trials.")
print("Final Policy, with 0 denotes black, 1 denotes red, 2 denotes green, and 3 denotes blue \n", policy)
return 0
main()
|
StarcoderdataPython
|
12836764
|
import logging
import requests
from .config import MeshConfiguration, ChebiConfiguration, EntrezConfiguration
from .parser import BasicParser, ChebiObjectParser
from .objbase import MeshObject
from .sparql import SparqlQuery, QueryTerm2UI
__all__ = ['MeshURI', 'MeshRDFRequest', 'MeshRDFResponse', 'MeshSearchRequest', 'MeshSearchResponse',
'ChebiRequest', 'ChebiSearchResponse', 'EntrezSearchRequest', 'EntrezSearchResponse',
'MeshESearchRequest', 'MeshESearchResponse']
MeshConfig = MeshConfiguration().load()
ChebiConfig = ChebiConfiguration().load()
EntrezConfig = EntrezConfiguration().load()
class BaseRequest(object):
def __init__(self, *args, **kwargs):
raise NotImplementedError('This method should be implemented by child class.')
def get_response(self):
raise NotImplementedError('This method should be implemented by child class.')
class BaseResponse(object):
def __init__(self, response, parser, **kwargs):
if not isinstance(response, requests.Response):
raise TypeError('Type of given response should be `requests.Response`.')
self.response = response
self.parser = parser()
self.content = None
self.parse()
def parse(self):
try:
self.content = self.parser.parse(self.response)
except Exception as ex:
print(self.response.url)
logging.exception(ex)
self.content = []
class MeshURI(object):
@classmethod
def build(cls, limit, year, format, inference, query, offset):
uri = MeshConfig.sparql.base_url + '?'
uri += 'query={}'.format(query)
uri += 'limit={}'.format(limit)
uri += 'year={}'.format(year)
uri += 'inference={}'.format(inference)
uri += 'offset={}'.format(offset)
return uri
class MeshRDFRequest(BaseRequest):
def __init__(self, fmt='json', inference=True, limit=10,
offset=0, query='', year='current'):
if not isinstance(query, SparqlQuery):
raise TypeError('Given `query` should be an instance of `SparqlQuery`.')
self.fmt = fmt
self.inference = inference
self.limit = limit
self.inference = 'true' if inference else 'false'
self.limit = limit
self.offset = offset
self.query = query
self.year = year
def get_response(self):
uri = MeshConfig.sparql.base_url + '?'
payload = {
'query': self.query,
'limit': self.limit,
'year': self.year,
'format': self.fmt,
'inference': self.inference,
'offset': self.offset
}
resp = None
try:
resp = requests.get(uri, params=payload)
except ex:
logging.exception(ex)
finally:
return resp
class MeshRDFResponse(BaseResponse):
def __init__(self, response, parser):
super(MeshRDFResponse, self).__init__(response, parser)
class MeshSearchRequest(BaseRequest):
def __init__(self, query='', exact=True):
self.query = query
self.exact = exact
def get_response(self):
d = MeshConfig.search.option
uri = MeshConfig.search.base_url + '?' + MeshConfig.search.query.format(query=self.query)
payload = {
"searchInField": d.searchInField.terms[1], # "termDescriptor"
"size": d.size,
"searchType": d.searchType[0] if self.exact else d.searchType[2],
"searchMethod": d.searchMethod[0], # "FullWord"
"sort": d.sort.Relevance
}
resp = None
try:
resp = requests.get(uri, params=payload)
except ex:
logging.exception(ex)
finally:
return resp
class MeshSearchResponse(BaseResponse):
def __init__(self, response, parser):
super(MeshSearchResponse, self).__init__(response, parser)
class MeshESearchRequest(BaseRequest):
def __init__(self, query='', exact=True, api_key=None):
self.query = query
self.exact = exact
self.api_key = MeshConfig.api_key if api_key is None else api_key
def get_response(self):
d = MeshConfig.esearch.option
uri = MeshConfig.esearch.base_url + '?' + MeshConfig.esearch.query.format(query=self.query)
if self.exact:
uri += '+AND+{}'.format(MeshConfig.esearch.cond.orgn_human)
payload = {k: d.get(k) for k in d.keys()}
if self.api_key is not None:
payload['api_key'] = self.api_key
resp = None
try:
resp = requests.get(uri, params=payload)
except ex:
logging.exceotion(ex)
finally:
return resp
class MeshESearchResponse(BaseResponse):
def __init__(self, response, parser):
super(MeshESearchResponse, self).__init__(response, parser)
class ChebiSearchRequest(BaseRequest):
def __init__(self, query='', exact=True):
self.query = query
self.exact = exact
def get_response(self):
d = ChebiConfig.search.option
uri = ChebiConfig.search.base_url + '?' + ChebiConfig.search.query.format(query=self.query)
payload = {k: d.get(k) for k in d.keys()}
payload['exact'] = 'true' if self.exact else 'false'
resp = None
try:
resp = requests.get(uri, params=payload)
except ex:
logging.exception(ex)
finally:
return resp
class ChebiSearchResponse(BaseResponse):
def __init__(self, response, parser):
super(ChebiSearchResponse, self).__init__(response, parser)
class EntrezSearchRequest(BaseRequest):
def __init__(self, query='', api_key=None, human_only=True):
self.query = query
self.api_key = EntrezConfig.api_key if api_key is None else api_key
self.human_only = human_only
def get_response(self):
d = EntrezConfig.esearch.option
uri = EntrezConfig.esearch.base_url + '?' + EntrezConfig.esearch.query.format(query=self.query)
# Search genes that only in human
if self.human_only:
uri += '+AND+{}'.format(EntrezConfig.esearch.cond.orgn_human)
payload = {k: d.get(k) for k in d.keys()}
if self.api_key is not None:
payload['api_key'] = self.api_key
resp = None
try:
resp = requests.get(uri, params=payload)
except ex:
logging.exception(ex)
finally:
return resp
class EntrezSearchResponse(BaseResponse):
def __init__(self, response, parser):
super(EntrezSearchResponse, self).__init__(response, parser)
if __name__ == '__main__':
query = 'Rab10'
req = EntrezSearchRequest(query)
resp = EntrezSearchRequest(req.get_response(), ChebiObjectParser)
import pdb; pdb.set_trace()
print(resp)
|
StarcoderdataPython
|
9795023
|
# Snake.py
# By <NAME> <<EMAIL>>
# MIT License
import pygame
from pygame.locals import *
import random
FPS = 10
SCREEN_SIZE = (640, 480)
CELL_SIZE = 20
COLS = SCREEN_SIZE[0] / CELL_SIZE
ROWS = SCREEN_SIZE[1] / CELL_SIZE
# Set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Setup directions
LEFT = (-1, 0)
RIGHT = (1, 0)
UP = (0, -1)
DOWN = (0, 1)
class Snake:
def __init__(self, cols, rows, cell_size=20, direction=(1, 0), color=(255, 255, 255), size=3):
self.cols = cols
self.rows = rows
self.start_x = int(self.cols//2)
self.start_y = int(self.rows//2)
self.cell_size = cell_size
self.direction = direction
self.color = color
self.segments = []
self.build_segments(size)
def build_segments(self, size):
# Set a list of segments coordinates
for i in range(1, size+1):
self.segments.append([(self.start_x - i) * self.cell_size, self.start_y * self.cell_size])
def add_segment(self):
x, y = self.direction
tail = self.segments[-1]
self.segments.append([tail[0] + x * self.cell_size, tail[1] + y * self.cell_size])
def check_edge_collision(self):
# Check if the Snake has hit the edges
head = self.segments[0]
if head[0] < 0 \
or head[0] == self.cols * self.cell_size \
or head[1] < 0 \
or head[1] == self.rows * self.cell_size: \
return True
return False
def check_segment_collision(self):
# Check if the Snake has hit itself
head = self.segments[0]
for segment in self.segments[1:]:
if head[0] == segment[0] and head[1] == segment[1]:
return True
return False
def check_collisions(self):
if self.check_edge_collision() or self.check_segment_collision():
return True
return False
def collide(self, food):
# Check if the Snake collided with the Food
x = food.x
y = food.y
head = self.segments[0]
if head[0] == x and head[1] == y:
return True
return False
def update(self):
x, y = self.direction
head = self.segments[0]
# Remove Snake's tail segment
self.segments.pop()
# Insert a new head segment
self.segments.insert(0, [head[0] + x * self.cell_size, head[1] + y * self.cell_size])
def render(self, surface):
for segment in self.segments:
segment_surface = pygame.Rect(segment[0], segment[1], self.cell_size, self.cell_size)
pygame.draw.rect(surface, self.color, segment_surface)
class Food:
def __init__(self, cols, rows, cell_size=20, color=(255, 255, 255)):
self.cols = cols
self.rows = rows
self.cell_size = cell_size
self.color = color
self.x = 0
self.y = 0
def set_random_location(self):
self.x = random.randint(0, (self.cols - 1)) * self.cell_size
self.y = random.randint(0, (self.rows - 1)) * self.cell_size
def render(self, surface):
food_surface = pygame.Rect(self.x, self.y, self.cell_size, self.cell_size)
pygame.draw.rect(surface, self.color, food_surface)
def main():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
clock = pygame.time.Clock()
# Create the Snake object. Only the two first arguments are mandatory
snake = Snake(COLS, ROWS, CELL_SIZE, RIGHT, GREEN)
# Create the Food object and set it's initial location. Only the two first arguments are mandatory
food = Food(COLS, ROWS, CELL_SIZE, RED)
food.set_random_location()
score = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
if event.type == KEYDOWN:
if event.key == K_LEFT and snake.direction != RIGHT:
snake.direction = LEFT
elif event.key == K_RIGHT and snake.direction != LEFT:
snake.direction = RIGHT
elif event.key == K_UP and snake.direction != DOWN:
snake.direction = UP
elif event.key == K_DOWN and snake.direction != UP:
snake.direction = DOWN
screen.fill(BLACK)
snake.update()
# Check if the Snake has hit itself or the edge
if snake.check_collisions():
break;
# Check if the Snake has eaten the Food
if snake.collide(food):
snake.add_segment()
food.set_random_location()
score += 1
food.render(screen)
snake.render(screen)
pygame.display.update()
clock.tick(FPS)
print("Your score:", score)
pygame.quit()
quit()
if __name__ == "__main__":
main()
|
StarcoderdataPython
|
6638491
|
<filename>clsim/resources/plots/antares_om_angular_sensitivity.py
#!/usr/bin/env python
#--------------------------------------------
# plot_antares_om_angular_sensitivity
#
# A script to plot the 4 four possible angular
# acceptances for an ANTARES OM.
#
# Further a comparison plot is done to show
# the precision of the Taylor expansion for the
# 'old' acceptance. In this case a Taylor expansion
# was neccessairy as the acceptance has been
# parametrized as polynomial of arccos, that can not
# be stored in the I3CLSimFunctionPolynomial class
#--------------------------------------------
import matplotlib
matplotlib.use("PDF")
import matplotlib.pylab as plt
from icecube import icetray, dataclasses
from icecube.clsim import I3CLSimFunctionPolynomial
from icecube.clsim.GetAntaresOMAngularSensitivity import *
params = {'backend': 'pdf',
'axes.labelsize': 10,
'text.fontsize': 10,
'legend.fontsize': 10,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'text.usetex': True}
matplotlib.rcParams.update(params)
matplotlib.rc('font',**{'family':'serif','serif':['Computer Modern']})
# A function definition for the original implementation of the 'old' acceptance
def OriginalWang(x):
a0=59.115
a1=0.52258
a2=0.60944E-02
a3=-0.16955E-03
a4=0.60929E-06
if x < -0.36:
return 0.
elif x >= 1.:
return 1.
else:
th = plt.arccos(x) * 57.29578 + 57.75
wang = a0 + a1*th + a2*th*th + a3*th*th*th + a4*th*th*th*th
wang /= 84.
return wang
#Get the implementations of the acceptance
acceptance_old = GetAntaresOMAngularSensitivity('old')
acceptance_NIM = GetAntaresOMAngularSensitivity('NIM')
acceptance_Genova = GetAntaresOMAngularSensitivity('Genova')
acceptance_Spring09 = GetAntaresOMAngularSensitivity('Spring09')
#Evaluate the functions
x = [float(i)/1000. for i in range(-1000,1001)]
y_old = [acceptance_old.GetValue(i) for i in x]
y_NIM = [acceptance_NIM.GetValue(i) for i in x]
y_Genova = [acceptance_Genova.GetValue(i) for i in x]
y_Spring09 = [acceptance_Spring09.GetValue(i) for i in x]
y_origwang = [OriginalWang(i) for i in x]
#Make the main plot
fig = plt.figure(1, figsize=[8,10])
fig.canvas.set_window_title("Angular sensitivity of an ANTARES OM from different measurements")
plt.subplot(211)
plt.xlabel("$cos(\\theta)$ [rad]")
plt.ylabel("sensitivity")
plt.title("Angular sensitivity of an ANTARES OM\nfrom different measurements")
plt.plot(x, y_old, label='old')
plt.plot(x, y_NIM, label='NIM')
plt.plot(x, y_Genova, label='Genova')
plt.plot(x, y_Spring09, label='Spring09')
plt.legend(loc='upper left')
plt.grid()
plt.subplot(212)
plt.xlabel("$cos(\\theta)$ [rad]")
plt.ylabel("log sensitivity")
plt.plot(x, y_old, label='old')
plt.plot(x, y_NIM, label='NIM')
plt.plot(x, y_Genova, label='Genova')
plt.plot(x, y_Spring09, label='Spring09')
plt.legend(loc='upper left')
plt.grid()
plt.yscale('log')
fig.savefig("antares_om_angular_sensitivity.pdf")
#Make the difference plot for the 'old' acceptance
diff = [y_old[i] - y_origwang[i] for i in range(y_old.__len__())]
fig = plt.figure(2, figsize=[8,10])
fig.canvas.set_window_title("The 'old' ANTARES OM angular sensitivity vs. its Taylor expansion")
plt.subplot(211)
plt.xlabel("$cos(\\theta)$ [rad]")
plt.ylabel("sensitivity")
plt.title("'old' angular sensitivity of an ANTARES OM")
plt.plot(x, y_origwang, label='Original implementation')
plt.plot(x, y_old, label='30 orders Taylor expansion')
plt.legend(loc='upper left')
plt.grid()
plt.subplot(212)
plt.xlabel("$cos(\\theta)$ [rad]")
plt.ylabel("Difference (Taylor - original) in sensitivity")
plt.title("Difference between the original implementation and its Taylor expansion")
plt.plot(x, diff)
plt.grid()
fig.savefig("TaylorExpansionOfOldAntaresOMAngularSensitivity.pdf")
#Show
#plt.show()
|
StarcoderdataPython
|
3411446
|
import sys
layers = 12
delta = 0.00000000001
if len(sys.argv) < 3:
print 'Usage: python compare_layers.py <file> <reference>'
sys.exit(2)
with open(sys.argv[1], 'r') as fin:
indata = fin.readlines()
with open(sys.argv[2], 'r') as fref:
refdata = fref.readlines()
for i in range(layers):
invals = indata[i].split(',')
if invals[0] != 'LAYER' + str(i):
print 'ERROR: Invalid input data for layer ' + str(i)
sys.exit(2)
refvals = refdata[i].split(',')
if refvals[0] != 'LAYER' + str(i):
print 'ERROR: Invalid reference data for layer ' + str(i)
sys.exit(2)
if len(refvals) != len(invals):
print 'ERROR: Dimensionality error in layer %d (expetced: %d, was: %d)' % \
(i, len(refvals), len(invals))
sys.exit(2)
for j in range(1, len(invals)):
if abs(float(invals[j])-float(refvals[j])) > delta:
print 'ERROR: Value %d at layer %d is wrong: %f (should be %f)' % \
(j, i, float(invals[j]), float(refvals[j]))
sys.exit(1)
print 'OK'
|
StarcoderdataPython
|
11225413
|
import numpy as np
A = np.matrix([[1,0,0],
[0,1,0],
[0,0,1]]) #lattice
print("Direct Lattice:\n{}".format(A))
B = 2*np.pi*(np.linalg.inv(A)).H #recip lattice
print("Recip Lattice:\n{}".format(B))
rc = 0.5*np.min(np.sqrt(np.sum(np.square(A),1)))
lrdimcut = 40
kc = lrdimcut / rc
print("lrdim: {}, rc: {}, kc: {}".format(lrdimcut,rc,kc))
#electronic structure, p. 85
mmax = np.floor(np.sqrt(np.sum(np.square(A),1)) * (kc/(2*np.pi))) + 1
mmax = np.array(mmax,dtype=int).reshape((3,)) #matrix to array
kpts = [] #translations of recip lattice
kmag = [] #magnitude
for i in range(-mmax[0], mmax[0] + 1):
for j in range(-mmax[1], mmax[1] + 1):
for k in range(-mmax[2], mmax[2] + 1):
if (i == 0) and (j==0) and (k==0):
continue
kvec = np.matrix([i,j,k])
kcart = np.array(np.dot(kvec,B)).reshape((3,))
if np.linalg.norm(kcart) > kc:
continue
kpts.append(np.array(kvec).reshape((3,)))
kmag.append(np.linalg.norm(kcart))
kpts = np.array(kpts)
kmag = np.array(kmag)
idx = np.argsort(kmag)
kpts = kpts[idx]
kmag = kmag[idx]
# 1-exp(-k^2) and k is unit k
sks = []
with open('simple_Sk.dat','w') as f:
f.write('# kx ky kz Sk err\n')
for i in range(len(kpts)):
kcart = np.array(np.dot(kpts[i],B)).reshape((3,))
kunit = kcart / (2*np.pi)
k = np.linalg.norm(kunit)
sk = 1-np.exp(-0.075*k*k)
sks.append(sk)
f.write('{0} {1} {2} {3} {4}\n'.format(kcart[0],kcart[1],kcart[2],sk,0.01))
print("Ewald Handler Corrections: ")
#corrections
vol = np.abs(np.linalg.det(A))
sigma2 = 0.5*kc/rc
vsum = 0
for i in range(len(kpts)):
k2 = kmag[i]*kmag[i]
vk = 4*np.pi / (k2 * vol) * np.exp(-0.25*k2/sigma2)
vsum += 0.5*vk*sks[i]
print(" Discrete: {}".format(vsum))
vint = 1.066688342657357 #from analytic mathematica calculation
|
StarcoderdataPython
|
5065191
|
<reponame>behdadahmadi/instamaker<gh_stars>10-100
#!/usr/bin/python
#Instagram Account Maker
#by <NAME>
#Twitter: behdadahmadi
#https://github.com/behdadahmadi
#https://logicalcoders.com
import requests
import hmac
import hashlib
import random
import string
import json
import argparse
def HMAC(text):
key = '3f0a7d75e094c7385e3dbaa026877f2e067cbd1a4dbcf3867748f6b26f257117'
hash = hmac.new(key,msg=text,digestmod=hashlib.sha256)
return hash.hexdigest()
def randomString(size):
chars = string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for _ in range(size))
def banner():
dotname = "-" * 31
print " "
print dotname.center(16,'-')
print ".:: " + 'Instagram Account Maker' + " ::.".center(4)
print "by <NAME>".center(30)
print "Twitter:behdadahmadi".center(30)
print dotname.center(20,'-')
def main():
banner()
parser = argparse.ArgumentParser()
parser.add_argument('name', help='Full Name')
parser.add_argument('username', help='Username')
parser.add_argument('email', help='Email')
parser.add_argument('password', help='Password')
args = parser.parse_args()
getHeaders = {'User-Agent':'Instagram 7.1.1 Android (21/5.0.2; 480dpi; 1080x1776; LGE/Google; Nexus 5; hammerhead; hammerhead; en_US)',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'en-US,en;q=0.8',
'upgrade-insecure-requests':'1'}
s = requests.Session()
s.get('https://instagram.com',headers=getHeaders)
guid = randomString(8) + '-' + randomString(4) + "-" + randomString(4) + '-' + randomString(4) + '-' +randomString(12)
device_id = 'android-' + str(HMAC(str(random.randint(1000,9999))))[0:min(64,16)]
information = {'username':args.username,'first_name':args.name,'password':<PASSWORD>,'email':args.email,'device_id':device_id,'guid':guid}
js = json.dumps(information)
payload = {'signed_body': HMAC(js) + '.' + js,'ig_sig_key_version':'4'}
postHeaders = {'Host':'i.instagram.com',
'User-Agent':'Instagram 7.1.1 Android (21/5.0.2; 480dpi; 1080x1776; LGE/Google; Nexus 5; hammerhead; hammerhead; en_US)',
'Accept-Language':'en-US',
'Accept-Encoding':'gzip',
'Cookie2':'$Version=1',
'X-IG-Connection-Type':'WIFI',
'X-IG-Capabilities':'BQ=='
}
x = s.post('https://i.instagram.com/api/v1/accounts/create/',headers=postHeaders,data=payload)
result = json.loads(x.content)
if result['status'] != 'fail':
if result['account_created'] == True:
print 'Account has been created successfully'
else:
print 'Error:'
for i in result['errors']:
print str(result['errors'][i][0])
else:
if result['spam'] == True:
print 'Instagram blocks your IP due to spamming behaviour.'
if __name__ == '__main__':
main()
|
StarcoderdataPython
|
5063791
|
<filename>caluma/form/tests/test_jexl.py
import pytest
from ..jexl import QuestionJexl
@pytest.mark.parametrize(
"expression,num_errors",
[
# correct case
('"question-slug"|answer|mapby', 0),
# invalid subject type
("100|answer", 1),
# two invalid subject types
('["test"]|answer || 1.0|answer', 2),
# invalid operator
("'question-slug1'|answer &&& 'question-slug2'|answer", 1),
],
)
def test_question_jexl_validate(expression, num_errors):
jexl = QuestionJexl()
assert len(list(jexl.validate(expression))) == num_errors
@pytest.mark.parametrize(
"expression,result",
[
('"a1"|answer', "A1"),
('"parent.form_b.b1"|answer', "B1"),
('"parent.form_b.parent.form_a.a1"|answer', "A1"),
],
)
def test_jexl_traversal(expression, result):
form_a = {"a1": "A1"}
form_b = {"b1": "B1"}
parent = {"form_a": form_a, "form_b": form_b}
form_a["parent"] = parent
form_b["parent"] = parent
jexl = QuestionJexl(form_a)
assert jexl.evaluate(expression) == result
@pytest.mark.parametrize(
"expression,result",
[
("[1,2] intersects [2,3]", True),
("[1,2] intersects [3,4]", False),
("[] intersects []", False),
("[1] intersects []", False),
("['foo'] intersects ['bar', 'bazz']", False),
("['foo'] intersects ['foo', 'foo']", True),
("[1] intersects [1] && [2] intersects [2]", True),
("[2] intersects [1] + [2]", True),
],
)
def test_intersects_operator(expression, result):
assert QuestionJexl().evaluate(expression) == result
|
StarcoderdataPython
|
5178402
|
import sys
import queue
import threading
import json
import collections
import time
from spirecomm.spire.game import Game
from spirecomm.spire.screen import ScreenType
from spirecomm.communication.action import Action, StartGameAction
def read_stdin(input_queue):
"""Read lines from stdin and write them to a queue
:param input_queue: A queue, to which lines from stdin will be written
:type input_queue: queue.Queue
:return: None
"""
while True:
stdin_input = ""
#print("Communicator: read_stdin", file=self.logfile, flush=True)
while True:
input_char = sys.stdin.read(1)
if input_char == '\n':
break
else:
stdin_input += input_char
input_queue.put(stdin_input)
def write_stdout(output_queue):
"""Read lines from a queue and write them to stdout
:param output_queue: A queue, from which this function will receive lines of text
:type output_queue: queue.Queue
:return: None
"""
while True:
output = output_queue.get()
print(output, end='\n', flush=True)
class Coordinator:
"""An object to coordinate communication with Slay the Spire"""
def __init__(self):
self.input_queue = queue.Queue()
self.output_queue = queue.Queue()
self.actions_played_queue = queue.Queue()
self.input_thread = threading.Thread(target=read_stdin, args=(self.input_queue,))
self.output_thread = threading.Thread(target=write_stdout, args=(self.output_queue,))
self.input_thread.daemon = True
self.input_thread.start()
self.output_thread.daemon = True
self.output_thread.start()
self.action_queue = collections.deque()
self.state_change_callback = None
self.out_of_game_callback = None
self.error_callback = None
self.game_is_ready = False
self.stop_after_run = False
self.in_game = False
self.last_game_state = None
self.last_error = None
self.last_msg = ""
self.last_action = None
self.logfile = open("ai_comm.log","w")
print("Communicator: Init ", file=self.logfile, flush=True)
def signal_ready(self):
"""Indicate to Communication Mod that setup is complete
Must be used once, before any other commands can be sent.
:return: None
"""
print("Communicator: signal_ready", file=self.logfile, flush=True)
self.send_message("ready")
def send_message(self, message):
"""Send a command to Communication Mod and start waiting for a response
:param message: the message to send
:type message: str
:return: None
"""
self.output_queue.put(message)
self.game_is_ready = False
def add_action_to_queue(self, action):
"""Queue an action to perform when ready
:param action: the action to queue
:type action: Action
:return: None
"""
self.action_queue.append(action)
def clear_actions(self):
"""Remove all actions from the action queue
:return: None
"""
self.action_queue.clear()
def execute_next_action(self):
"""Immediately execute the next action in the action queue
:return: None
"""
action = self.action_queue.popleft()
self.last_action = action
self.actions_played_queue.put(action)
action.execute(self)
def re_execute_last_action(self):
self.actions_played_queue.put(self.last_action)
self.last_action.execute(self)
def execute_next_action_if_ready(self):
"""Immediately execute the next action in the action queue, if ready to do so
:return: None
"""
if len(self.action_queue) > 0 and self.action_queue[0].can_be_executed(self):
self.execute_next_action()
def register_state_change_callback(self, new_callback):
"""Register a function to be called when a message is received from Communication Mod
:param new_callback: the function to call
:type new_callback: function(game_state: Game) -> Action
:return: None
"""
print("Communicator: register_state_change_callback", file=self.logfile, flush=True)
self.state_change_callback = new_callback
def register_command_error_callback(self, new_callback):
"""Register a function to be called when an error is received from Communication Mod
:param new_callback: the function to call
:type new_callback: function(error: str) -> Action
:return: None
"""
print("Communicator: register_command_error_callback", file=self.logfile, flush=True)
self.error_callback = new_callback
def register_out_of_game_callback(self, new_callback):
"""Register a function to be called when Communication Mod indicates we are in the main menu
:param new_callback: the function to call
:type new_callback: function() -> Action
:return: None
"""
print("Communicator: register_out_of_game_callback", file=self.logfile, flush=True)
self.out_of_game_callback = new_callback
def view_last_msg(self):
return self.last_msg
def get_action_played(self):
if not self.actions_played_queue.empty():
return self.actions_played_queue.get()
def get_next_raw_message(self, block=False):
"""Get the next message from Communication Mod as a string
:param block: set to True to wait for the next message
:type block: bool
:return: the message from Communication Mod
:rtype: str
"""
if block or not self.input_queue.empty():
self.last_msg = self.input_queue.get()
return self.last_msg
def receive_game_state_update(self, block=False, perform_callbacks=True, repeat=False):
"""Using the next message from Communication Mod, update the stored game state
:param block: set to True to wait for the next message
:type block: bool
:param perform_callbacks: set to True to perform callbacks based on the new game state
:type perform_callbacks: bool
:return: whether a message was received
"""
message = ""
if repeat:
message = self.last_msg
else:
message = self.get_next_raw_message(block)
if message is not None:
communication_state = json.loads(message)
self.last_error = communication_state.get("error", None)
self.game_is_ready = communication_state.get("ready_for_command")
if self.last_error is None:
self.in_game = communication_state.get("in_game")
if self.in_game:
self.last_game_state = Game.from_json(communication_state.get("game_state"), communication_state.get("available_commands"))
else:
print("Communicator detected error", file=self.logfile, flush=True)
if perform_callbacks:
if self.last_error is not None:
self.action_queue.clear()
new_action = self.error_callback(self.last_error)
self.add_action_to_queue(new_action)
elif self.in_game:
if len(self.action_queue) == 0 and perform_callbacks:
#print(str(self.last_game_state), file=self.logfile, flush=True)
new_action = self.state_change_callback(self.last_game_state)
self.add_action_to_queue(new_action)
elif self.stop_after_run:
self.clear_actions()
else:
new_action = self.out_of_game_callback()
self.add_action_to_queue(new_action)
return True
return False
def unpause_agent(self):
print("Communicator: game update " + str(time.time()), file=self.logfile, flush=True)
print("Communicator's game state:", file=self.logfile, flush=True)
print(str(self.last_game_state), file=self.logfile, flush=True)
self.last_game_state = Game.from_json(communication_state.get("game_state"), communication_state.get("available_commands"))
self.receive_game_state_update()
def run(self):
"""Start executing actions forever
:return: None
"""
print("Communicator: run", file=self.logfile, flush=True)
while True:
self.execute_next_action_if_ready()
self.receive_game_state_update(perform_callbacks=True)
def play_one_game(self, player_class, ascension_level=0, seed=None):
"""
:param player_class: the class to play
:type player_class: PlayerClass
:param ascension_level: the ascension level to use
:type ascension_level: int
:param seed: the alphanumeric seed to use
:type seed: str
:return: True if the game was a victory, else False
:rtype: bool
"""
print("Communicator: play_one_game", file=self.logfile, flush=True)
self.clear_actions()
while not self.game_is_ready:
self.receive_game_state_update(block=True, perform_callbacks=False)
if not self.in_game:
StartGameAction(player_class, ascension_level, seed).execute(self)
self.receive_game_state_update(block=True)
while self.in_game:
self.execute_next_action_if_ready()
self.receive_game_state_update()
if self.last_game_state.screen_type == ScreenType.GAME_OVER:
return self.last_game_state.screen.victory
else:
return False
|
StarcoderdataPython
|
8193208
|
<filename>chapter_15/cgi-bin/badlink.py
import cgi, sys
form = cgi.FieldStorage() # print all inputs to stderr; stodout=reply page
for name in form.keys():
print('[%s:%s]' % (name, form[name].value), end=' ', file=sys.stderr)
'''
The moral of this story is that unless you can be sure that the names of all but the
leftmost URL query parameters embedded in HTML are not the same as the name of
any HTML character escape code like amp, you should generally either use a semicolon
as a separator, if supported by your tools, or run the entire URL through cgi.escape
after escaping its parameter names and values with urllib.parse.quote_plus:
'''
|
StarcoderdataPython
|
1978295
|
import sys
import os
filename = sys.argv[1]
filedir = sys.argv[2]
os.chdir(filedir)
os.system('touch ' + filename)
os.chdir('/Users/vipul/Documents/coding/cp')
file, extension = filename.split('.')
if(extension=="py"):
cp_file_path = './cp_python_template.py'
elif(extension=="cpp"):
cp_file_path = './cp_cpp_template.cpp'
os.system('cp ' + cp_file_path + ' ../../../../..' + filedir + '/' + filename)
|
StarcoderdataPython
|
5197004
|
<reponame>CedarGroveStudios/AD9833_ADSR_FeatherWing
# The MIT License (MIT)
#
# Copyright (c) 2019 <NAME>
# Thanks to <NAME> for the driver concept inspiration
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`cedargrove_ad5245`
================================================================================
CircuitPython library for the Analog Devices AD5245 I2C Potentionmeter
* Author(s): <NAME>
Implementation Notes
--------------------
**Hardware:**
* `Cedar Grove Studios AD5245 breakout`_
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
_AD5245_DEFAULT_ADDRESS = 0x2C # 0b00101100
class AD5245:
"""Driver for the DS3502 I2C Potentiometer.
:param address: The I2C device address for the device. Default is ``0x2C``.
:param wiper: The default and inital wiper value. Default is 0.
"""
_BUFFER = bytearray(1)
def __init__(self, address=_AD5245_DEFAULT_ADDRESS, wiper = 0):
import board
import busio
self._i2c = busio.I2C(board.SCL, board.SDA)
from adafruit_bus_device.i2c_device import I2CDevice
self._device = I2CDevice(self._i2c, address)
self._wiper = wiper
self._default_wiper = wiper
self._normalized_wiper = self._wiper / 255.0
self._write_to_device(0, wiper)
def _write_to_device(self, command, value):
"""Write command and data value to the device."""
with self._device:
self._device.write(bytes([command & 0xff, value & 0xff]))
def _read_from_device(self):
"""Reads the contents of the data register."""
with self._device:
self._device.readinto(self._BUFFER)
return self._BUFFER
@property
def wiper(self):
"""The raw value of the potentionmeter's wiper.
:param wiper_value: The raw wiper value from 0 to 255.
"""
return self._wiper
@wiper.setter
def wiper(self, value=0):
if value < 0 or value > 255:
raise ValueError("raw wiper value must be from 0 to 255")
self._write_to_device(0x00, value)
self._wiper = value
@property
def normalized_wiper(self):
"""The normalized value of the potentionmeter's wiper.
:param normalized_wiper_value: The normalized wiper value from 0.0 to 1.0.
"""
return self._normalized_wiper
@normalized_wiper.setter
def normalized_wiper(self, value):
if value < 0 or value > 1.0:
raise ValueError("normalized wiper value must be from 0.0 to 1.0")
self._write_to_device(0x00, int(value * 255.0))
self._normalized_wiper = value
@property
def default_wiper(self):
"""The default value of the potentionmeter's wiper.
:param wiper_value: The raw wiper value from 0 to 255.
"""
return self._default_wiper
@default_wiper.setter
def default_wiper(self, value):
if value < 0 or value > 255:
raise ValueError("default wiper value must be from 0 to 255")
self._default_wiper = value
def set_default(self, default):
"""A dummy helper to maintain UI compatibility digital
potentiometers with EEROM capability (dS3502). The AD5245's
wiper value will be set to 0 unless the default value is
set explicitly during or after class instantiation."""
self._default_wiper = default
def shutdown(self):
"""Connects the W to the B terminal and open circuits the A terminal.
The contents of the wiper register are not changed."""
self._write_to_device(0x20, 0)
|
StarcoderdataPython
|
271384
|
<filename>tests/src/Exceptions_Reports/Teacher_Exception/regression_teacher_exception.py
# -*- coding: utf-8 -*-
import unittest
import time
from selenium.webdriver.support.select import Select
from Data.parameters import Data
from Exceptions_Reports.Teacher_Exception.teacher_exception_scripts import teacher_exception_report
from reuse_func import GetData
class cQube_teacher_exception_regression_report(unittest.TestCase):
@classmethod
def setUpClass(self):
self.data = GetData()
self.driver = self.data.get_driver()
self.driver.implicitly_wait(100)
self.data.open_cqube_appln(self.driver)
self.data.login_cqube(self.driver)
self.data.navigate_to_teacher_exception()
self.data.page_loading(self.driver)
year = Select(self.driver.find_element_by_id(Data.sar_year))
month = Select(self.driver.find_element_by_id(Data.sar_month))
self.year = year.first_selected_option.text
self.month = month.first_selected_option.text
def test_DistrictwiseDownload(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1,res2 = b.check_districts_csv_download()
self.assertNotEqual(res1,0,msg='Markers are not present')
self.assertEqual(0, res2, msg="Some district level csv file is not downloaded")
print('Checking each districtwise markers and csv file downloading ')
self.data.page_loading(self.driver)
def test_ClusterPerBlockCsvDownload(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1,res2 = b.ClusterPerBlockCsvDownload()
self.assertNotEqual(res1,0,msg='Markers are not present')
self.assertEqual(0,res2 , msg='Some cluster level files are not downloaded')
print('Checking each cluster markers and csv file downloading ')
self.data.page_loading(self.driver)
def test_SchoolPerClusterCsvDownload(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1,res2 = b.SchoolPerClusterCsvDownload()
self.assertNotEqual(0,res1,msg='Markers are not present')
self.assertEqual(0, res2, msg='Some School level files are not downloaded')
print('Checking each school wise markers and csv file downloading ')
self.data.page_loading(self.driver)
def test_Data_not_recieved(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res,r1,r2,r3 = b.test_total_not_recieved_data()
self.assertEqual(res,r1,msg='Block level data not recieved count mismatch found')
self.assertEqual(res,r2,msg='cluster level data not recieved count mismatch found')
self.assertEqual(res,r3,msg='School level data not recieved count mismatch found')
def test_teacher_exception_Blocks(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1,res2 = b.check_markers_on_block_map()
self.assertNotEqual(0,res1,msg="markers are not present on block level map")
self.assertEqual(0,res2,msg='Footer mis match found at block level')
print('Checked blockwise markers and csv file downloading ')
self.data.page_loading(self.driver)
def test_teacher_clusters(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1, res2 = b.check_markers_on_block_map()
self.assertNotEqual(0, res1, msg="markers are not present on cluster level map")
self.assertEqual(0, res2, msg='Footer mis match found at cluster level')
print('Checked cluster wise markers and csv file downloading ')
self.data.page_loading(self.driver)
def test_teacher_school(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1, res2 = b.check_markers_on_block_map()
self.assertNotEqual(0, res1, msg="markers are not present on school level map")
self.assertEqual(0, res2, msg='Footer mis match found at school level')
print('Checked schoolwise markers and csv file downloading ')
self.data.page_loading(self.driver)
def test_teacher_exception_icon(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res = b.test_icon()
self.assertEqual(0,res,msg='teacher exception report is not displayed')
print("Pat exception icon on landing is working ")
def test_teacher_exception_Logout(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res = b.click_on_logout()
self.assertEqual(res,'Log in to cQube',msg="logout button is not working")
self.data.login_cqube(self.driver)
self.data.navigate_to_teacher_exception()
print("Logout button is working fine ")
self.data.page_loading(self.driver)
def test_cluster_btn_records(self):
b = teacher_exception_report(self.driver,self.year, self.month)
res1,res2 = b.check_markers_on_clusters_map()
self.assertNotEqual(0,res1,msg="Cluster level markers are not present")
self.assertEqual(0,res2,msg='Cluster csv file is not downloaded')
print('Checked with Clusterwise map records')
self.data.page_loading(self.driver)
def test_block_btn_records(self):
b = teacher_exception_report(self.driver, self.year, self.month)
res1, res2 = b.check_markers_on_block_map()
self.assertNotEqual(0, res1, msg="Block level markers are not present")
self.assertEqual(0, res2, msg='Blockwise csv file is not downloaded')
print('Checked with blockwise map records')
self.data.page_loading(self.driver)
def test_school_btn_records(self):
b = teacher_exception_report(self.driver, self.year, self.month)
res1, res2 = b.check_markers_on_school_map()
self.assertNotEqual(0, res1, msg="School level markers are not present")
self.assertEqual(0, res2, msg='Schoolwise csv file is not downloaded')
print('Checked with schoolwise map records')
self.data.page_loading(self.driver)
@classmethod
def tearDownClass(cls):
cls.driver.close()
|
StarcoderdataPython
|
1951650
|
import hashlib
from tornado.web import RequestHandler
from tornado import gen
class Handler(RequestHandler):
@gen.coroutine
def post(self):
"""
修改密码
:return: if ok: '0' else '1'
"""
try:
username = self._get_cookie_username()
params = self._get_params()
password_indb = yield self._find_user_password(username)
self._check_password(params["password_old"], password_indb)
yield self._update_password(username, params["password_new"])
except RuntimeError:
self.write(str(1))
else:
self.write(str(0))
def _get_cookie_username(self):
username = self.get_secure_cookie("username")
if not username:
raise RuntimeError("Please login")
return username.decode()
def _get_params(self):
params = {}
params["password_old"] = self.get_argument("password_old", default="")
params["password_new"] = self.get_argument("password_new", default="")
for v in params.values():
if not v:
raise RuntimeError("Empry item")
return params
@gen.coroutine
def _find_user_password(self, username):
user = yield self.settings["database"]["user"].find_one({
"username": username,
}, {
"password": 1,
})
if not user:
raise RuntimeError("Username not exists")
return user["password"]
def _check_password(self, password_post, password_indb):
m = hashlib.md5()
m.update(password_post.encode("utf8"))
if m.hexdigest() != password_indb:
raise RuntimeError("Incorrect old password")
@gen.coroutine
def _update_password(self, username, password_new):
m = hashlib.md5()
m.update(password_new.encode("utf8"))
r = yield self.settings["database"]["user"].update_one({
"username": username,
}, {
"$set": {
"password": m.<PASSWORD>(),
},
})
if r.modified_count != 1:
raise RuntimeError("Update error")
|
StarcoderdataPython
|
374092
|
<reponame>Bhaskers-Blu-Org1/text-oriented-active-learning<filename>toal/samplers/RandomSampler.py
from random import shuffle
import pandas as pd
from .AbstractSampler import AbstractSampler
from toal.stores import BasicStore
class RandomSampler(AbstractSampler):
def choose_instances(self, store: BasicStore, batch_size=10) -> pd.DataFrame:
# just get the next n (random) samples
shuf_idx = list(range(store.unlabeled_Xs.shape[0]))
shuffle(shuf_idx)
unlabeled_selection = store.unlabeled_df.iloc[shuf_idx[:batch_size], :]
# TODO also return the prediction confidence for debugging (and explainability)?
return unlabeled_selection
|
StarcoderdataPython
|
4879217
|
#!/usr/bin/python3
import time
import serial
from serial import Serial
from datetime import datetime
import struct
import sys
# from collections import namedtuple
import numpy as np
import mysql.connector as sql
from scipy import interpolate
from sys import argv
import gps
import requests
import socket
lat = 0
lon = 0
spe_gps = 0
# battFile = open('oceanos_cell_discharge_capacity_14s.csv', mode='r')
# csv_reader = csv.DictReader(battFile)
Vdata = np.genfromtxt('oceanos_cell_discharge_capacity_14s.csv', dtype=float, delimiter=',', names=True)
vx = Vdata['voltage']
vy = Vdata['Percentage']
fvolt = interpolate.interp1d(vx, vy)
localdb = sql.connect(
host="127.0.0.1",
user="root",
password="<PASSWORD>",
database = "ocdb"
)
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
'''
hostdb = sql.connect(
host="sql126.main-hosting.eu",
user="u322154547_root",
passwd="<PASSWORD>",
database = "test"
)
'''
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=9600,
timeout = 1
)
ser.isOpen()
ser.flush()
# ser.setRTS(True)
time.sleep(2)
print('Log app for arduino CAN.')
now = datetime.now() # current date and time
date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
filename = "logs/can_log_"+now.strftime("%d%m%Y-%H-%M")+".csv";
f= open(filename,"w+")
f.write(date_time + '\n')
f.write('date, time, microseconds, speed, throttle, current, voltage, contTemp, motTemp, motErrCode, cntrStat, swStat, Discharge\n')
f.close()
while 1 :
ser.write(b'S')
arduinoInput = ser.readline()
out = datetime.now().strftime("%d/%m/%Y, %H:%M:%S, %f") + ', ' + str(arduinoInput,'ASCII')
elems = out.split(',')
speed = elems[0+3].strip()
throttle = elems[1+3].strip()
current = elems[2+3].strip()
voltage = elems[3+3].strip()
contTemp = elems[4+3].strip()
motTemp = elems[5+3].strip()
motErrCode = elems[6+3].strip()
cntrStat = elems[7+3].strip()
swStat = elems[8+3].strip()
rep = session.next()
localcursor = localdb.cursor()
try :
if (rep["class"] == "TPV"):
lat = rep.lat
lon = rep.lon
spe_gps = rep.speed
sendQuery_GPS = "INSERT INTO gps (Latitude, Longitude, Speed) VALUES ('"+str(lat)+"','"+str(lon)+"','"+str(spe_gps)+"')"
localcursor.execute(sendQuery_GPS)
localdb.commit()
except Exception as e :
pass
# print(Vdata['Percentage'])
energy = fvolt(float(voltage))
# print(energy)
out = out.strip('\n').strip('\r') + ', ' + str(energy) + ', ' + str(lat) + ', ' + str(lon) + ', ' + str(spe_gps) +'\n'
f= open(filename,"a+")
f.write("%s" % out)
f.close()
print(out)
sendQuery_CAN = "INSERT INTO motor (speed, throttle, current, voltage, contrTemp, motorTemp, motErrCode, cntrStat, swStat, energy) VALUES ('"+speed+"','"+throttle+"','"+current+"','"+voltage+"','"+contTemp+"','"+motTemp+"','"+motErrCode+"','"+cntrStat+"','"+swStat+"','"+str(energy)+"')"
localcursor.execute(sendQuery_CAN)
localdb.commit()
'''
hostcursor = hostdb.cursor()
hostcursor.execute("INSERT INTO motor (speed, throttle, current, voltage, contrTemp, motorTemp, motErrCode, cntrStat, swStat, energy) VALUES ('"+speed+"','"+throttle+"','"+current+"','"+voltage+"','"+contTemp+"','"+motTemp+"','"+motErrCode+"','"+cntrStat+"','"+swStat+"','"+str(energy)+"')")
hostdb.commit()
'''
|
StarcoderdataPython
|
1745663
|
# Generating fibonacci sequence
from typing import Generator
def fib6(n: int) -> Generator[int, None, None]:
yield 0
if n > 0:
yield 1
last: int = 0
next: int = 1
for _ in range(1, n):
last, next = next, last + next
yield next # main generation step
for i in fib6(20):
print(i)
|
StarcoderdataPython
|
225728
|
# pyOCD debugger
# Copyright (c) 2015-2020 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import namedtuple
from .ap import AccessPort
from .cortex_m import CortexM
from .cortex_m_v8m import CortexM_v8M
from .fpb import FPB
from .dwt import (DWT, DWTv2)
from .itm import ITM
from .tpiu import TPIU
from .gpr import GPR
# Component classes.
ROM_TABLE_CLASS = 0x1
CORESIGHT_CLASS = 0x9
GENERIC_CLASS = 0xe
SYSTEM_CLASS = 0xf # CoreLink, PrimeCell, or other system component with no standard register layout.
# [11:8] continuation
# [6:0] ID
ARM_ID = 0x43b
FSL_ID = 0x00e
# CoreSight devtype
# Major Type [3:0]
# Minor Type [7:4]
#
# CoreSight Major Types
# 0 = Miscellaneous
# 1 = Trace Sink
# 2 = Trace Link
# 3 = Trace Source
# 4 = Debug Control
# 5 = Debug Logic
#
# Known devtype values
# 0x11 = TPIU
# 0x21 = ETB
# 0x12 = Trace funnel (CSFT)
# 0x13 = CPU trace source (ETM, MTB?)
# 0x16 = PMU
# 0x43 = ITM
# 0x14 = ECT/CTI/CTM
# 0x31 = MTB
# 0x32 = TMC
# 0x34 = Granular Power Requestor
## Pairs a component name with a factory method.
CmpInfo = namedtuple('CmpInfo', 'name factory')
## Map from (designer, class, part, devtype, archid) to component name and class.
COMPONENT_MAP = {
# Designer|Component Class |Part |Type |Archid
(ARM_ID, CORESIGHT_CLASS, 0x193, 0x00, 0x0a57) : CmpInfo('CS-600 TSGEN', None ),
(ARM_ID, CORESIGHT_CLASS, 0x906, 0x14, 0) : CmpInfo('CTI', None ),
(ARM_ID, CORESIGHT_CLASS, 0x907, 0x21, 0) : CmpInfo('ETB', None ),
(ARM_ID, CORESIGHT_CLASS, 0x908, 0x12, 0) : CmpInfo('CSTF', None ),
(ARM_ID, CORESIGHT_CLASS, 0x912, 0x11, 0) : CmpInfo('TPIU', TPIU.factory ),
(ARM_ID, CORESIGHT_CLASS, 0x923, 0x11, 0) : CmpInfo('TPIU-M3', TPIU.factory ),
(ARM_ID, CORESIGHT_CLASS, 0x924, 0x13, 0) : CmpInfo('ETM-M3', None ),
(ARM_ID, CORESIGHT_CLASS, 0x925, 0x13, 0) : CmpInfo('ETM-M4', None ),
(ARM_ID, CORESIGHT_CLASS, 0x932, 0x31, 0x0a31) : CmpInfo('MTB-M0+', None ),
(ARM_ID, CORESIGHT_CLASS, 0x950, 0x13, 0) : CmpInfo('PTM-A9', None ),
(ARM_ID, CORESIGHT_CLASS, 0x961, 0x32, 0) : CmpInfo('TMC ETF', None ), # Trace Memory Controller
(ARM_ID, CORESIGHT_CLASS, 0x975, 0x13, 0x4a13) : CmpInfo('ETM-M7', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9a0, 0x16, 0) : CmpInfo('PMU-A9', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9a1, 0x11, 0) : CmpInfo('TPIU-M4', TPIU.factory ),
(ARM_ID, CORESIGHT_CLASS, 0x9a3, 0x13, 0x0) : CmpInfo('MTB-M0', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9a4, 0x34, 0x0a34) : CmpInfo('GPR', GPR.factory ), # Granular Power Requestor
(ARM_ID, CORESIGHT_CLASS, 0x9a6, 0x14, 0x1a14) : CmpInfo('CTI', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9e2, 0x00, 0x0a17) : CmpInfo('CS-600 APB-AP', AccessPort.create ),
(ARM_ID, CORESIGHT_CLASS, 0x9e3, 0x00, 0x0a17) : CmpInfo('CS-600 AHB-AP', AccessPort.create ),
(ARM_ID, CORESIGHT_CLASS, 0x9e4, 0x00, 0x0a17) : CmpInfo('CS-600 AXI-AP', AccessPort.create ),
(ARM_ID, CORESIGHT_CLASS, 0x9e5, 0x00, 0x0a47) : CmpInfo('CS-600 APv1 Adapter', AccessPort.create ),
(ARM_ID, CORESIGHT_CLASS, 0x9e6, 0x00, 0x0a27) : CmpInfo('CS-600 JTAG-AP', AccessPort.create ),
(ARM_ID, CORESIGHT_CLASS, 0x9e7, 0x11, 0) : CmpInfo('CS-600 TPIU', TPIU.factory ),
(ARM_ID, CORESIGHT_CLASS, 0x9e8, 0x21, 0) : CmpInfo('CS-600 TMC ETR', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9e9, 0x21, 0) : CmpInfo('CS-600 TMC ETB', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9ea, 0x32, 0) : CmpInfo('CS-600 TMC ETF', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9eb, 0x12, 0) : CmpInfo('CS-600 ATB Funnel', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9ec, 0x22, 0) : CmpInfo('CS-600 ATB Replicator', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9ed, 0x14, 0x1a14) : CmpInfo('CS-600 CTI', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9ee, 0x00, 0) : CmpInfo('CS-600 CATU', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9ef, 0x00, 0x0a57) : CmpInfo('CS-600 SDC-600', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc05, 0x15, 0) : CmpInfo('CPU-A5', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc07, 0x15, 0) : CmpInfo('CPU-A7', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc08, 0x15, 0) : CmpInfo('CPU-A8', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc09, 0x15, 0) : CmpInfo('CPU-A9', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc0d, 0x15, 0) : CmpInfo('CPU-A12', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc0e, 0x15, 0) : CmpInfo('CPU-A17', None ),
(ARM_ID, CORESIGHT_CLASS, 0xc0f, 0x15, 0) : CmpInfo('CPU-A15', None ),
(ARM_ID, CORESIGHT_CLASS, 0x9a9, 0x11, 0) : CmpInfo('TPIU-M7', TPIU.factory ),
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x11, 0) : CmpInfo('TPIU-M23', TPIU.factory ),
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x13, 0) : CmpInfo('ETM-M23', None ),
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x31, 0x0a31) : CmpInfo('MTB-M23', None ), # M23
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x00, 0x1a02) : CmpInfo('DWT', DWTv2.factory ), # M23
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x00, 0x1a03) : CmpInfo('BPU', FPB.factory ), # M23
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x14, 0x1a14) : CmpInfo('CTI', None ), # M23
(ARM_ID, CORESIGHT_CLASS, 0xd20, 0x00, 0x2a04) : CmpInfo('SCS-M23', CortexM_v8M.factory ), # M23
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x31, 0x0a31) : CmpInfo('MTB-M33', None ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x43, 0x1a01) : CmpInfo('ITM', ITM.factory ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x00, 0x1a02) : CmpInfo('DWT', DWTv2.factory ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x00, 0x1a03) : CmpInfo('BPU', FPB.factory ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x14, 0x1a14) : CmpInfo('CTI', None ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x00, 0x2a04) : CmpInfo('SCS-M33', CortexM_v8M.factory ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x13, 0x4a13) : CmpInfo('ETM-M33', None ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd21, 0x11, 0) : CmpInfo('TPIU-M33', TPIU.factory ), # M33
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x43, 0x1a01) : CmpInfo('ITM-M55', ITM.factory ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x00, 0x1a02) : CmpInfo('DWT-M55', DWTv2.factory ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x00, 0x1a03) : CmpInfo('BPU-M55', FPB.factory ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x00, 0x2a04) : CmpInfo('SCS-M55', CortexM_v8M.factory ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x11, 0) : CmpInfo('TPIU-M55', TPIU.factory ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x13, 0x4a13) : CmpInfo('ETM-M55', None ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd22, 0x16, 0x0a06) : CmpInfo('PMU-M55', None ), # M55
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x31, 0x0a31) : CmpInfo('MTB-M35P', None ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x43, 0x1a01) : CmpInfo('ITM-M35P', ITM.factory ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x00, 0x1a02) : CmpInfo('DWT-M35P', DWTv2.factory ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x00, 0x1a03) : CmpInfo('BPU-M35P', FPB.factory ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x14, 0x1a14) : CmpInfo('CTI-M35P', None ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x00, 0x2a04) : CmpInfo('SCS-M35P', CortexM_v8M.factory ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x13, 0x4a13) : CmpInfo('ETM-M35P', None ), # M35P
(ARM_ID, CORESIGHT_CLASS, 0xd31, 0x11, 0) : CmpInfo('TPIU-M35P', TPIU.factory ), # M35P
(ARM_ID, GENERIC_CLASS, 0x000, 0x00, 0) : CmpInfo('SCS-M3', CortexM.factory ),
(ARM_ID, GENERIC_CLASS, 0x001, 0x00, 0) : CmpInfo('ITM', ITM.factory ),
(ARM_ID, GENERIC_CLASS, 0x002, 0x00, 0) : CmpInfo('DWT', DWT.factory ),
(ARM_ID, GENERIC_CLASS, 0x003, 0x00, 0) : CmpInfo('FPB', FPB.factory ),
(ARM_ID, GENERIC_CLASS, 0x004, 0x00, 0) : CmpInfo('SCS-SC300', CortexM.factory ),
(ARM_ID, GENERIC_CLASS, 0x005, 0x00, 0) : CmpInfo('ITM', ITM.factory ),
(ARM_ID, GENERIC_CLASS, 0x006, 0x00, 0) : CmpInfo('DWT', DWT.factory ),
(ARM_ID, GENERIC_CLASS, 0x007, 0x00, 0) : CmpInfo('FPB', FPB.factory ),
(ARM_ID, GENERIC_CLASS, 0x008, 0x00, 0) : CmpInfo('SCS-M0+', CortexM.factory ),
(ARM_ID, GENERIC_CLASS, 0x00a, 0x00, 0) : CmpInfo('DWT-M0+', DWT.factory ),
(ARM_ID, GENERIC_CLASS, 0x00b, 0x00, 0) : CmpInfo('BPU', FPB.factory ),
(ARM_ID, GENERIC_CLASS, 0x00c, 0x00, 0) : CmpInfo('SCS-M4', CortexM.factory ),
(ARM_ID, GENERIC_CLASS, 0x00d, 0x00, 0) : CmpInfo('SCS-SC000', CortexM.factory ),
(ARM_ID, GENERIC_CLASS, 0x00e, 0x00, 0) : CmpInfo('FPB', FPB.factory ),
(ARM_ID, SYSTEM_CLASS, 0x101, 0x00, 0) : CmpInfo('TSGEN', None ), # Timestamp Generator
(FSL_ID, CORESIGHT_CLASS, 0x000, 0x04, 0) : CmpInfo('MTBDWT', None ),
}
|
StarcoderdataPython
|
6474786
|
import logging
import os
from git import NoSuchPathError, GitCommandError, InvalidGitRepositoryError
from assigner.backends import RepoError
from assigner.backends.exceptions import RetryableGitError
from assigner import progress
from assigner.backends.decorators import requires_config_and_backend
from assigner.roster_util import get_filtered_roster
from prettytable import PrettyTable
help = "Clone or fetch student repos"
logger = logging.getLogger(__name__)
@requires_config_and_backend
def get(conf, backend, args):
_get(conf, backend, args)
# Sans decorator to ease testing
def _get(conf, backend, args):
"""
Creates a folder for the assignment in the CWD (or <path>, if specified)
and clones each students' repository into subfolders.
"""
hw_name = args.name
hw_path = args.path
namespace = conf.namespace
semester = conf.semester
backend_conf = conf.backend
branch = args.branch
force = args.force
attempts = args.attempts
roster = get_filtered_roster(conf.roster, args.section, args.student)
path = os.path.join(hw_path, hw_name)
os.makedirs(path, mode=0o700, exist_ok=True)
output = PrettyTable(["#", "Sec", "SID", "Name", "Change"], print_empty=False)
output.align["Name"] = "l"
output.align["Change"] = "l"
for i, student in progress.enumerate(roster):
username = student["username"]
student_section = student["section"]
full_name = backend.student_repo.build_name(semester, student_section,
hw_name, username)
try:
repo = backend.student_repo(backend_conf, namespace, full_name)
repo_dir = os.path.join(path, username)
row = str(i + 1)
sec = student["section"]
sid = student["username"]
name = student["name"]
try:
logging.debug("Attempting to use local repo %s...", repo_dir)
repo.add_local_copy(repo_dir)
logging.debug("Local repo exists, fetching...")
results = repo.repo.remote().fetch()
for result in results:
logging.debug(
"fetch result: name: %s flags: %s note: %s",
result.ref.name,
result.flags,
result.note
)
# see:
# http://gitpython.readthedocs.io/en/stable/reference.html#git.remote.FetchInfo
if result.flags & result.NEW_HEAD:
output.add_row([
row, sec, sid, name, "{}: new branch at {}".format(
result.ref.name, str(result.ref.commit)[:8]
)
])
row = sec = sid = name = "" # don't print user info more than once
elif result.old_commit is not None:
output.add_row([
row, sec, sid, name, "{}: {} -> {}".format(
result.ref.name, str(result.old_commit)[:8],
str(result.ref.commit)[:8]
)
])
row = sec = sid = name = ""
logging.debug("Pulling specified branches...")
for b in branch:
try:
repo.get_head(b).checkout(force=force)
repo.pull(b)
except GitCommandError as e:
logging.debug(e)
logging.warning("Local changes to %s/%s would be overwritten by pull",
username, b)
logging.warning(" (use --force to overwrite)")
except (NoSuchPathError, InvalidGitRepositoryError):
logging.debug("Local repo does not exist; cloning...")
repo.clone_to(repo_dir, branch, attempts)
output.add_row([row, sec, sid, name, "Cloned a new copy"])
# Check out first branch specified; this is probably what people expect
# If there's just one branch, it's already checked out by the loop above
if len(branch) > 1:
repo.get_head(branch[0]).checkout()
except RetryableGitError as e:
logging.warning(e)
except RepoError as e:
logging.warning(e)
out_str = output.get_string()
if out_str != "":
print(out_str)
else:
print("No changes since last call to get")
def setup_parser(parser):
parser.add_argument("name",
help="Name of the assignment to clone or fetch.")
parser.add_argument("path", default=".", nargs="?",
help="Path to clone student repositories to")
parser.add_argument("--branch", "--branches", nargs="+", default=["master"],
help="Local branch or branches to pull when fetching")
parser.add_argument("-f", "--force", action="store_true", dest="force",
help="Discard local changes to student repositories when fetching")
parser.add_argument("--section", nargs="?",
help="Section to retrieve")
parser.add_argument("--student", metavar="id",
help="ID of student whose assignment needs retrieving.")
parser.add_argument("--attempts", default=5,
help="Number of times to retry failed git commands")
parser.set_defaults(run=get)
|
StarcoderdataPython
|
11380203
|
import pyblish.api
class ValidateContextHasInstance(pyblish.api.ContextPlugin):
"""確認場景有物件需要發佈
如果這個檢查出現錯誤,請使用 Creator 工具創建 Subset Instance 再進行發佈
"""
"""Context must have instance to publish
Context must have at least one instance to publish, please create one
if there is none.
"""
label = "發佈項目提交"
order = pyblish.api.ValidatorOrder - 0.49
def process(self, context):
msg = "No instance to publish, please create at least one instance."
assert len(context), msg
msg = "No instance to publish, please enable at least one instance."
assert any(inst.data.get("publish", True) for inst in context), msg
|
StarcoderdataPython
|
183380
|
<filename>SSolver.py
board = [[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]]
def solve():
if (checkBoard()):
return True
"Takes a sudoku board in array form as a parameter "
for y in range(0, 9):
for x in range(0, 9):
if (board[y][x] == 0):
for i in range(1, 10):
if (checkValid(x, y, i)):
board[y][x] = i
if (solve()):
return True
else:
board[y][x] = 0
return False
return True
def checkBoard():
for y in range(0, 9):
for x in range(0, 9):
if (board[y][x] == 0):
return False
return True
def checkValid(x, y, val):
"Checking x axis"
for i in range(0, len(board[y])):
if (board[y][i] == val):
return False
"Check y axis"
for i in range(0, len(board)):
if (board[i][x] == val):
return False
"Checking surrounding square"
if (y == 0 or y == 3 or y == 6):
if (csx(x, y+1, val) and csx(x, y+2, val)):
return True
if (y == 1 or y == 4 or y == 7):
if (csx(x, y-1, val) and csx(x, y+1, val)):
return True
else:
if (csx(x, y-1, val) and csx(x, y-2, val)):
return True
return False
def csx(x, y, val):
if (x == 0 or x == 3 or x == 6):
if (board[y][x+1] == val or board[y][x+2] == val):
return False
return True
if (x == 1 or x == 4 or x == 7):
if (board[y][x-1] == val or board[y][x+1] == val):
return False
return True
else:
if (board[y][x-1] == val or board[y][x-2] == val):
return False
return True;
def printBoard():
for i in range(0, len(board)):
print(board[i])
if (solve()):
printBoard()
|
StarcoderdataPython
|
6524862
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from os import environ
environ['SDL_VIDEO_CENTERED'] = '1'
import os.path
thisrep = os.path.dirname(__file__)
imagesrep = os.path.join(thisrep,'images')
from pygame import *
font.init()
from subprocess import Popen,PIPE
from sys import stdout
import pickle
from Buttons import Button0
from textwrap import wrap
import sys
from PygameReadWrite import text
label,title,mode,fontsize,width,bgcolor,fgcolor = pickle.loads(sys.stdin.buffer.read() if sys.version_info[0]==3 else sys.stdin.read())
try: label = label.decode('utf-8')
except AttributeError: pass
try: title = title.decode('utf-8')
except AttributeError: pass
font = font.Font(os.path.join(thisrep,'MonospaceTypewriter.ttf'),fontsize)
marge = 10
border = 2
linecolor = fgcolor
titlecolor = fgcolor
marge *= 2
border *= 2
char_w,char_h = font.size(' ')
foo = max((3*52,len(title)*char_w))
w = width-marge-border
if w < foo: w = foo
charperline = (w+(char_w-1))//char_w
label = text.Text(label,charperline)
width = charperline*char_w+marge+border
height = char_h*(len(label)+(3 if title else 1))+52+marge+border
scr = display.set_mode((width,height),NOFRAME)
r = scr.get_rect()
scr.fill(bgcolor)
r.inflate_ip(-border,-border)
draw.rect(scr,fgcolor,r,1)
r.inflate_ip(-marge,-marge)
y = r.y
if title:
title = text.Text(title,charperline)
title.screen(scr,r.topleft,fgcolor,font)
y = r.y + 2*char_h
draw.line(scr,linecolor,(r.left,r.top+char_h*1.5),(r.right,r.top+char_h*1.5),1)
x = r.x
label.screen(scr,(x,y),fgcolor,font)
YES = Button0(image.load(os.path.join(imagesrep,"valid.png")))
YES.midbottom =r.midbottom
NO = Button0(image.load(os.path.join(imagesrep,"cancel.png")))
NO.left = (r.w-104)//3+(marge+border)//2
NO.bottom = r.bottom
back = Button0(image.load(os.path.join(imagesrep,"back.png")))
back.midbottom = r.midbottom
buttons = [YES]
if mode >= 2:
buttons.append(NO)
YES.right = width-NO.left
if mode == 3:
buttons.append(back)
NO.bottomleft = r.bottomleft
YES.bottomright = r.bottomright
for i in buttons: i.screen()
display.flip()
run = True
while run:
ev = event.wait()
for button,output in zip(buttons,(True,False,None)):
if button.update(ev):
scr.fill(bgcolor,button)
display.update(button.screen())
if button.status:
pickle.dump(output,sys.stdout.buffer if sys.version_info[0]==3 else sys.stdout,protocol=2)
run = False
break
|
StarcoderdataPython
|
1647053
|
# twitter sentiment analysis
# (c) <NAME>, The Medusa's Cave Blog 2012
# Description: This file performs simple sentiment analysis on global twitter feeds
# Later versions may improve on the sentiment analysis algorithm
import os, sys, time; # import standard libraries
from twython import Twython; # import the Twitter Twython module
twitter = Twython(); # initialize it
f=open("neg.txt","r"); # open the file with keywords for sentiment analysis
fc=f.readlines(); # read it
wrds=[i.replace("\n","") for i in fc]; # save it for use
g=open("twit.txt","w"); # open the output file
g.write("@time, #tweets, sentiment index: % positive, % negative\n"); # write header to it
while True: # forever...
search_results = twitter.searchTwitter(q=sys.argv[1], rpp="500");
# search twitter feeds for the specified topic of interest with
# max results per page of 500.
x=search_results["results"]; # grab results from search
r=[]; # create placeholder to hold tweets
for i in x:
t=i["text"];
txt="".join([j for j in t if ord(j)<128]);
# parse tweets and gather those not directed to particular users
if txt.find("@")==-1: r+=[txt];
neg=0; # set counter for negative tweets
for i in r:
for j in wrds: # check against word list, calculate how many negatives
if i.lower().find(j)>-1:
break;
if j=="":
#print "pos,",i; # treating non-negatives as positives in this iteration
pass; # this may change later as we evolve to support three categories
else:
#print "neg,",i;
neg+=1;
#print "number of negatives: ",neg;
#print "sentiment index: positive: %5.2f%% negative: %5.2f%%" %((len(r)-neg)/float(len(r))*100,neg/float(len(r))*100);
#print ",".join([time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),str(len(r)),str((len(r)-neg)/float(len(r))*100)[:5]+"%",str(neg/float(len(r))*100)[:5]+"%"]);
g.write(",".join([time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),str(len(r)),str((len(r)-neg)/float(len(r))*100)[:5]+"%",str(neg/float(len(r))*100)[:5]+"%"])+"\n");
g.flush(); # write output to file, flush it, then sync it to disk immediately.
os.fsync(g.fileno());
time.sleep(180); # sleep for 3 mins then try again
g.close(); # close file after forever and exit program
sys.exit(0); # these two lines never reached but kept for completeness
|
StarcoderdataPython
|
3210403
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Plugin for the Zeitgeist SQLite database.
Zeitgeist is a service which logs the user activities and events, anywhere
from files opened to websites visited and conversations.
"""
from plaso.events import time_events
from plaso.lib import eventdata
from plaso.parsers import sqlite
from plaso.parsers.sqlite_plugins import interface
class ZeitgeistEvent(time_events.JavaTimeEvent):
"""Convenience class for a Zeitgeist event."""
DATA_TYPE = 'zeitgeist:activity'
def __init__(self, java_time, row_id, subject_uri):
"""Initializes the event object.
Args:
java_time: The Java time value.
row_id: The identifier of the corresponding row.
subject_uri: The Zeitgeist event.
"""
super(ZeitgeistEvent, self).__init__(
java_time, eventdata.EventTimestamp.UNKNOWN)
self.offset = row_id
self.subject_uri = subject_uri
class ZeitgeistPlugin(interface.SQLitePlugin):
"""SQLite plugin for Zeitgeist activity database."""
NAME = 'zeitgeist'
DESCRIPTION = u'Parser for Zeitgeist activity SQLite database files.'
# TODO: Explore the database more and make this parser cover new findings.
QUERIES = [
('SELECT id, timestamp, subj_uri FROM event_view',
'ParseZeitgeistEventRow')]
REQUIRED_TABLES = frozenset(['event', 'actor'])
def ParseZeitgeistEventRow(
self, parser_context, row, query=None, **unused_kwargs):
"""Parses zeitgeist event row.
Args:
parser_context: A parser context object (instance of ParserContext).
row: The row resulting from the query.
query: Optional query string. The default is None.
"""
event_object = ZeitgeistEvent(row['timestamp'], row['id'], row['subj_uri'])
parser_context.ProduceEvent(
event_object, plugin_name=self.NAME, query=query)
sqlite.SQLiteParser.RegisterPlugin(ZeitgeistPlugin)
|
StarcoderdataPython
|
1820114
|
<filename>Lib/color.py
import colorsys
import numpy as np
def generate_color(num_Color:int) -> list:
"""
https://github.com/qqwweee/keras-yolo3/blob/master/yolo.py
L82 - L91
"""
hsv_tuples = [(x / num_Color, 1., 1.) for x in range(num_Color)]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))
np.random.seed(10101) # Fixed seed for consistent colors across runs.
np.random.shuffle(colors) # Shuffle colors to decorrelate adjacent classes.
np.random.seed(None) # Reset seed to default
return colors
|
StarcoderdataPython
|
3566222
|
from __future__ import division
from __future__ import print_function
import numpy as np
from numpy.random import rand
from numpy import linalg as LA
import matplotlib
import matplotlib.pyplot as plt
from scipy import interpolate
from matplotlib.patches import Arrow, Circle, Rectangle
from matplotlib.patches import ConnectionPatch, Polygon
from matplotlib import rc
rc('font',**{'family':'sans-serif', 'size' : 10}) #, 'sans-serif':['Arial']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
#info on phase diagram
#black dot -> Q=1/3 vortices unbind
#red dot -> Q=1 vortices unbind
#green triangles -> cv max
#list of tcs at L=40
list_of_everything = np.loadtxt('tcs.data')
lambda3=2.1
#fraction=j2/j6
#temperature range
Tmax = 1.6
Tmax_plot = 1.6
Tmin = 0.6
figure_size = (3.4, 3.4)
fig = plt.figure(figsize = figure_size)
#fig = plt.figure()
#print(figure_size)
ax = plt.subplot(1,1,1)
#lambda = 0 KT points
tkt = 0.89
#plotting the two bare KT transitions
#all_cross = [[stiff_cross_j2, '*', 'black'], [sp_heat_cross_j2, '*', 'blue'], [binder_potts_j2, 'o', 'blue']]
#plot the black dotted box of the inside part
#plt.plot([0.5, 1.5], [Tmin, Tmin], color = 'black', linestyle = '--')
#plt.plot([0.5, 1.5], [Tmax, Tmax], color = 'black', linestyle = '--')
patches_stiff = []
patches_cv = []
patches_stiff2 = []
patches_cv2 = []
range_J2 = []
ixB = []
iyB = []
ixC = []
iyC = []
fP = []
fP_x = []
fKT1 = []
fKT1_x = []
fKT2 = []
fKT2_x = []
for i in range(len(list_of_everything)):
vals = list_of_everything[i]
if vals[3] == 0:
col = 'mediumpurple'
else:
col = 'teal'
patches_stiff.append(Circle((vals[0], vals[2]), radius=0.01, facecolor=col, edgecolor = 'black', linewidth = 0.5, zorder = 4))
#patches_cv.append(Circle((vals[0], vals[1]), radius=0.01, facecolor='red', edgecolor = 'black'))
patches_stiff2.append(Circle((vals[0], vals[2]), radius=0.01, facecolor=col, edgecolor = 'black', linewidth = 0.5, zorder = 4))
#patches_cv2.append(Circle((vals[0], vals[1]), radius=0.01, facecolor='red', edgecolor = 'black'))
range_J2.append(vals[0])
if 0.85 <= vals[0] <= 1.1:
ixB.append(vals[0])
ixC.append(vals[0])
iyB.append(vals[2])
if vals[0] <= 1.1:
fP_x.append(vals[0])
if vals[0] <= 0.85:
fKT1.append(vals[2])
fKT1_x.append(vals[0])
if 0.85 <= vals[0]:
fKT2.append(vals[2])
fKT2_x.append(vals[0])
range_J2 = np.array(range_J2)
N_cp = 40
Kc = 0.0
range_T = np.linspace(Tmin + 0.0001, Tmax, 60)
initial_cv_val = np.loadtxt('CV_data_pd.txt')
gridplot_cv = np.zeros((len(range_T), len(range_J2)))
for j in range(len(range_J2)):
#cv
#gridplot_cv[:,j] = (final_cv_val)
#log of cv
gridplot_cv[:,j] = np.log(initial_cv_val[:,j])
#get cv_max for that size
initial_cv_val_here = initial_cv_val[:,j]
maxcv = range_T[np.where(initial_cv_val_here == np.max(initial_cv_val_here))[0][0]]
print(maxcv)
if range_J2[j] > 1.2:
maxcv = list_of_everything[j][1]
if range_J2[j] <= 1.1:
patches_cv.append(Circle((range_J2[j], maxcv), radius=0.01, facecolor='red', edgecolor = 'black', linewidth = 0.5, zorder = 5))
patches_cv2.append(Circle((range_J2[j], maxcv), radius=0.01, facecolor='red', edgecolor = 'black', linewidth = 0.5, zorder = 5))
else:
patches_cv.append(Rectangle((range_J2[j]- 0.01, maxcv - 0.01), 0.01, 0.01, facecolor='red', edgecolor = 'black', linewidth = 0.5, zorder = 5))
patches_cv2.append(Rectangle((range_J2[j] - 0.01, maxcv - 0.01), 0.01, 0.01, facecolor='red', edgecolor = 'black', linewidth = 0.5, zorder = 5))
if 0.85 <= range_J2[j] <= 1.1:
iyC.append(maxcv)
if range_J2[j] <= 1.1:
fP.append(maxcv)
#adding second peaks
second_peaks = [57, 55, 50, 46, 43, 39];
for m in range(6):
maxcv2 = range_T[second_peaks[m]]
patches_cv.append(Rectangle((range_J2[m]- 0.01, maxcv2 - 0.01), 0.01, 0.01, facecolor='red', edgecolor = 'black', linewidth = 0.5, zorder = 5))
ixB = np.array(ixB)[::-1]
ixC = np.array(ixC)
iyB = np.array(iyB)[::-1]
iyC = np.array(iyC)
im = ax.imshow(gridplot_cv, interpolation='spline16', cmap='YlGn',origin='lower', extent = [0.5 - 0.025, 1.5 + 0.025, 0.6 - 1/(2*59), 1.6 + 1/(2*59)])
#fig.colorbar(im, shrink=0.5)
clb = plt.colorbar(im, shrink=0.65)
clb.ax.tick_params(labelsize=9)
# #clb.ax.set_title(r'$C_v/N$', fontsize = 12)
clb.ax.set_title(r'$\log \, c_v$', fontsize = 9)
#print(f'Potts (\Delta, T_3) = ({fP_x}, {fP}).')
#print(f'KT hexatic (\Delta, T_6) = ({fKT1_x}, {fKT1}).')
#print(f'KT nematic (\Delta, T_2) = ({fKT2_x}, {fKT2}).')
ax.plot(fP_x, fP, color = 'red', linewidth=0.5)
ax.plot(fKT1_x, fKT1, color = 'mediumpurple', linewidth=0.5)
ax.plot(fKT2_x, fKT2, color = 'teal', linewidth=0.5)
for p in patches_stiff:
ax.add_patch(p)
for ps in patches_cv:
ax.add_patch(ps)
plt.xlabel('$\Delta$', fontsize=9);
plt.ylabel('$T/J$', fontsize=9)
#ticks
major_ticks_x = np.arange(0.5, 1.5 + 0.01, 0.25)
minor_ticks_x = np.arange(0.5, 1.5 + 0.01, 0.05)
major_ticks_y = np.arange(0.6, 1.6 + 0.01, 0.2)
minor_ticks_y = np.arange(0.6, 1.6 + 0.01, 0.05)
tick_print_x = []
for elem in major_ticks_x:
tick_print_x.append('${:.2f}$'.format(elem))
tick_print_y = []
for elem in major_ticks_y:
tick_print_y.append('${:.1f}$'.format(elem))
ax.set_xticks(major_ticks_x)
ax.set_yticks(major_ticks_y)
ax.set_xticklabels(tick_print_x, fontsize = 9)
ax.set_yticklabels(tick_print_y, fontsize = 9)
ax.set_xticks(minor_ticks_x, minor=True)
ax.set_yticks(minor_ticks_y, minor=True)
#ax.set_xticklabels(tick_print, rotation=315)
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.4)
#ax.set_xlim([0,2])
#ax.set_ylim([0,Tmax_plot])
#putting the x label away from the center
#ax.xaxis.set_label_coords(1.08, -0.03)
# Draw a line between the different points, defined in different coordinate
# systems.
#dotted lines for the two parameters studied
#ax.plot([1.0, 1.0], [0.6, 1.6], linestyle = '--', color = 'black', linewidth = 2)
#ax.plot([0.5, 0.5], [0.6, 1.6], linestyle = '--', color = 'black', linewidth = 2)
#
# textstr = r'ordered'
# ax.text(0.5, 0.30, textstr, transform=ax.transAxes, fontsize=30,
# verticalalignment='top')
# textstr = r'hexatic'
# ax.text(0.05, 0.5, textstr, transform=ax.transAxes, fontsize=30,
# verticalalignment='top')
# textstr = r'disordered'
# ax.text(0.35, 0.85, textstr, transform=ax.transAxes, fontsize=30,
# verticalalignment='top')
#bbox= dict(boxstyle='square', fc="none", ec="k")
###########################
#####inset
###########################
ax.set_ylim([0.6, 1.6])
#ax.set_ylim([0,Tmax_plot])
#ax.indicate_inset_zoom(axins)
plt.tight_layout()
plt.show()
plt.savefig('./fig-phasediagram2-logcv.png', format='png',dpi = 600, bbox_inches='tight')
#plt.show()
|
StarcoderdataPython
|
8069563
|
class Solution:
#@param num: A list of non negative integers
#@return: A string
def largestNumber(self, num):
# write your code here
def quickSort(arr):
if (len(arr) <= 1):
return arr
mid = str(arr[0])
smaller = filter(lambda a: str(a) + mid > mid + str(a), arr[1:])
larger = filter(lambda a: str(a) + mid <= mid + str(a), arr[1:])
return quickSort(smaller) + [mid] + quickSort(larger)
sorted_num = quickSort(num)
sorted_num = map(lambda a: str(a), sorted_num)
res = ''.join(sorted_num)
return "0" if int(res) == 0 else res
|
StarcoderdataPython
|
126830
|
from django.urls import path, include, re_path
from . import views
app_name = 'accounts'
urlpatterns = [
re_path(r'^reachus', views.reachus, name='reachus'),
re_path(r'^login', views.login, name='login'),
re_path(r'^signup', views.signup, name='signup'),
re_path(r'^campus_signup', views.campus_signup, name='campus_signup'),
re_path(r'^step1', views.step1, name='step1'),
re_path(r'^step2', views.step2, name='step2'),
re_path(r'^step3', views.step3, name='step3'),
path('teamsignup/<encodeddata>/', views.teamsignup, name='teamsignup'),
path('teamsignupcomplete/', views.teamsignupcomplete, name='teamsignupcomplete'),
re_path(r'^logout', views.logout, name='logout'),
re_path(r'^forgot_password', views.forgot_password, name='forgot_password'),
path('reset_confirm/<umail>/', views.reset_confirm, name='reset_confirm'),
path('reset_password_successful', views.reset_password_successful, name='reset_password_successful')
]
|
StarcoderdataPython
|
156135
|
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
class OutageTest(TestCase):
def test_command_output(self):
out = StringIO()
# call_command("playlists", stdout=out)
# self.assertIn("Expected output", out.getvalue())
|
StarcoderdataPython
|
5048826
|
<filename>main.py
from hktm import create_app
app = create_app('prod.cfg')
#app.run(host='0.0.0.0')
|
StarcoderdataPython
|
1810268
|
def copy(a):
"""
Returns a copy of a given Galois field array.
See: https://numpy.org/doc/stable/reference/generated/numpy.copy.html
Warning
-------
This function returns an :obj:`numpy.ndarray`, not an instance of the subclass. To return a copy of the subclass, pass
`subok=True` (for numpy version 1.19 and above) or use `a.copy()`.
Examples
--------
.. ipython:: python
GF = galois.GF(2**3)
a = GF.Random(5, low=1); a
# NOTE: b is an ndarray
b = np.copy(a); b
type(b)
a[0] = 0; a
# b is unmodified
b
.. ipython:: python
a.copy()
"""
return
def concatenate(arrays, axis=0):
"""
Concatenates the input arrays along the given axis.
See: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html
Examples
--------
.. ipython:: python
GF = galois.GF(2**3)
A = GF.Random((2,2)); A
B = GF.Random((2,2)); B
np.concatenate((A,B), axis=0)
np.concatenate((A,B), axis=1)
"""
return
def insert(array, object, values, axis=None):
"""
Inserts values along the given axis.
See: https://numpy.org/doc/stable/reference/generated/numpy.insert.html
Examples
--------
.. ipython:: python
GF = galois.GF(2**3)
x = GF.Random(5); x
np.insert(x, 1, [0,1,2,3])
"""
return
|
StarcoderdataPython
|
11331476
|
<filename>Infer.py<gh_stars>1-10
# Load and run neural network and make preidction
import numpy as np
import torchvision.models.segmentation
import torch
import torchvision.transforms as tf
width=height=900 # image width and height
modelPath="400.torch"
#---------------------create image ---------------------------------------------------------
FillLevel=0.7
Img=np.zeros([900,900,3],np.uint8)
Img[0:int(FillLevel*900),:]=255
#-------------Transform image to pytorch------------------------------------------------------
transformImg = tf.Compose([tf.ToPILImage(), tf.Resize((height, width)), tf.ToTensor(),
tf.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])
Img=transformImg(Img)
#------------------Create batch----------------------------------------------
images = torch.zeros([1,3,height,width]) # Create batch for one image
images[0]=Img
#--------------Load and net-------------------------------------
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
Net = torchvision.models.resnet18(pretrained=True) # Load net
Net.fc = torch.nn.Linear(in_features=512, out_features=1, bias=True) # Set final layer to predict one value
Net = Net.to(device) # Assign net to gpu or cpu
#
Net.load_state_dict(torch.load(modelPath)) # Load trained model
#Net.eval() # Set net to evaluation mode, usually usefull in this case its fail
#----------------Make preidction--------------------------------------------------------------------------
Img = torch.autograd.Variable(Img, requires_grad=False).to(device).unsqueeze(0) # Convert to pytorch
with torch.no_grad():
Prd = Net(Img) # Run net
print("Predicted fill level", Prd.data.cpu().numpy())
print("Real fill level", FillLevel)
|
StarcoderdataPython
|
205778
|
import cv2
import os
import sys
from scipy.io import loadmat
import os.path as osp
import numpy as np
import json
from PIL import Image
import pickle
from sklearn.metrics import average_precision_score
from sklearn.preprocessing import normalize
from iou_utils import get_max_iou, get_good_iou
def compute_iou(a, b):
x1 = max(a[0], b[0])
y1 = max(a[1], b[1])
x2 = min(a[2], b[2])
y2 = min(a[3], b[3])
inter = max(0, x2 - x1) * max(0, y2 - y1)
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
return inter * 1.0 / union
def set_box_pid(boxes, box, pids, pid):
for i in range(boxes.shape[0]):
if np.all(boxes[i] == box):
pids[i] = pid
return
print("Person: %s, box: %s cannot find in images." % (pid, box))
def image_path_at(data_path, image_index, i):
image_path = osp.join(data_path, image_index[i])
assert osp.isfile(image_path), "Path does not exist: %s" % image_path
return image_path
def load_image_index(root_dir, db_name):
"""Load the image indexes for training / testing."""
# Test images
test = loadmat(osp.join(root_dir, "annotation", "pool.mat"))
test = test["pool"].squeeze()
test = [str(a[0]) for a in test]
if db_name == "psdb_test":
return test
# All images
all_imgs = loadmat(osp.join(root_dir, "annotation", "Images.mat"))
all_imgs = all_imgs["Img"].squeeze()
all_imgs = [str(a[0][0]) for a in all_imgs]
# Training images = all images - test images
train = list(set(all_imgs) - set(test))
train.sort()
return train
if __name__ == "__main__":
db_name = "psdb_test"
# root_dir = '~/Downloads/WRCAN-PyTorch/src/image'
# images_path = '/home/cvlab3/Downloads/WRCAN-PyTorch/src/images_cam/'
root_dir = '/home/cvlab3/Downloads/AlignPS/demo/anno/kist/'
with open('/home/cvlab3/Downloads/AlignPS/demo/anno/kist/test_new.json', 'r') as fid:
test_det = json.load(fid)
id_to_img = dict()
img_to_id = dict()
img_num = 0
for td in test_det['images']:
im_name = td['file_name'].split('/')[-1]
im_id = td['id']
id_to_img[im_id] = im_name
img_to_id[im_name] = im_id
img_num += 1
# print('0 img',id_to_img[0])
# print(len(id_to_img))
# image_file_names = os.listdir(images_path)
# id_to_img = dict()
# img_to_id = dict()
#
#
# for idx, f in enumerate(image_file_names):
# _, frame_no = f.split("|")
# file_name = f
# id_to_img[idx] = file_name
# img_to_id[file_name] = idx
# print('sys',sys.argv[1])
results_path = '/home/cvlab3/Downloads/AlignPS/work_dirs/faster_rcnn_r50_caffe_c4_1x_cuhk_single_two_stage17_6_nae1/'# + sys.argv[1]
#results_path = '/raid/yy1/mmdetection/work_dirs/fcos_center-normbbox-centeronreg-giou_r50_caffe_fpn_gn-head_dcn_4x4_1x_cuhk_reid_1500_stage1_fpncat_dcn_epoch24_multiscale_focal_x4_bg-2_sub_triqueue_nta_nsa'
#results_path = '/raid/yy1/mmdetection/work_dirs/fcos_center-normbbox-centeronreg-giou_r50_caffe_fpn_gn-head_4x4_1x_cuhk_reid_1000_fpncat'
# 'results_1000_x1'
# x1 = '_x1' #'_x1' ''
x1 = '_x1'
with open(os.path.join(results_path, 'results_1000{}.pkl'.format(x1)), 'rb') as fid:
all_dets = pickle.load(fid)
# print(all_dets[0])
gallery_dicts1 = {}
# gallery_dicts2 = {}
all_dets1 = all_dets[0]
# all_dets2 = all_dets[1]
# print(len(all_dets1), len(all_dets2))
num = 0
for i, dets in enumerate(all_dets1):
# print(i)
if i == 646:
break
image_id = i
gallery_dicts1[image_id] = dict()
# print(i)
gallery_dicts1[image_id]['bbox'] = dets[0][:, :4]
gallery_dicts1[image_id]['scores'] = dets[0][:, 4]
gallery_dicts1[image_id]['feats'] = dets[0][:, 5:]
gallery_dicts1[image_id]['pred_bbox'] = dets[0][:, :4]
r, = dets[0][:, 4].shape
list_num = []
# img = Image.open('/home/cvlab3/Downloads/WRCAN-PyTorch/src/images{}_cam/'.format(x1) + id_to_img[i])
img = cv2.imread('/home/cvlab3/Downloads/WRCAN-PyTorch/src/images{}_cam/'.format(x1) + id_to_img[i])
for k in range(r):
if gallery_dicts1[image_id]['scores'][k] > 0.2:
# print('bbox',gallery_dicts1[image_id]['bbox'][i])
numbers = gallery_dicts1[image_id]['bbox'][k]
# print(numbers)
list_num.append(numbers)
l = int(numbers[0])
t = int(numbers[1])
r = int(numbers[2])
b = int(numbers[3])
# print((l,r), (r,b))
cv2.rectangle(img, (l,t),(r,b),(0,0,255),3)
# print('bbox', (numbers))
# cropped_img = img.crop((numbers))
# cropped_img.save("/home/cvlab3/Downloads/WRCAN-PyTorch/src/images_modify{}_result/{}_{}.jpeg".format(x1,i,num))
num = num +1
gallery_dicts1[image_id]['pred_bbox'] = np.array(list_num, dtype=object)
# img.save("/home/cvlab3/Downloads/WRCAN-PyTorch/src/images{}_result/{}_{}.jpeg".format(x1, i, num))
cv2.imwrite("/home/cvlab3/Downloads/WRCAN-PyTorch/src/images_modify{}_result/{}_{}.jpeg".format(x1, i, num), img) # save img
# if gallery_dicts1[image_id]['scores']
# cv2.imwrite("/home/cvlab3/Downloads/WRCAN-PyTorch/src/images_result/{}.jpeg".format(i),
# gallery_dicts1[image_id]['bbox'])
thres = 0.2
ap = 0
precision = {}
recall = {}
for image_id in range(img_num-1):
query_box = gallery_dicts1[image_id]['pred_bbox'] # predicted bb
query_box = [list(map(int, q)) for q in query_box]
box = [b['bbox'] for b in test_det['annotations'] if b['image_id']==image_id]
# boxs.append(box)
query_gt_box = box
tp_num = get_max_iou(query_box, query_gt_box)
# print('tp_num ', tp_num)
if (len(query_gt_box) ==0) or (len(query_box)==0):
# precision[image_id] = 0
# recall = 0
continue
precision[image_id]=tp_num/len(query_box)
recall[image_id]= tp_num/len(query_gt_box)
# ap += precision*recall
ap_num = 0
for i in range(img_num-1):
# if i+1:
# print(precision[i+1],recall[i+1],recall[i])
# if (precision[i+1]) and (recall[i+1]) and (recall[i]):
try:
ap += precision[i+1]*(recall[i+1]-recall[i])
ap_num += 1
except:
pass
map = ap/ap_num
print('map',map)
# exit()
|
StarcoderdataPython
|
8084935
|
from django.core.management.base import BaseCommand, CommandError
from memes.tasks.fetchmemes import RedditMemeFetcher, GiphyMemeFetcher
class Command(BaseCommand):
help = 'Fetch Memes from each reddit,instagram,giphy,facebook'
''' now only reddit and giphy '''
redditmeme = RedditMemeFetcher()
giphymeme = GiphyMemeFetcher()
redditmeme.getInitialMemes()
giphymeme.getInitialMemes()
giphymeme.getTheOfficeMemes()
def handle(self, *args, **options):
self.stdout.write(self.style.SUCCESS('Successfully fetched everything'))
|
StarcoderdataPython
|
9656096
|
# -*- coding: utf-8 -*-
import pytest
from sktime.benchmarking.strategies import TSCStrategy
from sktime.benchmarking.tasks import TSCTask
from sktime.datasets import load_gunpoint
from sktime.datasets import load_italy_power_demand
from sktime.classification.compose import ComposableTimeSeriesForestClassifier
classifier = ComposableTimeSeriesForestClassifier(n_estimators=2)
DATASET_LOADERS = (load_gunpoint, load_italy_power_demand)
# Test output of time-series classification strategies
@pytest.mark.parametrize("dataset", DATASET_LOADERS)
def test_TSCStrategy(dataset):
train = dataset(split="train")
test = dataset(split="test")
s = TSCStrategy(classifier)
task = TSCTask(target="class_val")
s.fit(task, train)
y_pred = s.predict(test)
assert y_pred.shape == test[task.target].shape
|
StarcoderdataPython
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.