text
stringlengths
38
1.54M
from django.db import models from django.contrib.auth.models import User # Create your models here. class HighScore(models.Model): player = models.ForeignKey(User, on_delete=models.CASCADE, null=True) score = models.IntegerField(null=True) user_answer = models.JSONField(default=list) created_date = models.DateTimeField(null=True, auto_now_add=True, blank=True) # Show player name in Admin def __str__(self): return str(self.player)
import time import pdb import sys print sys.getdefaultencoding() print range(17501, 100000) def test(): now_time = time.time(); print now_time a= 10 print a # return a += 1 print a # exit b = 'test string' pdb.set_trace print pdb print b print time.time() if __name__ == '__main__': test()
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.db.models import Q import operator from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, ) from .models import Post from django.conf import settings # new from django.views.generic.base import TemplateView import stripe from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from .forms import ContactForm stripe.api_key = settings.STRIPE_SECRET_KEY def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['vehicle_type', 'manufacturer', 'model', 'year_of_purchase', 'place', 'distance_travelled','price', 'mileage', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['vehicle_type', 'manufacturer', 'model', 'year_of_purchase', 'place', 'distance_travelled','price', 'mileage', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def about(request): return render(request, 'blog/about.html', {'title': 'About'}) def contact(request): return render(request, 'blog/contact.html', {'title': 'Contact'}) class Payments(TemplateView): template_name = 'payments.html' def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='usd', description='A Django charge', source=request.POST['stripeToken'] ) return render(request, 'charge.html') def search(request): query = request.GET.get('q') results = Post.objects.filter(Q(title__icontains=query) | Q(content__icontains=query)) return render(request, 'blog/results.html', {'results': results}) def emailView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message.')
# Copyright (c) 2010, Trevor Bekolay # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # * Neither the name of the IRCL nor the names of its contributors may be used to # endorse or promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. valid_nwvar_types = ("object", "int", "float", "string") """A tuple containing the valid variable types in NWScript. @type: tuple of strings """ class ActualVerb(object): """ActualVerb holds information about an 'actual verb'. Actual verbs are the atomic actions defined in util_verbs.nss.""" def __init__(self, name="", description=""): """Sets up the ActualVerb's instance variables. @keyword name: The name of the ActualVerb @type name: string @keyword description: The description of the ActualVerb @type description: string """ self.name = name """ The name of the ActualVerb @type: string """ self.description = description """ The description of the ActualVerb @type: string """ self.vdarguments = [] """ The VerbData arguments that this ActualVerb requires. @type: list of strings """ self.varguments = [] """ The arguments that this ActualVerb requires. Comprised of a list of tuples of the form:: (Mandatory, Type, Name, Description) e.g.:: (True, "float", "fSpeed", "The speed at which the animation plays, relative to the default 1.0") @type: list of tuples """ class Behaviour(object): """An object to hold all of the information necessary to generate the code\ for a behaviour. Also contains methods to generate said code.""" def __init__(self): """Set up the behaviour's instance variables.""" self.verbs = [] """The list of verbs making up this behaviour. @type: list of L{Verb}s """ self.nwvariables = [] """The list of variables and actors that are used in this behaviour. @type: list of L{NWVariable}s """ self.name = "Behaviour" """The name of the behaviour. This is contrained to 12 characters, as the maximum length for an NWScript file is 16 characters and the behaviour name is prepended with "z_b_" for a script. @type: string """ def __setattr__(self, name, value): """Intercept changes to the name and update each verb. @param name: Name of the attribute being set. @type name: string @param value: The value to set the attribute to. """ if name == "name": if len(value) > 12: value = value[:11] for verb in self.verbs: verb.b_name = value object.__setattr__(self, name, value) def GenerateZBCode(self): """Generate the code for z_b_<behaviour> files. @return: The generated NWScript code. @rtype: string """ # Get the variables that we'll need in our generated code. lower_name = self.name.lower() upper_name = self.name.capitalize() z_b_code = """\ /* CODE GENERATED BY BEHAVIOUR TOOL */ #include \"b_%(lower_name)s\" // main will be called by a verb when it has been completed, through ExecuteScript. void main() { int iBehaviour = GetLocalInt(GetModule(), \"curr_behaviour\"); int iReturn = getVerbReturn(iBehaviour); int iVerb = getVerbFinished(iBehaviour); if (iReturn == SUCCESS) { control_%(upper_name)s(iBehaviour, iVerb); } else { timeout_%(upper_name)s(iBehaviour); } }""" % {'lower_name':lower_name, 'upper_name':upper_name} return z_b_code def GenerateBCode(self): """Generate the code for b_<behaviour> files. @return: The generated NWScript code. @rtype: string """ # Get the strings that we will need to plug into our shell # <behaviour name all lowercase> # e.g.: # fight lower_name = self.name.lower() # <behaviour name with the first letter capitalized> # e.g.: # Fight upper_name = self.name.capitalize() # VERBx: <context_name> <actual_name> <follower> <terminal> # VERBx_PRECONDITIONS: <preconditions seperated by ;;> # VERBx_FOLLOWERS: <followers seperated by spaces> # VERBx_VERBDATA: <vdarguments seperated by spaces> # VERBx_ARGUMENTS: <varguments seperated by ;;> # e.g.: # VERB1: instigate FaceAndSayLine Follower # VERB1_FOLLOWERS: retaliate callforhelp # VERB1_VERBDATA: oInstigator oVictim # VERB1_ARGUMENTS: "Hey punk! It's fightin' time!" verb_info_list = [] for ix, v in enumerate(self.verbs): if v.follower == True: follow_text = "Follower" else: follow_text = "Supporter" if v.terminal == True: terminal_text = "Terminal" else: terminal_text = "" verb_info_list.append("VERB%d: %s %s %s %s" % (ix+1, v.context_name, v.actual_name, follow_text, terminal_text)) if len(v.preconditions) > 0: precond_text = " VERB%d_PRECONDITIONS: " % (ix+1) for precond in v.preconditions: precond_text += (precond + ";; ") verb_info_list.append(precond_text[:-3]) if v.terminal == False: followers_text = " VERB%d_FOLLOWERS: " % (ix+1) for follow in v.followers: followers_text += (follow.context_name + ' ') verb_info_list.append(followers_text) vdargs_text = " VERB%d_VERBDATA: " % (ix+1) for vdarg in v.vdarguments: vdargs_text += (vdarg + ' ') verb_info_list.append(vdargs_text) if len(v.varguments) > 0: vargs_text = " VERB%d_ARGUMENTS: " % (ix+1) for varg in v.varguments: vargs_text += (varg + ";; ") verb_info_list.append(vargs_text[:-3]) verb_info = '\n'.join(verb_info_list) # ACTORx: <type> <name> <description> # e.g.: # ACTOR1: object oInstigator The instigator starts the fight. actor_info_list = [] ix = 1 for actor in self.nwvariables: if actor.isActor == True: actor_info_list.append("ACTOR%d: %s %s %s" % (ix, actor.type, actor.name, actor.description)) ix += 1 actor_info = '\n'.join(actor_info_list) # VARIABLEx: <type> <name> <description> # e.g.: # VARIABLE1: string sConv The conversation file to be run nwvar_info_list = [] ix = 1 for nwvar in self.nwvariables: if nwvar.isActor == False: nwvar_info_list.append("VARIABLE%d: %s %s %s" % (ix, nwvar.type, nwvar.name, nwvar.description)) ix += 1 nwvar_info = '\n'.join(nwvar_info_list) # const int <constant_name> = <id> # e.g.: # const int F_INSTIGATE_28 = 2 constants_list = [] for index, v in enumerate(self.verbs): if (v.follower == True): id = (index*2)+2 # + 2 to prevent an ID of 0 else: id = (index*2)+1 # + 1 to make supporters odd constants_list.append("const int %s = %d" % (v.constant_name, id)) constants = '\n'.join(constants_list) # // <name> - <description> # e.g.: # // oInstigator - The instigator starts the fight. nwvar_comments_list = [] for nwvar in self.nwvariables: nwvar_comments_list.append("// %s - %s" % (nwvar.name, nwvar.description)) nwvar_comments = '\n'.join(nwvar_comments_list) # , <type> <name> # e.g.: # , object oInstigator, object oVictim, string sConv nwvar_list = [] for nwvar in self.nwvariables: nwvar_list.append(", %s %s" % (nwvar.type, nwvar.name)) nwvars = ''.join(nwvar_list) # <name> != <invalid value> # e.g.: # oInstigator != OBJECT_INVALID && oVictim != OBJECT_INVALID && sConv != "" invalids_list = [] for nwvar in self.nwvariables: invalids_list.append("%s != %s" % (nwvar.name, nwvar.GetInvalidValue())) invalids = " && ".join(invalids_list) # b_Checkout(<name>, iID, iInterrupt) # e.g.: # b_Checkout(oInstigator, iID, iInterrupt) && b_Checkout(oVictim, iID, iInterrupt) checkout_list = [] for nwvar in self.nwvariables: if nwvar.isActor == True: checkout_list.append("b_Checkout(%s, iID, iInterrupt)" % (nwvar.name)) checkouts = " && ".join(checkout_list) # <first verb constant_name> # e.g.: # F_INSTIGATE_28 if len(self.verbs) > 0: firstverb_name = self.verbs[0].constant_name else: firstverb_name = "" # SetLocal<type>(o<behaviour name capitalized>, "<name>", <name>); # e.g.: # SetLocalObject(oFight, "oInstigator", oInstigator); # SetLocalObject(oFight, "oVictim", oVictim); # SetLocalString(oFight, "sConv", sConv); setlocal_list = [] for nwvar in self.nwvariables: setlocal_list.append(" SetLocal%s(o%s, \"%s\", %s);" % (nwvar.type.capitalize(), upper_name, nwvar.name, nwvar.name)) setlocals = '\n'.join(setlocal_list) # <type> <name> = GetLocal<type>(o<behaviour name capitalized>, "<name>"); # e.g.: # // Get the actors and other variables from the behaviour object. # object oInstigator = GetLocalObject(oFight, "oInstigator"); # object oVictim = GetLocalObject(oFight, "oVictim"); # string sConv = GetLocalString(oFight, "sConv"); getlocals_list = [" // Get the actors and other variables from the behaviour object."] for nwvar in self.nwvariables: getlocals_list.append(" %s %s = GetLocal%s(o%s, \"%s\");" % (nwvar.type, nwvar.name, nwvar.type.capitalize(), upper_name, nwvar.name)) getlocals = '\n'.join(getlocals_list) # case <constant_name>: # <verb's generated checkcues code> # break; # e.g.: # case F_INSTIGATE_28: # ... # break; # case F_RETALIATE_G8: # ... # break; # case S_CALLFORHELP_29: # ... # break; checkcues_switch_list = [] for v in self.verbs: checkcues_switch_list.append(" case %s:\n%s\n break;" % (v.constant_name, v.GenerateCheckcuesCode())) checkcues_switch = '\n'.join(checkcues_switch_list) # case <constant_name>: # <verb's generated control code> # break; # e.g.: # case F_INSTIGATE_28: # ... # break; # case F_RETALIATE_G8: # ... # break; # case S_CALLFORHELP_29: # ... # break; control_switch_list = [] for v in self.verbs: control_switch_list.append(" case %s:\n%s\n break;" % (v.constant_name, v.GenerateControlCode())) control_switch = '\n'.join(control_switch_list) # iPrevious = b_GetPausedBehaviour(<name>); # if (iPrevious) # { # setSegueToBehaviour(iPrevious, TRUE); # } # e.g.: # iPrevious = b_GetPausedBehaviour(oInstigator); # if (iPrevious) # { # setSegueToBehaviour(iPrevious, TRUE); # } # # iPrevious = b_GetPausedBehaviour(oVictim); # if (iPrevious) # { # setSegueToBehaviour(iPrevious, TRUE); # } segue_previous_list = [] for nwvar in self.nwvariables: if nwvar.isActor == True: segue_previous_list.append("""\ iPrevious = b_GetPausedBehaviour(%s); if (iPrevious) { setSegueToBehaviour(iPrevious, TRUE); }""" % (nwvar.name)) segue_previous = "\n\n".join(segue_previous_list) # b_Checkin(<name>); # e.g.: # b_Checkin(oInstigator); # b_Checkin(oVictim); checkin_list = [] for nwvar in self.nwvariables: if nwvar.isActor == True: checkin_list.append(" b_Checkin(%s);" % (nwvar.name)) checkin = '\n'.join(checkin_list) # Generate the code b_code = """\ /* CODE GENERATED BY BEHAVIOUR TOOL Don't delete this comment block! You can, however, modify the elements. Changes will show up when you reload the file. BEHAVIOUR: %(upper_name)s %(verb_info)s %(actor_info)s %(nwvar_info)s */ #include \"util_bintarray\" #include \"util_behaviour\" #include \"util_verbs\" /////////// Constants /////////// %(constants)s /////////// Declarations /////////// // Initializes the %(upper_name)s behaviour. %(nwvar_comments)s int start_%(upper_name)s(int iTimeout, int iInterrupt%(nwvars)s); void checkcues_%(upper_name)s(int iTimeout, int iBehaviour); void control_%(upper_name)s(int iBehaviour, int iVerb); void cleanup_%(upper_name)s(int iBehaviour); void timeout_%(upper_name)s(int iBehaviour); void segue_%(upper_name)s(int iBehaviour); /////////// Implementations /////////// int start_%(upper_name)s(int iTimeout, int iInterrupt%(nwvars)s) { // Make sure we have have what we need to start the behaviour. if (%(invalids)s) { object o%(upper_name)s = createBehaviourObject(); int iID = GetLocalInt(o%(upper_name)s, \"ID\"); // Check out our actors. if (%(checkouts)s) { // Set necessary parameters on the behaviour object. %(setlocals)s SetLocalInt (o%(upper_name)s, \"iInterrupt\", iInterrupt); SetLocalString(o%(upper_name)s, \"sScript\", \"z_b_%(lower_name)s\"); // Set up the cue array and add the first step to it. intarrayNew(o%(upper_name)s, \"cues\"); addCue(iID, %(firstverb_name)s); checkcues_%(upper_name)s(iTimeout, iID); return iID; } } return FALSE; } void checkcues_%(upper_name)s(int iTimeout, int iBehaviour) { %(getlocals)s // Are we finished? if (getBehaviourFinished(iBehaviour)) { cleanup_%(upper_name)s(iBehaviour); return; } // Check to see if we want to segue before we check if we're paused. if (getSegueToBehaviour(iBehaviour)) { segue_%(upper_name)s(iBehaviour); setSegueToBehaviour(iBehaviour, FALSE); setBehaviourPaused(iBehaviour, FALSE); DelayCommand(2*DEFAULT_HEARTBEAT_DELAY, checkcues_%(upper_name)s(iTimeout, iBehaviour)); return; } // If we're paused, we'll just idle (no need to check as often as usual). if (getBehaviourPaused(iBehaviour)) { DebugPrint(\"%(upper_name)s paused...\"); DelayCommand(4*DEFAULT_HEARTBEAT_DELAY, checkcues_%(upper_name)s(iTimeout, iBehaviour)); return; } // Have we timed out? if (!iTimeout) { timeout_%(upper_name)s(iBehaviour); DelayCommand(DEFAULT_HEARTBEAT_DELAY, checkcues_%(upper_name)s(iTimeout, iBehaviour)); return; } // Run through each cue and see if any of them fire int c_ix, c_max, iVerb; c_max = getNumCues(iBehaviour); for (c_ix = 0; c_ix < c_max; c_ix++) { iVerb = getNextCue(iBehaviour); DebugPrint(\"Checking verb \" + IntToString(iVerb)); switch (iVerb) { %(checkcues_switch)s } } DelayCommand(DEFAULT_HEARTBEAT_DELAY, checkcues_%(upper_name)s(iTimeout-1, iBehaviour)); DebugPrint(\"%(upper_name)s \" + IntToString(iBehaviour) + \" tick...\"); } void control_%(upper_name)s(int iBehaviour, int iVerb) { %(getlocals)s switch (iVerb) { %(control_switch)s } } void cleanup_%(upper_name)s(int iBehaviour) { %(getlocals)s int iInterrupt = GetLocalInt(o%(upper_name)s, \"iInterrupt\"); // If we paused behaviours, we'll segue back into them. if (iInterrupt == INTERRUPT_PAUSE) { int iPrevious; %(segue_previous)s } %(checkin)s destroyBehaviourObject(iBehaviour); } void timeout_%(upper_name)s(int iBehaviour) { %(getlocals)s // Insert timeout handling code here setBehaviourFinished(iBehaviour); } void segue_%(upper_name)s(int iBehaviour) { %(getlocals)s // Insert segue handling code here } """ % {"lower_name":lower_name, "upper_name":upper_name, "verb_info":verb_info, "actor_info":actor_info, "nwvar_info":nwvar_info, "constants":constants, "nwvar_comments":nwvar_comments, "nwvars":nwvars, "invalids":invalids, "checkouts":checkouts, "setlocals":setlocals, "getlocals": getlocals, "firstverb_name":firstverb_name, "checkcues_switch":checkcues_switch, "control_switch":control_switch, "segue_previous":segue_previous, "checkin":checkin} return b_code class NWVariable(object): """Contains information about an NWScript variable. The NWVariable class represents any variable that you can pass to a behaviour. This includes lines that can change based on where the behaviour is called, strings representing conversation files, flags, objects, etc. This class also takes care of actors; actors are just a special case of a normal variable, except that each behaviour requires at least one actor, and actors are always objects.""" def __init__(self, type="", name="", description="", isActor = False): """Sets up all the instance variables.""" self.type = type """The type of the NWVariable. Valid types are defined in L{valid_nwvar_types}. @type: string """ self.name = name """The name of the NWVariable. NWVariable names should follow conventions; the first letter of the variable is the first letter of the variable type, and the second letter is capitalized. e.g.: C{oActorA, sConversation} @type: string """ self.description = description """A short description of the NWVariable. These descriptions are only used in comments in the generated script, but they are nevertheless indispensable. @type: string """ self.isActor = isActor """Whether or not this NWVariable is an actor. @type: bool """ def GetInvalidValue(self): """Each NWScript type has an 'invalid' (default) value. We need these to test if we have been passed valid NWVariables. @return: The proper invalid value for the NWVariable's type. @rtype: string""" if self.type == "object": return "OBJECT_INVALID" elif self.type == "int": return "-1" elif self.type == "float": return "0.0" elif self.type == "string": return "\"\"" else: return None class Verb(object): """Verb generates code for each verb object. To use, change the attributes, then simply access the control attribute to see the generated code for the control_<Behaviour> section. Access the checkcues attribute to see the generated code for the checkcues_<Behaviour> section.""" def __init__(self, behaviour): """Sets up all the instance variables.""" self.context_name = "" """A name that can identify the verb in the context of the behaviour. @type: string """ self.b_name = behaviour.name.upper() """The name of the behaviour this verb is a part of. This is required when generating the constant_name. @type: string """ self.constant_name = "" """The constant that will be used to identify the verb in switch statements. It will be appended with the first two letters of the behaviour name to deal with conflicts (if one includes two behaviours with the same constant name, the script won't compile). e.g.: C{F_FI_INSTIGATE} @type: string """ self.actual_name = "" """The name of the actual verb. e.g.: C{FaceAndSayLine} @type: string """ self.follower = True """Is this verb a follower or a supporter? @type: bool """ self.terminal = False """Does the behaviour end at the termination of this verb? @type: bool """ self.followers = [] """The verbs that follow this verb. Terminal verbs have no followers. @type: list of L{Verb}s """ self.preconditions = [] """The preconditions that must be met before this verb will execute. @type: list of strings """ self.vdarguments = [] """Arguments for the creation of the VerbData object (oSubject, oDirObject, etc.) @type: list of strings """ self.varguments = [] """Arguments to pass to the actual verb when it's called. Not all verbs require arguments to be passed, so this can be empty. @type: list strings """ def __setattr__(self, name, value): """Intercept assignments to the context_name or follower attributes, so we can generate the constant_name automatically. @param name: Name of the attribute being set. @type name: string @param value: The value to set the attribute to. """ if name == "b_name": if len(value) < 2: value = "BH" value = value.upper() object.__setattr__(self, name, value) if name == "context_name" or name == "follower" or name == "b_name": # Only try to set the const_name if we have all the required attributes. if hasattr(self, "follower") and hasattr(self, "context_name") and hasattr(self, "b_name"): if object.__getattribute__(self, "follower") == False: startchar = 'S' else: startchar = 'F' const_name = "%c_%c%c_%s" % (startchar, self.b_name[0], self.b_name[1], self.context_name.upper()) object.__setattr__(self, "constant_name", const_name) def GenerateCheckcuesCode(self): """Generate the cueckcues code. @return: The generated NWScript code. @rtype: string """ # if(<preconditions joined by &&>) # e.g.: # if ((GetArea(GetNearestCreature(CREATURE_TYPE_ALIVE, TRUE, 2)) == GetArea(oVictim)) && (!GetIsDead(GetNearestCreature(CREATURE_TYPE_ALIVE, TRUE, 2)))) if len(self.preconditions) == 0: preconditions = "" else: preconditions = "if (%s)\n " % (" && ".join(self.preconditions)) # <actual verb name> # e.g.: # FaceAndSayLine actual = self.actual_name # , <VerbData arguments> # e.g.: # , oInstigator, oVictim vdarg_list = [] for vdarg in self.vdarguments: if vdarg != "": vdarg_list.append(", %s" % (vdarg)) vdargs = ''.join(vdarg_list) # , <actual verb arguments> # e.g.: # , "Oh, you're picking on the wrong person, fool...", sConv varg_list = [] for varg in self.varguments: if varg != "": varg_list.append(", %s" % (varg)) vargs = ''.join(varg_list) # clearFollowerCues(iBehaviour); OR removeCue(iBehaviour, <constant_name>); # e.g.: # removeCue(iBehaviour, S_CALLFORHELP_29); if self.follower == True: clear = "clearFollowerCues(iBehaviour);" else: clear = "removeCue(iBehaviour, %s);" % (self.constant_name) # Generate the code checkcues = """\ %(preconditions)s{ %(actual)s (VerbData(iVerb, iBehaviour%(vdargs)s)%(vargs)s); %(clear)s c_max = getNumCues(iBehaviour); }""" % {"preconditions":preconditions, "actual":actual, "vdargs":vdargs, "vargs":vargs, "clear":clear} return checkcues def GenerateControlCode(self): """Generate the control code. @return: The generated NWScript code. @rtype: string """ # setBehaviourFinished(iBehaviour); if self.terminal == True: # Generate the code control = " setBehaviourFinished(iBehaviour);" else: # addCue(iBehaviour, <follower constant name>); # e.g.: # addCue(iBehaviour, F_RETALIATE_G8); # addCue(iBehaviour, S_CALLFORHELP_29); addcues_list = [] for follow in self.followers: addcues_list.append(" addCue(iBehaviour, %s);" % (follow.constant_name)) # Generate the code control = '\n'.join(addcues_list) return control
# Given some waypoints (with headings), make a bunch of arcs such that: # Between each waypoint are two circlular arcs, tangent to each other and tangent # to each heading at the waypoints and oriented such that there is a smooth flight path # If desiredDuration and craft are specified, will scale about center until the desired time is reached (hopefully) from thesis.Trajectory import BaseTrajectory, ExplicitGeneralSegment def rescale(points, center, scale): """Scale X/Y coordinates around the given center""" cx, cy = center def rescaleSingle(pt): if len(pt) == 6: x, y, z, h, a1, a2 = pt elif len(pt) == 4: x, y, z, h = pt a1, a2 = 5, 5 else: raise TypeError('bad rescale point') x -= cx y -= cy x *= scale y *= scale x += cx y += cy return (x, y, z, h, a1, a2) return [rescaleSingle(pt) for pt in points] from math import sin, cos, sqrt, pi from thesis.optimize.BaseOptimizer import Vector def subSolve(leftInfo, rightInfo, rightFirst): """Solve the bi-arc like curves for the given info""" # Which way from the two points the centers are (+/- radian direction) rightSide = 1 if rightFirst else -1 leftSide = -1 if rightFirst else 1 quarter = pi / 2 left = Vector(leftInfo[0:2]) theta1 = leftInfo[3] leftDir = Vector([cos(theta1), sin(theta1)]) right = Vector(rightInfo[0:2]) theta2 = rightInfo[3] rightDir = Vector([cos(theta2), sin(theta2)]) # If our two thetas are nearly parallel, add in a small # correction factor to avoid a degenerate case corr = 0 if abs(theta1 - theta2) < 0.01: corr = 0.02 theta1Prime = theta1 + corr + leftSide * quarter theta2Prime = theta2 + rightSide * quarter u = cos(theta1Prime) - cos(theta2Prime) v = left[0] - right[0] w = sin(theta1Prime) - sin(theta2Prime) x = left[1] - right[1] a = u**2 + w**2 - 4 b = 2 * (u * v + w * x) c = v**2 + x**2 r1 = (-b + sqrt(b**2 - 4 * a * c)) / (2 * a) r2 = (-b - sqrt(b**2 - 4 * a * c)) / (2 * a) if r1 > 0 and r2 > 0: raise LogicError('Should not occur') r = r1 if r1 > 0 else r2 c1 = left + r * leftDir.rotate(leftSide * quarter + corr) c2 = right + r * rightDir.rotate(rightSide * quarter) # The tangent point of the two circles middle = (c1 + c2) / 2 # Determines which way around the circles we go (our theta ranges) toLeft = left - c1 toLeftMiddle = middle - c1 toRight = right - c2 toRightMiddle = middle - c2 leftThetaRange = [toLeft.angle(), toLeftMiddle.angle()] # XXX This is moderately opaque... #if leftSide < 0: leftThetaRange = leftThetaRange[::-1] #if rightFirst and leftThetaRange[1] > leftThetaRange[0]: leftThetaRange[0] += 2 * pi #if not rightFirst and leftThetaRange[1] < leftThetaRange[0]: leftThetaRange[1] += 2 * pi rightThetaRange = [toRightMiddle.angle(), toRight.angle()] #if rightSide > 0: rightThetaRange = rightThetaRange[::-1] #if rightFirst: rightThetaRange[0] += 2 * pi #if rightSide > 0 and rightThetaRange[1] < rightThetaRange[0]: rightThetaRange[1] += 2 * pi #if not rightFirst and leftThetaRange[1] > rightThetaRange[0]: rightThetaRange[0] += 2 * pi # This is stupid, make CW #print(leftThetaRange, rightThetaRange) leftDir = leftThetaRange[1] - leftThetaRange[0] rightDir = rightThetaRange[1] - rightThetaRange[0] # Should be going CW first but not if rightFirst: # CW and then CCW if leftDir > 0: # CCW but should be CW leftThetaRange[1] -= 2 * pi if rightDir < 0: # CW but should be CCW rightThetaRange[1] += 2 * pi else: # CCW and then cW if leftDir < 0: # CW but should be CCW leftThetaRange[1] += 2 * pi if rightDir > 0: # CCW but should be CW rightThetaRange[1] -= 2 * pi #if leftThetaRange[1] < leftSide * leftThetaRange[0]: leftThetaRange[1] += 2 * pi #if rightThetaRange[1] < rightSide * rightThetaRange[0]: rightThetaRange[1] += 2 * pi # Eh #leftThetaDist = (leftThetaRange[1] - leftThetaRange[0] + 2 * pi) % (2 * pi) #rightThetaDist = (rightThetaRange[1] - rightThetaRange[0] + 2 * pi) % (2 * pi) leftThetaDist = abs(leftThetaRange[1] - leftThetaRange[0]) rightThetaDist = abs(rightThetaRange[1] - rightThetaRange[0]) leftWeight = leftThetaDist / (leftThetaDist + rightThetaDist) rightWeight = rightThetaDist / (leftThetaDist + rightThetaDist) leftHeight = leftInfo[2] rightHeight = rightInfo[2] dz = rightHeight - leftHeight midHeight = leftHeight + dz * leftWeight #print(leftThetaDist, rightThetaDist, leftWeight, rightWeight, midHeight) #print(toLeftMiddle, leftThetaRange) leftSegment = ExplicitGeneralSegment(leftInfo[0:3], [*middle, midHeight], c1, leftThetaRange) rightSegment = ExplicitGeneralSegment([*middle, midHeight], rightInfo[0:3], c2, rightThetaRange) return leftSegment, rightSegment def solve(left, right, minimumRadius = None): """Solve both left-first and right-first arcs and return the shorter greater than the minimumRadius""" a = subSolve(left, right, True) b = subSolve(left, right, False) if minimumRadius is not None: if a[0].radius < minimumRadius: if b[0].radius < minimumRadius: raise TypeError('Too close! %.2f,%.2f<%.2f' % (a[0].radius, b[0].radius, minimumRadius)) return b # Return the shorter of the two paths if a[0].length + a[1].length < b[0].length + b[1].length: return a else: return b class SplineyTrajectory(BaseTrajectory): """ Construct our "Spliney" trajectory. The trajectory is made up of a series of waypoints, which describe a position and heading. Between each waypoint two circular arcs of equal radius are created, such that the circles are tangent to the headings at their positions, and each other. The parameters of the circles are chosen such that the path is continuous, and such that the shortest path of the two valid solutions is returned. Segments are thus dependent only on the waypoints immediately adjacent. """ def __init__( self, waypoints, center = (0, 0), desiredDuration = None, craft = None, minimumRadius = 50, initialHeight = 1000, fixedFirst = False, zSchedule = None ): currentScale = 1 doFixedPoint = desiredDuration is not None and craft is not None self.alphas = [] if zSchedule is not None: waypoints = self.doZSchedule(waypoints, zSchedule, craft) #print(waypoints) # Run a number of iterations of fixed point (should converge) # Or, just one if not doing fixed point for it in range(10 if doFixedPoint else 1): mappedPoints = rescale(waypoints, center, currentScale) if fixedFirst: mappedPoints[0] = waypoints[0] segments = [] time = 0 lastZ = initialHeight for i in range(len(waypoints) - 1): # Generate our segments x0, y0, z0, h0, a1, a2 = mappedPoints[i] segs = solve(mappedPoints[i], mappedPoints[i + 1], minimumRadius = minimumRadius) segments.extend(segs) if it == 0: self.alphas.extend([a1, a2]) if doFixedPoint: # Calculate our path time vl = segs[0].velocityThrustPower(craft, a1)[0] vr = segs[1].velocityThrustPower(craft, a2)[0] time += segs[0].length / vl + segs[1].length / vr if doFixedPoint: # Break early if we are close if abs(desiredDuration - time) < 0.001: break # Update our scale towards the desired value currentScale *= desiredDuration / time self.scale = currentScale super().__init__(segments) def doZSchedule(self, waypoints, zSchedule, craft): # Gather up the relative times of all of our segments import numpy as np gain, *schedule = zSchedule total_time = 0 times = [] for i in range(len(waypoints) - 1): x0, y0, h0, a1, a2 = waypoints[i] x1, y1, h1, _, _ = waypoints[i + 1] segs = solve([x0, y0, 1000, h0, a1, a2], [x1, y1, 1000, h1]) times.append(total_time) total_time += segs[0].length / segs[0].velocityThrustPower(craft, a1)[0] total_time += segs[1].length / segs[1].velocityThrustPower(craft, a2)[0] duration = 24 * 60 * 60 times = np.array(times) / total_time # Normalize our z Schedule schedule = np.array(schedule) schedule /= schedule.sum() rest, ascend, sustain, descend, moreRest = schedule ascendStart = rest sustainStart = ascendStart + ascend descendStart = sustainStart + sustain restStart = descendStart + descend # Start slicing and dicing out = [] z0 = 1000 # TODO hardcoding for i in range(len(waypoints)): x, y, h, a1, a2 = waypoints[i] z = z0 if i == len(times): z = z0 elif times[i] < ascendStart: z = z0 elif times[i] < sustainStart: z = z0 + (times[i] - ascendStart) * gain / ascend elif times[i] < descendStart: z = z0 + gain elif times[i] < restStart: z = z0 + gain - (times[i] - descendStart) * gain / descend out.append([x, y, z, h, a1, a2]) #print(times[i] if i < len(times) else 'end', z) return out
# # Copyright 2021 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 # import copy import json import logging from eth_utils import add_0x_prefix from ocean_lib.common.agreements.consumable import ConsumableCodes from ocean_lib.common.agreements.service_agreement import ServiceAgreement from ocean_lib.common.agreements.service_types import ServiceTypes from ocean_lib.common.ddo.credentials import AddressCredential from ocean_lib.common.ddo.public_key_base import PublicKeyBase from ocean_lib.common.ddo.public_key_rsa import PUBLIC_KEY_TYPE_ETHEREUM_ECDSA from ocean_lib.common.did import OCEAN_PREFIX, did_to_id from ocean_lib.common.utils.utilities import get_timestamp from ocean_lib.data_provider.data_service_provider import DataServiceProvider from ocean_lib.common.ddo.constants import DID_DDO_CONTEXT_URL, PROOF_TYPE from ocean_lib.common.ddo.public_key_rsa import PUBLIC_KEY_TYPE_RSA, PublicKeyRSA from ocean_lib.common.ddo.service import Service logger = logging.getLogger("ddo") class DDO: """DDO class to create, import, export, validate DDO objects.""" def __init__( self, did=None, json_text=None, json_filename=None, created=None, dictionary=None, ): """Clear the DDO data values.""" self._did = did self._public_keys = [] self._authentications = [] self._services = [] self._proof = None self._credentials = {} self._created = None self._status = {} self._other_values = {} if created: self._created = created else: self._created = get_timestamp() if not json_text and json_filename: with open(json_filename, "r") as file_handle: json_text = file_handle.read() if json_text: self._read_dict(json.loads(json_text)) elif dictionary: self._read_dict(dictionary) @property def did(self): """Get the DID.""" return self._did @property def is_disabled(self): """Returns whether the asset is disabled.""" if not self._status: return False return self._status.get("isOrderDisabled", False) @property def is_enabled(self): """Returns the opposite of is_disabled, for convenience.""" return not self.is_disabled @property def asset_id(self): """The asset id part of the DID""" if not self._did: return None return add_0x_prefix(did_to_id(self._did)) @property def services(self): """Get the list of services.""" return self._services[:] @property def proof(self): """Get the static proof, or None.""" return self._proof @property def credentials(self): """Get the credentials.""" return self._credentials @property def publisher(self): return self._proof.get("creator") if self._proof else None @property def metadata(self): """Get the metadata service.""" metadata_service = self.get_service(ServiceTypes.METADATA) return metadata_service.attributes if metadata_service else None @property def created(self): return self._created @property def encrypted_files(self): """Return encryptedFiles field in the base metadata.""" files = self.metadata["encryptedFiles"] return files def assign_did(self, did): if self._did: raise AssertionError('"did" is already set on this DDO instance.') assert did and isinstance( did, str ), f"did must be of str type, got {did} of type {type(did)}" assert did.startswith( OCEAN_PREFIX ), f'"did" seems invalid, must start with {OCEAN_PREFIX} prefix.' self._did = did return did def add_public_key(self, did, public_key): """ Add a public key object to the list of public keys. :param public_key: Public key, PublicKeyHex """ logger.debug(f"Adding public key {public_key} to the did {did}") self._public_keys.append( PublicKeyBase( did, **{"owner": public_key, "type": PUBLIC_KEY_TYPE_ETHEREUM_ECDSA} ) ) def add_authentication(self, public_key, authentication_type): """ Add a authentication public key id and type to the list of authentications. :param public_key: Key id, Authentication :param authentication_type: Authentication type, str """ authentication = {} if public_key: authentication = {"type": authentication_type, "publicKey": public_key} logger.debug(f"Adding authentication {authentication}") self._authentications.append(authentication) def add_service(self, service_type, service_endpoint=None, values=None, index=None): """ Add a service to the list of services on the DDO. :param service_type: Service :param service_endpoint: Service endpoint, str :param values: Python dict with index, templateId, serviceAgreementContract, list of conditions and purchase endpoint. """ if isinstance(service_type, Service): service = service_type else: values = copy.deepcopy(values) if values else {} service = Service( service_endpoint, service_type, values.pop("attributes", None), values, index, ) logger.debug( f"Adding service with service type {service_type} with did {self._did}" ) self._services.append(service) def as_text(self, is_proof=True, is_pretty=False): """Return the DDO as a JSON text. :param if is_proof: if False then do not include the 'proof' element. :param is_pretty: If True return dictionary in a prettier way, bool :return: str """ data = self.as_dictionary(is_proof) if is_pretty: return json.dumps(data, indent=2, separators=(",", ": ")) return json.dumps(data) def as_dictionary(self, is_proof=True): """ Return the DDO as a JSON dict. :param if is_proof: if False then do not include the 'proof' element. :return: dict """ if self._created is None: self._created = get_timestamp() data = { "@context": DID_DDO_CONTEXT_URL, "id": self._did, "created": self._created, } if self._public_keys: values = [] for public_key in self._public_keys: values.append(public_key.as_dictionary()) data["publicKey"] = values if self._authentications: values = [] for authentication in self._authentications: values.append(authentication) data["authentication"] = values if self._services: values = [] for service in self._services: values.append(service.as_dictionary()) data["service"] = values if self._proof and is_proof: data["proof"] = self._proof if self._credentials: data["credentials"] = self._credentials if self._status: data["status"] = self._status if self._other_values: data.update(self._other_values) return data def _read_dict(self, dictionary): """Import a JSON dict into this DDO.""" values = copy.deepcopy(dictionary) self._did = values.pop("id") self._created = values.pop("created", None) if "publicKey" in values: self._public_keys = [] for value in values.pop("publicKey"): if isinstance(value, str): value = json.loads(value) self._public_keys.append(DDO.create_public_key_from_json(value)) if "authentication" in values: self._authentications = [] for value in values.pop("authentication"): if isinstance(value, str): value = json.loads(value) self._authentications.append(DDO.create_authentication_from_json(value)) if "service" in values: self._services = [] for value in values.pop("service"): if isinstance(value, str): value = json.loads(value) if value["type"] == ServiceTypes.ASSET_ACCESS: service = ServiceAgreement.from_json(value) elif value["type"] == ServiceTypes.CLOUD_COMPUTE: service = ServiceAgreement.from_json(value) else: service = Service.from_json(value) self._services.append(service) if "proof" in values: self._proof = values.pop("proof") if "credentials" in values: self._credentials = values.pop("credentials") if "status" in values: self._status = values.pop("status") self._other_values = values def add_proof(self, checksums, publisher_account): """Add a proof to the DDO, based on the public_key id/index and signed with the private key add a static proof to the DDO, based on one of the public keys. :param checksums: dict with the checksum of the main attributes of each service, dict :param publisher_account: account of the publisher, account """ self._proof = { "type": PROOF_TYPE, "created": get_timestamp(), "creator": publisher_account.address, "signatureValue": "", "checksum": checksums, } def get_public_key(self, key_id): """Key_id can be a string, or int. If int then the index in the list of keys.""" if isinstance(key_id, int): return self._public_keys[key_id] for item in self._public_keys: if item.get_id() == key_id: return item return None def _get_public_key_count(self): """Return the count of public keys in the list and embedded.""" return len(self._public_keys) def _get_authentication_from_public_key_id(self, key_id): """Return the authentication based on it's id.""" for authentication in self._authentications: if authentication["publicKey"] == key_id: return authentication return None def get_service(self, service_type=None): """Return a service using.""" for service in self._services: if service.type == service_type and service_type: return service return None def get_service_by_index(self, index): """ Get service for a given index. :param index: Service id, str :return: Service """ try: index = int(index) except ValueError: logging.error(f"The index {index} can not be converted into a int") return None for service in self._services: if service.index == index: return service # try to find by type return self.get_service(index) @property def public_keys(self): """Get the list of public keys.""" return self._public_keys[:] @property def authentications(self): """Get the list authentication records.""" return self._authentications[:] @staticmethod def create_public_key_from_json(values): """Create a public key object based on the values from the JSON record.""" # currently we only support RSA public keys _id = values.get("id") if not _id: # Make it more forgiving for now. _id = "" # raise ValueError('publicKey definition is missing the "id" value.') if values.get("type") == PUBLIC_KEY_TYPE_RSA: public_key = PublicKeyRSA(_id, owner=values.get("owner")) else: public_key = PublicKeyBase( _id, owner=values.get("owner"), type=PUBLIC_KEY_TYPE_ETHEREUM_ECDSA ) public_key.set_key_value(values) return public_key @staticmethod def create_authentication_from_json(values): """Create authentication object from a JSON dict.""" key_id = values.get("publicKey") authentication_type = values.get("type") if not key_id: raise ValueError( f'Invalid authentication definition, "publicKey" is missing: {values}' ) authentication = {"type": authentication_type, "publicKey": key_id} return authentication def enable(self): """Enables asset for ordering.""" if not self._status: self._status = {} self._status.pop("isOrderDisabled") def disable(self): """Disables asset from ordering.""" if not self._status: self._status = {} self._status["isOrderDisabled"] = True @property def requires_address_credential(self): """Checks if an address credential is required on this asset.""" manager = AddressCredential(self) return manager.requires_credential() @property def allowed_addresses(self): """Lists addresses that are explicitly allowed in credentials.""" manager = AddressCredential(self) return manager.get_addresses_of_class("allow") @property def denied_addresses(self): """Lists addresesses that are explicitly denied in credentials.""" manager = AddressCredential(self) return manager.get_addresses_of_class("deny") def add_address_to_allow_list(self, address): """Adds an address to allowed addresses list.""" manager = AddressCredential(self) manager.add_address_to_access_class(address, "allow") def add_address_to_deny_list(self, address): """Adds an address to the denied addresses list.""" manager = AddressCredential(self) manager.add_address_to_access_class(address, "deny") def remove_address_from_allow_list(self, address): """Removes address from allow list (if it exists).""" manager = AddressCredential(self) manager.remove_address_from_access_class(address, "allow") def remove_address_from_deny_list(self, address): """Removes address from deny list (if it exists).""" manager = AddressCredential(self) manager.remove_address_from_access_class(address, "deny") def is_consumable( self, credential=None, with_connectivity_check=True, provider_uri=None ): """Checks whether an asset is consumable and returns a ConsumableCode.""" if self.is_disabled: return ConsumableCodes.ASSET_DISABLED if ( with_connectivity_check and provider_uri and not DataServiceProvider.check_asset_file_info( self, DataServiceProvider.get_root_uri(provider_uri) ) ): return ConsumableCodes.CONNECTIVITY_FAIL # to be parameterized in the future, can implement other credential classes manager = AddressCredential(self) if manager.requires_credential(): return manager.validate_access(credential) return ConsumableCodes.OK
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-05-03 10:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0001_initial'), ] operations = [ migrations.AlterField( model_name='profile', name='client', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to='accounts.Client', verbose_name='Client'), ), ]
from django.http import HttpResponse # Create your views here. def hello_world(request): return HttpResponse('Hello, world')
from ftplib import FTP import tarfile from io import BytesIO ftp = FTP('') ftp.login("","") ftp.pwd() print(ftp.pwd()) # FTP Class class FTPList: def __init__(self, instr, years="all", months="all", days="all"): self.instr = instr self.years = years self.months = months self.days = days def ShowYears(self): ftp.cwd(self.instr) ftp.retrlines('LIST') ftp.cwd("/") def GetList(self): dic = {} yearList = [] fileList = [] if self.years == "all": ftp.cwd(self.instr) yearList = ftp.nlst() for yeari in yearList: dic[yeari] = [] ftp.cwd(yeari) dic[yeari] = ftp.nlst() ftp.cwd("/"+self.instr) return (dic) # Run klasse = FTPList("cl31") cl31Dic = klasse.GetList() # Test Run for all days of 2014 ftp.cwd("2014") for fileArchive in cl31Dic["2014"]: f = BytesIO() theFile = ftp.retrbinary("RETR "+fileArchive,f.write) f.seek(0) tar = tarfile.open(fileobj=f) t = tar.extractfile(tar.getmembers()[0]) data = [x.decode("utf_8") for x in t.readlines()] #Test print(fileArchive) print(data[0:5]) # Original Loop ##for years in cl31Dict: ## ## for fileArchive in years: ## f = BytesIO() ## theFile = ftp.retrbinary("RETR "+fileArchive,f.write) ## f.seek(0) ## tar = tarfile.open(fileobj=f) ## ## t = tar.extractfile(tar.getmembers()[0]) ## data = [x.decode("utf_8") for x in t.readlines()]
from datetime import timedelta, datetime import time # Simple cache mechanism that checks if a user query was made before and # if yes, then returns that query # if no, saves the query to a dict # Every 24 hours cache clears itslef class Cache(): rates_by_day = {} sales_by_day = {} refresh_time = 86400 # 24h time_start = time.time() def __init__(self): time_start = time.time() def has_rate(self, date): return date in self.rates_by_day def has_rates_range(self, date_from, date_to): has = True delta = timedelta(days=1) tmp_from = datetime.strptime(date_from, "%Y-%m-%d").date() tmp_to = datetime.strptime(date_to, "%Y-%m-%d").date() while tmp_from <= tmp_to: if tmp_from.strftime("%Y-%m-%d") not in self.rates_by_day: has = False tmp_from += delta return has def has_sale(self, date): return date in self.sales_by_day def get_rates_range(self, date_from, date_to): ret_json = {} delta = timedelta(days=1) tmp_from = datetime.strptime(date_from, "%Y-%m-%d").date() tmp_to = datetime.strptime(date_to, "%Y-%m-%d").date() while tmp_from <= tmp_to: ret_json[tmp_from.strftime("%Y-%m-%d")] = self.rates_by_day[tmp_from.strftime("%Y-%m-%d")] tmp_from += delta return ret_json # Cache clears itself every 24 hours def check_refresh(self): if time.time() - self.time_start > self.refresh_time: rates_by_day = {} sales_by_day = {} time_start = time.time()
""" This file is the entrypoint of Bot application """ # Library includes import firebase_admin from firebase_admin import credentials # App includes import app.configuration as configuration from app.logging.core import Log from app.client import BotClient def main() -> None: """ Main function of bot application """ print('Starting up') # Setting up the configuration configuration.load_configuration() # Setup Loggers from config Log.config_init() Log.info('Logging is now available') # Retrive the app configuration bot_configuration: configuration.Config = configuration.get_config() # List the given configuration Log.warning('Listing bot configuration:') for key, value in bot_configuration.__dict__.items(): Log.warning(f'\t{key}: {value}') Log.warning('End of configuration') # Setting up the firebase Log.warning('Initializing firebase connection') cred = credentials.Certificate('.firebase') firebase_admin.initialize_app(credential=cred) Log.warning('Firebase was initiatied successfully') # Creating bot instance Log.warning('Creating BotClient instance') client = BotClient() # Run client client.run() if __name__ != '__main__': print('Bad entry point was used, use startup.py instead') else: main()
#Nischal Shrestha #9/19/2015 #MASTERMIND GAME import random alphabet = 'ABCDEF' code = ''.join(random.sample(alphabet, 4)) print (code) number_of_guesses_left = 10 code_broken = False guess_number = 0 print('Welcome to MasterMind') while number_of_guesses_left > 0: print ('Guesses left:',(number_of_guesses_left - guess_number), end = ' ') guess = input('Enter exactly 4 letters from ABCDEF: ') correct_position = 0 correct_letters = 0 tempguess = list(guess) tempcode = list(code) number_of_guesses_left -= 1 for i in range(4): if code[i] == guess[i]: correct_position += 1 for j in range(4): if tempcode[j] in tempguess: correct_letters += 1 print ('Correct in place: ', correct_position) print ('Correct letters: ', correct_letters) if guess == code: print('You won! Congratulations!') number_of_guesses_left = 0 code_broken = True if not code_broken: print ('The code is', code) print('Too bad, you lost.')
class Consts: FIRST_USER = { 'name': 'Matthew E. Taylor', 'user_id': 'edQgLXcAAAAJ' } VALID_DOMAINS = [ 'artificial intelligence', 'intelligent agents', 'multi-agent systems', 'reinforcement learning', 'robotics', 'computer science', 'machine learning', 'neural networks', 'Human-Level Machine Intelligence', 'Image processing', 'Computer vision', 'Pattern recognition', 'data mining', 'Computer Graphics', 'Data Analysis' ] BASE_ADDRESS = r'http://scholar.google.co.il/citations?user=' JOB_INFO_SEPARATOR = '$$$'
import collections filename = "A-large" #filename = "A-minimal" with open(filename + ".in", 'r') as inputfile: lines = inputfile.readlines() with open(filename + ".out", 'w') as outputfile: number_of_tests = 0 for linenumber, line in enumerate(lines): if linenumber == 0: number_of_tests = int(line.strip()) print("There are {} tests".format(number_of_tests)) elif linenumber > number_of_tests: break else: casenumber = linenumber n = [0]*10 print("\n\n*** Testcase {} ***".format(casenumber)) inputcharacters = sorted(line.strip()) print("Characters: {}".format(inputcharacters)) cc = collections.Counter(inputcharacters) assert sum(cc.values()) == len(inputcharacters) #print(cc) n[0] = cc['Z'] cc.subtract("ZERO"*n[0]) #print("ZERO removed", cc) n[2] = cc['W'] cc.subtract("TWO"*n[2]) #print("TWO removed", cc) n[4] = cc['U'] cc.subtract("FOUR"*n[4]) #print("FOUR removed", cc) n[6] = cc['X'] cc.subtract("SIX"*n[6]) #print("SIX removed", cc) n[8] = cc['G'] cc.subtract("EIGHT"*n[8]) #print("EIGHT removed", cc) n[5] = cc['F'] cc.subtract("FIVE"*n[5]) #print("FIVE removed", cc) n[3] = cc['H'] cc.subtract("THREE"*n[3]) #print("THREE removed", cc) n[7] = cc['V'] cc.subtract("SEVEN"*n[7]) #print("SEVEN removed", cc) n[1] = cc['O'] cc.subtract("ONE"*n[1]) #print("ONE removed", cc) n[9] = cc['I'] cc.subtract("NINE"*n[9]) #print("NINE removed", cc) assert sum(cc.values()) == 0 phonenumber = "" for i, v in enumerate(n): for j in range(v): phonenumber += str(i) answer = "Case #{}: {}\n".format(casenumber, phonenumber) print(answer) outputfile.write(answer)
def scramble(s1, s2): a = list(s1) b = list(s2) temp_list = set(a) & set(b) if temp_list == set(b): return True else: return False scramble('rkqodlw','world') scramble('cedewaraaossoqqyt','codewars') scramble('katas','steak') scramble('scriptjava','javascript') scramble('scriptingjava','javascript') scramble('scripting java','java script')
#coding:utf-8 __author__ = 'vanxkr@gamil.com' import urllib import requests class HtmlDownLoader(object): def download(self,url): if url is None: return None headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Connection': 'keep-alive', 'Host': 'pan.baidu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} for i in range(5): try: html = requests.get(url, headers=headers, allow_redirects=False, timeout=5) if html.status_code == 200: return html.content else: return 'drop' except requests.exceptions.ReadTimeout: print '## ['+str(i)+'] get page timeout' continue except requests.exceptions.ConnectionError: return 'drop' return 'drop'
import binascii a = '1c0111001f010100061a024b53535009181c' # (cypher text) b = '686974207468652062756c6c277320657965' # hit the bull's eye (key) c = '746865206b696420646f6e277420706c6179' # the kid don't play def xor_str(string1, string2): return binascii.hexlify( "".join( chr(ord(leftChr) ^ ord(rightChr)) for leftChr, rightChr in zip( binascii.unhexlify(string1.encode('utf-8')).decode('utf-8'), binascii.unhexlify(string2.encode('utf-8')).decode('utf-8') ) ).encode('utf-8') ).decode('utf-8') assert xor_str(a, b) == c
class Rectangle2D: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height def getX(self): return self.x def getY(self): return self.y def getHeight(self): return self.height def getWidth(self): return self.width def getRectangle(points): def getMax(points,n): x = points[n] length = len(points) for i in range(n, length, 2): if x < points[i]: x = points[i] return x def getMin(points, n): x = points[n] length = len(points) for i in range(n, length , 2): if x > points[i]: x = points[i] return x centerX = (getMax(points, 0) + getMin(points, 0)) /2 width = (getMax(points, 0) - getMin(points, 0)) centerY = (getMax(points, 1) + getMin(points, 1)) /2 height = (getMax(points, 1) - getMin(points, 1)) return Rectangle2D(centerX, centerY, width, height) # return rectangle object points = input("Enter points: ") points = [eval(x) for x in points.split()] rectangle = getRectangle(points) # rectangle object returned form function print("The bounding rectangle is centered at (", rectangle.getX(), ",", rectangle.getY(), ") with width", rectangle.getWidth(), "and height", rectangle.getHeight())
import re import cloudfront # Lines 1 & 2 are header # # Lines 3 & 4 don't include past field 26 (fle-encrypted-fields) # Line 5 includes 7 additional fields as per https://aws.amazon.com/about-aws/whats-new/2019/12/cloudfront-detailed-logs/ # Line 6 includes extra "unknown field data" EXAMPLE = """#Version: 1.0 #Fields: date time x-edge-location sc-bytes c-ip cs-method cs(Host) cs-uri-stem sc-status cs(Referer) cs(User-Agent) cs-uri-query cs(Cookie) x-edge-result-type x-edge-request-id x-host-header cs-protocol cs-bytes time-taken x-forwarded-for ssl-protocol ssl-cipher x-edge-response-result-type cs-protocol-version fle-status fle-encrypted-fields c-port time-to-first-byte x-edge-detailed-result-type sc-content-type sc-content-len sc-range-start sc-range-end 2014-05-23\t01:13:11\tFRA2\t182\t192.0.2.10\tGET\td111111abcdef8.cloudfront.net\t/view/my/file.html\t200\twww.displaymyfiles.com\tMozilla/4.0%20(compatible;%20MSIE%205.0b1;%20Mac_PowerPC)\t-\tzip=98101\tRefreshHit\tMRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==\td111111abcdef8.cloudfront.net\thttp\t-\t0.001\t-\t-\t-\tRefreshHit\tHTTP/1.1\tProcessed\t1 2014-05-23\t01:13:11\tFRA2\t182\t192.0.2.202\tGET\td111111abcdef8.cloudfront.net\t/soundtrack/happy.mp3\t304\twww.unknownsingers.com\tMozilla/4.0%20(compatible;%20MSIE%207.0;%20Windows%20NT%205.1)\ta=b&c=d\tzip=50158\tHit\txGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==\td111111abcdef8.cloudfront.net\thttp\t-\t0.002\t-\t-\t-\tHit\tHTTP/1.1\t-\t- 2014-05-23\t01:13:11\tFRA2\t182\t192.0.2.100\tGET\td111111abcdef8.cloudfront.net\t/index.html\t200\t-\tMozilla/5.0%2520(Windows%2520NT)\t-\t-\tHit\tSOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ==\td111111abcdef8.cloudfront.net\thttps\t23\t0.001\t-\tTLSv1.2\tECDHE-RSA-AES128-GCM-SHA256\tHit\tHTTP/2.0\t-\t-\t11040\t0.001\tHit\ttext/html\t78\t-\t- 2014-05-23\t01:13:11\tFRA2\t182\t192.0.2.100\tGET\td111111abcdef8.cloudfront.net\t/index.html\t200\t-\tMozilla/5.0%2520(Windows%2520NT)\t-\t-\tHit\tSOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ==\td111111abcdef8.cloudfront.net\thttps\t23\t0.001\t-\tTLSv1.2\tECDHE-RSA-AES128-GCM-SHA256\tHit\tHTTP/2.0\t-\t-\t11040\t0.001\tHit\ttext/html\t78\t-\t-\tfoo\tbar\tbaz""" NUM_HEADER_LINES = 2 # These fields should be present and set to the given value EXPECTED_ITEMS = { "_type": "doc", # test static field "@timestamp": "2014-05-23T01:13:11.000Z", # test combining fields "aws.cloudfront.edge_location": "FRA2", # test parsing field "http.response.total.bytes": 182, # test converting to int } # These fields should be present and set to the given value OR absent MAYBE_EXPECTED_ITEMS = { "aws.cloudfront.result_type_detailed": "Hit", # Extra field added 2019-12 "aws.cloudfront.time_to_first_byte": 0.001, # Extra field added 2019-12 with float conversion "aws.cloudfront.unhandled_fields": "['foo', 'bar', 'baz']", } # These fields should not be present EXPECTED_NON_ITEMS = { "http.response.content-range.start", # Values of '-' should be ignored } def test_filenames() -> None: assert not cloudfront.check_filename("foo") assert cloudfront.check_filename("DIST012346.2019-09-30-01.abcdef.gz") assert cloudfront.check_filename("prefix/DIST012346.2019-09-30-01.abcdef.gz") def test_basic() -> None: num_docs = 0 for line_no, line in enumerate(EXAMPLE.splitlines()): response = list(cloudfront.transform(line, line_no)) print("Line: %s Response: %s" % (repr(line), repr(response))) if line_no < NUM_HEADER_LINES: assert len(response) == 0 continue # We assert on line_no to improve pytest failure output num_docs += 1 assert line_no and len(response) == 1 doc = response[0] assert "_index" in doc assert "_type" in doc assert "@timestamp" in doc # Check the value of a few keys for key in EXPECTED_ITEMS: # We assert on key to improve pytest failure output assert key and doc[key] == EXPECTED_ITEMS[key] for key in MAYBE_EXPECTED_ITEMS: if key in doc: # We assert on key to improve pytest failure output assert key and doc[key] == MAYBE_EXPECTED_ITEMS[key] for key in EXPECTED_NON_ITEMS: # We assert on key to improve pytest failure output assert key and key not in doc # Check key names are all correct for key, value in doc.items(): assert isinstance(value, (str, int, float, bool)) assert key.islower() # Limited punctuation is allowed assert re.sub("[._@-]", "", key).isalnum() assert value != "-" assert num_docs == (len(EXAMPLE.split('\n')) - NUM_HEADER_LINES)
#!/usr/bin/env python import logging from contextlib import closing import socket import argparse import select import sys from textwrap import wrap import os import subprocess import irclib from time import sleep class Socket(object): """ Socket is a struct containing a socket and two handlers : on_write and on_read. This class is used by Network to store each sockets with its handlers. """ __slots__ = ("socket", "on_read", "on_write", "sockets") def __init__(self, sock, on_read=None, on_write=None): self.socket = sock if on_read: self.on_read = on_read if on_write: self.on_write = on_write class Network(object): """ The Network class provides an easy way to listen on a TCP port. It internally use select to block waiting for data, and permits you to manually add and remove sockets to be monitored. Basic usage is : net = Network() net.listen('127.0.0.1', 4242, sys.stdout.write) net.run_forever() public methods add_socket and remove_socket can be used if another part or your code have opened sockets, and you want Network to select on them. """ __slots__ = ('sockets', 'filenos') def __init__(self): self.sockets = [] self.filenos = {} def listen(self, addr, port, on_read): """ Listen for TCP connections on addr:port. The callback on_read is called, with the socket as single parameter, when data is available. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.add_socket(sock, lambda s: self.accept(s, on_read)) sock.bind((addr, port)) sock.listen(1) def accept(self, sock, on_read): """ Used internally to accept a connection on a socket. But if you need, you can use it, it will do a soc.accept() then add the accepted sock to the list of monitored ones, so when data is available, the callback on_read will be called. """ logging.debug("Accepting a connection") conn, _ = sock.accept() self.add_socket(conn, on_read) def add_socket(self, sock, on_read=None, on_write=None): """ Manually add a socket and its on_read / on_write handlers to this Network. """ logging.debug("Adding socket %d", sock.fileno()) self.sockets.append(sock) self.filenos[sock.fileno()] = Socket(sock, on_read, on_write) def remove_socket(self, sock): """ Manually remove a socket from the list of monitored ones. """ logging.debug("Removing socket %d", sock.fileno()) self.sockets.remove(sock) del self.filenos[sock.fileno()] def run_forever(self): """ Start the infinite loop listening on network. """ while True: logging.debug("Entering select...") (can_read, _, _) = select.select(self.sockets, [], []) [self.filenos[sock.fileno()].on_read(sock) for sock in can_read] class IRCBot: """ IRCBot is a basic bot that connect to a given serveur and channel with a given nickname, and then, only tries to execute 'executables' in the hooks directory named after the kinds of event it receive that can be : * error * join * kick * mode * part * ping * privmsg * privnotice * pubmsg <- Most usefull, it receive messages of the channel * pubnotice * quit * invite * pong and a generic hook called for EVERY event, even if a hook exists for the named event : * all_raw_messages """ def __init__(self, server, chan, key, nickname, local_port): self.network = Network() self.chan = chan self.key = key self.ircobj = irclib.IRC(self.add_socket, self.rm_socket) self.connection = self.ircobj.server() self.ircobj.add_global_handler("all_events", self._dispatcher, -10) self.ircobj.add_global_handler("welcome", self.on_connect) self.ircobj.add_global_handler("nicknameinuse", self.on_nicknameinuse) self.connection.connect(server, 6667, nickname) self.network.listen("127.0.0.1", local_port, self.read_message) self.network.run_forever() def on_nicknameinuse(self, c, _): c.nick(c.get_nickname() + "_") def on_connect(self, connection, _): connection.join(self.chan, self.key) def read_message(self, sock): """ Read a message on the local socket and write it to the channel """ data = sock.recv(1024) if not data: self.network.remove_socket(sock) else: self.privmsg(self.chan, data) def privmsg(self, to, message): """ Write a message to the channel """ if len(message) > 0: for line in message.split('\n'): wrapped = wrap(line, 512 - len("\r\n") - len("PRIVMSG %s :" % self.chan)) for wrapped_line in wrapped: if len(wrapped_line.strip()) > 0: self.connection.privmsg(to, wrapped_line) sleep(1) def add_socket(self, sock): self.network.add_socket(sock, lambda s: self.ircobj.process_data([s])) def rm_socket(self, sock): self.network.remove_socket(sock) @staticmethod def event_info(event): source = event.source().split('!', 1) \ if event.source() is not None else [] s_login = source[0] if len(source) > 0 else "" s_host = source[1] if len(source) > 1 else "" target = event.target().split('!', 1) \ if event.target() is not None else [] t_login = target[0] if len(target) > 0 else "" t_host = target[1] if len(target) > 1 else "" return event.eventtype(), s_login, s_host, t_login, t_host def _dispatcher(self, _, event): etype, s_login, s_host, t_login, t_host = IRCBot.event_info(event) try: call = ['hooks-enabled/%s' % etype, s_login, s_host, t_login, t_host] + event.arguments() logging.info("calling: %s", str(call)) if os.path.isfile(call[0]): message, debug = subprocess.Popen(call, stdout=subprocess.PIPE)\ .communicate() if len(message) == 0: return if debug is not None: logging.info(" \_ debug '%s'", debug) logging.info(" \_ response '%s'", message) message_type, message = message.split(' ', 1) if message_type == 'RAW': for line in message.split("\n"): self.connection.send_raw(line) else: self.privmsg(*message.split(' ', 1)) except Exception, ex: logging.critical(ex) logging.critical("while receiving %s of type %s from %s to %s", str(event.arguments), etype, s_login, t_login) def connect_to_irc(conf): if conf.daemonize: import daemon with daemon.DaemonContext(working_directory=os.getcwd()): IRCBot(conf.server, conf.chan, conf.key, conf.nickname, conf.local_port) else: IRCBot(conf.server, conf.chan, conf.key, conf.nickname, conf.local_port) def netwrite(to_send, host, port): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.connect((host, port)) [sock.send(data) for data in to_send] def say_something(conf): if len(conf.message) == 1 and conf.message[0] == '-': netwrite(sys.stdin, '127.0.0.1', conf.local_port) else: netwrite([' '.join(conf.message)], '127.0.0.1', conf.local_port) HELP = { "server": "IRC server address (ip or dns name)", "chan": "Chan to join", "nickname": "Nickname to use", "local_port": "Local port to listen to messages", "say_local_port": "Local listening port of the bot", "verbose": "Be verbose (Show warning messazges)", "vverbose": "Be very verbose (Show info messazges)", "vvverbose": "Be very very verbose (Show debug messages)", "quiet": "Be quiet", "ircbot": "IRC Bot", "connect": "Connect to a server", "say": "Say something (once connected)", "message": "What to say, '-' means stdin", "daemonize": "Demonize the client process", "key": "Channel key"} def main(): parser = argparse.ArgumentParser(description=HELP['ircbot']) parser.add_argument('-v', '--show-warnings', dest='logging_level', action='store_const', const=logging.WARNING, help=HELP['verbose']) parser.add_argument('-vv', '--show-infos', dest='logging_level', action='store_const', const=logging.INFO, help=HELP['vverbose']) parser.add_argument('-vvv', '--show-debugs', dest='logging_level', action='store_const', const=logging.DEBUG, help=HELP['vvverbose']) parser.add_argument('-q', '--quiet', dest='logging_level', action='store_const', const=logging.CRITICAL, help=HELP['quiet']) subparsers = parser.add_subparsers() parser_client = subparsers.add_parser('connect', help=HELP['connect']) parser_client.add_argument('server', help=HELP['server']) parser_client.add_argument('chan', help=HELP['chan']) parser_client.add_argument('nickname', help=HELP['nickname']) parser_client.add_argument('-p', '--port', dest="local_port", help=HELP['local_port'], type=int, default=6668) parser_client.add_argument('-d', '--daemonize', action='store_true', dest='daemonize', help=HELP['daemonize']) parser_client.add_argument('-k', '--key', dest='key', help=HELP['key'], default='') parser_client.set_defaults(func=connect_to_irc) parser_say = subparsers.add_parser('say', help=HELP['say']) parser_say.add_argument('message', nargs='+', help=HELP['message']) parser_say.add_argument('-p', '--port', dest="local_port", help=HELP['say_local_port'], type=int, default=6668) parser_say.set_defaults(func=say_something) conf = parser.parse_args() logging.basicConfig(level=conf.logging_level, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') conf.func(conf) if __name__ == "__main__": try: main() except KeyboardInterrupt: sys.exit(0)
from django.db import models from django.contrib.auth.models import AbstractUser import datetime """ Class Account Store the money balance between reload and transaction """ class Account(models.Model): balance = models.FloatField() name = models.CharField(max_length=50) def __str__(self): return self.name """ Class AccountTransaction """ class AccountTransaction(models.Model): amount = models.FloatField() created_at = models.DateTimeField(auto_now_add=True) account_id = models.ForeignKey(to=Account, on_delete=models.CASCADE) """ Class AccountReload """ class AccountReload(models.Model): amount = models.FloatField() created_at = models.DateTimeField(auto_now_add=True) account_id = models.ForeignKey(to=Account, on_delete=models.CASCADE) """ Class User Custom user model that takes differents fields in consideration for needs of the project. """ class User(AbstractUser): email = models.EmailField(unique=True) location = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) account_id = models.ForeignKey(to=Account, on_delete=models.CASCADE, blank=True, null=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'username'] class Meta: abstract = False def __str__(self): return "%s %s" % (self.first_name, self.last_name) """ Class Project """ class Project(models.Model): name = models.CharField(max_length=50) description = models.TextField() account_id = models.ForeignKey(to=Account, on_delete=models.CASCADE) user_id = models.ForeignKey(to=User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name """ Class ProjectRoles """ class ProjectRoles(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name """ Class UserProject """ class UserProject(models.Model): user_id = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='projects') project_id = models.ForeignKey(to=Project, on_delete=models.CASCADE, related_name='users') user_role = models.ForeignKey(to=ProjectRoles, on_delete=models.CASCADE, blank=True, null=True) """ Class Task """ class Task(models.Model): name = models.CharField(max_length=128) project_id = models.ForeignKey(to=Project, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField() ended_at = models.DateTimeField() def __str__(self): return self.name """ Class TaskUserAssignement """ class TaskUserAssignement(models.Model): user_id = models.ForeignKey(to=User, on_delete=models.CASCADE) task_id = models.ForeignKey(to=Task, on_delete=models.CASCADE) """ Class ShopProducts """ class ShopProduct(models.Model): name = models.CharField(max_length=128) price = models.FloatField() description = models.TextField()
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from slave import recipe_api import collections class ImmutibleMapping(dict): def __init__(self, data): super(ImmutibleMapping, self).__init__(data) assert all(isinstance(v, collections.Hashable) for v in self.itervalues()) def __setitem__(self, key, value): # pragma: no cover raise TypeError("May not modify an ImmutibleMapping") def __delitem__(self, key): # pragma: no cover raise TypeError("May not modify an ImmutibleMapping") def freeze(obj): if isinstance(obj, dict): return ImmutibleMapping((k, freeze(v)) for k, v in obj.iteritems()) elif isinstance(obj, list): return tuple(freeze(x) for x in obj) elif isinstance(obj, collections.Hashable): return obj else: # pragma: no cover raise TypeError('Unsupported value: %s' % (obj,)) class PropertiesApi(recipe_api.RecipeApi, collections.Mapping): """ Provide an immutable mapping view into the 'properties' for the current run. The value of this api is equivalent to this transformation of the legacy build values: val = factory_properties val.update(build_properties) """ def __init__(self, properties, **kwargs): super(PropertiesApi, self).__init__(**kwargs) self._properties = freeze(properties) def __getitem__(self, key): return self._properties[key] def __len__(self): return len(self._properties) def __iter__(self): return iter(self._properties)
import csv import requests import json import logging as log """ Tools for migrating legacy lists from Openverse Beta to the CC Catalog platform. """ def import_lists_to_catalog(parsed_lists): success = 0 errors = [] for _list in parsed_lists: _list = parsed_lists[_list] payload = { 'title': _list['title'], 'images': _list['images'] } response = requests.post( 'http://api.openverse.engineering/list', data=payload ) if 300 > response.status_code >= 200: json_response = json.loads(response.text) new_url = json_response['url'] success += 1 print(_list['email'], new_url, _list['title'], sep='||') else: # A handful of lists from the legacy application are empty, which # isn't accepted in the new API. Skip over them and log it. errors.append((_list['title'], response.text)) continue log.info(f'Migrated {success} lists successfully') if errors: log.error("The following errors occurred:") for error in errors: log.error(error) if __name__ == '__main__': with open('csvs/prod/lists.csv', 'r') as lists, \ open('csvs/prod/list_images.csv', 'r') as list_images, \ open('csvs/prod/users.csv', 'r') as users: lists = csv.DictReader(lists) list_images = csv.DictReader(list_images) users = csv.DictReader(users) # Compile all of the data required to migrate the lists and find the # emails of their owners. users_dict = {row['id']: row['email'] for row in users} lists_dict = {} for row in lists: if row['owner_id'] == '': continue lists_dict[row['id']] = { 'email': users_dict[row['owner_id']], 'title': row['title'], 'images': [] } for row in list_images: if row['list_id'] in lists_dict: lists_dict[row['list_id']]['images'].append(row['image_id']) # Use the API to migrate the lists. import_lists_to_catalog(lists_dict)
from mypy_extensions import TypedDict from speclib import array curve448_test = TypedDict('curve448_test', { 'private': str, 'public' : str, 'result' : str, 'valid' : bool} ) curve448_test_vectors : array[curve448_test] = array([ { 'private' : '3d262fddf9ec8e88495266fea19a34d28882acef045104d0d1aae121700a779c984c24f8cdd78fbff44943eba368f54b29259a4f1c600ad3', 'public' : '06fce640fa3487bfda5f6cf2d5263f8aad88334cbd07437f020f08f9814dc031ddbdc38c19c6da2583fa5429db94ada18aa7a7fb4ef8a086', 'result' : 'ce3e4ff95a60dc6697da1db1d85e6afbdf79b50a2412d7546d5f239fe14fbaadeb445fc66a01b0779d98223961111e21766282f73dd96b6f', 'valid' : True }, { 'private' : '203d494428b8399352665ddca42f9de8fef600908e0d461cb021f8c538345dd77c3e4806e25f46d3315c44e0a5b4371282dd2c8d5be3095f', 'public' : '0fbcc2f993cd56d3305b0b7d9e55d4c1a8fb5dbb52f8e9a1e9b6201b165d015894e56c4d3570bee52fe205e28a78b91cdfbde71ce8d157db', 'result' : '884a02576239ff7a2f2f63b2db6a9ff37047ac13568e1e30fe63c4a7ad1b3ee3a5700df34321d62077e63633c575c1c954514e99da7c179d', 'valid' : True }, { 'private' : '9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28dd9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b', 'public' : '3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b43027d8b972fc3e34fb4232a13ca706dcb57aec3dae07bdc1c67bf33609', 'result' : '07fff4181ac6cc95ec1c16a94a0f74d12da232ce40a77552281d282bb60c0b56fd2464c335543936521c24403085d59a449a5037514a879d', 'valid' : True }, { 'private' : '1c306a7ac2a0e2e0990b294470cba339e6453772b075811d8fad0d1d6927c120bb5ee8972b0d3e21374c9c921b09d1b0366f10b65173992d', 'public' : '9b08f7cc31b7e3e67d22d5aea121074a273bd2b83de09c63faa73d2c22c5d9bbc836647241d953d40c5b12da88120d53177f80e532c41fa0', 'result' : '07fff4181ac6cc95ec1c16a94a0f74d12da232ce40a77552281d282bb60c0b56fd2464c335543936521c24403085d59a449a5037514a879d', 'valid' : True } ])
# coding: utf-8 """ SevOne API Documentation Supported endpoints by the new RESTful API # noqa: E501 OpenAPI spec version: 2.1.18, Hash: db562e6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from swagger_client.api_client import ApiClient class ReportAttachmentsAlertsApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_alert_attachment(self, id, request_dto, **kwargs): # noqa: E501 """Create alert report attachment # noqa: E501 Creates a new alert report attachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_alert_attachment(id, request_dto, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report where the report attachment will be created (required) :param AlertAttachmentRequestDtoV1 request_dto: AlertAttachment request object (required) :return: AlertAttachmentResponseDtoV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.create_alert_attachment_with_http_info(id, request_dto, **kwargs) # noqa: E501 else: (data) = self.create_alert_attachment_with_http_info(id, request_dto, **kwargs) # noqa: E501 return data def create_alert_attachment_with_http_info(self, id, request_dto, **kwargs): # noqa: E501 """Create alert report attachment # noqa: E501 Creates a new alert report attachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_alert_attachment_with_http_info(id, request_dto, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report where the report attachment will be created (required) :param AlertAttachmentRequestDtoV1 request_dto: AlertAttachment request object (required) :return: AlertAttachmentResponseDtoV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'request_dto'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_alert_attachment" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `create_alert_attachment`") # noqa: E501 # verify the required parameter 'request_dto' is set if ('request_dto' not in params or params['request_dto'] is None): raise ValueError("Missing the required parameter `request_dto` when calling `create_alert_attachment`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'request_dto' in params: body_params = params['request_dto'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/{id}/attachments/alerts', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentResponseDtoV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def create_alert_attachment1(self, id, create_dto, **kwargs): # noqa: E501 """Create alert report attachment # noqa: E501 Creates a new alert report attachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_alert_attachment1(id, create_dto, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report where the report attachment will be created (required) :param AlertAttachmentCreateDto create_dto: AlertAttachment create object (required) :return: AlertAttachmentDto If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.create_alert_attachment1_with_http_info(id, create_dto, **kwargs) # noqa: E501 else: (data) = self.create_alert_attachment1_with_http_info(id, create_dto, **kwargs) # noqa: E501 return data def create_alert_attachment1_with_http_info(self, id, create_dto, **kwargs): # noqa: E501 """Create alert report attachment # noqa: E501 Creates a new alert report attachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_alert_attachment1_with_http_info(id, create_dto, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report where the report attachment will be created (required) :param AlertAttachmentCreateDto create_dto: AlertAttachment create object (required) :return: AlertAttachmentDto If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'create_dto'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_alert_attachment1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `create_alert_attachment1`") # noqa: E501 # verify the required parameter 'create_dto' is set if ('create_dto' not in params or params['create_dto'] is None): raise ValueError("Missing the required parameter `create_dto` when calling `create_alert_attachment1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'create_dto' in params: body_params = params['create_dto'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/{id}/attachments/alerts', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentDto', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment(self, id, **kwargs): # noqa: E501 """Get alert attachment # noqa: E501 Get an existing alert attachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: Alert attachment id (required) :return: AlertAttachmentDto If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_with_http_info(self, id, **kwargs): # noqa: E501 """Get alert attachment # noqa: E501 Get an existing alert attachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: Alert attachment id (required) :return: AlertAttachmentDto If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentDto', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_aggregation(self, id, **kwargs): # noqa: E501 """Get attachment aggregation # noqa: E501 Get alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_aggregation(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_aggregation_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_aggregation_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_aggregation_with_http_info(self, id, **kwargs): # noqa: E501 """Get attachment aggregation # noqa: E501 Get alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_aggregation_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_aggregation" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_aggregation`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/aggregation', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentAggregation', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_aggregation1(self, id, **kwargs): # noqa: E501 """Get attachment aggregation # noqa: E501 Get alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_aggregation1(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_aggregation1_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_aggregation1_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_aggregation1_with_http_info(self, id, **kwargs): # noqa: E501 """Get attachment aggregation # noqa: E501 Get alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_aggregation1_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_aggregation1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_aggregation1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/aggregation', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentAggregation', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_filter_schema(self, **kwargs): # noqa: E501 """Gets the filters schema # noqa: E501 Gets the filters schema containing available filter fields and values # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filter_schema(async_req=True) >>> result = thread.get() :param async_req bool :return: AlertAttachmentFiltersSchema If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_filter_schema_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_filter_schema_with_http_info(**kwargs) # noqa: E501 return data def get_alert_attachment_filter_schema_with_http_info(self, **kwargs): # noqa: E501 """Gets the filters schema # noqa: E501 Gets the filters schema containing available filter fields and values # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filter_schema_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: AlertAttachmentFiltersSchema If the method is called asynchronously, returns the request thread. """ all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_filter_schema" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/filters/schema', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentFiltersSchema', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_filter_schema1(self, **kwargs): # noqa: E501 """Gets the filters schema # noqa: E501 Gets the filters schema containing available filter fields and values # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filter_schema1(async_req=True) >>> result = thread.get() :param async_req bool :return: AlertAttachmentFiltersSchema If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_filter_schema1_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_filter_schema1_with_http_info(**kwargs) # noqa: E501 return data def get_alert_attachment_filter_schema1_with_http_info(self, **kwargs): # noqa: E501 """Gets the filters schema # noqa: E501 Gets the filters schema containing available filter fields and values # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filter_schema1_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: AlertAttachmentFiltersSchema If the method is called asynchronously, returns the request thread. """ all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_filter_schema1" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/filters/schema', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentFiltersSchema', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_filters(self, id, **kwargs): # noqa: E501 """Get filters # noqa: E501 Gets the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filters(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_filters_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_filters_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_filters_with_http_info(self, id, **kwargs): # noqa: E501 """Get filters # noqa: E501 Gets the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filters_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_filters" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_filters`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/filters', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AttachmentFilters', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_filters1(self, id, **kwargs): # noqa: E501 """Get filters # noqa: E501 Gets the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filters1(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_filters1_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_filters1_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_filters1_with_http_info(self, id, **kwargs): # noqa: E501 """Get filters # noqa: E501 Gets the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_filters1_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_filters1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_filters1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/filters', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AttachmentFilters', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_resource(self, id, **kwargs): # noqa: E501 """Get alert attachment resources # noqa: E501 Get alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_resource(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentResourceV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_resource_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_resource_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_resource_with_http_info(self, id, **kwargs): # noqa: E501 """Get alert attachment resources # noqa: E501 Get alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_resource_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentResourceV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_resource" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_resource`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/resources', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentResourceV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_resource1(self, id, **kwargs): # noqa: E501 """Get alert attachment resources # noqa: E501 Get alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_resource1(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: list[AlertAttachmentResource] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_resource1_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_resource1_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_resource1_with_http_info(self, id, **kwargs): # noqa: E501 """Get alert attachment resources # noqa: E501 Get alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_resource1_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: list[AlertAttachmentResource] If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_resource1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_resource1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/resources', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[AlertAttachmentResource]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_settings(self, id, **kwargs): # noqa: E501 """Get attachment settings # noqa: E501 Get alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_settings(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentSettingsV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_settings_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_settings_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_settings_with_http_info(self, id, **kwargs): # noqa: E501 """Get attachment settings # noqa: E501 Get alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_settings_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentSettingsV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/settings', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentSettingsV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_settings1(self, id, **kwargs): # noqa: E501 """Get attachment settings # noqa: E501 Get alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_settings1(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentSettings If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_settings1_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_settings1_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_settings1_with_http_info(self, id, **kwargs): # noqa: E501 """Get attachment settings # noqa: E501 Get alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_settings1_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentSettings If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/settings', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentSettings', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_time_settings(self, id, **kwargs): # noqa: E501 """Get alert attachment time settings # noqa: E501 Get alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_time_settings(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: TimeSettingV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_time_settings_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_time_settings_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_time_settings_with_http_info(self, id, **kwargs): # noqa: E501 """Get alert attachment time settings # noqa: E501 Get alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_time_settings_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: TimeSettingV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_time_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_time_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/time', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='TimeSettingV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_time_settings1(self, id, **kwargs): # noqa: E501 """Get alert attachment time settings # noqa: E501 Get alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_time_settings1(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: TimeSettings If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_time_settings1_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_time_settings1_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_time_settings1_with_http_info(self, id, **kwargs): # noqa: E501 """Get alert attachment time settings # noqa: E501 Get alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_time_settings1_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: TimeSettings If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_time_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_time_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/time', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='TimeSettings', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_visualization_settings(self, id, **kwargs): # noqa: E501 """Get attachment visualization settings # noqa: E501 Get alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_visualization_settings(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentVisualizationV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_visualization_settings_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_visualization_settings_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_visualization_settings_with_http_info(self, id, **kwargs): # noqa: E501 """Get attachment visualization settings # noqa: E501 Get alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_visualization_settings_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentVisualizationV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_visualization_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_visualization_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/visualizations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentVisualizationV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_alert_attachment_visualization_settings1(self, id, **kwargs): # noqa: E501 """Get attachment visualization settings # noqa: E501 Get alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_visualization_settings1(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentVisualization If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_alert_attachment_visualization_settings1_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_alert_attachment_visualization_settings1_with_http_info(id, **kwargs) # noqa: E501 return data def get_alert_attachment_visualization_settings1_with_http_info(self, id, **kwargs): # noqa: E501 """Get attachment visualization settings # noqa: E501 Get alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert_attachment_visualization_settings1_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :return: AlertAttachmentVisualization If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_alert_attachment_visualization_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_alert_attachment_visualization_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/visualizations', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentVisualization', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def partially_update_alert_attachment_visualization_settings(self, id, visualizations, **kwargs): # noqa: E501 """Partially update visualization settings # noqa: E501 Partial update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.partially_update_alert_attachment_visualization_settings(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualizationV1 visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualizationV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.partially_update_alert_attachment_visualization_settings_with_http_info(id, visualizations, **kwargs) # noqa: E501 else: (data) = self.partially_update_alert_attachment_visualization_settings_with_http_info(id, visualizations, **kwargs) # noqa: E501 return data def partially_update_alert_attachment_visualization_settings_with_http_info(self, id, visualizations, **kwargs): # noqa: E501 """Partially update visualization settings # noqa: E501 Partial update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.partially_update_alert_attachment_visualization_settings_with_http_info(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualizationV1 visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualizationV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'visualizations'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method partially_update_alert_attachment_visualization_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `partially_update_alert_attachment_visualization_settings`") # noqa: E501 # verify the required parameter 'visualizations' is set if ('visualizations' not in params or params['visualizations'] is None): raise ValueError("Missing the required parameter `visualizations` when calling `partially_update_alert_attachment_visualization_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'visualizations' in params: body_params = params['visualizations'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/visualizations', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentVisualizationV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def partially_update_alert_attachment_visualization_settings1(self, id, visualizations, **kwargs): # noqa: E501 """Partially update visualization settings # noqa: E501 Partial update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.partially_update_alert_attachment_visualization_settings1(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualization visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualization If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.partially_update_alert_attachment_visualization_settings1_with_http_info(id, visualizations, **kwargs) # noqa: E501 else: (data) = self.partially_update_alert_attachment_visualization_settings1_with_http_info(id, visualizations, **kwargs) # noqa: E501 return data def partially_update_alert_attachment_visualization_settings1_with_http_info(self, id, visualizations, **kwargs): # noqa: E501 """Partially update visualization settings # noqa: E501 Partial update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.partially_update_alert_attachment_visualization_settings1_with_http_info(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualization visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualization If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'visualizations'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method partially_update_alert_attachment_visualization_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `partially_update_alert_attachment_visualization_settings1`") # noqa: E501 # verify the required parameter 'visualizations' is set if ('visualizations' not in params or params['visualizations'] is None): raise ValueError("Missing the required parameter `visualizations` when calling `partially_update_alert_attachment_visualization_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'visualizations' in params: body_params = params['visualizations'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/visualizations', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentVisualization', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_aggregation(self, id, aggregation, **kwargs): # noqa: E501 """Update attachment aggregation # noqa: E501 Update alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_aggregation(id, aggregation, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentAggregation aggregation: Alert attachment aggregation (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_aggregation_with_http_info(id, aggregation, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_aggregation_with_http_info(id, aggregation, **kwargs) # noqa: E501 return data def update_alert_attachment_aggregation_with_http_info(self, id, aggregation, **kwargs): # noqa: E501 """Update attachment aggregation # noqa: E501 Update alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_aggregation_with_http_info(id, aggregation, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentAggregation aggregation: Alert attachment aggregation (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'aggregation'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_aggregation" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_aggregation`") # noqa: E501 # verify the required parameter 'aggregation' is set if ('aggregation' not in params or params['aggregation'] is None): raise ValueError("Missing the required parameter `aggregation` when calling `update_alert_attachment_aggregation`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'aggregation' in params: body_params = params['aggregation'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/aggregation', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentAggregation', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_aggregation1(self, id, aggregation, **kwargs): # noqa: E501 """Update attachment aggregation # noqa: E501 Update alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_aggregation1(id, aggregation, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentAggregation aggregation: Alert attachment aggregation (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_aggregation1_with_http_info(id, aggregation, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_aggregation1_with_http_info(id, aggregation, **kwargs) # noqa: E501 return data def update_alert_attachment_aggregation1_with_http_info(self, id, aggregation, **kwargs): # noqa: E501 """Update attachment aggregation # noqa: E501 Update alert attachment aggregation # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_aggregation1_with_http_info(id, aggregation, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentAggregation aggregation: Alert attachment aggregation (required) :return: AlertAttachmentAggregation If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'aggregation'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_aggregation1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_aggregation1`") # noqa: E501 # verify the required parameter 'aggregation' is set if ('aggregation' not in params or params['aggregation'] is None): raise ValueError("Missing the required parameter `aggregation` when calling `update_alert_attachment_aggregation1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'aggregation' in params: body_params = params['aggregation'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/aggregation', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentAggregation', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_filters(self, id, filters, **kwargs): # noqa: E501 """Update filters # noqa: E501 Updates the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_filters(id, filters, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AttachmentFilters filters: Filters that will be updated (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_filters_with_http_info(id, filters, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_filters_with_http_info(id, filters, **kwargs) # noqa: E501 return data def update_alert_attachment_filters_with_http_info(self, id, filters, **kwargs): # noqa: E501 """Update filters # noqa: E501 Updates the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_filters_with_http_info(id, filters, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AttachmentFilters filters: Filters that will be updated (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'filters'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_filters" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_filters`") # noqa: E501 # verify the required parameter 'filters' is set if ('filters' not in params or params['filters'] is None): raise ValueError("Missing the required parameter `filters` when calling `update_alert_attachment_filters`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'filters' in params: body_params = params['filters'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/filters', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AttachmentFilters', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_filters1(self, id, filters, **kwargs): # noqa: E501 """Update filters # noqa: E501 Updates the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_filters1(id, filters, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AttachmentFilters filters: Filters that will be updated (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_filters1_with_http_info(id, filters, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_filters1_with_http_info(id, filters, **kwargs) # noqa: E501 return data def update_alert_attachment_filters1_with_http_info(self, id, filters, **kwargs): # noqa: E501 """Update filters # noqa: E501 Updates the report attachment filters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_filters1_with_http_info(id, filters, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AttachmentFilters filters: Filters that will be updated (required) :return: AttachmentFilters If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'filters'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_filters1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_filters1`") # noqa: E501 # verify the required parameter 'filters' is set if ('filters' not in params or params['filters'] is None): raise ValueError("Missing the required parameter `filters` when calling `update_alert_attachment_filters1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'filters' in params: body_params = params['filters'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/filters', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AttachmentFilters', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_resource(self, id, resource, **kwargs): # noqa: E501 """Update alert attachment resource # noqa: E501 Update alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_resource(id, resource, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentResourceV1 resource: Alert attachment resources (required) :return: AlertAttachmentResourceV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_resource_with_http_info(id, resource, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_resource_with_http_info(id, resource, **kwargs) # noqa: E501 return data def update_alert_attachment_resource_with_http_info(self, id, resource, **kwargs): # noqa: E501 """Update alert attachment resource # noqa: E501 Update alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_resource_with_http_info(id, resource, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentResourceV1 resource: Alert attachment resources (required) :return: AlertAttachmentResourceV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'resource'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_resource" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_resource`") # noqa: E501 # verify the required parameter 'resource' is set if ('resource' not in params or params['resource'] is None): raise ValueError("Missing the required parameter `resource` when calling `update_alert_attachment_resource`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'resource' in params: body_params = params['resource'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/resources', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentResourceV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_resource1(self, id, resources, **kwargs): # noqa: E501 """Update alert attachment resource # noqa: E501 Update alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_resource1(id, resources, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param list[AlertAttachmentResource] resources: Alert attachment resources (required) :return: list[AlertAttachmentResource] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_resource1_with_http_info(id, resources, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_resource1_with_http_info(id, resources, **kwargs) # noqa: E501 return data def update_alert_attachment_resource1_with_http_info(self, id, resources, **kwargs): # noqa: E501 """Update alert attachment resource # noqa: E501 Update alert attachment resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_resource1_with_http_info(id, resources, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param list[AlertAttachmentResource] resources: Alert attachment resources (required) :return: list[AlertAttachmentResource] If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'resources'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_resource1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_resource1`") # noqa: E501 # verify the required parameter 'resources' is set if ('resources' not in params or params['resources'] is None): raise ValueError("Missing the required parameter `resources` when calling `update_alert_attachment_resource1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'resources' in params: body_params = params['resources'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/resources', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[AlertAttachmentResource]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_settings(self, id, settings, **kwargs): # noqa: E501 """Update attachment settings # noqa: E501 Update alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_settings(id, settings, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentSettingsV1 settings: Alert attachment settings (required) :return: AlertAttachmentSettingsV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_settings_with_http_info(id, settings, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_settings_with_http_info(id, settings, **kwargs) # noqa: E501 return data def update_alert_attachment_settings_with_http_info(self, id, settings, **kwargs): # noqa: E501 """Update attachment settings # noqa: E501 Update alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_settings_with_http_info(id, settings, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentSettingsV1 settings: Alert attachment settings (required) :return: AlertAttachmentSettingsV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'settings'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_settings`") # noqa: E501 # verify the required parameter 'settings' is set if ('settings' not in params or params['settings'] is None): raise ValueError("Missing the required parameter `settings` when calling `update_alert_attachment_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'settings' in params: body_params = params['settings'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/settings', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentSettingsV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_settings1(self, id, settings, **kwargs): # noqa: E501 """Update attachment settings # noqa: E501 Update alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_settings1(id, settings, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentSettings settings: Alert attachment settings (required) :return: AlertAttachmentSettings If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_settings1_with_http_info(id, settings, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_settings1_with_http_info(id, settings, **kwargs) # noqa: E501 return data def update_alert_attachment_settings1_with_http_info(self, id, settings, **kwargs): # noqa: E501 """Update attachment settings # noqa: E501 Update alert attachment settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_settings1_with_http_info(id, settings, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentSettings settings: Alert attachment settings (required) :return: AlertAttachmentSettings If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'settings'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_settings1`") # noqa: E501 # verify the required parameter 'settings' is set if ('settings' not in params or params['settings'] is None): raise ValueError("Missing the required parameter `settings` when calling `update_alert_attachment_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'settings' in params: body_params = params['settings'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/settings', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentSettings', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_time_settings(self, id, time_setting, **kwargs): # noqa: E501 """Update alert attachment time settings # noqa: E501 Update alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_time_settings(id, time_setting, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param TimeSettingV1 time_setting: Alert attachment time settings (required) :return: TimeSettingV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_time_settings_with_http_info(id, time_setting, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_time_settings_with_http_info(id, time_setting, **kwargs) # noqa: E501 return data def update_alert_attachment_time_settings_with_http_info(self, id, time_setting, **kwargs): # noqa: E501 """Update alert attachment time settings # noqa: E501 Update alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_time_settings_with_http_info(id, time_setting, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param TimeSettingV1 time_setting: Alert attachment time settings (required) :return: TimeSettingV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'time_setting'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_time_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_time_settings`") # noqa: E501 # verify the required parameter 'time_setting' is set if ('time_setting' not in params or params['time_setting'] is None): raise ValueError("Missing the required parameter `time_setting` when calling `update_alert_attachment_time_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'time_setting' in params: body_params = params['time_setting'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/time', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='TimeSettingV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_time_settings1(self, id, time_setting, **kwargs): # noqa: E501 """Update alert attachment time settings # noqa: E501 Update alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_time_settings1(id, time_setting, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param TimeSettings time_setting: Alert attachment time settings (required) :return: TimeSettings If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_time_settings1_with_http_info(id, time_setting, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_time_settings1_with_http_info(id, time_setting, **kwargs) # noqa: E501 return data def update_alert_attachment_time_settings1_with_http_info(self, id, time_setting, **kwargs): # noqa: E501 """Update alert attachment time settings # noqa: E501 Update alert attachment time settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_time_settings1_with_http_info(id, time_setting, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param TimeSettings time_setting: Alert attachment time settings (required) :return: TimeSettings If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'time_setting'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_time_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_time_settings1`") # noqa: E501 # verify the required parameter 'time_setting' is set if ('time_setting' not in params or params['time_setting'] is None): raise ValueError("Missing the required parameter `time_setting` when calling `update_alert_attachment_time_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'time_setting' in params: body_params = params['time_setting'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/time', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='TimeSettings', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_visualization_settings(self, id, visualizations, **kwargs): # noqa: E501 """Update visualization settings # noqa: E501 Update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_visualization_settings(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualizationV1 visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualizationV1 If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_visualization_settings_with_http_info(id, visualizations, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_visualization_settings_with_http_info(id, visualizations, **kwargs) # noqa: E501 return data def update_alert_attachment_visualization_settings_with_http_info(self, id, visualizations, **kwargs): # noqa: E501 """Update visualization settings # noqa: E501 Update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_visualization_settings_with_http_info(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualizationV1 visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualizationV1 If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'visualizations'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_visualization_settings" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_visualization_settings`") # noqa: E501 # verify the required parameter 'visualizations' is set if ('visualizations' not in params or params['visualizations'] is None): raise ValueError("Missing the required parameter `visualizations` when calling `update_alert_attachment_visualization_settings`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'visualizations' in params: body_params = params['visualizations'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/reports/attachments/alerts/{id}/visualizations', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentVisualizationV1', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_alert_attachment_visualization_settings1(self, id, visualizations, **kwargs): # noqa: E501 """Update visualization settings # noqa: E501 Update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_visualization_settings1(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualization visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualization If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_alert_attachment_visualization_settings1_with_http_info(id, visualizations, **kwargs) # noqa: E501 else: (data) = self.update_alert_attachment_visualization_settings1_with_http_info(id, visualizations, **kwargs) # noqa: E501 return data def update_alert_attachment_visualization_settings1_with_http_info(self, id, visualizations, **kwargs): # noqa: E501 """Update visualization settings # noqa: E501 Update alert attachment visualization settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_alert_attachment_visualization_settings1_with_http_info(id, visualizations, async_req=True) >>> result = thread.get() :param async_req bool :param int id: The id of the report attachment (required) :param AlertAttachmentVisualization visualizations: Alert attachment visualization settings (required) :return: AlertAttachmentVisualization If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'visualizations'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_alert_attachment_visualization_settings1" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `update_alert_attachment_visualization_settings1`") # noqa: E501 # verify the required parameter 'visualizations' is set if ('visualizations' not in params or params['visualizations'] is None): raise ValueError("Missing the required parameter `visualizations` when calling `update_alert_attachment_visualization_settings1`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'visualizations' in params: body_params = params['visualizations'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v2/reports/attachments/alerts/{id}/visualizations', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlertAttachmentVisualization', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
n = 100 sumOfSquares = 0 curSum = 0 for i in range(1,n + 1): sumOfSquares += i ** 2 curSum += i squareOfSums = curSum ** 2 print("Sum of Squares = " + str(sumOfSquares)) print("Square of Sums = " + str(squareOfSums)) print (curSum ** 2) - sumOfSquares
from flask import Flask from flask import render_template import forms app = Flask(__name__) @app.route('/') def index(): comment_form = forms.CommentForm() title = 'Curso Flask' return render_template('index.html' , title = title, form = comment_form) if __name__ == "__main__": app.run(debug = True, port = 8000) ## MAcro del tutorial 10 """{% macro show_list_h(value) %} <h1> {{ value }} </h1> <h2> {{ value }} </h2> <h3> {{ value }} </h3> <h4> {{ value }} </h4> <h5> {{ value }} </h5> {% endmacro %}"""
######### NOP Selection ######### doc = Document.getCurrentDocument() seg = doc.getCurrentSegment() adr = doc.getCurrentAddress() start, end = doc.getSelectionAddressRange() for x in range(start,end):   seg.writeByte(x,0x90)   seg.markAsCode(x)
# -*- coding: utf-8 -*- """ 配置文件 """ import os # 集成方法分类器 from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import RandomForestClassifier # 高斯过程分类器 from sklearn.gaussian_process import GaussianProcessClassifier # 广义线性分类器 from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.linear_model import RidgeClassifier from sklearn.linear_model import SGDClassifier from sklearn.linear_model import RidgeClassifierCV # K近邻分类器 from sklearn.linear_model.base import LinearClassifierMixin, SparseCoefMixin from sklearn.neighbors import KNeighborsClassifier # 朴素贝叶斯分类器 from sklearn.naive_bayes import GaussianNB # 神经网络分类器 from sklearn.neural_network import MLPClassifier # 决策树分类器 from sklearn.tree import DecisionTreeClassifier from sklearn.tree import ExtraTreeClassifier # 支持向量机分类器 from sklearn.svm import SVC from sklearn.svm import LinearSVC # 提升树 # from xgboost import XGBClassifier # from lightgbm import LGBMClassifier class DefaultConfig(object): """ 参数配置 """ def __init__(self): pass # 次数 k = 5 # 项目路径 project_path = '/'.join(os.path.abspath(__file__).split('/')[:-2]) # 停用词文件路径 stopwords_path = project_path + '/data/stopwords/stopwords.txt' # app_desc.dat 路径 app_desc_path = project_path + '/data/original/app_desc.dat' # apptype_id_name.txt 路径 apptype_id_name_path = project_path + '/data/original/apptype_id_name.txt' # apptype_train.dat 路径 apptype_train_path = project_path + '/data/original/apptype_train.dat' # apptype_train_term_doc.h5文件保存路径 apptype_train_term_doc_path = project_path + '/data/cache/apptype_train_term_doc.h5' # app_desc_term_doc.h5文件路径 app_desc_term_doc_path = project_path + '/data/cache/app_desc_term_doc.h5' # app_desc_apptype 对app_desc进行预判断 app_desc_apptype_path = project_path + '/data/cache/app_desc_apptype.h5' # apptype_train_classification.h5文件路径 apptype_train_classification_path = project_path + '/data/cache/apptype_train_classification.h5' # app_desc_classification.h5文件路径 app_desc_classification_path = project_path + '/data/cache/app_desc_classification.h5' # apptype_train_word_index.h5 apptype_train_word_index_path = project_path + '/data/cache/apptype_train_word_index.h5' # app_desc_word_index.h5 app_desc_word_index_path = project_path + '/data/cache/app_desc_word_index.h5' # 单模型 AdaBoostClassifier_model = AdaBoostClassifier() BaggingClassifier_model = BaggingClassifier() ExtraTreesClassifier_model = ExtraTreesClassifier() GradientBoostingClassifier_model = GradientBoostingClassifier() RandomForestClassifier_model = RandomForestClassifier() GaussianProcessClassifier_model = GaussianProcessClassifier() PassiveAggressiveClassifier_model = PassiveAggressiveClassifier() RidgeClassifier_model = RidgeClassifier(alpha=0.8, tol=0.1, solver="sag", normalize=True, max_iter=1000, random_state=2019) SGDClassifier_model = SGDClassifier() KNeighborsClassifier_model = KNeighborsClassifier() GaussianNB_model = GaussianNB() MLPClassifier_model = MLPClassifier() DecisionTreeClassifier_model = DecisionTreeClassifier() ExtraTreeClassifier_model = ExtraTreeClassifier() SVC_model = SVC() LinearSVC_model = LinearSVC() # XGBClassifier_model = XGBClassifier() # LGBMClassifier_model = LGBMClassifier() LinearClassifierMixin_model = LinearClassifierMixin() RidgeClassifierCV_model = RidgeClassifierCV() SparseCoefMixin_model = SparseCoefMixin() # 选中的模型 select_model = RidgeClassifier_model # select_model = 'lgb' # select_model = 'fast_text' # replace 是否进行替换 not_replace = False # 0.608/0.744 76.43278 # model = RidgeClassifier(random_state=2019) # 0.552/0.672 # model = PassiveAggressiveClassifier(random_state=2019) # 0.607/0.725 74.81213 # model = SGDClassifier(random_state=2019)
def function1: linecode line 1 chnage the same line from bigtrouble benach linecode line 2 linecode line 3 linecode line 4 linecode line 5 linecode line 6 linecode line 7 linecode line 8 # Thanks All my student def function2: linecode line 2-1 adding more code here from master branch linecode line 2-2 linecode line 2-3 linecode line 2-4 linecode line 2-5 linecode line 2-6 linecode line 2-7 linecode line 2-8 def function3: linecode line 3-1 change done using branch 2 linecode line 3-2 new change linecode line 3-3 linecode line 3-4 linecode line 3-5 linecode line 3-6 linecode line 3-7 linecode line 3-8
# -*-coding:utf-8-*- """样本A与样本B是两个n维向量,而且所有维度的取值都是0或1。 例如:A(0111)和B(1011)。 我们将样本看成是一个集合, 1表示集合包含该元素,0表示集合不包含该元素。 P:样本A与B都是1的维度的个数 q:样本A是1,样本B是0的维度的个数 r:样本A是0,样本B是1的维度的个数 s:样本A与B都是0的维度的个数 """ from numpy import * import scipy.spatial.distance as dist # 导入scipy距离公式 matV = mat([[1,1,0,1,0,1,0,0,1],[0,1,1,0,0,0,1,1,1]]) print "dist.jaccard:", dist.pdist(matV,'jaccard')
from .. import base class IsAlpha(base.And): ''' Accepts only strings with alphabetical characters, spaces, underscores or dashes ''' def __init__(self): super(IsAlpha, self).__init__( base.types.ToType(unicode), base.strings.IsRegexMatch(base.canonicals.ALPHA_RE), error_message='The specified value "{value}" is not a purely alphabetical string.' ) class IsAlphaNumeric(base.And): ''' Accepts only strings with alphabetical characters, spaces and dashes ''' def __init__(self): super(IsAlphaNumeric, self).__init__( base.types.ToType(unicode), base.strings.IsRegexMatch(base.canonicals.ALNUM_RE), error_message='The specified value "{value}" is not a purely alphanumeric string.' ) class IsNumeric(base.And): ''' Ensures only a numeric string ''' def __init__(self): super(IsNumeric, self).__init__( base.types.ToType(unicode), base.strings.IsRegexMatch(base.canonicals.NUMERIC_RE), error_message='The specified value "{value}" is not a purely numerical string.' ) class IsText(base.And): ''' Ensures a valid set of text like characters for descriptions. Includes acceptable punctuation. ''' def __init__(self): super(IsText, self).__init__( base.types.ToType(unicode), base.strings.IsRegexMatch(base.canonicals.TEXT_RE), error_message='The specified value "{value}" is not pure text.' ) class IsName(base.And): ''' Checks to make sure the string is a name. In otherwords, no numbers, symbols, or wierd punctuation. ''' def __init__(self): super(IsName, self).__init__( base.types.ToType(unicode), base.strings.IsRegexMatch(r'^[a-z\s\.]+$'), error_message='The specified value "{value}" is not a valid name.' ) class ToYesOrNo(base.And): ''' Determines whether input is affirmative or negative based on the common English language interpretations of words and abbreviations as defined in the canonicals module. ''' def __init__(self): super(ToYesOrNo, self).__init__( base.IfElse( base.types.IsType(bool), base.And(base.types.ToType(unicode), base.strings.ToCanonical(), base.vocabulary.Synonyms(base.canonicals.TRUE_FALSE_DICT)) ), error_message='The specified value "{value}" could not be converted to a simple Yes or No.' ) from . import commerce, web
import collections import re import jieba words = ['液化气', '果味', '柚子', '绿茶', '住宿费', '果味', '柚子', '绿茶', '住宿费', '果味'] def build_dataset(words, n_words): """ 函数功能:将原始的单词表示变成index """ print('words',words) count = [['UNK', -1]] count.extend(collections.Counter(words).most_common(n_words - 1)) print('count',count) dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary)# 给字典赋值,key:word valuew:0-n_word-1; 给每个单词编号 print('dictionary',dictionary) data = list() unk_count = 0 for word in words: if word in dictionary: index = dictionary[word] else: index = 0 # UNK的index为0 unk_count += 1 data.append(index)#words中每个单词在dictionary中的位置,若该单词未在dictionary中,则为0 count[0][1] = unk_count print('data',data) print('count',count) reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) print('reversed_dictionary',reversed_dictionary) return data, count, dictionary, reversed_dictionary data, count, dictionary, reversed_dictionary=build_dataset(words,3) print('Sample data', data[:4], [reversed_dictionary[i] for i in data[:4]])
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): #setting up user interface Form.setObjectName("Form") Form.resize(800, 500) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) Form.setMinimumSize(QtCore.QSize(800, 500)) Form.setMaximumSize(QtCore.QSize(800, 500)) self.tabWidget = QtWidgets.QTabWidget(Form) self.tabWidget.setGeometry(QtCore.QRect(290, 11, 261, 111)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded) self.tabWidget.setElideMode(QtCore.Qt.ElideNone) self.tabWidget.setDocumentMode(False) self.tabWidget.setObjectName("tabWidget") self.tab_1 = QtWidgets.QWidget() self.tab_1.setObjectName("tab_1") self.saveWeightsBtn = QtWidgets.QPushButton(self.tab_1) self.saveWeightsBtn.setGeometry(QtCore.QRect(150, 45, 93, 28)) self.saveWeightsBtn.setObjectName("saveWeightsBtn") self.trainBtn = QtWidgets.QPushButton(self.tab_1) self.trainBtn.setGeometry(QtCore.QRect(150, 10, 93, 28)) self.trainBtn.setObjectName("trainBtn") self.batchSizeSpBox = QtWidgets.QSpinBox(self.tab_1) self.batchSizeSpBox.setGeometry(QtCore.QRect(90, 47, 42, 22)) self.batchSizeSpBox.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.batchSizeSpBox.setMinimum(1) self.batchSizeSpBox.setProperty("value", 8) self.batchSizeSpBox.setObjectName("batchSizeSpBox") self.batchSizeLbl = QtWidgets.QLabel(self.tab_1) self.batchSizeLbl.setGeometry(QtCore.QRect(10, 47, 71, 20)) self.batchSizeLbl.setLayoutDirection(QtCore.Qt.LeftToRight) self.batchSizeLbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.batchSizeLbl.setObjectName("batchSizeLbl") self.epochsSpBox = QtWidgets.QSpinBox(self.tab_1) self.epochsSpBox.setGeometry(QtCore.QRect(90, 12, 42, 22)) self.epochsSpBox.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.epochsSpBox.setMinimum(1) self.epochsSpBox.setProperty("value", 16) self.epochsSpBox.setObjectName("epochsSpBox") self.epochsLbl = QtWidgets.QLabel(self.tab_1) self.epochsLbl.setGeometry(QtCore.QRect(10, 12, 71, 20)) self.epochsLbl.setLayoutDirection(QtCore.Qt.LeftToRight) self.epochsLbl.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.epochsLbl.setObjectName("epochsLbl") self.tabWidget.addTab(self.tab_1, "") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.loadWeightsBtn = QtWidgets.QPushButton(self.tab) self.loadWeightsBtn.setGeometry(QtCore.QRect(150, 10, 93, 28)) self.loadWeightsBtn.setObjectName("loadWeightsBtn") self.predictBtn = QtWidgets.QPushButton(self.tab) self.predictBtn.setGeometry(QtCore.QRect(150, 45, 93, 28)) self.predictBtn.setObjectName("predictBtn") self.tabWidget.addTab(self.tab, "") self.outputLbl = QtWidgets.QLabel(Form) self.outputLbl.setGeometry(QtCore.QRect(15, 115, 43, 16)) self.outputLbl.setObjectName("outputLbl") self.plainTextEdit = QtWidgets.QPlainTextEdit(Form) self.plainTextEdit.setGeometry(QtCore.QRect(11, 137, 781, 351)) self.plainTextEdit.setFrameShadow(QtWidgets.QFrame.Sunken) self.plainTextEdit.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap) self.plainTextEdit.setReadOnly(True) self.plainTextEdit.setPlainText("") self.plainTextEdit.setObjectName("plainTextEdit") self.loadDataBtn = QtWidgets.QPushButton(Form) self.loadDataBtn.setGeometry(QtCore.QRect(30, 40, 93, 28)) self.loadDataBtn.setObjectName("loadDataBtn") self.perceptronsSpBox = QtWidgets.QSpinBox(Form) self.perceptronsSpBox.setGeometry(QtCore.QRect(150, 40, 42, 22)) self.perceptronsSpBox.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.perceptronsSpBox.setSuffix("") self.perceptronsSpBox.setMinimum(1) self.perceptronsSpBox.setMaximum(256) self.perceptronsSpBox.setProperty("value", 12) self.perceptronsSpBox.setObjectName("perceptronsSpBox") self.perceptronsLbl = QtWidgets.QLabel(Form) self.perceptronsLbl.setGeometry(QtCore.QRect(200, 42, 71, 16)) self.perceptronsLbl.setLayoutDirection(QtCore.Qt.LeftToRight) self.perceptronsLbl.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.perceptronsLbl.setObjectName("perceptronsLbl") self.resultsGroupBox = QtWidgets.QGroupBox(Form) self.resultsGroupBox.setGeometry(QtCore.QRect(560, 20, 221, 101)) self.resultsGroupBox.setObjectName("resultsGroupBox") self.mseLbl = QtWidgets.QLabel(self.resultsGroupBox) self.mseLbl.setGeometry(QtCore.QRect(20, 30, 81, 16)) self.mseLbl.setObjectName("mseLbl") self.maeLbl = QtWidgets.QLabel(self.resultsGroupBox) self.maeLbl.setGeometry(QtCore.QRect(20, 50, 81, 16)) self.maeLbl.setObjectName("maeLbl") self.meanLbl = QtWidgets.QLabel(self.resultsGroupBox) self.meanLbl.setGeometry(QtCore.QRect(110, 30, 101, 16)) self.meanLbl.setObjectName("meanLbl") self.stdLbl = QtWidgets.QLabel(self.resultsGroupBox) self.stdLbl.setGeometry(QtCore.QRect(110, 50, 101, 16)) self.stdLbl.setObjectName("stdLbl") self.timeLbl = QtWidgets.QLabel(self.resultsGroupBox) self.timeLbl.setGeometry(QtCore.QRect(20, 70, 151, 16)) self.timeLbl.setObjectName("timeLbl") self.drawPlotsCbx = QtWidgets.QCheckBox(Form) self.drawPlotsCbx.setGeometry(QtCore.QRect(150, 70, 91, 20)) self.drawPlotsCbx.setChecked(False) self.drawPlotsCbx.setObjectName("drawPlotsCbx") self.retranslateUi(Form) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): # setting up text labels _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Chernyavskiy diploma")) self.saveWeightsBtn.setText(_translate("Form", "Save weights")) self.trainBtn.setText(_translate("Form", "Train && test")) self.batchSizeLbl.setText(_translate("Form", "Batch size:")) self.epochsLbl.setText(_translate("Form", "Epochs:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_1), _translate("Form", "Train NN")) self.loadWeightsBtn.setText(_translate("Form", "Load weights")) self.predictBtn.setText(_translate("Form", "Predict")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Form", "Load weights")) self.outputLbl.setText(_translate("Form", "Output:")) self.loadDataBtn.setText(_translate("Form", "Load data")) self.perceptronsLbl.setText(_translate("Form", "perceptrons")) self.resultsGroupBox.setTitle(_translate("Form", "Results")) self.mseLbl.setText(_translate("Form", "MSE: 0.0000")) self.maeLbl.setText(_translate("Form", "MAE: 0.0000")) self.meanLbl.setText(_translate("Form", "Mean: 0.0000")) self.stdLbl.setText(_translate("Form", "Stdev: 0.0000")) self.timeLbl.setText(_translate("Form", "Training time: 0.00 sec")) self.drawPlotsCbx.setText(_translate("Form", "Draw plots")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_())
#!/usr/bin/python2.6 # Client program from socket import * import os # Create sending socket s_host = "10.0.0.11" s_port = 3157 s_addr = (s_host,s_port) send_sock = socket(AF_INET,SOCK_DGRAM) send_sock.connect(s_addr) # Create receiving socket r_host = "10.0.0.1" r_port = 3158 r_buf = 9000 #BYTES r_addr = (r_host,r_port) receive_sock = socket(AF_INET,SOCK_DGRAM) receive_sock.bind(r_addr) data = range(0,64) Pcount=0 done="\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x0c" i=0 #Receives results directly #Takes: #Data: An array long enough to receive all packets coming back #Pcount: A variable place holder containing zero #done: a string containing the expected packet from hydra indicating the end of execution def FastReceive(data,Pcount,done): while(1): data[Pcount],r_addr =receive_sock.recvfrom(r_buf) if data[Pcount]==done: break Pcount=Pcount+1 results=[data,Pcount] return results
import subprocess import sys import math # Process template with input parameters def process_template(template, arguments): processed_template = template for arg in arguments: processed_template = processed_template.replace("{{arg}}", arg ,1) return processed_template # Return template content def read(filename): file = open(filename, "r") content = file.read() file.close() return content # Write a file content def write(filename, content): file = open(filename, "w") file.write(content) file.close() # Checks input parameters if len(sys.argv) > 1 and sys.argv[1] == "-h": print("Image2map is a Python 3 utility to generate Leaflet based maps from plain images.") print("Required arguments:") print("$python3 image2map.py map_name image_path image_width image_height") print("Options and arguments (locate between Python file and arguments list):") print("-h : List help, options and arguments.") print("-mp : Execute multicore process mode (monocore by default)") elif len(sys.argv) == 1 or len(sys.argv) < 5 or (len(sys.argv) > 5 and sys.argv[1] != "-mp") or (len(sys.argv) > 6 and sys.argv[1] == "-mp"): print("Invalid parameters. Read about use in official documentation or use -h for help.") else: # Check process mode for parameters position # Monocore i = 1 # Multicore if sys.argv[1] == "-mp": i = 2 print("Generating HTML document:") # HTML data list htmlArgs = [] htmlArgs.append(sys.argv[i]) # Map name # HTML making htmlTemplate = read("template.html") htmlProcessed = process_template(htmlTemplate, htmlArgs) write("index.html", htmlProcessed) print("done.") print("Generating JavaScript document:") # Max zoom equation: log2(max(width, height)/tilesize) defaultMaxZoom = math.ceil(math.log(max(int(sys.argv[i+2]), int(sys.argv[i+3]))/256) / math.log(2)) # JS data list jsArgs = [] jsArgs.append(str(defaultMaxZoom)) # Max zoom level jsArgs.append(sys.argv[i+2]) # Image width jsArgs.append(sys.argv[i+3]) # Image height # JavaScript jsTemplate = read("template.js") jsProcessed = process_template(jsTemplate, jsArgs) write("index.js", jsProcessed) print("done.") # Map tiles image = sys.argv[i+1] # Map image # Tiles making if i != 1: subprocess.run(["python3", "gdal2tiles-multiprocess.py", "-l", "-p", "raster", "-w", "none", image, "tiles"]) else: subprocess.run(["python3", "gdal2tiles.py", "-l", "-p", "raster", "-w", "none", image, "tiles"])
# 作者 yanchunhuo # 创建时间 2018/01/19 22:36 # github https://github.com/yanchunhuo from common.fileTool import FileTool import os import subprocess import platform def java_maven_init(): print('开始java maven更新......') print('删除旧的maven依赖包......') FileTool.truncateDir('common/java/lib/java/libs') print('删除旧的maven依赖包完成......') maven_update_command = 'mvn -U -f "' + os.path.join(os.getcwd(),'config/java/pom.xml"') + ' dependency:copy-dependencies -DoutputDirectory="' + os.path.join(os.getcwd(), 'common/java/lib/java/libs"') output = subprocess.check_output(maven_update_command, shell=True, timeout=3600) if 'Windows' == platform.system(): print(output.decode('cp936')) else: print(output.decode('utf-8')) print('完成java maven更新......')
def Trans_ChampN(ChampN): EngName = "" Kr = ["가렌", "갈리오", "갱플", "그라가스", "그브", "나르", "나미", "나서스", "노틸", "녹턴", "누누", "니달리", "니코", "다리", "다이애나", "드븐", "라이즈", "라칸", "람머", "럭스", "럼블", "레넥", "레오나", "렉사이", "렝가", "루시안", "룰루", "르블랑", "리신", "리븐", "리산", "마이", "마오", "말자", "말파", "모데", "몰가", "문도", "미포", "바드", "바루스", "바이", "베이가", "베인", "벨코즈", "볼베", "브랜드","브라움", "블라디", "블츠", "빅토르", "뽀삐", "사이온", "사일러스", "샤코", "세주", "소나", "소라카", "쉔", "쉬바나", "스웨인", "스카너", "시비르", "짜오", "신드라", "신지드", "쓰레쉬", "아리", "아무무", "아우솔", "아이번", "아지르", "아칼리", "아트", "알리", "애니", "애니비아", "애쉬", "야스오", "에코", "엘리스", "오공", "오른", "오리", "올라프", "요릭", "우디르", "우르곳", "워윅", "이렐리아", "이블린", "이즈", "일라", "자르반", "자야", "자이라", "자크", "잔나", "잭스", "제드", "제라스", "제이스", "조이", "직스", "진", "질리언", "징크스", "초가스", "카르마", "카밀", "카사딘", "카서스", "카시", "카이사", "카직스", "칼리", "카타", "케넨", "케틀", "케인", "케일", "코그모", "코르키", "퀸", "클레드", "킨드", "타릭", "탈론", "탈리야", "켄치", "트런들", "트타", "트린", "트페", "트위치", "티모", "파이크", "판테", "피들", "피오라", "피즈", "딩거", "헤카림"] Eng = ["Garen", "Galio", "Gangplank", "Gragas", "Graves", "Gnar", "Nami", "Nasus", "Nautilus", "Nocturne", "Nunu & Willump", "Nidalee", "Neeko", "Darius", "Diana", "Draven", "Ryze", "Rakan", "Rammus", "Lux", "Rumble", "Renekton", "Leona", "Rek'Sai", "Rengar", "Lucian", "Lulu", "LeBlanc", "Lee Sin", "Riven", "Lissandra", "Master Yi", "Maokai", "Malzahar", "Malphite", "Mordekaiser", "Morgana", "Dr. Mundo", "Miss Fortune", "Bard", "Varus", "Vi", "Veigar", "Vayne", "Vel'Koz", "Volibear", "Brand", "Braum", "Vladimir", "Blitzcrank", "Viktor", "Poppy", "Sion", "Sylas", "Shaco", "Sejuani", "Sona", "Soraka", "Shen", "Shyvana", "Swain", "Skarner", "Sivir", "Xin Zhao", "Syndra", "Singed", "Thresh", "Ahri", "Amumu", "Aurelion Sol", "Ivern", "Azir", "Akali", "Aatrox", "Alistar", "Annie", "Anivia", "Ashe", "Yasuo", "Ekko", "Elise", "Wukong", "Ornn", "Orianna", "Olaf", "Yorick", "Udyr", "Urgot", "Warwick", "Irelia", "Evelynn", "Ezreal", "Illaoi", "Jarvan IV", "Xayah", "Zyra", "Zac", "Janna", "Jax", "Zed", "Xerath", "Jayce", "Zoe", "Ziggs", "Jine", "Zilean", "Jinx", "Cho'Gath", "Karma", "Camille", "Kassadin", "Karthus", "Cassiopeia", "Kai'Sa", "Khazix", "Kalistar", "Katarina", "Kennen", "Caitlyn", "Kayn", "Kayle", "Kog'Maw", "Corki", "Quinn", "Kled", "Kindred", "Taric", "Talon", "Taliyah", "Tahm Kench", "Trundle", "Tristana", "Tryndamere", "Twisted Fate", "Twitch", "Teemo", "Pyke", "Pantheon", "Fiddlesticks", "Fiora", "Fizz", "Heimerdinger", "Hecarim"] for i in range(0, len(Kr)): if Kr[i] == ChampN: EngName = Eng[i] break return EngName def Line_ChampN(LineX): Num = 0; Top = ["Garen", "Gangplank", "Gnar", "Nami", "Nasus", "Darius","Ryze", "Rumble", "Renekton", "Rengar", "Riven", "Lissandra", "Maokai", "Malzahar", "Malphite", "Mordekaiser", "Dr. Mundo", "Vayne", "Volibear", "Vladimir", "Viktor", "Poppy", "Sion", "Sylas", "Shen", "Singed", "Akali", "Aatrox", "Yasuo", "Wukong", "Ornn", "Olaf", "Yorick", "Urgot", "Irelia", "Illaoi", "Jax", "Jayce", "Cho'Gath", "Karma", "Camille", "Karthus", "Cassiopeia", "Kennen", "Kayle", "Quinn", "Kled", "Tahm Kench", "Tryndamere", "Teemo", "Pantheon", "Fiora", "Heimerdinger", "Hecarim"] Jg = ["Gragas", "Graves", "Nocturne", "Nunu & Willump", "Nidalee", "Rammus", "Lux", "Rek'Sai", "Rengar", "Lee Sin", "Riven", "Master Yi", "Vi", "Poppy", "Sylas", "Shaco", "Sejuani", "Shyvana", "Xin Zhao", "Amumu", "Ivern", "Aatrox", "Elise", "Wukong", "Olaf", "Udyr", "Warwick", "Evelynn", "Jarvan IV", "Zac", "Jax", "Camille", "Karthus", "Khazix", "Kayn", "Kindred", "Taliyah", "Pantheon", "Fiddlesticks", "Hecarim"] Mid = ["Galio", "Nocturne", "Neeko", "Diana", "Ryze", "Lux", "Rumble", "Renekton", "Lulu", "LeBlanc", "Riven", "Lissandra", "Malzahar", "Veigar", "Vel'Koz", "Vladimir", "Viktor", "Sion", "Sylas", "Swain", "Syndra", "Ahri", "Aurelion Sol", "Azir", "Akali", "Aatrox", "Annie", "Anivia", "Yasuo", "Ekko", "Orianna", "Irelia", "Zed", "Xerath", "Jayce", "Zoe", "Ziggs", "Zilean", "Jinx", "Karma", "Kassadin", "Karthus", "Cassiopeia", "Katarina", "Corki", "Kled", "Talon", "Taliyah", "Twisted Fate", "Pantheon", "Fiora", "Fizz"] Adc = ["Draven", "Lucian", "Miss Fortune", "Varus", "Vayne", "Vladimir", "Viktor", "Sivir", "Ashe", "Yasuo", "Ezreal", "Xayah", "Jine", "Jinx", "Cassiopeia", "Kai'Sa", "Kalistar", "Caitlyn", "Kog'Maw", "Tristana", "Twitch"] Sup = ["Gragas", "Nami", "Nautilus", "Neeko", "Rakan", "Lux", "Leona", "Lulu", "Morgana", "Bard", "Veigar", "Vel'Koz", "Brand", "Braum", "Blitzcrank", "Poppy", "Sona", "Soraka", "Shen", "Thresh", "Alistar", "Ornn", "Zyra", "Janna", "Xerath", "Zilean", "Karma", "Taric", "Tahm Kench", "Pyke", "Fiddlesticks"] for i in range(0, len(Top)): if Top[i] == LineX: Num += 10000 break for i in range(0, len(Jg)): if Jg[i] == LineX: Num += 1000 break for i in range(0, len(Mid)): if Mid[i] == LineX: Num += 100 break for i in range(0, len(Adc)): if Adc[i] == LineX: Num += 10 break for i in range(0, len(Sup)): if Sup[i] == LineX: Num += 1 break return Num
from django.db import models # Create your models here. class Bed(models.Model): name = models.TextField(max_length=80) occupancy = models.IntegerField() def __str__(self): return self.name class RoomType(models.Model): name = models.TextField(max_length=80) image = models.ImageField(upload_to='images/') bed = models.ForeignKey(Bed, on_delete=models.DO_NOTHING) num_beds = models.IntegerField(default=1) rate = models.IntegerField(default=50) def occupancy(self): return self.bed.occupancy * self.num_beds def __str__(self): return self.name
import functools import os import flask import google.oauth2.credentials import googleapiclient.discovery from app import db from app.models.user import User from app.models.army import Army, Upgrade from dotenv import load_dotenv from authlib.client import OAuth2Session from flask_login import login_user, current_user from flask import url_for ACCESS_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token' AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent' AUTHORIZATION_SCOPE = 'openid email profile' load_dotenv() AUTH_REDIRECT_URI = os.getenv("FN_AUTH_REDIRECT_URI") BASE_URI = os.getenv("FN_BASE_URI") CLIENT_ID = os.getenv("FN_CLIENT_ID") CLIENT_SECRET = os.getenv("FN_CLIENT_SECRET") AUTH_TOKEN_KEY = 'auth_token' AUTH_STATE_KEY = 'auth_state' google_auth = flask.Blueprint('google_auth', __name__, template_folder='templates') def is_logged_in(): return True if AUTH_TOKEN_KEY in flask.session else False def build_credentials(): if not is_logged_in(): raise Exception('User must be logged in') oauth2_tokens = flask.session[AUTH_TOKEN_KEY] return google.oauth2.credentials.Credentials( oauth2_tokens['access_token'], refresh_token=oauth2_tokens['refresh_token'], client_id=CLIENT_ID, client_secret=CLIENT_SECRET, token_uri=ACCESS_TOKEN_URI) def get_user_info(): credentials = build_credentials() oauth2_client = googleapiclient.discovery.build( 'oauth2', 'v2', credentials=credentials) return oauth2_client.userinfo().get().execute() def no_cache(view): @functools.wraps(view) def no_cache_impl(*args, **kwargs): response = flask.make_response(view(*args, **kwargs)) response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '-1' return response return functools.update_wrapper(no_cache_impl, view) @google_auth.route('/login') @no_cache def login(): if current_user.is_authenticated: return flask.redirect(url_for('base.index')) session = OAuth2Session(CLIENT_ID, CLIENT_SECRET, scope=AUTHORIZATION_SCOPE, redirect_uri=AUTH_REDIRECT_URI) uri, state = session.authorization_url(AUTHORIZATION_URL) flask.session[AUTH_STATE_KEY] = state flask.session.permanent = True return flask.redirect(uri, code=302) @google_auth.route('/auth') @no_cache def google_auth_redirect(): if current_user.is_authenticated: return flask.redirect(url_for('base.index')) req_state = flask.request.args.get('state', default=None, type=None) if req_state != flask.session[AUTH_STATE_KEY]: return flask.make_response('Invalid state parameter', 401) session = OAuth2Session(CLIENT_ID, CLIENT_SECRET, scope=AUTHORIZATION_SCOPE, state=flask.session[AUTH_STATE_KEY], redirect_uri=AUTH_REDIRECT_URI) oauth2_tokens = session.fetch_access_token( ACCESS_TOKEN_URI, authorization_response=flask.request.url) flask.session[AUTH_TOKEN_KEY] = oauth2_tokens google_user = get_user_info() email = google_user.get('email') avatar = google_user.get('picture') existing_user = User.query.filter_by(email=email).first() if not existing_user: user = User(email=email, avatar=avatar, is_google_user=True) db.session.add(user) db.session.commit() army = Army(user_id=user.id) db.session.add(army) db.session.commit() upgrade = Upgrade(army_id=user.id) db.session.add(upgrade) db.session.commit() login_user(user) else: login_user(existing_user) return flask.redirect(BASE_URI, code=302) @no_cache def google_logout(): flask.session.pop(AUTH_TOKEN_KEY, None) flask.session.pop(AUTH_STATE_KEY, None) return flask.redirect(BASE_URI, code=302)
from wtforms import Form, TextField, TextAreaField, SubmitField, validators, ValidationError , IntegerField class ContactForm1(Form): empname = TextField("Employer name") city1 = TextField("City") state1 = TextField("State") country1 = TextField("Country") postitle = TextField("Position title") startdate = TextField("Start date") enddate = TextField("End date") submit = SubmitField("Next")
import datetime import json from xml.etree import ElementTree from django.test import TestCase from miscosas.models import Item, Feed, User, Profile, Vote from miscosas.apps import MisCosasConfig as Config VALID_YOUTUBE_KEY = "UC300utwSVAYOoRLEqmsprfg" INVALID_YOUTUBE_KEY = "4v56789r384rgfrtg" XML = "?format=xml" JSON = "?format=json" class TestGetViewsEmpty(TestCase): def test_main_page(self): ''' Tests the index page with nothing on the database ''' response = self.client.get('/') self.assertContains(response, "class='no-content'", count=2) self.assertContains(response, "class='feed-form'", count=1) def test_feeds_page(self): ''' Tests the feeds page with nothing on the database ''' response = self.client.get('/feeds') self.assertEqual(response.status_code, 200) self.assertContains(response, "class='no-content'", count=1) self.assertContains(response, "class='feed-form'", count=1) def test_feed_page(self): ''' Tests a feed page with nothing on the database ''' test_strings = ['ksdhgf', '34', '0', '4k_j%4', '-1', '1', '2'] for key in test_strings: response = self.client.get(f'/feed/{key}') self.assertEqual(response.status_code, 404) self.assertIn('miscosas/content/not_found.html', [t.name for t in response.templates]) def test_item_page(self): ''' Tests an item page with nothing on the database ''' test_strings = ['ksdhgf', '34', '0', '4kjj34', '-1', '1', '2'] for key in test_strings: response = self.client.get(f'/item/{key}') self.assertEqual(response.status_code, 404) self.assertIn('miscosas/content/not_found.html', [t.name for t in response.templates]) def test_users_page(self): ''' Tests the users page with nothing on the database ''' response = self.client.get('/users') self.assertContains(response, "class='no-content'", count=1, status_code=200) class TestGetViewsContent(TestCase): def setUp(self): ''' Posts some forms to have content available ''' form = {'key': VALID_YOUTUBE_KEY, 'source': Config.YOUTUBE} self.client.post('/feeds', form) def test_main_page(self): ''' Tests the index page after some feeds are added ''' response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, "class='simple-list'", count=1) self.assertContains(response, "class='no-content'", count=1) self.assertContains(response, "list-brief", count=Feed.objects.count()) self.assertContains(response, "class='feed-form'", count=1) self.assertContains(response, "class='vote-form'", count=0) def test_feeds_page(self): ''' Tests the feeds page after some feeds are added ''' response = self.client.get('/feeds') self.assertEqual(response.status_code, 200) self.assertContains(response, "class='simple-list'", count=1) self.assertContains(response, "list-brief", count=Feed.objects.count()) self.assertContains(response, "class='feed-form'", count=1) def test_feed_page(self): ''' Tests the feed page after some feeds are added ''' feeds = Feed.objects.all() self.assertGreater(feeds.count(), 0) for feed in feeds: response = self.client.get(f'/feed/{feed.pk}') self.assertEqual(response.status_code, 200) self.assertContains(response, "class='feed-detailed'", count=1) self.assertContains(response, "class='simple-list'", count=1) self.assertContains(response, "list-brief", count=10) self.assertContains(response, "class='vote-form'", count=0) def test_item_page(self): ''' Tests an item page after some feeds are added ''' items = Item.objects.all() self.assertGreater(items.count(), 0) for item in items: response = self.client.get(f'/item/{item.pk}') self.assertEqual(response.status_code, 200) self.assertContains(response, "list-brief", count=1) self.assertContains(response, "class='item-detailed'", count=1) self.assertContains(response, "class='vote-form'", count=0) self.assertContains(response, "class='comment-form'", count=0) class TestGetViewsAuthenticated(TestCase): def setUp(self): ''' Posts some forms to have content available ''' form = {'key': VALID_YOUTUBE_KEY, 'source': Config.YOUTUBE} self.client.post('/feeds', form) self.user = User.objects.create_user('root', password='toor') self.other_user = User.objects.create_user('aaa', password='aaa') self.client.force_login(self.user) self.item = Item.objects.get(pk=10) self.feed = Feed.objects.get(pk=1) def test_main_page(self): ''' Tests user lists on main menu ''' scores = [ i.upvote_count - i.downvote_count for i in Item.objects.all() if i.upvote_count > 0 and i.downvote_count > 0 ][:10] response = self.client.get('/') self.assertContains(response, "class='vote-form'", count=len(scores)) self.assertContains(response, "class='simple-list'", count=1) self.assertContains(response, "class='no-content'", count=2) def test_main_page_with_votes(self): ''' Tests main page after some items have been voted ''' user_votes = [[1, 5, 6, 10, 14, 15], [2, 3, 7, 12]] other_user_votes = [[2, 3, 5, 12], [4, 6, 10, 13]] for i in user_votes: for j in i: Vote(item=Item.objects.get(pk=j), user=self.user, positive=(i == user_votes[0])).save() for i in other_user_votes: for j in i: Vote(item=Item.objects.get(pk=j), user=self.other_user, positive=(i == other_user_votes[0])).save() response = self.client.get('/') self.assertContains(response, "class='simple-list'", count=3) self.assertContains(response, "list-brief", count=15) def test_feed_page(self): ''' Tests vote forms on feed page ''' response = self.client.get('/feed/1') self.assertContains(response, "class='vote-form'", count=10) def test_item_page(self): ''' Tests vote and comment forms on item page ''' response = self.client.get('/item/' + str(self.item.pk)) self.assertContains(response, "class='vote-form'", count=1) self.assertContains(response, "class='comment-form'", count=1) def test_users_page(self): ''' Tests user list ''' response = self.client.get('/users') self.assertContains(response, "class='user-brief", count=2) self.assertContains(response, "img", count=2) def test_own_user_page(self): ''' Tests user page of logged user ''' response = self.client.get('/user/' + self.user.username) self.assertContains(response, "class='settings-form'", count=1) self.assertContains(response, Profile.DEFAULT_PICTURE, count=1) def test_own_user_page_items(self): ''' Tests items in the user page of logged user ''' self.client.post('/item/1', {'action': 'upvote'}) self.client.post('/item/3', {'action': 'upvote'}) self.client.post('/item/10', {'action': 'downvote'}) self.client.post('/item/3', {'title': 'Hey', 'content': 'This is body', 'action': 'comment'}) response = self.client.get('/user/' + self.user.username) self.assertContains(response, "class='upvoted-items'", count=1) self.assertContains(response, "class='downvoted-items'", count=1) self.assertContains(response, "class='commented-items'", count=1) self.assertContains(response, "list-brief", count=4) self.assertContains(response, "class='vote-form'", count=4) self.assertContains(response, "href='/item/1'", count=1) self.assertContains(response, "href='/item/3'", count=2) self.assertContains(response, "href='/item/10'", count=1) def test_other_user_page(self): ''' Tests user page of a different user ''' response = self.client.get('/user/' + self.other_user.username) self.assertContains(response, "class='settings-form'", count=0) class TestGetPagesAsXml(TestCase): def setUp(self): form = {'key': VALID_YOUTUBE_KEY, 'source': Config.YOUTUBE} self.client.post('/feeds', form) self.user = User.objects.create_user('root', password='toor') def test_main_page(self): response = self.client.get('/' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_main_page_logged_in(self): self.client.force_login(self.user) response = self.client.get('/' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_main_page_no_content(self): Feed.objects.get().delete() response = self.client.get('/' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_feeds_page(self): response = self.client.get('/feeds' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_feed_page_no_content(self): Feed.objects.get().delete() response = self.client.get('/feed/1' + XML) self.assertEqual(response.status_code, 404) self.assertIn('miscosas/content/not_found.html', [t.name for t in response.templates]) def test_feed_page(self): response = self.client.get('/feed/1' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_item_page(self): response = self.client.get('/item/1' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_item_page_logged_in(self): self.client.force_login(self.user) response = self.client.get('/item/1' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_users_page(self): response = self.client.get('/users' + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_user_page(self): response = self.client.get('/user/' + self.user.username + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) def test_own_user_page(self): self.client.force_login(self.user) response = self.client.get('/user/' + self.user.username + XML) self.assertEqual(response['content-type'], 'text/xml') self.assertEqual(response.status_code, 200) ElementTree.fromstring(response.content) class TestGetPagesAsJson(TestCase): def setUp(self): form = {'key': VALID_YOUTUBE_KEY, 'source': Config.YOUTUBE} self.client.post('/feeds', form) self.user = User.objects.create_user('root', password='toor') def test_main_page(self): response = self.client.get('/' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_main_page_logged_in(self): self.client.force_login(self.user) response = self.client.get('/' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_main_page_no_content(self): Feed.objects.get().delete() response = self.client.get('/' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_feeds_page(self): response = self.client.get('/feeds' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_feed_page_no_content(self): Feed.objects.get().delete() response = self.client.get('/feed/1' + JSON) self.assertEqual(response.status_code, 404) self.assertIn('miscosas/content/not_found.html', [t.name for t in response.templates]) def test_feed_page(self): response = self.client.get('/feed/1' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_item_page(self): response = self.client.get('/item/1' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_item_page_logged_in(self): self.client.force_login(self.user) response = self.client.get('/item/1' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_users_page(self): response = self.client.get('/users' + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_user_page(self): response = self.client.get('/user/' + self.user.username + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content) def test_own_user_page(self): self.client.force_login(self.user) response = self.client.get('/user/' + self.user.username + JSON) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 200) json.loads(response.content)
def reverse(word): out = "" size = len(word) idx = size - 1 while idx >= 0: out += word[idx] idx -= 1 return out print(reverse("word")) print(reverse("hockey"))
from delivery_systemC.configs.config import NAME_PSW from delivery_systemC.libs.login import Login from delivery_systemC.libs.shop import Shop #conftest放到哪一个包,只对这个包起作用!,比如当前是test_case包 import pytest import os ''' **scope**: ##有4个级别参数 "function" (默认), 在conftest作用域下,所有的def test_xxx测试方法运行前都会执行1次! "class" ,在conftest作用域下,每一个的class Testxxx测试类,运行前都会执行一次 "module" ,在conftest作用域下,每一个的test_xxx.py测试模块,运行前都会执行一次 "session" ,在conftest作用域下,这个包运行前只会执行一次 ''' @pytest.fixture(scope='session',autouse=True) #加了autouse会自动调用 def start_running(): #在自动化执行一开始就执行下面的函数代码! print("start") #测试报告数据清除 try: for one in os.listdir('../report/tmp'): if 'json' in one or 'txt' in one: os.remove(f'../report/tmp/{one}') except: print('first time run') yield # 相当于teardown用法 #fixture里面函数不能直接调用执行,如果需要调试,需要先注释@pytest.fixture(scope='session',autouse=True) #思考: 商铺的编辑接口的初始化操作,--只有这一个接口需求,其他不需要 #能不能指定一些接口执行特定的fixture--哪里需要,哪里手动调用 @pytest.fixture(scope='function') def update_shop_init(shop_init): # 1 登录 #token = Login().login(NAME_PSW, getToken=True) # token = Login().login({'username': 'sq0777', 'password': 'xintian'}, getToken=True) # # 2 店铺id 列出店铺调用 #shop = Shop(token) shopID = shop_init.shop_list({'page':1,'limit':20})['data']['records'][0]['id'] ## 3 图片Info 图片上传接口 image_info =shop_init.file_upload('123.png','../data/123.png') return shopID, image_info ''' 问题点: 1-店铺更新接口,每一次操作都得操作登陆--累赘的 2-登陆操作--不只有店铺模块需要--其他也需要 3-如果业务比较复杂,需要前置条件进行模块化 解决方案: 1. 能不能把登录操作单独剥离出来 2. 店铺的实例化也可以剥离出来 3. 操作一个模块的测试,只需要登录一次 ''' #1 能不能把登录操作单独抽离出来 @pytest.fixture(scope='class') def login_init(): token = Login().login(NAME_PSW, getToken=True) return token # 2-店铺的实例也可以剥离出来---需要关联一个fixture @pytest.fixture(scope='class') def shop_init(login_init): # 在下一个fixture需要使用上一个fixture的返回值, # 直接在下一个函数的形参里写上上一个fixture的函数名字,使用他即可以 shop = Shop(login_init) return shop ''' fixture 使用技巧 方法1,使用函数名直接调用,但是没有返回值 @pytest.mark.usefixtures('update_shop_init')#写入函数名字,调用conftest 方法2,需要使用到fixture返回值, 直接在对应的接口函数里,加入一个形参,参数名就是fixture ''' # @pytest.fixture(scope='class') # def xt_shop(): # print("----类 class fixture") # # @pytest.fixture(scope='class') # def xt_shop2(): # print("----类 class fixture2") ''' #如果一个类,或者一个方法,需要多个fixture,可以叠加,先执行就近原则,下往上先2后1执行 @pytest.mark.usefixtures('xt_shop') #类级别 @pytest.mark.usefixtures('xt_shop2') #类级别 class TestShop: '''
import math import os import subprocess import sys def path_to_file(folder, file_name): return ('%s/%s' % (folder, file_name)) def image_files_in_folder(folder, include_path=True): path = lambda file: (path_to_file(folder, file_name)) if include_path else file all_files = os.listdir(folder) path_list = [] for file in all_files: if file.endswith('.jpg'): path_list.append(path(file)) return path_list def output_from_input(path): file_name = path.split('/')[-1] return '/'.join([OUTPUT_FOLDER, file_name]) def chunker(seq, size): return (seq[pos:pos + size] for pos in xrange(0, len(seq), size)) INPUT_FOLDER = sys.argv[1] OUTPUT_FOLDER = '%s-ela' % INPUT_FOLDER images = image_files_in_folder(INPUT_FOLDER, False) images = [image for image in images if image not in image_files_in_folder(OUTPUT_FOLDER, False)] images = (map(path_to_file, [INPUT_FOLDER] * len(images), images)) io_paths = map(lambda input_path: (input_path, output_from_input(input_path)), images) for path_batch in chunker(io_paths, 8): processes = [] for input_file, output_file in path_batch: default_options = 'python image-forensics-ela.py --trigger=1 --enhance=50' shell_command = '%s %s %s' % (default_options, input_file, output_file) process = subprocess.Popen(shell_command, shell=True) processes.append(process) print(input_file, output_file) [process.wait() for process in processes] # python generate_ela_files.py non-psed
import numpy as np import pandas as pd from sklearn.gaussian_process import GaussianProcessRegressor as gauss from sklearn.model_selection import StratifiedKFold from sklearn.metrics import mean_squared_error, explained_variance_score, mean_squared_log_error, r2_score, \ label_ranking_loss, log_loss, roc_auc_score from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression l_r = LogisticRegression() clf = RandomForestClassifier(n_estimators=10) data = pd.read_csv('flood_data.csv', delimiter=';', na_values=' ') numeric_params = ['WindSpeed', 'Temp', 'Sunshine', 'Precipitation', 'SeaLevelPressure', 'Humidity', 'Evapotranspiration', 'WaterLevel'] data = data.dropna() X = data[numeric_params] y = data['Flood'] skf = StratifiedKFold(n_splits=10) model = l_r # select model you desire here for train, test in skf.split(X, y): # still casting as a regression problem to learn probabilities. it makes more sense as a classification problem though model = model.fit(np.float32(X.iloc[train].values), np.float32(y.iloc[train].values)) y_pred = model.predict_proba(X.iloc[test]) print(log_loss(y.iloc[test].values, y_pred))
# -*- coding: utf-8 -*- """ Created on Tue Jan 21 21:52:08 2014 @author: mit """ """ # This script generate sequence with hidden word with certain generative model # Description taken from the assignment: The following generative model generates K sequences of length N: s1,...,sk where si = si1,...,siN. All sequences are over the alphabet [M]. Each of these sequences has a magic word of length w hidden in it and the rest of the sequence is called background. First, for each i, a start position is sampled uniformly from [N-w+1]. The the jth positions in the magic word are sampled from qj(x), which is Cat(x|thetaj) where thetaj has has a Dir(thetaj|alpha) prior. All other positions in the sequences are sampled from the background distribution q(x), which is Cat(x|theta) where theta has a Dir(theta|alphaprime) prior. """ from numpy.random import dirichlet from numpy.random import randint from sampling import sample WRITE_TO_FILE = True ### The properties for the generated sequence K = 10 # The number of sequence N = 15 # The length for each sequence w = 6 # The length of the magic word alphabet = ['A', 'C', 'T', 'G'] # The alphabet used in the sequence M = len(alphabet) # The number of alphabet used alpha_b = [1]*M # The alpha parameter for dirichlet prior of background letter alpha_w = [10,2,8,3] # The alpha parameter for dirichlet prior of hidden word ### Start the generator part # First, generate the starting position of the magic word for all sequences uniformly position = [0]*K for i in range(K): position[i] = randint(0, N-w+1) # Generate the background letters for all sequences cat_b = dirichlet(alpha_b) sequences = [] for i in range(K): seq = [] for j in range(N): seq += [sample(alphabet, cat_b)] sequences += [seq] # Generate the magic words theta = dirichlet(alpha_w, w) for i in range(K): start_pos = position[i] for j in range(w): sequences[i][start_pos+j] = sample(alphabet, theta[j]) if WRITE_TO_FILE: ### Store the generated sequence to file to be read later filename = 'a.seq' f = open(filename, 'w') f.write(str(K)+'\n') f.write(str(N)+'\n') f.write(str(w)+'\n') f.write(''.join(alphabet)+'\n') f.write(','.join(map(str, alpha_b)) +'\n') f.write(','.join(map(str, alpha_w)) +'\n') for s in sequences: f.write(','.join(map(str, s)) +'\n') f.write(','.join(map(str, position)) +'\n') f.close() else: print('K', K) print ('N', N) print ('w', w) print ('alphabet', alphabet) print ('alpha_b', alpha_b) print ('alpha_w', alpha_w) for s in sequences: print(s) print('position', position)
#!/usr/bin/env python3.3 import argparse import os import copy import utils import fastn import sam import external_progs import nucmer def map_and_parse_sam(ref_index, tags_fasta, tag_counts, log_fh): samfile = options.outprefix + '.maptags.sam' #utils.syscall('smalt map -d -1 -y 1 -f samsoft -o ' + samfile + ' ' + ref_smalt_index + ' ' + tags_fasta) utils.syscall(external_progs.bowtie2_align + ' -f -x ' + ref_index + ' -U ' + tags_fasta + ' -S ' + samfile) sam_reader = sam.file_reader(samfile) for sam_record in sam_reader: (contig_name, range) = sam_record.id.rsplit(':', 1) assert contig_name not in tag_counts if sam_record.is_mapped() \ and sam_record.tags['AS'][1] == 0 \ and ('XS' not in sam_record.tags or sam_record.tags['XS'][1] < 0): tag_counts[contig_name] = 1 else: tag_counts[contig_name] = 2 os.unlink(samfile) def get_unique_tags(ref_index, tag_length, unique_tagged_seqs, untagged_seqs, unique_tags, log_fh, second_index=None): if len(untagged_seqs) == 0: return tags_fasta_fname = options.outprefix + '.tags.test.fa' seqs_sam = options.outprefix + '.seqs.bowtie2.sam' second_seqs_sam = options.outprefix + '.second_seqs.bowtie2.sam' fout_tags = utils.open_file_write(tags_fasta_fname) tags = {} tag_info = {} # make fasta file of tags for id, seq in untagged_seqs.items(): tag = '' if len(seq) < tag_length: tag = fastn.Fasta(seq.id + ':1-' + str(len(seq)), seq.seq) tag_info[id] = [id, '1', str(len(seq)), tag.seq] else: left_coord = int(0.5 * len(seq) - 0.5 * tag_length) right_coord = left_coord + tag_length - 1 tag = fastn.Fasta(seq.id + ':' + str(left_coord+1) + '-' + str(right_coord+1), seq[left_coord:right_coord + 1]) tag_info[id] = [id, left_coord+1, right_coord+1, tag.seq] print(tag, file=fout_tags) tags[id] = copy.copy(seq) utils.close(fout_tags) # get the count of number of hits per tag from the results tag_counts = {} second_tag_counts = {} map_and_parse_sam(ref_index, tags_fasta_fname, tag_counts, log_fh) if second_index: map_and_parse_sam(second_index, tags_fasta_fname, second_tag_counts, log_fh) assert len(tag_counts) == len(second_tag_counts) # update the unique/non-unique tagged sequences for contig_name, hit_count in tag_counts.items(): assert contig_name not in unique_tagged_seqs if second_index: second_hit_count = second_tag_counts[contig_name] else: second_hit_count = 1 if hit_count == 1 == second_hit_count: unique_tagged_seqs[contig_name] = tags[contig_name] unique_tags.append(tag_info[contig_name]) del untagged_seqs[contig_name] try: os.unlink(tags_fasta_fname) except: print('Error deleting file "' + tags_fasta_fname + '"', file=sys.stderr) sys.exit(1) parser = argparse.ArgumentParser( description = 'Given a fasta file, finds a unique tag for each sequence. Can optionally give a second fasta file, and the script will check that the tag is unique in this second file as well.', usage = '%(prog)s [options] <in.fasta> <outprefix>') parser.add_argument('--min_tag_length', type=int, help='Starting tag length [%(default)s]', default=50) parser.add_argument('--max_tag_length', type=int, help='Max tag length [%(default)s]', default=1000) parser.add_argument('--tag_step', type=int, help='Step size in tag length [%(default)s]', default=50) parser.add_argument('--second_fasta', help='Name of a second fasta file to check for uniqueness of tags', default=None) parser.add_argument('fasta_in', help='Name of input fasta file', metavar='in.fasta') parser.add_argument('outprefix', help='Prefix of output files') options = parser.parse_args() untagged_seqs = {} fastn.file_to_dict(options.fasta_in, untagged_seqs) second_seqs = {} unique_tags = [] seqs_index = options.outprefix + '.seqs.bowtie2.index' #utils.syscall('smalt index -k 20 -s 10 ' + seqs_smalt_index + ' ' + options.fasta_in) utils.syscall('bowtie2-build ' + options.fasta_in + ' ' + seqs_index) if options.second_fasta: #second_seqs_smalt_index = options.outprefix + '.second_seqs_smalt_index' second_seqs_index = options.outprefix + '.second_seqs_bowtie2_index' #utils.syscall('smalt index -k 20 -s 10 ' + second_seqs_smalt_index + ' ' + options.second_fasta) utils.syscall('bowtie2-build ' + options.second_fasta + ' ' + second_seqs_index) else: second_seqs_index=None uniquely_tagged = {} f_log = utils.open_file_write(options.outprefix + '.log') for tag_length in range(options.min_tag_length, options.max_tag_length + 1, options.tag_step): get_unique_tags(seqs_index, tag_length, uniquely_tagged, untagged_seqs, unique_tags, f_log, second_seqs_index) print(tag_length,'unique:', len(uniquely_tagged), file=f_log) print(tag_length, 'nonunique', len(untagged_seqs), file=f_log) non_unique_fa = options.outprefix + '.seqs-without-unique-tags.fa' f = utils.open_file_write(non_unique_fa) for id, seq in untagged_seqs.items(): print(seq, file=f) utils.close(f) f = utils.open_file_write(options.outprefix + '.seqs-with-unique-tags.fa') for id, seq in uniquely_tagged.items(): print(seq, file=f) utils.close(f) for ext in ['1.bt2','2.bt2','3.bt2','4.bt2','rev.1.bt2','rev.2.bt2']: os.unlink(seqs_index + '.' + ext) second_coords = {} tag_counts = {} if options.second_fasta: tags_tmp_fa = options.outprefix + '.tags.tmp.fa' f = utils.open_file_write(tags_tmp_fa) for t in unique_tags: #print('>' + t[0] + ':' + str(t[1]) + ':' + str(t[2]) + '\n' + t[3], file=f) print('>' + t[0] + '\n' + t[3], file=f) utils.close(f) samfile = options.outprefix + '.maptags.sam' #utils.syscall('smalt map -d -1 -y 1 -f samsoft -o ' + samfile + ' ' + second_seqs_smalt_index + ' ' + tags_tmp_fa) utils.syscall(external_progs.bowtie2_align + ' -f -x ' + second_seqs_index + ' -U ' + tags_tmp_fa + ' -S ' + samfile) os.unlink(tags_tmp_fa) sam_reader = sam.file_reader(samfile) for sam_record in sam_reader: if sam_record.is_mapped(): tag_counts[sam_record.id] = tag_counts.get(sam_record.id, 0) + 1 second_coords[sam_record.id] = [sam_record.rname, sam_record.pos+1] else: tag_counts[contig_name] = -1 os.unlink(samfile) #os.unlink(second_seqs_smalt_index + '.smi') #os.unlink(second_seqs_smalt_index + '.sma') for ext in ['1.bt2','2.bt2','3.bt2','4.bt2','rev.1.bt2','rev.2.bt2']: os.unlink(second_seqs_index + '.' + ext) f = utils.open_file_write(options.outprefix + '.tag.info.tsv') for t in sorted(unique_tags): if options.second_fasta: if tag_counts[t[0]] == 1: t += second_coords[t[0]] elif tag_counts[t[0]] == -1: print('Warning: unmapped tag!', t[0], file=f_log) else: print('Warning: repetitive mapped tag!', t[0], file=f_log) print('\t'.join([str(x) for x in t]), file=f) utils.close(f) utils.close(f_log)
#Author: Scott Grether, Dustin Grady #Function: Create GUI with TKinter and set up widgets. Clock and weather that updates #Status: Working/ Tested import time import calendar from weather import WeatherClass try: #python3 from tkinter import * except: #python2 from Tkinter import * time1 = time.localtime(time.time()) class Application(Frame): def createTime(self):#Create Time widget self.Time = Label(self.top_right, fg='white', background='black', font=self.labelfont) self.Time.pack(side='right') self.Time.config(borderwidth=0) self.Time.config(highlightthickness=0) def createCal(self):#Create calendar widget self.Cal = Text(self.bottom_left,height=7,width=0,background='black', fg='white') self.Cal.insert(INSERT, calendar.month(time1[0], time1[1])) self.Cal.pack(side='left',fill='both',expand=True) self.Cal.config(borderwidth=0) self.Cal.config(highlightthickness=0) def createImage(self):#Create weather image widget self.imageWidget = Label(self.bottom_right, fg='white', background='black', font=self.labelfont) self.imageWidget.pack(side="right") self.imageWidget.config(borderwidth=0) self.imageWidget.config(highlightthickness=0) def createText(self):#Create weather text widget self.textWidget = Label(self.bottom_right, fg='white', background='black', font=self.labelfont) self.textWidget.config(bg='black', fg='white') self.textWidget.config(borderwidth=0)#Get rid of 1px border self.textWidget.config(highlightthickness=0)#Get rid of 1px border self.textWidget.config(height=3, width=20) self.textWidget.pack(expand=NO, fill=BOTH, side='right') def __init__(self, master=None): Frame.__init__(self, master) self.labelfont = ('Courier', 20, 'bold')#Font for all the widgets self.main_container = Frame(master, background='black') self.main_container.pack(side='top',fill='both',expand=True) master.minsize(width=1000,height=500)#Set window size self.top_frame = Frame(self.main_container, background='black') self.top_frame.pack(side='top',fill='x',expand=False) self.bottom_frame = Frame(self.main_container, background='black') self.bottom_frame.pack(side='bottom',fill='x',expand=False) self.top_left = Frame(self.top_frame, background='black') self.top_left.pack(side="left", fill="x", expand=True) self.top_right = Frame(self.top_frame, background='black') self.top_right.pack(side="right", fill="x", expand=True) self.bottom_right = Frame(self.bottom_frame, background='black') self.bottom_right.pack(side='right',fill='x',expand=True) self.bottom_left = Frame(self.bottom_frame, background='black') self.bottom_left.pack(side='left',fill='x',expand=True) #Create all thew widgets self.createTime() self.createCal() self.createImage() self.createText() self.top_left_label = Label(self.top_left, text="Top Left", fg='white', background='black') self.top_left_label.pack(side="left") #Display live time def tick(): global time1 time2 = time.localtime(time.time()) if time2 != time1: time1 = time2 app.Time.config(text=time.asctime(time1)) app.Time.after(1000, tick) '''Draw weather status/icon''' def draw_Weather(): global weatherClassObject weatherClassObject = WeatherClass() weatherImage = weatherClassObject.weatherImage weatherInfo = weatherClassObject.location + '\n' + str(weatherClassObject.currentWeather) + '\n' + str(weatherClassObject.currentTemperature + 'F')#Get description of weather/ temperature app.imageWidget.config(image = weatherImage) #update image app.textWidget.config(text = weatherInfo) #update text app.imageWidget.after(30000, draw_Weather)#update every x milliseconds root = Tk() root.title('Smart Mirror') app = Application(root) tick()#Initial call for clock ticking draw_Weather()#Initial call to get draw_Weather going root.mainloop()
from flask import Blueprint from flask import jsonify from yelp_beans.logic.metrics import get_meeting_participants from yelp_beans.logic.metrics import get_meeting_requests from yelp_beans.logic.metrics import get_subscribers from yelp_beans.models import MeetingSubscription metrics_blueprint = Blueprint("metrics", __name__) @metrics_blueprint.route("/subscribers", methods=["GET"]) def meeting_subscribers(): metrics = [] subscribed_users = get_subscribers() subscriptions = MeetingSubscription.query.all() for subscription in subscriptions: subscribed = set(subscribed_users[subscription.id]) for subscriber in subscribed: metrics.append( { "title": subscription.title, "subscriber": subscriber, } ) resp = jsonify(metrics) resp.status_code = 200 return resp @metrics_blueprint.route("/meetings", methods=["GET"]) def meeting_participants(): resp = jsonify(get_meeting_participants()) resp.status_code = 200 return resp @metrics_blueprint.route("/requests", methods=["GET"]) def meeting_requests(): resp = jsonify(get_meeting_requests()) resp.status_code = 200 return resp
from django.contrib import admin from models import Lobbyist, LobbyistCorporation, LobbyistsChange from django.contrib.contenttypes import generic from links.models import Link class LinksInline(generic.GenericTabularInline): model = Link ct_fk_field = 'object_pk' extra = 1 class LobbyistAdmin(admin.ModelAdmin): fields = ('person', 'description', 'image_url', 'large_image_url',) readonly_fields = ('person',) inlines = (LinksInline,) class LobbyistCorporationAdmin(admin.ModelAdmin): fields = ('name', 'description',) readonly_fields = ('name',) inlines = (LinksInline,) class LobbyistsChangeAdmin(admin.ModelAdmin): list_display = ('date', 'type', 'content_type', 'object_id', 'content_object') admin.site.register(Lobbyist, LobbyistAdmin) admin.site.register(LobbyistCorporation, LobbyistCorporationAdmin) admin.site.register(LobbyistsChange, LobbyistsChangeAdmin)
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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. """Tests for tensor2tensor.data_generators.program_search.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import os import shutil import tempfile from builtins import bytes # pylint: disable=redefined-builtin from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import program_search import tensorflow as tf class ProgramSearchAlgolispStub(program_search.ProgramSearchAlgolisp): """Stub of ProgramSearchAlgolisp that stubs out maybe_download_dataset. The maybe_download_dataset writes one predetermined example in a zip file self.n number of times and returns the file path. """ EXAMPLE = ('{"funcs": [], "tests": [{"output": 0, "input": {"a": 5}}, ' '{"output": 1, "input": {"a": 20}}, {"output": 2, "input": ' '{"a": 28}}, {"output": 1, "input": {"a": 13}}, {"output": 1, ' '"input": {"a": 27}}, {"output": 1, "input": {"a": 13}}, ' '{"output": 1, "input": {"a": 20}}, {"output": 0, ' '"input": {"a": 8}}, {"output": 0, "input": {"a": 8}}, ' '{"output": 0, "input": {"a": 4}}], "short_tree": ["invoke1", ' '["lambda1", ["if", ["==", ["len", ["digits", "arg1"]], "1"], "0",' ' ["+", "1", ["self", ["reduce", ["digits", "arg1"], "0", ' '"+"]]]]], "a"], "tags": [], "text": ["given", "a", "number", "a",' ' ",", "find", "how", "many", "times", "you", "can", "replace", ' '"a", "with", "sum", "of", "its", "digits", "before", "it", ' '"becomes", "a", "single", "digit", "number"], "return_type": ' '"int", "args": {"a": "int"}, "nodes": ["l1_recursive_digits"]}') EXAMPLE_INPUT = ('given a number a , find how many times you can replace a ' 'with sum of its digits before it becomes a single digit ' 'number') EXAMPLE_TARGET = ('[ invoke1 [ lambda1 [ if [ == [ len [ digits arg1 ] ] 1 ]' ' 0 [ + 1 [ self [ reduce [ digits arg1 ] 0 + ] ] ] ] ] a ' ']') N = 10 def maybe_download_dataset(self, tmp_dir, dataset_split): (_, data_file) = tempfile.mkstemp( suffix='.gz', prefix=str(dataset_split) + '-', dir=tmp_dir) with gzip.open(data_file, 'wb') as gz_file: content = '\n'.join([self.EXAMPLE] * self.N) gz_file.write(bytes(content, 'utf-8')) return data_file class ProgramSearchAlgolispTest(tf.test.TestCase): @classmethod def setUpClass(cls): # Setup the temp directory tree. cls.tmp_dir = tf.test.get_temp_dir() shutil.rmtree(cls.tmp_dir) os.mkdir(cls.tmp_dir) @classmethod def tearDownClass(cls): # Cleanup the temp directory tree. shutil.rmtree(cls.tmp_dir) def testEndToEnd(self): # End-to-end test, the stub problem class creates a .gz file with nps_stub.N # example and we check if we're able to process it correctly. nps_stub = ProgramSearchAlgolispStub() num = 0 for example in nps_stub.generate_samples(None, self.tmp_dir, problem.DatasetSplit.TRAIN): # Only one example in 'file', so this is OK. self.assertEqual(example['inputs'], ProgramSearchAlgolispStub.EXAMPLE_INPUT) self.assertEqual(example['targets'], ProgramSearchAlgolispStub.EXAMPLE_TARGET) num += 1 # assert that we have as many examples as there are in the file. self.assertEqual(num, nps_stub.N) if __name__ == '__main__': tf.test.main()
from django.shortcuts import render from django_redis import get_redis_connection from django.views import View import json, time from django.http import JsonResponse from django.shortcuts import render from homes.models import House import datetime from .models import Order from ihome.utils.views import LoginRequiredJsonMixin # Create your views here. from django.db.models import Q class AddorderView(LoginRequiredJsonMixin,View): # 定义POST方法 # TODO: 带验证 def post(self, request): user = request.user data = json.loads(request.body.decode()) house_id = data.get('house_id') start_date = data.get('start_date') end_date = data.get('end_date') # 提取参数 # 校验参数 house = House.objects.get(pk=house_id) # 判断下单用户是否为房主 # 下订单的用户编号 不能等于 房屋主人的用户编号  if user.id == house.user_id: return JsonResponse({'errno': '4105', 'errmsg': '用户身份错误'}) if not all([house_id, start_date, end_date]): return JsonResponse({'errno': '4103', 'errmsg': '参数错误'}) # 业务处理 # 判断用户是否登陆 # # 登陆查询5号库 # conn = get_redis_connection('order_information') # redis_orders = conn.hgetall('orders_%s' % user.id) order = Order.objects.filter(Q(house_id=house_id)&Q(begin_date=start_date)) # 判断用户所选房屋是否被预定 if order: return JsonResponse({'errno': '4003', 'errmsg': '数据已存在'}) else: # 写入数据库 days = (datetime.datetime.strptime(end_date, '%Y-%m-%d') - datetime.datetime.strptime(start_date, '%Y-%m-%d')).days house_price = int(house.price)/(int(house.acreage)/int(house.capacity)) order = Order( user_id=user.id, house_id=house_id, begin_date=start_date, end_date=end_date, house_price = house_price, days = days, amount = house_price*int(days), ) order.save() return JsonResponse({ "data": { "order_id": order.id }, "errno": '0', "errmsg": "下单成功" }) def get(self, request): # 提取参数 user = request.user role = request.GET.get('role') # 校验参数 if not role: return JsonResponse({'errno': '4103', 'errmsg': '参数错误'}) # 定义一个空字典用 # 判断用户是否登陆 # if user.is_authenticated: # 构建响应列表 if role == 'custom': orders = [] # ord_ids = Order.objects.all() # 便利并向列表中添加数据 # for ord_id in ord_ids: ord = Order.objects.filter(user_id=user.id) for i in ord: house = House.objects.get(id=i.house_id) orders.append({ 'amount': i.amount, 'comment': i.comment, 'ctime': i.create_time.strftime("%Y-%m-%d"), 'days': i.days, "end_date": i.end_date, "img_url": "http://qj9kppiiy.hn-bkt.clouddn.com/%s" % house.index_image_url, "order_id": i.id, "start_date": i.begin_date, "status": Order.ORDER_STATUS_ENUM.get(i.status), "title": house.title }) return JsonResponse({ "data":{ "orders": orders}, "errmsg": 'ok', "errno": '0' }) if role == 'landlord': orders = [] # ord_ids = Order.objects.all() # 便利并向列表中添加数据 # for ord_id in ord_ids: house = House.objects.filter(user_id=user.id) for k in house: ord=Order.objects.filter(house_id=k.id) for i in ord: house = House.objects.get(id=i.house_id) orders.append({ 'amount': i.amount, 'comment': i.comment, 'ctime': i.create_time.strftime("%Y-%m-%d"), 'days': i.days, "end_date": i.end_date, "img_url": "http://qj9kppiiy.hn-bkt.clouddn.com/%s" % house.index_image_url, "order_id": i.id, "start_date": i.begin_date, "status": Order.ORDER_STATUS_ENUM.get(i.status), "title": house.title }) return JsonResponse({ "data":{ "orders": orders}, "errmsg": 'ok', "errno": '0' }) #todo 带验证 class OrderStatus(LoginRequiredJsonMixin,View): def put(self, request, order_id): # 1 提取参数 data = json.loads(request.body.decode()) action = data.get('action') reason = data.get('reason') # 2 校验参数 if not action: return JsonResponse({"errno": "4103", "errmsg": "参数错误,缺少必要参数"}) # 3 业务处理 order = Order.objects.get(pk=order_id) if action == "accept": try: order.status = 3 # 状态为1(待支付) 表示房东已经接单 order.save() except Exception as e: return JsonResponse({"errno": "4001", "errmsg": "数据库写入错误"}) elif action == "reject": if not reason: return JsonResponse({"errno": "4103", "errmsg": "参数错误,缺少必要参数"}) try: order.status = 6 # 状态为6(已拒单) 表示房东已经拒单 order.comment = reason order.save() except Exception as e: return JsonResponse({"errno": "4001", "errmsg": "数据库写入错误"}) # 4 构建响应 return JsonResponse({ "errno": "0", "errmsg": "操作成功" }) #todo 带验证 class OrderComment(LoginRequiredJsonMixin,View): def put(self, request, order_id): data = json.loads(request.body.decode()) comment = data.get('comment') if not comment: return JsonResponse({"errno": "4103", "errmsg": "参数错误,缺少必要参数"}) try: order = Order.objects.get(pk=order_id) order.comment = comment order.status = 4 order.save() except Exception as e: return JsonResponse({"errno": "4001", "errmsg": "数据库写入错误"}) # 4 构建响应 return JsonResponse({ "errno": "0", "errmsg": "评论成功" })
# Lesson2, Task4 # check the method id() # id() method for integers x = 2 y = x print (x, y, id(x), id(y), id(2), id(3)) print () y = 3 print (x, y, id(x), id(y)) print () # python variables are references to the objects, but not objects itself # when y=x - y becomes a number from the reference to number 2 # when y=3 - y becomes a number from the reference to number 3, # it doesn't affect x, since it is still a number fromt the reference to a number 2 # id() method for lists x = [1,2] y = x print(x, y, id(x), id(y), id([1,2]), id([1,3])) print () y[1] = 3 print(x, y, id(x), id(y)) # python lists are objects, so when y=x - y not only has a value of x, # but also the same reference is to x and y. # When changing y we also change the value from a reference to y, # which is also a reference to x. So we change x value as well.
"""Shared utility functions for testing suite.""" import os from datetime import datetime def parse_filing_document_header(file_path): parsed = { "ACCESSION NUMBER": [], "CONFORMED SUBMISSION TYPE": [], "COMPANY CONFORMED NAME": [], "FILED AS OF DATE": [], } header = extract_header(file_path) for line in header: components = [l.strip() for l in line.split(":")] if ( components[0] == "ACCESSION NUMBER" or components[0] == "CONFORMED SUBMISSION TYPE" or components[0] == "COMPANY CONFORMED NAME" or components[0] == "FILED AS OF DATE" ): parsed[components[0]].append(components[1]) return parsed def extract_header(file_path): header = [] with open(file_path, "r", encoding="ascii") as f: for line in f: # </SEC-HEADER> indicates the end of the header info if line == "</SEC-HEADER>\n": break header.append(line) return header def verify_directory_structure( base_dir, filing_types, num_downloaded, symbol, full_cik, company_name, before_date=None, amends_included=False, ): # no ticker symbol available (only CIK) if symbol is None: symbol = strip_cik(full_cik) dir_content = os.listdir(base_dir) assert len(dir_content) == 1 assert dir_content[0] == "sec_edgar_filings" next_level_of_dir = base_dir.joinpath("sec_edgar_filings") assert next_level_of_dir.is_dir() dir_content = os.listdir(next_level_of_dir) assert len(dir_content) == 1 assert dir_content[0] == symbol next_level_of_dir = next_level_of_dir.joinpath(symbol) assert next_level_of_dir.is_dir() dir_content = os.listdir(next_level_of_dir) assert len(dir_content) == len(filing_types) for i in range(len(filing_types)): assert filing_types[i] in dir_content for ft in filing_types: next_level_of_dir_tmp = next_level_of_dir.joinpath(ft) assert next_level_of_dir_tmp.is_dir() dir_content = os.listdir(next_level_of_dir_tmp) assert len(dir_content) == num_downloaded next_level_of_dir_tmp = next_level_of_dir_tmp.joinpath(dir_content[0]) assert next_level_of_dir_tmp.is_file() assert next_level_of_dir_tmp.suffix == ".txt" accession_number = next_level_of_dir_tmp.stem # assert accession_number[:len(full_cik)] == full_cik header_contents = parse_filing_document_header(next_level_of_dir_tmp) assert ( len(header_contents["ACCESSION NUMBER"]) == 1 and len(header_contents["CONFORMED SUBMISSION TYPE"]) == 1 ) assert header_contents["ACCESSION NUMBER"][0] == accession_number header_submission = header_contents["CONFORMED SUBMISSION TYPE"][0] if amends_included: assert header_submission == ft or header_submission == f"{ft}/A" else: assert header_submission == ft # lack of standard SEC-HEADER format makes it hard to exact match the company name # without more advanced edge-case parsing, so this is a good estimate of the check assert company_name in header_contents["COMPANY CONFORMED NAME"] if before_date is not None: filing_date = datetime.strptime( header_contents["FILED AS OF DATE"][0], "%Y%m%d" ) assert filing_date <= datetime.strptime(before_date, "%Y%m%d") def strip_cik(full_cik): return full_cik.lstrip("0")
__author__ = 'andi' __scrabble_letters = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} # what is the english scrabble score of cloud def scrabble_score(question): word = question[38:] score = 0 for letter in word: score += __scrabble_letters[letter] return str(score) def __is_anagram(word1, word2): if len(word1) != len(word2): return False else: for letter in word1: if word1.count(letter) != word2.count(letter): return False return True # which of the following is an anagram of "listen": google, enlists, banana, silent def anagram(question): terms = question[40:] single_word = terms.split(":")[0].replace("\"", "") word_list = terms.split(":")[1].strip().split(", ") anagram_list = list() for word in word_list: if __is_anagram(single_word, word): anagram_list.append(word) return ", ".join(anagram_list)
from flask_login import UserMixin from datetime import datetime from . import db class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000)) class Orders(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) order_time = db.Column(db.DateTime, default=datetime.utcnow) class OrderLine(db.Model): id = db.Column(db.Integer, primary_key=True) product = db.Column(db.String(100)) price = db.Column(db.Float) user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
from ARappServer.DBinterface import AR_db import pandas as pd import numpy as np def _prepareData(objectID,limit = 10): ''' Извлечение данных и их подготовка для подачи на вход нейросети :param objectID: id физического объекта :param limit: колическтво данных, извлекаемых из БД :return: извлечённые данные типа DataFrame ''' labels = ["temp1"] data = AR_db.getManyByID(objectID,limit=limit) preparedData = [] for item in data: temp = [] for label in labels: temp.append(item[label]) preparedData.append(temp) df = pd.DataFrame(preparedData,columns=labels) return df def _reshapeData(dataFrame,window = 10): ''' Представление данных для подачи на вход нейросети LSTM :param dataFrame: входной датафрейм данных :param window: размер окна, по умолчанию равен 10 :return: два массива типа NumPy: массив с историческими данными и данными, необходимые для соотнесения обучения, т.е подаваемых на выход LSTM data_past - input data_next - output - предсказанные данные ''' data_past = [] data_next = [] for i in range(window, len(dataFrame)): data_past.append(dataFrame.iloc[i - window:i]) data_next.append(dataFrame.iloc[i]) return np.array(data_past), np.array(data_next) def prepareDataForTrain(ObjectID,quantity,window = 10): ''' Подготовка данных для обучения нейронной сети LSTM :param ObjectID: id физического объекта :param quantity: количество извлекаемых данных :param window: размер окна обучения :return: два массива типа NumPy: массив с историческими данными и данными, необходимые для соотнесения обучения, т.е подаваемых на выход LSTM data_past - input data_next - output - предсказанные данные ''' dataFrame = _prepareData(ObjectID,quantity) data_past,data_next = _reshapeData(dataFrame, window=window) return data_past,data_next def prepareDataForPredict(ObjectID,window = 10): ''' Подготовка данных для предсказания нейронная сеть - LSTM :param ObjectID: id физического объекта :param window: размер окна обучения и по совместительству количество извлекаемых данных :return: массива типа NumPy с последними историческими данными ''' dataFrame = _prepareData(ObjectID, window) data = np.array([dataFrame]) return data def prepareDataForTest(ObjectID,quantity,window = 10): ''' Подготовка данных для предсказания нейронная сеть - LSTM :param ObjectID: id физического объекта :param window: размер окна обучения и по совместительству количество извлекаемых данных :return: массива типа NumPy с последними историческими данными ''' dataFrame = _prepareData(ObjectID, quantity) data_past, data_next = _reshapeData(dataFrame, window=window) dataFrame = _prepareData(ObjectID, window) return np.array(data_past),data_next if __name__ == "__main__": x,y = prepareDataForTrain(1,6,3) # x = prepareDataForPredict(1)
from django.db import models from .Item import Item from .Attribute import Attribute class ItemAttribute(models.Model): item = models.ForeignKey(Item) attribute = models.ForeignKey(Attribute) class Meta: app_label = 'Core'
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from .models import TestimonialComponent, TestimonialItem from .admin import TestimonialItemInline @plugin_pool.register_plugin class TestimonialComponentPlugin(CMSPluginBase): model = TestimonialComponent inlines = [TestimonialItemInline] render_template = 'testimonial_plugin/plugin/testimonial_component.html' cache = False def render(self, context, instance, placeholder): context = super(TestimonialComponentPlugin, self).render(context, instance, placeholder) return context
import json import datetime def default(o): if isinstance(o, (datetime.date, datetime.datetime)): return o.strftime('%Y-%m-%d %H:%M') def action_create(action_type, **kwargs): return json.dumps({'forType': action_type, 'payload': kwargs}, default=default) class Connection: connection: dict = dict() def set(self, user_id, sid): try: self.connection[user_id].append(sid) except KeyError: self.connection[user_id] = [sid] def get(self, user_id): return self.connection[user_id] def delete(self, user_id, sid): for key, connect in enumerate(self.connection[user_id]): if connect == sid: del (self.connection[user_id][key]) def has_connections(self, user_id): return bool(self.connection.get(user_id)) connections = Connection()
import random import math def sigmoid(x): return 1 / (1 + math.exp(-x)) def derivativeSigmoid(x): return sigmoid(x) * (1-sigmoid(x)) class Perceptron: weights = [] input = [] learnRate = 0 bias = -1 def __init__(self, inputs, learnRate=0.1): # Add a bias self.input = inputs + [self.bias] for entry in self.input: self.weights.append(random.random()) self.learnRate = learnRate def get_sum(self): sum = 0 for i in range(len(self.input)): sum += self.input[i] * self.weights[i] return sum def update(self, expected): differences = [] for entry in self.input: tmp = self.learnRate * entry * derivativeSigmoid(self.get_sum()) * (expected - self.get_activation()) differences.append(tmp) for i in range(len(differences)): self.weights[i] = self.weights[i] + differences[i] def set_input(self, input): # Minus one because of the bias if len(input) != len(self.input)-1: print("ERROR: The new input is not correct, either too many or too few points") print("New input", input) print("Current input", self.input) exit() else: # re-add the bias self.input = input + [self.bias] def get_activation(self): return sigmoid(self.get_sum()) def __repr__(self): tmp = "" for i in range(len(self.input)): tmp += "Input: " + str(self.input[i]) + " Weight: " + str(self.weights[i]) + "\n" tmp += "Current output with these settings: " + str(self.get_activation()) + "\n" return tmp ####### # NOR # ####### 1|2|3| output trainingNOR = [[[0,0,0], 1], [[1,0,0], 0], [[1,1,0], 0], [[1,1,1], 0], [[0,1,0], 0], [[0,1,1], 0], [[0,0,1], 0], [[1,0,1], 0]] NOR = Perceptron(trainingNOR[0][0]) for j in range(100): for i in range(len(trainingNOR)): NOR.set_input(trainingNOR[i][0]) NOR.update(trainingNOR[i][1]) print("NOR RESULTS:") for i in range(len(trainingNOR)): NOR.set_input(trainingNOR[i][0]) print("{:2} {:20} {}".format(trainingNOR[i][1], NOR.get_activation(), 1 if NOR.get_activation() > 0.19 else 0))
from __future__ import unicode_literals import re from django.db import models class UserManager(models.Manager): def basic_validator(self, post_data): errors = {} EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if len(post_data['first_name']) < 1: errors['first_name'] = "Please provide a first name." if len(post_data['last_name']) < 1: errors['last_name'] = "Please provide a last name." if len(post_data['email']) < 1: errors['email'] = "Please provide a email." if not EMAIL_REGEX.match(post_data['email']): errors['email'] = "Invalid email address!" if len(post_data['password']) < 1: errors['password'] = "Please provide a password." if post_data['pw_confirm'] != post_data['password']: errors['pw_confirm'] = "Password confirmation doesn't match" return errors class User(models.Model): first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) email = models.EmailField() password = models.CharField(max_length = 64) created_at = models.DateTimeField(auto_now = True) updated_at = models.DateTimeField(auto_now = True) objects = UserManager() class Collection(models.Model): title = models.CharField(max_length=64) desc = models.CharField(max_length=255, default = "None") created_at = models.DateTimeField(auto_now = True) updated_at = models.DateTimeField(auto_now = True) user = models.ForeignKey(User, related_name="collections", on_delete=models.CASCADE, default = "") class TaskManager(models.Manager): def basic_validator(self, post_data): errors = {} if len(post_data['content']) < 1: errors['content'] = "" return errors class Task(models.Model): content = models.CharField(max_length=255) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now = True) updated_at = models.DateTimeField(auto_now = True) user = models.ForeignKey(User, related_name = "tasks", on_delete= models.CASCADE) collection = models.ForeignKey(Collection, related_name = "tasks", on_delete = models.CASCADE) objects = TaskManager()
import sys from guess import play , judge ans = []; def main(show): while len(ans) != 1: tryAns(nextGuess() , show) if show: print('ans is {}'.format(ans[0])) def genAns(idx , cur): global ans if idx == 0: ans = []; for i in range(0 , 10): if i in cur: continue elif idx != 3: genAns(idx + 1 , cur + [i]) else :ans.append(''.join([str(e) for e in cur + [i]])) def redAns(guess , a , b): global ans ans = [e for e in ans if judge(guess , e) == (a , b)] def tryAns(guess , show): tryAns.count += 1 redAns(guess , *play(guess)) if show: print("{}: guess {}".format(tryAns.count , guess)) nextGuess = lambda: ''.join([str(e) for e in ans[0]]) genAns(0 , []) if not sys.flags.interactive and __name__ == '__main__': tryAns.count = 0 main(show=True)
from setuptools import setup, find_packages from ethocaissuerclient.core.version import get_version VERSION = get_version() f = open('README.md', 'r') LONG_DESCRIPTION = f.read() f.close() setup( name='ethocaissuerclient', version=VERSION, description='An API client allowing an Issuer to use Ethoca', long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', author='Alan Blount', author_email='zeroasterisk@gmail.com', url='https://github.com/zeroasterisk/ethoca-issuer-client', license='unlicensed', packages=find_packages(exclude=['ez_setup', 'tests*']), package_data={'ethocaissuerclient': ['templates/*']}, include_package_data=True, entry_points=""" [console_scripts] ethocaissuerclient = ethocaissuerclient.main:main """, )
from django import forms from pyclass.todo.models import ToDoItem class ToDoItemForm(forms.ModelForm): class Meta: model = ToDoItem fields = ("name", "details", "excellence", "importance", "due", "interests", "tags")
''' This file is HTTP test for search (GET) Parameter: (token, query_str) Return: {messages} Steps to test search: 1. Register a user 2. The user login to the server 3. create a channel 4. send a message and search 5. test 1. search successfully ''' from json import load, dumps import urllib.request import urllib.parse import sys sys.path.append('..') import pytest PORT_NUMBER = '5204' BASE_URL = 'http://127.0.0.1:' + PORT_NUMBER @pytest.fixture def register_and_login_user_1(): ''' register and login(user1) ''' # RESET req = urllib.request.Request( f'{BASE_URL}/workspace/reset', headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) # REGISTER register_info = dumps({ 'email': 'z5237609@unsw.edu.au', 'password': 'Zxl010128', 'name_first': 'Xinlei', 'name_last': 'Zhang' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/register', data=register_info, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) # Login login_info = dumps({ 'email': 'z5237609@unsw.edu.au', 'password': 'Zxl010128' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST' ) payload = load(urllib.request.urlopen(req)) return payload @pytest.fixture def create_public_channel(): ''' public channel created ''' # Create public channel user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' channel_info = dumps({ 'token': user_1_token, 'name': 'publicchannel', 'is_public': True }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/channels/create', data=channel_info, headers={'Content-Type': 'application/json'}, method='POST' ) payload = load(urllib.request.urlopen(req)) return payload @pytest.fixture def create_private_channel(): ''' private channel created ''' # Create public channel user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' channel_info = dumps({ 'token': user_1_token, 'name': 'privatechannel', 'is_public': False }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/channels/create', data=channel_info, headers={'Content-Type': 'application/json'}, method='POST' ) payload = load(urllib.request.urlopen(req)) return payload @pytest.fixture def send_a_message(): ''' send message in the created channel ''' # send a message user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' message_info = dumps({ 'token': user_1_token, 'channel_id': 1, 'message': 'hello' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/message/send', data=message_info, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) message_info = dumps({ 'token': user_1_token, 'channel_id': 2, 'message': 'helloworld' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/message/send', data=message_info, headers={'Content-Type': 'application/json'}, method='POST' ) payload = load(urllib.request.urlopen(req)) return payload def test_search(register_and_login_user_1, create_public_channel, create_private_channel, send_a_message): ''' test normal cases ''' user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' response = register_and_login_user_1 assert response['u_id'] == 1 assert isinstance(response['token'], str) assert response['token'] == user_1_token response2 = create_public_channel assert response2['channel_id'] == 1 response3 = create_private_channel assert response3['channel_id'] == 2 response4 = send_a_message assert response4['message_id'] == 2 # Get search queryString = urllib.parse.urlencode({ 'token' : user_1_token, 'query_str' : 'hel' }) payload = load(urllib.request.urlopen(f"{BASE_URL}/search?{queryString}")) assert len(payload['messages']) == 2 assert payload['messages'][0]['message'] == 'helloworld' assert payload['messages'][1]['message'] == 'hello'
// MIN_LEVEL = 5 // MAX_LEVEL = 15 // Light switch | Bulb brightness // Dimmer level | 5 watt | 10 watt | 20 watt // 5 | 0 | 0 | 0 // 10 | 2.5 | 5 | 10 // 15 | 5 | 10 | 20 // new dimmer_switch // new light_bulb 20_watt // connect light_bulb -> dimmer_switch // set_level dimmer_switch 10 // get_brightness light_bulb 10 class Dimmer: def __init__(self,max_dim,min_dim): self.max_dim = max_dim self.min_dim = min_dim class Bulb(Dimmer): def __init__(self, watt,dim_lev,dimmer): self.watt = watt self.dim_lev = dim_lev super().__init__(dimmer.max_dim,dimmer.min_dim) def get_brightness(self): print(self.min_dim) res = ((self.dim_lev - self.min_dim) / (self.max_dim - self.min_dim)) * self.watt return res new_dimmer = Dimmer(15,5) new_bulb = Bulb(5,13,new_dimmer) res = new_bulb.get_brightness() print(res)
# Generated by Django 3.0.8 on 2020-07-09 15:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('brawler', '0002_auto_20200709_1348'), ] operations = [ migrations.AlterField( model_name='brawler', name='name', field=models.CharField(max_length=125, unique=True), ), ]
# converts from JSON to db model format from rest_framework import serializers from user_trophies.models import user_trophy class user_trophySerializer(serializers.ModelSerializer): class Meta: model = user_trophy fields = ('userID', 'trophy')
import cv2 import numpy as np #Greyscale img = np.zeros((512, 512)) cv2.imshow("Image", img) #RGB img2 = np.zeros((512, 512, 3), np.uint8) #Blue #img2[:] = 255, 0, 0 #cv2.line(img2, (0,0), (300,300), (0, 255, 0), 3) #cv2.line(image, (starting point), (ending point), (color), thickness) cv2.line(img2, (0,0), (img.shape[1], img.shape[0]), (0, 255, 0), 3) #cv2.line(image, (starting point), (diagonal point), (color), thickness) cv2.rectangle(img2, (0, 0), (250,350), (0, 0, 255), 2) #Fill Rectangle replace thickness with cv2.FILLED #cv2.rectangle(img2, (0, 0), (250,350), (0, 0, 255), cv2.FILLED) #cv2.circle(img, (starting point), radius, (color), thickness) cv2.circle(img2, (400, 50), 30, (255, 255, 0), 5) #cv2.putText(image, "text", (starting point), font, scale, (color), thickness) cv2.putText(img2, " OPEN CV ", (300, 200), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 150, 0), 1) cv2.imshow("Image 2", img2) cv2.waitKey(0)
# Generated by Django 3.0.4 on 2021-04-18 18:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('quizz', '0008_delete_result'), ] operations = [ migrations.RemoveField( model_name='choice', name='question', ), ]
from task.transformer_est import Classification from models.transformer import bert import tensorflow as tf class transformer_mt: def __init__(self, hp, voca_size, num_class_list, is_training=True): config = bert.BertConfig(vocab_size=voca_size, hidden_size=hp.hidden_units, num_hidden_layers=hp.num_blocks, num_attention_heads=hp.num_heads, intermediate_size=hp.intermediate_size, type_vocab_size=hp.type_vocab_size, ) seq_length = hp.seq_max use_tpu = False input_ids = tf.placeholder(tf.int64, [None, seq_length], name="input_ids") input_mask = tf.placeholder(tf.int64, [None, seq_length], name="input_mask") segment_ids = tf.placeholder(tf.int64, [None, seq_length], name="segment_ids") self.x_list = [input_ids, input_mask, segment_ids] self.y1 = tf.placeholder(tf.int64, [None], name="y1") self.y2 = tf.placeholder(tf.int64, [None], name="y2") self.y = [self.y1, self.y2] summary1 = {} summary2 = {} self.summary_list = [summary1, summary2] use_one_hot_embeddings = use_tpu self.model = bert.BertModel( config=config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings) task = Classification(num_class_list[0]) pred, loss = task.predict(self.model.get_sequence_output(), self.y1, True) self.logits = task.logits self.sout = tf.nn.softmax(self.logits) self.pred = pred self.loss = loss self.acc = task.acc summary1['loss1'] = tf.summary.scalar('loss', self.loss) summary1['acc1'] = tf.summary.scalar('acc', self.acc) with tf.variable_scope("cls2"): task2 = Classification(num_class_list[1]) pred, loss = task2.predict(self.model.get_sequence_output(), self.y2, True) self.logits2 = task2.logits self.sout2 = tf.nn.softmax(self.logits2) self.pred2 = pred self.loss2 = loss self.acc2 = task2.acc summary2['loss2'] = tf.summary.scalar('loss2', self.loss2) summary2['acc2'] = tf.summary.scalar('acc2', self.acc2) self.logit_list = [self.logits, self.logits2] self.loss_list = [self.loss, self.loss2] self.pred_list = [self.pred, self.pred2]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def distributeCoins(self, root): """ :type root: TreeNode :rtype: int """ global res res = 0 def dfs(r): global res if not r: return (0,0) c1,n1 = dfs(r.left) c2,n2 = dfs(r.right) N = n1 + n2 + r.val-1 # net coins going up res += c1 + c2 #print r.val, 'L',(c1,n1), 'R',(c2,n2), 'E', c1+c2,N C = abs(N) return (C,N) dfs(root) return res from library_for_lc import * t = deser([0,0,0,0,0,0,7]) # 4 print Solution().distributeCoins(t) """ t = deser([1,0,0,null,3]) # 4 print Solution().distributeCoins(t) t = deser([1,0,2]) # 2 print Solution().distributeCoins(t) t = deser([0,3,0]) # 3 print Solution().distributeCoins(t) t = deser([3,0,0]) # 2 print Solution().distributeCoins(t) t = deser([1,3,1,0,0,0,2]) # 4 print Solution().distributeCoins(t) """
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-24 01:26 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Gateway', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('gateway_id', models.CharField(default='ffff', max_length=64)), ('gateway_name', models.CharField(default='no name', max_length=64)), ('vendor', models.CharField(default='Huawei', max_length=64)), ('gateway_type', models.CharField(choices=[('LoRa', 'LoRa'), ('others', 'others')], default='LoRa', max_length=64)), ('province', models.CharField(choices=[('Guangdong', 'Guangdong'), ('Liaoning', 'Liaoning')], default='Guangdong', max_length=64)), ('city', models.CharField(choices=[('Guangzhou', 'Guangzhou'), ('Shenzhen', 'Shenzhen'), ('others', 'others')], default='Guangzhou', max_length=64)), ('address', models.CharField(default='Earth', max_length=64)), ('latitude', models.DecimalField(decimal_places=6, default=113.957666, max_digits=9)), ('longitude', models.DecimalField(decimal_places=6, default=22.523888, max_digits=9)), ('register_time', models.DateTimeField(auto_now_add=True)), ('Lastalive_time', models.DateTimeField(default=django.utils.timezone.now)), ('device_status', models.CharField(choices=[('ENABLED', 'ENABLED'), ('DISABLED', 'DISABLED')], default='ENABLED', max_length=32)), ], options={ 'ordering': ('gateway_id', 'gateway_name', 'gateway_type', 'register_time'), }, ), migrations.CreateModel( name='GatewayData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('data1', models.CharField(default='data1', max_length=128)), ('data2', models.CharField(default='data2', max_length=128)), ('battery', models.CharField(default='5%', max_length=64)), ('time', models.DateTimeField(auto_now_add=True)), ('gateway', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='gateways.Gateway')), ], ), ]
#!/usr/bin/env python from __future__ import print_function PKG = 'rbe_3002' NAME = 'a_star_test' import sys import unittest import rospy import rostest from rbe_3002.srv import * class TestAStar(unittest.TestCase): def test_correct_response(self): # When we setup access to the aStar service rospy.loginfo("Starting Unit Test") rospy.wait_for_service('a_star') s = rospy.ServiceProxy('a_star', AStar) startPoint = (4, 4) goalPoint = (7, 9) # When we make a request to this service req = AStarRequest(startPoint, goalPoint) pathResponse = s(req) path = zip(pathResponse.pathx, pathResponse.pathy) #Then the first and last values returned by the path should be the start and goal repspectively self.assertEquals(goalPoint, path[0], "The first elemet of the returned tuple was not the goal point") self.assertEquals(startPoint, path[-1], "The last elemet of the returned tuple was not the start point") if __name__ == '__main__': rostest.rosrun(PKG, NAME, TestAStar, sys.argv)
# encoding:utf-8 """ 1. 获取域名的IP地址以及地理位置,同时更新数据库,更新数据库规则如下: 1)若数据库中无该域名记录,则插入; 2)若数据库中有该域名记录,则与该域名最近一次的更新记录进行比较,若相同则不更新,不同则更新。 2. 获取域名的CNAME,同时更新数据库,规则与上相同 程亚楠 创建:2017.9.8 """ import schedule import time import DNS from db_manage import get_col from ip2location import ip2region from datetime import datetime source_col = 'malicious_domains' target_col = 'domain_ip_cname1' def resolve_domain_record(domain): """ 获取解析到的域名ip和cname列表 """ cnames = [] ips = [] req_obj = DNS.Request() try: answer_obj = req_obj.req(name=domain, qtype=DNS.Type.A, server="222.194.15.253") for i in answer_obj.answers: if i['typename'] == 'CNAME': cnames.append(i['data']) elif i['typename'] == 'A': ips.append(i['data']) except DNS.Base.DNSError: cnames = [] ips =[] return ips, cnames def fetch_mal_domains(): """ 获取待查询的域名列表 """ col = get_col(source_col) gamble_domains = col.find({}, {'_id': 0, 'domain': 1,'typ':1}) # 赌博网站 return [ (i['domain'],i['typ']) for i in gamble_domains] def is_same(source_data, target_data): """ 判断两个列表是否相同 """ return sorted(source_data) == sorted(target_data) def is_cname_same(cnames, original_cnames): """ 判断IP列表是否相同 """ cnames.sort() original_cnames.sort() return cnames == original_cnames def get_ip_cname(domain): """ 得到域名的IP地址列表和IP的地理位置 """ ips, cnames = resolve_domain_record(domain) geos = [] for i in ips: geos.append(ip2region(i)) return { 'domain': domain, 'ips': ips, 'cnames': cnames, 'geos': geos } def nonexistent_insert_db(ip_cname, dm_ty): """ 该域名若不存在则插入 """ insert_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") col = get_col(target_col) domain = ip_cname['domain'] # 域名记录若不存在则插入,存在则不做任何操作 result = col.update( { "domain": domain, }, { "$setOnInsert": { "dm_cname": [ { "cnames": ip_cname['cnames'], "insert_time": insert_time } ], 'dm_ip': [ { "ips": ip_cname['ips'], "geos":ip_cname['geos'], "insert_time": insert_time } ], "record_time": insert_time, # 文档插入时间 "dm_type": dm_ty }, }, True ) return result['updatedExisting'] # 是否更新返回标记位 def update_time(col, domain, dns_type, insert_time,cur_time): """ 当与最近一条记录相同时,则只更新时间即可 """ col_filed = "" if dns_type == 'CNAME': col_filed = 'dm_cname' elif dns_type == 'A': col_filed='dm_ip' col.update( {'domain': domain, col_filed+'.insert_time': insert_time }, { '$set': {col_filed+'.$.insert_time': cur_time}, # 注意$的使用 "$inc": { "visit_times": 0.5 } } ) def update_data(ip_cname): """ 若记录存在,则检查该条记录是否需要进行更新 """ cur_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") domain = ip_cname['domain'] ips = ip_cname['ips'] geos = ip_cname['geos'] cnames = ip_cname['cnames'] col = get_col(target_col) domain_data = col.find({'domain': domain}) # 得到数据库中已存的记录信息 d = list(domain_data)[:] original_ip_record = d[0]['dm_ip'][-1] original_cname_record = d[0]['dm_cname'][-1] original_ips, original_ip_insert_time = original_ip_record['ips'], original_ip_record['insert_time'] original_cnames, original_cname_insert_time = original_cname_record['cnames'],original_cname_record['insert_time'] # 判断IP是否相同 if is_same(ips, original_ips): print "与最近IP记录一致,更新时间" update_time(col, domain, 'A', original_ip_insert_time, cur_time) else: print "与最近IP记录不一致,新添加记录" insert_record(col,"A",domain,ips,cur_time,geos) # 判断cname是否相同 if is_same(cnames, original_cnames): print "与最近CNME记录一致,更新时间" update_time(col,domain,'CNAME',original_cname_insert_time,cur_time) else: print "与最近CNAME记录不一致,新添加记录" insert_record(col,'CNAME',domain,cnames,cur_time,geos) def insert_record(col,dns_type,domain,insert_data,cur_time,geos): name_field = {} if dns_type == "CNAME": name_field = { "dm_cname":{ "cnames": insert_data, "insert_time": cur_time } } elif dns_type == "A": name_field = { "dm_ip":{ "ips":insert_data, "geos":geos, "insert_time": cur_time } } col.update( {'domain': domain}, {"$push": name_field, "$inc": { "visit_times": 0.5 } } ) def main(): """ 主函数 """ domains = fetch_mal_domains() # 获取待查询的域名列表 for d, dm_ty in domains: print d, ':', dm_ty try: ip_cname = get_ip_cname('www.'+d) # 注意添加www insert_flag = nonexistent_insert_db(ip_cname,dm_ty) if insert_flag: update_data(ip_cname) else: print "域名新插入" except: print "异常" continue if __name__ == '__main__': main() schedule.every(2).hours.do(main) # 12小时循环探测一遍 while True: schedule.run_pending() time.sleep(1)
NUMBER_ONE = "h_1" NUMBER_TWO = "h_2" NUMBER_THREE = "h_3" NUMBER_FOUR = "h_4" NUMBER_FIVE = "h_5" NUMBER_SIX = "h_6" NUMBER_SEVEN = "h_7" NUMBER_EIGHT = "h_8" NUMBER_NINE = "h_9" NUMBER_TEN = "h_10" NUMBER_ELEVEN = "h_11" NUMBER_TWELVE = "h_12" DESCRIPTOR_AFTER = "de_after" DESCRIPTOR_BEFORE = "de_before" DESCRIPTOR_HALF = "de_half" DISTANCE_FIVE = "di_five" DISTANCE_TEN = "di_ten" DISTANCE_QUARTER = "di_quarter" DISTANCE_TWENTY = "di_twenty" MINUTE_ONE = "min_one" MINUTE_TWO = "min_two" MINUTE_THREE = "min_three" MINUTE_FOUR = "min_four" class TimeConstants: @staticmethod def get_hour_constants(hour): return "h_" + str(hour)
def resolve(): ''' code here ''' import collections N = int(input()) A_list = [[int(item) for item in input().split()] for _ in range(N)] A_list.sort(key=lambda x:x[0]) def is_root(node): root_check_que = collections.deque([node]) foot_print = [False for _ in range(N)] while root_check_que: temp_node = root_check_que.popleft() foot_print[temp_node] = True children = A_list[temp_node][1:3] for child in children: if child >= 0 and foot_print[child] == False: root_check_que.append(child) return all(foot_print) def preorder(node): if node == -1: return print('',node, end='') left = A_list[node][1] right = A_list[node][2] preorder(left) preorder(right) for i in range(N): if is_root(i): root = i break def inorder(node): if node == -1: return left = A_list[node][1] right = A_list[node][2] inorder(left) print('',node, end='') inorder(right) def postorder(node): if node == -1: return left = A_list[node][1] right = A_list[node][2] postorder(left) postorder(right) print('',node, end='') for i in range(N): if is_root(i): root = i break print('Preorder') preorder(root) print('') print('Inorder') inorder(root) print('') print('Postorder') postorder(root) print('') if __name__ == "__main__": resolve()
from collections import Counter def find_it(seq): counted = Counter(seq) for item in counted.items(): if item[1] % 2 != 0: return item[0] # add k v pairs with number and count of number # Idenitfy odd count # Return number
from __future__ import division, print_function import twitter import json from operator import itemgetter import string from gensim import corpora, models import nltk from nltk import word_tokenize, FreqDist import pandas as pd from time import sleep import numpy as np import pylab as pl with open("../data/uber.json") as f: uber = json.load(f) all_list = [status['text'] for status in uber['statuses']] names = [status['user']['screen_name'] for status in uber['statuses']] locations = [status['user']['location'] for status in uber['statuses']] verified = [status['text'] for status in uber['statuses'] if status['user']['verified'] is True] names = [status['user']['screen_name'] for status in uber['statuses'] if status['user']['verified'] is True] text_uber = " ".join([text for text in all_list]) textnltk_uber = nltk.Text(word_tokenize(text_uber)) textnltk_uber.collocations() textnltk_uber.count("taxi") textnltk_uber.concordance("taxi") stopwords = nltk.corpus.stopwords.words("english") def tweet_clean(t): cleaned_words = [word for word in t.split() if "http" not in word and not word.startswith("@") and not word.startswith(".@") and not word.startswith("#") and word != "RT"] return " ".join(cleaned_words) def tweet_clean(t): clean_words = [word for word in t.split() if "http" not in word and not word.startswith("@") and not word.startswith(".@") and word != "RT"] cleaned_words = [word.replace('#', '') for word in clean_words] return " ".join(cleaned_words) def all_punct(x): return all([char in string.punctuation for char in x]) def my_tokenize(text): init_words = word_tokenize(text) return [w.lower() for w in init_words if not all_punct(w) and w.lower() not in stopwords] tweet_list_cleaned = [my_tokenize(tweet_clean(tweet)) for tweet in all_list] tokens_list_cleaned = [] for i in tweet_list_cleaned: tokens_list_cleaned+=i fd = FreqDist(nltk.Text(tokens_list_cleaned)) ######################################################## # if want to look at top words dic = {} for word in fd.keys(): if fd[word]>=100: dic[word]=fd[word] dic2 = {} for word in dic.keys(): if word.isalpha(): dic2[word]=dic[word] X = np.arange(len(dic2)) pl.bar(X, dic2.values(), width=0.5) pl.xticks(X+0.25, dic2.keys(), rotation=70) ymax = max(dic2.values()) + 100 pl.ylim(0, ymax) pl.xlim(-0.5, len(dic2)) pl.tight_layout() pl.savefig('word_freq.png') pl.show()
# https://leetcode.com/problems/wildcard-matching/ # 如何优化匹配的速率 # 主要是遇到 * 时,后面的匹配需要一直遍历才行 class Solution: def isMatch(self, s: str, p: str) -> bool: chars = [""] for char in p: if char == "*" and chars[-1] == char: continue chars.append(char) p = "".join(chars) return self._isMatch(s, p) def _isMatch(self, s: str, p: str) -> bool: if not p: return len(s) == 0 if p[0] == "*": if len(p) == 1: return True newP = p[1:] i = 0 while i <= len(s): if self._isMatch(s[i:], newP): return True i += 1 return False if not s: return False if p[0] != "?" and p[0] != s[0]: return False return self._isMatch(s[1:], p[1:])
import tensorflow as tf import os from xbrl import XBRLParser, GAAP, GAAPSerializer num_steps = 500 batch_size = 128 data_x = [] data_y = [] test_x = [] test_y = [] for subdir, dirs, files in os.walk("data/"): print(os.path.split(subdir)[-1]) for f in files: xbrl_parser = XBRLParser() print(subdir+"/"+f) try: xbrl = xbrl_parser.parse(subdir+"/"+f) except: continue gaap_obj = xbrl_parser.parseGAAP(xbrl, context="current", ignore_errors=0) print("We here 2") serializer = GAAPSerializer() result = serializer.dump(gaap_obj) if "-13-" in f : test_x.append([]) for i, k in result.data: test_x[-1].append(k) else: data_x.append([]) for i, k in result.data: data_x[-1].append(k) print(data_x) X = tf.placeholder("float", [None, 76]) Y = tf.placeholder("float", [None, 2]) in_dim = 68 weights = { 'h1': tf.Variable(tf.random_normal([in_dim, 75])), 'h2': tf.Variable(tf.random_normal([75, 75])), 'h3': tf.Variable(tf.random_normal([75, 75])), 'h4': tf.Variable(tf.random_normal([75, 75])), 'h5': tf.Variable(tf.random_normal([75, 75])), 'h6': tf.Variable(tf.random_normal([75, 75])), 'h7': tf.Variable(tf.random_normal([75, 75])), 'h8': tf.Variable(tf.random_normal([75, 75])), 'out': tf.Variable(tf.random_normal([75, 2])) } biases = { 'b1': tf.Variable(tf.random_normal([75])), 'b2': tf.Variable(tf.random_normal([75])), 'b3': tf.Variable(tf.random_normal([75])), 'b4': tf.Variable(tf.random_normal([75])), 'b5': tf.Variable(tf.random_normal([75])), 'b6': tf.Variable(tf.random_normal([75])), 'b7': tf.Variable(tf.random_normal([75])), 'b8': tf.Variable(tf.random_normal([75])), 'out': tf.Variable(tf.random_normal([2])) } l1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) l2 = tf.add(tf.matmul(l1, weights['h1']), biases['b1']) l3 = tf.add(tf.matmul(l2, weights['h1']), biases['b1']) l4 = tf.add(tf.matmul(l3, weights['h1']), biases['b1']) l5 = tf.add(tf.matmul(l4, weights['h1']), biases['b1']) l6 = tf.add(tf.matmul(l5, weights['h1']), biases['b1']) l7 = tf.add(tf.matmul(l6, weights['h1']), biases['b1']) l_out = tf.matmul(l7, weights['out']) + biases['out'] loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.1) train_op = optimizer.minimize(loss_op) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(training_epochs): avg_cost = 0. total_batch = int(len(data_x)/batch_size) x = data_x y = data_y for i in range(total_batch): batch_x, batch_y = data_x[:i], data_y[:i] _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y}) avg_cost += c / total_batch if epoch % 100 == 0: print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost)) pred = tf.nn.softmax(logits) correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1)) print(pred) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # print("Accuracy:", accuracy.eval({X: data_x, Y: data_y}))
import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import matplotlib.pyplot as plt from util2 import get_normalized_data, y2indicator def error_rate(p, t): return np.mean(p != t) def main(): X_train, X_test, Y_train, Y_test = get_normalized_data() max_iter = 10 print_period = 10 learning_rate = 0.00004 regularization = 0.01 Ytrain_ind = y2indicator(Y_train) Ytest_ind = y2indicator(Y_test) N = X_train.shape[0] D = X_train.shape[1] batch_size = 500 n_batches = N/batch_size M1 = 300 M2 = 100 K = 10 W1_init = np.random.randn(D, M1)/28 b1_init = np.zeros(M1) W2_init = np.random.randn(M1, M2)/np.sqrt(M1) b2_init = np.zeros(M2) W3_init = np.random.randn(M2, K)/np.sqrt(M2) b3_init = np.zeros(K) X = tf.placeholder(tf.float32, shape=(None, D), name='X') T = tf.placeholder(tf.float32, shape=(None, K), name='T') W1 = tf.Variable(W1_init.astype(np.float32)) # if this doesnt work, make it np.float32 and find diff between both b1 = tf.Variable(b1_init.astype(np.float32)) W2 = tf.Variable(W2_init.astype(np.float32)) b2 = tf.Variable(b2_init.astype(np.float32)) W3 = tf.Variable(W3_init.astype(np.float32)) b3 = tf.Variable(b3_init.astype(np.float32)) Z1 = tf.nn.relu(tf.matmul(X, W1) + b1) Z2 = tf.nn.relu(tf.matmul(Z1, W2) + b2) Y_temp = tf.matmul(Z2, W3) + b3 cost = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(Y_temp, T)) train_op = tf.train.RMSPropOptimizer(learning_rate, decay= 0.99, momentum=0.9).minimize(cost) predict_op = tf.argmax(Y_temp, 1) #why this?? LL = [] init = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init) for i in range(max_iter): for j in range(int(n_batches)): X_batch = X_train[j*batch_size: (j+1)*batch_size,] Y_batch = Ytrain_ind[j*batch_size: (j+1)*batch_size,] sess.run(train_op, feed_dict={X:X_batch, T:Y_batch}) if print_period%10 == 0: test_cost = sess.run(cost, feed_dict={X:X_test, T: Ytest_ind}) prediction = sess.run(predict_op, feed_dict={X:X_test}) err = error_rate(prediction, Y_test) print ("Cost/err at iteration i=%d j=%d: %.3f / %.3f" % (i,j,test_cost,err)) LL.append(test_cost) plt.plot(LL) plt.show() if __name__ == '__main__': main()
from django.shortcuts import render, redirect from item.models import Item from django.shortcuts import render from .models import Cart, CartItem from django.http import HttpResponse from delivery.models import DeliveryBoy def view_cart(request): cart_id=request.session.get('cart_id',None) user=request.user if user.is_authenticated: if cart_id is not None: cart_obj=Cart.objects.get(pk=cart_id) cartitems=CartItem.objects.filter(cart=cart_obj) else: cart_obj=Cart.objects.create(user=user) request.session['cart_id']=cart_obj.id cartitems=CartItem.objects.filter(cart=cart_obj) n=DeliveryBoy.objects.filter().count() deliverytime=15*(n+1) return render(request,'mycart/view.html',{'cartitems':cartitems,'deliverytime':deliverytime,'ordertotal':'0'}) else: return HttpResponse("Please Go Back And LogIn First!!") def checkout(request): cart_id=request.session.get('cart_id', None) user=request.user if user.is_authenticated: if cart_id is not None: cart_obj=Cart.objects.get(pk=cart_id) n=DeliveryBoy.objects.filter(is_active=True).count() deliverytime=15*(n+1) return render(request,'mycart/view.html',{'deliverytime':deliverytime,'ordertotal':'0'}) def add_cart(request,item_id): cart_id=request.session.get('cart_id',None) user=request.user if user.is_authenticated: if cart_id is None: cart_obj=Cart.objects.create(user=user) request.session['cart_id']=cart_obj.id cartitem=CartItem.objects.filter(user=user,item=Item.objects.get(pk=item_id)) cartitems=cart_obj.items.all() else : cart_obj=Cart.objects.get(pk=cart_id) if CartItem.objects.filter(cart=cart_obj,item=Item.objects.get(pk=item_id)).exists(): cartitem=CartItem.objects.get(cart=cart_obj,item=Item.objects.get(pk=item_id)) cartitem.quantity+=1 cartitem.save() cartitems=CartItem.objects.filter(cart=cart_obj) else: cartitem=CartItem.objects.create(cart=cart_obj,item=Item.objects.get(pk=item_id)) cartitem.quantity=1 cartitem.save() cartitems=CartItem.objects.filter(cart=cart_obj) return render(request,'mycart/view.html',{'cartitems':cartitems}) else : return HttpResponse("Please Go Back and LOgin First!")
# Programming Exercise 3-2 # # Program to find which of two rectangles has the greater area. # This program will get two sets of lengths and widths from a user, # use them to calculate and compare two area values, # and display a message comparing those areas # Local variables # you need length, width and area for A and for B # initialize these as floats a_width = 0.0 a_length = 0.0 a_area = 0.0 b_width = 0.0 b_length = 0.0 b_area = 0.0 # Get length A from the user and convert it to a float a_width = input("What is the length of Rectangle a: ") a_length = input("what is the width of Recangle a: ") b_length = input("What is the lenght of Rectangle b: ") b_width = input("What is the length of Rectangle b: ") # Get width A from the user and convert it to a float a_length = float(a_length) a_width = float(a_width) b_length = float(b_length) b_width = float(b_width) # Get length B from the user and convert it to a float # Get width B from the user and convert it to a float # Calculate area A a_area = a_length * a_width a_area = ("%.2f" % a_area) # Calculate area B b_area = b_length * b_width b_area = ("%.2f" % b_area) # Print each area, formatting the values to 2 decimal places # if area A is greater, print "A is greater" message. print("Rectangle A = " , a_area) print("Rectangle B = " , b_area) if a_area > b_area: print("Rectangle A is greater than Rectangle B") elif b_area > a_area: print("Recangle B is greater than rectangle A") # else if area B is greater, print "B is greater" message. # else print "A and B are equal" message. else: print("Recangle A and B are Equal")
#! python3 # multiplicationTable - take a cmd line argument and create a multiplication table import openpyxl, sys from openpyxl.utils import get_column_letter from openpyxl.styles import Font userMultiplication = int(sys.argv[1]) wb = openpyxl.Workbook() sheet = wb.active for i in range(1, userMultiplication+1): sheet.cell(row=1,column=i + 1).value = i sheet.cell(row=1, column=i + 1).font = Font(bold=True) sheet.cell(row=i + 1, column = 1).value = i sheet.cell(row=i + 1, column=1).font = Font(bold=True) for col in range(2, userMultiplication+2): for row in range(2, userMultiplication+2): col_letters = get_column_letter(col) sheet[col_letters + str(row)] = (col - 1) * (row - 1) wb.save('multiplicationTable.xlsx')
# Generated by Django 2.2.6 on 2020-01-15 09:29 import datetime from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('ventas', '0052_auto_20200115_0055'), ] operations = [ migrations.AlterField( model_name='detalle_venta', name='descuento', field=models.DecimalField(decimal_places=2, default=0.0, max_digits=20, null=True), ), migrations.AlterField( model_name='detalle_venta', name='iva', field=models.DecimalField(decimal_places=2, default=0.0, max_digits=20, null=True), ), migrations.AlterField( model_name='venta', name='fecha', field=models.DateTimeField(default=datetime.datetime(2020, 1, 15, 9, 29, 17, 830685, tzinfo=utc)), ), migrations.AlterField( model_name='venta', name='id_medio_venta', field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.PROTECT, to='ventas.Medio_Venta'), preserve_default=False, ), ]
from tkinter import * import random import time from tkinter.simpledialog import askstring from tkinter import scrolledtext import xlrd b0=xlrd.open_workbook('b.xlsx') a0=xlrd.open_workbook('a.xlsx') c0=xlrd.open_workbook('c.xlsx') b=b0.sheet_by_index(0) a=a0.sheet_by_index(0) c=c0.sheet_by_index(0) def goto(line) : global lineNumber line = lineNumber def diseaselist(sym): colno=0 x0=[] for i in range(0,317): if(a.cell_value(0,i)==sym): colno=i break for i in range(1,66): if(a.cell_value(i, colno)==1): x0.append(a.cell_value(i,0)) return(x0) class App: def Encrypt1(self): global x symp1=self.contents1.get() symp1=symp1.lower() x=diseaselist(symp1) def Encrypt(self): global symp2 global x symp2 = self.contents.get() symp2 = symp2.lower() flag=0 for i in range(0,317): if(a.cell_value(0,i)==symp2): flag=1 break if(flag==1): y=diseaselist(symp2) x1=set(x) y1=set(y) f=x1.intersection(y) if(len(f)<=3): f=list(f) ctr=1 for i in range(0,len(f)): lbl=Label(root, text=f[i], font=("Arail", 10)) lbl.grid(column=0, row=10+i+ctr) for j in range(0,18): if(c.cell_value(j,0)==f[i]): txt=scrolledtext.ScrolledText(root, width=40, height=10) txt.grid(column=2, row=10+i+ctr) txt.insert(INSERT, c.cell_value(j, 1)) break ctr=ctr+1 exit() else: lbl=Label(root, text="Enter the next symptom.", font=("Arail", 10)) lbl.grid(column=0, row=5) x=list(f) else: lbl=Label(root, text="Enter the next symptom.", font=("Arail", 10)) lbl.grid(column=0, row=5) def __init__(self, master,x): frame = Frame(master) frame.grid() lbl=Label(frame, text="Welcome to your personal doctor.", font=("Arail Bold", 20)) lbl.grid(column=0, row=0) lbl1=Label(frame, text="Enter your symptoms or click on the suggested symptoms.", font=("Arial", 10)) lbl1.grid(column=0, row=1) lbl2=Label(frame, text="We will together predict the disease that you might have to treat you as soon as possible.", font=("Arial", 10)) lbl2.grid(column=0, row=2) #create a button with the quit command, and tell it where to go quitbutton = Button(frame, text = "quit", fg ="red", command = root.quit, width = 10) quitbutton.grid(row = 0, column =10) #create an entry box, tell it where it goes, and how large it is entry1 = Entry(frame, width = 100) entry1.grid(column = 0, row=3) #set initial content of the entry box self.contents1 = StringVar() self.contents1.set("Enter the first symptom here") entry1["textvariable"] = self.contents1 encrypt1 = Button(frame, text="Add this symptom", fg = "blue", command = self.Encrypt1) encrypt1.grid(row =3, column =2) #create an entry box, tell it where it goes, and how large it is entry = Entry(frame, width = 100) entry.grid(column = 0, row=4) #set initial content of the entry box self.contents = StringVar() self.contents.set("Enter the next symptom here") entry["textvariable"] = self.contents encrypt = Button(frame, text="Add this symptom", fg = "blue", command = self.Encrypt) encrypt.grid(row =4, column =2) root = Tk() root.title("Personal Doctor") root.geometry('900x500') flag=0 k=0 app = App(root,[]) root.mainloop()
from src.colorpredicate import ColorPredicate hist_args = { 'color_space': 'hsv', 'ch_indexes': (0, 1, 2), 'bins': (8, 8, 8), 'target_sr': 1.0 } gauss_hist_args = { 't_amp': 1.0, 't_cov': 0.01, 'threshold': 0.1 } grass_color_predicate = ColorPredicate("grass", "../data/grass/images") grass_color_predicate.create_multidimensional_histogram(**hist_args) grass_color_predicate.create_gaussian_smoothed_histogram(**gauss_hist_args) grass_color_predicate.plot_gaussian_smoothed_histogram(save=True)
# import re # s = input('input > ') # matched = re.match(r'[A-Z]',s[0]) # # print(matched) # if matched: # print(s[0] + s) # else: # print(s[0].upper() + s[1:]) s = input('input > ') if s[0].islower(): s2 = s[0].upper() + s[1:] else: s2 = s * 2 print(s2)
import os import pickle from xbmcswift2.cache import Cache, TimedCache from unittest import TestCase from datetime import timedelta import time def remove(filename): try: os.remove(filename) except OSError: pass class TestCache(TestCase): def test_pickle(self): filename = '/tmp/testdict.pickle' remove(filename) cache = Cache(filename, file_format='pickle') cache['name'] = 'jon' cache.update({'answer': 42}) cache.close() cache2 = Cache(filename, file_format='pickle') self.assertEqual(cache, cache2) self.assertEqual(2, len(cache2.items())) self.assertTrue('name' in cache2.keys()) self.assertTrue('answer' in cache2.keys()) self.assertEqual('jon', cache2.pop('name')) self.assertEqual(42, cache2['answer']) remove(filename) def test_csv(self): filename = '/tmp/testdict.csv' remove(filename) cache = Cache(filename, file_format='csv') cache['name'] = 'jon' cache.update({'answer': '42'}) cache.close() cache2 = Cache(filename, file_format='csv') self.assertEqual(sorted(cache.items()), sorted(cache2.items())) self.assertEqual(2, len(cache2.items())) self.assertTrue('name' in cache2.keys()) self.assertTrue('answer' in cache2.keys()) self.assertEqual('jon', cache2.pop('name')) self.assertEqual('42', cache2['answer']) remove(filename) def test_json(self): filename = '/tmp/testdict.json' remove(filename) cache = Cache(filename, file_format='json') cache['name'] = 'jon' cache.update({'answer': '42'}) cache.close() cache2 = Cache(filename, file_format='json') self.assertEqual(sorted(cache.items()), sorted(cache2.items())) self.assertEqual(2, len(cache2.items())) self.assertTrue('name' in cache2.keys()) self.assertTrue('answer' in cache2.keys()) self.assertEqual('jon', cache2.pop('name')) self.assertEqual('42', cache2['answer']) remove(filename) class TestTimedCache(TestCase): def test_pickle(self): filename = '/tmp/testdict.pickle' remove(filename) cache = TimedCache(filename, file_format='pickle', ttl=timedelta(hours=1)) cache['name'] = 'jon' cache.update({'answer': 42}) cache.close() # Reopen cache2 = TimedCache(filename, file_format='pickle', ttl=timedelta(hours=1)) self.assertEqual(sorted(cache.items()), sorted(cache2.items())) # Reopen again but with a one second ttl which will be expired time.sleep(2) cache3 = TimedCache(filename, file_format='pickle', ttl=timedelta(seconds=1)) self.assertEqual([], sorted(cache3.items())) cache3.close() # Ensure the expired dict was synced cache4 = TimedCache(filename, file_format='pickle', ttl=timedelta(hours=1)) self.assertEqual(sorted(cache3.items()), sorted(cache4.items()))
import tkinter as tk import tkinter.ttk as ttk class FundingSourceFrame: def __init__(self, root): source_of_funding_frame = tk.Frame(root) source_of_funding_frame.pack(fill=tk.X, padx=5) source_of_funding_label = tk.Label(source_of_funding_frame, text='Фінансування', width=14, anchor=tk.W) source_of_funding_label.pack(side=tk.LEFT, padx=5) self.funding_value = tk.IntVar() source_of_funding1 = tk.Radiobutton(source_of_funding_frame, variable=self.funding_value, value=1, text='Кошти МБ', command=self.check) source_of_funding1.pack(side=tk.LEFT, fill=tk.X, padx=5) source_of_funding2 = tk.Radiobutton(source_of_funding_frame, variable=self.funding_value, value=2, text='Кошти СФ', command=self.check) source_of_funding2.pack(side=tk.LEFT, fill=tk.X, padx=5) source_of_funding3 = tk.Radiobutton(source_of_funding_frame, variable=self.funding_value, value=3, text='Інше', command=self.check) source_of_funding3.pack(side=tk.LEFT, padx=(5, 0)) self.source_of_funding_entry = ttk.Entry(source_of_funding_frame) self.funding_value.set(1) def check(self): if self.funding_value.get() == 3: self.source_of_funding_entry.pack(fill=tk.X, padx=(0, 5)) else: self.source_of_funding_entry.pack_forget() def get_funding_value(self): val = self.funding_value.get() if val == 1: return "кошти місцевого бюджету" elif val == 2: return 'кошти спеціального фонду' elif val == 3: return self.source_of_funding_entry.get() def set_funding_value(self, value): if value == 'кошти місцевого бюджету': self.funding_value.set(1) elif value == 'кошти спеціального фонду': self.funding_value.set(2) else: self.funding_value.set(3) self.source_of_funding_entry.delete(0, tk.END) self.source_of_funding_entry.insert(0, value)
class Slide(object): def __init__(self, title, content): self.title = title self.content = self.convert_line_breaks(content) def convert_line_breaks(self, text): return text.replace('\n', '<br>')
import scipy as sp from scipy import interpolate import txtreader as reader import math import numpy as np def induced_drag_accent(y): q = float(input("What is the dynamic pressure?")) files = input("what is your file?") data = reader.filereader(files) y_array = data[0] chord_array = data[1] Ai_array = data[2] Cl_array = data[3] ICd_array = data[4] Di_array_2 = ICd_array*chord_array*q f_Di_2 = sp.interpolate.interp1d(y_array, Di_array_2, kind="cubic", fill_value="extrapolate") return(f_Di_2(y)) def moment_coeffecient_accent(y): q = float(input("What is the dynamic pressure?")) files = input("what is your file?") data = reader.filereader(files) y_array = data[0] chord_array = data[1] Cm_array = data[5] M_array = Cm_array*q*(chord_array**2) f_Cm = sp.interpolate.interp1d(y_array, M_array, kind="cubic", fill_value="extrapolate") return(f_Cm(y))
#-*- coding: utf-8 -*- # mecVovkeejMatsyas import argparse import getpass import capture import protocol_parser as pparser import file_writer as fwriter def parse_arguments(): parser = argparse.ArgumentParser(description="capture tool") parser.add_argument("-u", "--user", type=str, help='ssh username (required)') parser.add_argument("-i", "--ip", type=str, help='ssh host ip (required)') parser.add_argument("-p", "--port", type=int, default=22, help='ssh port (required)') parser.add_argument("--lppath", type=str, default='.', help='path to save pcap file (local)') parser.add_argument("--rppath", type=str, default='/tmp/paramiko.pcap', help='path to save pcap file (remote. default /tmp/paramiko.pcap)') parser.add_argument("--mdpath", type=str, default='.', help='path to save md file') parser.add_argument("--pktcount", type=int, default=3, help='packet count (default 3)') parser.add_argument("--bpffileter", type=str, help="BPF Filter string") args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() password = getpass.getpass() #Download handler = capture.SSHHandler( host=args.host, port=args.port, user=args.user, password=password, save_path=args.rppath #Remote Pcap Path ) if args.bpffilter is None: handler.start_capture(iface="eth0", pktcount=args.pktcount) else: handler.start_capture(iface="eth0", pktcount=args.pktcount, bpf_filter=args.bpffilter) handler.download_pcap(args.lppath) #Parse http_parser = pparser.HTTPParser(args.lppath) parsed_obj = http_parser.parse() #Write to file mdwriter = fwriter.MarkDownWriter(parsed_obj) mdwriter.write(args.mdpath) #Close handler.close()
# # class Marks: # # def __init__(self,m1,m2,m3): # self.m1=m1 # self.m2=m2 # self.m3=m3 # def average(self): # return sum([self.m1,self.m2,self.m3])//3 # # # # class Smarks(Marks): # # def __init__(self,num,snum): # super().__init__(10,20,30) # self.num=num # self.snum=snum # print("Hello from child class") # # def sum(self): # # super().average() # # print(sum([self.num,self.snum])) # # # # shreejan=Marks(1,1,1) # # print(shreejan.m3) # shree=Smarks(5,5) # shree.sum() # print(shree.m3) # # print(shree.average()) class Pycharm: def execute(self): print("Compiling") class Laptop: def coding(self,ide): ide.execute() ide=Pycharm() l=Laptop() l.coding(ide)
class SubscriptionMgr(object): def __init__(self): self.__pendings = dict() self.__doings = dict() def add_subscription(self, topic, offset): self.__pendings[topic] = offset self.__doings.pop(topic, None) def to_doing(self, topic, offset = None): if offset == None: offset = self.__pendings.get(topic) self.__doings[topic] = offset self.__pendings.pop(topic, None) def to_pendings(self): for topic, offset in self.__doings.items(): self.to_pending(topic, offset) def to_pending(self, topic, offset): self.add_subscription(topic, offset) def delete_subscription(self, topic): self.__pendings.pop(topic, None) self.__doings.pop(topic, None) def clear(self): self.__pendings.clear() self.__doings.clear() def has_subscribed(self, topic): return topic in self.__pendings or topic in self.__doings def get_all_pendings(self): return set(self.__pendings.items()) def get_all_doings(self): return set(self.__doings.items()) def get_doing(self, topic): return self.__doings.get(topic, -1)
import asyncio import unittest from decimal import Decimal from test.hummingbot.connector.gateway.clob_spot.data_sources.injective.injective_mock_utils import InjectiveClientMock from typing import Awaitable from unittest.mock import MagicMock from hummingbot.client.config.client_config_map import ClientConfigMap from hummingbot.client.config.config_helpers import ClientConfigAdapter from hummingbot.connector.exchange_base import ExchangeBase from hummingbot.connector.gateway.clob_spot.data_sources.injective.injective_api_data_source import ( InjectiveAPIDataSource, ) from hummingbot.connector.gateway.clob_spot.gateway_clob_api_order_book_data_source import ( GatewayCLOBSPOTAPIOrderBookDataSource, ) from hummingbot.connector.gateway.gateway_order_tracker import GatewayOrderTracker from hummingbot.connector.utils import combine_to_hb_trading_pair from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage, OrderBookMessageType from hummingbot.core.data_type.trade_fee import AddedToCostTradeFee, TokenAmount class MockExchange(ExchangeBase): pass class GatewayCLOBSPOTAPIOrderBookDataSourceTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop = asyncio.get_event_loop() cls.base = "COIN" cls.quote = "ALPHA" cls.trading_pair = combine_to_hb_trading_pair(base=cls.base, quote=cls.quote) cls.sub_account_id = "someSubAccountId" def setUp(self) -> None: super().setUp() self.listening_tasks = [] self.initial_timestamp = 1669100347689 self.injective_async_client_mock = InjectiveClientMock( initial_timestamp=self.initial_timestamp, sub_account_id=self.sub_account_id, base=self.base, quote=self.quote, ) self.injective_async_client_mock.start() client_config_map = ClientConfigAdapter(hb_config=ClientConfigMap()) self.api_data_source = InjectiveAPIDataSource( trading_pairs=[self.trading_pair], connector_spec={ "chain": "someChain", "network": "mainnet", "wallet_address": self.sub_account_id, }, client_config_map=client_config_map, ) self.connector = MockExchange(client_config_map=client_config_map) self.tracker = GatewayOrderTracker(connector=self.connector) self.api_data_source.gateway_order_tracker = self.tracker self.ob_data_source = GatewayCLOBSPOTAPIOrderBookDataSource( trading_pairs=[self.trading_pair], api_data_source=self.api_data_source ) self.async_run_with_timeout(coro=self.api_data_source.start()) def tearDown(self) -> None: self.injective_async_client_mock.stop() self.async_run_with_timeout(coro=self.api_data_source.stop()) for task in self.listening_tasks: task.cancel() super().tearDown() @staticmethod def async_run_with_timeout(coro: Awaitable, timeout: float = 1): ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coro, timeout)) return ret def test_get_new_order_book_successful(self): self.injective_async_client_mock.configure_orderbook_snapshot( timestamp=self.initial_timestamp, bids=[(9, 1), (8, 2)], asks=[(11, 3)] ) order_book: OrderBook = self.async_run_with_timeout( self.ob_data_source.get_new_order_book(self.trading_pair) ) self.assertEqual(self.initial_timestamp * 1e3, order_book.snapshot_uid) bids = list(order_book.bid_entries()) asks = list(order_book.ask_entries()) self.assertEqual(2, len(bids)) self.assertEqual(9, bids[0].price) self.assertEqual(1, bids[0].amount) self.assertEqual(1, len(asks)) self.assertEqual(11, asks[0].price) self.assertEqual(3, asks[0].amount) def test_listen_for_trades_cancelled_when_listening(self): mock_queue = MagicMock() mock_queue.get.side_effect = asyncio.CancelledError() self.ob_data_source._message_queue[self.ob_data_source._trade_messages_queue_key] = mock_queue with self.assertRaises(asyncio.CancelledError): listening_task = self.ev_loop.create_task( self.ob_data_source.listen_for_trades(self.ev_loop, asyncio.Queue()) ) self.listening_tasks.append(listening_task) self.async_run_with_timeout(listening_task) def test_listen_for_trades_successful(self): target_price = Decimal("1.157") target_size = Decimal("0.001") target_maker_fee = Decimal("0.0001157") target_taker_fee = Decimal("0.00024") target_maker_fee = AddedToCostTradeFee(flat_fees=[TokenAmount(token=self.quote, amount=Decimal("0.0001157"))]) target_taker_fee = AddedToCostTradeFee(flat_fees=[TokenAmount(token=self.quote, amount=Decimal("0.00024"))]) target_trade_id = "19889401_someTradeId" def configure_trade(): self.injective_async_client_mock.configure_trade_stream_event( timestamp=self.initial_timestamp, price=target_price, size=target_size, maker_fee=target_maker_fee, taker_fee=target_taker_fee, taker_trade_id=target_trade_id, ) msg_queue: asyncio.Queue = asyncio.Queue() subs_listening_task = self.ev_loop.create_task(coro=self.ob_data_source.listen_for_subscriptions()) self.listening_tasks.append(subs_listening_task) trades_listening_task = self.ev_loop.create_task( coro=self.ob_data_source.listen_for_trades(self.ev_loop, msg_queue) ) self.listening_tasks.append(trades_listening_task) self.ev_loop.call_soon(callback=configure_trade) self.injective_async_client_mock.run_until_all_items_delivered() msg: OrderBookMessage = self.async_run_with_timeout(msg_queue.get()) self.assertTrue(msg_queue.empty()) # only the taker update was forwarded by the ob data source self.assertEqual(OrderBookMessageType.TRADE, msg.type) self.assertEqual(target_trade_id, msg.trade_id) self.assertEqual(self.initial_timestamp, msg.timestamp) def test_listen_for_order_book_snapshots_cancelled_when_fetching_snapshot(self): mock_queue = MagicMock() mock_queue.get.side_effect = asyncio.CancelledError() self.ob_data_source._message_queue[self.ob_data_source._snapshot_messages_queue_key] = mock_queue with self.assertRaises(asyncio.CancelledError): self.async_run_with_timeout( self.ob_data_source.listen_for_order_book_snapshots(self.ev_loop, asyncio.Queue()) ) def test_listen_for_order_book_snapshots_successful(self): def configure_snapshot(): self.injective_async_client_mock.configure_orderbook_snapshot_stream_event( timestamp=self.initial_timestamp, bids=[(9, 1), (8, 2)], asks=[(11, 3)] ) subs_listening_task = self.ev_loop.create_task(coro=self.ob_data_source.listen_for_subscriptions()) self.listening_tasks.append(subs_listening_task) msg_queue: asyncio.Queue = asyncio.Queue() listening_task = self.ev_loop.create_task( self.ob_data_source.listen_for_order_book_snapshots(self.ev_loop, msg_queue) ) self.listening_tasks.append(listening_task) self.ev_loop.call_soon(callback=configure_snapshot) snapshot_msg: OrderBookMessage = self.async_run_with_timeout(msg_queue.get()) self.assertEqual(OrderBookMessageType.SNAPSHOT, snapshot_msg.type) self.assertEqual(self.initial_timestamp, snapshot_msg.timestamp) self.assertEqual(2, len(snapshot_msg.bids)) self.assertEqual(9, snapshot_msg.bids[0].price) self.assertEqual(1, snapshot_msg.bids[0].amount) self.assertEqual(1, len(snapshot_msg.asks)) self.assertEqual(11, snapshot_msg.asks[0].price) self.assertEqual(3, snapshot_msg.asks[0].amount)
from collections import deque water_quantity = int(input()) q = deque() while True: command = input() if command == 'Start': break q.append(command) while True: command = input().split() if command[0] == 'End': print(f'{water_quantity} liters left') break elif command[0] == 'refill': water_quantity += int(command[1]) elif water_quantity >= int(command[0]): water_quantity -= int(command[0]) print(f'{q.popleft()} got water') elif water_quantity < int(command[0]): print(f'{q.popleft()} must wait')