content
stringlengths
0
894k
type
stringclasses
2 values
from datetime import datetime, date, timezone import dateutil from dateutil.relativedelta import relativedelta import re from .util import calculate_price, DELIM_VALUE_REGEX, DOT_VALUE_REGEX from isodate import parse_duration, parse_datetime import pytz def create_default_context(numeric, responseMetadata): def c...
python
import container_crawler.utils import mock import unittest class TestUtils(unittest.TestCase): @mock.patch('container_crawler.utils.InternalClient') @mock.patch('container_crawler.utils.os') def test_internal_client_path(self, os_mock, ic_mock): os_mock.path.exists.return_value = True os_m...
python
import random from random import sample import argparse import numpy as np import os import pickle from tqdm import tqdm from collections import OrderedDict from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import precision_recall_curve from sklearn.covariance import L...
python
""" A QUANTIDADE DE UMA LETRA, A PRIMEIRA E A ÚLTIMA VEZ QUE APARECERAM NA FRASE! """ frase = str(input('Digite uma frase: ')).strip() frase = frase.upper() print('A quantidade de A é {} '.format(frase.count('A'))) print('A primeira vez que A apareceu foi: {} '.format(frase.find('A')+1)) print('A última vez que A ...
python
ll=range(5, 20, 5) for i in ll: print(i) print (ll) x = 'Python' for i in range(len(x)) : print(x[i])
python
from typing import Sequence, Union from PIL import Image class BaseTransform: """ Generic image transform type class """ slug: Union[None, str] = None # unique string that identifies a given transform @staticmethod def apply_transform( img: Image.Image, parameters: Sequence[Union[...
python
from collections import Counter input_data = open("day12.input").read().split("\n") input_data = [tuple(a.split("-")) for a in input_data] connections = [] for (a, b) in input_data: if a != 'start': connections.append((b, a)) connections += input_data connections.sort() def part1(path, b): return...
python
import os import numpy as np import pandas as pd from typing import Any, Dict, List, Optional, Tuple, NoReturn import skfuzzy as fuzz import skfuzzy.control as ctrl from aggregation import OWA_T1 import matplotlib.pyplot as plt class FLST1Model(object): def __init__(self, rules_path:str, expert_mode:str): ...
python
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize('fasterloop.pyx'))
python
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from enum import Enum, unique @unique class AnalyzeFieldIdx(Enum): IDX_MODULE_NAME = 0 IDX_ANALYE_NAME = 1 IDX_COLUMN_INFO = 2 IDX_IS_EXECUTE = 3
python
import unittest from . import day01 class TestDay1(unittest.TestCase): def test_basic(self): self.assertEqual('hello', 'hello') def test_fuel_is_calculated_correctly_for_given_examples(self): self.assertEqual(day01.get_fuel_required(module_mass=12), 2) self.assertEqual(day01.get_fuel_r...
python
# Code by JohnXdator n,k = map(int,input().split()) ups = list(map(int,input().split())) count = 0 for i in range(n): if ups[k-1] == 0 and ups[i] == ups[k-1]: count>=count+0 elif ups[k-1] <= ups[i]: count=count+1 else: count=count+0 print(count)
python
from django.test import TestCase from django.core.management import call_command class TestUi(TestCase): def setUp(self): call_command('loaddata', 'user', verbosity=0) call_command('loaddata', 'init', verbosity=0) call_command('loaddata', 'test/testWorld', verbosity=0) ...
python
import math import warnings from torch import Tensor import torch.nn as nn def zeros_(): """Return the initializer filling the input Tensor with the scalar zeros""" def initializer(tensor: Tensor, fan_in: int = None, fan_out: int = None): return nn.init.zeros_(tensor) return initializer def on...
python
#!/usr/bin/python # Filename: mysqlfunc.py # Purpose: All the mysql functions # !!! need to encapsulate a cur with something like a using statement # Database errors import MySQLdb, pdb, logger, dnsCheck from MySQLdb import Error #All the variables for paths from variables import * def create_dbConnection(): t...
python
#!/usr/bin/env python import functools import os import os.path from datetime import timedelta from functools import update_wrapper from flask import Flask, abort, current_app, jsonify, make_response, request import psycopg2 DATABASE = os.environ['POSTGRES_DB'] USERNAME = os.environ['POSTGRES_USER'] PASSWORD = os....
python
from botcity.core import DesktopBot # Uncomment the line below for integrations with BotMaestro # Using the Maestro SDK # from botcity.maestro import * class Bot(DesktopBot): def action(self, execution=None): # Fetch the Activity ID from the task: # task = self.maestro.get_task(execution.task_id) ...
python
import os from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from ibm_watson import PersonalityInsightsV3 from services.base import BaseService, BaseServiceResult class IBMWatson(BaseService): """ IBM Watson service wrapper """ def __init__(self, service_wrapper, service_url): ""...
python
#!/usr/bin/python3 # creates the SQLite database file - run this first import sqlite3 # create db file con = sqlite3.connect('./db/ic_log1_2020-06-30_manual.db') cur = con.cursor() # create table cur.execute('''CREATE TABLE IF NOT EXISTS iclog (date real, ic integer, note text)''') # close the connection con.close(...
python
# -*- coding: utf-8 -*- def main(): n, m = map(int, input().split()) summed = 4 * n - m xy = list() # 2x + 3y + 4z = M # x + y + z = N を解く # See: # https://atcoder.jp/contests/abc006/submissions/1112016 # WAの原因:成立しない条件の境界値を0以下だと思っていた,2項目の条件に気がつけなかった if summed < 0: ...
python
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: Jackson Lee 7/8/14 This script reads in a fasta or fastq and filters for sequences greater or less than a threshold length Input fastq file @2402:1:1101:1392:2236/2 GATAGTCTTCGGCGCCATCGTCATCCTCTACAC...
python
import numpy as np from os import listdir from os.path import join #def random_shift_events(events, max_shift=20, resolution=(180, 240)): def random_shift_events(events, f, max_shift=20, resolution=(195, 346)): H, W = resolution x_shift, y_shift = np.random.randint(-max_shift, max_shift+1, size=(2,)) ...
python
import json import cryptography.fernet from django.conf import settings from django.utils.encoding import force_bytes, force_text from django_pgjson.fields import get_encoder_class import six # Allow the use of key rotation if isinstance(settings.FIELD_ENCRYPTION_KEY, (tuple, list)): keys = [ cryptography...
python
from pptx import Presentation from pptx.util import Inches import pyexcel as pe print(""" Exemplo de criação de apresentação PPTX em loop utilizando dados de Excel Vish, o bagulho foi loko pra conseguir criar este aplicativo mano -> agora aprendi, já era Day 24 Code Python - 23/05/2018 """) dadosE...
python
""" This sample shows how to create a list in json of all items in a group Python 2.x/3.x ArcREST 3.5,6 """ from __future__ import print_function from __future__ import absolute_import import arcrest import os import json from arcresthelper import orgtools, common import csv import sys from arcresthelper....
python
def get_customized_mapping(cls): mapping = { "name": { "type": "text", "copy_to": [ "all" ] }, "is_public": { "type": "boolean" }, "taxid": { "type": "integer" }, "genes": { ...
python
#!/usr/bin/env python # # Copyright (C) 2007 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General ...
python
#!/usr/bin/env python from qiskit import QuantumProgram Circuit = 'oneBitFullAdderCircuit' # Create the quantum program qp = QuantumProgram() # Creating registers n_qubits = 5 qr = qp.create_quantum_register("qr", n_qubits) cr = qp.create_classical_register("cr", n_qubits) # One-bit full adder circuit, where: # qr...
python
"""add degree denormalizations Revision ID: 38c7982f4160 Revises: 59d7b4f94cdf Create Date: 2014-09-11 20:32:37.987989 """ # revision identifiers, used by Alembic. revision = '38c7982f4160' down_revision = '59d7b4f94cdf' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column(u'grano_entit...
python
from protodata.serialization_ops import SerializeSettings from protodata.reading_ops import DataSettings from protodata.utils import create_dir from protodata.data_ops import NumericColumn, split_data, feature_normalize, \ map_feature_type, float64_feature, int64_feature import tensorflow as tf import pandas as pd...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """argparse and main entry point script""" import argparse import logging import os import sys from logging.handlers import TimedRotatingFileHandler from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import kootkounter.bot LOG_LEVEL_STRINGS = ...
python
import sys from pathlib import Path # Path modifications paths = ["../build/src", "../src/preproc", "../src/util"] for item in paths: addPath = Path(__file__).parent / item sys.path.append(str(addPath.resolve())) #-----------------------------------------------------------------------------# import util_yam...
python
import os import yaml def root(): mydir = os.path.dirname(os.path.realpath(__file__)) return os.path.dirname(mydir) def tla_result_fixture(zone_number, score=0): return { 'score': score, 'present': True, 'disqualified': False, 'zone': zone_number, } def get_data(da...
python
from django.urls import include, path, re_path from . import handlers article_urlpatterns = [ path("2020/", handlers.handler_2020, name="articles-2020"), path( "categories/", include( [ path("<str:category>", handlers.category, name="categories"), pa...
python
import base64 import os from io import BytesIO from PIL import Image from rest_framework import serializers from photologue.models import Photo, Gallery from oms_cms.config import settings from django.conf import settings BASE_DIR = settings.BASE_DIR class ImageSerializerField(serializers.Field): def to_repr...
python
# vim: set expandtab shiftwidth=4 : # pylint: disable=missing-docstring import json import requests from . import base from . import settings class KeysSymmTest(base.BaseTest): user = settings.EXISTING_USERS[1] wrong_user = settings.EXISTING_USERS[2] def make_put_body(self): return { ...
python
#! /usr/bin/env python # -*- coding: utf-8 -*- """Generate ERT vs param. figures. The figures will show the performance in terms of ERT on a log scale w.r.t. parameter. On the y-axis, data is represented as a number of function evaluations. Crosses (+) give the median number of function evaluations for the smallest r...
python
# Generated by Django 2.1.5 on 2019-02-18 12:48 from django.db import migrations, models def change_negative_fields(apps, schema_editor): Resource = apps.get_model('resources', 'Resource') for resource in Resource.objects.all(): resource_has_changed = False if resource.area and resource.area ...
python
""" Samples of how to use tw2.jit Each class exposed in the widgets submodule has an accompanying Demo<class> widget here with some parameters filled out. The demos implemented here are what is displayed in the tw2.devtools WidgetBrowser. """ from tw2.core.resources import JSSymbol from tw2.jit.widgets import SQLAR...
python
import numpy as np from matplotlib import pyplot as plt from neural_network import NeuralNet def generate_data(): N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes X = np.zeros((N * K, D)) y = np.zeros(N * K, dtype='uint8') # class labels for j in range...
python
def rev(string): reverse_string = '' for c in range(len(string)-1, -1, -1): reverse_string += string[c] return reverse_string
python
from typing import Any, Iterable, Iterator, Mapping, Optional, Tuple, TypedDict, Union from eth_enr import ENRAPI from eth_enr.abc import ENRManagerAPI from eth_enr.typing import ENR_KV from eth_typing import HexStr from eth_utils import ( encode_hex, is_hex, is_integer, is_text, to_bytes, to_d...
python
# vim:fileencoding=utf-8 # License: BSD Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> # globals: ρσ_str def strings(): string_funcs = set(( 'capitalize strip lstrip rstrip islower isupper isspace lower upper swapcase' ' center count endswith startswith find rfind index rindex format join ...
python
from collections import OrderedDict import pytest from .. import * from .subroutines import ( findRecursionPoints, spillLocalSlotsDuringRecursion, resolveSubroutines, ) def test_findRecursionPoints_empty(): subroutines = dict() expected = dict() actual = findRecursionPoints(subroutines) ...
python
#!/bin/python def opDeterminer(ops): vals = [] for op in ops: if op[0] == 'r': (vals, success) = removeOp(vals, long(op[1])) if not success: print ('Wrong!') continue elif op[0] == 'a': (vals, success) = addOp(vals, long(op[1])...
python
import signal, time STATE = 0 def state2(signum, frame): print('state2') signal.signal(signal.SIGHUP, signal.SIG_DFL) def state1(signum, frame): print('state1') signal.signal(signal.SIGHUP, state2) signal.signal(signal.SIGHUP, state1) while STATE < 10: time.sleep(0.01)
python
''' testing models ''' from io import BytesIO from collections import namedtuple import json import pathlib import re from unittest.mock import patch from PIL import Image import responses from django.core.exceptions import ValidationError from django.core.files.base import ContentFile from django.db import models fr...
python
class _Position: def __init__(self, shares, share_price): if share_price <= 0: raise ValueError("Please enter a positive number for share_price") self.shares = shares self.position_size = float(shares * share_price) def buy(self, shares, share_price): if shares < 0 o...
python
import io import re from pathlib import Path from zipfile import ZipFile import typer from typer import Option, Argument from patterns.cli.services.lookup import IdLookup from patterns.cli.services.output import sprint, abort_on_error, abort from patterns.cli.services.pull import ( download_graph_zip, downloa...
python
# Copyright (C) 2014, Red Hat, 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...
python
import os from flask import render_template, url_for, flash, redirect,request,abort from blog import app,db,bcrypt from blog.models import User,Post from blog.forms import RegistrationForm, LoginForm,UpdateAccountForm,PostForm from flask_login import login_user,current_user,logout_user,login_required import secrets @...
python
import pandas as pd import logging def ris_detect(raw): """ Detect RIS format style. """ if raw.startswith('TY -'): logging.debug('RIS file format detected.') return 'ris' elif raw.startswith('%0'): logging.debug('Endnote file format detected.') return 'endnote' else: ...
python
import unittest import tethys_gizmos.views.gizmo_showcase as gizmo_showcase from requests.exceptions import ConnectionError from unittest import mock from django.test import RequestFactory from ... import UserFactory class TestGizmoShowcase(unittest.TestCase): def setUp(self): self.user = UserFactory() ...
python
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.util.i18n import _ from indico.web.breadcrumbs import render_breadcrumbs from indico.web.flask...
python
import json class ObjectLogService: """ Служба журналирования логов по объектам """ def __init__(self, app): """ :type app: metasdk.MetaApp """ self.__app = app self.__options = {} def log(self, record): """ Делает запись по объекту в журна...
python
# -*- coding: utf-8 -*- import scrapy import re from bgm.items import Record, Index, Friend, User, SubjectInfo, Subject from bgm.util import * from scrapy.http import Request import datetime import json mpa = dict([(i, None) for i in range(32)]) class UserSpider(scrapy.Spider): name = 'user' def __init__(sel...
python
if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from functools import partial from Stream import Stream, StreamArray from Stream import _no_value from Operators import stream_func from stream_test import * def square(v): ...
python
''' xbrlDB is an interface to XBRL databases. Two implementations are provided: (1) the XBRL Public Database schema for Postgres, published by XBRL US. (2) an graph database, based on the XBRL Abstract Model PWD 2. (c) Copyright 2013 Mark V Systems Limited, California US, All rights reserved. Mark V copyright app...
python
"""Heat pump module Modelling a heat pump with modelling approaches of simple, lorentz, generic regression, and standard test regression """ import os import math import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from sklearn.line...
python
# # PySNMP MIB module APTIS-HDLC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APTIS-HDLC-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:24:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
python
from datetime import datetime from validator.kube.resource import KubernetesResourceProvider from validator.base import ClusterResult from validator.namespace import validate_namespaces def run_validate(host, token): provider = KubernetesResourceProvider(host, token) ns = validate_namespaces(provider) no...
python
#!/usr/bin/env python # coding: utf-8 # # Coding Exercises (Part 1) # ## Full Data Workflow A-Z: Merging, Joining, Concatenating # ### Exercise 12: Merging, joining, aligning and concatenating Data # Now, you will have the opportunity to analyze your own dataset. <br> # __Follow the instructions__ and insert your ...
python
# Incorrect order a = 5 b = 5 print(c) c = 6
python
# -*- coding: utf-8 -*- from scapy.layers.l2 import Dot3, LLC, STP from scapy.all import sendp, RandMAC # -------------------------------------------------------------------------- # STP TCN ATTACK # -------------------------------------------------------------------------- def run(int...
python
# define self-attention # simply modify the code for this paper A Structured Self-Attentive Sentence Embedding class StructuredSelfAttention(torch.nn.Module): def __init__(self, batch_size, lstm_hid_dim, d_a, r, max_len, emb_dim=128, vocab_size=None, use_pretrained_embeddings = False, embeddin...
python
from django.test import override_settings from django.utils import timezone from hotels.models import HotelRoomReservation from pretix.exceptions import PretixError from pytest import mark def test_cannot_create_order_unlogged(graphql_client, user, conference, mocker): response = graphql_client.query( """...
python
import io import cv2 import fs import fs.memoryfs import numpy as np import matplotlib.pyplot as plt class ramp4(): """ INTRODUCTION ------------ A simple library to make mp4 movies with matplotlib.pyplot. It use RAM instead of disk storage for the temporary images. HOW TO USE ----------- ...
python
table_config = [ { 'field': None, 'title': '选择', 'display': True, 'text': { 'tpl': '<input type="checkbox" value="{n1}" />', 'kwargs': { 'n1': '@id', } }, '...
python
#!/usr/bin/python2 import sys import time fh = open(sys.argv[1], 'rb') stage_2 = fh.read() fh.close() sploit = [ '\x00', '\x00', # r7 '\x30', '\x30', # r6 '\x31', '\x31', # r5 '\x32', '\x32', # r3 '\x34', '\x33', # r2 '\x34', '\x34', # r1 '\x00', '\x0A', # canary '\x35', '\x35', # rbp '\x02', '\x2E', # ret ...
python
#!/usr/bin/python3 import cmath import numpy as np import pytest from pytest import approx from emtoolbox.tline.tline import TLine from emtoolbox.tline.mtl_network import MtlNetwork def pol2rect(mag, deg): return cmath.rect(mag, np.deg2rad(deg)) @pytest.mark.parametrize( "f", [ 5e6, np....
python
# Section 10.8.1 snippets # 10.8.1 Base Class CommissionEmployee # Testing Class CommissionEmployee from commissionemployee import CommissionEmployee from decimal import Decimal c = CommissionEmployee('Sue', 'Jones', '333-33-3333', Decimal('10000.00'), Decimal('0.06')) c print(f'{c.earnings():,.2f}') c.gros...
python
""" solution AdventOfCode 2019 day 20 part 2. https://adventofcode.com/2019/day/20. author: pca """ from general.general import read_file, get_location_input_files, measure import matplotlib.pyplot as plt from collections import Counter import networkx as nx import heapq def to_grid(grid_txt): grid = dict() ...
python
#!/usr/bin/env python # encoding: utf-8 from maze import Maze from RL_brain import SarsaLambdaTable, QLambdaTable import numpy as np METHOD = "QLambda" def get_action(q_table, state): state_action = q_table.ix[state, :] state_action_max = state_action.max() idxs = [] for max_item in range(len(state...
python
from abc import ABC, abstractmethod from datetime import datetime from typing import List from dateutil.tz import tz from pytz import timezone from dataclasses import dataclass from importlib import import_module from .constant import Interval, Exchange from .object import BarData, TickData from .setting import SETTI...
python
import os import requests import subprocess import wget import zipfile def download_latest_version(version_number, driver_directory): """Download latest version of chromedriver to a specified directory. :param driver_directory: Directory to save and download chromedriver.exe into. :type driver...
python
""" Given an array, return the max difference between 2 numbers in array whereby: - larger number is after smaller number in array order eg: [0, 1, 12] -> 12 eg: [12, 0, 1] -> 1 """ def maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[n...
python
from datetime import datetime import dill as pickle from pathlib import Path from copy import deepcopy import numpy as np from skimage.io import imread import GPnd from GPnd import * from plotting import MAP_Estimator if __name__=='__main__': f_path = Path('chains/2019-09-22T16-01-08_n100000.pkl') with op...
python
# encoding=utf8 # pylint: disable=line-too-long """Implementation of modified nature-inspired algorithms.""" from NiaPy.algorithms.modified.hba import HybridBatAlgorithm from NiaPy.algorithms.modified.hde import DifferentialEvolutionMTS, DifferentialEvolutionMTSv1, DynNpDifferentialEvolutionMTS, DynNpDifferentialEvolu...
python
from __future__ import annotations from typing import Any, TypeVar, cast from discord.ext import typed_commands C = TypeVar('C', bound='Cog[Any]') CT = TypeVar('CT', bound=typed_commands.Context) class Cog(typed_commands.Cog[CT]): def _inject(self: C, bot: typed_commands.Bot[CT], /) -> C: self.__pre_in...
python
import xlrd import csv def Excel2CSV(ExcelFile='SicCodesAllLevels.xls', SheetName='SIC4', CSVFile='ref_list.csv'): workbook = xlrd.open_workbook(ExcelFile) worksheet = workbook.sheet_by_name(SheetName) csvfile = open(CSVFile, 'wb') wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL) for...
python
import numpy as np import os class Lay(object): def __init__(self): self.__m = self.m_world = None self.__r = self.m_world = None self.__s = self.m_world = None self.m_world = None self.m_world_inv = None self.is_ready = False def set(self, move=np.eye(4), rota...
python
"""Class instance for Transformer """ import argparse # pylint: disable=unused-argument class Transformer(): """Generic class for supporting transformers """ def __init__(self, **kwargs): """Performs initialization of class instance Arguments: kwargs: additional parameters pass...
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from PySide2 import QtCore, QtGui, QtWidgets class GraphicView(QtWidgets.QGraphicsView): def __init__(self): QtWidgets.QGraphicsView.__init__(self) self.setWindowTitle("QGraphicsView") scene = QtWidgets.QGraphicsScene(self) sce...
python
# Generated by Django 3.2.7 on 2021-09-27 15:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rgd_fmv', '0001_initial'), ] operations = [ migrations.AlterField( model_name='fmv', name='status', fiel...
python
from bs4 import BeautifulSoup import requests import re from graph import Graph from player import Player class Crawler: def __init__(self,link_root=""): self.link_root = "https://www.hltv.org/stats/teams" self.headers = {} self.headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) Appl...
python
from flask_wtf import FlaskForm class NameForm(FlaskForm): pass
python
# coding: utf-8 """ MailSlurp API MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://ww...
python
"""""" import pytest import random import tempfile from textwrap import dedent from unittest import mock from pybryt.utils import * from .test_reference import generate_reference_notebook def test_filter_picklable_list(): """ """ l = [1, 2, 3] filter_picklable_list(l) assert len(l) == 3 w...
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @文件 :audit_utils.py @说明 : @时间 :2020/07/21 16:38:22 @作者 :Riven @版本 :1.0.0 ''' import base64, logging, socket, sys sys.path.append('.') from app_server.src.utils.collection_utils import get_first_existing from app_server.src.utils.to...
python
#!/home/jeffmur/archiconda3/envs/face_recon/bin/python3 import face_recognition import cv2 import numpy as np import pickle from pathlib import Path from datetime import datetime import signal,sys,time from google.cloud import pubsub_v1 # TODO (developer config) project_id = "{GOOGLE_CLOUD_PROJECT_ID}" topic_id = ...
python
from eeval.evaluator import evaluate from math import pi import timeit exprs = ( "2+2*2", "(2+2)+(2+2)", "-(2+2)+(-(2+2))", "(2+2)*(-(2+2))", "-(-(-(-(3*88888))))", "pi*2", "(pi+1)*(pi+2)", "-pi", "pi^2" ) constants = { "pi": pi } itercount = 1000 print("Evaluator test:") f...
python
from typing import Dict from smartz.api.constructor_engine import ConstructorInstance def is_true(arr, key): return key in arr and bool(arr[key]) class Constructor(ConstructorInstance): _SWAP_TYPE_ETHER = 'Ether' _SWAP_TYPE_TOKENS = 'ERC20 tokens' def __init__(self): self._TEMPLATES:...
python
from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from rest_framework import permissions class ReadSelf(permissions.BasePermission): """Permits access to the (user)model instance if the user corresponds to the instance""" message = _("You may only view your...
python
from __future__ import annotations def search_in_a_sorted_matrix( mat: list[list], m: int, n: int, key: int | float ) -> None: """ >>> search_in_a_sorted_matrix( ... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 5) Key 5 found at row- 1 column- 2 >>> search_in_a_sorte...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PinOnDiskMain.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): ...
python
from tests.utils import W3CTestCase class TestGridPositionedItemsContentAlignment(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'grid-positioned-items-content-alignment-'))
python
def search(nums: list[int], target: int) -> int: start, end = 0, len(nums) - 1 while start + 1 < end: mid = (start + end) // 2 if nums[mid] == target: return mid # Situaion 1: mid is in the left ascending part if nums[mid] > nums[start]: if ...
python
from .csv_parser import Parser as BaseParser class Parser(BaseParser): """Extract text from tab separated values files (.tsv). """ delimiter = '\t'
python
from mbctl import cli def test_cli_ok(): cli.run(['list'])
python
# -*- coding: utf-8 -*- """ Created on Sun Dec 5 00:25:04 2021 @author: Perry """ # import csv and matplotlib import csv import matplotlib.pyplot as plt # read data.csv into a dictionary called data data = csv.DictReader(open("data.csv")) # split the data into three lists for x, y, and z dataArrays = {"time": [], "x...
python