content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- import scrapy class ProductsSpider(scrapy.Spider): name = 'products' def start_requests(self): yield scrapy.Request( url="https://betalist.com/markets", callback=self.category_page ) def category_page(self, response): categories = r...
from setuptools import setup, find_packages import re def get_property(prop, project): result = re.search(r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop), open(project + '/__init__.py').read()) return result.group(1) setup( name='waldorf', version=get_property('__version__', 'wal...
from .parameterized_spline import ParameterizedSpline
from rest_framework import status from .decorators import action def patch_data(data, instance): if hasattr(instance, 'pk'): data['__pk'] = str(instance.pk) if hasattr(instance, 'uuid'): data['__uuid'] = str(instance.uuid) if hasattr(instance, 'id'): data['__id'] = str(instance...
from configparser import ConfigParser, NoSectionError, NoOptionError class BotPreferences(object): """ The BotPreferences class manages access to the config.ini file. Plugins can access these settings, but new settings have to be added to the file manually. """ # Prefix for commands, this can be ...
import time from fixture.additional import MH as add from model.group import Group class GH: def __init__(self, app): self.app = app def delete(self): self.delete_by_index(0) def delete_by_index(self, index): wd = self.app.wd self.open_group_page() wd.find_element...
from __future__ import print_function import os import sys import subprocess as sp import pytest import yaml import tempfile import requests import argparse import re import time import json import shutil from copy import deepcopy from argparse import Namespace from argparse import ArgumentParser import glob import con...
# -*- coding: UTF-8 -*- import pygame from pygame.locals import * import sys import random import time import sys path = './game/' sys.path.append(path) path = './game/' class DoodleJump: def __init__(self, FPS=30000): self.screen = pygame.display.set_mode((800, 800)) self.green = pygame.image.load...
# Copyright Platform9 Systems Inc. 2016 from sqlalchemy import MetaData, String, Table def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) table = Table('tenant_lease', meta, autoload=True) tenant_leases = list(table.select().execute()) for tenant_lease in tenant_leases: old_val ...
#!/usr/bin/env python # -- coding: utf-8 -- from app import app from sys import argv port = 8000 debug = True if len(argv) > 1 and argv[1]: port = argv[1] if len(argv) > 2 and argv[2]: if argv[2] != 'true': debug = False pass if __name__ == '__main__': __import__('routers') app.run(h...
from labeling import Encoding #import conll18_ud_eval as conll18 from argparse import ArgumentParser import subprocess as sp def convertToDependency(multitag, multitask_char): multitag_dep = multitag.split(multitask_char) # print(multitag_dep) #for 6 task if len(multitag_dep)>3: return multita...
from collections import defaultdict N, K = map(int, input().split()) counts = defaultdict(int) c = list(map(int, input().split())) count = 0 for i in range(K): counts[c[i]] += 1 if counts[c[i]] == 1: count += 1 answer = count for i in range(K, N): counts[c[i - K]] -= 1 if counts[c[i - K]] =...
from config import * def get_wordarray(input): params = {'string': input, 'language': language} response = requests.get(request_path, params, headers={'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'}) # convert text respon...
#!/usr/bin/env python from cwltool.context import LoadingContext from cwltool.workflow import default_make_tool from cwltool.resolver import tool_resolver from cwltool.load_tool import load_tool import json import sys import ruamel if len(sys.argv) < 2: print('Usage:', sys.argv[0], '<CWL URL>') exit(1) url = sy...
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal...
import numpy as np import cv2 import sys img = cv2.imread(sys.argv[1]) height, width, channels = img.shape multiplicatorDX = 1 multiplicatorDY = 1 PositionX = 0 PositionY = 0 while(1): crop_img = img[y:y+h, x:x+w]
from matplotlib.patches import Patch def make_legend(names, colors): """ Make a list of legend handles and colours :param names: list of names :param colors: list of colors :return: list of matplotlib.patches.Patch objects for legend """ legend_elements = [] for idx, name in enumerate...
import logging import re from typing import Any, Dict, Tuple, Union import requests from zulip_bots.lib import BotHandler class GithubHandler: """ This bot provides details on github issues and pull requests when they're referenced in the chat. """ GITHUB_ISSUE_URL_TEMPLATE = "https://api.githu...
import os import subprocess import errno import time import sys PIPE = subprocess.PIPE from vyperlogix import misc from vyperlogix.misc import _utils from vyperlogix.classes.CooperativeClass import Cooperative __copyright__ = """\ (c). Copyright 2008-2013, Vyper Logix Corp., All Rights Reserved. Pub...
import importlib import math from abc import ABC # Base exception EncoderException = type('EncoderException', (BaseException,), {}) # User-related exceptions EncoderConfigException = type('EncoderConfigException', (EncoderException,), {}) EncoderRuntimeException = type('EncoderRuntimeException', (EncoderException,), ...
""" Forms for manipulating tags """ from django import forms from tags.models import Tag, colours_enum class ColourSelect(forms.widgets.ChoiceWidget): input_type = "input" template_name = "tags/forms/colourSelect.html" option_template_name = "tags/forms/colourSelectOption.html" checked_attribute = {"d...
import mlflow from io import StringIO from fastapi import Request, Response from mlflow.exceptions import MlflowException from mlflow.pyfunc.scoring_server import ( CONTENT_TYPES, CONTENT_TYPE_CSV, CONTENT_TYPE_JSON, CONTENT_TYPE_JSON_SPLIT_ORIENTED, CONTENT_TYPE_JSON_RECORDS_ORIENTED, CONTENT...
# -*- coding: utf-8 -*- """ lantz.feat ~~~~~~~~~~ Implements Feat and DictFeat property-like classes with data handling, logging, timing, cache and notification. :copyright: 2012 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import time from...
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2021 Scipp contributors (https://github.com/scipp) # @author Neil Vaytet from .model import PlotModel from .tools import to_bin_centers, fix_empty_range, to_dict from .._scipp import core as sc import numpy as np class PlotModel3d(PlotModel): """ Model ...
import os import shutil import sys import time import zipfile from urllib import request import pandas as pd from tklearn.utils._progress import progress __all__ = [ 'pprint', 'download', 'dict_normalize', 'progress', ] def dict_normalize(data): """Normalize semi-structured dict data into a fla...
import os import sys from transifex.common.console import Color, pluralized, prompt from transifex.native.tools.migrations.mark import ( MarkLowConfidenceFilesPolicy, MarkLowConfidenceStringsPolicy, NoopMarkPolicy, create_mark_policy) from transifex.native.tools.migrations.models import Confidence from transif...
from unicornrainbow import UnicornRainbow from codingtrain import CodingTrain trains = [] NO_TRAINS = 2 def setup(): global unicorn, trains size(720, 360) this.surface.setTitle("Coding Train Unicorn Rainbow Stage 2") unicorn = UnicornRainbow() for i in range(NO_TRAINS): train = CodingTrain...
from os import path from threading import Thread from time import sleep from mido import MidiFile import argparse import keyboard as kbd from utils import find_best_shift, midi_play_filter octave_interval = 12 c3_pitch = 48 c4_pitch = 60 c5_pitch = 72 b5_pitch = 83 keytable = "z?x?cv?b?n?m" + "a?s?df?g?h?j" + "q?w?er?...
import unittest from linked_list_sort_nodes.solution import Solution class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class SolutionTest(unittest.TestCase): def list_from_array(self, vals: []) -> ListNode: next = None for i in range(len...
import numbers import mxnet as mx from PIL import Image from mxnet import recordio path_imgidx = "/home/lijc08/datasets/glintasia/faces_glintasia/train.idx" path_imgrec = "/home/lijc08/datasets/glintasia/faces_glintasia/train.rec" # path_imgidx = "/home/lijc08/datasets/glint/faces_glint/train.idx" # path_imgrec = "/h...
# Generated by Django 3.0.7 on 2020-07-01 12:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ...
import random from fastapi import FastAPI from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/public", StaticFiles(directory="public"), name="public") with open("theory.md", "r", encoding="utf-8") as f: lines = f.readlines() quiz = {} for i in range...
from decimal import Decimal as D, Decimal from django.conf import settings from django.utils.translation import ugettext as _ from django.db import models from django.db.models.signals import pre_save, post_save, post_delete from django_countries.fields import CountryField from bluebottle.payments.exception import Pay...
''' https://www.codeeval.com/open_challenges/30/ ''' import sys def main(): with open(sys.argv[1],'r') as word_file: for line in word_file.readlines(): lists = line.rstrip().split(';') first, second = [l.split(',') for l in lists] intersection = list(set(first).intersection(set(second))) intersection.so...
from .change_password import change_password # noqa from .login import login, logout # noqa from .profile import profile # noqa from .register import register, verify_registration # noqa from .register_email import register_email, verify_email # noqa from .reset_password import reset_password, send_reset_password_...
import sys from typing import Any, Optional, Tuple if sys.version_info >= (3, 8): from typing import Protocol, runtime_checkable else: from typing_extensions import Protocol, runtime_checkable @runtime_checkable class DType(Protocol): itemsize: int name: str kind: str @runtime_checkable class F...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ rpvizTest (c) University of Manchester 2019 rpvizTest is licensed under the MIT License. To view a copy of this license, visit <http://opensource.org/licenses/MIT/>. Created on Wed May 1 09:54:39 2019 @author: Pablo Carbonell, SYNBIOCHEM @description: Test the rp...
import pygame class Font(): def __init__(self, name, size): self._name = name self._size = size self._font = pygame.font.SysFont(name, size) #TODO Add support for font files def getFontName(self): return self._name def getFontSize(self): return self._siz...
''' 04 - Changing the style of scatter plot points Let's continue exploring Seaborn's mpg dataset by looking at the relationship between how fast a car can accelerate ("acceleration") and its fuel efficiency ("mpg"). Do these properties vary by country of origin ("origin")? Note that the "acceleration" variable is...
# generated by update to not change manually import dataclasses as dt import typing as t from bungieapi.json import to_json @dt.dataclass(frozen=True) class BungieFriendListClientResponse: detailed_error_trace: str error_code: "PlatformErrorCodes" error_status: str message: str message_data: t.Ma...
import cv2 import converter # Import picture & create HSI copy using algorithm img = cv2.imread('sourceImg.jpg', 1) hsi = converter.RGB_TO_HSI(img) # Display HSV Image cv2.imshow('HSI Image', hsi) # The three value channels cv2.imshow('H Channel', hsi[:, :, 0]) cv2.imshow('S Channel', hsi[:, :, 1]) cv2.imshow('I Cha...
# _*_ coding: utf-8 -*- try: import cid except ImportError: cid = None import io import pytest import conftest TEST1_FILEPATH = conftest.TEST_DIR / "fake_dir" / "fsdfgh" TEST1_CID_STR = "QmPevo2B1pwvDyuZyJbWVfhwkaGPee3f1kX36wFmqx1yna" TEST1_SIZE = 8 TEST2_CONTENT = b"Hello World!" TEST2_CID_STR = "zb2rhfE3SX3...
import cv2 import math from sklearn import neighbors import os import os.path import pickle from PIL import Image, ImageDraw import face_recognition from face_recognition.face_recognition_cli import image_files_in_folder import numpy as np from datetime import datetime import attendance as attend import exc...
# 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 # distributed under the L...
import tensorflow as tf import keras.backend as K def get_pos_neg_cross(y_true,y_pred): cat=tf.shape(y_true)[2] zero=tf.constant(0, dtype=tf.float32) ## reshape to 1D vectors the positive part yt=tf.reshape(y_true,[-1,cat]) yp=tf.reshape(y_pred,[-1,cat]) ## Count positives and define neg as ...
from ELDAmwl.backscatter.raman.params import RamanBscParams from ELDAmwl.extinction.params import ExtinctionParams from ELDAmwl.products import ProductParams from ELDAmwl.utils.constants import ERROR_METHODS class LidarRatioParams(ProductParams): def __init__(self): super(LidarRatioParams, self).__init__...
import tabula import os # uncomment if you want to pass pdf file from command line arguments # import sys # read PDF file # uncomment if you want to pass pdf file from command line arguments # tables = tabula.read_pdf(sys.argv[1], pages="all") tables = tabula.read_pdf("1710.05006.pdf", pages="all") # save them in a f...
# imports # ----------------------------------------------------------------------------- # pip-installable imports from __future__ import print_function, division import luigi import cPickle as pickle from math import ceil, floor import numpy as np import scipy as sp import os import logging import copy import datetim...
# Copyright 2019 Xilinx Inc. # # 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, ...
name = input("masukkan nama pembeli = ") alamat= input("Alamat = ") NoTelp = input("No Telp = ") print("\n") print("=================INFORMASI HARGA MOBIL DEALER JAYA ABADI===============") print("Pilih Jenis Mobil :") print("\t 1.Daihatsu ") print("\t 2.Honda ") print("\t 3.Toyota ") print("") pilihan = int(input("Pil...
# @Time : 2020/11/22 # @Author : Chenzhan Shang # @Email : czshang@outlook.com # UPDATE: # @Time : 2020/12/16 # @Author : Xiaolei Wang # @Email : wxl1999@foxmail.com import re from copy import copy import torch from tqdm import tqdm from crslab.data.dataloader.base import BaseDataLoader from crslab.data.datal...
import genetic class EightQueens(object): def test(self,size): geneset = [i for i in range(size)] def fnDisplay(candidate): display(candidate, size) def fnGetFitness(genes): return get_fitness(genes, size) optimalFitness = Fitness(0) best,mutations = genetic.get_best(fnGetFitness, 2*size, optima...
#!/usr/bin/env python # encoding=utf-8 from __future__ import print_function import os import sys try: from setuptools import setup except ImportError: print("This package requires 'setuptools' to be installed.") sys.exit(1) here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here...
# Copyright 2017-2020 Palantir Technologies, Inc. # Copyright 2021- Python Language Server Contributors. import logging import os from yapf.yapflib import file_resources from yapf.yapflib.yapf_api import FormatCode from pylsp import hookimpl from pylsp._utils import get_eol_chars log = logging.getLogger(__name__) ...
""" Some utility functions Author: Gao Shuhua Date: 2019/10/25 """ from typing import Tuple, List def read_network(file: str) -> Tuple[int, int, List[int]]: """ Read a Boolean network from a text file: Line 1: number of state variables Line 2: number of control inputs Line 3: transitio...
from pytest import fixture import pandas as pd import numpy as np import os THIS_DIR = os.path.dirname(os.path.abspath(__file__)) @fixture def get_cleaned_df(): matches_df = pd.read_csv(os.path.join(THIS_DIR, 'test_matches_df_pipeline.csv')) rank_df = pd.read_csv(os.pa...
#!/usr/bin/env python3 # -*- coding: iso-8859-1 -*- ############################################################################### # # ModuleLoader is the heart of Pythomnic3k. An instance of ModuleLoader is # accessible from all modules as pmnc and is essentialy the running cage itself. # # Pythomnic3k project # (c) ...
import numpy import torch import random from tqdm import * from skimage.external import tifffile import tools # Ensuring that we always start from the same random state (for reproductibility) random.seed(42) numpy.random.seed(42) # Sets default value for the channels of the images ACTIN, AXON, DENDRITE = 0, 1, 2 ...
from blessings import Terminal term = Terminal()
from urlparse import urlparse import os from flask import Blueprint, request, redirect, session from flask_login import logout_user from onelogin.saml2.auth import OneLogin_Saml2_Auth from onelogin.saml2.utils import OneLogin_Saml2_Utils from web.views.helpers import prevent_csrf from web.auth.saml.user_management im...
from uuid import uuid4 from django.conf import settings from django.db import models class CheckIn(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) bottle = models.ForeignKey("spirits.Bottle", on_delete=models.CASCADE) location = models.ForeignKey("world.Location", nu...
# -*- coding: utf-8 -*- import disnake from disnake.ext import commands from pypoca.config import COLOR, URLS from pypoca.database import Server from pypoca.ext import ALL, DEFAULT, Choice, Option class General(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @commands.slash_comm...
# -*- coding: utf-8 -*- # @Time : 2019-08-20 13:32 # @Author : Xichagui # @Site : # @File : __init__.py.py # @Software: PyCharm
""" The script moves the system date forward and the time backward to provoke backup start by schedule and speed up testing. For example, we have a backup plan which starts at 10:00:00 PM every day. To speed up testing, we need to move system date one day forward and the time backward to 09:59:00 PM after each backup s...
from django.apps import AppConfig class ThemingConfig(AppConfig): name = 'admin_tools.theming' verbose_name = 'Theming'
#!/usr/bin/env python # (C) Copyright IBM Corporation 2004, 2005 # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # ...
import pandas as pd import numpy as np from pymongo import MongoClient import json #37.168 filename = 'Journals.txt' key_journal_id = 'JournalId' key_issn = 'Issn' header = [key_journal_id,'Rank','NormalizedName','DisplayName',key_issn,'Publisher','Webpage','PaperCount','CitationCount','CreatedDate'] client = Mong...
import zconfig as config import logging import os import sys import traceback # FIXME: move browser creation somewhere else from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary MARKER = "="*5 class TestCaseMetaClass2(type): def __new__(cls,name,bases,dct): ...
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from parts.app.accounts import forms # Register model from parts.app.accounts.models import CustomUser, ProfileUser # change this to avoid direct calling from main config # Config settings ...
#! /usr/bin/python from gtk.gdk import * w=window_foreign_new((get_default_root_window().property_get("_NET_ACTIVE_WINDOW")[2][0])) state = w.property_get("_NET_WM_STATE")[2] maximized='_NET_WM_STATE_MAXIMIZED_HORZ' in state and '_NET_WM_STATE_MAXIMIZED_VERT' in state if maximized: w.unmaximize() if w.get_decorations(...
# 02-create-compute.py from azureml.core import Workspace from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException ws = Workspace.from_config() # Choose a name for your CPU cluster cpu_cluster_name = "cpu-cluster" # Verify that cluster does n...
#!/usr/bin/env python # -*- coding:utf-8 -*- #订阅 from RedisHelper import RedisHelper obj = RedisHelper() redis_sub = obj.subscribe()#调用订阅方法 while True: msg= redis_sub.parse_response() print (msg)
"""Representation of measurements taken by bm257s multimeter""" # pylint: disable=R0903 # Remove this once usage becomes clearer class Measurement: """Generic measurement representation :param prefix: Metric prefix of measurement :type prefix: str """ PREFIX_NONE = "" PREFIX_KILO = "k" P...
class EasyTraxParse: """Parses text files generated by the DOS program FirstChoice, prepares data for conversion to WTX format. Final reports can be generated by the current MB Labs LIMS system in text format. These files contain data displayed vertically (analytes going down the page, samples across), an...
#!/usr/licensed/anaconda3/2020.11/bin/python base = "/home/jdh4/bin/gpus" import sys sys.path = list(filter(lambda p: p.startswith("/usr"), sys.path)) sys.path.append(base) import json import subprocess import pandas as pd from dossier import ldap_plus if 1: rows = [] with open(base + "/utilization.json") as f...
import eel eel.init('web') eel.start('main.html')
import os import json import logging from zipfile import ZipFile from sendzip.taskapp.celery import app from datetime import datetime, timedelta from django.template.context import Context from django.core.mail import EmailMultiAlternatives import requests from urllib.request import urlopen import smtplib, ssl fr...
import re import cssutils import tempfile import fontforge from pyquery import PyQuery as pq FONT_CONTENT_TYPE = ( 'image/svg+xml', 'application/octet-stream', ) CSS_CONTENT_TYPE = ( 'text/css', ) BASE_ASCENT = 896 BASE_DESCENT = 128 def font(filepath): """Try to convert the contents of font file ...
# this menu.py only installs the SetLoop toolset. To remove the SetLoop examples, remove the menu.py in the Examples folder. # get script location (necessary for loading toolsets) dirName = os.path.dirname( os.path.abspath(__file__)).replace('\\', '/') # get node toolbar nodes = nuke.menu('Nodes') # load t...
from app import db # truncate mid.mesh # insert into mid.mesh (select * from legacy.mag_advanced_paper_mesh) class Mesh(db.Model): __table_args__ = {'schema': 'mid'} __tablename__ = "mesh" paper_id = db.Column(db.BigInteger, db.ForeignKey("mid.work.paper_id"), primary_key=True) descriptor_ui = db.Co...
import sys import re from socket import * ip_regexp = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$" port_regexp = "^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$" #A port is a 16-bit unsigned integer r...
import copy import numpy as np import pandas as pd import scipy.sparse as sp from collections import Counter from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import TfidfVectorizer from melusine.utils.transformer_scheduler import TransformerScheduler from melusine.config.con...
#!/usr/bin/env python3 import json import argparse import os import sys import subprocess from check_if_done import check_state_comet import time import shutil from shutil import copy2 from write_submit_script_comet import write_submit_comet import re ''' Submit particle picking job. Inputs: 1. Path to the directory o...
# Lint as: python3 # Copyright 2019 Deepmind Technologies Limited. # # 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 ap...
from opcua.ua import ObjectIds from opcua import Node class Shortcuts(object): """ This object contains Node objects to some commonly used nodes """ def __init__(self, server): self.root = Node(server, ObjectIds.RootFolder) self.objects = Node(server, ObjectIds.ObjectsFolder) s...
"""Example of K-Nearest Neighbors (KNN)""" # Dependencies from sklearn.neighbors import KNeighborsRegressor import numpy as np # Data (House Size (square meters) / House Prices ($)) X = np.array([[35, 30000], [45, 45000], [40, 50000], [35, 35000], [25, 32500], [40, 40000]]) # One-liner KNN = KNeighborsR...
import setuptools """ Install locally: >>> python setup.py install """ with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() def read_requirements(fname): requirements = [] with open(fname, "r") as fh: for line in fh: line = line.strip() if not...
# !/usr/bin/env python # -*-coding:utf-8 -*- # PROJECT : Question-Steo # Time :2020/12/17 22:26 # Warning :The Hard Way Is Easier def output(args): print("[最终结果为]: {}".format(args)) """ 台阶问题: 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 """ """ A: 求多少种可能的题目,一般有递推性质,即 f(n) 和 f(n-1)...f(1)之间有关系 所以,从f(...
def schedule_classes(classes, times): schedule = [] index = 0 while index < len(classes): schedule_classes = classes[index] + ": " + times[index] schedule.append(schedule_classes) index += 1 return schedule classes = ["Algebra", "History", "Biology", "Swimming"] times = ["9a.m...
# -*- coding: utf-8 -*- # This file is part of AYAB. # # AYAB 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 License, or # (at your option) any later version. # # AYAB i...
# 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 w...
import gym import numpy as np import typing as t from gym.spaces import Box from torch import FloatTensor from dataclasses import dataclass from dm_control.locomotion.examples import basic_cmu_2019 @dataclass class MultiObservation: features: FloatTensor frame: FloatTensor class DeepMindWallRunner(gym.Env)...
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-03-20 01:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shakha', '0005_auto_20180317_1907'), ] operations = [ migrations.AlterFiel...
import http.server import socketserver import os from time import sleep from threading import Thread import socket from contextlib import closing import json from random import random from statistics import mean # This script will create and run a server that will randomly timeout. The probability of a timeout is set ...
import os import json if __name__ == '__main__': dataset_name = '/raid5/lzl_data/someting-v2/something-something-v2' # 'jester-v1' with open('%s-labels.json' % dataset_name) as f: data = json.load(f) categories = [] for i, (cat, idx) in enumerate(data.items()): assert i == int...
from django.shortcuts import render, redirect def index(request): """Render the index page.""" return render(request, "treemap/index.html") def data(request): return redirect('/static/data/treemap.csv') # Various rendering ordering options order=[['party', 'state', 'district'], ['state', 'distr...
import sys import os sys.path.insert(1, os.path.join(sys.path[0], '..')) from neural_net import NetFactory from data_source import PreloadSource, DataSetIterator from gradient_descent import StochasticGradientDescent from cost_functions import QuadraticCost, CrossEntropyCost from activation_functions import Rectifier,...
import math as m #shallow B0 = -150.0 #vs 0 from gael B2 = -728.8 #from gael B4 = 343.91 #from gael B6 = - 50.57 #from gael def Bx(x): xx = x/300.0e3 xx2 = xx*xx xx4 = xx2*xx2 xx6 = xx4*xx2 return B0 + B2*xx2 + B4*xx4 + B6*xx6 def By(y,fc,dc,wc): return dc/(1.0+m.exp(-2.0*(y-wc)/fc)) + dc/...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class FilerImageConfig(AppConfig): name = 'cmsplugin_filer_image' verbose_name = _('django filer image')
from .TransformedDataset import TransformedDataset