content
stringlengths
0
894k
type
stringclasses
2 values
# Copyright (c) 2016, Ethan White # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and...
python
from validator.rule_pipe_validator import RulePipeValidator as RPV from validator import rules as R from validator import Validator, validate, validate_many, rules as R def test_rpv_001_simple(): data = "10" # with integer rules = [R.Integer(), R.Size(10)] rpv = RPV(data, rules) assert rpv.execut...
python
import os import random class Hangman(): def __init__(self): self.word = self.pick_random_word() self.word = self.word.upper() self.hidden_word = ["-" for character in self.word] self.word_length = len(self.word) self.used_letters = [] self.running = True ...
python
def test_add_pet(client, jwt): r = client.post( "/pets", json=dict( pet_type="cat", name="tospik", breed="persian", owner="emreisikligil" ), headers=dict(Authorization=f"Bearer {jwt}") ) assert r.status_code == 201 body = r....
python
import asyncio import youtube_dl import urllib.request import datetime from bot_client import * global queue queue = [] global nowPlaying nowPlaying = [] global ytdl_opts ytdl_opts = { 'format': 'bestaudio/best', #'ignoreerrors': True, #'no_warnings': True, #'debug_pr...
python
# --- import -------------------------------------------------------------------------------------- import os import numpy as np import WrightTools as wt from . import _pulse from ._scan import Scan # --- define -------------------------------------------------------------------------------------- here = os.pa...
python
import torch from torch import nn from torch.nn import functional as F from typing import List from resnet_layer import ResidualLayer class ConvDecoder(nn.Module): def __init__(self, in_channels: int, embedding_dim: int, hidden_dims: List = [128, 256], ...
python
from dassl.engine import TRAINER_REGISTRY from dassl.engine.trainer import TrainerMultiAdaptation from dassl.data import DataManager from dassl.utils import MetricMeter from torch.utils.data import Dataset as TorchDataset from dassl.optim import build_optimizer, build_lr_scheduler from dassl.utils import count_num_para...
python
''' A data model focused on material objects. ''' import synapse.lib.module as s_module class MatModule(s_module.CoreModule): def getModelDefs(self): modl = { 'types': ( ('mat:item', ('guid', {}), {'doc': 'A GUID assigned to a material object.'}), ('mat:spec', (...
python
from .test_utils import * print('#############################################') print('# TESTING OF MainDeviceVars MODEL FUNCTIONS #') print('#############################################') @tag('maindevicevars') class MainDeviceVarsModelTests(TestCase): def setUp(self): from utils.BBDD import...
python
from flask import request from .argument import ListArgument class QueryStringParser: """ A class to parse the query string arguments""" @staticmethod def parse_args(qs_args_def): """ Parse the query string """ qs_args_dict = QueryStringParser.args_def_to_args_dict(qs_args_def) ...
python
from machine import Pin, Timer import utime SOUND_SPEED = 0.0343 # in second CM_TO_INCH = 0.393701 CM_TO_FEET = 0.0328084 trigger = Pin(16, Pin.OUT) echo = Pin(17, Pin.IN) def get_distance(timer): trigger.high() utime.sleep(0.0001) trigger.low() start = 0 stop = 0 while echo.value()...
python
# Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license from ..postprocessing import multiclass_postprocess import numpy as np def test_multiclass_postprocess_smoke(): n = 1000 d = 2 k = 3 b = 10 X_binned = np.random.randint(b, size=(d, n)) feature_graphs = []...
python
import requests import base64 from datetime import datetime from datetime import timedelta from collections import UserString class RefreshingToken(UserString): def __init__(self, token_url, client_id, client_secret, initial_access_token, initial_token_expiry, refresh_token, expiry_offset=60, p...
python
#FLM: AT Font Info: Andres Torresi #configurar nombreFamilia='Tagoni' nombreDisenador='Andres Torresi' emailDisenador='andres@huertatipografica.com.ar' urlDisenador='http://www.andrestorresi.com.ar' urlDistribuidor='http://www.huertatipografica.com.ar' year='2012' ## from robofab.world import CurrentFont # all the ...
python
#import sys import select, queue from .pool import Pool from .io import open_listenfd, sys def main(*args, **kwargs): """ @params: init project """ if len(sys.argv) != 2: print("Usage: %s ports", sys.argv[0]) sys.exit(1) assert len(sys.argv) != 2 port = sys.argv[1] #type: in...
python
# -*- coding:utf-8 -*- # coding=<utf8> from django.db import models # Модели для логирования действий пользователей с активами class Logging(models.Model): user = models.CharField(max_length=140) request = models.TextField(blank = True, null = True) goal = models.TextField(blank = True, null = True) d...
python
#%% [markdown] # # Basic of Beamforming and Source Localization with Steered response Power # ## Motivation # Beamforming is a technique to spatially filter out desired signal and surpress noise. This is applied in many different domains, like for example radar, mobile radio, hearing aids, speech enabled IoT devices. #...
python
import os import shutil import click from datetime import datetime, timedelta from flask import current_app as app from sqlalchemy.sql.expression import false from alexandria.settings.extensions import db __author__ = 'oclay' @click.command() @click.option('--username', prompt=True, help='The username for the admin...
python
#!/usr/bin/python from singularity.package import calculate_similarity from singularity.utils import check_install import pickle import sys import os pkg1 = sys.argv[1] pkg2 = sys.argv[2] output_file = sys.argv[3] # Check for Singularity installation if check_install() != True: print("You must have Singularity i...
python
#!/usr/bin/env python """odeint.py: Demonstrate solving an ordinary differential equation by using odeint. References: * Solving Ordinary Differential Equations (ODEs) using Python """ from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt # pylint: disable=invalid-name # Solve y''(t...
python
print('-='*20) print('Analisador de Triângulos') print('-='*20) r1 = float(input('Primeiro Segmento: ')) r2 = float(input('Segundo Segmento: ')) r3 = float(input('Terceiro Segmento: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os segmentos acima PODEM formar um triângulo.') else: print('Os segm...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This command generates cs_pb2.py and cs_pb2_grpc.py files from cs.proto. These files are necessary for the execution of gRPC client and gRPC control server. """ from subprocess import call call("python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. cloud...
python
from .account import GroupSerializer, UserSerializer from .resource import ResourceSerializer __all__ = ["UserSerializer", "GroupSerializer", "ResourceSerializer"]
python
#!/usr/bin/python3.7 # Copyright 2020 Aragubas # # 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...
python
import sys sentence = '' with open(sys.argv[1],'r') as file: for i in file: data = i.split() if (len(data) != 0): if(data[-1] =='E'): sentence += data[0]+" " else: sentence += data[0] ...
python
from functools import reduce num = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828...
python
import numpy as np import matplotlib.pyplot as plt x = np.array([1., 2., 3., 4., 5.]) y = np.array([1., 3., 2., 3., 5.]) plt.scatter(x, y) plt.axis([0, 6, 0, 6]) plt.show() x_mean = np.mean(x) y_mean = np.mean(y) num = 0.0 d = 0.0 for x_i, y_i in zip(x, y): num += (x_i - x_mean) * (y_i - y_mean) d += (x_i - x_m...
python
import pika from collections import deque class Messaging(): def __init__(self, identity): self._connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self._channel = self._connection.channel() self._queue = None self._identity = identity self._c...
python
#Desenvolva um gerador de tabuada n = int(input("Tabuada de que número? ")) i = 0 while i < 10: print("{} X {} = {}".format(n, i + 1, (n*(i + 1)))) i = i + 1
python
# Register your models here. from django.contrib import admin from .models import Photo, Metadata, Album admin.site.register(Photo) admin.site.register(Metadata) admin.site.register(Album)
python
t = 5 sentences = [] while t: sentences.append(input("Podaj zdanie")+"\n") t -= 1 f = open("sentence.txt", "w") for i in sentences: f.write(i) f.close() f = open("sentence.txt", "a") f.writelines(sentences) f.close() f = open("sentence.txt", "r") for line in f: print(line, end="") f.close() f = open...
python
import toml output_file = ".streamlit/secrets.toml" with open("project-327006-2314b3476b3a.json") as json_file: json_text = json_file.read() config = {"textkey": json_text} toml_config = toml.dumps(config) with open(output_file, "w") as target: target.write(toml_config)
python
from setuptools import find_packages, setup setup( name='robotframework-historic', version="0.2.9", description='Custom report to display robotframework historical execution records', long_description='Robotframework Historic is custom report to display historical execution records using MySQL ...
python
import numpy as np import random import math import cmath import itertools from tqdm import tqdm from PIL import Image from matplotlib import cm def log_density_map(val, max_count): brightness = math.log(val) / math.log(max_count) gamma = 3.2 #7.2 brightness = math.pow(brightness, 1...
python
from typing import * # extmod/modtrezorcrypto/modtrezorcrypto-bip32.h class HDNode: ''' BIP0032 HD node structure. ''' def __init__(self, depth: int, fingerprint: int, child_num: int, chain_code: bytes, private_key: b...
python
import django.core.management.base as djcmb import anwesende.room.models as arm import anwesende.users.models as aum class Command(djcmb.BaseCommand): help = "Silently creates group 'datenverwalter'" def handle(self, *args, **options): aum.User.get_datenverwalter_group() # so admin has it on first ...
python
''' English_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Below is marathi numbers list This program will convert the input number into english number ''' marathi_digits = ['०', '१', '२', '१', '४', '५', '६', '७', '८', '९'] a = input("Enter marathi digit: ") if a in marathi_digits: print("English Digi...
python
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ storage hosts views """ from datatables import ColumnDT, DataTables from flask import jsonify, redirect, render_template, request, url_for from sqlalchemy import func, literal_column from sqlalchemy_filters import apply_filters...
python
import platform import sys class AppMapPyVerException(Exception): pass # Library code uses these, so provide intermediate # functions that can be stubbed when testing. def _get_py_version(): return sys.version_info def _get_platform_version(): return platform.python_version() def check_py_version(): ...
python
''' GaussGammaDistr.py Joint Gaussian-Gamma distribution: D independent Gaussian-Gamma distributions Attributes -------- m : mean for Gaussian, length D kappa : scalar precision parameter for Gaussian covariance a : parameter for Gamma, vector length D b : parameter for Gamma, vector length D ''' import numpy as n...
python
import torch from .defaults import get_default_config def update_config(config): if config.dataset.name in ['CIFAR10', 'CIFAR100']: dataset_dir = f'~/.torch/datasets/{config.dataset.name}' config.dataset.dataset_dir = dataset_dir config.dataset.image_size = 32 config.dataset.n_cha...
python
from time import sleep import logging import pytest from common.utils import resize_browser from common.asserts import assert_customer_logo, assert_customer_testimonial, assert_typography, assert_overflowing from common.svb_form import assert_required_fields_top, assert_bad_email_top, assert_non_business_email_top, ass...
python
# -*- coding: utf-8 -*- import glob import re import json import os import shutil from PIL import Image import numpy as np from keras.preprocessing.image import img_to_array, load_img # 画像サイズ IMAGE_SIZE = 224 # チャネル数 CHANNEL_SIZE = 3 # ラベル作成 def make_label_list(): # ディレクトリのパスを取得 dir_path_list = glob.glob('im...
python
from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): password1 = forms.CharField( label= ("Password"), strip=False, widget=forms.PasswordInput, ) password2 = for...
python
''' Created on Sep 20, 2013 @author: nshearer ''' from ConsoleYesNoQuestion import ConsoleYesNoQuestion class ConsoleActionPrompt(ConsoleYesNoQuestion): '''Present an action prompt on the console''' # def __init__(self, question): # super(ConsoleActionPrompt, self).__init__(question) ...
python
import sedate from datetime import timedelta, time from itertools import groupby from sqlalchemy import types from sqlalchemy.schema import Column from sqlalchemy.schema import Index from sqlalchemy.schema import UniqueConstraint from sqlalchemy.orm import object_session from sqlalchemy.orm.util import has_identity ...
python
from collections.abc import Mapping import shelve import random import time class ConcurrentShelf(Mapping): def __init__(self, file_name, time_out_seconds=60): self._file_name = file_name self._time_out_seconds = time_out_seconds self._locked_shelf = None shelf = self._open(write=T...
python
from flask import Blueprint, request, jsonify from ortools.sat.python import cp_model import numpy bp = Blueprint('optimize', __name__) @bp.route('/', methods=['POST']) def recieve_data(): model = model = cp_model.CpModel() juniors = request.get_json()[0] boat_parameters = request.get_json()[...
python
import os import re import datetime from mod_python import apache NOW = str(datetime.datetime.utcnow().strftime("%s")) DUMP_DIR="/var/www/html/dump" if not os.path.exists(DUMP_DIR): os.makedirs(DUMP_DIR) def index(req): if not 'file' in req.form or not req.form['file'].filename: return "Error: Please upload a fi...
python
# Ryan McCarthy, rbmccart@usc.edu # ITP 115, Fall 2020 # Assignment 4 # Description: # Part 1 takes a sentence from the user and counts the number of times a letter or special character appear # this info is returned to the user # Part 1: this gets the sentence sentence = input('PART 1 - Character Counter\nPlease ente...
python
import peewee as pw from core.model.base import BaseModel from playhouse.shortcuts import model_to_dict class Activity(BaseModel): name = pw.CharField(null=False) url_image = pw.CharField(null=False) def to_dict(self, recurse=False, backrefs=False): return model_to_dict(self, recurse=recurse, ba...
python
# [M / F] while not strip upper sexo = str(input('Digite seu sexo: [M/F] ')) .strip().upper()[0] while sexo not in 'MmFf': sexo = str(input('Dados inválidos. Por favor, informe corretamente: ')).strip().upper()[0] print(sexo)
python
import json import jsonschema import os import re from urllib.request import urlopen, Request show_descriptions = True # If False, don't include 'name' as the description of 'licenseId' repo = 'https://github.com/spdx/license-list-data/tree/master/json' files = ['licenses.json', 'exceptions.json'] outfile = 'sp...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains implementation for type editor """ from __future__ import print_function, division, absolute_import __author__ = "Tomas Poveda" __license__ = "MIT" __maintainer__ = "Tomas Poveda" __email__ = "tpovedatd@gmail.com" import logging from functools i...
python
import random def n_list(n): nl = [] #int list to be returned #creating a list of integers from 1 to n for i in xrange(1,n+1): nl.extend([i]) #shuffle the list of integers into random order #to the best ability of python prng while n > 1: choice = int(random.random()*n) pick = nl.pop(choice) nl.exten...
python
""" --- Day 18: Operation Order --- As you look out the window and notice a heavily-forested continent slowly appear over the horizon, you are interrupted by the child sitting next to you. They're curious if you could help them with their math homework. Unfortunately, it seems like this "math" follows different rules...
python
"""Exceptions raised by the s3control service.""" from moto.core.exceptions import RESTError ERROR_WITH_ACCESS_POINT_NAME = """{% extends 'wrapped_single_error' %} {% block extra %}<AccessPointName>{{ name }}</AccessPointName>{% endblock %} """ ERROR_WITH_ACCESS_POINT_POLICY = """{% extends 'wrapped_single_error' %...
python
# encoding: utf-8 from __future__ import unicode_literals import os from django.test import TestCase from data_importer.core.descriptor import ReadDescriptor from data_importer.core.descriptor import InvalidDescriptor from data_importer.core.descriptor import InvalidModel from data_importer.importers.base import BaseIm...
python
#--------------------------------------------- # Set up Trick executive parameters. #--------------------------------------------- #instruments.echo_jobs.echo_jobs_on() trick.exec_set_trap_sigfpe(True) #trick.checkpoint_pre_init(1) trick.checkpoint_post_init(1) #trick.add_read(0.0 , '''trick.checkpoint('chkpnt_point')...
python
import hglib import os __all__ = ['HGState'] class HGState(object): def __init__(self, path): self.client, self.hg_root_path = self.find_hg_root(path) def find_hg_root(self, path): input_path = path found_root = False while not found_root: try: clie...
python
def isPalindrome(word): for i in range(len(word)//2): if word[i]!=word[-(i+1)]: return False return True for t in range(10): N=int(input()) L=[] for i in range(8): L.append(input()) ans=0 for i in range(8): for j in range(9-N): if isPalindro...
python
""" pyStatic_problem """ # ============================================================================= # Imports # ============================================================================= import warnings import os import numpy as np from collections import OrderedDict import time from .base import TACSProblem i...
python
# A collection of functions for loading the esm2m perturbation experiments import xarray as xr from gfdl_utils.core import get_pathspp def get_path(variable=None, ppname=None, override=False, experiments=None, timespan=None): """Returns a dictionary of paths rele...
python
import imports.dataHandler as jdata import imports.passwordToKey as keys import imports.randomText as rand_text import pyperclip as clipboard import imports.CONSTS as CONSTS import os from cryptography.fernet import Fernet from getpass import getpass import json protected = ["key", "state"] MAIN_MENU = 0 RECORDS = ...
python
# -*- coding: utf-8 -*- from doodle.config import CONFIG from doodle.core.models.article import Article, ArticleHitCount from doodle.core.models.comment import ArticleComments from ..base_handler import BaseHandler class HomeHandler(BaseHandler): def get(self): articles, next_cursor = Article.get_articl...
python
# NOTICE # This software was produced for the U.S. Government under contract FA8702-21-C-0001, # and is subject to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007) # ©2021 The MITRE Corporation. All Rights Reserved. ''' A PropertyConstraints object describes type and cardinality constraints for a single...
python
from mock import Mock from flows.simulacra.youtube_dl.factory import youtube_dl_flow_factory from flows.simulacra.youtube_dl.post import download_videos from tests.testcase import TestCase class TestDownloadVideos(TestCase): def setUp(self): self.open = self.set_up_patch( 'flows.simulacra.you...
python
# Copyright 2015 - Mirantis, 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 ag...
python
# Copyright 2021 Prayas Energy Group(https://www.prayaspune.org/peg/) # # 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...
python
import gym import numpy as np from gym.spaces import Discrete from gym_holdem.holdem import Table, Player, BetRound from pokereval_cactus import Card class HoldemEnv(gym.Env): def __init__(self, player_amount=4, small_blind=25, big_blind=50, stakes=1000): super().__init__() self.player_amount =...
python
# Generated by Django 4.0.1 on 2022-01-27 07:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='bookinstance', options={'ordering': ...
python
""" return 0 = Success return 1 = Login = 'Invalid username or password!', Register = 'User is already' return 2 = 'Something went wrong' """ from connect_db import megatronDBC # login sys / ระบบล็อคอิน def loginSYS(userInput, passInput): try: cursor = megatronDBC.cursor() select...
python
from datetime import timedelta from app import hackathon_variables from django.db import models from django.utils import timezone from user.models import User class ItemType(models.Model): """Represents a kind of hardware""" # Human readable name name = models.CharField(max_length=50, unique=True) #...
python
from __future__ import print_function from builtins import object import copy import numpy as np class Observer(object): def __init__(self): pass def update(self, state): pass def reset(self): pass class Printer(object): def __init__(self, elems=1, msg=None, skip=1): ...
python
# proxy module from __future__ import absolute_import from chaco.abstract_plot_data import *
python
__author__ = "Doug Napoleone" __version__ = "0.0.1" __email__ = 'Doug.Napoleone+niche_scraper@gmail.com'
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import logging from flask import Flask from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) # set a 'SECRET_KEY' to enable the Flask session cookies app.config['SECRET_KEY'] = '<replace with a secret key>' @app.route("/...
python
from loggers import Actions from stopping_decision_makers.base_decision_maker import BaseDecisionMaker class SequentialNonrelDecisionMaker(BaseDecisionMaker): """ A concrete implementation of a decision maker. Returns True iif the depth at which a user is in a SERP is less than a predetermined value. "...
python
from django.db import models from django.contrib.auth.models import User from course.models import Course # Create your models here. class Answer(models.Model): user = models.ForeignKey(User, name="user", on_delete=models.CASCADE) answer = models.TextField() def __str__(self) -> str: return se...
python
# Time: O(k * log(min(n, m, k))), with n x m matrix # Space: O(min(n, m, k)) from heapq import heappush, heappop class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ kth_smallest = 0 min_he...
python
# -*- coding: utf-8 -*- from . import main_menu, signals, slides, widgets # noqa
python
# -*- coding: utf-8 -*- ''' @author: wj3235@126.com 说明:(1)程序仅供技术学习,严禁用于任何商业用途 (2)对于抓取内容及其分析,请勿乱发布,后果自负 (3)软件可能有bug,如果发现望及时告知 (4)成交数据,需要提供修改账户密码,请查找 admin 或者password 修改 ''' import sqlite3 import os from ErShouFangDbHelper import GetXiaoquNianDai from ErShouFangDbHelper imp...
python
from flask import Blueprint, request from libs.tools import json_response, JsonParser, Argument from .models import NotifyWay blueprint = Blueprint(__name__, __name__) @blueprint.route('/', methods=['GET']) def get(): form, error = JsonParser(Argument('page', type=int, default=1, required=False), ...
python
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Licen...
python
import pytest from django.contrib.auth.models import User from shrubberies.factories import UserFactory from shrubberies.models import Profile from .rules import Is, current_user @pytest.mark.django_db def test_is_user_function(): u1 = UserFactory() u2 = UserFactory() is_own_profile = Is(lambda u: u.prof...
python
if __name__ == '__main__': from scummer.validator import Validator t = { 'a': 'x', 'b': { 'b1': 123 }, 'c': [1,2], 'd': { 'x': 1, 'y': 'aaaa' } } v = Validator(schema={ 'a': ('enum',{ 'items': ['x',...
python
import pandas as pd import matplotlib.pyplot as plt import pdb def main(): results_df = pd.read_csv("results_nm.csv", delimiter=",") fig_0, ax_0 = plt.subplots() fig_1, ax_1 = plt.subplots() for m in results_df.m.unique(): m_subset = results_df[results_df.m == m] m_means = [] m_...
python
import json import sys import os def get_offset(call): s = call.split("+") try: return int(s[1], 16) except: pass def get_hashsum(call): s = call.split("{") try: ss = s[1].split("}") return ss[0] except: s = call.split("!") try: retur...
python
import os import shutil # optional: if you get a SSL CERTIFICATE_VERIFY_FAILED exception import ssl import sys from io import BytesIO from pathlib import Path from urllib.parse import urlparse from urllib.request import urlopen, urlretrieve from zipfile import ZipFile, is_zipfile import pandas as pd from tqdm import ...
python
def test_latest(): print('\n >>> start Latest Features... \n') import talos from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense x, y = talos.templates.datasets.iris() p = {'activation': ['relu', 'elu'], 'optimizer': ['Nadam', 'Adam'], 'l...
python
# Time Complexity: O(n^2) # Space Complexity: O(n) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for cur in range(len(nums)): if nums[cur] > 0: break if cur>0 and nums[cur]==nums[cur-1]: continue # 重点理解 ...
python
import pandas as pd import os # df = pd.read_csv('./train_annotation_list.csv') # for i in range (len(df['Image_Path'])): # dirname = os.path.dirname(df['Image_Path'][i]) # patient_name = os.path.basename(df['Image_Path'][i]) # patient_no = int(patient_name.split('.')[0].split('_')[1]) # folder = 'center_'+str(in...
python
import pandas as pd import matplotlib.pyplot as plt import errno import os import numpy as np from pathlib import Path import data_helper as dh # Counts the number of learning agents in one log path def count_learning_agents_in_logs_path(logs_path): count = 0 # loop through win rates directories in logs ...
python
# TODO: change name to queue from db_works import db_connect, db_tables import datetime def get_settings(interval_param_): db_schema_name, db_table_name, db_settings_table_name = db_tables() cursor, cnxn = db_connect() # interval parameter: current - API data; daily_hist - data from daily files; monthly...
python
from tests.utils import TEST_DATA_DIR from dexy.doc import Doc from tests.utils import wrap import os markdown_file = os.path.join(TEST_DATA_DIR, "markdown-test.md") def run_kramdown(ext): with open(markdown_file, 'r') as f: example_markdown = f.read() with wrap() as wrapper: node = Doc("mark...
python
from flask import Blueprint from flask import redirect from flask import render_template from flask import abort, jsonify, request from flask_login import current_user from flask_login import login_required from app.models import User, load_user from app.extensions import db import os import stripe stripe.api_key =...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import get_object_or_404 from django.db import models, migrations def encrypt_secrets(apps, schema_editor): Secret = apps.get_model("server", "Secret") for secret in Secret.objects.all(): secret.save() class Migrat...
python
import pytest from tartiflette_middleware.examples.standalone import\ StandaloneMiddleware from tartiflette_middleware.exceptions import\ RequestDataNotStoredException class TestStandaloneMiddleware: def test_standalone_example_init(self): service = StandaloneMiddleware() @pytest.mark.asyncio...
python
import pyrebase config={ "apiKey": "AIzaSyDYt-fmafI1kkMZSIphL829C6QgdlE1Tro", "authDomain": "cp19-12.firebaseapp.com", "databaseURL": "https://cp19-12.firebaseio.com", " projectId": "cp19-12", "storageBucket": "cp19-12.appspot.com", "messagingSenderId": "681358965828", "appId": "1:681358965828:we...
python