content stringlengths 5 1.05M |
|---|
import pyglet
from grid import Terrain
from pyglet.window import key
class Window(pyglet.window.Window):
def __init__(self):
super(Window,self).__init__(800, 800)
self.terrain = Terrain(self.get_size()[0], self.get_size()[1], 10)
def on_draw(self):
self.clear()
sel... |
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from kit.dtypes import KustoType
from kit.models.serializable import SerializableModel
@dataclass
class Column(SerializableModel):
dtype: str = KustoType.STRING.value
name: Optional[str] = None
index: Option... |
import tvm
from tvm.tensor_graph.core2.graph.concrete import Compute, Tensor
######################################################################
# for functional, all states are inputs, data from inside functionals
# can only be constants
######################################################################
de... |
import datetime as dt
import json
from bson import json_util
import pygal
import time
from pygal.style import BlueStyle
# These functions work on the GroupB totalStorage collection.
# as the dataset grows larger these methods will take too long
# in the future, may want to use "group by" equivalent and use map-reduc... |
from datetime import datetime, date
import json
from unittest.mock import patch
import tempfile
import os
from delphi_hhs.run import _date_to_int, int_date_to_previous_day_datetime, generate_date_ranges, \
make_signal, make_geo, run_module, pop_proportion
from delphi_hhs.constants import SMOOTHERS, GEOS, SIGNALS, ... |
import textwrap
sample_text = "fasdfsa' f sf af asfsadfsadfas as sdf asfsdf sdafsadfs s sa fsadf sadfsadasfdsadfsd f sdfasd fsd"
# Wrap this text.
wrapper = textwrap.TextWrapper(width=20)
word_list = wrapper.wrap(text=sample_text)
# Print each line.
for i, element in enumerate(word_list):
print(i, element)
|
import functools
from typing import TypeVar, Union, Callable, Any, List, Optional
from purpleserver.core import datatypes
from purpleserver.core import serializers
T = TypeVar('T')
def identity(value: Union[Any, Callable]) -> T:
"""
:param value: function or value desired to be wrapped
:return: value or ... |
# Analyze distribution of RGZ counterparts in WISE color-color space
#
rgz_dir = '/Users/willettk/Astronomy/Research/GalaxyZoo/rgz-analysis'
paper_dir = '/Users/willettk/Astronomy/Research/GalaxyZoo/radiogalaxyzoo/paper'
from astropy.io import fits
import numpy as np
from matplotlib import pyplot as plt
from matplotli... |
# -*- coding: utf-8 -*-
import math
# Zadanie 6 ---------------------------------
rad = float(input('Proszę podać promień okręgu: '))
circ = 2 * rad * math.pi
area = rad**2 * math.pi
print('\nOkrąg o promieniu', rad, 'ma: \n obwód równy', circ, '\n pole równe', area)
|
from PIL import ImageTk
from tkinter import END
from PIL import Image
from cv2 import imread, imwrite
import processImage as pI
import os
import popupWindows as pW
from tkinter.colorchooser import askcolor
exePath = os.getcwd()
def readScale(self):
# Disable manual checkbox
self.parent.ch1.config(state='dis... |
import core.utils as utils
def test_should_get_domain(db):
assert utils.get_domain() == 'http://example.com'
def test_should_get_domain_raise_error(db, mocker):
mock = mocker.patch.object(utils, 'Site')
mock.objects.get_current.side_effect = Exception
assert utils.get_domain() == ''
|
import pytest
from zoo.datacenters import utils as uut
@pytest.mark.parametrize(
"email,expected",
[
("[email protected]", "Jon Doe"),
("[email protected]", "Platform"),
("something", "Something"),
],
)
def test_email_to_full_name(email, expected):
assert uut.email_to_full_name... |
# Generated by Django 3.0.2 on 2020-02-13 03:47
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AdminUpdate',
fields=[
('ad... |
from cpselect import cpselect
|
# Generated by Django 3.2.7 on 2022-01-22 07:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_auto_20220122_1437'),
]
operations = [
migrations.AddField(
model_name='post',
name='is_editor_pick',
... |
"""
Credits:
Copyright (c) 2019-2022 Matej Aleksandrov, Matej Batič, Grega Milčinski, Domagoj Korais, Matic Lubej (Sinergise)
Copyright (c) 2019-2022 Žiga Lukšič, Devis Peressutti, Nejc Vesel, Jovan Višnjić, Anže Zupanc (Sinergise)
Copyright (c) 2019-2021 Beno Šircelj
This source code is licensed under the MIT license... |
"""
Loading MNIST data
"""
from mnist import MNIST
import numpy as np
def MNIST_load(N):
mndata = MNIST('samples')
y,z = mndata.load_training()
z = np.array(z[0:N])
y = np.array(y[0:N])/256
D = np.shape(y)[1]
zvalues = np.arange(0,10)
K = 10
gmm_data= {'y': y, 'z': z, 'N':N,'K': K,'D... |
"""
Revision ID: 0143_remove_reply_to
Revises: 0142_validate_constraint
Create Date: 2017-11-21 10:42:25.045444
"""
import sqlalchemy as sa
from alembic import op
revision = "0143_remove_reply_to"
down_revision = "0142_validate_constraint"
def upgrade():
op.drop_column("services", "letter_contact_block")
o... |
import numpy as np
import timeit
def Buffering_Array(Thresholded_Hologram,Initial_Hologram,Pixel_Size,Buffer_Size,Begin_Time,time_slices):
buffer_elements_x = np.int(np.floor(Buffer_Size[0]/Pixel_Size[0]))
buffer_elements_y = np.int(np.floor(Buffer_Size[1]/Pixel_Size[1]))
buffer_elements_z = np.int(n... |
'''
Brain Fuck Interpreter Python Edition
Python version should greater than Python 3.10.0
Author: Mux
Copy Right: Mux, 2021
'''
try:
import sys
if sys.version_info.major >= 10:
print("Python version should greater than 3.10")
exit(-1)
except ImportError as ierr:
print("Python do not inst... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import ezgal
class weight(object):
""" ezgal.weight class
Used to apply weights to EzGal model objects through multiplication """
weight = 1
ezgal_type = ''
def __init__(self, weight):
... |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from libica.openapi.libtes.api.task_runs_api import TaskRunsApi
from libica.openapi.libtes.api.task_versions_api import TaskVersionsApi
from libica.openapi.libtes.api.tasks_api import TasksApi
|
from clld.db.meta import DBSession
from clld.db.models.common import Source
from clldutils.misc import slug
from dogonlanguages.models import Document
def bangime(req):
docs = {
'memorial': 'eldersmemorialcall07',
'bangerimevocabulaire': 'bangerimevocabulaire',
'bangerimephrases': 'banger... |
#!/bin/python3
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao
# 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, ... |
version = '2.1.4'
version_cmd = 'riak version'
download_url = 'http://s3.amazonaws.com/downloads.basho.com/riak/2.1/2.1.1/ubuntu/trusty/riak_2.1.1-1_amd64.deb'
install_script = """
dpkg -i riak_2.1.1-1_amd64.deb
"""
|
def verificar_repeticao(numero):
if numero < 10:
return True
if 10 <= numero < 100:
d1 = numero // 10
d2 = numero - d1 * 10
if d1 == d2:
return False
else:
return True
if 100 <= numero < 1000:
d1 = numero // 100
d2 = (numero - d... |
"""ppm docker compose new命令的处理."""
from typing import Dict
from pmfp.utils.endpoint import EndPoint
from ..core import (
dockercompose,
common_schema_properties
)
properties: Dict[str, object] = {
"dockercompose_name": {
"type": "string",
"title": "f",
"description": "指定docker-compo... |
from domain.route import entity
from flask_mongoengine import BaseQuerySet
from domain.airport.service import get_airport
from domain.airport.dtos import json_from_airport, json_from_airports
def args_to_origin(args):
origin_name = args.get('origin', None)
return None if origin_name is None else get_airport(or... |
from django.db import models
from django.conf import settings
from SocialNetwork_API.models.timestamped import TimeStampedModel
from SocialNetwork_API.models.user_types import PositiveTinyIntegerField
class Api(TimeStampedModel):
expired_at = models.DateTimeField(auto_now=False, default=settings.REST_FRA... |
# coding=utf-8
# Copyright 2022 The Reach ML Authors.
#
# 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 ... |
import math
def structure_solution(solution):
res = {
# List of classes with their exams
'classes': {},
# List of exams with their teachers
'teachers': {},
# Number of days
'days': 0
}
for block in solution:
day = math.floor(block[2] / 4)
... |
from arm.logicnode.arm_nodes import *
class LoopNode(ArmLogicTreeNode):
"""Resembles a for-loop (`for (i in from...to)`) that is executed at
once when this node is activated.
@seeNode While
@seeNode Loop Break
@input From: The value to start the loop from (inclusive)
@input To: The value to e... |
from django.contrib import admin
from .models import Category, Post, Tag
class PostAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'created_at', ]
list_display_links = ['id', 'title', ]
ordering = ['-created_at', 'id', ]
search_fields = ['title', 'content', ]
date_hierarchy = 'created_at'... |
from stix_shifter.stix_translation import stix_translation
from stix_shifter_utils.utils.module_discovery import modules_list
translation = stix_translation.StixTranslation()
class TestTranslationDialecs(object):
def test_supported_dialects(self):
modules = modules_list()
for module in modules:
... |
import ccxt.async as ccxt
import asyncio
import json
import networkx as nx
from .utils.general import ExchangeNotInCollectionsError
class CollectionBuilder:
def __init__(self):
self.exchanges = ccxt.exchanges
# keys are market names and values are an array of names of exchanges which support that... |
import keras
import json
import os.path
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
from keras.optimizers import RMSprop
import os
from os import environ
from keras.callbacks import TensorBoard
from emetrics import EMetrics
import pandas as pd
from math import sqrt
import numpy as ... |
"""This module contains the general information for AdaptorRssProfile ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class AdaptorRssProfileConsts:
pass
class AdaptorRssProfile(ManagedObject):
"""This is AdaptorRssPr... |
from arxiv.submission.domain.agent import User
TITLES = [
(2344371, 'Maximally Rotating Supermassive Stars at the Onset of Collapse: The Perturbative Effects of Gas Pressure, Magnetic Fields, Dark Matter and Dark Energy', User(native_id=12345, email='[email protected]', forename='', surname='', suffix='', identifier=Non... |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Qubit reset to computational zero.
"""
from .instruction import Instruction
from .instructionset import InstructionSet
fr... |
#! /usr/bin/python
try:
import xmlrpclib as xrc
except ImportError:
import xmlrpc.client as xrc
#s = xrc.dumps(("str", 1, True, {"k1": 1, "k2": 2}), "testfunc")
s = xrc.dumps(("<str&#~!>", 1, True), "testfunc")
print(s)
print(xrc.dumps(({},), "testfunc"))
print(xrc.dumps(({"1": "ab", "2": "cd"},), "testfunc"... |
"""empty message
Revision ID: 0058_add_letters_flag
Revises: 0057_change_email_template
Create Date: 2016-10-25 17:37:27.660723
"""
# revision identifiers, used by Alembic.
revision = "0058_add_letters_flag"
down_revision = "0057_change_email_template"
import sqlalchemy as sa
from alembic import op
def upgrade():... |
from django.db import models
import django
django.setup()
# Create your models here.
class Carouseldata(models.Model):
heading = models.CharField(max_length=30)
text_field = models.CharField(max_length=250)
image = models.FileField(upload_to='uploads/')
|
#!/usr/bin/env python
# -*- mode: python; encoding: utf-8 -*-
"""Test the fileview interface."""
from grr.gui import runtests_test
from grr.lib import access_control
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib import rdfvalue
from grr.lib import test_lib
from gr... |
import numpy as np
import pandas as pd
from libreco.data import random_split, DatasetPure
from libreco.algorithms import SVDpp # pure data, algorithm SVD++
# remove unnecessary tensorflow logging
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ["KMP_WARNINGS"] = "FALSE"
tf.compat.... |
from django.conf import settings
from django.http import HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.utils.decorators import method_decorator
from django.utils.html import escape
from django.utils import translation
from django.vie... |
"""
This file contains the code for the task that gets details of an IPO.
"""
import json
from core.constants import GREET_MESSAGE, REDIS_HASHES, DATA_STR, V1_DATA_STR, PAYMENTS_LINK, INFO_MESSAGE, CREATORS_LINK_1, CREATORS_LINK_2
from redis_conf import RedisConf
from scrapers.mybot import MyBot
def fetch_ipo_de... |
# ----------------------------------------------------------------------------
# Copyright (c) 2018-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
#!/usr/bin/env python3
# =============================================================================
# License: WTFPL
# =============================================================================
"""Getting to grips with the pandas DataFrame.
Run this example script using this command:
python example.... |
import pytest
from pytest_bdd import given, scenario, then, when
@pytest.mark.skip(reason="Currently not implemented")
@scenario('../docker_build.feature', 'Dockerfile is not found')
def test_dockerfile_is_not_found():
pass
@given('a path that does not contain a Dockerfile')
def a_path_that_does_not_contain_a_doc... |
#
# Copyright 2018 Analytics Zoo Authors.
#
# 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... |
import cv2
from cv2 import aruco as aruco
import numpy as np
import os
def aruco_3D_to_dict(object_points):
object_ndarray = np.loadtxt(object_points, delimiter=",")
return {int(array[0]): array[1:].tolist() for array in object_ndarray}
def load_coefficients(path):
'''Loads camera matrix and distortion c... |
from pygwin._pg import pg as _pg
from pygwin.surface import surface as _surface
from PIL import Image as _im
import tempfile as _tf
import randstr as _rs
import pickle as _p
import bz2 as _bz2
import os as _os
def load(path):
if path.endswith('.gif'):
im = _im.open(path)
with _tf.Tempor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check density inversion QC test
"""
import numpy as np
from cotede.qc import ProfileQC
from cotede.qctests import DensityInversion, densitystep
from ..data import DummyData
from .compare import compare_feature_input_types, compare_input_types
try:
import gsw
... |
from dataiku.exporter import Exporter
import re
import json
import logging
from splunklib.binding import connect
import splunklib.client as client
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO,
format='splunk plugin %(levelname)s - %(message)s')
class SplunkIndexExpo... |
from tkinter import *
root = Tk() #Tk() opens up a blank window, and we've set it equal to root
topFrame = Frame(root) #It's better to split your window layout into parts, which here, are called frames
topFrame.pack() #pack literally means to stuff 'things' into the window, here we stuffed in one frame
bottomFram... |
from requests_html import HTMLSession
import sbol2
import rdflib
class col_methods:
"""A class used to carry out a switch case statement for different\
properties in SBOL files
"""
def __init__(self, prop_nm, prop_val, sbol_doc, role_dict, org_dict):
"""The switch statement to call differe... |
def merge_sort(items):
if len(items) <= 1:
return items
# split
middle_index = len(items) // 2
left_split = items[:middle_index]
right_split = items[middle_index:]
return middle_index, left_split, right_split
# re-merge
def merge(left, right):
result = []
while (left and right):
... |
import datetime
import pytz
from django.contrib.auth.models import Group, Permission
from django.core.exceptions import ValidationError
from django.db.models.deletion import ProtectedError
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from rest_framework import status
from rest_frame... |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
from matplotlib.dates import DateFormatter
path = "C:\\Users\\pierre\\Downloads\\files\\Download\\samsunghealth_pierre.major_202008021218\\com.samsung.shealth.sleep.202008021218.csv"
df = pd.read_csv(path, index... |
import random
from myelin.core import Policy
class RandomPolicy(Policy):
"""
A uniformly random policy.
# Arguments
action_space: a callable that returns a list of available
actions from a given state.
"""
def __init__(self, action_space):
self.action_space = action_s... |
'''
Created on Jun 4, 2016
@author: Debanjan.Mahata
'''
import requests
import json
import sys
import config
import yagmail
import csv
from time import sleep
from config import DEVICE_PLANT_MAPPING
from config import PLANT_DEVICE_MAPPING
from config import DEVICE_STALE_DATA_MINS
from config import CAM_STALE_DATA_MINS... |
#!/usr/bin/python3
import camoco.RefGenDist as RefGenDist
from collections import defaultdict
import matplotlib.pylab as plt
from .Camoco import Camoco
from .Locus import Gene, Locus
from .Chrom import Chrom
from .Genome import Genome
from .Tools import memoize, rawFile
from .Exceptions import CamocoZeroWindowError
... |
import tkinter as tk
import os
import util
from frames.add_quantity_frame import AddQuantityFrame
from frames.add_unit_frame import AddUnitFrame
from frames.converter_frame import ConverterFrame
from frames.main_frame import MainFrame
from util import get_all_quantities
from constants.files import *
class Applicatio... |
import pytest
import logging
from esprima import parseScript
from photoshop import PhotoshopConnection
from photoshop.protocol import Pixmap
from .mock import (
script_output_server, subscribe_server, error_status_server, jpeg_server,
pixmap_server, filestream_server, PASSWORD
)
class CallbackHandler(object):... |
from hallo.events import EventMessage, EventMode
from hallo.server import Server
from hallo.test.server_mock import ServerMock
def test_devoice_not_irc(hallo_getter):
test_hallo = hallo_getter({"channel_control"})
serv1 = ServerMock(test_hallo)
serv1.name = "test_serv1"
serv1.type = "NOT_IRC"
test... |
import boto3
from jinja2 import Environment, FileSystemLoader
import re
from .APIException import Exception_400
import os
def generate_conf(request):
data = extract_data(request)
template_string = data['data']
key_prefix = data['parameters']['key_prefix']
aws_region = os.environ['AWS_REGION']
tem... |
import pytest
import pandas
from nereid.src.treatment_facility.constructors import build_treatment_facility_nodes
from nereid.core.io import parse_configuration_logic
@pytest.mark.parametrize(
"ctxt_key, has_met_data",
[("default", True), ("default_api_no_tf_joins_valid", False)],
)
@pytest.mark.parametrize(... |
'''
Function:
新年贺卡生成器
Author:
Car
微信公众号:
Car的皮皮
'''
import os
import io
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtGui
from PIL import Image, ImageDraw, ImageFont
'''新年贺卡生成器'''
class NewYearCardGenerator(QtWidgets.QWidget):
tool_name = '新年贺卡生成器'
d... |
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC... |
from __future__ import absolute_import
from __future__ import print_function
import os, tqdm
from ephys.spiketrains import get_spiketrain
from ephys import core
from ephys import events
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from six.moves import zip
def do_raster(raster_data, ... |
#==============================================================================
# SM 2/2016
# ReaDATA CSV frame data generated from the excel files using Pandas
# and generates the association matrix for Attacker and Comer data.
# Input : sheet_ID <frame ID>
# Output : R_DIR > ADJ_A/C_***.csv
#========================... |
'''@package encoders
contains the encoders for encoder-decoder classifiers'''
from . import ed_encoder, ed_encoder_factory
|
#
# Copyright (c) 2017, Stephanie Wehner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions an... |
from .rrsm import try_mkdir, reasonable_random_structure_maker
from .super_cell import compute_super_cell_needed_for_rcut, super_cell, super_cell_if_needed
from .polymorphD3 import PolymorphD3
from .job_control import vasp_job_maker, outcar_to_traj
from .kgrid import get_kpts_from_kpd, kgrid_from_cell_volume, safe_kgr... |
# Generated by Django 3.2.12 on 2022-05-13 02:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wormil', '0002_alter_specimen_description'),
]
operations = [
migrations.AddField(
model_name='fossil',
name='organ... |
#coding:utf-8
#
# id: bugs.core_2893
# title: Expression in a subquery may be treated as invariant and produce incorrect results
# decription:
# Confirmed wrong resultset on 2.1.2.18118.
# Added sample from core-3031.
#
# tracker_id: CORE-2893
# mi... |
#!/usr/bin/env python
import os
import re
from setuptools import find_packages, setup
def get_version(*file_paths):
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
... |
#!/usr/bin/python3
# buttcockles 1.0 - small scraper for findsubdomains.com
import requests
import argparse
import socket
from lxml import html
def geddem(args):
eh = "https://findsubdomains.com/subdomains-of/"
dom = args.domain
print("\033[1m[!] Looking up %s" % dom)
p = requests.get(eh+dom.stri... |
from gwcconfig.GeoWebCacheServer import GeoWebCacheServer
try:
from config import *
except ImportError:
print("Failed to load settings")
def main():
server = GeoWebCacheServer(GWC_REST_API_URL,GWC_REST_API_USERNAME,GWC_REST_API_PASSWORD)
test_layer = server.get_layer(LAYER_NAME)
test_layer.fetch()... |
import contextlib
import threading
from unittest.mock import MagicMock, Mock, patch
import paho.mqtt.client as paho
import pytest
from tavern._plugins.mqtt.client import MQTTClient, _handle_tls_args, _Subscription
from tavern._plugins.mqtt.request import MQTTRequest
from tavern.util import exceptions
def test_host_... |
# -*- coding: utf-8-*-
import os
import logging
import pipes
import tempfile
import subprocess
import psutil
import signal
from abc import ABCMeta, abstractmethod
import yaml
import lib.diagnose
import lib.appPath
class AbstractVoiceEngine(object):
"""
Generic parent class for voice engine class
"""
... |
"""
Support for RainMachine devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/rainmachine/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_BINARY_SENSORS, CO... |
from math import ceil, sqrt
#returns 1 as composite
def isPrime(x):
if x > 6 and (x % 6 == 1 or x % 6 == 5):
limit = ceil(sqrt(x))
for i in range(2, (limit+1)):
if x % i == 0:
return False
return True
return (x == 2 or x == 3 or x == 5) |
"""
"""
# Full imports
import math
# Partial imports
from pytups import TupList, SuperDict
import numbers
def read_excel(path: str, param_tables_names: list = None) -> dict:
"""
Read an entire excel file.
:param path: path of the excel file
:param param_tables_names: names of the parameter tables
... |
"""
Provides class and functions to interact with FOBOS aperture deployment.
.. include:: ../include/links.rst
"""
import time
from itertools import chain, combinations
from IPython import embed
import numpy
from scipy.optimize import linear_sum_assignment
from matplotlib import pyplot, patches
from sklearn.neigh... |
#!/usr/bin/env python3
"""Graficzny interfejs użytkownika"""
import pygame
import constants as c
# Ignore false positive pygame errors
# pylint: disable=no-member
class Gui:
"""Obsługa graficznego interfejsu użytkownika."""
def __init__(self, screen):
self.screen = screen
def draw_screen(self,... |
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
for food in my_foods:
print(food)
for food in friend_foods:
print(food)
friend_foods = my_foods
pri... |
import datetime
import os
from enum import Enum
from io import BytesIO, RawIOBase
from typing import IO, Any, Dict, List, Optional, Union, cast
import arrow
import requests
from typing_extensions import Protocol
try:
from mcap.mcap0.records import Schema as McapSchema
from mcap.mcap0.stream_reader import Stre... |
from typing import (Callable,
Type)
from cfractions import Fraction
from shewchuk import Expansion
from ground.core.hints import (Multipoint,
Point)
def centroid(multipoint: Multipoint,
point_cls: Type[Point],
inverse: Callable[[int], Frac... |
from django.http import HttpResponse
#from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.forms.models import model_to_dict
from django.db.models import Count, Q
from models import CollectItem, CollectTag
import json
import time
# TBD: rewrite to django-rest-frame... |
#!/usr/bin/env python3
import os
import subprocess
import json
# Text styling class
class Text:
HEADER = '\033[1;34m'
SUCCESS = '\033[1;32m'
FAIL = '\033[1;21m'
ENDC = '\033[0m'
# Shell commands class
class Commands:
INSTALL_PY_DEPS = 'sudo apt-get install -y python3 python3-distutils python3-pip ... |
from spinta import commands
from spinta.components import Context
from spinta.datasets.backends.sqldump.components import SqlDump
@commands.wait.register(Context, SqlDump)
def wait(context: Context, backend: SqlDump, *, fail: bool = False) -> bool:
# SqlDump is not a real backend.
return True
|
import pytest
from hat.event.server import common
import hat.event.server.backends.sqlite
pytestmark = pytest.mark.asyncio
@pytest.fixture
def db_path(tmp_path):
return tmp_path / 'sqlite.db'
async def test_create(db_path):
conf = {'module': 'hat.event.server.backends.sqlite',
'db_path': str(... |
import codecs
import os
import tempfile
import pytest
from pji.service.dispatch import Dispatch, DispatchTemplate
from .base import DISPATCH_TEMPLATE, TASK_TEMPLATE_SUCCESS_1, TASK_TEMPLATE_SUCCESS_2, TASK_TEMPLATE_FAILURE_1
from ..section.section.base import COMPLEX_TEXT
# noinspection DuplicatedCode
@pytest.mark.... |
#!/usr/bin/env python
# ===============================================================================
# dMRIharmonization (2018) pipeline is written by-
#
# TASHRIF BILLAH
# Brigham and Women's Hospital/Harvard Medical School
# [email protected], [email protected]
#
# ====================================... |
import math
import random
from contextlib import suppress
from decimal import Decimal
from functools import wraps
from django.apps import apps
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.core.cache import cache
from d... |
"""
Author: Yao Feng
Copyright (c) 2020, Yao Feng
All rights reserved.
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from skimage.io import imread
from pytorch3d.structures import Meshes
from pytorch3d.io import load_obj
from pytorch3d.renderer.mesh import rasteri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = 'AJay'
__mtime__ = '2019/5/9 0009'
"""
#配置信息
'''
爬取手机端的接口信息,
"http://v2.sohu.com/integration-api/mix/region/84?size=100",
爬取方式,
获取每天的最新的新闻,一般200篇就
一般情况可以获取100多个页面新闻的链接
对比对应的set集合有没有连接
没有连接就存入数据库,存入待爬取的数据库
然后集合中加入此链接
爬取模块,定期从数据... |
import unittest
from unittest import mock
from pathlib import Path
import thonnycontrib.thonny_black_format as plugin
tests_folder = Path(__file__).parent
class TestPlugin(unittest.TestCase):
def test_plugin(self):
"""
Test that `show_info` is displaying the correct messages and
`load_p... |
from __future__ import absolute_import
from builtins import range
import logging
import keras.backend as ker
from numpy import pi as pi_const
from keras.layers import Lambda, Multiply, Add
from keras.models import Input
from keras.models import Model
from .sampling import sample_standard_normal_noise
from .architect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.