text
stringlengths
38
1.54M
from functions import createDbconnection dbconnection=createDbconnection() mycursor=dbconnection.cursor() mycursor.execute("CREATE TABLE transactions(Id int(11)AUTO_INCREMENT primary key,amount int(11),balance int(11),member_Id int(11),agents_Id int(11),clubcards_Id int(11))")
class Course: def __init__(self, name, instructor, room, time): self.name = name self.instructor = instructor self.room = room self.time = time def print(self): print(self.name + ' ' + self.instructor + ' ' + self.room + ' ' + str(self.time))
from GeneticSearchDNN import GeneticSearchDNN from Chromosome import Chromosome gen = GeneticSearchDNN(40, 8, 8, 4, 10, _testPercentage = 0.2) gen.searchVerbose('INX', 'TIME_SERIES_DAILY', None,'searches_after-change/search-dnn-stock-40-8-8-4-10-5epochs-5hl-INX-daily', _numberToSave=5, _generations=100, _epochs=5, _...
import re import json # def sum_of_all_numbers(): # file = open('day12.txt').read() # all_numbers = re.findall('\-?[0-9]+', file) # result = 0 # for i in all_numbers: # result += int(i) # print(result) def hook(obj): if "red" in obj.values(): return {} else: return...
import os import pandas as pd import pytest from kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.common.constants import RACE from kf_lib_data_ingest.common.errors import InvalidIngestStageParameters @pytest.fixture(scope="function") def df(): """ Reusable test dataframe ...
class calculator: m_text_list = [] def __init__(self): self.text_list=[] def sum_mul(self, choice, *args): if choice == "sum": result = 0 for i in args: result = result + i elif choice == "mul": result = 1 for i in arg...
import unittest from src.application import Application class TestStringMethods(unittest.TestCase): def test_server_socket_status(self): def get_handler(req, res): """ GET handler :param src.http_request.HttpRequest req: :param src.http_response.HttpResponse...
""" Modeling: Mass Total + Source Inversion ======================================= In this script, we fit `Interferometer` data with a strong lens model where: - The lens galaxy's light is omitted (and is not present in the simulated data). - The lens galaxy's total mass distribution is an `EllIsothermal` a...
import random import math def rand_probability(): return float(random.randint(0, 100)) / 100.0 def euclidean_distance(start, end): return math.sqrt((start[0] - end[0])**2 + (start[1] - end[1])**2)
from django.contrib import admin # Register your models here. from compras.models import Producto, Pedido, Lineapedido class LineapedidoInline(admin.StackedInline): model = Lineapedido extra = 0 class PedidoAdmin(admin.ModelAdmin): list_display = ['id','usuario','fecha'] inlines = [LineapedidoInlin...
import pygame from proton.component import * from pygame import Color from proton.component import Component from proton.ui.uigraphics import UIGraphics from proton.ui.uigraphics import Dims class TextComponent(UIGraphics): def __init__(self, _gameobject): """ :param _gameobject: """ ...
from hwt.synthesizer.exceptions import TypeConversionErr class InvalidVHDLTypeExc(Exception): def __init__(self, vhdlType): self.vhdlType = vhdlType def __str__(self): variableName = self.variable.name return ("Invalid type, width is %s in the context of variable %s" %...
import requests, bs4 res = requests.get('https://s155-en.ogame.gameforge.com/game/index.php?page=overview') res.text soup = bs4.BeautifulSoup(res.text, 'html.parser') #rec = soup.select('#scoreContentField') print(rec)
""" Copyright (c) 2020 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...
import pandas as pd df = pd.read_csv( "AC_ratings_google3m_koeper_SiW.csv", error_bad_lines=False, delimiter="\t" ) train_df = df.sample(n=50000) val_df = df.sample(n=2500) train_df.to_csv("train/AC_ratings_google3m_koeper_SiW.csv", sep="\t") val_df.to_csv("val/AC_ratings_google3m_koeper_SiW.csv", sep="\t")
from __future__ import absolute_import from __future__ import unicode_literals import sys from . import runner from . import analyze_runner, check, findjob, raw_runner, rsync_runner # The `sql_runner` module is not currently Python 2.4 compatible. if not sys.version.startswith('2.4.'): from . import sql_runner t...
import sys import os def binary_search(list, key): first=0 last=len(list)-1 found=False while( first <= last and not found): mid = (first+last)//2 if list[mid] == key: found=True else: if key<list[mid]: last=mid-1 else: ...
# Copyright 2019 The MLPerf Authors. 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 by applicable ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018/12/21 10:10 @Author : xycfree # @Descript: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options # ========================================================== # # chrome he...
from Car_Detection_TF.yolo import YOLO from Mosse_Tracker.TrackerManager import * from PIL import Image from VIF.vif import VIF """ Unit test for VIF class. """ def init_tracker(): cap = cv2.VideoCapture('videos/Easy.mp4') ret, frame = cap.read() yolo = YOLO() image = Image.fromarray(frame) ...
from time import sleep import pygame import glob import os from pygame import event from auxx import * pygame.init() BG_COLOR = (83,209,212) #Quick helper function for getting board coordinates def coordToBoard(coord): print('coord = ', coord) x = coord[0] * (boardSize/10) y = boardSize - (coord[1] + 1) * (b...
number = 1 y = 2 if number == 1: number = number + 2 if number == y: print ("midagi on valesti") if 5 < 10: print ("5 on tõesti väiksem kui 10") if 10 >= 10: print ("mulle sobib")
#Prints a box #Given a height and width, print a box consisting of * characters as its border rows = int(input("Width? ")) columns = int(input("Height? ")) for i in range(rows): for j in range(columns): if (i == 0 or i == rows - 1 or j == 0 or j == columns - 1): print('*', end = ' ') ...
# # MIT License # # Copyright (c) 2019 Keisuke Sehara # # 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 the rights # to use, copy, modify, me...
#!/usr/bin/python import sys import json from Bio import SeqIO import os import subprocess from collections import defaultdict target_to_seq = {} # Make a dictionary for target ids and their sequences targets_filename = "/mnt/gnpn/gnpn/projects/orphanpks/TargetMining/Antismash_gbids/targets.12.fa" for record in SeqI...
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from utils import read_log, plot_hist, update_fontsize, autolabel, read_p100_log from plot_sth import Bar import plot_sth as Color OUTPUT_PATH = '/media/sf_Shared_Data/tmp/sc18' num_of_nodes = [2, 4, 8, 16] num_of_nodes = [2, 4, ...
from rest_framework import serializers from common.models.general import BusinessUnit class BusinessUnitSerializer(serializers.ModelSerializer): label = serializers.StringRelatedField(source='Description') value = serializers.StringRelatedField(source='BusinessUnitId') class Meta: model = Busines...
import poplib from email.parser import Parser from decodeMailContent import print_info, get_att def decodedict(dict1): temp=dict() for key in dict1: value=dict1[key] temp[key]=value return temp def decodeBoolean(boolean1): temp=False; temp=boolean1; return temp; def decodeMai...
#!/usr/bin/python3 import sys def read_map_output(file): """ Return an iterator for key, value pair extracted from file (sys.stdin). Input format: key \t value Output format: (key, value) """ for line in file: yield line.strip().split("\t") def tag_reducer(): data = read_map_outp...
from __future__ import with_statement import os.path import random import pytest from whoosh import redline as kv from whoosh.compat import b, xrange from whoosh.util import now, random_name from whoosh.util.testing import TempDir def test_bisect_regions(): regions = [kv.Region(0, 0, "b", "d", 0), ...
class Coche(): def __init__(self): self.marca = "Audi" self.color = "Rojo" self.ruedas = 4 self.enmarcha = False def arrancar(self,arrancamos): self.enmarcha=arrancamos if(self.enmarcha): return "El coche esta en marcha" else: return "...
from django.db import models # Primary key (serial number or other ID) of Device is expected to be set # before the device attempts to connect for the first time. # Create your models here. class Device(models.Model): # Serial number (or other ID) of device device_id = models.CharField(primary_key=True, max_...
JSON_TOKENS = [",", ":", "{", "}", "[", "]"] def tokenize(string): """ Decomposes a string representation of json into a list of json tokens Tokens include: {, }, [, ], :, ,, strings, bools, null, numerics :param string: String representation of json :return: List of tokens """ tokens = []...
import clilib.decorator.resource as resource import clilib.decorator.verb as verb class TestDecoratorVerb(): def test_decorated_function_registers_as_a_verb(self): @resource class MyResource(): @verb def get(self): print('Got something') assert 'get...
# game.py import random # loads the random module import os from dotenv import load_dotenv load_dotenv() print("Rock, Paper, Scissors, Shoot!") print("----------------------") #capture player name player_name = os.getenv('PLAYER_NAME') print ("Hi ",player_name,". Welcome to my game.") #prompt user to enter a choic...
import '.'firebase_admin from firebase_admin import '.'ml from firebase_admin import '.'credentials firebase_admin.initialize_app( credentials.Certificate('/path/to/your/service_account_key.json'), options={ 'storageBucket': 'your-storage-bucket', }) model = create_model() source = ml.TFLiteGCSModelSo...
# coding=utf-8 class AnsiColours: colours = { 'black': '\033[0;30m', 'blue': '\033[0;34m', 'cyan': '\033[0;36m', 'green': '\033[0;32m', 'red': '\033[0;31m', 'purple': '\033[0;35m', 'yellow': '\033[0;33m', 'light_grey': '\033[0;37m', 'colour_e...
from stag.parser.python_ast_parser import Parser class Plugin: @property def name(self): return 'stag_python' def patterns(self): return [ '*.py', # TODO: pyx? SConstruct/script? ] def create_parser(self): return Parser()
from django.contrib import admin from .models import account_data # Register your models here. class UserData(admin.ModelAdmin): list_display = ['username', 'key', 'value'] list_filter = ['username'] admin.site.register(account_data, UserData)
#! /usr/bin/python # -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) # import funkcí z jiného adresáře import os import os.path import pytest path_to_script = os.path.dirname(os.path.abspath(__file__)) import unittest import numpy as np import sys try: import skelet3d data3d = np...
#!/usr/bin/python2 import sys from PyQt4 import QtGui, QtCore from clusterAMMControl import AMMControl from clusterSwitchControl import SwitchControl from clusterBladeControl import BladeControl from clusterBladeCenterPanel import BladeCenterPanel from clusterRTOP import RtopPanel from clusterMediaTray import Clust...
# Generated by Django 2.2 on 2019-12-13 14:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0019_epospayment'), ] operations = [ migrations.AlterModelOptions( name='epospayment', options={'verbose_name':...
from text_query_handlers import AbstractHandler as ah import re from random import randint import ConstantsAndUtils as cau class ProxyCallHandler(ah.AbstractHandler): match_regex = "(/message: (.*)\n?/id: (.*))" def predicate(self, message): return len(re.findall(self.match_regex, message.text)) > 0 ...
# -*- coding: utf-8 -*- """ Created on Thu May 30 10:15:05 2019 @author: user """ """ N값, Group 수정 N값 자동화함. Group 지정만, """ # In[] Group 지정 highGroup = [0,2,3,4,5,6,8,9,10,11,59] # 5% # exclude 7, 이유: basline부터 발이 부어있음. inter phase에 movement ratio가 매우 이례적임 (3SD 이상일듯) # 1추가 제거 ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-11-06 15:43 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dataentry', '0068_auto_20181024_1729'), ('dataentry', '0071_merge_20181101_1434'), ] ...
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. # -*- coding: utf-8 -*- # pragma pylint: disable=unused-argument, no-self-use import sys import json import pytest from requests.exceptions import HTTPError from fn_cisco_asa.lib.cisco_asa_client import CiscoASAClient from resilient_circuits.util import get_fu...
import pygame from resources import get_sheet # Ce fichier n'est pas utilisé dans le jeu class AnimatedSprite(pygame.sprite.Sprite): """Extended sprite class to animate more easily""" def __init__(self, **keyargs): super(AnimatedSprite, self).__init__() self.animations = dict() for key, value in keyargs.item...
from django.db import models from django.contrib.auth.models import UserManager, User from django.utils import timezone from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User) date_joined = models.DateTimeField(('date_joined'), defa...
import re import requests header_info = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36" } response = requests.get(url='https://www.baidu.com/s?wd=云班课', headers=header_info) body_str = response.text titls = r...
#__all__ = ["code","elements"] #from .elements import CodeElement, ValueElement, Function, Subroutine, TypeExecutable #from .elements import CustomType, Module, DocGroup, DocElement #from .code import CodeParser
# 飞参和振动相关性分析 from FileUtils.functionUtils import findFolder, readTime, readData, loadFile, printFiles, printColumns, matchData import scipy.stats as scs import os def FPCorrCalculator(vibName, flightTime): ''' 计算输入变量(vibName)与某个架次(flightTime)飞行参数的Pearson's Correlation 返回2个变量corr_list, col_list corr_li...
import motor.motor_asyncio from selenium import webdriver from selenium.webdriver.chrome.options import Options import asyncio from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Gsshop(): def __...
# Find Three Largest Numbers # O(n) # n = len(array) def findThreeLargestNumbers(array): res = [float('-inf'), float('-inf'), float('-inf')] for i in array: if i > res[2]: res.append(i) elif i > res[1]: res.insert(2, i) elif i > res[0]: res.insert(1, i) if len(res) > 3: res = res[1:] return ...
from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.six import python_2_unicode_compatible @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unic...
print("Hello World") counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county, voters in counties_dict.items(): print(f"{county} county has {voters:,} registered voters.") my_votes = 3330 total_votes = 15590 percentage_votes = (my_votes / total_votes) * 100 message = (f"You received {...
from .c_dataloader import CDataLoader from .c_dataloader_sklearn import * from .c_dataloader_svmlight import CDataLoaderSvmLight from .c_dataloader_imgclients import CDataLoaderImgClients from .c_dataloader_imgfolders import CDataLoaderImgFolders from .c_dataloader_mnist import CDataLoaderMNIST from .c_dataloader_lfw i...
#coding:utf-8 import unittest import os from report import HTMLTestRunner_TT import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import time # base_dir = str(os.path.dirname(os.path.dirname(__file__))) # base_dir = str(os.path.dirname(os.path.realpath(__file__))) # cur_pa...
# !/usr/bin/env python2 import rospy from autominy_msgs.msg import Speed, SpeedCommand, NormalizedSteeringCommand, SteeringAngle, NormalizedSpeedCommand from nav_msgs.msg import Odometry import math import tf class PDController: def __init__(self): # Subscribers self.sub_speed = rospy.Subscriber...
from Expresiones.Arreglos import Arreglos class TablaSimbolos: def __init__(self,nombre, anterior = None): self.tabla = {} self.anterior = anterior self.nombre = nombre def BuscarIdentificador(self, id): tablaActual = self while tablaActual != None:...
#!/usr/bin/env python3 import json import subprocess import sys data = json.load(open('/home/marxin/Downloads/instructions.json')) descriptions = {} def get_description(insn): if insn in descriptions: return descriptions[insn] for suffix in ('b', 's', 'l', 'q'): if insn.endswith(suffix) and...
import sys import string import pprint try: xrange except NameError: xrange = range pp = pprint.PrettyPrinter() def clean_words(words): return [word.lower().translate(None, string.punctuation) for word in self.idx2word] def load_data(fileName): with open(fileName, "r") as fp: data = fp.read() splitda...
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys #import ritesh1 import pandas as pd import matplotlib.pyplot as plt data=pd.read_csv('matches.csv') data1=pd.read_csv("deliveries.csv") data1.dismissal_kind.fillna('notout',inplace=True) data1.player_dismissed.fillna...
import sympy as sm import numpy as np import torch import time #_generate_matrix______________________________________________ def sympy_coo_matrix(I, J, V, size): # sort I, J, V such that I is monotonic increasing from sympy import Matrix I, J, V = list(I), list(J), Matrix(V) I_idx = sorted(range(len(...
# Creates an image representing all the DNA code downloaded from 23andme. # # Run with 'python3 dna_image.py <name_of_23andme_text_file>' # # An image will pop up with the results, and it will be saved as 'dna.png' in # the current working directory. Note that this image contains all the data in # your DNA so it should...
#encoding=utf-8 from __future__ import unicode_literals import sys sys.path.append("../") import Terry_toolkit as tkit # t= tkit.Db() tdb=tkit.Db() # tdb.add(key="niubi",value={'gender': "male", 'age': 28, 'name': 'john'}) # tdb.add(key="niub2",value="wqwq") # j=tdb.get(key="niub2") # print(type(j)) # print(j) tdb....
from django.conf.urls import url from cooks import views urlpatterns = [ url(r'^', views.cooks, name='phoenix-cooks'), ]
#!/usr/bin/python # This script reads in a fixed form .f file and converts it to a free form # .f90 file import sys import re import argparse class FortranLine: def convert(self): line = self.line # If the line is short, replace with a newline. If the line is not short, save the da...
from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.urls import reverse ''' class Right(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name="Right", help_text="Enter a right"...
# -*- coding: utf-8 -*- from collections import OrderedDict from pyexcel_xlsx import save_data import xlrd import pymysql.cursors import os DB_HOST = "***.**.**.*8" DB_PORT =222 DB_USER = "222" DB_PASSWORD = "222" DB_NAME = "222" # Main routine # 写Excel数据, xls格式,以sheet为单位 def save_xls_file(xls_header,xls...
from django.urls import path, include urlpatterns = [ # todo path("auth/", include("api_analysis_dataset.v1.auth.urls"), name="api_v1_auth"), path("analysis/", include("api_analysis_dataset.v1.analysis.urls"), name="api_v1_analysis") ]
#!/usr/bin/env python3 #Author : Eric Normandeau (Louis Bernatchez' Lab) #This script is available at https://github.com/enormandeau/stacks_workflow """Filtering SNPs in VCF file output by STACKS1 or STACKS2 minimaly Usage: <program> input_vcf min_cov percent_genotypes max_pop_fail min_mas output_vcf Where: inp...
#-*- coding: iso-8859-15 -*- ''' Cartesian control: Torso and Foot trajectories ''' import config import motion def main(): ''' Example of a cartesian foot trajectory Warning: Needs a PoseInit before executing Example available: path/to/aldebaran-sdk/modules/src/examples/ ...
"""Constants in AstroWeather component.""" DOMAIN = "astroweather" CONF_FORECAST_TYPE = "forecast_type" CONF_FORECAST_INTERVAL = "forecast_interval" CONF_LATITUDE = "latitude" CONF_LONGITUDE = "longitude" CONF_ELEVATION = "elevation" CONF_TIMEZONE_INFO = "timezone_info" CONF_CONDITION_CLOUDCOVER_WEIGHT = "cloudcover_w...
from unittest import TestCase import csv from transform.Covid19USTransformer import Covid19USTransformer from transform.Covid19CSV import Covid19CSV class TestCovid19USTransformer(TestCase): @staticmethod def _createVerificationObject(hdr_, str_): # Input string may have embedded commas in a field. ...
__author__ = 'Vineets' def isprime(num): i = 2 while i * i <= num: if num % i == 0: return False i += 1 return True def mapper(data): output = {} for num in data: for i in range(2, num + 1): if num % i == 0 and isprime(i): if not i in...
from pydantic import BaseSettings from typing import Any import json class Settings(BaseSettings): DEBUG: bool = False TESTING: str = '' PROJECT_NAME: str = '2343' PROJECT_API_V1: str = '1.1' SQLALCHEMY_DATABASE_URI : str = 'postgresql://dbuser:dbpass@localhost:5432/agros-stage' SQLALCHEM...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ roc_crossval_comp.py Uses binary classifiers (category splits 2) and published classifiers to generate a Receiver Operating Characteristic (ROC) curve with calculated area under the curve (AUC). usage: roc_crossval_comp.py """ import numpy as np from scipy import in...
class Solution: def numSquares(self, n): dp = [0] while len(dp) <= n: dp.append(min(dp[-i ** 2] for i in range(1, int(len(dp) ** 0.5 + 1))) + 1) return dp[-1] if __name__ == '__main__': solution = Solution() print(solution.numSquares(6255))
import requests # should create Set-Cookie:mycookie=myvalue header if vulnerable PAYLOADS = [r"%0D%0ASet-Cookie:mycookie=myvalue", r"%0d%0aSet-Cookie:mycookie=myvalue", r"crlf%0dSet-Cookie:mycookie=myvalue", r"crlf%0aSet-Cookie:mycookie=myvalue", r"%23%0dSet-Cookie:mycoo...
import re import os import logging # Adopted from: https://github.com/HASTE-project/haste-image-analysis-container2/tree/master/haste/image_analysis_container2/filenames # file example # /share/mikro/IMX/MDC_pharmbio/exp-TimeLapse/A549-20X-DB-HD-BpA-pilot1/2019-03-27/84/TimePoint_1/A549-20X-DB-HD-BpA-pilot1_B02_s1_thu...
# Generated by Django 2.0.2 on 2018-02-10 06:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('demo', '0021_files_file_id'), ] operations = [ migrations.AlterField( model_name='files', name='file_id', ...
from selenium.webdriver.common.by import By from selenium.webdriver.remote.webdriver import * from selenium.webdriver.common.action_chains import ActionChains from selenium import webdriver import time class BasePage(object): def __init__(self): self.driver = webdriver.Chrome() self.timeout = 30 ...
# TCP port to be used for twisted communication COMMUNICATION_PORT = 7999 # Created services, each item represent one service and the master and worker # class contains business logic for the specific services. SERVICES = { 'http': { 'MasterClass': "master.services.http.nginx_master_service.NginxMasterServ...
import itertools from flask import g, request, render_template, json from brutus_module_math import app from brutus_module_math import nlCalc @app.route('/') def index(): """ Get the index page. """ return "Brutus Math Module" @app.route('/api/request', methods=['POST']) def create_request(): ...
from django.db import models # Create your models here. class Product(models.Model): UM = 'um' MS = 'ms' PS = 'ps' SHOPS = [ (UM, UM), (MS, MS), (PS, PS), ] product_id = models.IntegerField('商品ID', unique=True) stock_pcs = models.IntegerField('商品庫存數量', default=0) ...
from segmentation.segmentation_abstract import Segmentation import pandas as pd class ActivityWindow(Segmentation): def applyParams(self, params): res = super().applyParams(params) return res def segment3(self, buffer): for i, row in self.a_events.iterrows(): act = row.A...
#creates random database with paths for 50 nodes import random f=open("db.txt","a") x=0 while x < 50: q=random.randint(0,50) f.write(str(q)) f.write(" ") p=random.randint(0,50) f.write(str(p)) f.write(" ") if p==q: f.write('0') else: f.write(str(random.randint(1,105))) f.write("\n") x+=1 ...
#matrixTools.py #Sunday, September 27, 2020 import staticMatrix def buildMatrix(inputString, formattingFunction): data = [] iterator = 0 tempRow = [] while iterator < len(inputString): character = inputString[iterator] if character.isspace() or character == ",": iterato...
""" Homework 2 Create 5 dictionaries. Each dictionary should represent a CV. Create a CV containing the information of the 5 created people. Print the information on CVs created on the screen. """ mehmet_cv = {"Name": "Mehmet", "Surname": "Altın", "Age": 34, "Gender": "Male", ...
import shelve import re, os from urllib.parse import urlparse from PartA import tokenize, computeWordFrequencies stopWord = ''' a about above after again against all am an and any are aren't as at be because been before being below between both but by can't cannot could couldn't did didn't do does doesn't doing don't...
import pandas as pd from sklearn.svm import SVC, LinearSVC from sklearn import model_selection from sklearn import metrics import warnings warnings.filterwarnings('ignore') # "error", "ignore", "always", "default", "module" or "once" glass = pd.read_csv("glass.csv") # Preprocessing data X = glass.drop('Type', axis=...
from hashlib import md5 from io import BytesIO from aspen.simplates.pagination import parse_specline, split_and_escape from babel.messages.extract import extract_python import jinja2.ext JINJA_BASE_OPTIONS = dict( trim_blocks=True, lstrip_blocks=True, line_statement_prefix='%', extensions=['jinja2.ext.do...
from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier import numpy as np from sklearn.datasets import load_digits import matplotlib.pyplot as plt digits = load_digits() '''from sklearn.model_selection import train_test_split X_train, X_test,...
from cryptofeed import FeedHandler from cryptofeed.defines import LIQUIDATIONS from cryptofeed.exchanges import EXCHANGE_MAP async def liquidations(data, receipt): print(f'Cryptofeed Receipt: {receipt} Exchange: {data.exchange} Symbol: {data.symbol} Side: {data.side} Quantity: {data.quantity} Price: {data.price} ...
#!/usr/bin/env python3 """Contains `KappaComplex`, a class to represents a list of agents chained into a larger entity, and the `embed_and_map` function.""" import re import networkx as nx from collections import deque from typing import Deque, Dict, List, Set, Tuple, Union from .KappaMultiAgentGraph import KappaMult...
from pico2d import * import game_framework from bullet import * from buff import * from hpmp import * import game_world import main_state IDLE_STATE = 0 RUN_STATE = 1 BACKSTEP_STATE = 2 JUMP_STATE = 3 DOWN_STATE = 4 ATTACK_STATE = 5 DEFENSE_STATE = 6 HP_HEAL_STATE = 7 MP_HEAL_STATE = 8 GUN_STATE = 9 SPECIAL_ATTACK_STA...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) DIGIT=23 GPIO.setup(DIGIT, GPIO.IN) def read_sensor() : digit_val=GPIO.input(DIGIT) return digit_val
""" General utility methods """ import os import click import json def extract_path(path): """ Extract the path to path and basename """ dir_name = os.path.dirname(path) dir_name = prepend_slash(dir_name) dir_name = append_slash(dir_name) base_name = os.path.basename(path) return (dir_nam...
import os import glob import pandas as pd import numpy as np def build_primary_pset_tables(pset_dict, pset_name): """ Build the tissue, drug, and gene tables for a PSet and return them in a dictionary, with table names as the keys. @param pset_dict: [`dict`] A nested dictionary containing all tables ...
class BaseVocoder: def __init__(self, device): self._device = device def synthesize(self, mel): raise NotImplementedError("Please subclass!")