content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
###
#
# Lenovo Redfish examples - Get metric inventory
#
# Copyright Notice:
#
# Copyright 2019 Lenovo 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.o... | python |
#!usr/bin/python
# -*- coding:utf8 -*-
# 列表生成式(列表推导式)
# 1. 提取出1-20之间的奇数
# odd_list = []
# for i in range(21):
# if i % 2 == 1:
# odd_list.append(i)
# odd_list = [i for i in range(21) if i % 2 == 1]
# print(odd_list)
# 2. 逻辑复杂的情况 如果是奇数将结果平方
# 列表生成式性能高于列表操作
def handle_item(item):
return item * item
odd... | python |
"""
Desenvolva uma lógica que leia o peso e a altura de uma pessoa,
calcule seu IMC e mostre seu status.
Rasgue as minhas cartas
E não me procure mais
Assim será melhor, meu bem
O retrato que eu te dei
Se ainda tens, não sei
Mas se tiver, devolva-me
Devolva-me - Adriana Calcanhot... | python |
# -*- coding: utf-8 -*-
from flask import Flask
from peewee import MySQLDatabase
from celery import Celery
from config import config
db = MySQLDatabase(None)
def create_app(config_name):
"""
创建flask应用对象
:param config_name:
:return:
"""
app = Flask(__name__)
app.config.from_object(confi... | python |
from __future__ import print_function, division
#
import sys,os
quspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,quspin_path)
#
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import spinful_fermion_basis_1d # Hilbert space spinful fermion basis
import numpy as ... | python |
"""
Sponge Knowledge Base
Action metadata Record type
"""
def createBookType(name):
return RecordType(name, [
IntegerType("id").withNullable().withLabel("Identifier"),
StringType("author").withLabel("Author"),
StringType("title").withLabel("Title")
... | python |
"""
restriction generaters representing sets of packages
"""
| python |
# http://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/
from sys import maxint
class MyStack:
def __init__(self):
self.minimum = -maxint-1
self.stack = []
def push(self,val):
if not self.stack:
self.minimum = val
... | python |
import pygame
import math
pygame.font.init()
DEBUG_FONT = pygame.font.Font(None, 22)
def get_surface(obj):
""" Returns a Surface representing the parameter.
if obj is the filename of an image, a surface containing the image will be returned.
if obj is a Surface, it will be returned unchanged.
"""
... | python |
# 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 unittest
import beanmachine.ppl as bm
import torch
import torch.distributions as dist
from beanmachine.ppl.experimental.abc.abc_infe... | python |
from .base import init
| python |
__author__ = 'zaxlct'
__date__ = '2017/4/6 下午12:14'
import re
from django import forms
from operation.models import UserAsk
# class UserAskForm(forms.Form):
# name = forms.CharField(required=True, min_length=2, max_length=20)
# phone = forms.CharField(required=True, min_length=11, max_length=11)
# cours... | python |
from .libs import metadata
from .libs import utils
from .libs.athena import Athena
from .libs.s3 import S3
from .libs.csv_parser import single_column_csv_to_list, csv_to_list_of_dicts
from .libs.policy_generator import PolicyGenerator
import argparse
import logging
def arguments():
parser = argparse.ArgumentParse... | python |
import boto3
import json
from datetime import datetime
#to download, <bucket, obj name, file path to dl to>
# s3.download_file(
# "iot-fastgame-proj-ads","beard.jpg","downloads/beard.jpg"
# )
#to upload <file path to upload from, bucket, obj name>
# s3.upload_file('images/pokemon.jpg','iot-fastgame-proj-ads','pok... | python |
import turtle as t # підключення бібліотеки
from random import randint
from turtle import *
screen = t.getscreen() # вікно
t.title("Черепашка")
my_turtle = t.Turtle()
my_turtle.shape("turtle") # square , triangle , classic
#my_turtle.color("green")
my_turtle.color("black","red")
my_turtle.shapesize(2,2,0)
#for i in ran... | python |
cisco_ios = "Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)"
a = cisco_ios.split()
print(a)
b = a.index('Version')
c = a[b+1]
d = c[:-1]
print(d)
# for i in a:
# if i=='Version':
# print(i) | python |
from math import sqrt, ceil
def p1(num: int):
size = ceil(sqrt(num))
center = ceil((size - 1) / 2)
return max(0, center - 1 + abs(center - num % size))
assert p1(1) == 0
assert p1(12) == 3
assert p1(23) == 2
assert p1(1024) == 31
assert p1(347991) == 480
# p2 349975
# https://oeis.org/A141481
| python |
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
# Copyright (c) 2008 Brendan Dolan-Gavitt <bdolangavitt@wesleyan.edu>
#
# Additional Authors:
# Mike Auty <mike.auty@gmail.com>
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of... | python |
# -*- coding: utf-8 -*-
__author__ = 'abbot'
import requests
# response = requests.get("https://www.12306.cn/mormhweb/", verify = False)
# print(response.text)
response = requests.get("http://www.baidu.com")
print(response.content)
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'a test module'
import sys
_author_ = 'tianmaolin'
def fun1(*a):
print(a)
def fun2(**b):
print(b)
# fun1(1, 2, 5)
# fun2(name='tianmlin', age=22)
def test():
args = sys.argv
if len(args) == 1:
print("Hello World!")
elif len(args) == 2:
... | python |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from conte... | python |
import os
from typing import Any
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
import cssutils
import requests
url_re = r'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)'
def delete_duplicates(l: list) -> list:
new_l = []
... | python |
# Generated by Django 2.2 on 2019-06-21 07:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0055_auto_20190620_1527'),
]
operations = [
migrations.AddField(
model_name='presentation',
name='is_keynote',
... | python |
# AUTOGENERATED FILE! PLEASE DON'T EDIT
from .callbacks import Callback, Callbacks, Cbs
import k1lib, os, torch
__all__ = ["Autosave", "DontTrainValid", "InspectLoss", "ModifyLoss", "Cpu", "Cuda",
"DType", "InspectBatch", "ModifyBatch", "InspectOutput", "ModifyOutput",
"Beep"]
@k1lib.patch(Cbs)
c... | python |
import cowsay
print(cowsay.get_output_string('trex', 'Hello (extinct) World')) | python |
#!/usr/bin/env python
# coding=utf-8
#list:[]
bicycles = ['trek', 'cannodale', 'redline', 'speciakixrdd']
print(bicycles)
#下标正数: 0,1,2,... , n - 1; 到着数: -1, -2, ...., n
print(bicycles[0].title())
print(bicycles[-1])
motorcycles = ['honda', 'yamaha', 'suzyki']
print(motorcycles)
## 修改
motorcycles[0] = 'ducati... | python |
import torch
class ModelPipeline:
def __init__(self, preprocessor, model, return_numpy=True):
self.preprocessor = preprocessor
self.model = model
self.return_numpy = return_numpy
def __call__(self, *args, **kwargs):
inputs = self.preprocessor(*args, **kwargs)
if isinst... | python |
#!/Users/rblount/.pyenv/versions/AdOfCode/bin/python
import sys
import os
import numpy as np
from TerminalColors import BRED, BGREEN, ENDCOLOR
from AOC import AOC
testing = False
days = 100
def parse_input(data_input: list):
array = np.genfromtxt(data_input, dtype=int, delimiter=1)
return array
def prin... | python |
from .realtime import interface, urlib
################################################################
## Simulated robot implementation
################################################################
class SimConnection:
"""Implements functionality to read simulated robot state (arm and F/T sensor) and command ... | python |
import sys
import time
from networktables import NetworkTables
import logging
logging.basicConfig(level=logging.DEBUG)
NetworkTables.initialize(server = "localhost")
sd = NetworkTables.getTable("/vision")
while True:
try:
x = sd.getNumberArray('centerX')
width = sd.getNumberArray('width')
... | python |
# Generated by Django 3.0.5 on 2020-09-02 22:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0020_auto_20200903_0339'),
]
operations = [
migrations.AlterField(
model_name='questiontable',
name='count1... | python |
from django.apps import AppConfig
class HarvesterConfig(AppConfig):
default_auto_field = 'django.db.models.AutoField'
name = 'harvester'
| python |
#!/usr/bin/env python3.7
"""
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent
"""
import json
import os
from typing import Uni... | python |
"""ssoadmin module initialization; sets value for base decorator."""
from .models import ssoadmin_backends
from ..core.models import base_decorator
mock_ssoadmin = base_decorator(ssoadmin_backends)
| python |
import unittest
from page.thread_page import Page
import time
class threadDemo(unittest.TestCase):
def __repr__(self):
return 'appdemo'
@classmethod
def setUpClass(cls):
cls.page = Page()
def test_a_thread(self):
time.sleep(6)
self.page.login_btn()
time.sleep(... | python |
import falcon
from falcon.testing import TestResource as ResourceMock
from tests import RestTestBase
from monitorrent.rest import no_auth, AuthMiddleware
def is_auth_enabled():
return False
class TestAuthMiddleware(RestTestBase):
def setUp(self, disable_auth=False):
super(TestAuthMiddleware, self).s... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String, Bool
from burger_war_dev.msg import war_state
from actionlib_msgs.msg import GoalStatusArray
class StateControlBot():
def __init__(self):
self.pub = rospy.Publisher("main_state",String, queue_size=10)
self.s... | python |
valor1 = 0
acumu1 = 0
valor2 = 10
acumu2 = 10
while valor <= 8:
print(acumulador, valor1)
else:
print('terminou o laço') | python |
from ._pyg_decoders import (
LogSoftmaxDecoderMaintainer,
SumPoolMLPDecoderMaintainer,
DiffPoolDecoderMaintainer,
DotProductLinkPredictionDecoderMaintainer
)
| python |
import random
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t = t[::-1]
res = []
for length, word in t:
res.append(word)
return res
def sort_by_length_random(words):
"""Modify this example so that words with the same length appear in ran... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
# fix sys path so we don't need to setup PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'userena.runtests.settings'
import django
if django.VERSION >= (1, 7, 0):
# starting from 1.... | python |
import pytest
from omniscient.utils.query_graph_utils import QueryGraphUtils
@pytest.fixture(scope="class")
def setup():
sparql = """
PREFIX ns: <http://rdf.freebase.com/ns/>
SELECT DISTINCT ?x
WHERE {
FILTER (?x != ?c)
FILTER (!isLiteral(?x) OR lang(?x) = '' OR langMatches(lang(?... | python |
A = ['C', 'D', "E", "F", "G"]
B = [3, 0, 4, 1, 2]
def sort(A, B):
t = zip(A,B)
t = sorted(t, key=lambda x: x[1])
A, B = zip(*t)
return A
print sort(A,B) | python |
""""""
# Standard library modules.
import os
# Third party modules.
import pytest
import pyxray
# Local modules.
from pymontecarlo_penepma.importer import PenepmaImporter
# Globals and constants variables.
@pytest.fixture
def importer():
return PenepmaImporter()
@pytest.mark.asyncio
async def test_import(ev... | python |
import os
import streamlit as st
import pandas as pd
import plotly.express as px
from PIL import Image
favicon = Image.open("media/favicon.ico")
st.set_page_config(
page_title = "AICS Results",
page_icon = favicon,
menu_items={
'Get Help': 'https://github.com/All-IISER-Cubing-Society/Results',
... | python |
"""
Create a movie
==============
This example shows how to create a movie, which is only possible if `ffmpeg` is
installed in a standard location.
"""
from pde import UnitGrid, ScalarField, DiffusionPDE, MemoryStorage, movie_scalar
grid = UnitGrid([16, 16]) # generate grid
state = ScalarFi... | python |
import warnings
warnings.simplefilter('ignore')
import pytest
import numpy as np
import keras
from hand_classifier.hand_cnn import HandCNN
@pytest.mark.parametrize("img_shape, target_shape", [((512, 512, 3), (224, 224, 3)), ((820, 430, 3), (96, 96, 3)), ((400, 800, 3), (114, 114, 3))])
def test_preprocessing(img_sha... | python |
from flask import Blueprint
main=Blueprint("main",__name__)
from .views import * | python |
# # scan_test.py
# # Author: Thomas MINIER - MIT License 2017-2018
# from query_engine.sage_engine import SageEngine
# from query_engine.iterators.scan import ScanIterator
# from query_engine.iterators.union import BagUnionIterator, RandomBagUnionIterator
# from database.hdt_file_connector import HDTFileConnector
#
# h... | python |
# Copyright 2018 Sabino Miranda Jimenez
# 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 w... | python |
from ._helpers import export_data, ExportScope
from . import orders, nested_orders
| python |
RESNET = "resnet"
XCEPTION = "xception"
INCEPTIONV3 = "inceptionv3"
VGG16 = "vgg16"
IMAGENET = "imagenet"
CONFIG_FILE = "config.json"
MODEL_INFO_FILE = "model_info.json"
SCORING = "scoring"
RETRAINING = "retraining"
BEFORE_TRAIN = "before_train"
RETRAINED_SUFFIX="_retrained"
CUSTOM_TOP_SUFFIX = "_customtop"
RETRAINED =... | python |
import datetime
from dateutil import tz
def identity(x):
'''return the input value'''
return x
def local_timestamp(ts):
'''return a dst aware `datetime` object from `ts`'''
return datetime.datetime.fromtimestamp(ts, tz.tzlocal())
def strftime(ts):
if ts is None:
return 'None'
if ... | python |
"""
Copyright (c) 2018-2021 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 law or agreed to in wri... | python |
"""
This module details user input api
"""
import time
from queue import Queue, Empty
from pubsub import pub
from fixate.config import RESOURCES
from collections import OrderedDict
USER_YES_NO = ("YES", "NO")
USER_RETRY_ABORT_FAIL = ("RETRY", "ABORT", "FAIL")
def _user_req_input(msg, target=None, attempts=5, **kwarg... | python |
"""
NOTE: Здесь можно описывать и другие аспекты, которые идут параллельно основному использованию.
Если слишком длинно - можно и ссылками на офиц. доку
"""
def example_1():
pass
if __name__ == "__main__":
example_1() | python |
import os.path
from data.base_dataset import BaseDataset, get_transforms_reid, get_transforms_LR_reid, get_transforms_norm_reid
from data.image_folder import make_reid_dataset
from PIL import Image
from scipy.io import loadmat
import numpy as np
class SingleMarketDataset(BaseDataset):
@staticmethod
def modify... | python |
from pm4pymdl.algo.mvp.utils import succint_mdl_to_exploded_mdl, clean_objtypes
import pandas as pd
def preprocess(df, parameters=None):
if parameters is None:
parameters = {}
conversion_needed = False
try:
if df.type == "succint":
conversion_needed = True
except:
... | python |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import torchvision
import torch
import matplotlib.pyplot as plt
from pathlib import Path
import logging
import time
import pickle
from sklearn.model_selection import train_test_split
from torch.utils.data import TensorDataset, DataLoader
from torch.utils.da... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 08/10/2017
Updated: 02/04/2018
# Description
Unit tests for the functions in the ands.algorithms.numerical.barycentric
module.
"""
import unittest
from ands.algorithms.numerical.barycentric import barycentric, compu... | python |
# -*- coding=utf-8 -*-
__all__ = [
'tiny_imagenet',
'imagewoof2',
'imagenette2'
]
import os
import torch
import torchvision
_default_batch_size = 32
_default_num_workers = 4
def _transform(train=True):
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
if train:
return torchvi... | python |
#!/usr/bin/python
import util
TAG_LIST_1 = ['keyspace', 'shard', 'type']
TAG_LIST_2 = ['type']
TAG_LIST_3 = ['method', 'keyspace', 'shard', 'type']
TAG_LIST_4 = ['method', 'keyspace', 'type']
def process_data(json_data):
epoch_time = util.get_epoch_time()
util.create_metric(epoch_time, "vitess.healthcheck... | python |
import requests
import os
API_URL = 'http://127.0.0.1:8000/api/devices/devicetype/1/'
API_KEY = os.environ['TESTAUTH']
headers = {'Authorization': f'Token {API_KEY}'}
r = requests.delete(API_URL, headers=headers)
print(r.status_code)
| python |
from django.test import TestCase
class AnalyzerTasksTestCase(TestCase):
@classmethod
def setUpTestData(cls):
pass
| python |
#!/usr/bin/env python
import sys,argparse
import numpy
import os
import time, datetime
import h5py
import scipy.misc
import configobj
def get_valid_stacks(f_names):
f_names_valid = []
for fn in f_names:
with h5py.File(fn,"r") as f:
if "mean" in f.keys():
f_names_valid.append... | python |
#coding=utf-8
# Copyright (c) 2018 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | python |
import json
import requests
import code
class Demand():
def __init__(self, region='ap-southeast-1', instanceType='m4.large', operatingSystem='Linux'):
self.url = 'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/{}/index.json'.format(region)
self.instanceType = instanceTyp... | python |
"""
Our exception hierarchy:
* HTTPError
x RequestError
+ TransportError
- TimeoutException
· ConnectTimeout
· ReadTimeout
· WriteTimeout
· PoolTimeout
- NetworkError
· ConnectError
· ReadError
· WriteError
· CloseError
- ProtocolE... | python |
# Copyright 2020 Google LLC
#
# 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 applicable law or agreed to in writing, ... | python |
"""
GMail! Woo!
"""
__title__ = 'gmail'
__version__ = '0.1'
__author__ = 'Charlie Guo'
__build__ = 0x0001
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Charlie Guo'
from gmail import Gmail
from mailbox import Mailbox
from message import Message
from utils import login, authenticate
| python |
import pytest
from pype import *
from timeseries import *
__author__ = "Mynti207"
__copyright__ = "Mynti207"
__license__ = "mit"
def test_lexer():
# sample data
data = '''
3 + 4 * 10
+ -20 *2
'''
# pass data to lexer and tokenize
lexer.input(data)
for tok in lexer:
assert ... | python |
# -*- coding:utf-8; -*-
class SolutionV1:
def letterCombinations(self, digits):
# 1. 定义一个集合存储最后的字符串
result = []
# 2. 然后定义一个递归函数,来生成符合条件的字符串
# 递归函数的参数如何定义:
# i 表示递归层数,虽然不知道i此时到底什么意思。
# digits表示要传递的数字字符,因为生成数字对应的字母字符串肯定是离不开这个参数的
def helper(i, digits, s):
... | python |
##
## This file is part of the libsigrok project.
##
## Copyright (C) 2013 Martin Ling <martin-sigrok@earth.li>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the Lice... | python |
import os
import shutil
import audeer
import audformat
import audiofile as af
import pandas as pd
src_dir = 'src'
build_dir = audeer.mkdir('build')
# Prepare functions for getting information from file names
def parse_names(names, from_i, to_i, is_number=False, mapping=None):
for name in names:
key = n... | python |
X_raw_0 = [
[0, 0.1, 0, 0, 0],
[0.1, 0, 0.1, 0, 0.1],
[0, 0.1, 0, 0.1, 0],
[0, 0, 0.1, 0, 0],
[0, 0.1, 0, 0, 0]
]
node_info_0 = [
{
'min_load': 0,
'max_load': 30,
'min_power': 0,
'max_power': 15,
'load_coeff': 10,
'load_ref': 20,
'power_co... | python |
from typing import List
from pydantic import BaseModel, Field
__all__ = [
"ArticleRankDTO",
]
class ArticleRankDTO(BaseModel):
articleTitle: str = Field(
... ,
description = "文章标题"
)
viewCount: int = Field(
... ,
description = "文章浏览量"
... | python |
# ===========================================================================
# Copyright 2013 University of Limerick
#
# This file is part of DREAM.
#
# DREAM is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Founda... | python |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
# (c) 2017, Peter Sprygada <psprygad@redhat.com>
# (c) 2017 Ansible Project
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fcntl
import gettext
import os
import ... | python |
#!/usr/bin/env python3
#encoding=utf-8
#-----------------------------------------
# Usage: python3 4-getattr-builtins.py
# Description: compare __getattr__ and __getattribute__
#-----------------------------------------
class GetAttr:
eggs = 88 # eggs stored on class, spam on instance
def __init__(self... | python |
# Exercício Python 024
# Leia o nome de uma cidade. Começa com 'SANTO'
cidade = str(input('Digite o nome de uma cidade: ')).strip()
minusculo = cidade.lower()
santo = 'santo'in minusculo[0:5]
print(santo)
# outra forma
print(cidade[:5].lower() == 'santo')
| python |
import numpy
import pytest
import helpers
import meshio
@pytest.mark.parametrize(
"mesh",
[
helpers.tri_mesh,
helpers.tri_mesh_2d,
helpers.tet_mesh,
helpers.add_cell_data(helpers.tri_mesh, 1, dtype=float),
helpers.add_cell_data(helpers.tri_mesh, 1, dtype=numpy.int32),
... | python |
"""
LINK: https://leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Follow up: Could you write a solution that works in logarithmic time complexity?
Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: n = 5
Outpu... | python |
from generators import *
from laws import (monoid_laws, functor_laws, applicative_laws, monad_laws, trans_laws)
from fplib.maybe import Maybe
from fplib.transformer import trans
from fplib.ident_t import IdT
T = trans(IdT, Maybe)
def cmpidt(idt0, idt1):
return idt0.unwrap == idt1.unwrap
def test_idt_functor()... | python |
"""
Energy level and transitions classes
"""
import numpy as np
import astropy.units as u
import astropy.constants as const
from fiasco.util import vectorize_where
__all__ = ['Level', 'Transitions']
class Level(object):
def __init__(self, index, elvlc):
self._index = index
self._elvlc = elvlc
... | python |
"""
# -*- coding: utf-8 -*-
__author__ = "Akash"
__email__ = "akashjio6666@gmail.com"
__version__ = 1.0.0"
__copyright__ = "Copyright (c) 2004-2020 Leonard Richardson"
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
Description:
Py-Insta Is A Python Library
... | python |
import scrython
import time
query = input("Type the name of the set: ")
time.sleep(0.05)
sets = scrython.sets.Sets()
for i in range(sets.data_length()):
if sets.set_name(i) == query:
print("Set code:", sets.set_code(i).upper())
break
else:
continue
| python |
import json
import binascii
import struct
import random
from io import BytesIO
import sys
from operator import itemgetter
class Item():
def __init__(self, name, index, quantity, rate):
self.name = name
self.index = index
self.quantity = quantity
self.rate = rate
def __repr__(self):
return ... | python |
import os
from pytest import fixture
from zpz.filesys.path import relative_path
from zpz.spark import PySparkSession, ScalaSparkSession, SparkSession, SparkSessionError
livy_server_url = None
@fixture(scope='module')
def pysession():
return PySparkSession(livy_server_url)
@fixture(scope='module')
def scalases... | python |
from benchbuild.projects.benchbuild.group import BenchBuildGroup
from benchbuild.utils.wrapping import wrap
from benchbuild.settings import CFG
from benchbuild.utils.compiler import lt_clang, lt_clang_cxx
from benchbuild.utils.downloader import Git
from benchbuild.utils.run import run
from benchbuild.utils.versions imp... | python |
# Elaine Laguerta (github: @elaguerta)
# LBNL GIG
# File created: 28 May 2021
# Smell tests to verify Solution API functions
from gigpower.solution import Solution
from gigpower.solution_dss import SolutionDSS
from gigpower.solution_fbs import SolutionFBS
from gigpower.solution_nr3 import SolutionNR3
from gigpower.ut... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Django Models documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 29 06:50:23 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in thi... | python |
load("@bazel_tools//tools/jdk:toolchain_utils.bzl", "find_java_runtime_toolchain", "find_java_toolchain")
def _proto_path(proto):
"""
The proto path is not really a file path
It's the path to the proto that was seen when the descriptor file was generated.
"""
path = proto.path
root = proto.root... | python |
"""
Methods for working with releases, including the releaseObject class
definition live here.
"""
# standard library imports
from datetime import datetime, timedelta
import json
# second party imports
from bson import json_util
from bson.objectid import ObjectId
import flask
import pymongo
# local imports
f... | python |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import os
import sys
import signal
import time
from datetime import datetime
from datetime import timedelta
# import cv2 as cv
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt # 导入模块 matplotlib.pyplot,并简写成 plt
import numpy as np # 导入... | python |
"""
Class to represent the results of a prediction.
"""
import codecs
import logging
import os
import warnings
from numpy import ndarray
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.metrics import \
confusion_matrix, \
recall_score, \
precision_score, \
f1_score, \
accuracy_sc... | python |
import server_socket
import threading
class Microphone(object):
def __init__(self, host, port, steer):
self.steer = steer
self.socket = server_socket.Server(host, port)
self.client = self.socket.Get_Client()
def Recv(self) :
while True :
# 스레드를 돌면서 s... | python |
#!/usr/bin/env python2
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""This simulates a real job by producing a lot of output."""
from __future__ import print_function
__author__ = 'asharif@google.com (Ahmad Sharif)'
import time
def Main():
"""The main function."""
for j in range(10):
for i in rang... | python |
############## Configurator for command line programs
#### tests
# 2016 Portia Frances Limited for UBS
# Author: Thomas Haederle
import logging
logger = logging.getLogger(__name__)
import pytest
#from nose.tools import *
from configurator import Configurator
def test_configurator_initialize():
conf = Configurat... | python |
def signed8(b):
if b > 127:
return -256 + b
else:
return b
def signed16(v):
v &= 0xFFFF
if v > 0x7FFF:
return - 0x10000 + v
else:
return v
def signed24(v):
v &= 0xFFFFFF
if v > 0x7FFFFF:
return - 0x1000000 + v
else:
return v
def read_... | python |
# import geopandas
# from utils.common import load_shape
# from pathlib import Path
# import sys
# sys.path.append(str(Path(__file__).parent.parent))
# from configs import server_config
# # from shapely.geometry import shape
# from db_connection import DBConnection
# from alchemy import Eez
# import shapely.geometry as... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.