content stringlengths 5 1.05M |
|---|
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
print("The temperature in Celsius: ", (fahrenheit-32)*(5/9))
|
""" Tool for extending the label information with the chess game state, i.e. the camera piece
color and square content.
"""
import argparse
import cv2 as cv
from rookowl.global_var import PIECE_DISPLAY_SHAPE
from rookowl.label import load_labels, save_label
# =≡=-=♔=-=≡=-=♕=-=≡=-=♖=-=≡=-=♗=-=≡=-=♘=-=≡=-=♙=-=≡=-=... |
import torch
import torch.nn as nn
import torch.nn.functional as F
# 한 Batch에서의 loss 값
def batch_loss(loss, images):
return loss.item() * images.size(0)
class FocalLoss(nn.Module):
def __init__(self, weight=None, gamma=2.0, reduction="mean"):
nn.Module.__init__(self)
self.weight = weight
... |
def spread_pixels(Nside_low, Nside_high, ID):
from math import log
Llow = int(log(Nside_low, 2))
Lhigh = int(log(Nside_high, 2))
print(Llow, Lhigh)
b = bin(ID)
DN = Lhigh-Llow
a = [bin(i)[2:].zfill(2**DN) for i in range(4**DN)]
pix_IDs = []
for i in a:
x = (b[2:].zfill(... |
#!/usr/bin/env python
"""Play a fixed frequency sound."""
from __future__ import division
import math
from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio
try:
from itertools import izip
except ImportError: # Python 3
izip = zip
xrange = range
def sine_tone(stream, frequency, duration, v... |
#!/usr/bin/env python3
"""Forward kinematic example using pinocchio
Sends zero-torque commands to the robot and prints finger tip position.
"""
import os
import numpy as np
from ament_index_python.packages import get_package_share_directory
import pinocchio
import robot_interfaces
import robot_fingers
if __name__ == ... |
if __name__ == '__main__' and __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ))
import os
import torch
from utils.model_serialization import strip_prefix_if_present
from utils import zipreader
import argparse
from tqdm import tqdm
i... |
import datetime
from termcolor import cprint
import get_all_caches as caches
def calculate_all_prices(fiat='EUR', coin='XMR', start='04-02-2020', high_low='high', coin_amount=int(42), fiat_amount_spent=int(0)):
coin_amount = int(coin_amount) # double casting to int here prevents crashes later on
historical_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, James Cammarata <jcammarata@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# make it possible to run as standalone program
import sys
import re
import random
import string
sys.path.append('/srv/chemminetools')
sys.path.append('/srv/chemminetools/sdftools') # allow tools.py to be imported
from django.core.management import setup_environ
import chemm... |
import os
import argparse
import numpy as np
class SceneGraphNode(object):
def __init__(self):
pass
def set_attribute(self, attr, value):
if attr not in self.__dict__.keys():
raise ValueError(f"Unknown attribute: {attr}")
self.__dict__[attr] = value
def get_attri... |
c = {'z': '\033[m'}
l = ['w', 'r', 'g', 'y', 'b', 'm', 'c', 'k']
i = j = 0
for lin in range(30, 38):
c[l[i]] = f'\033[{lin}m'
i += 1
i = j = 0
for lin in range(30, 38):
for col in range(40, 48):
c[l[i] + l[j]] = f'\033[{lin};{col}m'
j += 1
i += 1
j = 0
def clr(text='', value='z')... |
# Generated by Django 3.2.9 on 2022-01-15 21:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20220115_1425'),
]
operations = [
migrations.AlterField(
model_name='comments'... |
import sys
import os
import configparser
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from functools import partial
from PIL import ImageTk, Image
from tkinter import filedialog
class Gui:
"""
This class represents a GUI for reading, changing and writing purposes.
The... |
"""
Tests CoreML Imputer converter.
"""
import numpy as np
import unittest
try:
from sklearn.impute import SimpleImputer as Imputer
import sklearn.preprocessing
if not hasattr(sklearn.preprocessing, 'Imputer'):
# coremltools 3.1 does not work with scikit-learn 0.22
setattr(sklearn.preprocess... |
from django.core.exceptions import ValidationError
def following_changed(sender, action, instance, *args, **kwargs):
"""Raise an error if admin tries to assign User to the Users follow list"""
# m2mchanged.connect specified in apps.py
following = instance.following.all()
creator = instance.user
... |
from arcutils.settings import PrefixedSettings
DEFAULTS = {
'default': {
# Notes:
# - There are two LDAP hosts, ldap-bulk and ldap-login; Elliot has
# said that ldap-login "has more servers in the pool" and he
# recommends using it over ldap-bulk (RT ticket #580686); n... |
from django.contrib import admin
from ledger.accounts.models import EmailUser
from disturbance.components.proposals import models
from disturbance.components.proposals import forms
from disturbance.components.main.models import ActivityMatrix, SystemMaintenance, ApplicationType
#from disturbance.components.main.models ... |
# Copyright 2019 Belma Turkovic
# TU Delft Embedded and Networked Systems Group.
# NOTICE: THIS FILE IS BASED ON https://github.com/p4lang/behavioral-model/blob/master/mininet/p4_mininet.py, BUT WAS MODIFIED UNDER COMPLIANCE
# WITH THE APACHE 2.0 LICENCE FROM THE ORIGINAL WORK.
# Copyright 2013-present Barefoot Netw... |
from rl.agent import DiscreteAgent
from rl.environment import DiscreteEnvironment
from rl.experience_tuple import ExperienceTupleSerializer
class ExperimentConfiguration:
"""Configuration to run an Experiment."""
def __init__(self, agent: DiscreteAgent, environment: DiscreteEnvironment,
num_... |
"""
DREAprep.py - Allows for inputs to be passed to multiple components
"""
from openmdao.main.api import Component, Slot
from openmdao.lib.datatypes.api import Float
from MEflows import MEflows
class DREAprep(Component):
""" Passes input variables to output variables so they can be passed to multi... |
from multiprocessing import current_process, Value, Process
from time import sleep
from random import random
from reader_writer_lock import MultiprocessingFactory
from reader_writer_lock.MpFactory import Integer
def test(option):
test_name = ["No priority", "Read priority", "Write priority"]
prin... |
import numpy as np
class FCM:
"""Fuzzy C-means
Parameters
----------
n_clusters: int, optional (default=10)
The number of clusters to form as well as the number of
centroids to generate
max_iter: int, optional (default=150)
Hard limit on iterations within solver.
m: f... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 19-1-24 下午4:04
# @Author : Hubery
# @File : helper.py
# @Software: PyCharm
import json
import requests
from django.core.cache import cache
from HuberyBlog.settings import BASE_HEADERS
def page_cache(timeout):
def wrapper1(view_func):
def wrapp... |
import re
#!/usr/bin/env python3
def getStarSystems():
starsfound = re.compile("\Stars Visited\": (\alnum+\.\alnum+)")
result = starsfound.findall(content)
stars = []
if result:
for r in result:
stars.append(r)
print(result)
return stars
|
import os
import sys
import tempfile
import subprocess
import contextlib
import json
import time
# https://stackoverflow.com/questions/6194499/pushd-through-os-system
@contextlib.contextmanager
def pushd(new_dir):
previous_dir = os.getcwd()
os.chdir(new_dir)
try:
yield
finally:
os.chdi... |
import pandas as pd
import shutil
from shareplum import Site
from shareplum.site import Version
from shareplum import Office365
# SharePoint
user_name = '@eafit.edu.co'
password = ''
authcookie = Office365('https://eafit.sharepoint.com', username=user_name, password=password).GetCookies()
site = Site('https://eafit.s... |
# # Copyright (c) 2019, Corey Smith
# # Distributed under the MIT License.
# # See LICENCE file for full terms.
# """
# Tests for the data examples.
# """
# # import sys
# import inspect
# # import os
# from pathlib import Path
# import numpy as np
# # import paramiko
# # import pytest
# # import sqlalchemy
# # sy... |
"""
Helios Signals
Effectively callbacks that other apps can wait and be notified about
"""
import django.dispatch
# when an election is created
election_created = django.dispatch.Signal(providing_args=["election"])
# when a vote is cast
vote_cast = django.dispatch.Signal(
providing_args=["user", "voter", "elec... |
from setuptools import setup, find_packages
import sys
import os
import re
org = 'PEtab-dev'
repo = 'petab_select'
def read(fname):
"""Read a file."""
return open(fname).read()
def absolute_links(txt):
"""Replace relative petab github links by absolute links."""
raw_base = \
f"(https://ra... |
REGISTRY = {}
from .episode_runner import EpisodeRunner
REGISTRY["episode"] = EpisodeRunner
from .parallel_runner import ParallelRunner
REGISTRY["parallel"] = ParallelRunner
from .episode_cross_runner import EpisodeCrossRunner
REGISTRY["cross"] = EpisodeCrossRunner |
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import euclidean_distances
from scipy.io import loadmat
from matplotlib import pyplot as plt
from sklearn.metrics import normalized_mutual_info_score
from sklearn.metrics import adjusted_rand_score
def autoselect_dc(max_id, max_dis, min_dis, ... |
from __future__ import print_function
import math, types
import numpy as N
import matplotlib.pyplot as P
def plotres(psr,deleted=False,group=None,**kwargs):
"""Plot residuals, compute unweighted rms residual."""
res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs
if (not deleted) and N.any(psr.d... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
import pathlib
import shutil
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--supplementary_pdf", type=str)
args = parser.parse_args()
supplementary = pathlib.Path(args.supplementary_pdf) if args.supplementary_pdf else None
assert supplementary.exists() and supplementary.is_file()
root = (pat... |
import datetime
import json
from datetime import date,timedelta
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from operis.log import log
from ws4redis.redis_store import RedisMessage
from ws4redis.publisher import RedisPublisher
from selenium_tests.webdriver import PpfaWebDriver
#from... |
from flask import Flask
from flask_assets import Bundle, Environment
from flask_compress import Compress
from flask_talisman import Talisman
from flask_wtf.csrf import CSRFProtect
from govuk_frontend_wtf.main import WTFormsHelpers
from jinja2 import ChoiceLoader, PackageLoader, PrefixLoader
from config import Config
... |
def operate(operator, *args):
return eval(operator.join([str(x) for x in args]))
print(operate("+", 1, 2, 3))
print(operate("*", 3, 4))
|
# Generated by Django 2.0.8 on 2019-06-05 09:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('protein', '0007_proteingproteinpair_references'),
('structure', '0017_structure_contact_representative_score'),
('residue', '0002_auto_20180504_1417'... |
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# MIT License (https://opensource.org/licenses/MIT)
"""Utility functions."""
import fnmatch
import logging
import os
import sys
import tarfile
from distutils.version import LooseVersion
import numpy as np
import torch
import yaml
def find... |
from Attribute import Attribute
from Distribution.DistributionFactory import DistributionFactory
class AttributeFactory:
"""
Class to generate and deploy specific attributes that
will share a distribution factory. Attributes types are:
- custom
- boolean
- string
- int or int64
... |
from django.core.management.base import BaseCommand, CommandError
from charts.models import ChartConfig
class Command(BaseCommand):
help = "Delete all ChartConfig objects"
def handle(self, *args, **options):
all = ChartConfig.objects.all()
self.stdout.write("{} ChartConfig Type objects will... |
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''
Dirac Hartree-Fock
'''
import ctypes
import time
from functools import reduce
import numpy
import scipy.linalg
from pyscf import lib
from pyscf.lib import logger
from pyscf.scf import hf
from pyscf.scf import _vhf
import pyscf.scf.chkfile
def... |
import sys
import requests
import time
import datetime
# API URLS
URL_STATS_PROVIDER = 'https://api.nicehash.com/api?method=stats.provider&addr={}'
URL_BTC_PRICE = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC&tsyms={}'
WALLET = '1P5PNW6Wd53QiZLdCs9EXNHmuPTX3rD6hW' #Dummy wallet. To be overwritten
##... |
import copy
import argparse
import os
from PIL import Image
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.models as models
from LossFunction import ContentLoss, StyleLoss
plt... |
import os
from dotenv import load_dotenv
dirname = os.path.dirname(__file__)
try:
#print(os.path.join(dirname, '.env'))
load_dotenv(dotenv_path=os.path.join(dirname, '.env'))
except FileNotFoundError:
pass
|
#!/home/alvaro/.miniconda3/envs/fazip/bin/python
from fazip import fazip
import sys
import getpass
def do_extraction(zipname):
host, user, pwd = fazip.get_mysql_info()
db = fazip.connect_to_db(user, pwd, host)
fazip.unzip_files(db, zipname)
db.close()
def do_compression(zipname, files):
host, u... |
import sys, os
sys.path.append(os.pardir)
from lark import Lark, Token
from parsing import grammar, cool_ast, preprocess
from parsing.cool_transformer import ToCoolASTTransformer
from checksemantic.checksemantics import CheckSemanticsVisitor
from checksemantic.scope import Scope
from cool import fetch_program
... |
#!/usr/bin/env python
# -*- animation -*-
"""
Visualize a complex-valued function
"""
import numpy as np
import gr
def domain_colors(w, n):
H = np.mod(np.angle(w) / (2 * np.pi) + 1, 1)
m = 0.7
M = 1
isol = m + (M - m) * (H * n - np.floor(H * n))
modul = np.absolute(w)
Logm = np.log(modul)
... |
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.documentation import include_docs_urls
import notifications.urls
urlpatterns = [
path(r'', include('rbac.urls')),
path(r'', include('cmdb.urls')),
path(r'', include('rmms.url... |
# Copyright 2018-2021 Jakub Kuczys (https://github.com/jack1142)
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import logging
import os
import numpy as np
from .siamese_net import DNN
logger = logging.getLogger(__name__)
package_directory = os.path.dirname(os.path.abspath(__file__))
similarity_model_pretrained = os.path.join(package_directory, "model")
class SimilarityModel:
def __init__(self):
self.model = Non... |
from __future__ import annotations
from yarl import URL
import io
import typing
import os
from .factory import construct_repr
if typing.TYPE_CHECKING:
from .factory import HttpHandler
__all__ = ("Image",)
class Image:
"""
A class representing an `Image`.
Attributes:
url (str): URL of the... |
import logging
import enum
import copy
import telegram.error
from telegram import (
InlineKeyboardButton,
InlineKeyboardMarkup,
ParseMode
)
from app.entities import KnowledgeStatus
from app.card import Card
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import socket
default_port = 8003 # default port when adding a new server
listen_port = 8003 # server listens on this port
my_address = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("1.")][0]
dns_module_listen_port = 800... |
import datetime
import logging
from django.core.management.base import BaseCommand
from django.db import connection, transaction
from framework.celery_tasks import app as celery_app
logger = logging.getLogger(__name__)
TABLES_TO_POPULATE_WITH_MODIFIED = [
'addons_zotero_usersettings',
'addons_dropbox_userset... |
#!/usr/bin/env python
#Makes the output file "grid" which is used in various postprocessing scripts
import argparse
import numpy as np
import sys
import os
import re
# parse command line options
parser = argparse.ArgumentParser(description="Generates a cartesian mesh with a uniform region surrounded by a stretched gri... |
"""
App entry point which register FastAPI routers.
More info about used app structure: https://fastapi.tiangolo.com/tutorial/bigger-applications/
If you want to create a new API endpoint add endpoint handler to existed router or
create a new module in `routes` directory.
"""
from fastapi import FastAPI
from fastapi.... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from matplotlib import cm
from scipy.interpolate import interp1d
from scipy.spatial import distance
from scipy.optimize import differential_evolution
CELL_INFO_DIR = os.path.join('data-share', 'raw', 'cell_info')
def blend_electrodes(el... |
#!/usr/bin/env python
from distutils.core import setup
setup(name = "ciscotropo-webapi-python",
version = "0.1.4",
url = "http://github.com/tropo/tropo-webapi-python",
maintainer = "Cisco",
maintainer_email = "support@tropo.com",
description ... |
from heuslertools.tools.measurement import Measurement
import xrayutilities as xu
import warnings
import numpy as np
class RSMMeasurement(Measurement):
"""Object representing rsm measurement.
Parameters
----------
file : str
path of xrdml file.
Attributes
----------
en : str
... |
import numpy as np
import numpy.linalg as la
def gaussian_estimate(data, label, alpha):
assert len(data) == len(label), "label length mismatch"
assert label.min() == 0, "label should start from 0"
assert label.max() != 0, "label should have multiple"
trim = np.sum(data, axis=0) > 0
data = data[:, ... |
#
# 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
# ... |
# coding=utf-8
"""
Default Django settings for all Work4 projects.
Your own app should import all attributes from this file.
"""
from __future__ import unicode_literals
import os
import sys
from tzlocal import get_localzone
def env_to_bool(val):
"""Use this when parsing environment variables for booleans as ... |
""" This will module contains the setup_flask function as well as registry functions """
__author__ = 'Ben Christenson'
__date__ = "9/15/15"
import os
import inspect
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_login
from flask_login import LoginManager
from flask.blueprints ... |
import wasm3 as m3
import pytest
from helpers import wat2wasm
MV_SWAP_WASM = wat2wasm("""
(module
(func (export "swap") (param i32 i32) (result i32 i32)
(get_local 1)
(get_local 0)
)
)
""")
MV_IMPORT_WASM = wat2wasm("""
(module
(type $t0 (func (param i32 i64) (result i64 i32)))
(import "env" "swap" (... |
""" # lint-amnesty, pylint: disable=cyclic-import
XFields for video module.
"""
import datetime
from xblock.fields import Boolean, DateTime, Dict, Float, List, Scope, String
from xmodule.fields import RelativeTime
# Make '_' a no-op so we can scrape strings. Using lambda instead of
# `django.utils.translation.ug... |
"""Ingest by directly writing a ZIP file to archive storage.
"""
from __future__ import print_function
import sys
import os
import os.path
import re
import time
from threading import Thread
if sys.version_info < (3, 0):
import Queue as queue
else:
import queue
import zlib
import logging
import pytest
import ic... |
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
def has_object_permission(self,request,view,obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.id==request.user.id
class UpdateStatus(permissions.BasePermission):
de... |
import collections
import logging
import string
from abc import abstractmethod
from typing import Callable, List
from flask_sqlalchemy import SQLAlchemy
from retrying import retry
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import FlushError, NoResultFound
from profiles.exceptions import OrcidTo... |
from .common import EWSAccountService, create_attachment_ids_element
from ..properties import RootItemId
from ..util import create_element
class DeleteAttachment(EWSAccountService):
"""MSDN:
https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/deleteattachment-operation
"""
... |
"""
388. Longest Absolute File Path
Medium
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1... |
# -*- coding: utf-8 -*-
# DO NOT EDIT THIS FILE!
# This file has been autogenerated by dephell <3
# https://github.com/dephell/dephell
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = ""
setup(
long_description=readme,
name="tgintegration",
version=... |
import logging
from datetime import datetime
import tweepy
import creds
from main import make_covid_graph
logging.basicConfig(filename='nepal-covid.log',
level=logging.INFO,
format='%(asctime)s-%(name)s - %(levelname)s - %(message)s',
datefmt='%d-%b-%y %H... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_compat.py
Last updated: 2019-09-27
"""
from wz_core.reporting import Report
from test_core import testinit, runTests
if __name__ == '__main__':
testinit ()
# from wz_compat import migrate
# runTests (migrate)
# from wz_compat import import_pup... |
import base64
import logging
from tornado.escape import json_decode
from tornado.web import Finish
from db import UserStatus
from emailer import send_verification_email, send_password_reset_email
from service.property import get_property, set_property
from service.user import (
get_user,
get_user_profile,
... |
from bs4 import BeautifulSoup
from collections import Counter
from string import punctuation
def word_frequencies(url):
"""
Downloads the content from the given URL and returns a dict {word -> frequency}
giving the count of each word on the page. Ignores HTML tags in the response.
:param url: Full URL ... |
import numpy as np
array = np.array([['08', '02', '22', '97', '38', '15', '00', '40', '00', '75', '04', '05', '07', '78', '52', '12', '50', '77', '91', '08'],
['49', '49', '99', '40', '17', '81', '18', '57', '60', '87', '17', '40', '98', '43', '69', '48', '04', '56', '62', '00'],
['81', '49', '31', '73', '55', '79', '... |
import os
import logging
import cfn_storage_gateway_provider
import cfn_cache_provider
import cfn_file_share_provider
log = logging.getLogger()
log.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
def handler(request, context):
if request['ResourceType'] == 'Custom::StorageGatewayNfsFileShare':
return cfn_f... |
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as random
import re
import textstat
from scipy import stats
from scipy.stats import spearmanr
#coding:utf-8
###############
#一般図書のYL
x = [8, 6.6, 8.5, 6.5, 5, 7, 6, 5, 5, 5, 6.5, 6.5, 7, 8.2, 7.6, 7.5, 7.5, 7.3,
7, 8.2, 8, 8.5, 7, 6.6, 7.7, 7... |
import asyncio
from collections import OrderedDict
import logging
import uuid
import msgpack
import re
import types
from wolverine.module import MicroModule
from wolverine.module.controller.zhelpers import unpackb, packb, dump
from wolverine.module.service import ServiceMessage
logger = logging.getLogger(__name__)
c... |
"""
Class Encore CIS 211 w/ Joseph
contest.py
Author: Joseph Goh
Updated: 03/04/2021
"""
from typing import List, Dict
class Hometown:
def __init__(self, name: str):
self.name = name
self.champions = []
def get_total_wins(self) -> int:
total = 0
for champ in self.champions:
... |
#!/usr/bin/env python3
"""
Copyright (c) 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... |
'''Adapte o código do desafio #107, criando uma função adicional chamada moeda() que consiga
mostrar os números como um valor monetário formatado.'''
import moeda
preco = float(input('Digite o preço: R$ '))
print(f'A metade de {moeda.moeda(preco)} é {moeda.moeda(moeda.metade(preco))}')
print(f'O dobro de {moeda.moeda... |
input = open('/Users/krishjain/Desktop/AdventOfCode/Day 6/input.txt', "r").read()
input = input.split("\n\n")
countOfAnswersPerGroup = []
for i in input:
listOfAnswersToWhichAnsweredYes = []
for j in i.replace("\n", ""):
listOfAnswersToWhichAnsweredYes.append(j)
unorderedListOfAnswers = list... |
import matplotlib.pyplot as plt
env_map = [(8.92, 283.86), (17.83, 283.44), (68.13, 720.79), (112.8, 892.9), (140.79, 888.92), (101.75, 533.38), (106.89, 478.2), (115.39, 449.42), (117.73, 405.24), (111.25, 342.38), (87.73, 243.69), (113.38, 286.37), (121.92, 281.75), (124.33, 264.21), (124.39, 244.14), (125.74, 228.7... |
#
# Copyright (c) 2013-2014 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import cStringIO
import httplib2
import re
import sys
import fixtures
from inventoryclient import exc
from inventoryclient import shell as inventoryclient_shell
from inventoryclient.tests import utils
from testtools import ... |
# coding: utf-8
# http://gitlab.skoltech.ru/shapeev/mlip-dev/blob/master/src/external/python/mlippy/cfgs.py
from __future__ import print_function
import numpy as np
class Cfg:
pos = None
lat = None
types = None
energy = None
forces = None
stresses = None
desc = None
grade = None
def... |
from bitrue.client import Client
if __name__ == '__main__':
client = Client(api_key='',
api_secret='',
)
trades = client.get_my_trades()
print(client._order_format_print(trades))
'''
symbol id orderId origClientOrderId price qty comm... |
# coding=utf-8
# Copyright 2022 The Balloon Learning Environment 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 require... |
liste = ["ali", "veli"]
print(liste)
if "al" not in liste:
print("var") |
from .optim_low import *
__all__ = ["OptimMP"]
|
"""empty message
Revision ID: dcbee03e3639
Revises:
Create Date: 2018-07-10 04:25:35.968792
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'dcbee03e3639'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
from trezor import wire
from trezor.messages import MessageType
def boot():
# only enable LoadDevice in debug builds
if __debug__:
wire.add(MessageType.LoadDevice, __name__, "load_device")
wire.add(MessageType.ResetDevice, __name__, "reset_device")
wire.add(MessageType.BackupDevice, __name__, ... |
from __future__ import print_function
import sys
import os
import requests
from datetime import datetime
from random import randint
import re
class Facegrab:
def __init__(self):
self.base_url = "http://graph.facebook.com/picture?id={}&width=800"
self.sess = requests.Session()
self.sess.hea... |
from polygon import WebSocketClient
from polygon.websocket.models import WebSocketMessage
from typing import List
import asyncio
c = WebSocketClient(subscriptions=["T.*"])
async def handle_msg(msgs: List[WebSocketMessage]):
for m in msgs:
print(m)
async def timeout():
await asyncio.sleep(1)
pri... |
import numpy as np
#import tensorflow as tf
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from tqdm import tqdm
import argparse
import sys
import cv2
import math
rgb = True
def draw_bboxes (img, boxes, outname):
for i in range(len(boxes)):
xmin,ymin,xmax,ymax,cat = boxes[i]
c... |
from pylama_dmypy import VERSION
from setuptools import setup, find_packages
# fmt: off
setup(
name = "pylama-dmypy"
, version = VERSION
, packages = find_packages(include="pylama_dmypy.*", exclude=["tests*"])
, extras_require =
{ 'tests':
[ "pylama==8.3.8"
, "mypy==0.942"
... |
# -*- coding: utf-8 -*-
__all__ = ('SlashCommandPermissionOverwriteWrapper', 'SlashCommandWrapper', )
from functools import partial as partial_func
from ...discord.guild import Guild
from ...discord.preconverters import preconvert_snowflake
from ...discord.interaction import ApplicationCommandPermissionOverwrite
UNL... |
from collections import deque, defaultdict
import sys
N = int(input())
ab = []
for i in range(N - 1):
ab.append(tuple(map(int, input().split())))
c_list = list(map(int, input().split()))
c_list.sort()
c_que = deque(c_list)
cnt = defaultdict(int)
outs = defaultdict(list)
for a, b in ab:
cnt[a - 1] += 1
cn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.