content
stringlengths
5
1.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. # # 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 re...
import discord import wikipedia from tkn import * language = "en" client = discord.Client() @client.event async def on_ready(): print("Bot is ready") print(client.user.name) print(client.user.id) @client.event async def on_server_join(server): await client.send_message(server.default_channel, ...
from argparse import ArgumentParser import asyncio from asyncio import Event from contextlib import ExitStack from logging import getLogger from pathlib import Path import re from signal import SIGTERM, SIGINT import sys from tempfile import TemporaryDirectory from .aggregate import aggregate_s3_logs from .s3_client i...
def graph_update(street_network,previous_graph,taget_transport_graph,mode,specific_mode): from scipy.spatial import KDTree, cKDTree previous_graph.add_nodes_from(taget_transport_graph.nodes(data=True)) previous_graph.add_edges_from(taget_transport_graph.edges(data=True)) street_nodes=[] for node,dat...
from ctypes import * from ctypes.wintypes import * class LIST_ENTRY(Structure): pass class LDR_DATA_TABLE_ENTRY(Structure): pass class LDR_LIST_ENTRY_U(Union): _fields_ = [ ("list", POINTER(LIST_ENTRY)), ("entry", POINTER(LDR_DATA_TABLE_ENTRY)), ] LIST_ENTRY._fields_ = [ ("Flink...
#!/usr/bin/env python """ Handler of timestamps which operation type is insert op=insert """ __author__ = "Yaroslav Litvinov" __copyright__ = "Copyright 2016, Rackspace Inc." __email__ = "yaroslav.litvinov@rackspace.com" ENCODE_ESCAPE = 1 ENCODE_ONLY = 0 NO_ENCODE_NO_ESCAPE = None def format_string_insert_query(tab...
from field.fq import Fq from field.fq2 import Fq2 from field.fq6 import Fq6 class G2: field_modulus = None non_residue = None def __init__(self, val): if not self.field_modulus: raise AttributeError("Field modulus is not set") if not self.non_residue: raise Attribu...
# -*- coding: utf-8 -*- """Testcases for cssutils.util""" from __future__ import with_statement import cgi from email import message_from_string, message_from_file import StringIO import sys import urllib2 import xml.dom try: import mock except ImportError: mock = None print "install mock library to run ...
from django.contrib.auth import get_user_model from factory import Faker, Sequence, LazyAttribute from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): first_name = Faker("first_name") last_name = Faker("last_name") username = Sequence(lambda i: f"test-user-{i}") email =...
import celery import datetime import time from celery import task from celery.execute import send_task from celery.signals import celeryd_init from celery.signals import celeryd_after_setup from celery.utils.log import get_task_logger from croniter import croniter from datetime import datetime from datetime import t...
# Copyright 2020 The Magenta Authors. # Modifications Copyright 2020 Jack Spencer Smith. # # 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 # #...
# -*- coding: utf-8 -*- # # @Author: Florian Briegel (briegel@mpia.de # @Date: 2021-07-06 # @Filename: __init__.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) from __future__ import annotations import asyncio from contextlib import suppress from clu.actor import AMQPActor from cluplus...
# -*- coding: utf-8 -*- """ Created on Tue Dec 22 14:56:13 2015 The Huber_braun neuronal model function @author: porio """ import numpy as np from numba import jit,float64 # PARAMETERS -- Must be defined first to allow numba compile # Node parameters # Any of them can be redefined as a vector of length nnodes gd = 2....
# -*- coding: utf-8 -*- """ -------------------------------------- @File : goods.py @Author : maixiaochai @Email : maixiaochai@outlook.com @Created on : 2020/5/4 18:26 -------------------------------------- """ from flask import request from flask_restful.reqparse import RequestParser from flask_restful...
class IsrealResponse(object): def __init__(self, data, status="success", http_status_code=200, http_extra_headers=None): self.data = data self.status = status self.http_status_code = http_status_code self.http_extra_headers = http_extra_headers def dictify(self): return ...
#!/usr/bin/env python3 import dns.exception import dns.flags import dns.message import dns.rcode import dns.rdataclass import dns.rdatatype import dns.resolver import json import math import os import pickle import redis import socket import socketserver import struct import sys import threading import time allowed_r...
import logging from pylops.basicoperators import Regression logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING) def LinearRegression(taxis, dtype='float64'): r"""Linear regression. Creates an operator that applies linear regression to a set of points. Values along the t-axis ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 Radim Rehurek <me@radimrehurek.com> # # This code is distributed under the terms and conditions # from the MIT License (MIT). import io import os from setuptools import setup, find_packages def read(fname): return io.open(os.path.join(os.path....
from .Scaling import * from .EncodeCategoricalVariable import * from .SplitDataset import * from .GlobalPreprocessing import *
from freezegun import freeze_time from pyramid.testing import DummyRequest from keyloop.security import KeyLoopAuthenticationPolicy def test_remember_no_realm(): auth_p = KeyLoopAuthenticationPolicy("sekret", max_age=30) req = DummyRequest() assert auth_p.remember(req, "principal") == [] def test_forge...
# login page save new users # home page -> user content page, save user content # import os from flask import Flask from flask import render_template from flask import request from flask import session from qaviton.utils.databases.sqlite import DataBase from lessons.flask_lessons.flask_examples import DBCommands app =...
""" Copyright (C) 2021 SE Slash - All Rights Reserved You may use, distribute and modify this code under the terms of the MIT license. You should have received a copy of the MIT license with this file. If not, please write to: secheaper@gmail.com """ from src.modules.formatter import formatSearchQuery, formatTitle d...
import json import sys import codecs # read parameters from files with open('emission.txt', mode='r') as f: em = json.load(f) with open('transition.txt', mode='r') as f: tr = json.load(f) with open('word_tag.txt', mode='r') as f: w_t = json.load(f) tags = set(tr['start']) words = set(w_t) def prob_emi...
#!/usr/bin/env python import cv2 as cv import numpy as np from umucv.stream import autoStream def nada(v): pass cv.namedWindow("binary") cv.createTrackbar("umbral", "binary", 128, 255, nada) for key, frame in autoStream(): #print(frame) gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #print(gray) ...
from .betting import Betting from .account import Account
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option)...
from pyomo.environ import * from pyomo.dae import * from math import pi import numpy as np import matplotlib.pyplot as plt from datetime import datetime from adaptiveMesh import adaptiveMeshFunc for iter in range(4): warmStart = 1 cubicSplineExtrapU0 = 1 # myMethod = 'ORTHO'; nfe = 20; ncp = 11 ...
"""Testing utilities.""" import numpy as np try: from uncertainties import unumpy except ImportError: # pragma: nocover unumpy = None def allclose(a, b, use_covariance=False, **kw): """Return `True` if a and be are close. Like np.allclose, but first tries a strict equality test, and also...
import pandas class ExtFilesHandler: def __init__(self): pass def get_passwords_from_file(self, file, type_csv): data = pandas.read_csv(file) websites_list = [] usernames_list = [] pass_list = [] tags_list = [] if type_csv == 'custom': webs...
import mysql.connector title=input("Enter Title:") dec=input("ENter Dec:") try: conn = mysql.connector.connect(host='localhost',database='djangoapp',user='root',password='') mycursor=conn.cursor() mycursor.execute("UPDATE todos SET descs = '"+dec+"' WHERE title = '"+title+"'") conn.commit() print("update...
import pickle import wx from direct.showbase.PythonUtil import getBase as get_base class DragDropTarget(wx.DropTarget): def __init__(self, validate_fn, drop_fn): super().__init__() self.validate_fn = validate_fn self.drop_fn = drop_fn do = wx.CustomDataObject('data') se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Yikai Wang """ import json import random def load_json(dir): """ load json file :param dir: path we save the data :return: data as a list. """ data = [] with open(dir, 'r') as f: while True: a = f.readline() ...
import random def task1_a1(): """ Write a program that prompts the user to enter a real number, computers the square root of the number and prints it out in two decimal places. """ x1 = float(input('Enter a real number: ')) print(f'{x1**0.5:.2f}') def task1_a2(): """ Write a prog...
import numpy as np def L2(v, *args): """Returns the L2 norm of a vector v INPUTS ======= v: list Vector of which the L2 norm to be calculated *arg: list, optional Weight vector RETURNS ======== L2_norm: float float unless len(v) != len(ar...
import cv2 from pathlib import Path face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml') vc = cv2.VideoCapture(0, cv2.CAP_DSHOW) print("Enter your name :") fold = input() count = 1 def saveimage(img, username, imgId): Path("images/{}".format(username)).mkdir(parents ...
""" mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence Original game "minecraft" by Mojang Studios (www.m...
# Copyright (C) 2015 Philipp Baumgaertel # All rights reserved. # # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE.txt file for details. from math import fabs import unittest from skgpuppy.Covariance import GaussianCovariance, SPGPCovariance, Covariance, Dot, Peri...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ An example of linear regression """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm import statsmodels.formula.api as smf #Some made up data minutes_played=np.array([120,452,185,708,340,561]) goals_scored=np.array([...
from chass.get_variable import get_variable # This function takes the preprocessed file as input # It returns a list of triples in which the first element gives the function name, # second element gives the starting line number and the third element gives the ending line number def identify_functions(file) : file =...
import cv2 from PIL import Image import pytesseract import os import shutil import VideoParse as vp from selenium import webdriver # Url to video def process_url(url, videoPath): # download vp.downloadYt(url, videoPath) transcript = process_video(videoPath) # delete video os.remove(videoPath) ...
# Copyright 2011 VMware, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.utils.http import urlencode from django.conf import settings from smsgateway.backends.base import SMSBackend class SpryngBackend(SMSBackend): def get_send_url(self, sms_request, account_dict): # Encode message msg = sms_requ...
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import numpy as np import gensim.downloader as api class WordEmbedding(nn.Module): def __init__(self, text_encoder_type, pooling_strat, dictionary): """Embeds tokenised sequence into a fixed length ...
from machine import Pin, SPI import st7789 spi = SPI(2, baudrate=30000000, polarity=1, phase=1, sck=Pin(18), mosi=Pin(19), miso=Pin(14)) display = st7789.ST7789( spi, 135, 240, reset = Pin(23, Pin.OUT), cs = Pin(5, Pin.OUT), dc = Pin(16, Pin.OUT), backlight = Pin(4, Pin.OUT), ...
########################################################################## # mriWorks - Copyright (C) IRMAGE/INSERM, 2020 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # https://cecill.info/licences/Licence_CeCILL_V2-en.html # for detai...
from django.db import models class Course(models.Model): LENGTH = ( ('H', 'Half Year'), ('Y', 'Full Year') ) CAMPUS = ( ('UTSG', 'St. George'), ('UTM', 'Mississauga'), ('UTSC', 'Scarborough') ) BREADTH = ( (1, 'Creative and Cultural Representations...
import json # for loading the word_list import re def writeHook(num, hook): # writes the hook return f"- num: {num}\n link: {hook}\n" def createPattern(num): # return a pattern conversion_list = [] # aids in creating the final_pattern i = 0 while i < ...
import datetime from fabric import task PRODUCTION_CODE_DIR = '/www/apache/domains/www.toidupank.ee/django-projects/live-osale/foodbank-campaign/src' # for FreeBSD compatibility SHELL = '/bin/sh -c' @task def newcampaign(c, old_start_date, new_start_date): # verify that arguments are valid dates datetime.d...
class ApplicationStateListener(object): order = None def on_start(self, application): pass def on_stop(self, application): pass
#!/usr/bin/env python ''' Code adapted from https://blog.checkpoint.com/wp-content/uploads/2015/07/matsnu-malwareid-technical-brief.pdf ''' import os import sys import datetime import string def is_hex(s): if not s.startswith('0x'): return False s = s[2:] hex_digits = set(string.hexdigits) #...
#!/usr/bin/env python # encoding: utf-8 # this is list of Thai stop words drawn originally from Apache Lucene # ref: originally THAI_STOP_WORDS = frozenset([ u'ไว้', u'ไม่', u'ไป', u'ได้', u'ให้', u'ใน', u'โดย', u'แห่ง', u'แล้ว', u'และ', u'แรก', u'แบบ', u'แต่', u'เอง', u'เห็น', u'เลย', u'เริ่ม', u'เรา', u'...
# This file was *autogenerated* from the file test.sage from sage.all_cmdline import * # import sage library magma.load("primitivize.m") sigma = magma('[Sym(6) | [3, 5, 4, 6, 2, 1], [2, 3, 1, 5, 6, 4], [5, 4, 3, 2, 1, 6]]') sigma_prim = magma.Primitivize(sigma) print(sigma_prim)
# -*- coding: utf-8 -*- import re import textwrap from . import _unittest as unittest from datatest.difference import BaseDifference from datatest.difference import Missing from datatest.difference import Extra from datatest.difference import Invalid from datatest.difference import Deviation from datatest.difference i...
""" This file is about how to load data from sklearn. Library : sklearn Moduale : datasets Class : load_digits Object : digits_data data : Digits Data """ # Import important libraries from sklearn.datasets import load_digits import matplotlib.pyplot as plt # Object of load_digits digits_data = load_digits() ...
from engine.downloadTorrent import DownloadTorrent import unittest import time import shutil import os class TestDownloadTorrent(unittest.TestCase): def setUp(self): self.first_info_hash = 'b26c81363ac1a236765385a702aec107a49581b5' # Ubuntu 20.04 ISO image self.first_save_path = 'tmp' self...
from nonogram.solution import Solution from common.matrix import Matrix from nonogram.solver.layout_index import LayoutIndex, SolutionCell class SolutionStep(object): ROW = 0 COL = 1 def __init__(self, nonogram): self._uid = 1000 self._idToIndex = {} self._nonogram = nonogram ...
# Generated by Django 2.2.17 on 2021-11-12 14:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("torchbox", "0139_homepage_featured_posts_and_hero_image"), ] operations = [ migrations.AlterField( ...
# code adpated from https://subluminal.wordpress.com/2008/07/31/running-standard-deviations/#more-15 import math n=0 mean=0 pwrSumAvg=0 stdDev=0 list_of_values = [3.0, 5.0, 8.0, 10.0, 4.0, 8.0] for x in list_of_values: n += 1 mean += (x - mean) / n pwrSumAvg += ( x * x - pwrSumAvg) / n if n - 1 > 0: ...
import sst import os import ConfigParser def connect(name, c0, port0, c1, port1, latency): link = sst.Link(name) link.connect( (c0, port0, latency), (c1, port1, latency) ) return link class Config: def __init__(self, cfgFile, **kwargs): cp = ConfigParser.ConfigParser() if not cp.re...
#!/usr/bin/env seiscomp-python ############################################################################ # Copyright (C) by GFZ Potsdam # # # # You can redistribute and/or modify this program unde...
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a ...
from unittest import TestCase from drawable2svg.VectorDrawable2Svg import convert_vector_drawable_stream class VectorDrawable2SvgTestCase(TestCase): def test_convert_xml_stream_to_svg(self): with open('data/ic_launcher.xml', 'rb') as icon_xml: with open('data/colors.xml', 'rb') as colors_x...
import os from setuptools import setup about = {} here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'mingw_ldd', '__version__.py'), 'r', encoding='utf-8') as f: exec(f.read(), about) setup( name=about['__title__'], version=about['__version__'], description=about['__descri...
import os import sys import random from unittest import TestCase sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") sys.path.append(os.path.dirname( os.path.abspath(__file__)) + "/../PathPlanning/RRT") try: from PathPlanning.RRT import rrt_with_sobol_sampler as m except ImportError: rais...
#! /usr/bin/env python # Brokers communication between Dakota and SWASH through files. # # Arguments: # $1 is 'params.in' from Dakota # $2 is 'results.out' returned to Dakota import sys import os import re import shutil from subprocess import call def read(output_file, variable=None): """Read data from a MAT...
# vim: set encoding=utf-8 # pylint: disable=wrong-import-position """ Main view (wttr.in) implementation. The module is a wrapper for the modified Wego program. """ import sys import re from gevent.subprocess import Popen, PIPE sys.path.insert(0, "..") from translations import get_message, SUPPORTED_LANGS from glob...
"""Custom exceptions.""" class JWTExpiredException(Exception): """Raised when JWT token expires."""
import warnings class Ebolve: """" EBOLVE (EDWARDS-BELL-OHLSON aLghorithmic Value Engine""" def __init__(self, input): self.eps1 = input['eps1'] # forecasted eps Year 1 self.eps2 = input['eps2'] # forecasted eps Year 2, not neg self.ltg = input['ltg'] ...
# GridGain Community Edition Licensing # Copyright 2019 GridGain Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause # Restriction; you may not use this file except in compliance with the License. You may obtain a # copy of th...
# Demo Python Booleans - Functions can Return a Boolean ''' Functions can Return a Boolean You can execute code based on the Boolean answer of a function: ''' # Print "YES!" if the function returns True, otherwise print "NO!": def myFunction() : return True if myFunction(): print("YES!") else: print("NO!")
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under th...
''' Created on 1.12.2016 @author: Darren '''''' Given an integer array nums, find the sum of the elements between indices i and j (i &le; j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 up...
from positional_list import PositionalList class FavoritesList: class _Item: __slots__ = '_value', '_count' def __init__(self, e): self._value = e self._count = 0 def _find_position(self, e): walk = self._data.first() while walk is not None and walk.el...
from docs_conf.conf import * # flake8: noqa
import json import logging import os import sys from json import JSONDecodeError import dropbox import requests logger = logging.getLogger('dropbox_backup') logger.setLevel(logging.INFO) log_console = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') log_c...
import requests, html, json, tweepy # Get credits from a local file with open("creds.json") as f: creds = json.load(f) # Start up tweepy consumer_key = creds["consumer_key"] consumer_secret = creds["consumer_secret"] access_token = creds["access_token"] access_token_secret = creds["access_token_secret"] auth = t...
from cwm_worker_operator import deployer from cwm_worker_operator import common from cwm_worker_operator import config from .common import get_volume_config_ssl_keys from .test_domains_config import CERTIFICATE_KEY, CERTIFICATE_PEM, INTERMEDIATE_CERTIFICATES def assert_domain_deployer_metrics(deployer_metrics, obser...
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """A mixin for objects that can be cloned""" import itertools from ggrc.services import common class Clonable(object): """Clonable mixin""" __lazy_init__ = True CLONEABLE_CHILDREN = {} _operati...
import ssl import pytest import trustme @pytest.fixture(scope="session") def ca(): return trustme.CA() @pytest.fixture(scope="session") def localhost_cert(ca): return ca.issue_cert("localhost") @pytest.fixture(scope="session") def httpserver_ssl_context(localhost_cert): context = ssl.SSLContext(ssl.P...
# Generated by Django 3.2.7 on 2021-10-09 05:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tienda_mascotas', '0006_remove_race_rt'), ] operations = [ migrations.DeleteModel( name='race', ), ]
# Copyright (c) 2018 The Regents of the University of Michigan # and the University of Pennsylvania # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
#!/bin/bash/python3 import numpy as np from scipy.integrate import odeint from tikzpy import TikzPicture """ Plots the Lorenz dynamical system. Note: This might not work for some users because of TeX's buffer size parameter, which is a fixed quantity that tells TeX when to quit a process (even if there are ...
from collections import namedtuple import numpy import numpy as np import cv2 # Based on https://github.com/pyxploiter/Barcode-Detection-and-Decoding Region = namedtuple('Region', 'image rect box percent area shape box_percent') debug = False def detect_regions_multipage(images): results = [] for image in ...
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from ..models import CollectJob from ..serializers import CollectJobSerializer class CollectJobList(generics.ListCreateAPIView): queryset = CollectJob.objects.all() serializer_class = CollectJobSerializer fi...
import click import supercheckers as sc @click.command() def main(): player_1 = sc.ConsolePlayer(sc.Team.ONE) player_2 = sc.ConsolePlayer(sc.Team.TWO) state = sc.GameState(player_1, player_2, sc.Journal(sc.Board())) verifier = sc.Verifier(sc.all_rules()) with sc.Game(state, verifier) as game: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: if not root: return True inorder =...
# Copyright 2021 F5 Networks Inc. # # 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 writi...
from suika.core.db import SessionLocal from suika.models.product import Product from suika.models.price import Price db = SessionLocal() products = db.query(Product).join(Price).all() for product in products: # Get the latest price for the product current_price = product.prices[-1] product.current_price ...
import time import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm from pydrake.all import PiecewisePolynomial from qsim.simulator import (QuasistaticSimulator, QuasistaticSimParameters) from qsim.system import (cpp_params_from_py_params) from quasistatic_simulator.examples.setup_simulation_diagram ...
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.binding.datatypes as xs import pyxb.binding.basis import pyxb.utils.domutils import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <schema xmlns...
import unittest from ddt import ddt, data, unpack from typing import List from merge_two_sorted_lists import Solution, ListNode @ddt class Tester(unittest.TestCase): def setUp(self): self.s = Solution() @data( [[], [], []], [[1], [], [1]], [[1,2,3], [], [1,2,3]], [[], [...
from binaryninja import LowLevelILLabel, LowLevelILFlagCondition from binaryninja.architecture import Architecture, ArchitectureHook from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM from capstone.arm64 import * # # http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0473e/CJAJIHAD.html # # Suffix Fla...
# -*- coding: utf-8 -*- ############################################################################# # # Copyright © Dragon Dollar Limited # contact: contact@dragondollar.com # # This software is a collection of webservices designed to provide a secure # and scalable framework to build e-commerce websites. # # This s...
import os import sys sys.path.append(os.path.dirname(__file__)) import argparse import yaml import pickle from rls_policies import RandomPolicy, RLSOptimalPolicy, RLSFixedOnePolicy, DQNPolicy, RLSOptimalDiscretePolicy from utils import make_env, read_config def main(): parser = argparse.ArgumentParser() parse...
# (C) 2021 GoodData Corporation def _tables_to_dict(tables): return dict([(t.table_name, t) for t in tables])
import random from kf_lib.actors import fighter_factory from kf_lib.utils import rnd, rndint from ._base_encounter import BaseEncounter from ._utils import get_escape_chance, check_scary_fight, try_escape CH_ENEMY_REPENTS = 0.5 NUM_AMBUSH_THUGS = (2, 4) REP_REFORM_ENEMY = 10 class Ambush(BaseEncounter): def __...
import unittest2 import check_graphite class CheckGraphiteDataEvaluationTests(unittest2.TestCase): def test_no_exit_without_nones(self): self.assertEquals(check_graphite.check_max_none_values([5, 10, 20], 50, False),None) def test_no_exit_some_nones(self): self.assertEquals(check_graphite.che...
# -*- encoding=utf-8 -*- # The bulk() api accepts index, create, delete, and update actions. # Use the _op_type field to specify an action (_op_type defaults to index): from elasticsearch import Elasticsearch client = Elasticsearch("localhost:9200") print client index = "forum" type = "article" print client.indice...
from rrutil import * send_gdb('b breakpoint') expect_gdb('Breakpoint 1') send_gdb('c') expect_gdb('Breakpoint 1') send_gdb('watch -l *p2') expect_gdb('Hardware watchpoint 2') send_gdb('c') expect_gdb('watchpoint 2') send_gdb('delete 2') send_gdb('c') expect_gdb('Breakpoint 1') send_gdb('watch -l *p4') expect_gdb('Ha...
# CTCI E2.6: Implement a function to check if a linked list is palindrome. from data_structures import linkedList as ll def isPalindrome(list:ll.List) -> bool: s:ll.Node = list.head f:ll.Node = list.head if s == None or s.next == None: return True stack = [] count = 1 while f != None...