content
stringlengths
5
1.05M
from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .models import Post def post_list(request): posts = Post.objects.all()[:20] data = {'results': list(posts.values('title', 'author__username', 'created_at'))} return JsonResponse(data) def post_detail(request,...
from typing import Iterable from google.protobuf import field_mask_pb2 class FieldMask: ''' A local wrapper for official protobuf FieldMask. ''' def __init__(self, paths: Iterable[str]) -> None: self.paths = set(paths) @classmethod def from_pb(cls, pb_obj: field_mask_pb2.FieldMask): ...
""" Airline settings & info views. """ from aiohttp import web_exceptions import simplejson as json from sunhead.rest.views import JSONView from aeroport.management.utils import get_airlines_list, get_airline class BaseAirlineView(JSONView): @property def requested_airline(self): return self.reque...
import copy from numpy import array from utils import NgramScore, beam_search, load_chain, sample_next def z_read(line: str, chain: dict, num_solutions: int) -> None: columns = line.lower().split() loader = NgramScore("../data/statistic/english_1grams.txt") # list for probabilities as monograms of char...
import frappe @frappe.whitelist() def update_serial_no(): serial_no_list = [ '0201200V000DH0200211', '0201200V000DH0200212', '0201200V000DH0200213', '0201200V000DH0200214', '0201200V000DH0200215', '0201200V000DH0200216', '0201200V000DH0200217', ...
# # author: Jungtaek Kim (jtkim@postech.ac.kr) # last updated: February 8, 2021 # import numpy as np from bayeso_benchmarks.benchmark_base import Function def fun_target(bx, dim_bx): assert len(bx.shape) == 1 assert bx.shape[0] == dim_bx y = (1.5 - bx[0] + bx[0] * bx[1])**2 + (2.25 - bx[0] + bx[0] * bx...
# Generated by Django 2.2.8 on 2020-02-08 14:46 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20200202_1625'), ('accounts', '0003_buyer_cart'), ('purchase', '0002_a...
animals_orig = [['dogs', 'puppies'], ['cats', 'kittens']] # Shallow Copy using slice operator -- can get confusing with mutation animals_copy = animals_orig[:] # Deep Copy using accumulation and nested iteration animals_deep_copy = [] for lst in animals_orig: copied_inner_list = [] animals_deep_copy.append(copied...
#!/bin/env python3 # -*- coding: utf-8 -* ''' 项目名称: JD-Script / jd_getFollowGift Author: Curtin 功能: Date: 2021/6/6 上午7:57 建议cron: 0 9 * * * python3 jd_getFollowGift.py new Env('关注有礼'); ''' ################################## #cookie填写,注意:#ck 优先读取【JDCookies.txt】 文件内的ck 再到 ENV的 变量 JD_COOKIE='ck1&ck2' 最后才到脚本内 cookies=ck...
# coding: utf-8 import datetime import numpy as np from ..nonlinear import ConstantTurn from ....types.state import State def test_ctmodel(CT_model): """ ConstantTurn Transition Model test """ state = State(np.array([[3.0], [1.0], [2.0], [1.0], [-0.05]])) linear_noise_coeffs = np.array([0.1, 0.1]) tu...
import pint ureg = pint.UnitRegistry(auto_reduce_dimensions=True) ureg.define("reference_frame = [_reference_frame]") ureg.define("@alias grade = gradian") ureg.define("@alias astronomical_unit = ua") ureg.define("line = inch / 12") ureg.define("millitorr = torr / 1000 = mTorr") ureg.define("@alias torr = Torr")
import math import numpy as np from copy import deepcopy from charcad.draw.coordinates import Coordinates from charcad.draw.utils import DrawingChars _EMPTY_GRID = np.array([[' ']]) class GraphicObject: def __init__(self, x=0, y=0, transparent=True): self.set_coordinates(x, y) self.graph = None...
#!/usr/bin/python3.5 # -*-coding: utf-8 -* from collections import defaultdict import concurrent.futures from queue import Queue import threading import uuid from LspAlgorithms.GeneticAlgorithms.LocalSearch.LocalSearchEngine import LocalSearchEngine from LspAlgorithms.GeneticAlgorithms.PopulationEvaluator import Popul...
from rest_framework import permissions class IsAutoRepairShopOrStaff(permissions.BasePermission): message = "Auto Repair Shop restricted or Staff member" def has_permission(self, request, view): return request.user and (request.user.is_from_auto_repair_shop or request.user.is_staff) class IsInspect...
from rx import Observable def subscribe(observer): observer.on_next(1) observer.on_next(1) observer.on_next(2) observer.on_next(3) observer.on_next(2) observer.on_completed() print("\n== distinct ==") values = Observable.create(subscribe) subscription = values.distinct().subscribe( on_ne...
import json import sys def defineKey(key): if key == "buildings": return 'buid' if key == "floorplans": return 'fuid' if key == "pois": return 'puid' def compareObjs(couchObjects, mongoObjects, type): keys = ["is_building_entrance","floor_number","pois_type","buid","image","c...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-10-12 00:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bot', '0007_auto_20171012_0030'), ] operations = [...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import time from faker import Faker from CustClass_full import Customer #import transition_matrix transition_matrix = pd.read_csv("data/transition_matrix.csv", index_col=0) # In[54]: # class Customer: # ''' a single cu...
######## map # Transform each object of list # i.e. multiple each object by 3 in [0,1,2,3] x = range(5) print(list(x)) y = map(lambda x: x*3,x) def multiply_5(num): return num*5 print(list(y)) y = map(multiply_5,x) print(list(y)) ######## filter # Removed items from list based on condition y = fi...
import os from collections import Counter def main(): file = open('input.txt', 'r') lines = [line.replace('->', ',').strip().replace(' ', '') for line in file.readlines()] solutions(lines) def solutions(lines): points, diagonals = [], [] for line in lines: x1, y1, x2, y2 = map(int,...
"""Pytest-compatible classes and functions testing the Few Acres classes""" import pprint import re import time import pytest from few_acres_of_snow.few_acres_classes import \ FewAcresOfSnowController, FewAcresOfSnowHistory from few_acres_of_snow.tests.test_moves import moves9575653_fr from site_yucata.classify_g...
#import logging import os import time DEBUG = False API_URL_PREFIX = "/anuvaad-etl/document-processor/gv-document-digitization" HOST = '0.0.0.0' PORT = 5001 BASE_DIR = 'upload' #BASE_DIR = '/home/naresh/anuvaad/anuvaad-etl/anuvaad-extractor/document-processor/ocr/ocr-gv-server/' download_folder = 'upload' E...
from django.http import JsonResponse from dplhooks import settings class AuthenticationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): is_private = not request.path.startswith('/p') if is_private and ('AUTHORIZATION' not in ...
import argparse import gzip from rdkit import Chem import tqdm from rdkit import RDLogger from rdkit.Chem.MolStandardize import rdMolStandardize def main(): """ takes sdf file of initial training molecules and sdf file of training molecules (both optionally gzipped) and returns only those initial trai...
import torch from torch.nn import functional as F from openpose.model.matcher import Matcher from openpose.model.balanced_positive_negative_sampler import ( BalancedPositiveNegativeSampler, ) from openpose.structures.boxlist_ops import boxlist_iou from openpose.model.utils import cat from openpose.layers import s...
import argparse import os from pathlib import Path from random import shuffle def parse_args(): parser = argparse.ArgumentParser( description= 'Export Image Annotations Pairs as TXT' ) parser.add_argument( '--ds_path', dest='dataset_path', help='Base Dataset Path',...
from collections import deque def simplemovingaverage(period): assert period == int(period) and period > 0, "Period must be an integer >0" summ = n = 0.0 values = deque([0.0] * period) # old value queue def sma(x): nonlocal summ, n values.append(x) summ += x - values.popl...
# Copyright (c) 2013 Stian Lode # # 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, including without limitation the rights # to use, copy, modify, merge, publish, distrib...
################################################################################### # Copyright (c) 2021 Rhombus Systems # # # # Permission is hereby granted, free of charge, to any person obtai...
import unittest import mock from django.conf import settings from django.contrib import messages from django.utils import formats from django.utils import timezone from django_cradmin import cradmin_testhelpers from model_mommy import mommy from devilry.devilry_group import devilry_group_mommy_factories as group_mom...
from .sub_models.models_accounts import * from .sub_models.models_verticals import * from .sub_models.models_spiders import * from .sub_models.models_contacts import *
import pvtoolslib # Build the s3 filename database and save to file. pvtoolslib.build_s3_filename_list() filedata = pvtoolslib.get_s3_filename_df() print(filedata)
import tkinter as tk from random import randint import time import math from project.MouseController import MouseController class WheelSpinner(tk.Frame): def __init__(self, master, wheel_options, radius, *args, **kwargs): super().__init__(master, *args, **kwargs) self.master = master sel...
from multipledispatch import dispatch import matplotlib.pyplot as plt import numpy as np import pandas as pd from .colour import PAL a = (list, np.ndarray) @dispatch(np.ndarray, function) def viz(x, f): # Now condition on the observations to make predictions. plt.plot(x, f(x), c=PAL[0]) plt.show() retu...
#!/usr/bin/env python ''' mcu: Modeling and Crystallographic Utilities Copyright (C) 2019 Hung Q. Pham. 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.or...
import os import re import html from udmurt_translit import UdmurtTransliterator class CsvProcessor: """ Contains methods for adding transliterated columns to a CSV file. """ rxDir = re.compile('[/\\\\][^/\\\\]+$') def __init__(self, transliterator, sep='\t', srcCol=0, ...
import importlib import platform import sys from argparse import ArgumentParser from typing import Iterable, List, Optional, Sequence, Set, Tuple from . import __version__ from .config import Config from .linter import Linter from .problem import ProblemType IGNORABLE_TYPES = [t.name for t in (ProblemType.URI, Proble...
""" Find reachable nodes given a set of root nodes and properties TODO: the --subj, --pred, and --obj options should perhaps be renamed to --node1-column-name, --label-column-name, and --node2-column-name, with the old options kept as synonyms. TODO: the root file name should be parsed with parser.add_inp...
def mat_rows(s, n): return zip(*(iter(s), ) * n) def mat_cols(s, n): return zip(*(iter(s[n * k:]) for k in xrange(n))) def mat_null(fn, s, n): return len(tuple(0 for a in fn(s, n) if a == (None, ) * n))
import numpy as np from unittest import TestCase from diffprivlib.mechanisms import Bingham from diffprivlib.utils import global_seed class TestBingham(TestCase): def setup_method(self, method): if method.__name__ .endswith("prob"): global_seed(314159) self.mech = Bingham a =...
import httpx # from pytest import fixture, mark # @fixture(scope="session") # def client(): # """ # A shared client for all requests in the test suite. # """ # return httpx.Client() client = httpx.Client()
""" config.py Contains application settings encapsulated using Pydantic BaseSettings. Settings may be overriden using environment variables. Example: override uvicorn_port default setting export UVICORN_PORT=5200 or UVICORN_PORT=5200 python bluebutton/main.py """ import certifi import os import socket ...
from setuptools import setup setup( name='nginx-parser', packages=['src'], version='0.1', description='A simple parser for nginx logs', author='George Davaris', author_email='davarisg@gmail.com', license='MIT', url='https://github.com/davarisg/nginx-parser', # use the URL to the github...
#!/usr/bin/env python # python 3.8.5 import numpy from PIL import Image def genImage(img_width=512, img_height=256): # Define img width and height as an integer img_width = int(img_width) img_height = int(img_height) # Define key name filename = 'key.png' img_array = numpy.random.rand(img_he...
from django.db import models from datetime import datetime class Retailer(models.Model): name = models.CharField(max_length=100, primary_key=True) address = models.CharField(max_length=100) sector_choices = (('a','Private'),('b','Government'),('c','Semi-Private'),('d','Other')) sector = models.CharField(ma...
import malmopy malmo = malmopy.Malmo() malmo.start_mission('missions/patrol.xml') for obs in malmo.observations(): floor = obs['floor'] # (0,1) means in front # (-1,0) is to the left # (1,0) is to the right # front is a string description of the block front = floor[(0,1)] # implement th...
""" Common place to document project logging codes. HL7L = HL7 Listener service.""" # ERROR HL7_MLLP_CONNECT_ERROR = "HL7LERR001: Error connecting to the HL7 MLLP listener port %s" NATS_CONNECT_ERROR = "HL7LERR002: Error connecting to the NATS server %s" NATS_NOT_INITIALIZED = "HL7LERR003: NATS not initialized." HL7_M...
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import dirname, abspath, join from indra.benchmarks import bioprocesses as bp # from indra.benchmarks import complexes as cp from indra.benchmarks import phosphorylations as phos from indra.util import u...
""" Standard Windows functions required for the system. The required APIs are: * running processes * * GUI windows * mapping a window to a process ID """ import sys import importlib # Top-level global def from .funcs_any_win import SHELL__CANCEL_CALLBACK_CHAIN def __load_functions(modules):...
#!/usr/bin/python3 # ================================================== """ File: RMedian - Phase 3 Author: Julian Lorenz """ # ================================================== # Import import math import random # ================================================== def phase3(X, L, C, R, cnt): n = len(X) s...
import requests from requests_ntlm2 import HttpNtlm2Auth # test for mragaei session = requests.Session() # un-authenticated r1 = session.get("http://52.208.44.235/iisstart.htm", verify=False) Referer = dict(Referer = "http://192.168.1.20/now") # set auth handler for authenticted, use same connection session.auth = H...
from numba import jit from numpy import exp, zeros, meshgrid from tqdm import tqdm from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from core import create_dir, make_paths, make_animation, make_video, parse_args @jit(nopython=True) def intensity_initialization(n_points, x, y, x_0, y_0, M)...
def bar(foo_new, i_new): need_break = False if i_new > 2: foo_new = False need_break = True return foo_new, need_break def main(indices): foo = True for i in indices: foo, need_break = bar(foo, i) if need_break: break return foo
""" In this file one can find the implementation of helpful class and functions in order to handle the given dataset, in the aspect of its structure. Here is the implementation of helpful class and functions that handle the given dataset. """ import json import csv from scipy.stats import zscore from torch import Tens...
import sys import types from unittest.mock import Mock module_name = 'arcpy' arcpy = types.ModuleType(module_name) sys.modules[module_name] = arcpy arcpy.da = Mock(name=module_name + '.da')
import requests from util import * from logger import * from tgpush import * class ZJULogin(object): """ Attributes: sess: (requests.Session) 统一的session管理 """ headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 ...
from matplotlib import pyplot as plt import numpy as np python = [6, 7, 8, 4, 4] javascript = [3, 12, 3, 4.1, 6] x1 = np.arange(len(python)) x2 = [x + 0.25 for x in x1] plt.bar(x1, python, width=0.25, label = 'Python', color = 'deepskyblue') plt.bar(x2, javascript, width=0.25, label = 'Javascript', color = 'medium...
import names import random from django.core.management.base import BaseCommand, CommandError from crm.models import Contact def phn(): p = list('0000000000') p[0] = str(random.randint(1, 9)) for i in [1, 2, 6, 7, 8]: p[i] = str(random.randint(0, 9)) for i in [3, 4]: p[i] = str(random....
import sys import pytest from quart import Quart, Response, url_for from quart.testing import QuartClient from werkzeug.datastructures import Headers from .app import create_app @pytest.fixture def app() -> Quart: # import app factory pattern app = create_app(graphiql=True) # pushes an application cont...
#!/usr/bin/env python from __future__ import print_function import sys import rospy from robotican_demos_upgrade.srv import * def pick_unknown_client(): rospy.wait_for_service('pick_unknown') try: pick_unknown_req = rospy.ServiceProxy('pick_unknown', pick_unknown) resp1 = pick_unknown_req("a...
# -*- coding=utf-8 -*- from .file_io import * from .time_it import TimeIt from .util_doc import pkuseg_postag_loader from .zip_file import zip_file, unzip_file
from math import cos from math import pi from math import sin from typing import List from random import Random import matplotlib.pyplot as plt import pandas as pd import seaborn as sns def plot_clusters(clusters: List[List], centroids: List[List], labels: List[int]) -> None: """Plot custer data. Args: ...
from gi.repository import Gtk from pychess.Utils.IconLoader import get_pixbuf, load_icon # from pychess.widgets.WebKitBrowser import open_link main_window = None gtk_close = load_icon(16, "gtk-close", "window-close") def mainwindow(): return main_window def createImage(pixbuf): image = Gtk.Image() i...
"""A class for the Lemke Howson algorithm with lexicographical ordering""" from itertools import cycle import numpy as np import numpy.typing as npt from typing import Tuple from nashpy.integer_pivoting import make_tableau, pivot_tableau_lex from .lemke_howson import shift_tableau, tableau_to_strategy def lemke_how...
""" Copyright 2020 Jackpine Technologies Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
from ..PyQt.QtGui import QDoubleSpinBox, QApplication from ..PyQt.QtCore import pyqtProperty, QEvent, Qt from .base import PyDMWritableWidget class PyDMSpinbox(QDoubleSpinBox, PyDMWritableWidget): """ A QDoubleSpinBox with support for Channels and more from PyDM. Parameters ---------- parent : QW...
katok = ['다현', '정연', '쯔위', '사나', '지효'] def delete_data(position): kLen = len(katok) katok[position] = None for i in range(position+1, kLen, 1): katok[i-1] = katok[i] katok[i] = None del(katok[kLen-1]) print(katok) delete_data(1) print(katok) delete_data(3) print(katok)
#!/usr/bin/env python3 """fileio.py""" from pprint import pprint def write_json_data(filename: str, json_data: str): """Writes the passed json data to the passed filename""" try: with open(filename, 'w') as write: write.write(json_data) except Exception as e: printf(f'{e}') d...
import cv2 image = cv2.imread("../assets/img.png") x, y, w, h = 180, 65, 700, 750 cropped_image = image[y:y + h, x:x + w] cv2.imshow("Cropped", cropped_image) cv2.waitKey(0)
#!/usr/bin/env python # encoding: utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') """ Created by Cuong Pham on 2012-01-27. Copyright (c) 2012 Nemo Find Inc. All rights reserved. Base class for all of our spiders. """ from bs4 import BeautifulSoup import lxml.html import time import os from scrapy impo...
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from troop.models import Troop import csv import os class Command(BaseCommand): help = "Imports a set of users from a CSV file" def add_arguments(self, parser): parser.add_argument("filen...
#!/usr/bin/env python3 import argparse as ap import json import logging import multiprocessing import os import re import shlex import shutil import subprocess as sp import sys import tarfile import tempfile import zipfile from collections import Counter from datetime import timedelta from distutils.dir_util import cop...
from copy import deepcopy import torch from torch import nn from rltorch.agent import BaseAgent class SacDiscreteAgent(BaseAgent): def __init__(self): super(SacDiscreteAgent, self).__init__() self.writer = None self.gamma_n = None self.alpha = None self.tau = None ...
import random import pygame from pygame.locals import * import sys import Grandmas_Game_Closet as Main RED = (255, 0, 0) GREEN = (0, 255, 0) DARKGREEN = (20, 100, 20) BLUE = (0, 0, 255) PURPLE = (255, 0, 255) YELLOW = (255, 255, 0) GREY = (100, 100, 100) WHITE = (255, 255, 255) NAVY = (60, 60, 100) DARKGREY = (30, 30,...
import hashlib import hmac import json import logging from metagov.core.plugin_manager import Registry, Parameters, VotingStandard import metagov.plugins.discourse.schemas as Schemas import requests from metagov.core.errors import PluginErrorInternal from metagov.core.models import GovernanceProcess, Plugin, AuthType,...
import re import requests def get(url: str) -> dict: """ title、videos """ data = {} headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" } rep = requests.get(url, headers=headers, timeout=10...
# Automatically created by: shub deploy from setuptools import setup, find_packages setup( name = 'hubstorage-frontera', version = '0.1', packages = find_packages(), install_requires = [ 'frontera', 'hubstorage', 'requests', 'six', ], )
import blpapi import datetime class BbDownloader: def __init__(self): self.output_file = "" self.TICK_DATA = blpapi.Name("tickData") self.COND_CODE = blpapi.Name("conditionCodes") self.TICK_SIZE = blpapi.Name("size") self.TIME = blpapi.Name("time") self.TYPE = blpapi...
# Copyright (c) 2021 Cybereason Inc # This code is licensed under MIT license (see LICENSE.md for details) MT_DATABASE = 'DATABASE' MT_DATABASE_SYSTEM = 'DATABASE_SYSTEM' MT_INSTANCE = 'INSTANCE'
from .roleplay.main import *
from .ascii_factory import num2str def init(screen): global width, height height, width = screen.getmaxyx() def draw_speedmeter(screen, state): margin_y, margin_x = 4, 4 hud = ['▛▀▀▀▀▀▀▀▀▀▀▀▀▀▜', '▍ ▐', '▍ ▐', '▍ ▐', '▍ ...
from flask import Flask, render_template, abort from flask_talisman import Talisman from csp import csp app = Flask(__name__) Talisman(app, content_security_policy=csp, content_security_policy_nonce_in=['script-src']) SUPPORTED_LANGS = ('en', 'ja') @app.route('/') def index(): return render_tem...
'# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @Daddy_Blamo wrote this file. As long as you retain this notice you # can do whatever you want w...
# Copyright (c) 2015. # Philipp Wagner <bytefish[at]gmx[dot]de> and # Florian Lier <flier[at]techfak.uni-bielefeld.de> and # Norman Koester <nkoester[at]techfak.uni-bielefeld.de> # # # Released to public domain under terms of the BSD Simplified license. # # Redistribution and use in source and binary forms, with or wit...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Old starter program currently not in use and not maintained? """ import sys import os sys.stdout = sys.stderr import atexit import threading import cherrypy from rst2html import Rst2Html from flup.server.fcgi import WSGIServer import cgitb cgitb.enable() cherrypy.con...
""" Assignment 1: - Check is the given number is even or not. - Your function should return True if the number is even, False if the number is odd. - Name your function `is_even` Input: An integer Output: A boolean Example: > is_even(2) == True > is_even(5) == False > is_even(0) == True """ ... # tests if _...
from collections import defaultdict import django from django.db.models import ( BooleanField, DateField, ExpressionWrapper, OuterRef, Q, Subquery, functions, ) from .orm_fields import OrmBaseField, OrmBoundField from .types import ( ASC, DateTimeType, DateType, IsNullType,...
info = { "UNIT_NUMBERS": { "a náid": 0, "náid": 0, "a haon": 1, "aon": 1, "a dó": 2, "dhá": 2, "dó": 2, "a trí": 3, "trí": 3, "a ceathair": 4, "ceathair": 4, "ceithre": 4, "a cúig": 5, "cúig": 5, ...
from SNR_Calculation import SNR_Calculation mode = { "em_mode": "Conv", "em_gain": [1], "readout_rate": 1, "preamp": 1, "bin": 1, "sub_img": 1024, "t_exp": 1, } _SKY_FLUX = 12.298897076737294 # e-/pix/s _HATS24_FLUX = 56122.295000000006 # e-/s _N_PIX_STAR = 305 _HATS24_MAG = 12.25 mag = ...
# ******************************************************************************* # # Copyright (c) 2020-2021 David Briant. All rights reserved. # # ******************************************************************************* import sys if hasattr(sys, '_TRACE_IMPORTS') and sys._TRACE_IMPORTS: print(__name__) ...
def foo(*, x=None, y=None): print(x, y)
# Find K pairs with smallest sums # ttungl@gmail.com def kSmallestPairs(self, nums1, nums2, k): # sol: queue = [] def push(i, j): if i < len(nums1) and j < len(nums2): heapq.heappush(queue, [nums1[i] + nums2[j], i, j]) push(0, 0) # init pairs = [] # output while queue and len(pairs...
import random import unittest import requests import common _S = 'basics' _T0 = 'minimal' _T1 = 'basictable1' _T2 = 'basictable2' _T2b = 'ambiguous2' _Tc1 = 'composite1' _Tc2 = 'composite2' _Tr1 = 'column_removal_a' _Tr2 = 'column_removal_b' from common import Int8, Text, Timestamptz, \ RID, RCT, RMT, RCB, RMB,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: Mikolaj Metelski """ import json import pathlib import pickle import uuid from typing import Any, Dict, List, Tuple, Union import helpers from core import AbstractModel def run_on_param_grid(model: Union[AbstractModel.__class__, AbstractModel], ...
from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class PercentField(models.IntegerField): """ Integer field that ensures field value is in the range 0-100. """ default_validators = [ MinValueValidator(0), MaxValueValidator(100), ]...
import logging import os from dataclasses import dataclass, field from datetime import datetime from shutil import copy2 from typing import Generator, List, Optional from jinja2 import Environment, FileSystemLoader from PIL import ImageGrab logger = logging.getLogger(__name__) class ReportError(Exception): pass...
#módulo que vai ter um método que encripta arquivos def change_files(filename, cryptoFn, block_size=16): with open(filename, 'r+b') as _file: raw_value = _file.read(block_size) while raw_value: cipher_value = cryptoFn(raw_value) #compara o tamanho do bloco cifrado e do plain ...
# Generated by Django 3.1.2 on 2020-12-16 13:16 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('myapp', '0019_auto_20201216_1305'), ] operations...
# -*- coding: utf-8 -*- """ Created on Wed Apr 28 18:01:13 2021 @author: matisse """ import board, pieces, ia # Renvoie un objet de déplacement basé sur l'entrée de l'utilisateur. Il ne vérifie pas si le déplacement est valide. def get_utilisateur_move(): tour_str = input("Votre tour: ") tour_str...
import sys from TeproAlgo import TeproAlgo class TeproDTO(object): """This class will encapsulate all data that is sent back and forth among NLP apps that belong to the TEPROLIN platform.""" def __init__(self, text: str, conf: dict): # The original text to be preprocessed self._text =...