content
stringlengths
5
1.05M
""" This script displays the Trace image and the traces in an RC Ginga window. .. include common links, assuming primary doc root is up one directory .. include:: ../include/links.rst """ from pypeit.scripts import scriptbase class ChkAlignments(scriptbase.ScriptBase): @classmethod def get_parser(cls, widt...
# -*- coding: utf-8 -*- import random import string import time from datetime import datetime from apps.database.session import db from config import JsonConfig def get_model(model): if JsonConfig.get_data('TESTING'): return model.test_model return model def get_token(): random_string = string...
import json import os import pymzml import pandas as pd import numpy as np from tqdm import tqdm from matchms.importing import load_from_mgf from pyteomics import mzxml, mzml import logging logger = logging.getLogger('msql_fileloading') def load_data(input_filename, cache=False): """ Loading data generically...
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. import cohesity_management_sdk.models.site_backup_file import cohesity_management_sdk.models.site_info class SiteBackupStatus(object): """Implementation of the 'SiteBackupStatus' model. Attributes: backup_file_vec (list of SiteBackupFile): List ...
""" Language resources are defined separately from :class:`Intent` and :class:`Entity` classes. They are stored as plain YAML files in a `language/` folder, aside Agent Python modules; this is to be flexible in the relationship with designers and translators, as well as to allow some degree of automation when downloadi...
def intro(): print("*********************************************") print("* Friends of Seaview Pier *") print("*********************************************") print() def capture_new_member_details(volunteer_locations): member_details = [] firstname = "" lastna...
#!/usr/bin/env python # # test_fnirt.py - # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # import os.path as op import itertools as it import numpy as np import nibabel as nib import pytest import fsl.data.image as fslimage import fsl.utils.tempdir as tempdir import fsl.data.constants as co...
import torch from torch.nn import init import torch.nn as nn # ============================================================================= # ============================================================================= # This is a Pytorch implementation of Star Topology Convolution. # ===============================...
import boto3 import json import time import os cf = boto3.client('cloudformation') sns = boto3.client('sns') waiter = cf.get_waiter('stack_create_complete') def sendnotification(appname, nonprod_acc, message): env_name = appname.lower() sns_arn = "arn:aws:sns:us-east-1:" + nonprod_acc + ":ECSNotifica...
import torch import torch.nn as nn from models.AttnLayers import Attention class AttnDecoder(nn.Module): def __init__(self, hidden_size, output_size=1, use_attention=True, attention='tanh'): super(AttnDecoder, self).__init__() self.hidden_size = hidden_size self.output_size = output_size ...
from typing import List import re def valid_line(line: str) -> bool: """ 行バリデーション Parameters ---------- line: str 行テキスト Returns ------- valid: bool validであるフラグ """ lstriped = line.lstrip() if len(lstriped) == 0: return False if lstriped[0] ==...
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
## ========================================================================= ## ## Copyright (c) 2019 Agustin Durand Diaz. ## ## This code is licensed under the MIT license. ## ## utils.py ...
# Copyright (c) 2021 PaddlePaddle Authors. 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.org/licenses/LICENSE-2.0 # # Unless required by appl...
numbers = [int(x) for x in input().split()] print(sorted(numbers))
import os, sys import cv2 import numpy as np import pandas as pd import string import mediapipe as mp import pickle from zipfile import ZipFile from utils import StaticSignProcessor, mp_process_image, generate_dataframe, annotate_image, pred_class_to_letter # load the model with open('saved_model.pkl', 'rb') as f: ...
""" Asyncio pydispatch (Signal Manager) This is based on [pyDispatcher](http://pydispatcher.sourceforge.net/) reference [Django Signals](https://docs.djangoproject.com/en/4.0/topics/signals/) and reference [scrapy SignalManager](https://docs.scrapy.org/en/latest/topics/signals.html) implementation on [Asyncio](https:/...
# By manish.17, contest: ITMO Academy. Двоичный поиск - 2, problem: (D) Children Holiday # https://codeforces.com/profile/manish.17 m, n = map(int, input().split()) if m == 0: print(0) print(*[0]*n) quit() a = [] for i in range(n): t, z, y = map(int, input().split()) a += [[t, z, y]] alpha, omega ...
# coding: utf-8 # # created on April Fool's Day 2018 # In[1]: import os from pymatgen.io.vasp.sets import MPRelaxSet from pymatgen import Structure from Utilities import get_time_str, get_current_firework_from_cal_loc # In[2]: def Write_Vasp_POTCAR(cal_loc, structure_filename, workflow): """ Write PO...
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class Organization(models.Model): name = models.CharField(max_length=255) class CustomUserWithM2MManager(BaseUserManager): def create_superuser(self, username, orgs, password): user = self.model(use...
import os from setuptools import setup def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name="unitable", version="0.0.2", author="Mark Howison", author_email="mark@howison.org", url="https://github.com/mhowison/unitable", keywords...
from ferrisnose import AppEngineWebTest from ferris.core.controller import Controller from ferris.core.messages import Messaging from ferris.core.ndb import Model, ndb import json class Person(Model): title = ndb.StringProperty(required=True) content = ndb.TextProperty() class People(Controller): class ...
import soba.visualization.ramen.mapGenerator as ramen import soba.run from collections import OrderedDict from model import SEBAModel from time import time import os import signal from unittest import TestCase import json, requests from jsonschema import validate import socket import unittest import listener import sy...
from rest_framework import viewsets from rest_framework import permissions from rest_framework.response import Response from newsfeed.models import Entry from .renderers import MongoDBJSONRenderer from .mixins import MongoDBPaginationMixin class NewsfeedViewset(MongoDBPaginationMixin, viewsets.ViewSet): renderer...
"""Tic Tac Toe game using Min-Max algorithm""" from copy import deepcopy from tkinter import Button, Tk from tkinter.font import Font class Board: """Tic Tac Toe Game Board""" def __init__(self, other=None): self.player = "X" self.opponent = "O" self.empty = "-" self.size = 3 ...
# coding: utf-8 from common.np import * # import numpy as np from common.layers import Softmax class WeightSum: ''' Encoderの全系列の隠れ状態hs(N, T, H)と 系列ごとの重みを示すアライメントa(N, T)から積和を取り、 現系列の変換に必要な情報を含むコンテキストベクトルc(N, H)を 出力するレイヤ ''' def __init__(self): self.params, self.grads = [], [] ...
import argparse from itertools import chain import logging import pickle from multiprocessing import Pool from collections import defaultdict from gilda.grounder import load_gilda_models from indra_db_lite import get_plaintexts_for_text_ref_ids from indra_db_lite import get_text_ref_ids_for_agent_text from .cases i...
import cv2 as cv import numpy as np from time import gmtime, strftime, sleep, time import logging import math # NVIDIA jetson ues the gstreamer pipeline for getting it's data def gstreamer_pipeline (capture_width=800, capture_height=640, display_width=800, display_height=640, framerate=60, flip_method=0) : ret...
#!/usr/bin/python3 import pytest from brownie.convert import to_bytes def test_type_bounds(): with pytest.raises(ValueError): to_bytes("0x00", "bytes0") with pytest.raises(ValueError): to_bytes("0x00", "bytes33") def test_length_bounds(): for i in range(1, 33): type_ = "bytes" ...
# -*- coding: utf-8 -*- import os import sys import threading import time sys.path.append(os.path.join(os.getcwd(), "Lib")) from Lib.OCC import BRepPrimAPI from Lib.aocxchange import step_ocaf from Lib.OCC.gp import gp_Pnt from agent import Agent def __createBlock__(color, step_exporter, position): agent_box_shap...
# Copyright (2017-2021) # The Wormnet project # Mathias Lechner (mlechner@ist.ac.at) import numpy as np import torch.nn as nn import kerasncp as kncp from kerasncp.torch import LTCCell import pytorch_lightning as pl import torch import torch.utils.data as data # nn.Module that unfolds a RNN cell into a sequence class...
from __future__ import absolute_import from .DatabaseConnection import DatabaseConnection
import numpy from matplotlib import pyplot from matplotlib import colors from analytic_covariance import calculate_sky_power_spectrum from analytic_covariance import calculate_beam_power_spectrum_averaged from analytic_covariance import calculate_beam_power_spectrum from analytic_covariance import calculate_total_powe...
from __future__ import division, print_function, absolute_import import numpy from rep.estimators import XGBoostClassifier, XGBoostRegressor from rep.test.test_estimators import check_classifier, check_regression, generate_classification_data __author__ = 'Alex Rogozhnikov' def very_basic_xgboost_test(): X, y, ...
""" Make Catch pig with two agents. forked from: https://github.com/Bigpig4396/Multi-Agent-Reinforcement-Learning-Environment/ tree/master/env_CatchPigs Thanks to their authors. """ # pylint: disable-all # flake8: noqa # noqa import random import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec i...
# # ISC License # # Copyright (C) 2021 DS-Homebrew # Copyright (C) 2021-present lifehackerhansol # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # T...
"""Test for my functions.""" from functions import * def test_string_concatenator(): assert string_concatenator('abc', 'def') == 'abcdef' def test_DNA_to_mRNA_List(): assert DNA_to_mRNA_List('CTGATCG') == ['G', 'A', 'C', 'U', 'A', 'G', 'C'] def test_DNA_to_mRNA(): assert DNA_to_mRNA('CTGA...
from __future__ import absolute_import from django.conf import settings MEDIA_URL = getattr(settings, "MEDIA_URL", "/media/") ADMIN_URL = getattr(settings, "ADMIN_URL", "/admin/") STATIC_URL = getattr(settings, "STATIC_URL", "/static/")
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. # from twisted.conch.error import ConchError from twisted.conch.ssh import channel, connection from twisted.internet import defer, protocol, reactor from twisted.python import log from twisted.spread import banana import os, stat, pick...
import re ''' Step 1: Clean the triple file. In the dbpedia case, we just need the part of resource URI that indicate entity/type/predicate names. ''' fileName = []#List of triple files to be process notRdf = open('./notRdf.txt','w')#Record the lines that refers to a type but not rdf:type for index2,fname in en...
import netlink import pprint import cStringIO def get_family(): con = netlink.new_generic() hdr = netlink.new_genlmsg( { "cmd": netlink.CTRL_CMD_GETFAMILY, "version": 0, "reserved": 0 } ) payload = netlink.generic_id_...
## Created by C. Cesarotti (ccesarotti@g.harvard.edu) 04/2019 ## Last updated: 04/24/20 ## ## Calculates the event isotropy for ring configurations with ## random orientations. ## ############################# # import sys import time import warnings import numpy as np import matplotlib.pylab as plt import random from...
from pymongo import MongoClient import json client = MongoClient('localhost', 27017) db = client['pymongo_test'] cursor = db.pymongo_test posts = db.posts # post_data = { # 'Name': 'Milk', # 'Quantity': '1', # 'Expiration Date': '4/03/20' # } # result = posts.insert_one(post_data) # print('One post: {0}'...
import os.path import logging import shutil import pandas as pd import numpy as np import ada.utils.experimentation as xp class XpResults: @staticmethod def from_file(metrics, filepath): if os.path.exists(filepath): df = pd.read_csv(filepath, index_col=0) time_str ...
import torch from models.vae import VAE # lambda_d, lambda_od = 100, 10 def matrix_diag(diagonal): N = diagonal.shape[-1] shape = diagonal.shape[:-1] + (N, N) device, dtype = diagonal.device, diagonal.dtype result = torch.zeros(shape, dtype=dtype, device=device) indices = torch.arange(result.num...
import numpy as np import re, collections def get_vocab(filename): vocab = collections.defaultdict(int) try: with open(filename, 'r', encoding='utf-8') as fhand: for line in fhand: words = line.strip().split() for word in words: vocab[' '.join(...
# # Pyserini: Reproducible IR research with sparse and dense representations # # 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...
import xml.sax from hashlib import md5 def func1(): test_digest = md5("test string").digest() return test_digest def func2(): # double vulnerability test_digesta, test_digestb = md5("test string").digest(), md5("test string2").digest() return test_digesta, test_digestb def func3(val): assert 0 !...
# !/usr/bin/python # -*- coding: UTF-8 -*- from svg.path.path import * def get_quadratic_coordinate_with_time(t:float, /, *, p0:complex, p1:complex, p2:complex): if t < 0 or t > 1: return points = [p0, p1, p2] polynomials = [eval("(1-t)**2"), eval("2*t*(1-t)"), eval("t**2")] return sum([prod * ...
import numpy as np import os import sys import tensorflow as tf from model import CVAE import matplotlib.pyplot as plt import streamlit as st @st.cache(allow_output_mutation=True) def load_model(PATH): model = CVAE(2, 128) # Restore the weights model.load_weights(PATH) return model def main(): st...
import os import requests from dotenv import load_dotenv from fastapi import APIRouter, Depends import sqlalchemy from pydantic import BaseModel, SecretStr from app import config router = APIRouter() headers = {'x-rapidapi-key': os.getenv('api_key'), 'x-rapidapi-host': os.getenv('host') } class RentalLi...
import random import time import my_set import sys class Element: def __init__(self, val: int): self.val = val def __hash__(self) -> int: return self.val def time_fct(l1, l2, fct): start = time.time() output = fct(l1, l2) # output = timeout(fct, args=(l1, l2), timeout_duration=1...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals import requests import getpass from .utils import MyAdapter from .utils import make_response try: r_input = raw_input except NameError: r_input = input DEFAULT_BASE_URL = "https://127.0.0.1:5000/api/v1.0" ...
from .db import schemas from typing import List, Optional from pydantic import BaseModel class EnrichedUrl(BaseModel): url: Optional[schemas.Url] = None stats: List class RequestMetadata: def __init__( self, referer: str = "", os: str = "", browser: str = "", device: str = "" ): sel...
from util import * import yaml import sys from connect import create_service # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/gmail.compose'] def main(): if sys.argv[1] == None: print('To create and send email, include details in YAML file and speci...
from __future__ import absolute_import from bokeh.util.dependencies import import_required pd = import_required('pandas', 'glucose sample data requires Pandas (http://pandas.pydata.org) to be installed') from os.path import join from . import _data_dir data_dir = _data_dir() data = pd.read_csv( j...
#!/usr/bin/python # Copyright (C) Vladimir Prus 2003. Permission to copy, use, modify, sell and # distribute this software is granted provided this copyright notice appears in # all copies. This software is provided "as is" without express or implied # warranty, and with no claim as to its suitability for any purp...
def max_word(filename): """Return the most frequent word in the file filename.""" freq = {} for piece in open(filename, encoding = 'UTF-8').read().lower().split(): # is "piece" a line? # only consider alphabetic characters within this piece word = ''.join(c for c in piece if c.isalpha()) ...
import argparse import subprocess import sys from typing import Optional from .containerization import CAN_RUN_NATIVELY, DockerContainer, DockerRun from .plugins import Command class PolyBuild(Command): name = "build" help = "runs `polybuild`: clang with PolyTracker instrumentation enabled" _container: O...
#!/usr/bin/python # The usual preamble import numpy as np import pandas as pd import time # Get data (NYC 311 service request dataset) and start cleanup data = pd.read_csv('data/us_cities_states_counties.csv', delimiter='|') data.dropna(inplace=True) print "Done reading input file..." start = time.time() # Get all ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Mon Dec 12, 2011 @author:Isabel Restrepo A script to run (fast) k-means on the set of means found for each category """ import os; import dbrec3d_batch import multiprocessing import Queue import time import random import optparse import sys from math import lo...
import tweepy #library for building apps for twitter import time #library for controling the sleep of the message CONSUMER_KEY ="Enter your api key" CONSUMER_SECRET = "Enter your api secret key" ACCESS_KEY ="Enter your access key" ACCESS_SECRET="Enter your access secret key" auth = tweepy.OAu...
def get_maintenance_cost( mean, remainder, factor=40, decimal_places=3 ): expected_value_variable_squared = mean + (mean ** 2) return round( remainder + (expected_value_variable_squared * factor), decimal_places ) a_mean, b_mean = map(float, input().split()) print( ...
#!/usr/bin/env python3 import sys import os import time import serial # This is a quick and dirty control program for the Kenwood TM-271A and TM-281A # transceiver to allow remote base like operations for use with Allstar or # other digital modes. It is primarily targeted at the Raspberry Pi but being # in Python allo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/12/19 9:27 # @Author : NingAnMe <ninganme@qq.com> import argparse from dateutil.relativedelta import relativedelta import time from datetime import datetime import os import requests from lib.lib_cimiss import get_cimiss_ssi_ssh_tem_data from config i...
#!/usr/bin/python from __future__ import with_statement import sys import os default_path = '/usr/local/id/streaming_pb_downloader/current/configs' default_filename = 'event_name_list.txt' if len(sys.argv) > 2: print('Usage:\n{0}\nor\n{0} output_path'.format(sys.argv[0])) sys.exit(0) if len(sys.argv) == 2: defau...
from jinja2 import Environment, FileSystemLoader def main(frank, output_dir): print "Executing python codegen: main()", frank # load up the jinja template # env = Environment(loader=FileSystemLoader("")) env = Environment(loader=FileSystemLoader(__path__)) client = env.get_template("client.jinja"...
# # 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 writing, software # distributed under...
from functools import lru_cache from typing import Tuple, List, Dict import math from .RayInfluenceModel import RayGridInfluenceModel, Ray class WideRayGridInfluenceModel(RayGridInfluenceModel): """ Calculates the weights of the grid cells by calculating the distance of the center of the cell to the ray...
# Generated by Django 2.2.5 on 2019-09-06 16:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('search', '0001_initial'), ('team', '0001_initial'), ] operations = [ migrations...
import re import itertools regex = r"<x=(-*\d+),\sy=(-*\d+),\sz=(-*\d+)>" p = re.compile(regex) def moon(p_x, p_y, p_z, v_x, v_y, v_z): return {"pos": {"x": p_x, "y": p_y, "z": p_z}, "vel": {"x": v_x, "y": v_y, "z": v_z}} a = [] for line in open('day12-2019.txt').read().split('\n'): x, y, z = p.match(line)...
from . import * from ..fetchers import OAIFetcher from ..parsers import OAIParser class OAIController(CorpusController): '''CorpusController designed for the OAI database ''' # Default start date for batch retrieval DATE_FROM = datetime.date(2010, 1, 1) # Default time window for batch retrieval DATE_...
# Backward compatibility with Python 2. from __future__ import print_function, absolute_import, division # Suppress all warnings. import warnings warnings.filterwarnings('ignore') import tensorflow as tf from tensorflow.contrib import rnn from tensorflow.contrib import legacy_seq2seq import numpy as np class Mode...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.urls import reverse from django.db.models import Q from django.views.decorators.csrf import csrf_exempt from django.forms....
import logging import inspect from ..core.memory import MemoryException, FileMap, AnonMap from .helpers import issymbolic ###################################################################### # Abstract classes for capstone/unicorn based cpus # no emulator by default from unicorn import * from unicorn.x86_const imp...
#!/usr/bin/env python3 import os import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D import numpy as np from tqdm import tqdm from util.constants import PLEARN_ACTIONS, plearn_action_to_text from mivp_...
from collections import Counter from bs4 import BeautifulSoup from bs4.dammit import EncodingDetector from sparkcc import CCIndexWarcSparkJob from word_count import WordCountJob class CCIndexWordCountJob(CCIndexWarcSparkJob, WordCountJob): """ Word count (frequency list) from WARC records matching a SQL query ...
import pytest import pathlib from align.schema.subcircuit import SubCircuit from align.schema.parser import SpiceParser # WARNING: Parser capitalizes everything internally as SPICE is case-insensitive # Please formulate tests accordingly @pytest.fixture def setup_basic(): return 'X1 a b testdev x=1f y=0...
import torch import torch.nn as nn from torch.nn import LSTM, LSTMCell, Linear, Parameter class InteractorwoLSTM(nn.Module): def __init__(self, hidden_size_textual: int, hidden_size_visual: int, hidden_size_ilstm: int): """ :param input_size: :param hidden_size: ""...
from flask import Flask from flask import request app = Flask(__name__) # level 0 @app.route('/') def home_page(): html = """ <head> <title>我的网站</title> </head> <body> 这是我的网站 </body> """ return html # level 1 @app.route('/<name>') def sayhello(name): html = f""" ...
#2 step process take image of background and select a colour for the cloth. #code for image of the background import cv2 #This is my webcam cap = cv2.VideoCapture(0) #back is what camera is reading while cap.isOpened(): ret,back=cap.read() #Here i am simply reading from my webcam if ret: #same as writ...
# -*- coding: utf-8 -*- # Inspired by: # https://github.com/lingdb/CoBL/issues/223#issuecomment-256815113 from __future__ import unicode_literals, print_function from django.db import migrations from cobl.source_scripts.handle_duplicate_sources import handle_sources, \ sourcesExist sources_changes = {'merge': {}, ...
import pandas as pd def load_data(portfolio_data_absolute_path="/home/chris/Dropbox/Finance/data/portfolio_trades.ods", stock_data_absolute_path="/home/chris/Dropbox/Finance/data/stock_trades.ods", income_data_absolute_path="/home/chris/Dropbox/Finance/data/income.ods", etf_ma...
import os from PyQt4.QtCore import QDir, QFile, QSettings from whoosh import fields __appname__ = 'mikidown' __version__ = '0.3.1' class Setting(): def __init__(self, notebooks): # Index directory of whoosh, located in notebookPath. self.schema = fields.Schema( path = fields.TEXT(s...
import asyncio from perftests.helpers import Time, client print('Running rest_implementation benchmark with async_v20 version', client.version) async def rest_implementation(repeats): for _ in range(repeats): account = await client.account() account.json() loop = asyncio.get_event_loop() with Time...
#!/usr/bin/env python3 import sys, getopt, os from shutil import copyfile def main(argv): if os.environ['NEWT_TEMPLATE_PATH'] == '': template_path = "/opt/newt/templates" else: template_path = os.environ['NEWT_TEMPLATE_PATH'] template = '' filename = '' EXECUTABLE = False t...
def cci_parens(n): ls = [['(',1,0]] while(True): if(len(ls) == 0): break new_ls = [] for elem in ls: l = elem[1] r = elem[2] comb = elem[0] if(l == n): print(comb + (')'*(l-r))) continu...
import os import json import time import pandas as pd from haystack import Label, MultiLabel, Answer from haystack.utils import launch_es, fetch_archive_from_http, print_answers from haystack.document_stores import ElasticsearchDocumentStore from haystack import Document, Pipeline from haystack.nodes.retriever import...
from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="gpu_slic", version="0.0.1a3", python_requires=">=3.6", package_dir={"": "src"}, packages=find_packages(where="src"), include_package_data=True, install_requires=[ ...
from typing import List, Tuple, Union import numpy as np from pgdrive.component.lane.circular_lane import CircularLane from pgdrive.component.lane.straight_lane import StraightLane from pgdrive.constants import LineType from pgdrive.utils.utils import import_pygame PositionType = Union[Tuple[float, float], np.ndarra...
""" A Python wrapper for Transmission's RPC interface. >>> from transmission import Transmission >>> client = Transmission() >>> client('torrent-get', ids=range(1,11), fields=['name']) {u'torrents': [ {u'name': u'Elvis spotted in Florida.mov'}, {u'name': u'Bigfoot sings the hits'}, # ... {u'name': u'...
import collections import json import random import string import urllib.request from datetime import datetime, timedelta from os import urandom from pathlib import Path from flask import Flask, jsonify, request from flask_marshmallow import Marshmallow from flask_sharded_sqlalchemy import BindKeyPattern from flask_sh...
#!/usr/bin/python3 #basic class will be imported from here import astm_file2mysql_general as astmg import sys, logging, time #For mysql password sys.path.append('/var/gmcs_config') import astm_var log=1 my_host='127.0.0.1' my_user=astm_var.my_user my_pass=astm_var.my_pass my_db='biochemistry' inbox='/root/ashish....
from itertools import groupby class Solution: def countAndSay(self, n): def gen(s): return "".join(str(len(list(g))) + k for k, g in groupby(s)) s, i = "1", 1 while i < n: s = gen(s) i += 1 return s
import json history_path = 'outputs/ResUNet.json' history_file = open(history_path, "r") history = history_file.read() history_file.close() history = json.loads(history) import matplotlib.pyplot as plt plt.plot(history['train']) plt.plot(history['valid']) plt.legend(['train loss', 'valid loss']) plt.show()
from selenium import webdriver from PIL import Image from io import BytesIO import time import re import argparse import os import json from utils import generate_img_filename from templates import template_path def get_args(): example_text = ''' examples: python openassessit/%(capture_element_pic)s --in...
from electrum_ltc.i18n import _ fullname = _('Satochip 2FA') description = ' '.join([ _("This plugin allows the use of a second factor to authorize transactions on a Satochip hardware wallet."), _("It sends and receives transaction challenge and response."), _("Data is encrypted and stored on a remote serve...
from django.db import models from django.utils.timezone import now class Company(models.Model): class CompanyStatus(models.TextChoices): LAYOFFS = "Layoffs" HIRING_FREEZE = "Hiring Freeze" HIRING = "Hiring" name = models.CharField(max_length=30, unique=True) status = models.CharFi...
from unittest import TestCase from mock import Mock, patch class TestAPIConnection(TestCase): def setUp(self): self._requests_patcher = patch('broadstreetads.requests') self.requests = self._requests_patcher.start() def tearDown(self): self._requests_patcher.stop() def one(self, ...
import plato_fit_integrals.initialise.create_ecurve_workflows as ecurves import matplotlib.pyplot as plt def plotFittedIntsVsInitial(integInfo,coeffsToTablesObj): initInts = coeffsToTablesObj._integHolder.getIntegTableFromInfoObj(integInfo,inclCorrs=False).integrals fitInts = coeffsToTablesObj._integHolder...