text
stringlengths
3.07k
12.6k
import sys, os, time, shutil, spotipy, time, datetime, logging, io from urllib.request import urlopen from spotipy.oauth2 import SpotifyClientCredentials clientID = '' clientSecret = '' IGNORE_ARTWORK = False def setClientData(ID, secret): global clientID global clientSecret clientID = ID clientSecret = secret ...
import json from enum import Enum from flask import Flask, request from flask_cors import cross_origin from .db import ( DB, COIN_USER_KEY, COIN_AMOUNT_KEY, COIN_CGID_KEY, COIN_SYMBOL_KEY, COIN_PRICE_KEY, COIN_WALLET_TYPE_KEY, PWD_KEY, USERNAME_KEY, ) PORTFOLIO_DATA_COINS_KEY = 'c...
import turtle, random ''' TODO: DONE 1. Make a little tree as a step toward genetic algorithm. DONE 2. Add a seed 3. Put all the parameters in a list. 4. produce a couple rows of trees with random parameters 5. make it so you can click to further evolve a particular tree. How much can you simplify this? Make a recurs...
import pytest import numpy as np from numpy.testing import assert_allclose from sklearn.compose import ColumnTransformer from sklearn.datasets import load_boston from sklearn.datasets import load_iris from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble...
"""Create geocube.""" import os from datetime import datetime as dt import numpy as np from ..vectors import deg180 def _header(cube): """Geocube header. Parameters ---------- cube: pyvims.VIMS VIMS cube. """ return f""" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;...
#!/usr/bin/env python import roslib; roslib.load_manifest('robot_kf') import rospy import math import numpy as np import scipy.optimize from nav_msgs.msg import Odometry from robot_kf.msg import WheelOdometry from sensor_msgs.msg import Imu class OdometryCalibrator: def __init__(self): self.time_gps = list...
#!/usr/bin/env python # coding: utf-8 # In[3]: # this definition exposes all python module imports that should be available in all subsequent commands import json import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow...
from optapy import problem_fact, planning_id, planning_entity, planning_variable, \ planning_solution, planning_entity_collection_property, \ problem_fact_collection_property, \ value_range_provider, planning_score from optapy.types import HardSoftScore from datetime import time @problem_fact class Room: ...
""" """ # TODO test raising exceptions import hashlib import string from pathlib import Path import pytest from pfmsoft.util.file_hash import file_hash @pytest.fixture(scope="function") def hash_test_data(tmp_path): test_data_root_dir = tmp_path / "file_hash_test_data" test_data_root_dir.mkdir(exist_ok=Tr...
#!/usr/bin/env python3 import argparse import datetime import json import logging import os import sys import tempfile import yaml from typing import Any, List, Dict from .vm_operator.hetzner_cloud_operator import HetznerCloudOperator from .scan_worker.ssh_worker import SshWorker LOG_FORMAT = '%(asctime)s %(filena...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import time import cv2 import numpy as np import rospy from absl import flags, app from pyrobot import Robot from cmp_runner import...
#! python """ Utils for outputing read status of FL reads, and making read mapping abundance file. """ from collections import defaultdict from ..io import GroupReader, MapStatus, ReadStatRecord, \ ReadStatReader, ReadStatWriter, AbundanceRecord, AbundanceWriter __author__ = '<EMAIL>' def read_group_file(group...
# -*- coding: utf-8 -*- """ This micro-service provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: <NAME> """ import time import Pyro4 from...
import random import numpy as np import gym from gym.spaces import Box, Discrete from actor_net import ActorNet from critic_net import CriticNet from actor_net_bn import ActorNet_bn from critic_net_bn import CriticNet_bn from tensorflow_grad_inverter import grad_inverter from collections import deque import os "...
import os import re import pipes import socket import conducto as co from . import client_utils, constants, container_utils, log, types as t from ..internal import host_detection as hostdet def agent_container_name(): profile_id = co.api.Config().default_profile host_id = co.api.Config().get_host_id() ret...
# -*- coding: utf-8 -*- from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from django import forms from django.utils.translation import ugettext, gettext from django.contrib.auth.forms import Se...
from collections import namedtuple import datetime import logging import os import pytz import firebase_admin from firebase_admin import credentials from firebase_admin import firestore from user_report import response_data_util from user_report import table_config _PROJECT_NAME = os.environ.get('PROJECT_ID') _SURVE...
""" Implemention of the Maze ADT. """ import turtle import pygame from dataclasses import dataclass from lliststack import Stack class Maze: """ Class for representing Maze objects. Attributes: maze: The list of lists representing the maze. _start: The starting position of the maze; marked...
# -*- coding: utf-8 -*- """Utility functions to manage the MySQL database, includes SQLAlchemy classes and functionality. """ import os import argparse import logging import sys from datetime import datetime as dt from sqlalchemy import create_engine, Column, CHAR, VARCHAR, BigInteger, \ Integer, String from sqlalc...
# -*- coding:utf-8 -*- from flask_restful import Resource, reqparse from common.log import loggers from common.sso import access_required from common.db import DB from common.const import role_dict from collections import Counter from common.utility import salt_api_for_product import os logger = loggers() parser = re...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Aplicación para resolver el Challenge Python L1 Desarrollado por <NAME> version 1.0 Bitacora: fecha: 2021-02-27 observacion: Version 1 por: <NAME> """ import requests import pandas as pd import json import hashlib from datetime im...
""" Copyright (c) 2019 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 Unless required by applicable law or agreed to in writin...
import pandas as pd import tensorflow as tf import argparse # CSV_COLUMN_NAMES = ['id', 'uid', 'gzh', 'xh', 'gz', 'middle_time', 'avg_time', 'ios', 'android', 'wifi', 'nonwifi', 'game0', 'game1', 'game2', 'game3', 'game4', 'type', 'dates'] CSV_COLUMN_NAMES = ['id', 'uid', 'gzh', 'xh', 'gz', 'deposit', 'time0', 'time1'...
#!/usr/bin/env python3 from ipaddress import ip_address, ip_network from requests import get from os.path import join from tarfile import open as taropen from shutil import move, rmtree from os import unlink from re import match from math import log2 from ipwhois import IPWhois from geoip2.database import...
from RecSearch.Config.ConfigGenMeta import meta_data_objects import PySimpleGUI as sg from RecSearch.Config.ConfigGenInputDef import InputFunctions from RecSearch.Config.ConfigGenKeyManage import KeyManager, default_key_manager class MainDataWorkerLayoutManager: """Manages DataWorker/Interface GUI Layout Creation...
# Create your views here. from rest_framework import status from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, DestroyAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from mlh.utils.paginat...
# -*- coding: utf-8 -*- """Main module.""" from typing import Any, List, Tuple, Union import pyparsing as pp from asn1vnparser import _grammar, jsonencoder def parse_asn1_value( asn1_value: str, as_json: bool = False, parse_all: bool = True ) -> Union[Any, str, Tuple[Any, str], Tuple[str, ...
#---------------------------------------------------------------------- # Copyright (c) 2013, <NAME> # 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 r...
from utils.mol_geometry import compute_torsion, compute_angle, compute_distance, ic_to_xyz import torch import numpy as np def construct_z_matrix(X, ref_atoms, placing_order): ''' Given a torch.tensor array, whose rows are the cartesian coordinates of a molecule, generates a Z-matrix computing internal coordin...
from torch.autograd import Variable from copy import deepcopy import torch import numpy as np import time from utils import get_prediction def deepfool( im, net, lambda_fac=3.0, overshoot=0.02, step_size=0.01, max_iter=50, device="cuda", ): n_queries = 0 X0 = deepcopy(im) # - Keep...
import numpy as np import pandas as pd from copy import deepcopy from typing import Callable, Union, Tuple def predefined_sample(max_num_attempts, screen_likely_voters): """ Generate a function that will contact a particular number of people and use whoever responds. (i.e. "I'm going to call 1000 people ...
#!/usr/bin/env python3 # # (C) 2018-2020 <NAME> # Create PETSc binary files .vec,.is from ascii .msh mesh file generated by Gmsh. # This script reads both the current (4.1) and legacy (2.2) file formats from # Gmsh. See # http://gmsh.info/doc/texinfo/gmsh.html#MSH-file-format # http://gmsh.info/doc/texinfo/gmsh....
""" Coconut zero-knowledge proofs. """ from petlib.bn import Bn from bplib.bp import BpGroup from hashlib import sha256 from binascii import hexlify from coconut.utils import ec_sum def to_challenge(elements): """ generates a Bn challenge by hashing a number of EC points """ Cstring = b",".join([hexlify(x.exp...
import logging from collections import OrderedDict from django.urls import reverse from rest_framework import serializers from rest_framework.utils.serializer_helpers import ReturnDict logger = logging.getLogger(__name__) def update_or_create_links(model, instance, instance_type, links_data): '''Update or crea...
import math import random import fractions # This is method to compute Euler's function # The method here is based on "counting", which is not good for large numbers in cryptography def phi(n): amount = 0 for k in range(1, n + 1): if math.gcd(n, k) == 1: amount += 1 return amount # The...
import importlib import sys from datetime import timedelta as delta import numpy as np import parcels import xarray as xr sys.path.append("/nethome/4302001/diffusion-hydro-mod/kernels") import Markov1_3D_BC_taper import Markov1_3D_BC_taper_init import density_elements_sampled dt = 40*60 # seconds Tl = 20*24*60*60 ka...
import sampling import torch import math import logging logger = logging.getLogger(__file__) class DefaultStateStore: def __init__(self, model, default_token = 0): self.last_token = {} self.states = {} self.model = model self.default_token = default_token def forward(self, request): key = requ...
import cv2 import time import numpy as np import pandas as pd from matplotlib import pyplot as plt import os import random import albumentations as albu from albumentations.pytorch.transforms import ToTensorV2 import torch import torchvision from torch.utils.data import DataLoader, Dataset from models import MyModel ...
#! /usr/bin/env python3 from __future__ import print_function from builtins import range import optparse import os import re from pprint import pprint import six epsilon = 1.e-4 def getPieceFromObject (obj, description): """Returns piece from object """ parsed = GenObject.parseVariableTofill (description) ...
# Copyright 2019 <NAME> # Licensed under the Apache License, Version 2.0 (the "License") import random import torch import torch.nn as nn import torch.nn.functional as F from . import freeze_module from .s2s_transformer import Encoder as AttnEncoder from .s2s_lstm import Encoder, Decoder class AttnAligner(nn.Module...
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import random import datetime dayInMonth = {1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} """ Function: warmupGenerator ========================= Create warm up visualization data set Three students on t...
# -*- coding: utf-8 -*- import contextlib import github import keyring # NOQA import pytest import requests # NOQA import zazu.github_helper __author__ = "<NAME>" __copyright__ = "Copyright 2016" def test_make_gh_with_saved_credentials(mocker): mocker.patch('keyring.get_password', return_value='token') moc...
from __future__ import annotations import math, random, time from typing import Any, Optional, Union from . import items from .items import format_currency from .store import CannotAffordError, Error, Store as _Store class User: __slots__ = ('store', 'id', 'balance', 'boost', 'inventory', '_next_boost') def __...
# -*- encoding: utf-8 -*- ''' @Filename : main.py @Datetime : 2020/08/19 16:12:29 @Author : Joe-Bu @version : 1.0 ''' import os import sys sys.path.append('../../') from copy import deepcopy from datetime import datetime, timedelta import numpy as np import pandas as pd # from sklearn.preprocessing imp...
# This script compute metrics and cache predictions on val/test set # Flow: parse args -> get predictions -> compute metrics -> cache results # Usage: # PYTHONPATH='/home/users/arsh/ultrasound' \ # CUDA_VISIBLE_DEVICES=1 \ # taskset --cpu-list 10-19 \ # python src/main/eval.py --config va5.yml import argparse import ...
import numpy as np from time import process_time from dir_spec.ds import ds import matplotlib.pyplot as plt DATA_FILE = 'test_data.npz' N_CHANS = 5 def test_wsf(plot=False): """Test DS estimation via Wilson spectral factorization.""" X, area, fs = _load_data() start = process_time() wsf_ds = ds(X, fs...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from imageio import imread import torchvision class PerceptLoss(object): def __init__(self): pass def __call__(self, LossNet, fake_img, real_img): with torch.no_grad(): real_feature = LossNet(re...
import numpy as np import torch import torch.nn.functional as F from torch.autograd import Variable, Function from utils import NanError, HookDetectNan, HookPrintName, count_nans from global_const import Tensor def real(z): return z[..., 0] def imag(z): return z[..., 1] def conjugate(z): z_copy = z.cl...
""" Defines the Datalite decorator that can be used to convert a dataclass to a class bound to a sqlite3 database. """ import sqlite3 as sql from dataclasses import asdict, make_dataclass from sqlite3 import IntegrityError, Connection from typing import Optional, List, Union, Type, TypeVar from .commons import _conver...
# encoding=utf-8 import os,sys import numpy as np import matplotlib.pyplot as plt import random from collections import Counter #交互式显示 plt.ion() plt.figure("Agent's Q(s,a)") THE_NUMBER = 21 ENV_POLICY = "not-random" class ENV(object): def __init__(self): self.policy = ENV_POLICY return def r...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 <NAME> # # 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 require...
from tkinter import * import tkinter.messagebox tk = Tk() tk.title("Tic Tac Toe") pa = StringVar() playerb = StringVar() p1 = StringVar() p2 = StringVar() bclick = True flag = 0 def disableButton(): button1.configure(state=DISABLED) button2.configure(state=DISABLED) button3.configure(stat...
import yaml import pytest from unittest import mock from argparse import Namespace from mlagents.trainers.upgrade_config import convert_behaviors, main, remove_nones from mlagents.trainers.settings import ( TrainerType, PPOSettings, SACSettings, RewardSignalType, ) BRAIN_NAME = "testbehavior" # Check...
from taichi.core import ti_core as _ti_core from taichi.lang.impl import field from taichi.lang.kernel_impl import kernel from taichi.lang.matrix import Vector from taichi.lang.ops import atomic_add from taichi.types.annotations import template from taichi.types.primitive_types import f32 from .staging_buffer import (...
import torch from torch import nn from torch import optim from torchvision import datasets, transforms, models import torch.nn.functional as F from torch.optim import lr_scheduler from torch.autograd import Variable from collections import OrderedDict def create_model(arch="vgg19", hidden_units=4096, learning_rate=0.0...
#!/usr/bin/env python import _socket import logging from argparse import ArgumentParser from json import loads from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR, SO_REUSEPORT from socket import error as SocketError, timeout as TimeoutError from socket import socket from threading import Lock, Thread fr...
# python3 from sys import stdin import copy EPS = 1e-6 PRECISION = 20 class Equation: def __init__(self, a, b): self.a = a self.b = b class Position: def __init__(self, column, row): self.column = column self.row = row def ReadEquation(): size = int(input()) a = []...
import glob import logging import os.path from abc import abstractmethod from typing import Dict, Iterator, List, Optional, Type, Union from common import directories, file_utils from common.commands.database import DatabaseUploadCommand from common.types import ( Context, EntityExtractionResult, EntityLoc...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ TensorFlow Helper functions. """ from __future__ import unicode_literals import os import tensorflow as tf from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops, control_flow_ops from tensorflow.contrib.rnn import EmbeddingWrapper...
#* pyx509 - Python library for parsing X.509 #* Copyright (C) 2009-2010 CZ.NIC, z.s.p.o. (http://www.nic.cz) #* #* This library is free software; you can redistribute it and/or #* modify it under the terms of the GNU Library General Public #* License as published by the Free Software Foundation; either...
# # Util for WebDriver # import sys from string import Formatter from functools import wraps from numbers import Integral from .locator import Locator from .keys import Keys PY3 = sys.version_info[0] == 3 class MemorizeFormatter(Formatter): """Customize the Formatter to record used and unused kwargs.""" ...
from __future__ import print_function import os import sys import unittest from functools import partial import numpy try: sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) except: sys.path.insert(0, os.path.dirname(os.path.abspath("."))) from bx.bbi.bigwig_file import BigWigFile def allclose(...
import numpy as np import matplotlib.pyplot as plt import scipy.constants as physcons from amuse.units import units from amuse.community.vader.interface import Vader G = physcons.G*1e3 | units.cm**3 / units.g / units.s**2 def setup_vader (params): torb = 2.*np.pi*params['R_out']/params['vphi'] chi = G*par...
# (c) 2021 Okawo # This code is licensed under MIT license (see LICENSE for details) """Server loop that communicates between the driver and posers.""" import asyncio from .__init__ import __version__ DOMAIN = (None, 6969) class Server: def __init__(self): """ im not sure about this on chief, ...
import os.path as osp from glob import glob import tensorflow as tf from tensorflow_datasets.core import ( Version, GeneratorBasedBuilder, DatasetInfo ) from tensorflow_datasets.core.features import ( FeaturesDict, Image as ImageF, Text, Tensor, ClassLabel, ) import numpy as np from PIL...
import abc from megastone.mem.errors import MemoryWriteError from elftools.elf import elffile from elftools.elf.constants import P_FLAGS, SH_FLAGS from ..execfile import ExecFile from ..format import ExecFormat from megastone.mem import AccessType, Segment from megastone.mem.segments import SplittingSegmentMemory, Di...
from kivy.app import App from kivy.properties import StringProperty from kivymd.uix.label import MDLabel from plyer import email from . import BaseScreen from ..i18n import _ from ..utility import get_app_details class ConsentLabel(MDLabel): """ Class with Pre-defined label style. Style defined in KV language. "...
""" Utilities """ import functools import glob import multiprocessing as mp import os import numpy as np import tqdm import yaml class Config: __slots__ = [ 'workspace', 'sds_root', 'sfile_root', 'tfrecord', 'train', 'test', 'eval', 'sql_database...
_auther_ = 'Harry' _date_ = '5/22/2018 3:07 PM' from time import time import hashlib import json from flask import Flask,jsonify,request from uuid import uuid4 from urllib.parse import urlparse import requests from argparse import ArgumentParser class Blockchain: def __init__(self): #构造函数 self.chain =...
import unittest from mock import Mock from arbalest.pipeline import SqlTimeSeriesImport from arbalest.redshift.schema import Property, JsonObject def assert_schema_equal(test_case, expected, actual): test_case.assertEqual(expected.table, actual.table) test_case.assertEqual(expected.update_table, actual.update...
from enum import Enum from json import load as json_load from os import listdir from time import sleep from requests.sessions import Session class ADFObjectType(Enum): """ Set of object types in Azure Data Factory that can be deployed. """ LinkedService = 'linkedService' Dataset = 'dataset' ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 <NAME> # # 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 a...
############################################################################# # # Copyright (c) 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFT...
""" Author: <NAME>, <EMAIL> Date: 04/2017 """ import bcrypt from flask import request from bson import json_util, ObjectId import pymongo from api import auth, db from api.module import Module from api.models.models import Order, OrderException, Shipping, Customer, Product, OrderedProduct, OrderedProductException f...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
import asyncio import gc import os import socket import time import uuid from concurrent.futures import ThreadPoolExecutor import aioodbc import pyodbc import pytest import uvloop from aiodocker import Docker @pytest.fixture(scope='session') def session_id(): """Unique session identifier, random string.""" ...
#!/usr/bin/python # _*_ coding: utf8 _*_ import sqlite3 import yaml import sys import os PATH_CURRENT = os.path.abspath(__file__) PATH_PARENT = os.path.dirname(PATH_CURRENT) WORKHOME = os.path.dirname(PATH_PARENT) HOSTSINVENTORY = WORKHOME+'/ansible/jieyun.hosts' GROUPVAR = WORKHOME+'/ansible/group_vars/all.yml' PLA...
from django.shortcuts import render, redirect from django.http import HttpRequest, HttpResponse from django.db.models import Q from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from .models import User, Message, Roo...
""" Builds the Excel wrapper classes from a Strata class. """ from .method_builders import get_method_builder, ArgConverterBuilder def get_wrapper_class_name(class_name): """Gets the default wrapper class name for a Strata class name.""" components = class_name.split(".") if tuple(components[:3]) != ("com...
import os import glob import numpy as np import torch import sys import pipes from classifier_control.classifier.utils.general_utils import str2int class CheckpointHandler: @staticmethod def get_ckpt_name(epoch): return 'weights_ep{}.pth'.format(epoch) @staticmethod def get_epochs(path):...
from typing import Optional,Tuple from math import log import torch from torch.nn import ModuleList, Linear, BatchNorm1d from torch import Tensor import torch.nn.functional as F from torch_sparse import SparseTensor,matmul from torch_geometric.nn.conv import MessagePassing from torch_geometric.typing import OptTensor ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= ## @file ostap/fitting/roofit.py # Module with decoration of some RooFit objects for efficient use in python # @author <NAME> <EMAIL> # @date 2011-06-07 # ==================================...
# coding: utf8 from collections import namedtuple import os from unittest import TestCase from oopycql.query import CypherQuery class RegexForParameterFindingTestCase(TestCase): TestParamFinderQuery = namedtuple('TestParamFinderQuery', 'query params') TEST_QUERIES = [ TestParamFinderQuery( ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from website.apps.core.models import Language from website.apps.lexicon.models import Lexicon from website.apps.pronouns.models import Paradigm, PronounType, Pronoun, Relationship from website.apps.pronouns.tests import P...
from pathlib import Path from typing import Awaitable, Callable, List, Optional import aiohttp from yarl import URL from ._abc import ( AbstractDeleteProgress, AbstractDockerImageProgress, AbstractFileProgress, AbstractRecursiveFileProgress, ImageCommitFinished, ImageCommitStarted, ImagePr...
from rest_framework import serializers from drf_base64.fields import Base64ImageField from data.models import Farmer, FarmImage from api.serializers import ExperimentFastSerializer, MediaListSerializer def get_writable_method_field(base_serializer_class): """ Returns a SerializerMethod field that inherits the ...
import pyclaw.runclaw from numpy import * from numpy import linalg import pylab import subprocess import unittest import os import inspect import types import implicit_claw.python.claw_solution_1d as claw_solution_1d import implicit_claw.python.claw_solution_2d as claw_solution_2d class ConvergenceTestError(Excepti...
import codecs import csv import argparse import re METRIC_FILE = 'logs/chatbot_metrics.txt' CLASSES_FILE = 'logs/class_correspondances.csv' PROPERTIES_FILE = 'logs/property_correspondances.csv' UNDER_BRACKETS_RE = re.compile('\[(.*?)\]') DATE_FORMAT = '%Y-%m-%d %H:%M:%S,%f' CSV_PROPERTIES_HEADER = ['domain_field', ...
from datetime import datetime import bcrypt from flask import json from flask_login import UserMixin from slugify import slugify from martinblog import db # many to many relationship post_has_tags = db.Table( 'post_has_tags', db.Column('post_id', db.Integer, db.ForeignKey('Entries.PostID', onde...
from pynq import PL from .emmio import EMMIO # Register Space REG_CONTROL = 0x00 REG_GIE = 0x04 REG_IE = 0x08 REG_IS = 0x0C REG_ACTIVE_HEIGHT = 0x10 REG_ACTIVE_WIDTH = 0x18 REG_BG_PATTERN_ID = 0x20 REG_FG_PATTERN_ID = 0x28 REG_MASK_...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import subprocess import sys import os try: from setuptools import setup except ImportError: from distutils.core import setup CLASSIFIERS = """ Development Status :: 3 - Alpha Intended Audience :: D...
import collections import hashlib from django import forms from django.conf import settings from django.db import models from django.db.models import Max from django.db.models.signals import post_save from django.dispatch import receiver from django.template.defaultfilters import slugify from django.utils import timez...
""" This file has functions to process edf files. """ import os import sys import bz2 import _pickle as cPickle import numpy from multiprocessing import Pool # ------------------------------------------------------------------------------ def decompress_pickle(filename): ''' Load any compressed pickle file ...
"""Launcher of a needed file. *Undone.*""" import tkinter import os import tkinter.messagebox as mbox import tkinter.simpledialog as dialog from action import action # Mind this import. ### Tests ############################################################################## # info = tkinter.Label(window, text=...
from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.conf import settings from django.utils.translation import gettext_lazy as _ from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel...
""" Module containing ASTVistor class and helpers useful for traversing and extracting information from an AST. """ from lib2to3 import pytree from lib2to3.patcomp import compile_pattern from lib2to3.pgen2 import token from lib2to3.pytree import Node, Leaf __all__ = ["ASTError", "ASTVisitor", "descend", "find_last_le...
import os import argparse import math import itertools import time import urllib.request import json from concurrent.futures import ThreadPoolExecutor import tiletanic import shapely def get_args(): parser = argparse.ArgumentParser(description='xyz-tile download tool') parser.add_argument('tileurl', ...
#! /usr/bin/env python3 # # Copyright 2020 <NAME> <<EMAIL>> # # 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, modi...
import sys from pathlib import Path sys.path.append(str(Path(__file__).absolute().parent.parent)) """Map uncertain labels to constant labels (e.g. 0, 1) or to labels from another file.""" import argparse import pandas as pd import util from collections import Counter, OrderedDict from dataset.constants import COL_PAT...
#!/usr/bin/env python """GRR config parsing code.""" import abc import collections import configparser import errno import io import logging import os from typing import Any, BinaryIO, Dict, Type from grr_response_core.lib.util.compat import yaml class Error(Exception): pass class SaveDataError(Error): """Rai...