content
stringlengths
5
1.05M
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- import sys import tornado.web import tornado.httpserver import tornado.ioloop import tornado.options import tornado.websocket from os.path import join, isdir from gen import cfg from core.loader import load from json impor...
import datetime import subprocess import os import socket general_current_folder = os.path.basename(os.getcwd()) general_current_year = datetime.datetime.now().year general_homedir = os.path.expanduser('~') # d.general_hostname=subprocess.check_output(['hostname']).decode().rstrip() general_hostname = socket.gethostna...
""" https://www.hackerrank.com/challenges/making-anagrams/problem """ def makingAnagrams(s1, s2): if s1 == s2: return 0 else: all = set(s1+s2) k1 = {i: s1.count(i) for i in all} k2 = {i: s2.count(i) for i in all} k3 = {} for i, v in k1.items(): diff =...
# Copyright 2020-2022 OpenDR European Project # # 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 agree...
import time class SingleObject: already_instantiated = False def __init__(self, number): """You can only make one of these!""" if self.already_instantiated is True: print("This test is going to take a really really long time") time.sleep(60) self.mark_instantiate...
#!/usr/bin/env python3 import math import sys if len(sys.argv) != 2 : print('Usage: {} <file> >file.bin'.format(sys.argv[0]), file=sys.stderr) sys.exit(1) input = sys.argv[1] alphabet = None with open(input, 'r') as fd: alphabet = set(fd.read()) alphabet = ''.join(sorted(list(alphabet - set('\n')))) bit...
""" Copyright 2021 Bernard Spiegl 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,...
from adt import adt, Case @adt class Cmd: CASE0: Case CASE1: Case[str] CASE2: Case[str, str] CASE3: Case[str, str, str]
# -*- coding: utf-8 -*- from __future__ import absolute_import import unittest import pushpad import requests import datetime try: import mock except ImportError: from unittest import mock class TestNotification(unittest.TestCase): _test_token = '5374d7dfeffa2eb49965624ba7596a09' _test_project_id = 12...
#!/usr/bin/python3 # Chao Xu import os import logging import argparse import re import time import urllib from selenium import webdriver from reportlab.pdfgen import canvas # logger LOGGER='dumpbook118' DEFAULT_WAIT_INTERVAL=2.5 def init_logging(verbose): log = logging.getLogger(LOGGER) ch = loggi...
import os import sys import numpy as np from PIL import Image from skimage import io from skimage.color import rgba2rgb, gray2rgb from sklearn.model_selection import train_test_split from torch.utils.data import Dataset sys.path.append('../') from research.age.cfg import cfg class UTKFaceDataset(Dataset): """ ...
######## # Copyright (c) 2015 GigaSpaces Technologies Ltd. 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...
# -*- coding: utf-8 -*- """ Created on Mon Aug 7 14:32:04 2017 @author: Benjamin """ from bin_sort import bins_are_neighbours import numpy as np # ----------------------------------------------------------------------------- GLOBAL_VERBOSITY_FLAG = True def print_generations(bin_generations): if GLOBAL_VERB...
import os import pandas as pd import numpy as np import pyddem.tdem_tools as tt fn_csv = '/data/icesat/travail_en_cours/romain/results/vol_final/dh_19_rgi60_int_base.csv' nproc=64 fn_tarea='/data/icesat/travail_en_cours/romain/data/outlines/rgi60/tarea_zemp.csv' fn_out = '/data/icesat/travail_en_cours/romain/results/v...
from z3 import * import constraint as cnst # Input variable matrix m = [[ Int("x_%s_%s" % (i+1, j+1)) for j in range(9)] for i in range(9) ] constraint = cnst.entryCnst + cnst.rowCnst + cnst.colCnst + cnst.squareCnst instance = ((0,0,0,0,9,4,0,3,0), (0,0,0,5,1,0,0,0,7), (0,8,9,0,0,0,0,...
import torch from torch.autograd import Variable from numpy.fft import rfft2, irfft2 class BadFFTFunction(torch.autograd.Function): def forward(self, input): numpy_input = input.numpy() result = abs(rfft2(numpy_input)) return input.new(result) def backward(self, grad_output): ...
dicinario =dict() d=list() for i in range(0,3,1): dicinario["nome"]=input(f"digite o nome de indice[{i}]: ") dicinario["idade"]= input(f"digite a idade de indice[{i}]: ") d.append(dicinario.copy()) for i in range(0,3): print(f"{d[i]['nome']}=={d[i]['idade']}")
import logging from logging import INFO, DEBUG, WARNING, ERROR # pylint: disable=unused-import def get_logger(name): logging.basicConfig(format='%(asctime)s %(levelname)s :\t%(filename)s (%(lineno)d) :\t%(funcName)s :\t%(message)s') logger = logging.getLogger(name) return logger
from scipy.stats import spearmanr import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import shutil from scipy.stats import rankdata import time from scipy.spatial.distance import pdist, squareform import _pickle as cp def min_max_transform(data): ''' This function does a linear ...
import json from typing import Callable, Dict, List, NewType, Tuple, Optional from pydantic import BaseModel, Field, NonNegativeInt, PositiveInt from pydantic.utils import import_string from electricitymap.contrib.config import EXCHANGES_CONFIG, ZONES_CONFIG # we could cast this to a NamedTuple with x/y accessors Po...
from mayan.apps.rest_api import generics from ..models.document_models import RecentlyCreatedDocument from ..permissions import permission_document_view from ..serializers.document_serializers import DocumentSerializer class APIRecentlyCreatedDocumentListView(generics.ListAPIView): """ get: Return a list of ...
import numpy from chainer import cuda from chainer import function from chainer import utils from chainer.utils import type_check class Maximum(function.Function): """Element-wise maximum of input variables.""" def check_type_forward(self, in_types): type_check.expect( in_types.size() ==...
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLES1 import _types as _cs # End users want this... from OpenGL.raw.GLES1._types import * from OpenGL.raw.GLES1 import _errors from OpenGL.constant import Constant as _C ...
# This code is a part of yawlib library: https://github.com/letuananh/yawlib # :copyright: (c) 2014 Le Tuan Anh <tuananh.ke@gmail.com> # :license: MIT, see LICENSE for more details. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^synset/(?P<s...
import shutil import sys,os sys.path.insert(0,os.path.join(os.path.dirname(__file__),"..")) os.environ['LIGHT9_SHOW'] = "_test_show" try: shutil.rmtree("_test_show") except OSError: pass os.mkdir("_test_show") f = open("_test_show/config.n3", "w") f.write(""" @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema...
# # PySNMP MIB module H3C-MINM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-MINM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:09:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
#!/usr/bin/env python3 import random import unittest from panda import pack_can_buffer, unpack_can_buffer class PandaTestPackUnpack(unittest.TestCase): def test_panda_lib_pack_unpack(self): to_pack = [] for _ in range(10000): address = random.randint(1, 0x1FFFFFFF) data = bytes([random.getrandbi...
import sqlite3 def connect(): try: con = sqlite3.connect('db.sqlite') except sqlite3.Error as error: print(f"Failed to connect to the database: {error}") return return con def init_db(): con = connect() try: cur = con.cursor() query = """ creat...
""" forms definition for the app """ from wtforms import Form, StringField, validators, BooleanField class EmailForm(Form): email = StringField('Email', [validators.Length(min=6, max=60), validators.Email()]) class LoginForm(EmailForm): password = StringField('Password', [validators.Length(min=6, max=40)])...
import json import os from datetime import datetime from datetime import timedelta import airflow import urllib3 from airflow import DAG from airflow.models import Variable from airflow.operators.python import BranchPythonOperator from airflow.operators.python import PythonOperator from airflow.operators.trigger_dagru...
import string from datetime import datetime import nltk import sklearn_crfsuite from sklearn.model_selection import train_test_split from sklearn_crfsuite import metrics from ..argument_pipeline.base import Model from ..corpora import load_essay_corpus from ..corpora._essay_corpus import tokenize_essay_sentences from...
from django.db import models class Category(models.Model): name = models.CharField(max_length=30) parent = models.ForeignKey('Category', on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Expense(models.Model): amount = models.DecimalField(max_digits=10, decimal_...
# The input funciton allows you to prompt the user for a value # You need to declare a variable to hold the value entered by the user name = input('What is your name? ') print(name)
import os import requests import pandas as pd class Landslide: """Contains the NASA landslide data Atributes --------- df: pandas.DataFrame Dataframe with landslide data Methods ------- summarize Returns summary statistics of the dataset ""...
""" Testing Module For TagManager """ import uuid import pytest import time from ticktick.helpers.hex_color import generate_hex_color def test_check_fields_labels(client): """Tests exception raised for all bad inputs in _check_fields""" # Test label already exists name = str(uuid.uuid4()) label = nam...
#! /usr/bin/env python3 # changing bases for IP address management from sys import argv def main(): global theNum global mode mode = argv[1] theNum = input("Enter address to to convert to {}: ".format(mode)) if "." in theNum: concat = "" theNum = theNum.split(".") #print...
from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.views import PasswordChangeView from django.views.generic import TemplateView from slavdict...
import json import os from celery import Celery from weather import Weather from base import Session from pytz import timezone host = os.environ['REDIS_HOST'] port = os.environ['REDIS_PORT'] app = Celery('tasks', broker='redis://' + host + ':' + port + '/0') @app.task(name='saveData') def save(data): ...
import socket import os #-----------------to find the local IP address---------------------- gw = os.popen("ip -4 route show default").read().split() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((gw[2], 0)) ip = s.getsockname()[0] gateway = gw[2] host = socket.gethostname() print ("IP:", ip, " GW:", ...
import numpy as np import snc.utils.snc_types as types from typing import Set def is_pull_model(model_type: str) -> bool: """ Function determines whether network is a pull model by checking the model type string. """ return model_type == 'pull' def get_dynamic_bottlenecks(w: types.WorkloadSpace, ...
from __future__ import unicode_literals, print_function, division from collections import OrderedDict import struct import sys from pcapparser import packet_parser from pcapparser import pcap, pcapng, utils from pcapparser.constant import FileFormat from pcapparser.printer import HttpPrinter from pcapparser.httpparser...
__author__ = "patras" import numpy as np class GoalDescriptor(): def __init__(self, gid, params, value, r, achieved_func=None, failure_func=None, refinement=None): self.goalId = gid self.goalArgs = params # params include arguments and values self.goalValue = value self.reward = r ...
# coding: utf-8 # In[1]: import sys import warnings if not sys.warnoptions: warnings.simplefilter('ignore') import tensorflow as tf import numpy as np from tqdm import tqdm import re import collections import json import os from unidecode import unidecode def batch_sequence(sentences, dictionary, maxlen = 5...
import numpy as np import tensorflow as tf _BATCH_NORM_DECAY = 0.9997 _BATCH_NORM_EPSILON = 0.001 def batch_norm_relu(inputs, training_phase, name): inputs = tf.layers.batch_normalization(inputs, axis=1, momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, training=...
"""Image processing software for locating intracranial electrodes.""" __version__ = '2.0' from img_pipe.utils import list_rois, export_labels # noqa from img_pipe.img_pipe import (check_pipeline, recon, compute_warp_to_template, # noqa plot_pial, label, reg_CT_to_MR, ...
from textblob import TextBlob import random, sys, os, math import parser LINE_MAX = 6 WORDS_MAX = 20 ERROR = "?#$*&! - that word is not in the corpus." class Caption: def __init__(self, content): self.text = None self.content = content self.words = None self.word_count = None ...
from __future__ import print_function import tkinter as tk import pyaudio import wave import numpy as np import os from keras.models import load_model on_hit = False pre_hit = False CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 RECORD_SECONDS = 2 WAVE_OUTPUT_FILENAME = "D:\\Github\\k...
import json from typing import Any, Dict, Iterable import jsonlines from benedict import benedict def read_jsonline_file(filename: str) -> Iterable: """Read a jsonline file Parameters ---------- filename : str The jsonline file Returns ------- Iterable [description] ...
import abc import attr import tensorflow as tf from filterflow.base import State from filterflow.resampling.base import ResamplerBase, resample @tf.function def _discrete_percentile_function(spacings, n_particles, on_log, weights=None, log_weights=None): """vectorised resampling function, can be used for system...
# This file is part of Indico. # Copyright (C) 2002 - 2022 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. import fnmatch import re from collections import defaultdict from datetime import datetime from hashlib im...
import psyco; psyco.full() from fltk import * import copy, time import sys sys.path.append('..') import GUI.ysSimpleViewer as ysv import Resource.ysOgreDataLoader as yol import Resource.ysMotionLoader as yf import Renderer.ysRenderer as yr import Util.ysPythonEx as ype import Implicit.csIMSModel as cmm i...
import numpy as np def sel_slice(sel, dims): return tuple([ slice(None) if dim not in sel.keys() else sel[dim] for dim in dims ]) def sel_dims(sel, dims): return [ dim for dim in dims if dim not in sel.keys() or \ isinstance(sel[dim], np.ndarray) or \ type(sel[dim]) in (list, tuple) ]
print('importing functions from the pymicro library') try: from pymicro.apps.wxImageViewer import ImageViewer from pymicro.apps.wxVolumeViewer import wxVolumeViewer from pymicro.apps.View import View except: print('exception occured importing modules') from pymicro.crystal.lattice import * from pymicro...
import ConfigParser class Config: def __init__(self, file_name='controller_config.ini'): self.RASPBERRY_PI_DATA_PIN = None self.TRANSMITTER_CODES = None self.EARLIEST_ENABLE_HOUR = None self.EARLIEST_ENABLE_MINUTE = None self.LATEST_DISABLE_HOUR = None self.LATEST_D...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # soitbegins, a script that imports an image and sets necessary image metadata properties # version: 0.0.1a # Copyright 2018 Brian King # License: Apache import argparse import datetime from getpass import getpass import json import keyring import os import plac import r...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2020 all rights reserved # """ Instantiate a script """ def test(): # access the framework import pyre # declare a trivial application class application(pyre.application, family='shells.application'): ...
""" Modified SHIFT training script for use with hackathon data. you can change training settings by modifying args in opt rather than command line Place this script in the SHIFT/ directory and place the "utils/data.py" file as "hack_data.py" in the root directory as well. """ import time from models import create_mod...
from jwcrypto import jwk, jwt import httplib2 import json import os import pkgutil import time import urllib class AppleMusic(object): def __init__(self): self.key = jwk.JWK() key_path = os.path.join(os.path.dirname(__file__), 'AuthKey_8937YX2XGP.p8') self.key.import_from_pem(file(key_path,...
#!/usr/bin/python2 ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); y...
"""Integration testing for the application's summary module. """ import os import unittest from portiapy import summary from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) class TestSummary(unittest.TestCase): """Set of integration tests for all functions concerning the summary module. """ ...
from datetime import datetime from app import database as db class Chatroom(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(150), nullable = False) creationDate = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) lastUpdate = db.Column(db.DateTim...
from allauth.socialaccount.adapter import get_adapter from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider from django.urls import reverse_lazy from django.shortcuts import redirect from accounts.models import User from .apps impor...
from baduk.command.command_types import UndoableCommand from baduk.stones.group_of_stones import GroupOfStones from baduk.stones.stone_link import StoneLink class MergeWithAdjacentGroupsOfStones(UndoableCommand): def __init__(self, groups: set, stone_link: StoneLink, adjacent_stones: list): self.stone_li...
#!/usr/bin/env python """ Take .txt output of multiple structure alignment between PDBs as generated by gesamt (http://www.ccp4.ac.uk/dist/html/gesamt.html) and output label files to use with GetContacts. """ import os class Aligned_Residues: def __init__(self, processed_line, include_nonaligned=False): ...
"""Host Reservation DHCPv4""" # pylint: disable=invalid-name,line-too-long import pytest import misc import srv_msg import srv_control @pytest.mark.v4 @pytest.mark.host_reservation @pytest.mark.kea_only def test_v4_host_reservation_circuit_id(): misc.test_setup() srv_control.config_srv_subnet('192.168.50.0...
try: from typing import Literal except ImportError: from typing_extensions import Literal from .base import BaseFunction class Now(BaseFunction): obj: Literal['functions.Avg'] = 'functions.Now' alias: str = None def to_sql(self) -> str: sql = "NOW()" if self.alias is not None: ...
from gammagl.datasets import Flickr def test(): dataset = Flickr('./Flickr', 'flickr') g = dataset.data pass test()
# -*- coding: utf-8 -*- """Basic functions and classes to check for permissions.""" from django.contrib.auth.mixins import UserPassesTestMixin from rest_framework import permissions GROUP_NAMES = ['student', 'instructor'] class IsOwner(permissions.BasePermission): """Custom permission to only allow owners of an...
import gin import rdkit from rdkit import Chem import pandas as pd import numpy as np import numpy.testing as npt import pytest import tensorflow as tf BONDS = { Chem.BondType.SINGLE:1.0, Chem.BondType.DOUBLE:2.0, Chem.BondType.TRIPLE:3.0, Chem.BondType.AROMATIC:1.5, Chem.BondType.UNSPECIFIED:0.0 }...
#!/usr/bin/env python3 import json import shlex from argparse import ArgumentParser from typing import List, Any, Dict import subprocess import os import yaml def load_yaml(fp) -> Any: return yaml.load(fp, Loader = getattr(yaml, "CLoader", yaml.Loader)) def update_all(apps_list: str, branch: str, apps_dir: str,...
from os import environ import os import shutil import requests import tempfile import nltk.data from gevent.pywsgi import WSGIServer from flask import Flask, after_this_request, render_template, request, send_file from subprocess import call from predict_certainty import CertaintyEstimator #from certainty...
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import numpy as np import math import seaborn as sns import geopandas as gpd import requests import shapely from shapely.geometry import Point with st.echo(code_location='below'): st.title("Рынок апартаментов Москвы") st.header("Я хочу ...
#Wallet import SocketUtils import Transactions import TxBlock import pickle import Signatures head_blocks = [None] wallets = [('localhost',5006)] miners = [('localhost',5005),('localhost',5007)] break_now = False verbose = True my_private,my_public = Signatures.generate_keys() tx_index = {} def StopA...
# coding: utf-8 # create by tongshiwei on 2019/7/2 __all__ = ["url_dict", "get_data"] import os from urllib.request import urlretrieve import requests from bs4 import BeautifulSoup from longling import config_logging, LogLevel, path_append # from longling.spider import download_data from .utils import decompress DE...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('heritage', '0011_projectasset'), ] operations = [ migrations.RemoveField( model_name='interviewasset', ...
#!/usr/bin/python # -*- coding: utf8 -*- import sas as main_sas import time import binascii import random import string sas=main_sas.sas('/dev/ttyS3') sas.start() #print sas.int_to_bcd(1234567890365421,8) ### EFT to machine ##for i in range(1,6): ## a= sas.eft_load_cashable_credits( amount=10, coun...
# Copyright 2014 OpenStack Foundation # 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 requ...
import datetime from mixer.backend.mongoengine import mixer from mongoengine import NotUniqueError, ValidationError from mass_flask_core.models import AnalysisSystem, AnalysisSystemInstance from mass_flask_core.tests import FlaskTestCase from mass_flask_core.utils import TimeFunctions class AnalysisSystemInstanceTest...
# Generated by Django 3.1.1 on 2020-09-29 05:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('customer_profiles', '0002_auto_20200927_1118'), ] operations = [ migrations.RemoveField( model_name='customerprofile', name=...
#!/usr/bin/env python # coding=utf-8 """ 本模块用于作文自动拼写、语法检查及纠错. 本模块中包含以下类: FlaskApp: 作文自动拼写、语法检查及纠错 本模块中包含以下方法: writingGrammarCorrect: 作文自动拼写、语法检查及纠错接口方法 本模块中包含以下属性: app: 作文自动拼写、语法检查及纠错应用程序 """ from gevent import monkey monkey.patch_all() import os import time import json import logging import logging.h...
# Put development specific settings here
import arcade from mc2d.config import ( FULLSCREEN, TITLE, WINDOW_SIZE ) from mc2d.main_menu import MainMenu def main(): window = arcade.Window(*WINDOW_SIZE, TITLE, fullscreen=FULLSCREEN) main_menu = MainMenu() window.show_view(main_menu) main_menu.setup() arcade.run() if __name__...
"""Unit test for treadmill.runtime.linux._manifest. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest # Disable W0611: Unused import import tests.treadmill_test_skip_windows # pylint: disable=W061...
from urllib2 import urlopen import os from shutil import copy2 from datetime import datetime import sys repCutoff = 1000 searchURL = "http://forum.kerbalspaceprogram.com/index.php?/search/&type=core_members&sortby=pp_reputation_points&sortdirection=desc&page=[PAGENUMBER]" Desc_File = "Descriptions.txt" Output...
BinaryOperators = {'/' : lambda a, b: '\\frac{' + a + '}{' + b + '}'} UnaryOperators = {'sqrt' : lambda a: '\\sqrt{'+ a + '}'} def set(equation): Output = [] terms = equation.split(" ") i = 0 while i < len(terms): term = terms[i] if term == '*': Output.append('\\cdot') ...
r""" Variationally optimizing measurement protocols ============================================== .. meta:: :property="og:description": Using a variational quantum algorithm to optimize a quantum sensing protocol. :property="og:image": https://pennylane.ai/qml/_images/illustration1.png .. related:: ...
import decimal import datetime import PySimpleGUI import ets2.model def wear_info_label(label, key): return [PySimpleGUI.Text(label, size=(11, 1), justification="left"), PySimpleGUI.Text("---", size=(5, 1), ...
""" Microsoft Academic Graph ======================== """ from sqlalchemy import Column, ForeignKey from sqlalchemy.dialects.mysql import VARCHAR, TEXT from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import relationship from sqlal...
from PIL import Image import cv2 import sys import numpy as np import os S = 255 Dir = os.getcwd() path = os.path.join(Dir, 'source') images = os.listdir(path) for file in images: filename = file.split('.')[0] image = cv2.imread(f"{path}/{file}") # if in rgb shape = image.shape if ...
import discord import logging from typing import Coroutine, List, Union, TYPE_CHECKING from discord.ext import commands from gtbot.core.action import Action from gtbot.core.errors import NotAllowed, NotFound, SilentError from gtbot.core.team import Lorax, Krampus from .lorax import PlantTree, CreateFores...
from django.conf.urls import patterns, include, url import views urlpatterns = patterns('', # Examples: # url(r'^$', 'campaignManager.views.home', name='home'), # url(r'^blog/', include('blog.urls')), #url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'), url(r'^new_turn/(?P<campaign_id>\d+)/$',...
''' Created on Apr 16, 2018 @author: broihier ''' import bluetooth import Lock import Switch class BluetoothServer(object): ''' Bluetooth server class ''' def __init__(self): self.switch = Switch.Switch(2) self.server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.se...
#!/usr/bin/env python """Creates an override file based on a large .env file. The existing stacks ship with very large .env files. These files duplicate all of the defaults in the .yml files. We have realised that this makes reading the .env file quite over-whelming. The .env file doesn't need to export anything that ...
#!/usr/bin/python # # Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "L...
""" This module contains event handlers for events fired during the Codenames game. """ import json from flask_socketio import emit from flask_login import current_user from app import socketio, db from app.games.codenames.models import ( CodenamesTeams, CodenamesRooms, ) from .constants import NAMESPACE, TE...
"""Contains helpers for heterogeneous queue items.""" import typing as t class Entry(t.NamedTuple): """Data structure that helps manage heterogeneous queues. This designates the source of where an entry came from, the entry kind from that source, and the data associated with the entry. """ sourc...
from iminuit._core import FCN, MnUserParameterState, MnMigrad, MnStrategy from pytest import approx import pytest @pytest.fixture def debug(): from iminuit._core import MnPrint prev = MnPrint.global_level MnPrint.global_level = 3 yield MnPrint.global_level = prev def test_strategy(): assert...
''' Author: yangxingchen Date: 2021-02-04 11:27:47 LastEditors: yangxingchen LastEditTime: 2021-02-04 11:28:56 Description: ''' from . import api
# -*- coding: utf-8 -*- """ 【简介】 内置信号槽示例 """ from PyQt5.QtCore import QObject, pyqtSignal # 信号对象 class QTypeSignal(QObject): # 定义一个信号 sendmsg = pyqtSignal(object) def __init__(self): super(QTypeSignal, self).__init__() def run(self): # 发射信号 self.sendmsg.emit('Hell...
try: from ._util import * from .global_var import * from .Qobj import * except: from _util import * from global_var import * from Qobj import * import matplotlib.pyplot as plt from scipy.optimize import minimize import logging log = logging.getLogger('LabberDriver') class QuantumParser(): ...