content
stringlengths
5
1.05M
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
""" Dictionary custom sorting. Source: https://github.com/laowantong/customsort """ import unicodedata from collections import OrderedDict def to_ascii(s): return unicodedata.normalize("NFD", s.lower()).encode("ASCII", "ignore") def make_custom_sort(orders): orders = [{k: -i for (i, k) in enumerate(reverse...
import subprocess from contextlib import contextmanager from tempfile import NamedTemporaryFile from time import sleep import requests from throttle_client import Client # Endpoint of throttle server started by cargo main BASE_URL = "http://localhost:8000" @contextmanager def cargo_main(cfg: str): ...
# Lab 12 RNN import sys import torch import torch.nn as nn from torch.autograd import Variable torch.manual_seed(777) # reproducibility # 0 1 2 3 4 idx2char = ['h', 'i', 'e', 'l', 'o'] # Teach hihell -> ihello x_data = [0, 1, 0, 2, 3, 3] # hihell one_hot_lookup = [[1, 0, 0, 0, 0], # 0 ...
from hujan_ui.installers.models import ConfigMAAS from requests_oauthlib import OAuth1Session from .exceptions import MAASError class MAAS: ok = list(range(200, 205)) fail = list(range(400, 500)) config = None def __init__(self): self.config = ConfigMAAS.objects.first() if not self.co...
# prune_topojson_attrs.py # # For all 'geometries' in the input TopoJSON, prune all 'properties' # *except* the HISPANIC_PCT_2010 property, and write out the resulting # TopoJSON object. # Having done this, the result must be geometrically simplified # (a.k.a. 'compressed). The mechanism to do this wasn't documented ...
from django.urls import reverse from django.contrib.auth.models import User from rest_framework import serializers, status from rest_framework.test import APITestCase from .models import Region, Location, Order from v1.account.models import Account from .serializers import OrderSerializer, RegionSerializer class Region...
""" Usage: negbio_pipeline normalize [options] --output=<directory> <file> ... Options: --output=<directory> Specify the output directory. --suffix=<suffix> Append an additional SUFFIX to file names. [default: .normalized.xml] --verbose Print more information about progress. """ ...
# coding: utf-8 # Using a LSTM single model to text various cleaning steps and impact on score. # # Controls: # - CNN single model # - maxlen: 65 # - min occurance vocab: 5 # - glove.6B.100D # - epochs: 2 # - cv: 3 # - max features 20000 model_name = 'grid_benchmark' import os import logging logging.basicConfig(fi...
import torch import torch.nn as nn from torch.nn.utils import weight_norm import torch.nn.functional as F class Chomp1d(nn.Module): """ What is this for?? This simply truncates chomp_size dots from the end of the sequence to make it the original length after Conv1d with """ def __init__(self, ...
from __future__ import absolute_import import copy from crispy_forms.utils import TEMPLATE_PACK from django import forms from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied, ObjectDoesNotExist from django.db import models from django.forms.models import modelf...
{ "targets": [ { "target_name": "audio", 'conditions': [ ['OS=="win"', { "sources": ["audio-napi.cc"], "cflags" : [ "-lole32", "-loleaut32"] }], ['OS=="linux"', { "sources": ["audio-napi_dummy.cc"] }], ['OS=="mac"', { ...
# -*- coding=utf-8 -*- import time class TimeIt(object): ''' 程序运行的消耗时间统计 Args: name(str): 指定代码段的功能含义,可不指定 unit(str): 计时单位,包括 秒(s)与毫秒(ms) no_print(bool): 指定是否打印计时 ''' def __init__(self, name=None, unit='s', no_print=False): self.start_time = None self.restart_t...
# HackerRank: Compare the Triplets (Solution) # https://www.hackerrank.com/challenges/compare-the-triplets/problem def compareTriplets(a, b): a_points = 0 b_points = 0 for i in range(3): if a[i] > b[i]: a_points += 1 elif a[i] < b[i]: b_points += 1 return a_points, b_points
""" Preprocess Sklearn WIR nodes to enable DAG extraction """ from ..instrumentation.dag_node import DagNodeIdentifier from ..utils import traverse_graph_and_process_nodes class SklearnDagPostprocessor: """ Preprocess Sklearn WIR nodes to enable DAG extraction """ # pylint: disable=too-few-public-met...
from pymongo import MongoClient import pandas as pd from sanic.log import logger from config import * from bson.objectid import ObjectId import copy import json async def save_csv_to_mongo(config, csv_file, config_id): client = MongoClient(config.MONGO_HOST, config.MONGO_PORT) db=client.exago if config_...
from src.configurations.config import WordModelConfiguration from .wic_dataset import WicProcessor from src.utils import utils from src.dataset.dataset import * from src.modules.contextual_embedder import ContextualEmbedder import numpy as np import torch from torch import nn from torch.nn import functional as F def...
import socket from threading import Thread status = { 200: "200 OK", 404: "404 NOT FOUND", 401: "401 Unauthorized" } def mkHeader(header): return f"\n\r{header}\n\r" class HTTPServer(object): def __init__(self,callback, ip="0.0.0.0", port=8088): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
default_app_config = 'www.apps.WwwAppConfig'
def find_pairs_with_given_difference(arr, k): intermediate = list() # A: use 2 for loops to find those triplet, and put them in a 2D array for index, element in enumerate(arr): for other_index, other_elem in enumerate(arr): if index != other_index: if element - other_elem...
# Estrutura básida para projetos de Machine Learning e Deep Learning # Por Adriano Santos. import torch from torch import nn, optim from utils.dataset import DataSet import torchvision.transforms as transforms from model import ModelCNN from sklearn.metrics import accuracy_score import random from random import choice...
import sys import os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/..") from frontui.linq import first_or_default from frontui.data_provider import DataProvider from frontui.views.member import calc_points, add_one_month, calculate_date_period from frontui.models import Checklist
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden product = "Apple iMac" price = 3699 # formatting print("the", product, "costs", price) print("the {} costs {}".format(product, price)) print("the %s costs %d" % (product, price)) print(f"the {product} costs {price}") ############...
# ''' pg_draw_circle_save101.py # draw a blue solid circle on a white background # save the drawing to an image file # for result see http://prntscr.com/156wxi # tested with Python 2.7 and PyGame 1.9.2 by vegaseat 16may2013 # ''' # import pygame as pg # # pygame uses (r, g, b) color tuples # white = (255, 255, 255) ...
''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms and conditions stipulated in t...
import os from os.path import join from cffi import FFI ffibuilder = FFI() ffibuilder.set_unicode(False) folder = os.path.dirname(os.path.abspath(__file__)) with open(join(folder, "pandas_plink", "_bed_reader.h"), "r") as f: ffibuilder.cdef(f.read()) with open(join(folder, "pandas_plink", "_bed_reader.c"), "r"...
''' Title : Day 10: Binary Numbers Domain : Tutorials Author : Ahmedur Rahman Shovon Created : 03 April 2019 ''' #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input()) b = str(bin(n))[2:] l = len(b) max_1 = 0 i = 0 ...
import re found = False for i in range(1, 6): if re.fullmatch(".*FBI.*", input()) is not None: print(i, end=' ') found = True if not found: print("HE GOT AWAY!")
#!/usr/bin/env python import math import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Generate random planes to form a convex polyhedron. # Create a polyhedral representation of the planes. # create some points lying between 1<=r<5 (r is radius) # the points also have normals pointi...
import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.cm as cm import numpy as np from tanager_feeder.utils import cos, sin class HemispherePlotter: def __init__(self): pass @staticmethod def plot(geoms, data, incidence, sample_name, data_label): offset = 0 i...
from pyld import jsonld import pyld.documentloader.requests import pandas as pd import csv, os, json, copy, requests def deep_get(dikt, path): """Get a value or values located in `path` from a nested dictionary. Use a string separated by periods as the path to access values in a nested dictionary: dee...
from pandas import read_csv def sort_list(fileName): dataframe = read_csv(fileName+'.csv', delimiter=';') rowsList = [list(row) for row in dataframe.values] rowsList.sort(key=lambda column:column[2]) # rowsList.insert(0, dataframe.columns.to_list()) return rowsList fileName = input("Nome do arquivo csv: ") pri...
# Generated by Django 3.1.4 on 2021-01-29 04:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0016_auto_20201227_2257'), ] operations = [ migrations.AlterField( model_name='projectpost', name='thumbnail...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 14 12:00:00 2020 @author: divyanshvinayak """ T = int(input()) for I in range(T): N, M = map(int, input().split()) P = N * M A = list(range(N)) for J in range(N): A[J] = list(map(int, input().split())) for...
import scrapy from myproject.items import Page from myproject.utils import get_content class BroadSpider(scrapy.Spider): name = "broad" start_urls = ( # はてなブックマークの新着エントリーページ。 'http://b.hatena.ne.jp/entrylist', ) def parse(self, response): """ はてなブックマークの新着エントリーページをパースす...
from . import ansible from . import console from . import fs from . import internal from . import terminal from . import vagrant from . import virtualbox # historically, these have been part of core # we've left them here for backwards-compatibility from dsf._net import http from dsf._cmd import shell from dsf._log im...
import torch from torch.nn.functional import conv2d, _Reduction, avg_pool2d from torch.nn.modules.loss import _Loss def _fspecial_gaussian(size, channel, sigma): coords = torch.tensor([(x - (size - 1.) / 2.) for x in range(size)]) coords = -coords ** 2 / (2. * sigma ** 2) grid = coords.view(1, -1) + coord...
from .client import Client from .session import Session from .handle import Handle from .transaction import Transaction
import json import os import sys import cv2 data_dir = "data/" h,w = 2448.0,3264.0 ## image shape files = os.listdir(data_dir) f = open('labelsxdata.txt','w') for fc in files: if fc[-4:] == '.png': print(fc) with open(os.path.join(data_dir,fc[:-4]+"_refactored.json")) as json_data: d...
"""Interactive command line interface (CLI).""" from threading import Event import random import os # TODO -- use match statement with python >= 3.10 instead of if/else? # ================================ MAIN CLASS ================================ class CommandLineInterface: """Interactive CLI to manage pr...
import collections import numpy as np from sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin from sklearn.linear_model import LinearRegression from sklearn.preprocessing import QuantileTransformer, quantile_transform from sklearn.utils import check_array from sklearn.utils.validation import check_is_...
from data import * import math import time jobs=loadjobs() data=loadset() tims=loadtime() print("investing*"+str(len(jobs))) print(jobs) alpha=0.1 deltaT=1000 srelmin=0.0001 frac=0.1 minhits=10 def mean(q): ret=q[0] for i in range(1,len(q)): ret=ret*(1-alpha)+alpha*q[i] return ret def std(q,m=...
from __future__ import print_function, division, absolute_import import sys from toolz import identity if sys.version_info[0] < 3: class SeekableFile(object): def __init__(self, file): if isinstance(file, SeekableFile): # idempotent file = file.file self.file = fil...
import microgear.client as client import logging import time appid = "ekaratnida" gearkey = 'jtD9ag08syPtqiK' # key gearsecret = 'vDEEIuw9Ssj4OvbrBHmM4hZfa' # secret client.create(gearkey,gearsecret,appid,{'debugmode': True}) # สร้างข้อมูลสำหรับใช้เชื่อมต่อ client.setalias("ekarat") # ตั้งชื่้อ def callback_connect...
from oswrapper import * from cvat.apps.engine.models import * from django.db.models import Q import requests import json import os global generator_id generator_id = 0 global generator_id_sorted generator_id_sorted = 0 def getObjectStoragesPerProject(user_id, project_id, isAdmin): # if the user au...
from typing import Callable import networkx import pytest from beagle.backends.networkx import NetworkX from beagle.nodes import Process @pytest.fixture() def nx() -> Callable[..., NetworkX]: def _backend(*args, **kwargs) -> networkx.Graph: return NetworkX(*args, consolidate_edges=True, **kwargs).graph(...
import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, pause, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import make_get_conf, OptimizationSolver import scipy.optimize as sopt import scipy.optimize.linesearch as linesearch #...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """""" from koicore.koi_object import KoiObject class KoiInteger(KoiObject): def __init__(self, value: int): super().__init__() self.value = value def to_boolean(self): from .koi_boolean import KoiBoolean if self.value == 0: ...
""" Package level utils.""" import shlex def parse_kv_pairs(key_value_string): """ Parse string of key value pairs to dict Example: 'key1=value1 "key 2"="value 2"' --> {'key1': value1, 'key 2': 'value 2'} parse(s) """ if not key_value_string: return {} return dict(token.s...
#!/usr/bin/env python from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys def main(): for path in sys.argv[1:] or sys.stdin.read().splitlines(): with open(path, 'rb') as path_fd: contents = path_fd.read() if b'\r' in contents: ...
# -*- encoding: utf-8 -*- # # Copyright (c) 2014, OVH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
# -*- coding: utf-8 -*- """ Script to automate the merge and export of thermal camera files Created on Wed May 02 16:22:14 2018 @author: tbeleyur """ import re import subprocess import os import easygui as eg # change the current working directory print('please choose a folder') overall_folder = eg.diropenbox() os.c...
# step 1. imports from sqlalchemy import (create_engine, MetaData, Table, Column, Integer, String, ForeignKey, Float, DateTime) from sqlalchemy.orm import sessionmaker, mapper, relation from sqlalchemy.orm.shard import ShardedSession from sqlalchemy.sql import operators from sqlalchemy import sql import datetime ...
"""The Z-Wave-Me WS integration.""" import logging import voluptuous as vol from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity import Entity from zwave_ws import ZWaveMe from .const import CONF_TOKEN, CONF_URL, DOMAIN, PLATFORMS, ZWAVEPLATFORMS _LOGGER = logging.getLogger(__n...
import reshade as rs class TestReLUActivationNeuron: def test_ReLUActivationNeuron(self): input = rs.Connection() output = rs.Connection() rs.activation.ReLUActivationNeuron(input, output) assert input.value == 0 assert output.value == 0 input.value = -1 ...
# this is the setup of the joke. is uses a formatter to put the number 10 # inside of the string # NOTICE how you were able to use a formatter in the variable declaration # You figured that out yourself last lesson. Good job Jared. 12/23/2015 x = "There are %d types of people." % 10 # this joke is getting old already ...
import networkx as nx import matplotlib.pyplot as plt CEMM_COL1 = ( 0/255, 85/255, 100/255) CEMM_COL2 = ( 0/255, 140/255, 160/255) CEMM_COL3 = ( 64/255, 185/255, 212/255) CEMM_COL4 = (212/255, 236/255, 242/255) DARK_CEMM_COL1 = (0/255, 43/255, 50/255) BAR_COL = (0.639, 0.639, 0.639) def set(): #sns.set() <--...
from django.conf.urls import patterns, include, url from django.conf import settings from django.views.generic import TemplateView from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^...
import logging from pprint import pprint as pp import click import coloredlogs import matplotlib.style as mp_style import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] LOG = logging.getLogger(__name__) #####...
from keras.preprocessing import text, sequence import joblib from ..base import BaseTransformer class Tokenizer(BaseTransformer): def __init__(self, char_level, maxlen, num_words): self.char_level = char_level self.maxlen = maxlen self.num_words = num_words self.tokenizer = text....
# Copyright (c) 2021, ac and Contributors # See license.txt import unittest import frappe from frappe.exceptions import ValidationError class TestJournalEntry(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.doctype = 'Journal Entry' def test_journal_entry_validation_errors(self): with sel...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftORleftANDleftMAYORIGUALQUEMENORIGUALQUEMAYORQUEMENORQUEleftSIGNO_MASSIGNO_MENOSleftSIGNO_PORSIGNO_DIVISIONleftSIGNO_POTENCIASIGNO_MODULOACTION ADD ALL ALTER AND ANY...
import discord from discord.ext import commands class MyHelp(commands.MinimalHelpCommand): def __init__(self): super().__init__() self.verify_checks = False @staticmethod def _get_command_signature(command): return f"`{command.qualified_name}`" async def send_bot_help(self, m...
computer_choice = 'rock' user_choice = input('Enter rock, paper, or python:\n') if computer_choice == user_choice: print('TIE') else: print('You lose :( Computer wins :D')
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-08 13:39 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migr...
#!/apps/base/python3/bin/python import os import re import sys import json import time import math import gzip import shutil import string import random import hashlib import argparse import multiprocessing from http.server import SimpleHTTPRequestHandler, HTTPServer DV_LOCATION = os.path.dirname(os.path.realpath(__...
import pandas as pd import json df = pd.read_csv('raw_input_data.csv', sep=';') data = {'timestamp': list(df['Timestamp']), 'wind_velocity_mean': list(df['Wind_speed_mean']), 'L50eq': list(df['L50eq']), 'chronogram': list(df['chronogram']) } with open('input_data.json', 'w+') as f: ...
import numpy as np import pytest import astropy.units as u from astropy.nddata import InverseVariance, StdDevUncertainty from astropy.tests.helper import assert_quantity_allclose from ..spectra.spectrum1d import Spectrum1D from ..tests.spectral_examples import simulated_spectra from ..manipulation.resample import Flux...
from elasticsearch.exceptions import NotFoundError import logging logger = logging.getLogger(__name__) def rollable_alias(client, alias): """ Ensure that `alias` is an alias, and points to an index that can use the _rollover API. :arg client: An :class:`elasticsearch.Elasticsearch` client object ...
import requests from bs4 import BeautifulSoup response = requests.get("http://google.com/") print " STATUS: " + str(response.status_code) print " CABECERAS: " + str(response.headers) cuerpo_respuesta = response.content if response.status_code == 200 : html = BeautifulSoup(cuerpo_respuesta, "html.pars...
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the oceanography-specific units. They are also available in the `unyt` namespace. """ import numpy as _numpy import unyt # Sverdrup unyt.define_unit('Sverdrup', 1e6*unyt.m**3/unyt.s)
import sys from argparse import Namespace, ArgumentParser from collections import defaultdict from logging import getLogger, FileHandler, INFO import datetime from functools import reduce from copy import deepcopy import _pickle as pic import time import numpy as np from sklearn.utils import shuffle im...
"""Views Notes: * Some views are marked to avoid csrf token check because they rely on third party providers that (if using POST) won't be sending csrf token back. """ from __future__ import absolute_import import six from sudo.utils import is_safe_url from django.conf import settings from django.htt...
from mlmo.eval.metrics import BaseMetric, RougeMulti from mlmo.utils.helpers.metrics import comp_f1 from collections import OrderedDict class SoftPrRecF1(BaseMetric): """ Computes a soft version of precision, recall, and f1 for sequences. Currently, it's uses RougeMulti to produce soft-matches/scores. ...
if __name__ == '__main__': # main 파일을 엔트리포인트로 사용할 경우, path에 폴더 경로를 추가해 절대 경로로 임포트가 가능하게 함 from sys import path import os path.append(os.path.dirname(__file__)) import json import base64 import settings from settings import DEBUGGING as debugging def lambda_handler(event, context): try: ...
"""Unit tests for skycomponents """ import logging import os import unittest import astropy.units as u import numpy from astropy.coordinates import SkyCoord from arl.data.polarisation import PolarisationFrame from arl.image.operations import export_image_to_fits from arl.skycomponent.operations import insert_skycom...
# coding: utf-8 """ LOCKSS Poller Service REST API API of the LOCKSS Poller REST Service # noqa: E501 OpenAPI spec version: 1.0.0 Contact: lockss-support@lockss.org Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from lock...
#!/usr/bin/env python from email.utils import parsedate_tz, mktime_tz import re PARTS = [ r'(?P<host>\S+)', # host %h r'\S+', # indent %l (unused) r'(?P<user>\S+)', # user %u r'\[(?P<time>.+)\]', # time %t r'"(?P<reque...
from os import path import glob import unittest base_model_dir = path.join(path.expanduser("~"), "data", "carml", "dlperf") def find_onnx_model(name, batch_size=1): files = glob.glob(path.join(base_model_dir, name, "**", "*.onnx"), recursive=True) if len(files) == 0: m...
#!/usr/bin/python # -*- coding: utf-8 -*- # decrypts Enigma messages
import pandas as pd import dash from dash.dependencies import Input, Output, State, MATCH, ALL import dash_core_components as dcc import dash_html_components as html from dash.exceptions import PreventUpdate import dash_bootstrap_components as dbc import dash_table import plotly.graph_objs as go from threading impor...
#MIT License #Copyright (c) 2018 The University of Michigan #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, m...
from sarna.model.enums.base_choice import BaseChoice class AuthSource(BaseChoice): _init_ = "value engine" database = 1, None ldap = 2, None ad = 3, None class UserType(BaseChoice): auditor = 1 trusted_auditor = 2 manager = 3 admin = 4
import bisect class SortList(): def __init__(self,iterable=(),key=None): if hasattr(key,'__call__'): self.key = key elif key: self.key = lambda x: x[key] sorted_list = sorted((key(value),value) for value in iterable) self.keys = [k for k, item in sorted_list]...
from datetime import datetime from decimal import Decimal from functools import reduce from unittest.case import TestCase from uuid import uuid4 from eventsourcing.application import AggregateNotFound, Repository from eventsourcing.domain import TZINFO, Snapshot from eventsourcing.persistence import ( DatetimeAsIS...
from tkinter import * from tkinter.scrolledtext import * import file_menu import edit_menu import format_menu import help_menu # MAIN WINDOW OF eTEXT, CONTAINS THE ROOT AND THE MENU root = Tk() root.title("eText - Untitled") root.geometry("800x600+700+70") root.resizable(0,0) root.iconbitmap("C:/Users/ma...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type class ErrorMessages(): BATCH_FAILURE_MSG = "Failed. Check 'msg' field in 'ims_output' for more details." INVALID_CHAR_IN_CMD = "Invalid character(s) found in command." INVALID_MEMBER_LIST_TYPE = "Received unexpected t...
#!/usr/bin/env python3 ''' Python script to convert YouTube JSON subtitles to SRT format Owain Kenway ''' # Convert a numeric time in ms to format used in SRT # timestamp - the time in ms since start # delta - extra time for calculating durations. def timeconvert(timestamp=0, delta=0): wn = timestamp + del...
from traitlets import default from .baseapp import NbGrader, nbgrader_aliases, nbgrader_flags from ..exchange import Exchange, ExchangeList, ExchangeError aliases = {} aliases.update(nbgrader_aliases) aliases.update({ "timezone": "Exchange.timezone", "course": "Exchange.course_id", }) flags = {} flags.updat...
from bottle import run, request, route @route('/runCode', method='POST') def runCode(): name_of_return_variable = 'return_variable' function_definition = request.params['functionDefinition'] function_call = request.params['functionCall'] outputMap = {} error_output = '' error_occured = False testRunCode = fun...
import calendar import datetime import operator import re from django.core.exceptions import ValidationError from dateutil.parser import parse as dateutil_parse class Period: # abstract base class prefix = None validation_regex = r".*" minimum = None maximum = None contains = [] def __ini...
from engine.npc import Npc
# encoding=utf8 import requests r = requests.get('http://www.bigerhead.com') # print r.text # 设置代理 proxy proxies = { 'http': '127.0.0.1:9999', 'https': '127.0.0.1:9999' } param = {'name': 'wangc', 'age': 12} r2 = requests.get('http://www.bigerhead.com', proxies=proxies, params=param) print(r2.text) print(r2...
from contextlib import closing import pytest import sqlalchemy from sqlalchemy.sql.schema import Table as DbTable from osmaxx.utils.frozendict import frozendict from tests.conftest import TagCombination from tests.conversion.converters.inside_worker_test.conftest import slow from tests.conversion.converters.inside_wo...
import random def gameWin(comp, you): if comp == you: return None elif comp == 's': if you == 'w': return False elif you =='g': return True elif comp == 'w': if you == 's': return True elif you == 'g': ret...
from . import FloorModifier, FloorModifierLoader from ...attack_attribute import AttackAttribute from ...common import binary_to_list class AttributeBonusFM(FloorModifier): @classmethod def handles(self, name): return name == 'battr' def parse_value(self): args = self.value.split(';') ...
import dataclasses import pytest from jsonlog_cli.key import Key from jsonlog_cli.pattern import Pattern, TemplatePattern from jsonlog_cli.record import Record @dataclasses.dataclass() class Example: line: str expected: str pattern: Pattern def record(self): return Record.from_string(self.l...
# Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task from .util import createLedgerTraintuple @shared_task def createLedgerTraintupleAsync(args): return createLedgerTraintuple(args)
"""Unit tests for the one.params module. NB: `setup` function also tested with TestOneSetup class in one.tests.test_one. """ import unittest from unittest import mock from pathlib import Path from functools import partial import tempfile import one.params import one.params as params from . import util from . import T...