text
stringlengths
8
6.05M
# coding: utf-8 import numpy as np class Sigmoid(object): @staticmethod def y(z): return 1 / (1 + np.exp(-z)) @staticmethod def dy_dz(y): return y * (1. - y)
from django.conf import settings from django.contrib.auth.models import AbstractUser #importing AbstractUser from django, it's a model. It has defined what it means to be an abstract user. It's a model that comes baked in, and we're going to inherit from that model. from django.db import models class User(AbstractUser...
import csv import cv2 import numpy as np import sklearn default_batch_size = 30 ### Generator and Image Processing def generator(data, batch_size=default_batch_size): path = './data/IMG/' while 1: # Loop forever so the generator never terminates for i in range(0, len(data), batch_size): batch = data[i:i...
import gym from gym import wrappers import qlearning import numpy import matplotlib.pyplot as plt NUM_EPISODES = 2000 N_BINS = [8, 8, 8, 8] MAX_STEPS = 200 FAIL_PENALTY = -100 EPSILON = 0.5 EPSILON_DECAY = 0.99 LEARNING_RATE = 0.05 DISCOUNT_FACTOR = 0.9 RECORD = False MIN_VALUES = [-0.5, -2.0, -0.5, -3.0] MAX_VALUES...
# time complexity O(n) # space complexity O(1) def is_palindrome(input): if input < 0: return False divisor = 1 while(input/divisor >= 10): divisor *= 10 # print("divisor: ", divisor) while(input > 0): leading = input // divisor trailing = input % 10 # print("leading:", leading) # print("trailing:",...
from django.contrib.auth.models import Group, User # type: ignore from rest_framework import authentication # type: ignore from rest_framework import exceptions from carts.oidc import ( extract_kid, fetch_pub_key, fetch_user_info, invalidate_cache, verify_token, ) from carts.carts_api.models impor...
''' TODO ''' from datetime import datetime import requests import pandas as pd # officeID values DEV = True OFFICE_SENATE = 6 SENATE_TYPE_ID = 'C' STATES = ['CA', 'KY', 'OR'] if DEV else [ 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD',...
# -*- coding: utf-8 -*- # Copyright (C) 2010 Francesco Piccinno # # Author: Francesco Piccinno <stack.box@gmail.com> # # 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 2 of the Lic...
# Generated from Naja.g4 by ANTLR 4.9 from antlr4 import * if __name__ is not None and "." in __name__: from .NajaParser import NajaParser else: from NajaParser import NajaParser # This class defines a complete listener for a parse tree produced by NajaParser. class NajaListener(ParseTreeListener): # Ente...
import copy def merge_main(master_schedule, new_schedule): """ Merge a new schedule with the main schedule found in the database. :param master_schedule: [{"": [[],[],...]},...] :param new_schedule: [{"": [[],[],...]},...] :return: master_schedule """ nm = copy.deepcopy(master_schedule) ...
import torch.nn as nn from src.set_encoders import ( ContextBasedLinear, ContextBasedMultiChannelLinear, ContextFreeEncoder) from src.set_decoders import LinearSumSet, SimpleSubset from src.util_layers import FlattenElements import torch.nn.functional as F class ElementFlatten(nn.Module): def forward(s...
class Solution: def evalRPN(self, tokens): if not tokens: return 0 stack = [] for item in tokens: if item in '+-/*': n1, n2 = stack.pop(), stack.pop() if item == '+': stack.append(n1 + n2) elif item =...
import requests url = 'http://www.baidu.com/' strhtml = requests.get(url)#git方式获取网页数据,存至strhtml变量 print(strhtml.text)#文本形式输出网页
#!/usr/bin/env python from trillium.extensions import celery from trillium import create_app, DefaultConfig if __name__ == '__main__': app = create_app(DefaultConfig) with app.app_context(): celery.start()
from numpy.random import RandomState from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from random import Random seed = 42 py_rng = Random(seed) np_rng = RandomState(seed) t_rng = RandomStreams(seed) def set_seed(n): global seed, py_rng, np_rng, t_rng seed = n py_rng = Random(seed) np_rng = ...
import pytest from onegov.newsletter import NewsletterCollection, RecipientCollection from onegov.newsletter.errors import AlreadyExistsError def test_newsletter_collection(session): newsletters = NewsletterCollection(session) n = newsletters.add("My Newsletter", "<h1>My Newsletter</h1>") assert n.name...
from pyVim import connect from pyVmomi import vim from pyVmomi import vmodl import atexit # import tools.cli as cli import ssl def getHosts(content): host_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True) obj = [host for host in host_view.view] host_view.Destroy()...
from math import log10 def nsn(N): K = sum( list( map( int, list( str(N))))) return N/K def snuke(N): k = int( log10(N))+1 s = N now = nsn(N) for d in range(k+1): x = (10**(d+1))*(N//(10**(d+1)) + 1) - 1 y = nsn(x) if y < now: s = x now = y re...
from django.contrib import admin from .models import Article,Comment,HashTag # Register your models here. @admin.register(Article,Comment,HashTag) class FeedAdmin(admin.ModelAdmin): pass
#!/usr/bin/env python3 # encoding: utf-8 """ exercise3.py Created by Jakub Konka on 2011-10-28. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ import random as rnd import math ## Revision def WC_Words(filename): try: f = open(filename,'r') contents = f.read().split('\n') f.close() c...
from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import HeartBeat import json import logging logger = logging.getLogger(__name__) # Create your views here. @csrf_exempt def beat(request, identifier): data = None if req...
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 15:04:56 2019 @author: LEGION-JCWP """ import tellurium as te import roadrunner """ This model assumes that K_AB > A_total and that """ r = te.loada(""" J0: A + B -> AB ; K_AB * A * B - 1/K_AB * AB J1: B + C -> BC ; K_BC * B * C - 1/K_BC * BC J4: AB + C -> ABC ; K_AB...
# pylint: disable=no-member, unused-wildcard-import, no-name-in-module import pygame from pygame import mouse import pieces as pieces_lib import math import time import sys from random import shuffle, randint, choice import network import json from oooooooooooooooooooooooooooooooooooooooooooootils import * import _thre...
from examples.rps.rpsbot import RPSRobot from examples.rps.robotteam import RobotTeam import hackathon beat = {"R": "P", "P": "S", "S": "R"} rbeat = {"P": "R", "S": "P", "R": "S"} class RPSGame(hackathon.Game): def __init__(self, robots: list, *args, **kwargs): super().__init__(robots, *args, **kwargs) ...
#!/usr/bin/python #Control dynamixel with key input (position control). #NOTE: Run before this script: rosrun ay_util fix_usb_latency.sh #NOTE: Run before this script: ../fix_usb_latency.sh ''' Keyboard interface: 'q': Quit. 'd','a','w','s': Right turn, left turn, up, down. 'C','B': Move to Center (of rotation)...
''' Normalized robustness discussion ''' import warnings warnings.simplefilter("ignore", UserWarning) # Import base python modules import numpy as np from matplotlib import pyplot as plt from scipy.optimize import minimize import scipy.optimize import os import sys import pdb # Add my local path to the relevant modul...
import warnings, datetime from surveymonkey.exceptions import SurveyMonkeyWarning class Call(object): """ Base class for all API calls """ _api = None date_params = ( 'start_date', 'end_date', 'start_modified_date', 'end_modified_date' ) @property def call_name(self): retur...
############################################################################# # REVERSE CLASSIFICATION ACCURACY IMPLEMENTATION - 2018 # # Rob Robinson (r.robinson16@imperial.ac.uk) # # - Includes RCA.py and RCAfunctions.py # # ...
def InOrder(ls): stack=[] res=[] i=0 while i < len(ls) or len(stack) > 0: if i < len(ls): stack.append(ls[i]) i = 2 * i + 1 #找左孩子 else: p=stack.pop() res.append(p) ind=ls.index(p) i = 2 * ind + 2 #找右孩子 for i in r...
#!/usr/bin/python ''' Day 5 - Morning (pt. 1) The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. In addition, the...
# -*- coding: utf-8 -*- # @Author: gvishal # @Date: 2019-03-31 00:26:01 # @Last Modified by: vishalgupta07 # @Last Modified time: 2019-04-05 19:04:01 from django.urls import path from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, EventListView from . i...
import itertools from collections import defaultdict from locus import Locus def chrom_sort(chroms): # get characters after 'chr' alphanum = [c.split('chr')[1] for c in chroms] # split up chroms with and without '_', convert numbers to ints for easier sorting mapped = [] unmapped = [] f...
import pandas import matplotlib.pyplot as plt import random as rd import math import numpy as np def variable(width, height, density, cluster_density): """variables""" node_member, cluster_member, station_member, \ node_energy, shot_dis_data = [], [], [], [], [] len_nodes = math.ceil(den...
from django.contrib import admin from .models import * # Register your models here. class PersonaAdmin(admin.ModelAdmin): list_display = ['nombre','apellido','direccion','telefono'] class AutorAdmin(admin.ModelAdmin): list_display = ['persona'] class UsuarioAdmin(admin.ModelAdmin): list_display = ['per...
#!/usr/bin/env python # # This is a dictionary test by python # people = { 'Alice' : { 'phone' : '2101', 'address' : 'No.1 st,PH,US' }, 'Betch' : { 'phone' : '2155', 'address' : 'No.172,Wall St,US' }, 'Cecil' : { 'phone' : '3106', 'address' :...
def make_selector_on_deviceA(): from selector_wizard.make_initial_selector import process_clear_json_dataset process_clear_json_dataset(name="jst_first_10_selector_A", threshold=0.9, json_data=None, path_to_this_json=None, model=None) def make_dataset_for_device_B_by_shift(): #...
from django.urls import path, include from likes.views import LikeList, unLike urlpatterns = [ path('', LikeList.as_view()), path('remove', unLike), ]
from mrjob.job import MRJob class
import cadquery as cq length = 3887. width = 50. thickness = 5. box = cq.Workplane("XY").box(length, width, width) print(box) box2 = box.translate(thickness, thickness, 0) show_object(box)
import numpy as np from lmfit import Model def rational_R_ge(q2,a,b,R): return a*(1.-R*R*q2/6.+b*q2)/(1+b*q2) class xy_bootstrap(object): def read_in(self,filename,seed=7): data=np.loadtxt(filename,skiprows=1) self._q2=data[:,0] self._ge=data[:,1] self._dge=data[:,2] np...
# Generated by Django 2.1 on 2018-10-23 06:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0003_dailyinput_dummy'), ] operations = [ migrations.RenameField( model_name='concept', old_name='id_user', ...
import pandas as pd import pandas as pd import requests as req import datetime as dt import json import os def api_call(url_base,i): json_req = req.get(url_base.format(i)) dfs = [] if json_req.status_code == 200: jsonstr = json.loads(json_req.content) for dict_ in jsonstr["features"]: ...
# Generated by Django 2.2.1 on 2019-07-12 08:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('people', '0005_auto_20190711_2032'), ] operations = [ migrations.CreateModel( name='organizations', fields=[ ...
from .models import Tag, User from django import forms class TagForm(forms.Form): CHOICES = ( ('Java', 'Java'), ('Javascript', 'Javascript'), ('Python', 'Python'), ('PHP', 'PHP'), ('HTML', 'HTML'), ('CSS', 'CSS'), ('Cyptocurrency', 'Cyptocurrency'), ) ...
#edit print ('this is not an exit')
import datetime from operator import itemgetter from django.conf import settings from django.db.models import Q, Subquery, Sum from django.views.generic.base import TemplateView from braces.views import LoginRequiredMixin from rest_framework import renderers from rest_framework.decorators import action from rest_fram...
import os def locate_resource_file(fname): return os.environ['HOME'] + '/rif_data/' + fname
import scrapy import unicodedata import re import regex import sqlite3 from scrapy.crawler import CrawlerProcess class ao3spider(scrapy.Spider): name = "hpspider" allowed_domains = ['archiveofourown.org'] custom_settings = { 'DOWNLOAD_DELAY': 5, 'ROBOTSTXT_OBEY': False, ...
import pygame import random from pygame import * pygame.init() white = (255, 255, 255) yellow = (255, 255, 102) black = (0, 0, 0) red = (213, 50, 80) green = (0, 255, 0) blue = (50, 153, 213) purple = (184, 61, 186) dis_width = 600 dis_height = 400 dis = pygame.display.set_mode((dis_width, dis_heig...
import time from Util_new import Tag, Option, SubType, setTmp, getTmp, setFound, isFound, isComboActive, setCombo, split, getPlayerID, gameId, setCurState, GameState, setWaiting, setMulligan from Board import * from Cards_new import * from Bachelor.Ba.Util_new import getCurState, Player, EffectTime, Cardtype from types...
import threading import time from contextlib import contextmanager class LockManager: locks = {} def get(self, key): thread_id = threading.get_ident() while self.locks.get(key) not in [None, thread_id, None]: time.sleep(1) self.locks[key] = thread_id def release(self,...
import operator from functools import reduce import os import math import pyautogui from PIL import Image import fileinput import time l={} p={} p['30nn']=["ak","aa","qq","kk"] p['30nns']=[] p['20nn']=["aa","ak","kk","aq","qq","jj","tt"] p['20nns']=[] p['100n']=["aa","kk","qq","jj","tt","99","88","77","66","55","44",...
class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ my_dict = dict() for i in nums: if i in my_dict: my_dict[i] +=1 else: my_dict...
class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ def helper(i, j): res1 = 0 while (i >= 0 and j < len(s) and s[i] == s[j]): res1 += 1 i -= 1 j += 1 retur...
#stack expression = "1 2 + 3 4 - *" class Stack: def __init__(self): self.stack = [] def push(self, a): self.stack.append(a) def pop(self): return self.stack.pop() def is_empty(self): return not self.stack if __name__ == '__main__': stack =...
import cv2 import json import numpy as np import time import csv import os import sys from datetime import datetime import datetime as dt import matplotlib.pyplot as plt import configparser #read config params config = configparser.ConfigParser() config.read('../config.ini') screenHeightPX = int(config['DEFAULT']['scr...
# q9 for i in range(50, 81, 10): print(i)
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ max_ = 0 n = len(s) if n == 1: return n if n == 2: return int(s[0] != s[1]) + 1 for i in range(n-1): for j in r...
from wtforms import Form,StringField,ValidationError from wtforms.validators import Length,Regexp from apps.front.models import UserModel class Verify_sendcode(Form): #发送注册验证码验证 mobile = StringField(validators=[Regexp(r'^1(3|4|5|7|8)\d{9}$', message='手机号码输入错误')]) def validate_mobile(self,fi...
# -*- coding: utf-8 -*- # coding=utf-8 # __author__ = 'zy' import os import shutil import time import datetime s = os.sep # 根据unix或win,s为\或/ # root = "d:" + s + "ll" + s #要遍历的目录 # origin = "/Users/zy/Downloads/a/" # 不会被改变 # 所有问题都会被移动到root目录,入参和移动目标的考量 root = "/Users/zy/Downloads/a/" # 所有被移动文件的后缀名 suffix = ".mp4"...
if 0: print("True") else: print("False") name = input("Please enter your name: ") if name: print("Hello, {}".format(name)) else: print("Are you the man with no name?")
#!/usr/bin/env python def checkindex(key): if not isinstance(key,(int,long)): raise TypeError if key < 0: raise IndexError class AthimeticSequence: def __init__(self,start=0, step=1): self.start=start self.step=step self.changed={} def __getitem__(self,key): checkindex(key) try: ...
#!/usr/bin/env python #========================================================================= # proc-sim [options] <elf-file> #========================================================================= # # -h --help Display this message # -v --verbose Verbose mode # --trace Turn on line tracing # # ...
/home/ajitkumar/anaconda3/lib/python3.7/functools.py
""" LeetCode - Medium """ """ Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place. Follow up: A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space sol...
#!/usr/bin/env python3.6 import json import sys import boto3 from aws_console.console import Console def get_url_via_credentials(): session = boto3.Session() credentials = session.get_credentials() frozen_credentials = credentials.get_frozen_credentials() if frozen_credentials...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-09-27 03:30 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('messaging', '0022_auto_20160927_0415'), ] operations = [ migrations.AddField...
''' Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible t...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('USA_Housing.csv') print(df.head()) print("="*40) print(df.info()) print("="*40) print(df.describe()) print("="*40) print(df.columns) print("="*40) sns.pairplot(df) plt.show() sns.d...
import json from channels.generic.websocket import AsyncWebsocketConsumer class PlayerConsumer(AsyncWebsocketConsumer): '''Handels all socket communications for each player''' async def connect(self): # User that is not authenticated (anonymous) should not be accepted if 'user' in self.scope ...
#!/usr/bin/env python2.7 import db, datetime def load(conn): queue_contracts = db.Contract.load_by_state(conn = conn, state = db.Contract.IN_QUEUE) accepted_contracts = db.Contract.load_by_state(conn = conn, state = db.Contract.IN_PROGRESS) last_update = reduce(max, [x.last_seen for x in queue_contracts]...
num1=[] for i in range(4): num1.append(int(input("enter a value "))) print(num1)
from anvil import Anvil from anvil.entities import KilnRepo def main(): anvil = Anvil("spectrum") anvil.create_session_by_prompting() res = anvil.get_json("/Repo/68219") repo = KilnRepo.from_json(anvil, res) subrepos = repo.where_used() if __name__ == '__main__': main()
#!/usr/bin/python3 # Adapted from http://noahdesu.github.io/2014/06/01/tracing-ceph-with-lttng-ust.html import sys import numpy from babeltrace import * import time import math import getopt # This is for ceph version 9.0.0-928-g98d1c10 (98d1c1022c098b98bdf7d30349214c00b15cffec) requests = { int("0x00100", 16)...
import json import os import numpy as np import cv2 import matplotlib.pyplot as plt import torch from PIL import Image import torch import torch.utils.data import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor import torchvision from torchvision.models.detection import FasterRCNN fro...
# Generated by Django 3.0.2 on 2020-06-20 08:58 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('obsapp', '0037_auto_20200620_1311'), ] operations = [ migrations.AlterField( model_name='chats', nam...
#!/usr/bin/python3 import pprint import re import json import time import sys import json Lines = sys.stdin.readlines() json_body = "" for line in Lines: json_body = json_body + line.strip('\n') json_obj = json.loads(json_body) i = 0 for files in json_obj['files']: url = json_obj['files'][i]["url"] ...
""" LeetCode - Medium """ """ Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. Example 1: Input: [1,0,1,1,0] Output: 4 Explanation: Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s...
''' For Checking anomolies within data ''' from datetime import datetime from pathlib import Path import json import os import sys import pandas as pd __author__ = 'Edward Chang' class FormatChecker: ''' Checks Excel File for Header format, Correct Units, and other fields Also counts Wi...
def find_min_max(arr): start_index = None comparisons = 0 if len(arr) % 2 == 0: if arr[0] > arr[1]: max_val = arr[0] min_val = arr[1] else: max_val = arr[1] min_val = arr[0] start_index = 2 comparisons += 1 else: max_val = arr[...
# Generated by Django 2.2 on 2019-04-15 23:37 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('onlclass', '0019_auto_20190416_0834'), ] operations = [ migrations.AlterField( model_name='subjec...
# coding=utf-8 import os import sys from setuptools import find_packages from setuptools import setup assert sys.version_info[0] == 3 and sys.version_info[1] >= 6, "eosbase requires Python 3.6 or newer." def readme_file(): return 'README.rst' if os.path.exists('README.rst') else 'README.md' # yapf: disable se...
import pandas as pd import numpy as np # from sklearn.linear_model import LogisticRegression # from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier # from sklearn.svm import SVC # from xgboost import XGBClassifier # from sklearn.tree import DecisionTreeClassifier # from sklearn.dummy import DummyClas...
stk=[] size=int(input('enter the size')) top=0 n=0 def push(): global top,size if(top>size): print('stack is full') else: p=int(input('enter the element want to push')) stk.append(p) top+=1 def pop(): global top,size if(top<=0): print('stack is empty') els...
import os from util.class_property import ClassProperty __all__ = ["FileStore"] _GOOD_SONG_DIR_ENV = "GOOD_SONG_DIR" _BAD_SONG_DIR_ENV = "BAD_SONG_DIR" class FileStore(object): @ClassProperty @classmethod def good_songs_dir(cls): return FileStore.__get_song_dir(_GOOD_SONG_DIR_...
#import sys #input = sys.stdin.readline Q = 10**9+7 def getInv(N):#Qはmod inv = [0] * (N + 1) inv[0] = 1 inv[1] = 1 for i in range(2, N + 1): inv[i] = (-(Q // i) * inv[Q%i]) % Q return inv def getFactorialInv(N): inv = [0] * (N + 1) inv[0] = 1 inv[1] = 1 ret = [1]*(N+1) f...
from django.urls import path from .views import checkout,HomeView,ItemDetailView app_name='core' urlpatterns=[ path('product/<slug>',ItemDetailView.as_view(),name='product'), path('',HomeView.as_view(),name='home'), path('checkout/',checkout,name='checkout'), ]
from utils import parse_to_tree, read_input def get_metadata_sum(node): return sum(node.metadata) + sum(map(get_metadata_sum, node.children)) if __name__ == '__main__': tree = parse_to_tree(read_input()) print(get_metadata_sum(tree))
import copy import os import os.path as osp from typing import Sequence, Union, List, Tuple, Type, Optional from . import GaussianFilterLayer from .layers import ( FilteredFieldLayer, FilterFreeFieldLayer, Layer, PerfectBBLayer, PerfectFieldLayer, FilterFreeConeLayer, PerfectConeLayer, ) fr...
'''This module implements Picture Transfer Protocol (ISO 15740:2013(E)) It is transport agnostic and requires a transport layer to provide the missing methods in the class :py:class`PTPDevice`. Convenience structures are provided to pack messages. These are native-endian and may need to be adapted to transport-endian...
# -*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def get_variables_to_train(hypes): """Returns a list of variables to train. Returns: A list of variables to train by the optimizer. """ if...
# Generated by Django 2.0.2 on 2019-09-27 05:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0005_auto_20190927_1008'), ] operations = [ migrations.AddField( model_name='marketer', name='t_amount', ...
from selenium.webdriver.common.by import By class BasePageLocators: LOGIN_LINK = (By.CSS_SELECTOR, "#login_link") BASKET = (By.XPATH, "//a[@class='btn btn-default']") USER_ICON = (By.CSS_SELECTOR, ".icon-user") class MainPageLocators: ... class LoginPageLocators: LOGIN_FORM = (By.CSS_SELECTOR,...
from .minimization import minimize from .exceptions import LineSearchFailError, NotTangentVectorError __all__ = ['minimize', 'LineSearchFailError', 'NotTangentVectorError'] __version__ = '1.0'
from myhdl import * from sigmat import SignalMatrix, m_flat_top import random W0 = 9 matrix = SignalMatrix() flati = matrix.get_flat_signal() flato = matrix.get_flat_signal() nbits = len(flati) print nbits clock = Signal(bool(0)) reset = ResetSignal(0, active=1, async=False) sdo = Signal(bool(0)) def test_matrix(c...
#!/usr/bin/env python import os import sys import inspect import re import argparse import random parser = argparse.ArgumentParser(description=""" Description ----------- """,formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Authors ------- Vincent Merel """) #Input files parser.add_arg...
import time import board import busio import adafruit_adxl34x i2c = busio.I2C(board.SCL, board.SDA) accelerometer = adafruit_adxl34x.ADXL345(i2c) while True: print("%f %f %f" % accelerometer.acceleration) time.sleep(0.2)
# encoding: utf-8 """ @desc: compute ppl according to file generated by `fairseq-generate --score-reference` """ import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("--file") args = parser.parse_args() total_score = 0 total_count = 0 with open(args.file) as ...
import abc import time_util from typing import IO class Entry(abc.ABC): def __init__(self, id_): self.id = id_ def is_similar_all(self, *texts) -> bool: result = True for arg in texts: if isinstance(arg, list) or isinstance(arg, set): for text in arg: ...
from .server import RCNetwork, RCNeighbors