text stringlengths 38 1.54M |
|---|
import time
from serial import SerialException
from opentrons.util.log import get_logger
log = get_logger(__name__)
class Connection(object):
def __init__(self, sp, port='', baudrate=115200, timeout=0.02):
sp.port = port
sp.baudrate = baudrate
sp.timeout = timeout
self.serial_... |
#! /usr/bin/env python
"""
Author: LiangLiang ZHENG
Date:
File Description
"""
from __future__ import print_function
import sys
import argparse
class Solution(object):
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
'''
只需要找到临接的数比方 3,2,2,2,2, 或1,... |
# Generated by Django 2.1.1 on 2018-09-18 08:28
from django.db import migrations
def set_regions_departments(apps, schema_editor):
Perimeter = apps.get_model("geofr", "Perimeter")
perimeters = Perimeter.objects.all()
for perimeter in perimeters:
if perimeter.region:
perimeter.regions ... |
from flask import Flask, make_response, request
app = Flask("dummy")
def configure_app(app):
'''
add database link to the config of app
'''
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
|
import tensorflow as tf
from typing import Tuple
from tensorflow.keras import initializers
from random import randint
# import tensorflow_addons as tfa
def build_feature_extractor(
input_seq_len: int,
batch_size: int,
) -> Tuple[tf.ker... |
import bisect
import hashlib
class ConsistentHashRing(object):
def __init__(self, replicas=100):
self.replicas = replicas
self._keys = []
self._nodes = {}
def _hash(self, key):
"""Given a string key, return a hash value."""
key = str(key)
return int(hashlib.md... |
from scripts.parsing_singlethread import *
# globals
record_limit = 100
stopwatch = Stopwatch()
stopwatch.start()
# truncate database
create_database()
create_domain_table()
# do insertion
insert_all_normal(limit=record_limit)
# stop measuring
stopwatch.stop()
print("Time of execution: ", stopwatch.results())
|
from django.contrib import admin
from .models import TutorProfile, TutorReviews, StudentProfile
# Register your models here.
class TutorProfileAdmin(admin.ModelAdmin):
class Meta:
model = TutorProfile
class TutorReviewsAdmin(admin.ModelAdmin):
class Meta:
model = TutorReviews
class StudentProfileAdmin(admin.Mod... |
import unittest
from piepline.data_producer import BasicDataset
class TestingBasicDataset(BasicDataset):
def _interpret_item(self, item) -> any:
return self._items[item]
class BasicDatasetTest(unittest.TestCase):
def test_init(self):
try:
TestingBasicDataset(list(range(12)))
... |
class Car:
# Properties
color = ""
brand = ""
number_of_wheels = 4
number_of_seates = 4
maxspeed = 0
# constructor
def __init__(self, color, brand, number_of_wheels, number_of_seates, maxspeed):
self.color = color
self.brand = brand
self.number_of_seates = number... |
#f1 = open('d:\te.txt',encoding='utf-8',mode='r') #OSError: [Errno 22] Invalid argument: 'd:\te.txt'
f1 = open('d:/te.txt',encoding='utf-8',mode='r')
content = f1.read()
print(content)
f1.close()
'''
open 内置函数,open底层调用的是操作系统的接口。
f1,变量,f1,fh,file_handler,f_h,文件句柄。 对文件进行的任何操作,都得通过文件句柄. 的方式。
encoding:可以不写,不写参数,默认编... |
import sys
import os
import json
import time
import hmac
import hashlib
import base64
import requests
import numpy as np
import urllib.request
import urllib, time, datetime
import os.path
import time
import hmac
import hashlib
from decimal import *
try:
from urllib import urlencode
from urlparse import urljoin... |
from sqlMethods import *
import pandas as pd
from twitter_queries import *
def get_all_entities(con):
sql = """
SELECT
tweet_id, entity_type, start_index, stop_index
FROM
tweet_entities
WHERE
entity_type = 'USER_MENTION'
... |
# -*- coding: utf-8 -*-
'''
Created on Dec 13, 2016
@author: ToOro
'''
from technique.web_crawling.util.common import link_crawler
from technique.web_crawling.mongo_cache import MongoCache
from alexa_cb import AlexaCallback
def main():
scrape_callback = AlexaCallback()
cache = MongoCache()
# cache.clear()... |
while True:
tal1 = int(input("Mata in tal1"))
tal2 = int(input("Mata in tal2"))
print(f"summan av {tal1} och {tal2} är {tal1+tal2}")
fortsatt = input("Vill du fortsätta? J/N")
if fortsatt == "N":
break
#TODO Vi gör en till loop - ogiltig inmatning
|
# from sqlalchemy import Column, String, create_engine, CHAR, Integer
# from sqlalchemy.orm import sessionmaker
# from sqlalchemy.ext.declarative import declarative_base
#
# Base = declarative_base()
#
#
# class User(Base):
# __tablename__ = "user"
# id = Column(Integer, primary_key=True)
# nameuser = Colum... |
import psycopg2
import os
# DEFAULTS
DEFAULT_PORT = 2345
DEFAULT_PASSWORD = '123'
DEFAULT_HOST = '127.0.0.1'
# variables
password = os.getenv('POSTGRES_PASSWORD')
if (password is None):
password = DEFAULT_PASSWORD
port = DEFAULT_PORT
host = DEFAULT_HOST
def main(password, host, port):
# create connection
... |
import subprocess
import os
import sys
import re
import json
import pdb
import datetime
import shlex
from collections import defaultdict, Counter
from collections.abc import Mapping
from itertools import chain
__all__ = ["run", "pipe", "Pipe", "save_stats", "string2cigar", "cigar2string", "guess_sample_name", "nullc... |
# -*- coding: utf-8 -*-
import numpy as np
import pdb
def read_seq(seq_file, mod="extend"):
seq_list = []
seq = ""
with open(seq_file, "r") as fp:
for line in fp:
seq = line[:-1]
seq_array = get_seq_concolutional_array(seq)
seq_list.append(seq_array)... |
# -*- coding: utf-8 -*-
import gzip
import hashlib
import hmac
from StringIO import StringIO
import random
import xlrd
def gzdecode(data):
compressedstream = StringIO(data)
gziper = gzip.GzipFile(fileobj=compressedstream)
data2 = gziper.read()
return data2
def random_str(len):
str = ""
for i... |
import tensorflow as tf
import numpy as np
# 加入忽略
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
a = np.arange(0, 5) # 生成步长为1的等差一维数组
b = tf.convert_to_tensor(a, dtype=tf.int64) # 将a转化为张量
c = tf.fill([2, 2], 3)
d = tf.constant([1, 5], dtype=tf.int64) # 创建张量
d_change = tf.cast(d, dtype=tf.float64) # 强制转换数据类型
pri... |
import sys
import re
import string
def do_generate(input_file, output):
content = str(input_file.read())
# replace <doc> and next line with next line
#pattern = re.compile(r'<doc.*>\n.*\n')
#content = str(pattern.findall(content))
documents = re.split(r'</doc>\n', content)
content = ''
for... |
num1 = 12
key = True
if num1 == 12:
if key:
print('Num1 is equal to Twelve and they have the key!')
else: print('Num1 is equal to Twelve and they do no have the key!')
elif num1 < 12:
print('Num1 is less than Twelve!')
else:
print('Num1 is not eqaul to Twelve!')
|
from django.core.exceptions import ValidationError
import os
def validate_file_size(value):
filesize= value.size
if filesize > 2097152:
raise ValidationError("The maximum file size that can be uploaded is 2MB")
else:
return value
def validate_file_extension(value):
ext = os.path.s... |
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Table, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
import random
import string
import httplib2
Base = declarative_base()
secret_key = ''.joi... |
# Source : https://github.com/mission-peace/interview/blob/master/python/dynamic/longest_increasing_subsequence.py
# Find a subsequence in given array in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible.
# Time Complexity: O(N^2), Space Compl... |
import numpy as np
import tensorflow as tf
import cv2
import os
from style_transfer.model import build_model
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def preprocess_img(img, target_shape=None):
# image = cv2.imread(str(path))
if target_shape is not None:
img = cv2.resize(img, target_shape)
img =... |
# Generated by Django 3.1.6 on 2021-08-09 05:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BMIList', '0007_checkstatus_eprogram_indexstatus_record'),
]
operations = [
migrations.CreateModel(
... |
import inspect
import numbers
import math
import numpy
import FreeCAD
import Part
import Mesh
import FreeCADGui as Gui
from forbiddenfruit import curse
def print(x):
FreeCAD.Console.PrintMessage (str(x)+"\n")
def document():
return FreeCAD.activeDocument()
def vector(*arguments, angle = None, length = 1):
if... |
import battlecode as bc
import random
import sys
import traceback
import Units.sense_util as sense_util
import Units.movement as movement
import Units.explore as explore
import Units.Ranger as Ranger
import Units.variables as variables
import Units.clusters as clusters
import time
battle_radius = 10
def timestep(unit... |
import ssl
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class Top10Notices:
def nsu_top10_notice(self):
... |
# Generated by Django 2.2.15 on 2020-08-15 06:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0009_auto_20200810_0726'),
]
operations = [
migrations.AddField(
model_name='details',
name='github',
... |
from django.db import models
# Create your models here.
class WeatherReports(models.Model):
class Meta:
db_table = 'weather_reports'
verbose_name = 'Погодные сводки'
DEFAULT_VALUE = {'pressure': 0, 'temperature': 0, 'humidity': 0, 'wind_speed': 0}
city = models.ForeignKey('api.Cities', v... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import signal
from seleniumwebtests import swt
def signal_handler(signal, frame):
print "\nKilling..."
swt.end()
sys.exit(0)
def main(options={}):
signal.signal(signal.SIGINT, signal_handler)
swt.set_options(options)
... |
#!/usr/bin/python3
"""File I/O"""
import json
def from_json_string(my_str):
"""File I/O"""
return json.loads(my_str)
|
import tflearn.datasets.oxflower17 as oxflower17
import numpy as np
class BatchDatset:
def __init__(self):
print("Initializing Batch Dataset Reader...")
self._read_images()
self.batch_offset = 0
self.epochs_completed = 0
def _read_images(self):
self.images, self.annota... |
# [DP-Sequence-Action-Groups]
# https://leetcode.com/problems/largest-sum-of-averages/
# 813. Largest Sum of Averages
# https://www.youtube.com/watch?v=IPdShoUE9z8
# Related: 312. Burst Balloons
# We partition a row of numbers A into at most K adjacent (non-empty)
# groups, then our score is the sum of the average of... |
from rest_framework import permissions
from users.models import Student
class IsTeacher(permissions.BasePermission):
def has_permission(self, request, view):
if request.user:
if request.user.role == "TE":
return True
else:
return False
else:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 16:29:40 2020
@author: tnye
"""
# Imports
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Reaad in dataframes
rt_df = pd.read_... |
# coding=utf-8
from pyspark import SparkContext, SparkConf
import json
import nltk
def fit(line):
#筛选glove语料库中的名词,专有名词和动词原形
vals = line.rstrip().split(' ')
word = vals[0]
f_word = nltk.pos_tag([word])[0]
if f_word[1] in ['NN','NNP','VB']:
return [(word,map(float, vals[1:]))]
else:
return []
# def fit2(line)... |
from django.test import TestCase, RequestFactory, Client
from django.contrib.auth.models import AnonymousUser, User
import public_gate.views as views
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
cl... |
import gym
import numpy as np
from gym import wrappers
env = gym.make('CartPole-v1')
RANDOM_ACTION = 1
WEIGHT_BASED_ACTION = 2
def get_action(strategy, observation, weights):
if strategy == RANDOM_ACTION:
return env.action_space.sample()
elif strategy == WEIGHT_BASED_ACTION:
return 1 if np.... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
# This module is part of the package GTW.OMP.SRM.
#
# This module is licensed under the... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.stats import chisquare
from sympy import *
import os
#This is just needed for later, you can skip the latex part
message = r""" %% AMS-LaTeX Created with the Wolfram Language : www.wolfram.com
\docu... |
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy.schema import (
CheckConstraint,
Column,
ForeignKey,
Table,
UniqueConstraint,
)
from sqlalchemy.types import JSON, Integer, String
from iheroes_api.infra.database.models.user import User
from iheroes_api.infra.database.sqlalchemy impor... |
class PriorityQueueADT:
def add(self, key, value):
raise NotImplementedError
def min(self):
raise NotImplementedError
def remove_min(self):
raise NotImplementedError
def is_empty(self):
return len(self) == 0
def __len__(self):
raise NotImplementedError |
import string
import random
import numpy as np
for r in range(3):
for size in [100, 1000, 10000, 100000, 1000000, 10000000]:
if r == 0:
stream_list = [''.join(random.choice(string.ascii_lowercase)) for _ in range(size)]
else:
d = np.random.normal(13, 4.5, size).astype(np.in... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import chainer
from chainer import training
from chainer.training import extensions
import dataset
from models.vgg16 import VGG16
from models.generators import FCN32s, FCN16s, FCN8s
from models.discriminators import (
LargeFOV... |
import time
from multiprocessing import Process
def ask_user():
start = time.time()
ask_usr = input("Enter your name")
print(f"Hello, {ask_usr}")
print(f"ask_usr {time.time() - start}")
def do_math():
start = time.time()
print("Start calculation...")
[i**2 for i in range(2000000)]
prin... |
# coding: cp949
# print("기본 if문법") # if, for, while 없이 단독으로 indentation이 불가능
money = True
#if money:
#print("택시를 타고 가라") # if 이하에는 반드시 1개 이상의 statement가 있어야 한다.
#if money:
# print("택시를 타고 가라") # indentation은 공백, 탭 모두 허용한다.
#if money:
# print("현금이 있는것으로 확인 되었음") #동일한 indentation으로 구성된 statement는
# print("택시타고,,... |
import model
import view
import pygame
"""
This is controler.
"""
game_engine = model.GameEngine()
graphical_view = view.GraphicalView(game_engine)
while game_engine.running:
#pass event to model and view
for event in pygame.event.get():
graphical_view.notify(event)
game_engine.notify(e... |
"""Contains the base class for flippers."""
import copy
from mpf.core.device_monitor import DeviceMonitor
from mpf.devices.driver import ReconfiguredDriver
from mpf.core.system_wide_device import SystemWideDevice
from mpf.devices.switch import ReconfiguredSwitch
@DeviceMonitor(_enabled="enabled")
class Flipper(Sys... |
"""
Functions for generating distance restraints from
evolutionary couplings and secondary structure predictions
Authors:
Thomas A. Hopf
Anna G. Green (docking restraints)
"""
from pkg_resources import resource_filename
from evcouplings.utils.config import read_config_file
from evcouplings.utils.constants import ... |
import nacl.encoding
import nacl.signing
bob_priv_key = nacl.signing.SigningKey.generate()
bob_pub_key = bob_priv_key.verify_key
bob_pub_key_hex = bob_pub_key.encode(encoder=nacl.encoding.HexEncoder)
print(f"Bob Public Key: {bob_pub_key_hex}")
signed = bob_priv_key.sign(b"Some important message")
print(signed) |
# For Linked List problems that need nodes to be rearranged
# use this implementaion of linked list that has a head as well as tail pointer.
# append method has different uses, so practice it.
# Linked List Implementation
# for problems where nodes have to be rearranged
class Node:
def __init__(self,data):
... |
import copy
class Solution:
def letterCombinations(self, digits: str):
"""
由键盘字符得到对应的字符列表比较容易,关键是怎么进行组合,如果输入字符太多,循环次数太多
"""
# 用字典就好了,按ASCII码计算,行不通,应为有'7' '9'这两个例外
# lettersList = []
# for digit in digits:
# if int(digit) <= 6:
# letters = [... |
from rdflib import Namespace, Graph, Literal, RDF, URIRef
from rdfalchemy.rdfSubject import rdfSubject
from rdfalchemy import rdfSingle, rdfMultiple, rdfList
from brick.brickschema.org.schema._1_0_2.Brick.Exhaust_Fan_Enable_Command import Exhaust_Fan_Enable_Command
class AHU_Exhaust_Fan_Enable_Command(Exhaust_Fan_En... |
# -*- encoding: UTF-8
import unittest
import z3
import libirpy
import libirpy.unittest
import libirpy.solver as solver
import libirpy.util as util
import nickel.unwindings as ni
import datatypes as dt
import spec
import spec.label as l
import state
import ctx
from prototypes import proto
TestCase = libirpy.unittest... |
import sys
import datetime
from multiprocessing import Pool
from icg import card
def multiSim(idx):
pool = card.generate_pool()
stats = {}
stats['triggers'] = {}
for c in pool:
for effect in c.effects:
stats['triggers'][effect.triggerName] = stats['triggers'].get(effect.triggerName... |
from django.db import models
# Create your models here.
class Project(models.Model):
client = models.CharField(max_length=200, null=True)
logo = models.FileField(blank=True)
location = models.CharField(max_length=200, null=True)
vessel = models.CharField(max_length=200, null=True)
def __str__(sel... |
from django.urls import path, include
from rest_framework.parsers import JSONParser
from rest_framework.renderers import JSONRenderer
from rest_framework_xml.parsers import XMLParser
from rest_framework_xml.renderers import XMLRenderer
from rest_framework import routers, serializers, viewsets
from quiz.models import ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Niccolò Bonacchi
# @Date: Wednesday, January 16th 2019, 2:03:59 pm
import argparse
import logging
import shutil
from pathlib import Path
from shutil import ignore_patterns as ig
import ibllib.io.extractors.base
import ibllib.io.flags as flags
import ibllib.io.raw... |
import os
HOST = 'localhost'
PORT = 11211
IPSTACK_ACCESS_KEY = os.environ.get('IPSTACK_ACCESS_KEY', '<your access key>')
|
class Stack:
def __init__(self):
self.items=[]
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def check_palindrome(input):
stack = Stack()
is_palindrome=False
for char in input:
stack.push(char)
for char in input:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 17:21:23 2020
@author: idchiang
"""
from .hrchy_plot import *
|
# -*- coding: utf-8 -*-
"""
IMPORTANT!:
Before writing an email asking questions such as
'What does this input has to be like?' or
'What return value do you expect?' PLEASE read our
exercise sheet and the information in this template
carefully.
If something is still unclear, PLEASE talk to your
colleagues bef... |
#Янова Даниэлла ИУ7-23
#Защита файлов
fl=open('Computer.txt','r') #Открываю и сохраняю записи файла
lines= fl.read().split()
fl.close()
fin=open('find.txt','w') #Создаю пустой файл для результатов
fin.close()
fin=open('find.txt','a+') #Открываю созданный файл для вноса результатов
s=input('Компьютеры какой стоимости в... |
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from collections import OrderedDict
#==============================================================================
class ErrorPlot:
"""
Creates error plot for specified data
Note: s... |
import torch
from torchvision import datasets, transforms
import torchvision.models as models
from torch import nn
from collections import OrderedDict
import time
from torch import optim
from workspace_utils import active_session
import error_types as error
def _load_data(train_dir, test_dir='./flowers/test/'):
... |
#!/usr/bin/env python3
#JSON file containing all print statements that the program outputs to the screen, this includes
#user input as well potential error messages.
#When passed into a class pulling the error messages, this is passed into the ld_json class which converts
#this json into a dictionary. The dictionary i... |
from flask import Flask
from hatchet import Environment
def test_app_is_flask(app):
assert isinstance(app, Flask)
def test_app_is_testing_config(app):
assert app.config.get("ENV") == Environment.TEST
def test_app_has_sqlalchemy_connection_string(app):
assert app.config.get("SQLALCHEMY_DATABASE_URI") =... |
from django.http import HttpResponse, HttpResponseRedirect
# Create your views here.
def home(request):
print(request) # It display <WSGIRequest 'GET> means it display the requested method i.e POST, GET, DELETE etc
print(dir(request)) # It disply all methods available in request
print(request.get_full_pat... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ht={ }
for string in strs:
ss=''.join(sorted(string))
if ss in ht:
ht[ss].append(string)
else:
ht[ss]=[string]
return ht.val... |
from django.conf import settings
import os
FILE_TYPE_CHOICES = (
('im', 'Image'),
('vi', 'Video'),
('au', 'Audio'),
)
STATIC_FILE_PATH = os.path.join('mail') |
# -*- coding: utf-8 -*-
import numpy as np
class MPCEnv(object):
def __init__(self,
dynamics,
renderer,
reward_system,
dt,
use_visual_state=False):
"""
Arguments:
dynamics:
Agent dynamics
... |
# This script extract a python list from a data frame column in a CSV file
# In other words in helps dealing from Python to R
import pandas as pd
df = pd.read_csv('/Users/Ofix/Documents/Fac/internat/Recherche/projets/synchro/synchroData/Git/INCANT/Data/CSV/studyInfoData/indexList.slideddata.csv')
saved_column = df.x #... |
from flask import Flask
from flask_apscheduler import APScheduler
import os
import datetime
from .blueprint.home.routes import home_bp, joke
from .blueprint.facebook.routes import facebook_bp, downloadFaces
from .blueprint.admin.routes import admin_bp
def create_app():
app = Flask(__name__)
app.config['SQLA... |
import subprocess
def Run(command_str, sync_output = False):
print "Run: %s"%command_str
if sync_output:
subprocess.call(command_str)
print "----------"
else:
output = subprocess.check_output(command_str)
print "Output: %s"%output
print "----------"
... |
"""IoT application framework interface
This module provides an interface to the IoT application framework. The
framework provides a simple inter application communication framework and
event system.
The main feature of this module is the IotApp class, which provides bindings
to the IoT application framework C-library... |
from app import app
app.config['UPLOAD_FOLDER'] = '/tmp/codehost/uploads/binaries'
app.run(host='0.0.0.0',debug=True) |
# Import necessary libraries
import pandas as pd
def prep_data(df):
'''
Function to dummy variable all categorical columns and reorder columns into useful order
Input: Cleaned dataframe
Output: Dataframe with dummy variables in correct order
'''
# Dummy variables for categorical ... |
pub = "CD5F8A24C7605008897A3C922C0E812E769DE0A46442C350CB78C7868539F3D38AAC80B3E6A506605910E8599806B4D1D148F2F6B81DA04796A8A5AEE18F29E83E16775A2A0A00870541F6574ED1438636AE0A0C116E07104F48F72094863A3869E1C8FC220627278962FB22873E3156F18E55DEC94E970064EC7F4E0E88454012E2FD5DFE5F8D19BF170F9CCB3F46E0FD1019BCB02D9083A0703C61... |
import turtle
tartaruga=turtle.Turtle()
tartaruga.hideturtle()
campo=turtle.Screen()
tartaruga.pensize(3)
lados=int(input('Introduza o número de lados do polígono: '))
comprimento=int(input('Introduza o comprimento dos lados do polígono: '))
cor_borda=input('Introduza a cor das bordas do polígono: ')
cor_interior=input... |
import collections
import os
import sys
import unittest
from importlib import import_module
from airflow.models import DagBag, DAG
class TestDagIntegrity(unittest.TestCase):
LOAD_SECOND_THRESHOLD = 2
DAG_FOLDER = "src/dags"
def setUp(self):
self.dagbag = DagBag(dag_folder=TestDagIntegrity.DAG_FO... |
import torch
import numpy as np
import os
import numpy as np
import matplotlib.pyplot as plt
try:
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import AllChem
from rdkit import RDLogger
lg = RDLogger.logger()
lg.setLevel(RDLogger.CRITICAL)
ZINC250_BOND_DECODER = {1: Chem.rdchem.BondType.SING... |
from the_import import ProvincialClass as pc, imported_func
class Abra():
def __init__(self):
self.cadabra()
def cadabra(self):
print("cadabra")
def b():
Abra()
b()
pc()
HiddenClass() # this is probably too defensive
imported_func()
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 12:30:09 2018
@author: Laura
"""
from measures.algorithms.fair_ranker.runRankFAIR import initPAndAlpha, calculateP
from measures.algorithms.fair_ranker.test import FairnessInRankingsTester
def fairnessTestAtK(dataSetName, ranking, protected, unProtected, k):
... |
import os
import json
import pandas as pd
from dotenv import load_dotenv
from pathlib import Path
from model import SiameseBiLSTM
from preprocess import build_vocab_and_transform, build_embeddings, build_train_data, build_test_data, build_padded_data
from evaluation import precision_m, recall_m, f1_m, confusion_matrix... |
import numpy as np
class StandardScaler():
def __init__(self):
self.mean_ = None
self.scale_ = None
def fit(self, X):
''' 根据训练数据集获得数据的均值和方差
'''
assert X.ndim == 2, "The dimension of X mu... |
from django.shortcuts import render
from .models import StudentData
def studentreg_view(request):
if request.method=="POST":
roll=request.POST.get('roll','')
sname=request.POST.get('sname','')
mobile=request.POST.get('mobile','')
fee=request.POST.get('fee','')
email=request.P... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django_declension.models import Word, DeclensionFail
admin.site.register(Word)
admin.site.register(DeclensionFail)
|
from rest_framework import generics, permissions
from .models import Jobs
from .serializers import JobsSerializer
# code was moved from API.py file as views will only be used for API releated actions so no reason to not just have everything in views
# creates an api list of all user Jobs as well as allowing for creat... |
import os
import json
from os.path import dirname, realpath
from pathlib import Path
import logging
LOGGER = logging.getLogger("Configs")
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls)._... |
import tensorflow as tf
groups = tf.constant([[0,1,2,3],[4,5,6,7]])
arr = tf.constant([[10,0],[20,0],[30,0],[40,0],[50,0],[60,0],[70,0],[80,0]])
output = tf.gather(arr, groups)
print(output) |
'''
Pytorch implementation of SeqSleepNet taking as input single channel signal
x: [bs, seq_len, Fs*30]
y: [bs, seq_len, num_classes]
Original SeqSleepNet implmentation includes following steps:
input x [bs, seq_len, 30*100]
1: send x to time-frequency representation obtaining x: [bs, seq_len,... |
#!/usr/bin/python3
"""
Object to serialization.
"""
def class_to_json(obj):
"""functionthat describes a dictionary for JSON serialization
of an object.
Arg:
obj: object to serialization.
Return the dictionary description with simple data structure.
"""
return obj.__dict__
|
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __repr__(self):
return "[{},{}]".format(self.start, self.end)
class Solution(object):
def open_ratio(self, open_times, query_time):
"""
:type intervals: List... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from itertools import product
from unittest import mock
import torch
from botorch.acquisition.multi_... |
#!/usr/bin/env python
import sys
import os
def indent(n):
ind = ''
for i in range(0, n):
ind += ' '
return ind
def dBraces(text):
return text.replace('{', '{{').replace('}', '}}')
def printMulti(text, prefix, suffix):
first = True
for line in text.split('\n'):
if first:
... |
# Given a list of numbers, you should find the sum of these numbers.
# Your solution should not contain any of the banned words, even as a part of another word.
#
# The list of banned words are as follows:
#
# sum
# import
# for
# while
# reduce
# Input:
# A list of numbers.
#
# Output:
# The sum of numbers.
#
# Examp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.