content
stringlengths
5
1.05M
__author__ = 'nobit' import wx import socket import threading import time myEVT_COUNT = wx.NewEventType() EVT_COUNT = wx.PyEventBinder(myEVT_COUNT, 1) # myEVT_RECV = wx.NewEventType() EVT_RECV = wx.PyEventBinder(myEVT_RECV, 1) class CountEvent(wx.PyCommandEvent): """Evetn to singal that a count value is ready ...
''' Module responsible for Celery task status polling of various other modules that make use of the message queue system. 2020-21 Benjamin Kellenberger ''' from bottle import request, abort from .backend.middleware import TaskCoordinatorMiddleware class TaskCoordinator: def __init__(self, confi...
import hashlib import os from io import BytesIO import shlex import subprocess import sys import warnings from itertools import zip_longest import base64 from signal import * import ntpath import binascii from PIL import Image, ImageChops from src.exiftool import ExifTool import logging logger = logging.getLogger('...
from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('filters', parent_package, top_path) config.add_data_dir('tests') # Como tests no es considerado como un ...
from sklearn.metrics import accuracy_score, precision_score, recall_score import numpy as np import json from IPython import embed def JsonReader(fileName): fileReader = open("json/" + fileName + ".json", "r") itemList = json.load(fileReader)[fileName] fileReader.close() itemDict = {} for item...
REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. "DEFAULT_PERMISSION_CLASSES": [], "DEFAULT_AUTHENTICATION_CLASSES": [], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE":...
import sys from functools import partial as p from textwrap import dedent import pytest from tests.helpers.agent import Agent from tests.helpers.assertions import has_event_type, has_log_message from tests.helpers.util import wait_for pytestmark = [ pytest.mark.skipif(sys.platform != "win32", reason="only runs o...
import pytest from selenium.webdriver.common.keys import Keys from selenium.webdriver.remote.webdriver import WebDriver from steps import login_litecart from drivers import drivers @pytest.fixture def driver(request): chrome = drivers.create_chrome_driver() request.addfinalizer(chrome.quit) return chrome ...
"""Methods to submit a MeasurementSet object to Nava's API.""" import urllib.parse from claims_to_quality.config import config from claims_to_quality.lib.qpp_logging import logging_config import newrelic.agent import requests from retrying import retry logger = logging_config.get_logger(__name__) STOP_MAX_ATTEMP...
import torch import tensorflow as tf print(torch.cuda.is_available()) print(tf.test.is_built_with_cuda()) import os import argparse from solver import Solver from data_loader import get_loader from torch.backends import cudnn import configparser def str2bool(v): return v.lower() in ('true') def main(config): ...
import time import unittest from unitti import load_classes, batch e1 = ['A', 'B', 'C', 'D'] e2 = ['A', 'C', 'B', 'D'] r = [] # batch = 0 @batch(0) class TestA(unittest.TestCase): def test1(self): r.append('A') time.sleep(0.1) # default batch class TestB(unittest.TestCase): def test1(self)...
# # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # # Copyright (c) 2015 Juniper Networks, Inc. # All rights reserved. # # Use is subject to license terms. # # 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...
import codecs from setuptools import setup, find_packages TESTS_REQUIRE = [ 'fudge', 'nti.testing >= 3.0.0', 'pyhamcrest', 'z3c.baseregistry', 'zope.testrunner', 'coverage', 'zope.testing', ] def _read(fname): with codecs.open(fname, encoding='utf-8') as f: return f.read() ...
import os.path from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from itertools import product from collections.abc import Iterable from random import sample import numpy as np import pandas as pd from utils import print_args, JobManager class HyperParams: def __init__(self, path_dir): t...
from typing import List class Solution: def sortArray(self, nums: List[int]) -> List[int]: min_num, max_num = min(nums), max(nums) buckets = [0] * (max_num - min_num + 1) for num in nums: buckets[num - min_num] += 1 return [i + min_num for i, count in en...
import os import math import time import argparse import torch import torch.backends.cudnn as cudnn from torch import optim import torch.nn.functional as F from torchvision.utils import save_image from stylegan.stylegan_generator_model import StyleGANGeneratorModel from utils.losses import PerceptualLoss import numpy ...
def print_weather_data(observation_dict): if 'weather' in observation_dict: weather_dict = observation_dict['weather'] else: return for key, value in weather_dict.items(): print(f"{key} --> {value}")
import ctypes import collections import threading import travel_backpack import win32con import win32api import win32gui from typing import Callable import atexit from win_key_hook.input_parser import InputParser from uuid import uuid4 class WinLowLevelHook(metaclass=travel_backpack.Singleton): hook_thread: threa...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function from enum import Enum from characteristic import attributes from constr...
"""SMOK Job Entry Subsystem / Tracker for Applications"""
#!/usr/bin/env python # -*- coding: utf-8 -*- import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.core.management import setup_environ #from django.db import transaction import datetime import logging def minute_update(): try: from auctions.models import AuctionSession sessi...
# MedsNET Timetable Scraper # Main Scraper # Reinis Gunārs Mednis / Ikars Melnalksnis 2020 from selenium.common.exceptions import TimeoutException from selenium.webdriver import Firefox from selenium.webdriver.common.by import By from selenium.webdriver.firefox.options import Options from selenium.webdriver.support im...
from mayan.apps.appearance.classes import Icon icon_dashboard_detail = Icon( driver_name='fontawesome', symbol='tachometer-alt' ) icon_dashboard_link_icon = Icon( driver_name='fontawesome', symbol='external-link-alt' ) icon_dashboard_list = Icon( driver_name='fontawesome', symbol='tachometer-alt' )
""" Copyright (c) 2021 Elix, Inc. """ from .ge_operations.crossover import crossover from .ge_operations.fragment_crossover import fragment_crossover from .ge_operations.mutate import mutate from .ge_operations.selfies_crossover import selfies_crossover from .ge_operations.selfies_mutate import selfies_mutate
import time import os import logging import platform import csv from datetime import datetime import statistics from polyglotdb import CorpusContext from polyglotdb.config import CorpusConfig from polyglotdb.io import (inspect_buckeye, inspect_textgrid, inspect_timit, inspect_labbcat, inspect_...
import os from matplotlib import pyplot as plt from matplotlib import rc rc("text", usetex=True) journeys_str = """B & OcdefgD & 08:08 & 08:28 & 3 & 20 C & OcdeD & 08:08 & 08:32 & 2 & 24 D & OcdeD & 08:08 & 08:59 & 2 & 51 E & OabD & 08:13 & 08:50 & 1 & 37 ...
''' Note: torch.onnx does not needd to be installed as it comes with Pytorch. ''' import datetime import math import os from time import time import matplotlib.pyplot as plt import numpy as np import onnx import onnxruntime import torch from torch import nn from torch import optim import torch.onnx as torch_onnx impor...
def modify_values(id, name, subjects): id = 102 name = 'Rajesh Agarwal' subjects[0] = -101 print(f'(Inside modify_values) Id= {id}, Name= {name}, Subjects= {subjects}') def modify_values_v2(id, name, subjects): id = 102 name = 'Rajesh Agarwal' subjects[0] = -101 print(f'(Inside modi...
"""47. Permutations II https://leetcode.com/problems/permutations-ii/ Given a collection of numbers that might contain duplicates, return all possible unique permutations. Example: Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ] """ import copy from typing import List class Solution: def permute_uni...
class Source: ''' Source class to define Source Objects ''' def __init__(self,id,name,description,category,language): self.id = id self.name = name self.description = description self.category = category self.language = language class Article: ''' Articl...
import pkgutil import types from importlib.abc import PathEntryFinder from types import ModuleType from typing import Iterator, List, Optional, cast from funcy import collecting, notnone import ballet from ballet.feature import Feature from ballet.util import dfilter from ballet.util.log import logger __all__ = ( ...
import torch import torchvision import torchvision.transforms as T import argparse import time from torch.utils.data.distributed import DistributedSampler import os os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,3" parser = argparse.ArgumentParser() parser.add_argument("--local_rank", default=0, type=int) parser.add_arg...
""" 根据年月日,计算星期 """ import time def get_week_by_day(year, month, day): str_time = "%d-%d-%d" % (year, month, day) time_tuple = time.strptime(str_time, "%Y-%m-%d") return int(time_tuple[6]) + 1 print(get_week_by_day(2020, 11, 19))
from django.contrib import admin from paytm.models import Order, Item @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ('order_id', 'txn_id', 'amount', 'status') def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj...
'''test_angdia.py''' # pragma pylint: disable=C0413, E0401 import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import json import logging import unittest from math import atan2, pi import traveller_utils class TestAngdia(unittest.TestCase): ''' angdia unit t...
import unittest from programy.config.brain.brain import BrainDynamicsConfiguration from programy.dynamic.sets.set import DynamicSet class MockDynamicSet(DynamicSet): def __init__(self, config): DynamicSet.__init__(self, config) def is_member(self, client_context, value, additional=None): ra...
""" Author: Taivanbat "TK" Badamdorj github.com/taivanbat """ import itertools import subprocess from multiprocessing import Process from pprint import pprint from random import choice from subprocess import DEVNULL import os from gpu_utils import GPUMemoryUtils from param_utils import * class HPSearch: def __i...
import boto3 import json client = boto3.client('accessanalyzer') policy = """ { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "*", "Resource": "*" } ] } """ r = client.validate_policy( policyDocument=policy, # policyType...
import sys sys.path.insert(0,"../src/") from problem30 import waterremaining def test_problem30_1(): assert waterremaining([2,1,2]) == 1 def test_problem30_2(): assert waterremaining([3, 0, 1, 3, 0, 5]) == 8
class SntpInfo(object): def __init__(self, api_client): self.api_client = api_client def get_sntp_info(self): jsondata = self.api_client.get("system/sntp_server") if not self.api_client.error: sntp_servers = [] for server in jsondata["sntp_servers"]: ...
import os import sys from celery import Celery from django.conf import settings # Add the apps directory to the python path for celery to find the apps sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../..')) # set the default Django settings module for the 'celery' program. os.environ.set...
#!/usr/bin/env python # vim: ts=4 sw=4 et """Prompts for User Inputs""" import sys import re from pyVmomi import vim # pylint: disable=no-name-in-module from vctools.query import Query from vctools import Logger class Prompts(Logger): """ User prompts for selection configuration values. It's best if these ...
"""This module contains the general information for BiosVfUmaBasedClustering ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfUmaBasedClusteringConsts: VP_UMA_BASED_CLUSTERING_DISABLE_ALL2_ALL = "Disable (All2All...
import torchtext.data import torchtext.datasets def load(path, format, fields, tokenize=str.split, preprocessing=None, embedding_dim=60, batch_size=4, device=None, skip_header=False): """Load a tabular dataset. Arguments: path (s...
import argparse import re import sys import nltk def main(): punc_error_patt = re.compile(r"([A-z])(\.|\?|\!)([A-z])") url_patt = re.compile(r"[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)") contiguous_space_patt = re.compile(r"\s+") for line in sys.stdin: rating, ...
#!/usr/bin/env python """ The example below is taken from http://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-custom-nn-modules where you can find in-depth comment about the standard PyTorch code. We will focus here on the monitoring instead to illustrate the `StatMonitor` class. Note however tha...
from typing import Dict, Optional, Tuple import random import string import tensorflow as tf import numpy as np from tqdm import tqdm import re from os import listdir from os.path import isfile, join import pickle as pkl from Bio.SeqRecord import SeqRecord from Bio import SeqIO """ Paired Homology Detection task int...
def ficha(nome_jogador, quantidade_gols): return f"O jogador {nome_jogador} fez {quantidade_gols} gol(s) no campeonato." nome = str(input("Nome do jogador: ")).strip().title() if nome.strip() == "": nome = "<desconhecido>" gols = str(input("Número de Gols: ")) if gols.isnumeric(): gols = int(gols...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division from pprint import pprint as pp import cffi import pytest @pytest.mark.unit def test_import(): '''Basic test to determine if glfw can be imported successfully''' import glfw assert locals()['glfw'] == glfw @p...
# -*- coding: utf-8 -*- import os import uuid import shutil import tempfile from subprocess import DEVNULL, run from requests import request import dramatiq BOOKLET_URL = 'https://webtool.dav-kempten.de/api/client/booklets/' @dramatiq.actor def update_booklet_list(pk): import django django.setup() fro...
import os,sys if os.path.isfile('.apikey') == False: consumerKey = input("Consumer Key: ") consumerSecret = input("Consumer Secret: ") accessToken = input("Access Token: ") accessTokenSecret = input("Access Token Secret: ") printArray = [consumerKey,consumerSecret,accessToken,accessTokenSecret] with open(".apike...
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # 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.apa...
# possible years to select from years = [2007, 2008, 2009, 2010, 2015, 2016, 2017, 2018, 2019, 2020] last_fnf_year = 2017 # speckle filters to select from speckle_filters = [ {"text": "No Speckle filter", "value": "NONE"}, {"text": "Refined Lee (zoom dependent)", "value": "REFINED_LEE"}, {"text": "Quegan F...
''' Created on 16 Nov 2016 @author: gbstring ''' from flask import render_template, session, redirect, url_for from .forms import TitleForm from .models import Title from .__init__ import db from app import app
from astral import LocationInfo from datetime import datetime import sys import time import pytz BEDTIME_SHUTDOWN_HOLD_TIME = 5 ABORT_BEDTIME_PROTOCOL_HOLD_TIME = 3 LONG_BREAK_HOLD_TIME = 2 QUICK_SPRINT_HOLD_TIME = 2 END_SESSION_HOLD_TIME = 2 DEMO_MODE_HOLD_TIME = 2 MAX_CLICK_TIME = 1.2 END_STATS_DISPLAY_LENGTH = 7....
import torch from torch import nn import torch.nn.functional as F from tianshou.data import Batch from tianshou.policy import PGPolicy class A2CPolicy(PGPolicy): """docstring for A2CPolicy""" def __init__(self, actor, critic, optim, dist_fn=torch.distributions.Categorical, ...
""" The LeNet. Paper: http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf """ import torch import torch.nn as nn from scratchai.nets.common import Flatten from scratchai.utils import load_from_pth from scratchai.pretrained import urls __all__ = ['Lenet', 'lenet_mnist', 'lenet_cifar10'] def conv(ic:int, oc:int, k:in...
import BIbear import yaml import random import math with open("settings.yaml") as file: settings = yaml.load(file, Loader=yaml.FullLoader) next_bear = settings['generation_settings']['next_bear'] count_bear = settings['basic_settings']['count_bear'] chance_mutant = settings['generation_settings']['chance_mutan...
""" problem3 --- The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ import math def is_prime(q): q = abs(q) if q == 2: return True if q < 2 or q&1 == 0: return False return pow(2, q-1, q) == 1 if __name__ == '__main__': N = 60085147514...
from typing import List, Union, Iterable, Optional from ..api import Dataset, KeywordQueryLog, RangeDatabase, QuerySpace, RangeQueryLog from .types import StatisticsTypes class StatisticsCase: """ A statistic case to use with the StatisticsEvaluator. It consists of one or multiple StatisticTypes to evaluate,...
from builtins import range import ROOT import copy import math def applyLegendSettings(leg): leg.SetBorderSize(0) leg.SetFillColor(10) leg.SetLineColor(0) leg.SetFillStyle(0) # leg.SetTextSize(0.035) # leg.SetTextFont(42) def createRatioCanvas(name, errorBandFillColor=14, errorBandStyle=3354): ...
#-*- coding: utf-8 -*- # ssh.alfredworkflow, v1.1 # Robin Breathe, 2013 import alfred import json import re from os import path from time import time _MAX_RESULTS=36 class Hosts(object): def __init__(self, original, user=None): self.original = original self.hosts = {original: ['input']} ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import copy import logging import nzbhydra from collections import namedtuple from io import BytesIO from builtins import * from flask import request, send_file from fur...
from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.Flood import stations_highest_rel_level from floodsystem.station import MonitoringStation stations = build_station_list() update_water_levels(stations) for station_tuple in stations_highest_rel_level(stations, 10): print(st...
#!/bin/python3 import math import os import random import re import sys from collections import Counter, OrderedDict # class OrderedCounter(Counter, OrderedDict): pass [print(*c) for c in OrderedCounter(sorted(input())).most_common(3)] # second way is also return first three alphabet and then count """ if __name...
from pylab import * import postgkyl as pg data = pg.data.GData('f1-hw-lr_chi_100.h5') interp = pg.data.GInterpModal(data, 2, 'ns') iGrid, iValues = interp.interpolate() pcolormesh(iGrid[0], iGrid[1], transpose(iValues[:,:,0])) axis('image') show()
# coding=utf-8 """This module, javascript_manager.py, deals with pre-processing javascript files, combining them, and minimizing them.""" from libraries.code_api.source_file_abstraction.code_directories.code_directory import CodeDirectory from libraries.code_api.source_file_abstraction.code_files.js_file import Gener...
""" A collection of regularly used functions """ def validate_key_type(key): """Checks if the key is of type str. Args: key(str): the key to validate""" if not type(key) == str: raise TypeError('Key must be of type string')
__all__ = ['periodic_continuous_signal', 'signal_function']
import dataclasses from typing import Tuple, Type, TypeVar Entity = TypeVar('Entity') EntityData = TypeVar('EntityData') def init_subclass(cls: Type[Entity], bases: Tuple[Type[Entity], ...]) -> None: if cls not in getattr(cls, '__skip_dataclass__', ()): if not hasattr(cls, '__annotations__'): ...
# # 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...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Implementation of the OSGi LogService, based on Python standard logging :author: Thomas Calmant :copyright: Copyright 2020, Thomas Calmant :license: Apache License 2.0 :version: 1.0.1 .. Copyright 2020 Thomas Calmant Licensed under the Apache License...
import collections import os import shutil import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset from src.models.MultiTaskClassification import MetaModel, NonLinClassifier from src.mo...
import mini import math lcd = mini.lcd() key = mini.key() lcd.color(0x404040) lcd.bar(0, 14, lcd.width, lcd.height-14) a = 0 lx = 0 ly = 0 r = min(lcd.width, lcd.height)*0.4 cx = lcd.width/2 cy = lcd.height/2 lcd.color(0xffffff) while key.get() == 0: nx = math.sin(a)*r + cx ny = math.cos(a)*r + cy a = a + math....
"""Scripts for demos.""" import logging import click from . import ( norms, scoracle) logger = logging.getLogger(__name__) # main function @click.group() def demo(): """Run a demo's server.""" pass # register subcommands to the command group subcommands = [ norms.norms, scoracle.scora...
import sublime import sublime_plugin import subprocess import os import shlex from shutil import copy # os.system can't be used here since it creates new cmd window #arguments containing the code #initiate load settings settings #so can be access from anywhere setting = None flag = 0 user_setting = None user_co...
# ABC152c def main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) n = int(input()) p = list(map(int, input().split())) cou = 0 m = 10**9 for i in range(n): if m < p[i]: cou += 1 m = min(m, p[i]) print(n-cou) if __name__ == '__ma...
from ptrlib import * def malloc(index, size): sock.sendlineafter("> ", "1") sock.sendlineafter("?\n", str(index)) sock.sendlineafter("size: \n", str(size)) return def write(index, data): sock.sendlineafter("> ", "2") sock.sendlineafter("?\n", str(index)) sock.sendafter("data: \n", data) ...
DS = 'yelp' # DS = 'ratebeer' OUTPUT_PATH = f'data/{DS}_output' # Corpus TRAIN_CORPUS = f'{OUTPUT_PATH}/split/train.txt' DEV_CORPUS = f'{OUTPUT_PATH}/split/dev.txt' TEST_CORPUS = f'{OUTPUT_PATH}/split/test.txt' # User & Item files USER_FILE = f'{OUTPUT_PATH}/users.txt' ITEM_FILE = f'{OUTPUT_PATH}/items.txt' # Vocabu...
#!/usr/bin/env python3 import http import database import os database = database.Database() err = "" redirect = "" sql = "" second = 0 sndkey = "" show_table = "" select = "" addLink = "" tableList = [] nameList = [] redirect = database.check_cookie(os.environ) sql = "SHOW tables" database.cur.execute(sql) if da...
from os.path import dirname, join, abspath from .ui import VUnit
import cv2 import numpy cv2.reprojectImageTo3D()
# -*- coding: utf-8 -*- import numpy as np alpha = [ 1e-3, 1e-2 ] beta = [ 0.0, 1.0, 1.5 ] t_ini = np.array([ 1e7 ]) a_ini = np.empty((len(alpha), len(beta), len(t_ini))) ## 1e-3, 0 a_ini[0,0] = [ 0.4106 ] ## 1e-3, 1 a_ini[0,1] = [ 0.6690 ] ## 1e-3, 1.5 a_ini[0,2] = [ 0.6739 ] ## 1e-2, 0 a_ini[1,0] = [ 0.5338 ]...
#!/usr/bin/env python """ @author : 'Muhammad Arslan <rslnrkmt2552@gmail.com>' """ import os import threading import time from netaddr import IPNetwork, IPAddress import socket import struct from ctypes import * from get_ip import get_lan_ip host = get_lan_ip() subnet = '.'.join(host.split('.')[:3]) + '.0/24' magi...
from .rotate_anchor_head import RAnchorHead from .rotate_retina_head import RRetinaHead from .rotate_retina_refine_head import RRetinaRefineHead __all__ = ['RAnchorHead', 'RRetinaHead', 'RRetinaRefineHead']
from fastapi import APIRouter, Body, HTTPException, Request, status from electionguard.ballot import PlaintextBallot from electionguard.election import CiphertextElectionContext from electionguard.manifest import InternalManifest, Manifest from electionguard.encrypt import encrypt_ballot from electionguard.group impor...
#!/usr/bin/python3 import os import sys import filecmp import hashlib import click from .util import calculateSHA1Sum from .index import DirectoryIndex def findMatches(filename,index,sha1=False): matches = [] if sha1: filesha1 = calculateSHA1Sum(filename) if filesha1 == "da39a3ee5e6b4b0d3255...
from .base import Community from ..service_types import SchemaType, ServiceType from ..format import format_value class ILLDatacite(Community): NAME = 'ill' IDENTIFIER = 'ill' URL = 'https://data.ill.fr/openaire/oai' SCHEMA = SchemaType.DataCite SERVICE_TYPE = ServiceType.OAI OAI_METADATA_PREF...
# -*- coding:utf-8 -*- from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.template.defaultfilters import slugify from ckeditor_uploader.fields import RichTextUploadingField import hashlib # 用户模型 class Master(models.Model): displayname = models.Cha...
# Generated by Django 2.2.20 on 2021-10-20 06:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0133_auto_20210729_1609'), ('api', '0133_auto_20210922_1327'), ] operations = [ ]
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals import pi3d import math import random import numpy as np import pi3d.util.Screenshot import sys # ************** VISIBILITY CHECK FUNCTIONS ************************ # # check if each tower is visible from the "left" d...
import cocotb from cocotb.triggers import Timer from cocotb.triggers import Edge @cocotb.test() async def reg_fork_data(dut): """It should fork data on both channels, and only take down in.ack once both outputs acknowledge it""" # Reset dut.reset.value = 1 dut.io_in_req.value = 0 dut.io_in_data.v...
# -*- coding: utf-8 -*- """ This module contains some helpers to deal with the real http world. """ import threading import logging import select import socket import time import os import six import webob from six.moves import http_client from waitress.server import TcpWSGIServer def get_free_port(): s = socke...
import unittest class Node: def __init__(self, data): self.data = data self.children = [] def __repr__(self): return str(self.data) + ' : [' + str(self.children) + ']' class Solution: def __init__(self): self.nodes = {} self.queries = [] self._path_proce...
# -*- coding:utf-8 -*- import requests from html.parser import HTMLParser # ================ define const =============== BASEPATH = "I:/" HTMLURLS = ["http://datachart.500.com/ssq/history/newinc/history.php", "http://kaijiang.zhcw.com/lishishuju/jsp/ssqInfoList.jsp"] HEADERS = [ { ...
#!/usr/bin/python #coding:utf-8 import random import urllib2 import socket from time import sleep from config import is_port_open, is_http def random_str(len): str1 = "" for i in range(len): str1 += (random.choice("ABCDEFGH1234567890")) return str(str1) # @is_port_open def verify(ip, port=80, ...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import click import requests from ...console import CONTEXT_SETTINGS, abort, echo_success @click.command( 'remove-labels', context_settings=CONTEXT_SETTINGS, short_help='Remove all labels from an is...
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse("user:register") GET_TOKEN_URL = reverse("user:login") class UserApiTests(TestCase): def setUp(s...
import urllib import logging import http.client import json import socket import re DEFAULT_TIMEOUT = 5 class Request: def __init__(self): pass def _parse_content_type(self, c_type): res = re.match(r"(?P<type>\w+?)\/(?P<app>\w+?);" r"\s*charset=(?P<charset>.+)", ...
import os from flask import Flask, request, render_template, redirect, url_for, session, send_file from werkzeug.utils import secure_filename from bs4 import BeautifulSoup import re from .counter import start, make_table, get_cmmts, Comment, SubTheme from flask_bootstrap import Bootstrap import jsonpickle from fla...