content
stringlengths
5
1.05M
import pandas as pd import numpy as np import skopt import copy import logging import math import os import random import typing import time import warnings from configtune.base_tuner import TuningBase from configtune.config_mapping import set_by_path, get_paths from skopt.space import Real, Integer from skopt.utils ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import mimetypes from sys import argv from cleave.http import HttpServer from cleave.http.handler import HandleRequest from cleave.http.response import Response from cleave.debug import Log class FileStorage(HandleRequest): BASE_DIR = None BASE_FILE = No...
# -*- coding: utf8 -*- """ clikraken.api.public.rates This module queries pulls the latest change rates for a currency pair. Licensed under the Apache License, Version 2.0. See the LICENSE file. """ from forex_python.converter import CurrencyRates def rates(args): """Get the exchange rate for a given currency...
from django.apps import AppConfig class ProductappConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "ProductApp" def ready(self): import ProductApp.signals # noqa: F401
#insertion query for new movie id, movie name and rating id (RatingID joins with Rating table) insert_movie = '''INSERT INTO Movies (MovieID, Title, RatingID) VALUES(%s, %s, %s);''' #query not currently used, retrieves all rows from movies table select_all_movie = "SELECT * FROM Movies;" #retrieves all fields from mo...
import utils async def run(client, message, args, prefix, db): if message.author.guild_permissions.manage_messages: gag = message.guild.get_role(751514494307663949) uye = utils.get_user(message.guild, args[0]) if not uye: raise Exception(f"Üye '{args[0]}' bulunamadı") await uye.ad...
import numpy import theano import theano.tensor as T from mlpv import * if __name__ == '__main__': ''' train_mlp(learning_rate=0.01, n_epochs=10, batch_size=500, n_hidden=[500], patchSize=19, trainsamples=1000, val_samples=10000, test_samples=1000, doResample=False, validation_frequency = 1, activatio...
DESTINATION_FOLDER: str = 'Downloads/images/full'
import json from pathlib import Path import re import csv def readj(p): # return json.loads(Path(p).read_text('utf-8', errors='ignore')) return json.loads(Path(p).read_text('utf-8', errors='replace')) def get_id(s): s = Path(s).stem r = r'_(?P<id>.*)(_[abc])?(\.*)' m = re.search(r,...
""" Run a Single Task """
''' Collection of popup widgets @author Kyriakos Zarifis ''' from PyQt4 import QtGui, QtCore import os class TsComboBox(QtGui.QDialog): ''' Popup a ComboBox for timestamp selection ''' def __init__(self, parent=None): self.parent = parent QtGui....
import game import pygame from pygame.locals import * class Resources: def cambiar(self,imagen): sheet = game.load_image(imagen) rects = [pygame.Rect(112,2,26,40), pygame.Rect(112,2,26,40), pygame.Rect(112,2,26,40), pygame.Rect(4,4,30,38), ...
import sys, os import unittest sys.path.insert(0, os.path.dirname(__file__)) import test_hashes if __name__ == '__main__': loader = unittest.TestLoader() suites = [loader.loadTestsFromTestCase(test_hashes.TestHashFunctions)] test_suite = unittest.TestSuite(suites) unittest.TextTestRunner().run(test_s...
from django.conf import settings from moj_irat.healthchecks import HealthcheckResponse, JsonUrlHealthcheck, \ UrlHealthcheck, registry from zendesk_tickets.client import zendesk_auth registry.register_healthcheck(JsonUrlHealthcheck( name='api', url='%s/healthcheck.json' % settings.API_URL, value_at_js...
from ._factorize import factorize
import torch t1 = torch.Tensor([5,2,6,7]) t2 = torch.Tensor([9,3,6,1]) l1 = [5,2,6,7] l2 = [9,3,6,1] print(t1+t2) print(l1+l2) conc = torch.stack((t1,t2), dim=0) print(conc) t3 = torch.rand((4,2)) print(t3.shape) print(conc.shape) # Matrix Multiplication mult = torch.mm(conc, t3) print(mult) # Slicing print(mult[...
import os import numpy as np import argparse import os.path as osp import json from tqdm import tqdm from mmcv import mkdir_or_exist IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] def is_image_file(filename): return any(filename.endswith(extension) ...
from typing import Dict from typing import List from datetime import datetime from botocore.paginate import Paginator class DescribeFleetAttributes(Paginator): def paginate(self, FleetIds: List = None, PaginationConfig: Dict = None) -> Dict: pass class DescribeFleetCapacity(Paginator): def paginate(...
import argparse import json from btlewrap.bluepy import BluepyBackend from miflora import miflora_scanner from miflora.miflora_poller import MiFloraPoller, \ MI_CONDUCTIVITY, MI_MOISTURE, MI_LIGHT, MI_TEMPERATURE, MI_BATTERY def poll_miflora(mac): """Poll data from specific MiFlora sensor.""" poller = Mi...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: nordicsemi/dfu/dfu-cc.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import...
import argparse import errno import importlib import logging import os import typing from components import CheckSolver logging.basicConfig( format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO ) LOGGER = logging.getLogger() SOLUTIONS_DIR = os.environ["SOLUTIONS_DIR"] ATTRIBUTES...
#!/usr/bin/env python # This is a single-line comment print("Comments are useful.") """ This is a multi-line Comment which spans many lines """ print("You should comment your code.")
# Generated by Django 2.2.10 on 2021-10-13 01:47 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Pool', fields=[ ('id', models.AutoField(au...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'UIBase.ui' # # Created by: PyQt5 UI code generator 5.7.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): ...
from engine.controllers.factories import ShipPartControllerFactory from engine.models.factories import ShipPartModelFactory from engine.models.ship_parts import ThrusterModel controller_factory = ShipPartControllerFactory() model_factory = ShipPartModelFactory() class TestHorizontalEngineAt135DegreesOff(object): ...
"""Data preprocessing.""" import os import pickle from typing import Any, Tuple import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split def load_pickle(f: str) -> Any: """Load a pickle file. Parameters: f: the pickle...
class ListOrdersController: def __init__(self, list_orders_use_case): self.list_orders_use_case = list_orders_use_case def route(self, body): response = self.list_orders_use_case.list() return response
from __future__ import print_function from argparse import ArgumentParser import json import logging import os from squad_evaluate_v1_1 import evaluate def evaluate_squad(dataset_file, prediction_file): logging.info('\tEvaluating squad predictions in %s' % prediction_file) with open(dataset_file) as datas...
#!/usr/bin/env python # Copyright 2015 University of Chicago import argparse import datetime import grp import os import pwd import sys import elasticsearch import elasticsearch.helpers import pytz import xattr ES_NODES = ['uct2-es-head.mwt2.org:9200', 'uct2-es-door.mwt2.org:9200'] TZ_NAME = "US/Central" TIMEZONE =...
import collections import logging from ..geometry import Position, Size, Rectangle, WithSizeMixin from .core import Generator, Digable from .bsp import BSPGenerator log = logging.getLogger(__name__) class Room(Digable): """Rectangular room. Left and top border are considered walls, so rooms can share wa...
#!/usr/bin/env python3 from setuptools import setup, find_packages with open("README.md", "r") as readme_file: readme = readme_file.read() requirements = [ "requests", "validators" ] setup( name="fisherman", version="1.0.1", author="Edward", author_email="14011954+0xedwar...
"""Helper module for reading utf-8 or ANSI encoded files. For further information see https://github.com/peter88213/PyWriter Published under the MIT License (https://opensource.org/licenses/mit-license.php) """ def read_file(inputFile): """Read a utf-8 or ANSI encoded text file. Positional argum...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import logging class Vocabulary(object): EOL_ID = 2 # end of line _EOL = "_EOL" PAD_ID = 1 _PAD = "_PAD" UNK_ID = 0 _UNK = "_UNK" def __init__(self, vocabulary_path): self.vocab = None self.rev_vocab = None s...
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from aws import Action as BaseAction from aws import BaseARN service_name = 'AWS Elemental MediaConnect' prefix = 'mediaconnect' class Action(BaseAction): def __init__(self, action=None): s...
#!/usr/bin/env python # _*_ coding: utf-8_*_ # # Copyright 2016 7x24hs.com # thomas@7x24hs.com # # 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...
import boto3 import os from botocore.exceptions import ClientError def get_stack_outputs(): """ Gets asetuapi stack outputs if it exists """ cfn = boto3.client("cloudformation") try: asetuapi_stack = cfn.describe_stacks(StackName="asetuapi") except ClientError: print( ...
#!/usr/bin/env python3 import os import sys from itertools import zip_longest from platform import release import yaml from jinja2 import Environment, FileSystemLoader, Template, TemplateNotFound from git import Repo, GitConfigParser, Remote, Blob, Object class RestrictedFileSystemLoader(FileSystemLoader): def ...
''' 2. 定义一个列表操作类:Listinfo 1) 方法: 1- 列表元素的添加 (添加的元素必须是字符串或者整型数) 2- 取值 3- 合并 4- 删除并返回最后一个元素 ''' class Listinfo(object): def __init__(self, ls): self.__ls = ls def addElm(self, elm): if isinstance(elm, (int, str)) == False: raise ValueError("你所插入列表的元素类型不符合整型或者字符串要求") self.__ls.ap...
import os # base directory basedir = os.path.abspath(os.path.dirname(__file__)) # database class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'todolist.db') SQLALCHEMY_TRACK_MODIFICATIONS = False
# -*- coding: utf-8 -*- """ """ import os import nose from nose import tools import numpy as np from numpy import testing # dynfunconn from dyconnmap import sliding_window_indx, sliding_window from dyconnmap.fc import PLV def test_sliding_window(): rng = np.random.RandomState(1) data = np.load("../example...
# 3rd party import unittest # Package level import world as world_helper # Note that I'm not using cell_states here... If I change a state value that # could break all these tests. However I think the current way reads better. # Leaving it as is for now. class GetNeighbors(unittest.TestCase): def test_center_cel...
# Hands-on Topic 5 #Student: Jignesh Chaudhary, Student id:197320 # 5.3 Determine the real root of f (x) = -25 + 82x - 90x^2 + 44x^3 - 8x^4 + 0.7x^5: # (a) Graphically. # (b) Using bisection to determine the root to es = 10%. Employ initial guesses of xl = 0.5 and xu = 1.0. # (c) Perform the same computation as in...
import numpy as np # type: ignore import tensorflow as tf # type: ignore from numpy.testing import assert_array_almost_equal # type: ignore from pokermon.features.examples import ( make_forward_backward_example, make_forward_example, ) from pokermon.model import heads_up from pokermon.poker import result fr...
""" Написать функцию, которая используя модуль requests скачивает файл сохраняет его на файловой системе, функция имеет два параметра: ссылка на файл и имя на файловой системе. В качестве примера ссылки на файл можно использовать лицензию из ГитХаба из вашего репозитория: https://raw.githubusercontent.com/manti-by/less...
from ...connection_cursor import cur def id_for_fund(fund): """Retrieves the integer identification number for the specified fund. Parameters ---------- fund: String. The fund whose integer identifier is requested. """ cur.execute("SELECT id FROM funds WHERE fund='{}'".format(fund)) ...
#!/usr/bin/env python import os, sys import re from itertools import izip_longest import random import csv import logging import numpy as np import data_utils from data_utils import tokenize, tokenize_hanzi from zipfile import ZipFile from data_utils import get_file, to_one_hot, syslogger download_all_csvs = False # ...
import numpy as np from scipy import signal from margrie_libs.margrie_libs.signal_processing.filters import box_smooth, diff from margrie_libs.margrie_libs.signal_processing.measures import get_sd from margrie_libs.margrie_libs.signal_processing.thresholding import find_levels, find_level_increase from margrie_l...
from django.conf import settings from django.conf.urls import url from django.urls import include, path from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views from rest_framework import routers, permis...
import json import logging import subprocess import time import string import random from haiku_node.config.config import UnificationConfig from haiku_node.network.eos import get_cleos log = logging.getLogger(__name__) UNIF = 0.03 DATA_PROVIDER = 0.3 END_USERS = 0.67 class UndRewards: def __init__(self, uapp_a...
from __future__ import division from classification import Classification from metrics_reduced import SpanishTools from folksonomy import folksonomy classifier = Classification() spanish_tools = SpanishTools() class JSONClassificationResponse: """ Classifies all comments in a JSON file: ------------------------...
from django.urls import reverse from rest_framework import status from test_helpers.clients import DataTestClient class DataWorkspaceTests(DataTestClient): def test_control_list_entries(self): url = reverse("data_workspace:dw-control-list-entries-list") expected_fields = ("id", "rating", "text", ...
import torch import torch.nn as nn # Part AutoEncoder based on ImNet ############################################################################## class Encoder3D(nn.Module): def __init__(self, n_layers, ef_dim=32, z_dim=128): super(Encoder3D, self).__init__() model = [] in_channels = 1 ...
import torch import numpy as np import xarray as xr import holoviews as hv from holoviews import opts from combine1d.core.arithmetics import RMSE, mean_BIAS, max_dif from combine1d.core.exception import MaxCalculationTimeReached import os hv.extension('matplotlib') class DataLogger(object): def __init__(self, be...
""" PASSENGERS """ numPassengers = 15378 passenger_arriving = ( (3, 4, 4, 7, 2, 3, 1, 1, 1, 2, 2, 0, 0, 2, 3, 2, 5, 3, 1, 2, 2, 2, 0, 0, 0, 0), # 0 (5, 6, 6, 4, 1, 0, 1, 3, 0, 1, 0, 1, 0, 1, 7, 3, 2, 7, 1, 2, 1, 2, 0, 0, 0, 0), # 1 (2, 6, 4, 3, 1, 2, 1, 3, 1, 0, 2, 0, 0, 5, 1, 4, 4, 4, 0, 1, 3, 2, 1, 2, 2, 0), ...
# -*- coding: utf-8 -*- import unittest from six import with_metaclass from .meta import MetaTestSequence tests = [ { "input": "Title", "expected": ["Artist", "Title"], "options": {"defaultArtist": "Artist"}, } ] class TestSequence(with_metaclass(MetaTestSequence, unittest.TestCase)):...
import numpy as np from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils from chainer import Link, Chain, ChainList import chainer.links as L import chainer.functions as F from lib.utils import * from lib.functions import * import time class Darknet19(Chain): """ Darknet...
import numpy as np import pandas as pd from glob import glob dfs = list() directoryPath = 'data/raw/data_for_november_2019_evaluation/south_sudan_data/IMF/' filenames = glob(directoryPath + 'imf*.xlsx') for filename in filenames: df = pd.read_excel(filename) df = df.transpose() index_val = df.index....
from .conv import Conv2d from .functional import relu from .linear import Linear __all__ = ["relu", "Linear", "Conv2d"]
def conduit_login(driver): driver.find_element_by_xpath('//a[contains(text(),"Sign in")]').click() driver.find_element_by_xpath('//input[@placeholder="Email"]').send_keys("Aniko1@gmail.com") driver.find_element_by_xpath('//input[@placeholder="Password"]').send_keys("Tananiko-1") driver.find_element_by_...
import sys def isSquare(parts, x, y, n): a = y * 5 + x b = a + n c = a + 5 * n # top line for i in [[a + x, a + 1 + x] for x in range(0, n)]: if i not in parts and i[::-1] not in parts: return False # bottom line for i in [[c + x, c + 1 + x] for x in range(0, ...
import os import imageio import numpy as np import torch import torchvision import clip from skimage import exposure from dd_ffm.lib import Siren, get_mesh_grid, fourierfm, slice_images clip_normalize = torchvision.transforms.Normalize((0.48145466, 0.4578275, 0.40821073), ...
# 测试&结果的预测&实际结果 car = 'subaru' print("Is car == 'subaru'? I predict True.") print(car == 'subaru') print("\nIs car == 'audi'? I predict False.") print(car == 'audi') car = 'Aston Martin' print("\nIs car == 'bwm'? I predict False.") print(car == 'bwm') print("\nIs car == 'Aston Martin'? I predict True.") print(car ==...
#!/usr/bin/env python from __future__ import print_function import os import logging import select import shutil import subprocess import sys import threading import time import unittest from yumrepos.app import create_application from yumrepos.fs_backend import FsBackend def call(popenargs, logger, stdout_log_leve...
from . import ColorSensor, MotorController, MotorMixer, Pilot, Odometry
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from rbb_swagger_server.models.base_model_ import Model from rbb_swagger_server import util class FileSummary(Model): """NOTE: This class is auto generated by the...
from django.apps import AppConfig class ChallengesConfig(AppConfig): name = "challenges"
# -*- coding: utf-8 -*- """ Input plug-in for a voronoi calculation. """ from aiida.orm.calculation.job import JobCalculation from aiida.common.utils import classproperty from aiida.common.exceptions import (InputValidationError, ValidationError) from aiida.common.datastructures import (CalcInfo, CodeInfo) from aiida....
# -*- coding: utf-8 -*- from resources.properties import AVAILABLE_HELP_COMMANDS from src.logger import logger from strings.help_command import INCORRECT_HELP_FORMAT, MOVIES_COMMAND_TEXT, HELP_COMMAND_TEXT, SERIES_COMMAND_TEXT, START_COMMAND_TEXT from strings.help_command import STATUS_COMMAND_TEXT, SUBTITLES_COMMAND_...
import FWCore.ParameterSet.Config as cms from Configuration.Geometry.GeometryRecoDB_cff import * from Configuration.AlCa.GlobalTag_condDBv2 import GlobalTag from Configuration.StandardSequences.MagneticField_cff import * from RecoVertex.BeamSpotProducer.BeamSpot_cfi import * from RecoTracker.TrackProducer.TrackRefitt...
TEXT_URLS = "ftp://ftp.wwpdb.org/pub/pdb/derived_data/pdb_seqres.txt" regex_type = "protein_patterns"
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class User(AbstractUser): USER_TYPE_CHOICES = ( (0, 'admin'), (1, 'Operationnel'), ...
# -*- coding: utf-8 -*- """ Created on Sun Sep 6 17:03:42 2020 @author: gilta """ import os.path as pth import yaml with open('../config.yaml', 'r') as fp: config = yaml.load(fp, yaml.FullLoader) path = pth.dirname(pth.abspath(__file__))[:-3] + '/' import numpy as np import pandas as pd import xgboos...
""" RENDER """ render_camera = 'cam1' render_lights = '' """ MATERIAL """ mat = 'constant1' mat_color = '' """ INSTANCES """ inst_state = 0
# Copyright 2019 Stanford University # Copyright 2016, Yahoo Inc. # Licensed under the terms of the Apache License, Version 2.0. See the LICENSE file associated with the project for terms. class Operation(object): """ This is an abstract class representing a data transformation. To use this, please inheri...
# Copyright (c) 2021 - present, Timur Shenkao # 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 appl...
from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings app_name='rankestimate' urlpatterns = [ path('marks', views.MarksAPIView.as_view()), path('marks/<str:pk>', views.MarksAPIView.as_view()), # to capture our ids path('ran...
import dgl import dgl.function as fn from dgl.nn.pytorch.softmax import edge_softmax import numpy as np import torch as th import torch.nn.functional as F import torch.nn as nn from .config import cfg from .utils import * class LGCNLayer(nn.Module): def __init__(self): super().__init__() d_x = cf...
from __future__ import print_function import argparse import sys import torch.nn.functional as F import torch.optim as optim from basic_opt import * from models import EmbeddingImagenet, EmbeddingOmniglot, MetricNN sys.path.append(os.getcwd()) from dataset.data_loader import data_loader from torch.optim.lr_scheduler...
# Generated by Django 3.0.5 on 2020-04-19 10:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('article', '0004_comment_article'), ] operations = [ migrations.RenameField( model_name='comment', old_name='content', ...
class RescaleDatasetService: def __init__(self, data, scale): self.data = data self.scale = scale def call(self): scaled_data = [] for row in self.data: scaled = [self.scale[i] * row['input'][i] for i in range(len(self.scale))] scal...
class ProfileMixin(object): """ mixin for user model with queryset methods """ def get_user_by_email(self, email): return self.get(email=email) def get_user_by_username(self, username): return self.get(username=username) def get_user_by_emaillist(self, emails): ...
def foo(a, test=None, *er): return test
from flask import render_template, request, redirect, jsonify from app import app from app.proto import API_pb2 from grpc import RpcError @app.route('/send_message', methods=['POST']) def send_message(): from app import stub data = request.json pb_message = API_pb2.Message() pb_message.user.username ...
# -*- coding: utf-8 -*- """ URL config for the ds (main) app """ from django.urls import path from ds import views app_name = 'ds' urlpatterns = [ path('', views.index, name='index'), path('dashboard/', views.dashboard, name='dashboard'), path('about/', views.about, name='about'), path('process/', v...
# -*- coding: utf-8 -*- # Copyright 2019 SAMITorch Authors. All Rights Reserved. # # # Licensed under the MIT License; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # # https://opensource.org/licenses/MIT # # # Unless required by applicable ...
from unittest import TestCase import numpy as np import time from candidates import initialize_candidates from solver import solve class TestSolver(TestCase): def setUp(self) -> None: self.num_tests = 10000 sudokus = np.load("../data/sudoku.npz") self.puzzles = sudokus["puzzles"] ...
import pytest @pytest.mark.e2e @pytest.mark.parametrize("lossless_priorities", [[3, 4]]) def test_pfc_pause_e2e(api, settings, utils, lossless_priorities): """ Configure ports where, - tx port can only respond to pause frames for `lossless_priorities` - rx port is capable of sending pause frames for a...
# -*- coding: utf-8 -*- { 'name': 'Marketing', 'version': '1.1', 'depends': ['base', 'base_setup'], 'author': 'OpenERP SA', 'category': 'Hidden/Dependency', 'description': """ Menu for Marketing. =================== Contains the installer for marketing-related modules. """, 'website': ...
import visa # open scope rm = visa.ResourceManager() scope = rm.open_resource( < visa resource string > ) print(scope.query('*idn?')) scope.timeout = 10000 scope.write('*rst') # reset scope.query('*opc?') # sync scope.write('autoset EXECUTE') # autoset scope.query('*opc?') # sync frameSize = scope.query('horizon...
import argparse if __name__=='__main__': parser = argparse.ArgumentParser('Generate all possible peak pairs on the same chromosome ' + 'and have a distance within [5Kb, 2Mb] from a BED file') parser.add_argument('input', help='The input file in BED ...
import threading import random import time import datetime import pickle, os class session: def __init__(self, sesid, timeout = 259200): self.id = sesid self.timeout = timeout self.idle = datetime.datetime.now() self.data = {} def setData(self, param, value): self.data[pa...
from db import get_db, close_db app.app_context(app=db) close_db() db=get_db() db.execute('SELECT * FROM user')
# -*- coding: utf-8 -*- # @Time : 2021/9/22 8:53 # @Author : Gang # @File : ivDataAnalysis.py import time from PyQt5.QtCore import QObject, pyqtSignal from multiprocessing import cpu_count, Pool from gangLogger.myLog import MyLog from ivAnalysisConst import * from ivDataProcessUtils import IVDataProcessUtils as D...
""" photos_fetched null Revision ID: 54627e8199c9 Revises: 1259f25794b5 Create Date: 2016-01-28 21:11:56.199158 """ # revision identifiers, used by Alembic. revision = "54627e8199c9" down_revision = "1259f25794b5" from alembic import op import sqlalchemy as sa def upgrade(): op.alter_column( "rides", ...
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # DLink.DxS.get_oam_status # --------------------------------------------------------------------- # Copyright (C) 2007-2015 The NOC Project # See LICENSE for details # -------------------------------------------------------...
#coding:utf-8 """人口数据 数据来源: 国家统计局 <http://data.stats.gov.cn/easyquery.htm?cn=C01> """ import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('population.csv', sep='\t') df['增长率'] = (df['年末总人口(万人)']/df['年末总人口(万人)'].shift(-1) - 1)*100 df['性别比'] = df['男性人口(万人)'] / df['女性人口(万人)'] df['城镇化率'] = (df['城镇人口(万人)'...
from mock import patch from nose.tools import * # noqa import arrow from tests import PMGTestCase from pmg import app from pmg.models import db, CommitteeMeeting from pmg.search import Search from pyelasticsearch import ElasticSearch class TestSearch(PMGTestCase): @patch.object(ElasticSearch, 'bulk_index') ...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def isBST(root): return isBSTUtil(root, INT_MIN, INT_MAX) def isBSTUtil(node, low, high): if node is None: return True if node.data < low or node.data > high: return False ...
from juriscraper.opinions.united_states.state import nm class Site(nm.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.url = 'https://nmonesource.com/nmos/nmca/en/nav_date.do?%s' % self.IFRAME
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hwtLib.peripheral.displays.segment7 import Segment7 from hwtLib.examples.base_serialization_TC import BaseSerializationTC class Segment7TC(BaseSerializationTC): __FILE__ = __file__ def test_toVhdl(self): self.assert_serializes_as_file(Segment7(), "...