content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
from distutils.core import setup
from pinder import __version__
setup(
name='pinder',
version=__version__,
description='Python API for Campfire.',
license='BSD',
author='Lawrence Oluyede',
author_email='l.oluyede@gmail.com',
url='http://dev.oluyede.org/pinder/',
... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
##############################################
# The MIT License (MIT)
# Copyright (c) 2018 Kevin Walchko
# see LICENSE for full details
##############################################
# These are IntFlags, so you can compare them to ints. They
# start with 1 and go to N.
# ZmqType.pub == 1
# ZmqType.sub == 2
#
from enu... |
from openpyxl import Workbook, load_workbook
import os
import glob
import json
#directories
FIGRAM_PATH = '/media/mjia/Data/CNN-fMRI/FIGRIM/SCENES_700x700'
CROPPED_SUN_PATH = '/media/mjia/Data/CNN-fMRI/cropped'
TARGET_PATH = '/media/mjia/Data/CNN-fMRI/Pool'
if os.path.isdir(TARGET_PATH):
os.popen("rm -r -f" + TARG... |
# ---------------------------------------
# Program by Orlov.A.
#
#
# Version Date Info
# 1.0 2016 Initial Version
#
# ----------------------------------------
# x = 25
#
# if x == 25:
# print("YES, yo're right")
# else:
# print("NO!!!!!!!!!!!!!!!!!!!!!!!!")
age = 13
if (age <= 4):
print... |
elements = bytes([255])
print (elements[0])
|
# coding: UTF-8
import setting
TOKEN = setting.TOKEN
print(TOKEN)
## 以降ソースコード
|
# Ideal Gas Force Field
import numpy as np
class IdealGas:
def __init__(self):
pass
def __call__(self, x, *args, **kwargs):
return np.zeros_like(x) |
from http import HTTPStatus
from fastapi import Depends, Query
from starlette.exceptions import HTTPException
from lnbits.core.crud import get_user, get_wallet
from lnbits.core.services import check_invoice_status, create_invoice
from lnbits.decorators import WalletTypeInfo, get_key_type
from . import paywall_ext
fr... |
from __future__ import division
from warnings import warn
from numpy import sqrt, exp, power, linspace, interp, log, pi
from environment import Atmosphere, G_0
MAX_T_TO_W = 5
class Mission(object):
"""
A mission as defined by a list of segments.
"""
def __init__(self, segments=None, atmosphere=Non... |
import torch
import torch.nn as nn
from ..utils import ConvModule
from qd3dt.core import bbox_overlaps
class Relations(nn.Module):
def __init__(self,
in_channels=1024,
inter_channels=1024,
groups=16,
num_embed_convs=1,
share_em... |
T = int(raw_input())
for i in range (0,T):
money, item_price, exchange_wrapper = [int(x) for x in raw_input().split(' ')]
bought = money / item_price
answer = bought
wrappers = bought
while wrappers >= exchange_wrapper:
extra_items = wrappers / exchange_wrapper
answer += extra_... |
"""
abc-classroom.utils
===================
"""
import os
import subprocess
import sys
import tempfile
import textwrap
from contextlib import contextmanager
from functools import lru_cache
from shutil import copystat, copy2
from IPython import get_ipython
class Error(OSError):
pass
# a copy of shutil.copytr... |
"""
Solution to an exercise from
Think Python: An Introduction to Software Design
Allen B. Downey
This program requires Gui.py, which is part of
Swampy; you can download it from thinkpython.com/swampy.
This program started with a recipe by Noah Spurrier at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/5219... |
import random
import discord
import discord.ext.commands as commands
from .util import checks
SHIMMY_SERVER_ID = '140880261360517120'
NSFW_ROLE_ID = '261189004681019392'
eight_ball_responses = [
# Positive
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes, definitely",
"You may... |
from tars_data_models.spendy.transaction import Transaction |
import os
from pyairtable import Table, Base, Api
from abc import ABC, abstractmethod
class DB_Connector(ABC):
@abstractmethod
def Get_Api(self):
pass
@abstractmethod
def Get_Base(self):
pass
@abstractmethod
def Get_Table(self, table_name: str):
pass
class PyAirtable_... |
import numpy as np
import matplotlib.pyplot as plt
import argparse
from random import shuffle
from mpl_toolkits.mplot3d import Axes3D
from tqdm import *
from sklearn.cluster import KMeans
from sklearn.preprocessing import normalize
from pymongo import MongoClient
from scipy.spatial import distance
from sklearn.metrics ... |
from flask import url_for
def test_hostgroups(client, access_token):
token = access_token
res = client.get(url_for('hostgroups'), headers={'authorization': "Bearer {token}".format(token=token)})
assert res.status_code == 200
assert res.json[0]['id'] == 1
assert res.json[0]['name'] == "default"
... |
'''
Configures logger
'''
import logging
import os
# Delete previous debug log
if os.path.exists("debug.log"):
os.remove("debug.log")
# Initialize logger
FORMAT = '[%(levelname)s] - %(asctime)s: %(message)s'
logging.basicConfig(handlers=[logging.FileHandler(filename='debug.log', encoding='utf-8', mode='a+')],
... |
__author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS
# Modules
import matplotlib.pyplot as plt
# RiBuild Modules
from delphin_6_automation.database_interactions import mongo_setup
fro... |
import os
import warnings
import numpy as np
import pandas as pd
import uncertainties as un
import uncertainties.unumpy as unp
from matplotlib import pyplot as plt
from matplotlib import widgets
from skimage import io
from skimage.filters import sobel_v
from ...dir import d_drive, convert_dir_to_local
from ...uncerta... |
# Copyright (c) 2021 Princeton University
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import unittest
sys.path.insert(1, '../..')
from synthetic_workload_invoker.EventGenerator import *
class TestEventGenerator(unittest.TestC... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
class Solution:
def canPlaceFlowers(self, pos, n):
pos = [0] + pos + [0]
for i in range(1, len(pos)-1):
if n == 0: return True
if not (pos[i] or pos[i-1] or pos[i+1]):
pos[i] = 1
n -= 1
return n == 0
|
from devito import Eq, Operator, TimeFunction, left, right, staggered_diff
from examples.seismic import PointSource, Receiver
def ForwardOperator(model, source, receiver, space_order=4,
save=False, **kwargs):
"""
Constructor method for the forward modelling operator in an elastic media
... |
#####
# MySQL 5.5.45 (64bit) Local Credentials Disclosure
# Tested on Windows Windows Server 2012 R2 64bit, English
# Vendor Homepage @ https://www.mysql.com
# Date 05/09/2016
# Bug Discovered by Yakir Wizman (https://www.linkedin.com/in/yakirwizman)
#
# http://www.black-rose.ml
# Source Code for the executable... |
import os
import re
import sys
import json
import socket
import sqlite3
import logging
import datetime
import telegram
from time import sleep
from src.chrono import Chrono
from src.command import Task
from src.command import Command
from src.utils import get_api_token
from src.simple_parser import Parser
... |
#from django.forms import ModelForm, fields
from django import forms
from person.models import ImapServer, SmtpServer
class ImapServerForm(forms.ModelForm):
class Meta:
model = ImapServer
widgets = {
'passwd': forms.PasswordInput(),
}
class SmtpServerForm(forms.ModelForm):
... |
import click
from mysocketctl.utils import *
@click.group()
def socket():
"""Manage your global sockets"""
pass
def get_sockets(authorization_header):
api_answer = requests.get(api_url + "connect", headers=authorization_header)
validate_response(api_answer)
return api_answer.json()
def new_so... |
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .models import Project, Risk
from .serializers import (ProjectSerializer,
ProjectSerializerForUpdateReque... |
import urllib.request
import json
class ab_User():
def __init__(self):
self.appId = 'wxff3cfebbdcbcd135'
self.appScrect = 'b9774614f15c56e6e42884ff84ee5168'
def getOpenId(self, code):
getUrl = ' https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=au... |
"""
498. Diagonal Traverse
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Note:
The total number of elements of the given matrix will no... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
def evaluate(model, data_loader, metrics, device):
if model.training:
model.eval()
summary = {metric: 0 for metric in metrics}
for step, mb in tqdm(enumerate(data_loader), desc='steps', total=len(data_loader... |
import pytest
from cognigraph.nodes.processors import Beamformer
from cognigraph.nodes.sources import FileSource
from cognigraph.nodes.tests.prepare_tests_data import (info, # noqa
fwd_model_path,
data_path)
i... |
from pathlib import Path
import pytest
import pybmoore
@pytest.mark.parametrize(
"filename,terms",
[
(
"tests/data/br_constitution.txt",
["Deus", "Brasil"],
),
(
"tests/data/br_constitution.txt",
["Supremo Tribunal Federal", "Emenda Con... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Unit tests about articles' API"""
from logging import DEBUG
import pytest
from marucat_app import create_app
@pytest.fixture
def client():
app = create_app(level=DEBUG, db='test')
app.testing = True
return app.test_client()
def test_get_list(client):... |
# Copyright (c) 2018-2021, Texas Instruments
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of condition... |
"""
@author: David Lei
@since: 20/10/2017
Given two sorted lists and return a list of their intersection with no
duplicates with O(1) space and O(n) run time
For example:
A[2,3,3,4,6,6,8] B[3,3,6,7,9]
should return [3, 6]
Approach:
So since they are sorted we can have pointers i looking at array a and j looking... |
from dataclasses import astuple
import agent
import numpy as np
import torch
import torch.nn as nn
from agent import NNBase
from gym import Space
from gym.spaces import Box, Dict, Discrete, MultiDiscrete
from my.env import Obs
from transformers import CLIPModel
from utils import init
def get_size(space: Space):
... |
import argparse
import os
import sys
import zipfile
def parse_args(args_list):
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='install cudnn')
parser.add_argument('zipfile', help='downloaded cudnn zip file')
args = parser.parse_args(args_list)
return args
def main(args_... |
"""Configuring Django Mutadi app for Heroku"""
import django_heroku
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from .base import *
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = False
ALLOWED_HOSTS = [os.environ["DJANGO_ALLOWED_HOSTS"]]
CSRF_COOKIE_SECURE = True
SESSION_CO... |
import os
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.33.0"
class LibBasisUniversalConan(ConanFile):
name = "libbasisu"
description = "Basis Universal Supercompressed GPU Texture Codec"
homepage = "https://github.com/Binomia... |
from core import MLPActorCritic
import numpy as np
import torch
from torch.distributions import Normal
import torch.nn as nn
from torch.nn.modules import activation
from torch.nn import MSELoss
from torch.optim import Adam
import gym
import math
from skimage.transform import resize
from copy import deepcopy
# Bipedal... |
from django.conf import settings
from . import models
def init_paging_details(page_number):
page_size = settings.PAGE_SIZE
start = (page_number - 1) * page_size
return models.PagingDetails(
page_number=page_number,
start_record=start,
end_record=start + page_size,
prev_pa... |
"""
Use of this source code is governed by the MIT license found in the LICENSE file.
Socket connection
"""
import time
import threading
import logging
from queue import Queue
import socket
from plugwise.constants import SLEEP_TIME
from plugwise.connections.connection import StickConnection
from plugwise.message impor... |
import requests
url = "https://giftcards.reloadly.com/reports/transactions?startDate=2021-06-01 00:00:00&endDate=2021-06-18 23:17:02"
payload={}
headers = {
'Authorization': 'Bearer eyJraXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json',
'Accept': 'application/com.reloadly.giftcards-v1+json'
}... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Uses th... |
#! /usr/bin/env python
# XXX origin and center are incorrect
import nmrglue as ng
# read in the file
dic,data = ng.pipe.read("../common_data/2d_pipe_tppi/test.fid")
# process the direct dimension
dic,data = ng.pipe_proc.sp(dic,data,off=0.35,end=0.98,pow=2,c=1.0)
dic,data = ng.pipe_proc.zf(dic,data,auto=True)
dic,dat... |
from django.db import models
from appregister.base import Registry
class Question(models.Model):
pass
class BooleanQuestion(Question):
pass
class MultipleChoiceQuestion(Question):
pass
# Setting up the registry.
class QuestionRegistry(Registry):
base = Question
discovermodule = 'questions... |
# -*- coding: Utf-8 -*
import os
import sys
from typing import Callable
def __set_constant_path(path_exists: Callable[[str], bool], path: str, *paths: str, special_msg=None, raise_error=True) -> str:
all_path = os.path.join(path, *paths)
if not os.path.isabs(all_path):
all_path = os.path.join(os.path.... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class PropertyScrapperItem(scrapy.Item):
address = scrapy.Field()
suburb = scrapy.Field()
description = scrapy.Field()
sold_date = scrapy... |
# já colocando .strip() para tirar os espaços do início e fim da string e o upper() para maiúscula
frase = str(input('Digite a frase: ')).strip().upper()
# para separar as palavras como em uma lista
palavras = frase.split()
# aqui abaixo a função join aglutina as palavras da lista
juntar_palavras = ''.join(palavras)... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from parlai.core.torch_agent import TorchAgent, Output
from torch import optim
import global_variables as gl
class BagOfNGrams(nn.Module):
def init_layers(self):
for l in self.layers:
if getattr(l, 'weight', None) is not None:
... |
import zipfile
import os
#import PIL
from lxml import etree as ET
__author__ = 'pierre'
ns = {'kra': 'http://www.calligra.org/DTD/krita'}
class Kra(object):
maindoc_xml = None
merged_image = None
basename = None
icc = None
icc_path = None
kra_name = None
def __init__(self, krafile):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Bertrand256
# Created on: 2017-03
from __future__ import annotations
import functools
import hashlib
import re
import urllib, urllib.request, urllib.parse
from functools import partial
from io import BytesIO
from typing import Optional, Tuple, List, ByteString, D... |
import argparse
import re
import numpy as np
from operator import add
from pyspark import SparkContext
from pyspark.ml.feature import NGram
from pyspark.sql import SparkSession
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import StringIndexer
from pyspark.ml.classification import RandomForestClassifi... |
import os
import argparse
import library.utils as utils
import library.migrationlogger as m_logger
import library.localstore as store
import library.clients.entityclient as ec
import library.status.dashboard_status as ds
log = m_logger.get_logger(os.path.basename(__file__))
def print_args(args):
#log.info("Usin... |
import setuptools
from pyncli import __version__ as pyncli_version
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyncli",
version=pyncli_version,
author="Evgeniy Semenov",
author_email="edelwi@yandex.ru",
description="Command Line Interface for NextClo... |
"""
Function Group Utilities
========================
"""
from __future__ import annotations
from collections import abc
from ...atom import Atom
__all__ = (
'get_atom_map',
)
def get_atom_map(
id_map: dict[int, int],
atoms: abc.Iterable[Atom],
) -> dict[int, Atom]:
"""
Get an atom map from ... |
import pandas as pd
import sys
import os
import sklearn.model_selection
# THis helper script was written to reformat the covid protein receptor
# docking dataframes produced by A. Partin into input files for the
# smiles_regress_transformer.py code that Rick produced.
data_path = sys.argv[1]
base = os.path.basename(d... |
import torch
from torch import nn, optim
from torch.utils.data import DataLoader, sampler
from tqdm import tqdm
from argument import get_args
from backbone import vovnet39, vovnet57, resnet50, resnet101
from utils.dataset import COCODataset, collate_fn
from model import ATSS,Efficientnet_Bifpn_ATSS
from utils import t... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from orc8r.protos import streamer_pb2 as orc8r_dot_protos_dot_streamer__pb2
class StreamerStub(object):
"""Streamer provides a pipeline for the cloud to pu... |
# Desafio044:
++++
valor_da_compra = float(input('valor da compra? '))
forma_de_pg = input('Qual a forma de pagamento? \033[1:31mD\033[m para dinheiro ou \033[1:31mC\033[m para cartão ').strip()
if forma_de_pg == 'D'or 'd':
print(f'Pagamento a vista em dinhero voce tem desconto de 10% e o valor final sera de {(valor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/4 22:48
# @Author : LoRexxar
# @File : bet2loss_abi.py
# @Contact : lorexxar@gmail.com
Bet2lossABI = [
{
"anonymous": False,
"inputs": [
{
"indexed": False,
"name": "b64email",
... |
import time
import glob
import os
import types
import socket
def read_paths ():
fulllist = []
for file in glob.glob("*96*messages"):
print 'reading ' + file
fullfile = (open(file).read().splitlines())
for x in fullfile:
if 'RPD_MPLS_LSP_CHANGE'in x and 'Sep 1... |
"""
For documentation on this script, run with -h flag
"""
import sys
import os
import time
import logging
import openpyxl
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
from datetime import datetime as dt
class ArcPyLogHandler(logging.StreamHandler):
"""
Custom logging class ... |
import torch.nn as nn
import torch.optim as optim
from torchvision.transforms import ToTensor
from cifar_pipeline.dataset import CIFARImagesDataset, CIFARTargetsDataset
from pipeline.config_base import ConfigBase
from pipeline.datasets.base import DatasetWithPostprocessingFunc, DatasetComposer, OneHotTargetsDataset
fr... |
from .allreduce import allreduce_tree
from .broadcast import broadcast_one_to_all, broadcast_ring, broadcast_spreading
from .neighbor_allreduce import neighbor_allreduce
|
from __future__ import division, print_function
import os
import click
desikan_label_ids = {
"left_thalamus": 10,
"right_thalamus": 49,
"left_caudate": 11,
"right_caudate": 50,
"left_putamen": 12,
"right_putamen": 51,
"left_pallidum": 13,
"right_pallidum": 52,
"left_hippocampus": 17... |
import pandas as pd
import os
import sys
from typing import List
from utilies import merge_features
def make_merged_data(
raw_path: str, processed_path: str,data: str, build_files: bool = True
) -> pd.DataFrame:
if data not in ['train', 'test']:
raise ValueError('Argument \'data\' must be one of \'t... |
from django import forms
from django.forms.models import inlineformset_factory
from .models import Choice, Question
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ('text', )
ChoiceFormSet = inlineformset_factory(
parent_model=Question, model=Choice, form=Question... |
from azure_lightning_flask.application import create_app
def main():
app = create_app()
app.run()
if __name__ == "__main__":
main() |
from shortcuts.actions.base import BaseAction, FloatField
class NumberAction(BaseAction):
itype = 'is.workflow.actions.number'
keyword = 'number'
number = FloatField('WFNumberActionNumber')
|
from rest_framework import serializers, pagination
from .models import Catalog, Element
class CatalogSerializer(serializers.ModelSerializer):
"""This class is used to manage how we pass Catalog to the client app."""
class Meta:
model = Catalog
fields = '__all__'
class ElementSerializer(seri... |
"""Content discriminator for DRIT"""
from torch.nn import Conv2d, Sequential, InstanceNorm2d, Identity, \
ReflectionPad2d, LeakyReLU
from ..base_module import BaseModule
from ..blocks import ConvBlock
class ContentDiscriminator(BaseModule):
"""Content discriminator"""
def __init__(self, **kwargs):
... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class SSDHead(nn.Module):
def __init__(self,
num_classes=81,
in_channels=[256,256,256,256,256],
aspect_ratios=([2], [2, 3], [2, 3], [2, 3], [2], [2])):
super(SSDHead, ... |
import os
def include_code(filename, lines="", mark_disjoint="", language="",
start_with=None, end_before=None):
# Note: this filter hackily assumes content/ since I don't want to figure
# out how to actually pull values from the Dactyl config file from this
# point in the code.
with ... |
from neo.Core.TX.Transaction import Transaction, TransactionType
from neocore.Cryptography.ECCurve import ECDSA
class EnrollmentTransaction(Transaction):
PublicKey = None
_script_hash = None
def __init__(self, *args, **kwargs):
"""
Create an instance.
Args:
*args:
... |
from mapping.tridiag.get_tridiag_solver import get_tridiag, get_tridiag_from_diag, get_tridiag_from_special_sparse
|
import sys
sys.path.append("..") # to import higher directory.
from Queues.queue import Queue
class Node(object):
def __init__(self, value):
self.info = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
de... |
import numpy as np
# generate artificial data
nr_of_bb = 4000
# minimal and maximal position and dimension of rectangles
min_xywh = [.0,.0,.2,.2]
max_xywh = [1.,1.,1.,1.]
# four lists of rectangles:\
# - bbs1 and bbs2 are used to generate examples R(x,y) with x in bbs1 and y in bbs2;
# - bbs12 = bbs1 + bbs2
# - bbst... |
filename='update.test'
with open(filename) as f:
conf=[]
for line in f:
line=line.strip().split(',')
conf.append(line)
def update_data(d='d'):
if 'test' in conf:
print 'updated!!'
else:
print 'notupdate'
|
from __future__ import division
from fractions import Fraction
from vector import Vector
import unittest
def gcd(a, b):
while b:
a, b = b, a%b
return a
class IntegerLattice:
def __init__(s, *args):
if len(args) == 1 and hasattr(args[0], '__iter__'):
s.basis = list(args[0])
else:
s.basis ... |
"""
Synthetic example with high concurrency. Used primarily to stress test the
library.
"""
import argparse
import contextlib
import sys
import time
import threading
import random
# Comment out to test against the published copy
import os
sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)) + '/../..')
impo... |
"""
3,猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
"""
def find_x(day):
x = 3*(2**(day-1))-2
return x
print(find_x(10))
# a10=1
# a9=(a10+1)*2
# a8=(a9+1)*2
# ....
# 数学思想,正常人的思想
# res = 1
# for i in range(9):
# res += 1
# res ... |
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Deque, Optional
@dataclass
class Node:
data: int
left: Optional[Node] = None
right: Optional[Node] = None
def left_tree_value_bfs(root: Node):
resu... |
"""
Batch process Windows 10 and 7/8 icon file colorings
Python 3.x
"""
import io
import os
import sys
import struct
import statistics
from pprint import pprint
from colorsys import rgb_to_hls, hls_to_rgb
from PIL import Image # pip3 install pillow
"""
Windows10.ico:
Values: 25,559
Hue Avg: 45.228,... |
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from manager import models as pmod
from . import templater
from django.conf import settings
import decimal, datetime
# This page allows an employee to make or edit a store
def proces... |
import json
from nativeconfig.exceptions import DeserializationError, ValidationError, InitializationError
from nativeconfig.options.base_option import BaseOption
class DictOption(BaseOption):
"""
DictOption represents Python dict in config. DictOption can contain other Options as values of dict.
"""
... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
MagicMock,... |
from dataclasses import dataclass
from bindings.gmd.md_geometric_objects_type import MdGeometricObjectsType
__NAMESPACE__ = "http://www.isotc211.org/2005/gmd"
@dataclass
class MdGeometricObjects(MdGeometricObjectsType):
class Meta:
name = "MD_GeometricObjects"
namespace = "http://www.isotc211.org... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import math
from collections import OrderedDict
from ..util import import_
import numpy as np
from ..symbolic import SymbolicSys, TransformedSys, symmetricsys
sp = import_('sympy')
ys = [
np.array([0.43976714474700634, 0.... |
from __future__ import unicode_literals
import yaml
from pathlib import Path
import os
from prompt_toolkit import prompt
import pandas as pd
from src.pipeline_components.tile_creator import TileCreator
from src.pipeline_components.tile_downloader import TileDownloader
from src.pipeline_components.tile_processor import... |
import os
#get pure terachem gradients for comparison
pdbdir = "/home/xuyanting/qr-tests-p1/01_finalised"
coords="/home/xuyanting/qr-tests-p1/01_finalised/"
work_dir ="/home/xuyanting/sp/"
pdbs =[]
for pdb_file in os.listdir(pdbdir):
# pdbs.append(os.path.join(pdbdir,pdb_file))
pdbs.append(pdb_file[:-4])
template ... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def checkTen(n, f):
flag = f
temp = n
while (n is not None):
n.val += flag
if n.val >= 10:
n.val -= 10
flag = 1
else:
flag = 0
temp = n
... |
#!/usr/bin/env python3
from zorrom import solver
from zorrom.util import add_bool_arg
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description='Guess mask ROM layout based on constraints')
parser.add_argument(
'--bytes',
required=True,
help=... |
#
# _author_ = Mahendran P <Mahendran_P@Dell.com>
#
# Copyright (c) 2021 Dell EMC 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... |
def pythonstuff_main():
return 'This is just to initialize the project. I\ll kill it later'
|
from django.conf import settings
from web3 import Web3, HTTPProvider
from web3.middleware import geth_poa_middleware
def get_w3():
w3 = Web3(HTTPProvider(settings.NODE_URL))
w3.middleware_stack.inject(geth_poa_middleware, layer=0)
return w3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.