content
stringlengths
5
1.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import re import requests from bs4 import BeautifulSoup def get_last_series(url: str) -> int: rs = requests.get(url) root = BeautifulSoup(rs.content, 'html.parser') fields_str = root.select_one('ul.flist').get_text(strip=True) ...
import os from pathlib import Path from shutil import rmtree from tests.lib.base import DeloggerTestBase from tests.lib.urlopen_mock import UrlopenMock class TestPresets(DeloggerTestBase): def teardown_method(self): log_dir = self.OUTPUT_DIRPATH if not Path(log_dir).is_dir(): return F...
"""Top-level package for the 'dltf' framework. Running ``import dltf`` will recursively import all important subpackages and modules. """ import logging import dogs_vs_cats.src.inception_resnet_v2 logger = logging.getLogger("dogs_vs_cats") __url__ = "https://github.com/ShiNik/DeepLearning_Tensorflow" __version__ =...
"""Class for symbolic expression object or program.""" import array import os import warnings from textwrap import indent import numpy as np from sympy.parsing.sympy_parser import parse_expr from sympy import pretty from dsr.functions import PlaceholderConstant from dsr.const import make_const_optimizer ...
import os.path import sys import warnings from setuptools import find_packages, setup if sys.version_info < (2, 7): raise NotImplementedError( """\n ############################################################## # globus-sdk does not support python versions older than 2.7 # ###############################...
import json from collections import defaultdict from decimal import Decimal import bleach import dateutil.parser import pytz from django.dispatch import receiver from django.urls import reverse from django.utils.formats import date_format from django.utils.html import escape from django.utils.safestring import mark_sa...
import mcradar as mcr import xarray as xr import numpy as np import pandas as pd import os from IPython.core.debugger import Tracer ; debug=Tracer() #insert this line somewhere to debug def getApectRatio(radii): # imput radii [mm] # auer et all 1970 (The Dimension of Ice Crystals in Natural Clouds) d...
import numpy as np """ v_l object. c*r^{n-2}*exp{-e*r^2} """ class rnExp: def __init__(self, n, e, c): self.n = np.asarray(n) self.e = np.asarray(e) self.c = np.asarray(c) def __call__(self, r): return np.sum( r[:, np.newaxis] ** self.n * self.c ...
#!/usr/bin/python3.8 import os import requests import argparse import queue import threading import logging DOWNLOAD_THREADS = 6 IO_THREADS = 2 download_queue = queue.Queue() write_queue = queue.Queue() files_lock = threading.Lock() def download_worker(download_queue, write_queue, url, chunk_size): finished ...
from spendfrom import determine_db_dir class Options(object): def __init__(self): self.fromaddresses = list() self.toaddress = None self.new = False self.datadir = determine_db_dir() self.conffile = "crown.conf" self.fee = "0.025" self.amount = None s...
# Need to import path to test/fixtures and test/scripts/ # Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/' # # To run tests, you can do 'python -m testtools.run tests'. To run specific tests, # You can do 'python -m testtools.run -l tests' # Set the env variable PARAMS_FILE to point to your ini ...
# -*- coding: utf-8 -*- """ @author: Jatin Goel """ import os from flask import Flask APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = ( 'sqlite:///' f'{os.path.join(os.getcwd(), "database.db")}' ).replace("\\", "/") APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False APP.config['SECRET_KEY...
import unittest from code.core.enumerations import * import json class TestEnumBase(unittest.TestCase): @classmethod def dummy(cls, One = 1, Two = 2, Three = 3, Four = 4): pass # class TestEnumBase class TestEnum(TestEnumBase): @enumeration class ParsingSample: One = 1 ...
import json def load_expressions(): """Returns the expressions_file loaded from JSON""" with open('../data/BotCycle/expressions.json') as expressions_file: return json.load(expressions_file) def load_intents(): """Returns a list of names of the intents""" with open('../data/BotCycle/entities...
import os import h5py import numpy as np def copy_file_struct(f, hmap, fo): """ Iteratively copy a HDF5 file structure to a new file Arguments: -f : File from which to copy [OPEN HDF5 file handle] -hmap : Current file object of interest to copy from -fo : File to copy structure to ...
""" The child process. """ import time from asyncio import get_event_loop from typing import Callable, Optional from prompt_toolkit.eventloop import call_soon_threadsafe from .backends import Backend from .key_mappings import prompt_toolkit_key_to_vt100_key from .screen import BetterScreen from .stream import BetterS...
# Generated by Django 3.2 on 2022-02-19 13:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('products', '0005_remove_pr...
# -*- coding: utf-8 -*- import scrapy class AdzanItem(scrapy.Item): c = scrapy.Field() # city d = scrapy.Field() # day s = scrapy.Field() # shubuh t = scrapy.Field() # terbit z = scrapy.Field() # zuhur a = scrapy.Field() # ashr m = scrapy.Field() # maghrib i = scrapy.Field() # isya
import os import sys from os import path from flask import Flask from flask.ext.login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_recaptcha import ReCaptcha app = Flask(__name__) sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) #config for Forms, Register and FCM tokens a...
""" Standalone program to copy a file to azure, and return the URL to access the file. The idea is that you can run from the command line and escape to shell because sometimes the write takes awhile. Then look in the log file to get the URL for sharing. To test: run copy_to_azure To copy a file: python copy_to_azure...
#!/usr/bin/env python # Copied from https://github.com/xantares/mingw-ldd/blob/master/mingw-ldd.py # Modified to point to right prefix location on Fedora. # WTFPL - Do What the Fuck You Want to Public License from __future__ import print_function import pefile import os import sys def get_dependency(filename): ...
import torch import torch.utils.data as tud import numpy as np from utils import create_space import os # from PIL import Image, ImageFile import torchvision.transforms.functional as TF from collections import defaultdict import rasterio from rasterio.windows import Window import pyproj # ImageFile.LOAD_TRUNCATED_IMAG...
from distutils.core import setup setup( name='page-objects', version='1.1.0', packages=['page_objects'], url='https://github.com/krizo/page-objects.git', license='MIT', author='Edward Easton', author_email='eeaston@gmail.com', description='Page Objects for Python', requires=['selenium',...
from enum import Enum from typing import Union class CONNECTION_STYLE(Enum): angle = 1 angle_3 = 2 arc = 3 arc_3 = 4 bar = 5 def get_name(self) -> str: return { 'angle': 'angle', 'angle_3': 'angle3', 'arc': 'arc', 'arc_3': 'arc3', ...
# Librerias Future from __future__ import unicode_literals # Librerias Django from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import DetailView, ListView # Librerias de terceros from apps.website.submodels.post import PyPost def index(request):...
###################################################################################### ### This is a read-only file to allow participants to run their code locally. ### ### It will be over-writter during the evaluation, Please do not make any changes ### ### to this file. ...
print('Cliente da Vagalume API Iniciado: \n') nome_artista = input('Digite o nome de um Artista\n') import busca resultado = busca.artista(nome_artista) newinput = input('Digite:\n-pos: para saber a posição do artista no ranking\n-album: para saber o ultimo álbum do artista\n-frequencia: para saber as palavras mais...
import json import logging from homeassistant.components.http import HomeAssistantView from .util import DOMAIN, XIAOAI_API, matcher_query_state, find_entity from .xiaoai import (XiaoAIAudioItem, XiaoAIDirective, XiaoAIOpenResponse, XiaoAIResponse, XiaoAIStream, XiaoAIToSpeak, XiaoAITTSItem, ...
from apistar import Include, Route from settings.config import DEBUG from views.spider import callback from views.crate import crate_list, crate_detail routes = [ Route('/', 'GET', crate_list), Route('/crate/{crate_id}', 'GET', crate_detail), Route('/spider', 'POST', callback), ] if DEBUG: from apis...
#!/usr/bin/env python3 """Générateur de service AVAHI pour Freebox en mode bridge Lit les informations depuis http://mafreebox.freebox.fr/api_version Crée un fichier utilisable comme service avahi. Permet d’utiliser Freebox Compagnon avec une Freebox en mode Bridge : https://dev.freebox.fr/bugs/task/22301 """ i...
import matplotlib.pyplot as plt from matplotlib import ticker from matplotlib.colors import LogNorm import matplotlib import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') def Plotting(ebs,aps,Na,stime,mus,Np,Ne,Nmu): t,ax = plt.subplots(nrows =2, ncols = 1, figsize=(7,5)) #extent...
import re import math import operator import collections import unittest __version__ = (0, 0, 11) _non_word_re = re.compile(r'[^\w, ]+') __all__ = ('FuzzySet',) class FuzzySet(object): def __init__(self, iterable=(), gram_size_lower=2, gram_size_upper=3): self.exact_set = {} self.match_dict = c...
import requests import autoscaler.conf.engine_config as eng import os def remove_old_create_new(f_name, header): if os.access(f_name, os.R_OK): os.remove(f_name) write_to_file(header, f_name) def write_to_file(stats, f_name): csv = open(f_name, "a") csv.write(stats) def get_dpid(ip): ...
from pathlib import Path from math import ceil from sys import maxsize from pprint import pprint def parse_reactions(raw_text): reactions = dict() r_inputs = reactions["inputs"] = list() r_outputs = reactions["outputs"] = list() for line in raw_text.split("\n"): if len(line) == 0: c...
from dependency_injector.wiring import inject, Provide from ...container import Container from ...service import Service @inject def test_function(service: Service = Provide[Container.service]): return service
from .models import Podcasts,Votes,Comments,Profile from django import forms class RateForm(forms.ModelForm): class Meta: model=Votes exclude=['user','podcast'] class PostForm(forms.ModelForm): class Meta: model=Podcasts exclude=['user','design','usability','content'] class Re...
"""Test suite for the pyproject_cookiecutter_test package."""
import tensorflow as tf from einops.layers import tensorflow as tfeinsum from tensorflow.keras import initializers, layers from .layers import DiagonalAffine, PatchEmbed, PerSampleDropPath def mlp_block(x, hidden_units, out_units, activation, dropout_rate, name=None): x = layers.Dense(units=hidden_units, name=na...
#!/usr/bin/python # import RPi.GPIO as GPIO import spidev, time, math, random, logging class Gibson_LED_Driver: ## name constants ## proglist = {'static':0, 'fadeupdown':1, 'flyingcolor':2, 'throb':3, 'randomstatic':4, 'spin':5} colorlist = {'single':0, 'alternating':1, 'wide-alternating':2, 'colorwheel':...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import math from typing import Dict, Optional from tabulate import tabulate class StatsItem: de...
# encoding: utf-8 import copy import datetime from secrets import token_urlsafe from sqlalchemy import types, Column, Table, ForeignKey, orm from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.mutable import MutableDict import ckan.plugins.toolkit as tk from ckan.model import meta, User, DomainObjec...
# Copyright (c) 2021, NVIDIA 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
#!/usr/bin/env python import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup def read(*names, **kwargs): with open(os.path.join(os.path.dirname(__file__), *names), 'r') as fp: return fp.read() def find_version(*file_paths): versi...
import bcrypt from app.database import BaseMixin, db from app.serializer import ma class User(db.Model, BaseMixin): __tablename__ = 'user_table' userID = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, nullable=False) _password = db.Column(db.Binary(60)) email = db.Column...
import boto3 from .. import config # Module API def change_acl_on_s3(bucket, acl, path='', endpoint_url=None): def func(package): # Prepare client s3_url = endpoint_url or config.S3_ENDPOINT_URL s3_client = boto3.client('s3', endpoint_url=s3_url) # Change ACL # list_obj...
# Description: Count number of *.log files in current directory. # Source: placeHolder """ cmd.do('print("Count the number of log image files in current directory.");') cmd.do('print("Usage: cntlogs");') cmd.do('myPath = os.getcwd();') cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));') cmd.do('print("Number of ...
""" A terminal based ray-casting engine. 'esc' to exit 't' to turn off textures 'wasdqe' or arrow-keys to move 'space' to jump Depending on your terminal font, Renderer.ascii_map may need to be adjusted. If you'd like to make an ascii map more suitable to your terminal's font, check my Snippets repository for a scrip...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: edwardahn Evaluate a policy and publish metrics. """ import argparse import cProfile import pstats import sys import joblib import matplotlib.pyplot as plt import numpy as np from rllab.sampler.utils import rollout def profile_code(profiler): """ ...
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf from tensorflow.contrib import antares if tf.version.VERSION.startswith('2.'): tf = tf.compat.v1 tf.disable_eager_execution() from _common import * x = create_variable([64, 224, 224, 3], dtyp...
import datetime import sqlalchemy # noinspection PyPackageRequirements from models.model_base import ModelBase class Roll(ModelBase): __tablename__ = 'rolls' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True) created = sqlalchemy.Column(sqlalchemy.DateTime, default=datetim...
import json import os class Const: def __init__(self, logger = None): self.init_const() self.logger = logger controllerAddr = "NOT SET" controllerPort = "NOT SET" BASE_PATH = "/home/mmeinen/polybox/code/DC-MONDRIAN" #TODO: needs to be set whenever run somewhere else... (not elegant but ...
donations = [ { 'price': 1, 'thanks': True, 'col_size': 12, }, { 'price': 5, 'thanks': True, 'link': True, 'col_size': 12, }, { 'price': 10, 'thanks': True, 'link': True, 'status': 'SUPPORTER', 'col_size...
def merge_the_tools(string, n): out = [list(string)[k:k+n] for k in range(0,len(list(string)),n)] for x in out: print(''.join(sorted(set(x), key=x.index)))
# Write the pseudo code for a program that reads a target csv file and adds the correct typing to its contents. # After that it should transpose the resulting csv file
# Author: Simon Liedtke <liedtke.simon@googlemail.com> # # This module was developed with funding provided by # the Google Summer of Code (2013). """ Overview ^^^^^^^^ The database package exports the following classes and exceptions: :classes: - Database :exceptions: - EntryAlreadyAddedError ...
import numpy as np import torch import matplotlib.pyplot as plt from collections import OrderedDict def linear_size(output): output_size = np.array(output.size()) h, w = output_size[2], output_size[3] size = int(h * w) return size def count_parameters(model): return sum(p.numel() for p in model....
"""treelstm.py - TreeLSTM RNN models Written by Riddhiman Dasgupta (https://github.com/dasguptar/treelstm.pytorch) Rewritten in 2018 by Long-Huei Chen <longhuei@g.ecc.u-tokyo.ac.jp> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : losses.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 10/04/2018 # # This file is part of NSCL-PyTorch. # Distributed under terms of the MIT license. import torch import torch.nn as nn import torch.nn.functional as F import jactorch __a...
from typing import List class Solution1: def rotate(self, matrix: List[List[int]]) -> None: n = len(matrix) for i in range(n//2): for j in range(n-n//2): matrix[i][j], matrix[~j][i], matrix[~i][~j], matrix[j][~i] = \ matrix[~j][i], matrix[~i][~j], ma...
# -*- coding: utf-8 -*- from .darts import * from .priors import * from .posterior import * from .plotting import * from .utils import * from .plot_system_evolution import * __version__ = "1.1.0" # try: # __DART_BOARD_SETUP__ # except NameError: # __DART_BOARD_SETUP__ = False # # if not __DART_BOARD_SETUP__...
# Input: a comma-separated list of integers, representing a program and its data TEST = "1,9,10,3,2,3,11,0,99,30,40,50" with open('day02.txt', 'r') as infile: PUZZLE = infile.read() def part1(data): """Return the value at position 0 after running the program. Put 12 and 2 in positions 1 and 2 before run...
# -*- coding: utf-8 -*- """ Created on Mon Apr 29 18:28:55 2019 @author: yoelr """ from . import Facility from ..decorators import cost from thermosteam import Stream import numpy as np from ... import HeatUtility # from copy import copy __all__ = ('CoolingTower',) #'CoolingTowerWithPowerDemand') @cost('Flow rate', ...
# Evalúa qué puntos del grid del CRU corresponden a # la Cuenca del Valle de México. import os import pandas as pd import numpy as np import geoviews as gv import geopandas as gpd gv.extension("matplotlib") gv.output(size = 150) fdir_d = os.getcwd() + "/data/Cuencas/Regiones_Hidrologicas_Adminis...
# -*- coding: utf-8 -*- # Copyright (c) 2019-2021 Ramon van der Winkel. # All rights reserved. # Licensed under BSD-3-Clause-Clear. See LICENSE file for details. # importeer individuele competitie historie from django.core.management.base import BaseCommand from HistComp.models import HistCompetitie, HistCompetit...
#!/usr/bin/env python2 # Copyright (c) 2017, ESET # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of cond...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Joe Gao (jeusgao@163.com) import os import numpy as np from fastapi import FastAPI from predictor import main from storages import DIC_ZODB, milvusDB app = FastAPI() collection_cosine = 'dependency' partition_tags_cosine = '202103' collection_words = 'word...
# -*- coding: utf-8 -*- import json from flask.ext.script import Manager from app import app import config app.config.from_object(config.DevelopmentConfig) manager = Manager(app) @manager.command def index_data(): print("Indexing...") '''try: app.elasticsearch.indices.create(index='big-one', ignor...
# GOMC Example for the Gibbs Ensemble (GEMC) using MoSDeF [1, 2, 5-10, 13-17] # Note: In this specific example, we will be using the GEMC_NVT ensemble. # Import the required packages and specify the force field (FF) being used. # Note: For GOMC, the residue names are treated as molecules, so the residue names must...
class Solution: def largestValues(self, root): maxes = [] if not root: return maxes stack = [(root, 0)] while stack: node, level = stack.pop() if level >= len(maxes): # first time reaching this level] # append dire...
import math import pickle import torch from torch import distributed as dist from torch.utils.data.sampler import Sampler from torch.nn import SyncBatchNorm import numpy as np def get_rank(): if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 re...
""" Contains special test cases that fall outside the scope of remaining test files. """ import textwrap from unittest.mock import patch from flake8_type_checking.checker import ImportVisitor from flake8_type_checking.codes import TC001, TC002 from tests import REPO_ROOT, _get_error, mod class TestFoundBugs: def...
from .resources import BaseResource, BaseWithSubclasses class SwitchConnection: def __init__(self, resource, connection_alias): self.resource = resource self._connection_alias = connection_alias def __enter__(self): if issubclass(self.resource, BaseWithSubclasses): modifie...
# !/usr/bin/env python # -*- coding: utf-8 -*- """ Connector to generate connect, engine and session object based on parameters defined in config.yaml """ __author__ = 'Laurent.Chen' __date__ = '2019/7/15' __version__ = '1.0.0' import os import yaml from sqlalchemy import create_engine from sqlalchemy...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from app1.models import MyUser # Register your models here. admin.site.register(MyUser, UserAdmin)
class Solution: def countPairs(self, nums: List[int], k: int) -> int: result=0 for i in range(len(nums)-1): for j in range(i+1, len(nums)): if nums[i]==nums[j] and (i*j)%k==0: result+=1 return result
from django.conf.urls import url from ..views.admin import SubmissionRejudgeAPI, ClassSubmissionListAPI urlpatterns = [ url(r"^submission/rejudge?$", SubmissionRejudgeAPI.as_view(), name="submission_rejudge_api"), url(r"^class_submission/?$", ClassSubmissionListAPI.as_view(), name="class_submission_api"), ]
# -*- coding: utf-8 -*- """Core settings and configuration.""" # Part of Clockwork MUD Server (https://github.com/whutch/cwmud) # :copyright: (c) 2008 - 2017 Will Hutcheson # :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) from os import getcwd from os.path import join DEBUG = False TESTING =...
from FSMConfig import FSMConfig class GraphicsMouseManager: def __init__(self): self.leftDown = False self.middleDown = False self.rightDown = False self.gcLocal = FSMConfig() self.prevDragX = None self.prevDragY = None self.draggedObject = ...
#!/usr/bin/env python3.8 # Copyright 2021 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import json import os import sys def main(): parser = argparse.ArgumentParser() parser.add_argument( ...
# Angus Dempster, Francois Petitjean, Geoff Webb # # @article{dempster_etal_2020, # author = {Dempster, Angus and Petitjean, Fran\c{c}ois and Webb, Geoffrey I}, # title = {ROCKET: Exceptionally fast and accurate time classification using random convolutional kernels}, # year = {2020}, # journal = {Data Mi...
from django.contrib import admin from django.urls import path from . import views app_name = 'sbadmin' urlpatterns = [ path('table/', views.TableView.as_view(), name='table'), path('chart/', views.ChartView.as_view(), name='chart'), path('', views.IndexView.as_view(), name='index'), path('home/', view...
# -*- coding: utf-8 -*- # import bibliotek import os import datetime # zmienna-licznik przeskanowanych folderow i separator czysazdjecia = countope = 0 lines_seen = set() # aktualna data i godzina czasstart = datetime.datetime.now() print("~~~~~~START~~~~~~\t" + str(czasstart).split(".")[0]) # usunac jesli stosujem...
import os import sys import requests import ConnectWindow, ConnectedWindow, Driver from PySide2 import QtCore from PySide2.QtUiTools import QUiLoader from PySide2.QtWidgets import QApplication, QLineEdit, QPushButton, QTabWidget, QWidget class LoginWindow(QtCore.QObject): def __init__(self, ui_file, driver_window,...
__author__ = 'joon' import sys sys.path.insert(0, 'ResearchTools') from util.construct_filenames import create_token from util.construct_controls import subcontrol from util.ios import mkdir_if_missing, save_to_cache, load_from_cache from util.maths import Jsoftmax, proj_lp, proj_lf, compute_percentiles from util.dic...
"""Backend for rendering multi-frame images using PIL. These are internal APIs and subject to change at any time. """ try: import PIL except (ImportError): PIL = None from .shared import Backend, BackendError, check_output class PILMultiframeBackend(Backend): """Backend for rendering multi-frame images...
import jwt.exceptions import pytest from okay.jwt import main, decode __author__ = "Cesar Alvernaz" __copyright__ = "Cesar Alvernaz" __license__ = "MIT" from fixtures.jwt_fixtures import VALID_TOKEN, SECRET, \ EXPECTED_TOKEN_PAYLOAD, INVALID_SECRET, VALID_RS256_TOKEN, \ EXPECTED_TOKEN_RS256_PAYLOAD def test...
import os,re, sys from byo.track import Track, load_track from byo.io.genome_accessor import GenomeCache, RemoteCache from byo.io.annotation import AnnotationAccessor #from byo.io.lazytables import NamedTupleImporter as Importer import byo.config import logging class LazyTranscriptLoader(object): def __init__(sel...
# -*- coding: utf-8 -*- # @Time : 2018/5/28 22:03 # @Author : ddvv # @Site : http://ddvv.life # @File : xiaomistorespider.py # @Software: PyCharm """ 第三方依赖库: Crypto 功能: 1. 获取小米商店应用评论 消息说明: 1. "AppSpider-0010-001" : 应用评论 """ import scrapy from appspider.commonapis import * CONST_INFO = { 'app_na...
#!/usr/bin/python # Simple tcp fuzz against a target import socket from sys import exit,argv if len(argv) < 2: print "Performs a simple fuzz against a target" print "Usage: %s <Target IP Address/hostname> <Target Port>" % str(argv[0]) exit(1) #Create an arry of buffers, from 10 to 2000, with increments of 20. buf...
#!/usr/bin/python import sys import re threshold = float(sys.argv[1]) tp = 0 fp = 0 fn = 0 typePr = {} for line in sys.stdin: if re.search(r'^\d', line): fields = line.rstrip('\n').split(' ') gold = fields[1] (predicted, conf) = fields[2].split(':') print "%s\t%s\t%s" % (gold, p...
import datetime as dt import re from collections import namedtuple from pathlib import Path import pytest import ravenpy from ravenpy.config.commands import ( BasinStateVariablesCommand, EvaluationPeriod, GriddedForcingCommand, HRUStateVariableTableCommand, ) from ravenpy.config.rvs import OST, RVC, R...
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import nowdate, get_last_day, add_days from erpnext.assets.doctype.asset.test_asset import create_asset_data from erpnex...
import logging import os from ...utils import import_export_content from ...utils import paths from ...utils import transfer from kolibri.core.tasks.management.commands.base import AsyncCommand logger = logging.getLogger(__name__) class Command(AsyncCommand): def add_arguments(self, parser): node_ids_h...
import os import mimetypes import json from plantcv.plantcv import fatal_error # Process results. Parse individual image output files. ########################################### def process_results(job_dir, json_file): """Get results from individual files. Parse the results and recompile for SQLite. Args: ...
import logging import traceback import urllib import datetime import mimetypes import os import sys import zlib import gzip import StringIO import json from pylons import request, response, session, tmpl_context as c from pylons import app_globals from pypesvds.lib.base import BaseController, render from pypesvds.lib...
# Generated by Django 2.0.2 on 2018-05-16 11:02 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('project', '0019_auto_20180516_1034'), ] operations = [ migrations.AlterFie...
from typing import Tuple, Iterable from rlp.utils import str_to_bytes from state.util import utils from storage.kv_store import KeyValueStorage # log = get_logger('db') databases = {} class KeyValueStorageInMemory(KeyValueStorage): def __init__(self): self._dict = {} def get(self, key): i...
#!/usr/bin/env python # coding: utf-8 ## define the convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(...
from .CTCModel import *
''' Module containing all the requisite classes to perform test steps. Adding new actions ------------------- Creating new simple actions in the code is designed to be fairly straightforward, and only requires three steps: 1. Add an entry for the action on the ``enums`` module 2. Create a function to perform the act...