text
stringlengths
8
6.05M
#Accepts an accession number, returns a protein sequence from Bio import SeqIO from Bio import Entrez from Bio.Blast import NCBIWWW,NCBIXML import argparse from time import sleep parser = argparse.ArgumentParser(description='Get aa sequence from accession number') parser.add_argument('-an', '--accession', help='the a...
#!/usr/bin/env python3 from hashlib import sha256 from os import fsync, path from signal import SIGINT, signal from time import monotonic from sys import exit def signal_handler(signum, frame): """ """ print('\nE: got signal {}'.format(signum)) exit(1) def get_len(fpath): """ """ try: ...
from snippets.models import Snippet from snippets.serializers import SnippetSerializer from snippets.serializers import UserSerializer from rest_framework import generics from django.contrib.auth.models import User class SnippetList(generics.ListCreateAPIView): """ List all snippets, or create a new snippet. ...
def Calc(A,B,Op): if Op==1: return A-B elif Op==2: return A*B elif Op==3: return A/B else: return A+B A=float(input("ะ: ")) B=float(input("B: ")) N1=int(input("N1: ")) N2=int(input("N2: ")) N3=int(input("N3: ")) print(Calc(A,B,N1)) print(Calc(A,B,N2))...
import os os.chdir("D:\Deep_Learning_A_Z\Artificial_Neural_Networks") import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') #X = dataset.iloc[:, [2, 3]].values Takes only 2 & 3 X = dataset.iloc[:,3:13].values y = datas...
from django.db import models # Create your models here. class ESTATUS(models.Model): IDESTATUS = models.AutoField(primary_key=True) DESCRIPCION = models.CharField(max_length=50) def __str__(self): return '%s %s'%(str(self.IDESTATUS), self.DESCRIPCION) class PERIODOESCOLAR(models.Model): IDPERIODO = models.Aut...
#!/usr/bin/env python """ A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html """ from os import path try: from pip.req import parse_requirements except ImportError: # pip >= 10 from pip._internal.req import parse_requirements from setuptools import find_packa...
if __name__ == '__main__' and __package__ is None: import sys from os import path sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__))))) from utct.TensorFlow.trainer1 import Trainer1 from common.TensorFlow.optimizer import Optimizer from common.train_config import TrainConfig fro...
from .BrushControl import BrushControl from PyQt5 import QtWidgets, QtCore class FontChooserControl(BrushControl): def __init__(self, brush, label, callback = None, fontName = ""): BrushControl.__init__(self, brush, label, callback) self.label = QtWidgets.QLabel(label) self.control = QtWi...
import nltk from nltk.util import ngrams from collections import defaultdict import random import argparse parser = argparse.ArgumentParser(description='Ngram Model') parser.add_argument('--data', type=str, default='../../data/full_dataset.txt', help='location of data corpus') parser.add_argument('...
from DominoExceptions import BadSumException, BadDominoException from Solitaire import Solitaire class InteractiveSolitaire(Solitaire): def turn(self): """This is a function that handles a turn in the solitaire's game""" # We choose which dominoes are going to be removed # and we sort the...
from matrices import Matriz from dataclasses import dataclass from enum import Enum import re class LexerException(Exception): def __init__(self): self.message = "Carรกcter invรกlido." class Tipo(Enum): LEF_PARENS = 0 RIG_PARENS = 1 NUMERO = 2 COMA = 3 @dataclass class Token: tipo_to...
from constante import * import math from laser import Laser class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = playerIMG self.rect = self.image.get_rect() self.rect.x = ecranW/2 self.rect.y = ecranH/2 self.angle = 0 self.o...
""" Script to check conversion from nPE to MeV of positron, which were simulated with tut_detsim.py of JUNO offline version J18v1r1-pre1. This is a cross-check to script check_conversion_npe_mev.py, where the conversion from nPE to MeV of neutron and protons is calculated. The conversion factor of pos...
#!/usr/bin/python import os, subprocess, sys subprocess.call(['python', 'virtualenv.py', 'flask']) if sys.platform == 'win32': bin = 'Scripts' else: bin = 'bin' subprocess.call(['python', '-m', 'venv', 'flask']) #subprocess.call(['easy_install', 'virtualenv']) subprocess.call([os.path.join('flask', bin, 'easy_i...
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import pandas as pd from transfer import transfer_suggestion from pydantic import BaseModel from google.cloud import storage import requests class Item(BaseModel): team_list: list budget: float app = FastAPI() app.add_middleware( ...
from left_recursion import * def create_first_follow_matrix(): # creates and return it first_follow_matrix = {} for nonterminal in input_dict["Grammar"]["Nonterminal"]: first_set = set() follow_set = set() verified_nonterminal_list = [] #will contain nonterminals for which we should no...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'employee_objective', 'version': '1.0', 'category': 'Sales', 'sequence': 5, 'summary': 'Track employee-s sale/leads/invoicing individual objectives.', 'description': "", 'website': '...
import time import math import datetime import microdotphat microdotphat.set_clear_on_exit(True) def set_brightness(value): microdotphat.set_brightness(value) def wait(seconds): time.sleep(seconds) def reset(): microdotphat.clear() microdotphat.show() def print_string_fade(text): start = ti...
C=str(input("C= ")) N1=int(input("N1= ")) N2=int(input("N2= ")) CCC={ 'N':[(1=='W'),(2=='N'),(-1=='E')], 'E':[(1=='N'),(2=='E'),(-1=='S')], 'S':[(1=='E'),(2=='S'),(-1=='W')], 'W':[(1=='S'),(2=='W'),(-1=='N')] } if(C=='N')and(C=='E')and(C=='S')and(C=='W'): print(CCC.get(C))
import logging import time import numpy as np from numpy.random import RandomState import lasagne from lasagne.updates import adam from lasagne.objectives import categorical_crossentropy from lasagne.nonlinearities import elu,softmax,identity from hyperoptim.parse import cartesian_dict_of_lists_product,\ product_of...
__author__ = "Narwhale"
################################################### # # # General utility file for scoring methods, pca, # # etc. # # # # Authors: Amy Peerlinck and Neil Walton # # ...
prod_list_url = 'lighting/lamps/desk-lamps' header_search_results = 'Search Results for' prod_links_css = "#sbprodgrid a.productbox" prod_title_css = '[data-qa="text-pdp-product-title"]' prod_option_css = 'a.js-visual-option' add_to_cart_button_css = 'input[data-data-qa="button-add-to-cart"]' def assert_at_prod_lis...
import math import numpy # Horizontal: Item item = ['Phim hร nh ฤ‘แป™ng', 'Phim Hร n Quแป‘c', 'Phim khoa hแปc', 'Phim tรฌnh cแบฃm', 'Phim Nhแบญt Bแบฃn'] # Vertical: User user = ['Tรบ', 'Thแบฏng', 'Trรขm', 'ร', 'Trinh'] rating_matrix = [ [0,4,1,4,1], [1,2,5,2,5], [4,5,1,3,4], [0,1,5,1,4], [4,3,1,3,1], ] # Item sim...
''' import shutil import requests from slackbot.bot import default_reply import os from keras.preprocessing import image from sklearn.model_selection import train_test_split import keras import numpy as np import tensorflow as tf import random as rn import os from keras import backend as K import numpy as np from keras...
def next_element(arr): stack = [] ans = {} stack.append(arr[0]) for i in range(1, len(arr)): next = arr[i] while len(stack) != 0 and arr[i] > stack[-1]: ans[stack[-1]] = i+1 stack.pop() stack.append(next) for i in stack: ans.append([...
#!/usr/bin/python import urllib,urllib2,sys,csv def readPage(pageId): url='http://www.osha.gov/pls/imis/establishment.inspection_detail' params=urllib.urlencode({'id':pageId}) req=urllib2.Request(url,params) response=urllib2.urlopen(req) con=response.readlines() return con def extractVal...
#!/usr/bin/env python __author__ = 'Ajit Apte' from django.utils import simplejson from google.appengine.api import urlfetch from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class EventsHandler(webapp.RequestHandler): @classmethod def _convert_events(cls, eve...
__author__ = 'apple' try: from osgeo import ogr print 'Import of ogr from osgeo worked. Hurray!\n' except: print 'Import of ogr from osgeo failed\n\n'
#!/usr/bin/env python2 ################################################## # GNU Radio Python Flow Graph # Title: Default Test # Generated: Thu Dec 10 22:45:58 2015 ################################################## from gnuradio import analog from gnuradio import blocks from gnuradio import eng_notation from gnuradio ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report #๋ฐ์ดํ„ฐ ์ฝ์–ด๋“ค์ด๊ธฐ wine = pd.read_csv("./data/winequality-white.csv", sep=';', encoding='utf-8') #๋ฐ์ดํ„ฐ๋ฅผ ๋ ˆ์ด๋ธ”๊ณผ ...
#I pledge my Honor that I have abided by the Stevens Honor System. #I understand that I may access the course textbook and course lecture notes but I am not to access any other resource. #I also pledge that I worked alone on this exam. #Meher Kohlli def Mathematicalfunction(): print("\nMATHEMATICAL FUNCTIONS") ...
from flask import Flask, flash, render_template, request import pickle import numpy as np app = Flask(__name__) app.secret_key = b'dasdasda\n\xec]/' clf_model = pickle.load(open('beta_model_3.pkl', 'rb')) @app.route("/") def home(): a = [['0', '0', '0', '0', '0', '3000', '0', '66', '360', '0', '0']] ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 26 00:46:22 2018 @author: Angela """ def smallest_factor(n): """Return the smallest prime factor of the positive integer n.""" if n==1: return 1 for i in range(2, int(n**.5)): if n % i == 0: return i return n #Test for zero and negative v...
# Write a class Book โ€“each book has a title (string) and one or more authors. # Write a class to represent an author โ€“each author has a name (string) and an email address (string class Book: def __init__(self, title): self._title = title self._authors = [] def add_author(self, a): sel...
import requests requests.post('http://httpbin.org/post') requests.put('http://httpbin.org/put') requests.delete('http://httpbin.org/delete') requests.head('http://httpbin.org/get') requests.options('http://httpbin.org/get')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 26 13:46:06 2018 @author: thomas """ import os dir_path = os.path.dirname(os.path.realpath(__file__)) + '/' cwd = os.getcwd() St = os.path.basename(cwd) Re = os.path.split(os.path.dirname(cwd))[-1] OpenDatabase("localhost:"+dir_path+"VTK/AVG.vtk"...
from .base_page import BasePage from .locators import ProductPageLocators class ProductPage(BasePage): def add_object_to_basket_solve(self): button_basket = self.browser.find_element(*ProductPageLocators.ADD_TO_BASKET) button_basket.click() self.solve_quiz_and_get_code() def add_objec...
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 10:51:13 2015 @author: eejvt Code developed by Jesus Vergara Temprado Contact email eejvt@leeds.ac.uk University of Leeds 2015 """ import numpy as np import sys import matplotlib.pyplot as plt #sys.path.append('C:\opencv\build\x64\vc12\bin') fr...
"""empty message Revision ID: 0daa0acd5042 Revises: 70e970adcb0f Create Date: 2019-04-25 21:25:28.759000 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0daa0acd5042' down_revision = '70e970adcb0f' branch_labels = None depends_on = None def upgrade(): # ...
#!/usr/bin/env python import bottle import redis import settings import hashlib settings.r = redis.Redis(host=settings.REDIS_HOST,port=settings.REDIS_PORT,db=settings.REDIS_DB) from bottle_session import Session from model import User,Post,Timeline reserved_usernames = 'follow mentions home signup login logout pos...
# Generated by Django 3.0.6 on 2020-05-28 11:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('musicRun', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='song', name='artist', ), ...
from flask import Blueprint from flask import jsonify from shutil import copyfile, move from google.cloud import storage from google.cloud import bigquery from flask import request from google.auth.transport.requests import AuthorizedSession import dataflow_pipeline.felicidad_y_cultura.tabla_personal_beam as tabla_pers...
# %% import pandas as pd import numpy as np import matplotlib.pyplot as plt from original_approach.encoding import encode_similarity_matrix df = pd.read_csv('raw/epitope_table_export_1608718806.csv', skiprows=[0]) df # %% df['len'] = df['Description'].apply(len) peptides = list(df[df['len'] == 9]['Description'].un...
from typing import Dict import importlib import numpy as np from manythings.util_yaml import yaml_loader import click import wandb from wandb.keras import WandbCallback import mlflow from mlflow.models.signature import ModelSignature from mlflow.types.schema import Schema, TensorSpec # api_key = os.environ['WANDB_API_...
# scalable ttt # 21 22 23 24 25 # 16 17 18 19 20 # 11 12 13 14 15 # 6 7 8 9 10 # 1 2 3 4 5 # s = size while True: try: s = int(input("Please specify number for rows/columns ")) break except: print("Sorry, please try again.") """ def field(x): y = x field = x * ...
from . import api, brackets, utils TOURNAMENT_PREFIX = 'tournament/' EVENT_URL = '/event/' VALID_PARAMS = ['event', 'phase', 'groups', 'stations'] def show(tournament_name, params=[], filter_response=True): """Retrieve a single tournament record by `tournament name`""" utils._validate_query_params(params=pa...
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # --------------------------------------------...
import numpy as np import re import sys import time from multiprocessing import Process, Queue from plotter.utils.gcode import * from plotter.utils.calibration import * def processPlotterQueue(plotter): """Callback for plotter process.""" plotter.processQueueAsync() class BasePlotter: """Base class of...
# Submitter: loganw1(Wang, Logan) from goody import type_as_str import inspect class Check_All_OK: """ Check_All_OK class implements __check_annotation__ by checking whether each annotation passed to its constructor is OK; the first one that fails (by raising AssertionError) prints its problem, wi...
# Generated by Django 2.0.5 on 2018-07-31 12:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_management_app', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='assignment', ...
import functools import math import numpy as np import plotly.graph_objs as go import plotly.figure_factory as ff import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import State, Input, Output from datetime import date, timedelta, datetime import pandas as pd impor...
import sys from PyQt5.QtWidgets import QDialog, QLabel, QComboBox, QDoubleSpinBox from PyQt5.QtWidgets import QApplication, QGridLayout class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) date = self.getdata() rates = sorted(self.rates.keys()) ...
from typing import List from leetcode import test def predicate_the_winner(nums: List[int]) -> bool: dp = [[-1] * 21 for _ in range(21)] def range_sum(start: int, end: int) -> int: nonlocal nums return sum(nums[i] for i in range(start - 1, end)) def dfs(left: int, right: int) -> int: ...
""" Code that goes along with the Airflow located at: http://airflow.readthedocs.org/en/latest/tutorial.html """ from airflow import DAG from airflow.operators.bash_operator import BashOperator from datetime import date,datetime, timedelta import os import getpass from airflow.operators import WaitGCSOperator defaul...
from CallBackOperator import CallBackOperator from SignalGenerationPackage.DynamicPointsDensitySignal.DynamicPointsDensityUIParameters import DynamicPointsDensityUIParameters class AccelerationTimeCallBackOperator(CallBackOperator): def __init__(self, model): super().__init__(model) # overridden ...
import pyaudio import wave import speech_recognition as sr CHUNK = 1024 r = sr.Recognizer() r.energy_threshold = 4000 # obtain audio from microphone #source = sr.Microphone(device_index=None, sample_rate=16000, chunk_size=CHUNK) #with source: with sr.Microphone() as source: #print("Calibrating mic...") # listen fo...
__author__ = 'peace' def parse(): infile = open("source.c", "r") print(outerIfAndBody(infile.readlines())) def recurse(lines): paths = outerIfAndBody(lines) for path in paths: for index, body in path: if len(body ) != 0: path[index] = outerIfAndBody(b...
from pico2d import * import game_framework # import boys_state import title_state import time def enter(): global logo,startedOn startedOn = time.time() logo = load_image('../res/kpu_credit.png') def exit(): global logo del logo #logo = None def draw(): clear_canvas() logo.draw(400, 300) update_canvas() de...
#read a particular line from a file. User provides bothe the line #numbe and the file name file_str = input("Open what file: ") status = True while status: try: input_file = open(file_str) find_line_str = input("Which line (integer): ") find_line_int = int(find_line_str) for count,...
import glob import os classes=['1','2','7'] val='MOT17-13' data_dir='/home/waiyang/crowd_counting/Dataset/MOT17det/train' train_data='/home/waiyang/crowd_counting/keras-yolo3/MOT_train.txt' val_data='/home/waiyang/crowd_counting/keras-yolo3/MOT_val.txt' MOT_sets={} for MOTset in glob.glob(os.path.join(data_dir,"*"))...
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): dummy = ListNode(0) current = dummy while l1 is not None or l2 is not None: if l1 is not None and (l2 is None or l1.val <=...
def string_chunk(*args): if len(args)!=2 or type(args[1]) is not int or args[1]<1: return [] return [args[0][x:x+args[1]] for x in range(0,len(args[0]),args[1])] ''' You should write a function that takes a string and a positive integer n, splits the string into parts of length n and returns them in an array....
import sys import os f = open("C:/Users/user/Documents/atCoderProblem/import.txt","r") sys.stdin = f # -*- coding: utf-8 -*- n = input() digit = len(n) n = int(n) def make753(num): cand = [""] endj = 0 for i in range(num): for j in range(endj,3 ** i + endj): cand.app...
from django.conf.urls import url from .controllers import generate, rearrange, home urlpatterns = [ url(r'^generate$', generate), url(r'^rearrange', rearrange), url(r'^$', home), ]
import boto3 import json def get_lambda_info(): """ function to get lambda configurations """ # choosing ec2 to get region names conn = boto3.client('ec2') regions = [region['RegionName'] for region in conn.describe_regions()['Regions']] func_info = [] # looping thorugh regions f...
import getopt import sys version = '1.0' verbose = False output_filename = 'default.out' print('ARGV :', sys.argv[1:]) options, remainder = getopt.getopt( sys.argv[1:], 'o:v', ['output=', 'verbose', 'version='] ) print('OPTIONS :', options) for opt, arg in options: if opt in ('-o',...
from common.run_method import RunMethod import allure @allure.step("ๆ•™็ ”/ๅœจ็บฟไฝœไธš/ๆžๅธˆ้€šAPP่Žทๅ–็ญ็บงๅˆ—่กจ") def online_homework_getOnlineHomeworkClasses_get(params=None, header=None, return_json=True, **kwargs): ''' :param: urlๅœฐๅ€ๅŽ้ข็š„ๅ‚ๆ•ฐ :body: ่ฏทๆฑ‚ไฝ“ :return_json: ๆ˜ฏๅฆ่ฟ”ๅ›žjsonๆ ผๅผ็š„ๅ“ๅบ”๏ผˆ้ป˜่ฎคๆ˜ฏ๏ผ‰ :header: ่ฏทๆฑ‚็š„header :host: ่ฏทๆฑ‚็š„็Žฏๅขƒ...
###MetabolomicsParser #Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California #Author Nathan Salomonis - nsalomonis@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 #in the Softw...
"""VLAN Tags Class.""" from fmcapi.api_objects.apiclasstemplate import APIClassTemplate from fmcapi.api_objects.helper_functions import validate_vlans import logging import warnings class VlanTags(APIClassTemplate): """The VlanTags Object in the FMC.""" VALID_JSON_DATA = ["id", "name", "type", "data", "desc...
import numpy as np import pandas as pd import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify #?check_same_thread=False engine = create_engine("sqlite:///Resour...
# -*- coding: utf-8 -*- from __future__ import print_function import time import numpy as np import OpenGL.GL as gl import OpenGL.GLU as glu import pygame #local imports import resources from common import SETTINGS, COLORS from screen import Screen class TextDisplay(Screen): def __init__(self, ...
import subprocess def getip(): # Set up the interfaces we are looking for interfaces= {"wlan0:":"none"} # Get the network interfaces #ifconfig=subprocess.Popen("ifconfig", shell=True, stdout=subprocess.PIPE).stdout.read() ifconfig=subprocess.check_output("ifconfig",shell=True).decode("utf-8") # Go through th...
# Import models from mmic_docking.models import InputDock from mmelemental.models import Molecule from mmic_autodock_vina.models import AutoDockComputeInput # Import components from mmic.components.blueprints import GenericComponent from mmic_cmd.components import CmdComponent from mmelemental.util.units import conve...
import requests import lxml.html import sqlite3 class crawer: def __init__(self): self.base_list_url = 'https://www.melon.com/mymusic/playlist/mymusicplaylist_list.htm?memberKey=41920075' self.header = { 'User-Agent' : 'Mozilla/5.0'} self.init_playlist_url = [] self.detail_play...
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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, ...
# -*- python -*- # Assignment: Car # Create a class called Car. # In the__init__(), allow the user to specify the following # - attributes: # - price # - speed # - fuel # - mileage # # If the price is greater than 10,000, set the tax to be 15%. # Otherwise, set the tax to be 12%. # # Create six different inst...
import os from datetime import datetime from flask import Flask, request, flash, url_for, redirect, \ render_template, abort, send_from_directory, jsonify, session import pymongo app = Flask(__name__) app.config.from_pyfile('flaskapp.cfg') @app.route("/", methods=['GET', 'POST']) def hello(): try: c...
from keras.engine import Model import numpy as np from keras.preprocessing import image from keras.applications.resnet50 import ResNet50, preprocess_input import argparse from os import path, listdir, makedirs def create_model(): model = ResNet50(include_top=False, input_shape=(224, 224, 3), weights=None, pooling...
from os import system from colorama import Fore from subprocess import check_output system('cls') print(Fore.GREEN + """ โ–‘โ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘ โ–‘โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•—โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–‘โ•šโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘ โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–‘โ•šโ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•šโ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘ โ–‘โ–‘โ•šโ–ˆโ–ˆโ•”โ•โ–‘โ•šโ–ˆโ–ˆโ•”โ•โ–‘โ–‘โ–‘โ–‘โ–‘...
def calc(x): total1 = ''.join(str(ord(i)) for i in x) total2 = total1.replace('7','1') return sum(map(int,total1))-sum(map(int,total2)) ''' Given a string, turn each letter into its ASCII character code and join them together to create a number - let's call this number total1: 'ABC' --> 'A' = 65, 'B' = 6...
# 1ใ€ไธ่ƒฝ # 2ใ€่ƒฝ # 3ใ€ๅญ—็ฌฆ่ฝฌASCII็ ๏ผŒord() # ASCII็ ่ฝฌๅญ—็ฌฆ๏ผŒchr() # 4ใ€่ฟ็ฎ—ๅญ—็ฌฆไธฒ๏ผŒ็„ถๅŽ่ต‹ๅ€ผ็ป™ๅฆไธ€ไธชๅ˜้‡ # 5ใ€ s = 's,pa,m' s = s.split(',') print(s[1]) # 6ใ€ print(len('a\nb\x1f\000d'))
import unittest from poker.card import Card from poker.validators import StraightValidator class StraightValidatorTest(unittest.TestCase): def setUp(self): self.three_of_clubs = Card(rank = "3", suit = "Clubs") self.four_of_diamonds = Card(rank = "4", suit = "Diamonds") self.five_of_spades...
import json from pandas import DataFrame from pprint import pprint from binance import Binance from datetime import datetime def timestamp_to_real_time(ts): return datetime.utcfromtimestamp(ts / 1000).strftime('%Y-%m-%d %H:%M:%S') def get_profit_details(coin): coin_name = coin[:-3] # get all orders ...
from django import forms from django.contrib.auth import get_user_model User = get_user_model() class ContactForm(forms.Form): fullname=forms.CharField(widget=forms.TextInput( attrs={"class":"form-control","placeholder":"full name"})) email=forms.EmailField( widget=forms.EmailInput(attrs={"class":"form-...
import numpy as np import cv2 as cv from matplotlib import pyplot as plt from os.path import join class Hsv: def __init__(self, filename, path=None): if path: print('fname in hsv ', join(path, filename)) self.img = cv.imread(join(path, filename)) else: self.img = cv.imread(filename) def to_hsv(s...
wordList = [] pageList = [] while 1: words, pageNum = input().split(' ') wordList.append(words) pageNum.append(pageNum) wordList.sort()
# libraries import os import requests import time import pyaudio import RPi.GPIO as GPIO # interface from interface.lights import Lights # recording from record import Record # ordering from ordering.speech_processing import SpeechProcessing import ordering.speech_processing_threads as SpeechProcessin...
# Copyright 2017 datawire. 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 law or agr...
# x = "sajjad" # for item in x: # print(item) # y = ("sajjad", "Parvane") # for item in y: # # print(item) # z = ["Sajjad","Parvaneh"] # for item in z: # print(item) w = { "sajjad": { "name" : "sajjad", "age" : "37", "genfer" : "male" }, "parvane":"female" } for item in ...
#!/usr/bin/python #coding=utf-8 import re import json def redict(regex, words): r = re.compile(regex) match_words = filter(r.match, words) return match_words if __name__ == '__main__': dic = json.loads(open('dict.json', 'r').read()) words = set(dic.keys()) print map(lambda word: {word:dic[wo...
from collections import defaultdict, deque, Counter from heapq import heapify, heappop, heappush import math from copy import deepcopy from itertools import combinations, permutations, product, combinations_with_replacement from bisect import bisect_left, bisect_right import sys def input(): return sys.stdin.readl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from netCDF4 import Dataset, num2date # to work with NetCDF files from os.path import expanduser import matplotlib.pyplot as plt import xarray as xr import glob, os import numpy as np import matplotlib import matplotlib.pyplot as plt import matplot...
#!/usr/bin/env python # Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that extra filters are pruned correctly for Visual Studio 2010 and later. """ import TestGyp test = TestGyp.TestGyp(formats=...
#!/usr/bin/env python3 import paho.mqtt.client as mqtt # This is the Subscriber def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("devices/MyDevice/sensors/TC1/value") def on_message(client, userdata, msg): print("new value!") print(msg.payload.decode...
# Generated by Django 3.0.3 on 2020-06-11 21:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dimensoes', '0016_auto_20200611_1852'), ] operations = [ migrations.RenameField( model_name='clientemodel', old_name='numero...
import re, htmlentitydefs # # Remove entities (html or xml) form the input # based on http://effbot.org/zone/re-sub.htm#unescape-html # def unescapeEntities(xmlText): def replaceEntities(matchObject): text = matchObject.group(0) if text[:2] == "&#": # character reference tr...
#!user/bin/env python ################################################################################ # File: object_library.py # Author: Vikram Prasad # Date: January 25, 2018 # Desc: This file defines all the class objects needed for the spending # tracker. ##################################...
"""This module handles execution of job tasks. """ import logging from functools import partial as build_func logger = logging.getLogger(__name__) def task_callback(loop, task, tasks, task_map, future): """Gets called when a task has finished executing. Determines whether the result produced by the task is a m...