text
stringlengths
8
6.05M
# LEVEL 1 # http://www.pythonchallenge.com/pc/def/map.html scrambled = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." new = "" first = ord('a') last = ord('z') ...
import redis as rd import json class User: def __init__(self, id): self.id = id self.cache = rd.StrictRedis() def save_thumbs_change(self, track_id, change): try: data = self.get_data() except AttributeError: # must be no data yet d...
##ok so i'm gonna make 5 functions to draw things; ##circle, rectangle, python logo, and star, and then i make one up ##[probably my name]. ##then all i need is a loop ## to make the program ask if they have a picture they wanna draw, ##a loop inside that asking what picture, ##a try/except block to try to open the ...
#!/usr/bin/env python from os.path import join from functools import partial import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits import basemap import netCDF4 as nc4 from e3sm_case_output import E3SMCaseOutput, day_str abs_cmap = plt.get_cmap('BuGn') cmap = ...
""" Pick ith Ball after Arranging Given the radius and color of ‘n’ balls and an index ‘i’, write a C++ program to arrange them in ascending order as per their volume and when volumes of two balls are same arrange them as per their name. After arranging, print the details of the ith ball. For example, when five balls a...
# Dessa bibliotek används för att förenkla livet from gpiozero import Device, LED, PWMLED, Button from gpiozero.pins.mock import MockFactory from unittest.mock import Mock import pygame.mixer as mixerenhet import time import sys from cowsay import kitty as säger if sys.platform == 'darwin': Device.pin_factory = Mo...
#Coastal Engineering Design Package #Title: Wave Mechanics #Author: Francisco Chaves #Version 0.00 #First Created: 21.12.2015 #Latest Edit: 21.12.2015 #Description: import datetime # By default, MyTime is set to today's date, but it can be set to any other date. class MyTime(): def __init__(self): self.year = da...
t_ctr = t = inc = total = 0 while t_ctr <= 1_000_000: s = str(t) t += (inc+1) inc += 1 t_ctr += 1 for _ in range(len(s)): if int(s)**0.5 == int(int(s)**0.5): total += 1 break s = s[1:]+s[0] print(total)
import redis class Test: def __init__(s, collector, test, participant): s.collector = collector s.test = test s.participant = participant s.counter = 0 def error(s, msg): s.__report('error', msg) def warning(s, msg): s.__report('warning', msg) def ok(s...
#---------------------- Import packages as per the requirement----------------------- import json import datetime import time import os import dateutil.parser import logging import boto3 import re import requests #import pymssql #from datetime import datetime import urllib import urllib2 from botocore.exceptions impor...
''' rule_handler.py Copyright 2013 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af is distributed in the hope tha...
# Реализуйте дек с динамическим зацикленным буфером. # Для тестирования дека на вход подаются команды. # В первой строке количество команд. Затем в каждой строке записана одна команда. # Каждая команда задаётся как 2 целых числа: a b. # a = 1 - push front, # a = 2 - pop front, # a = 3 - push back, # a = 4 - pop ba...
#! /usr/bin/env python3 # ---------------------------------------------------------------------------- # # check_solvable.py # # # # By - jacksonwb ...
def solution(s): answer = [] A = list(map(int, s.split())) answer.append(str(min(A))) answer.append(str(max(A))) # str(min(A) + ' ' + max(A)) # join은 리스트의 자료형이 str이어야함 return ' '.join(answer)
#!/usr/bin/env python ''' Regular Expressions Exercise 3: Given the spec-* files in the data/ directory, write a script that uses regular expressions to list the three numbers in each filename to a new file where the values are tab delimited, e.g. 4055 55359 0001 Hint: Look up the Python module "glob". ''' import ...
from os import environ class Config: # Database db_uri = environ.get('SQLALCHEMY_DATABASE_URI') db_epic_table = environ.get('SQLALCHEMY_EPIC_TABLE') db_jira_table = environ.get('SQLALCHEMY_JIRA_TABLE') # JIRA jira_username = environ.get('JIRA_USERNAME') jira_api_key = environ.get('JIRA_A...
import argparse def swapcase_decorator(gen): def wrapper(*arg, **kwargs): for i in gen(*arg, **kwargs): yield i.swapcase() return wrapper @swapcase_decorator def duplicate_words_gen(file_path): with open(file_path, 'r') as f: content = f.read() def filter_func(s: str): ...
# Juice Front Middleware. This module contains a set of classes that could be # used as middleware to Django. import tidy import django.conf # The Tidy middleware prettifies HTML markup, can remove broken validation # and a bunch of other cool stuff. This certainly gives a slight impact on # performance, but if your ...
""" Generic tools for distributing computationally intensive tasks across multiple threads. """ import os import numpy as np import shutil from tempfile import mkdtemp import multiprocessing as mp from tqdm import tqdm from hylite import HyCloud, HyImage from hylite import io def _split(data, nchunks): """ S...
from __future__ import division import pandas as pd import Bio from Bio.PDB import * import urllib2 import os import shutil import sys import subprocess from ete3 import Tree import copy from blosum import * from Bio.Blast import NCBIWWW from Bio.Blast import NCBIXML from Bio import SeqIO from Bio.Align.Applications im...
'''module for item catalog db handlers''' from flask import session as login_session from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Catalog, Base, CatalogItem, User db_session = None def SetupDB(): engine = create_engine('sqlite:///ItemCatalog.db') # Bi...
import getopt import socket import sys import os import platform from nfutil import * from enumip import * #----------------------------------------------------------------------------- def usage(): print print "Usage: nfcli --list --eth_addr=ADDR --ip_type=TYPE --ip_addr=IP, --netmask=MASK, --gat...
__version__ = '0.38.0'
# Implement function ToLowerCase() that has a string parameter str, # and returns the same string in lowercase. class Solution: def toLowerCase(self, s) -> str: return s.lower() if __name__ == '__main__': test_input = 'HelLo' print(Solution.toLowerCase(Solution, test_input))
""" Tools for MD scripts """ import pytraj as pt import MDAnalysis as mda import os from typing import Optional, Tuple default_mask = "" def load_traj_mda(itraj: str, itop: Optional[str] = None) -> mda.Universe: """ Load trajectory (and topology) from file. Args: itraj (str): Trajectory file n...
# Problem Statement : # 9.4 Write a program to read through the mbox-short.txt and figure out who has # sent the greatest number of mail messages. The program looks for 'From ' lines # and takes the second word of those lines as the person who sent the mail. The # program creates a Python dictionary that maps the sen...
import io import json import os import sys from . import sources class TR(object): def __init__(self, source): self.source = source @classmethod def main(cls, argv=None): if argv is None: argv = sys.argv[1:] source = get_source(argv[0]) tr = cls(source) ...
# encoding: utf-8 """ @ author: wangmingrui @ time: 2019/1/30 16:32 @ desc: 配置文件 """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # client的根目录 HOME_DIR = os.path.join(BASE_DIR, 'user_data','HOME') MAX_RECV_SIZE = 1024 * 8 USER_QUATO = 1024 * 1024 * 1024 * 10 # 初始用户配额为10G HOST ...
from django.db import models # Create your models here. class Carro(models.Model): nombre = models.CharField(max_length=50) precio = models.FloatField(default=1) año = models.IntegerField(default=20)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree...
class cpairs: def __init__(self, l, w): self.l = l self.w = w def __eq__(self, other): if not isinstance(other, cpairs): return NotImplemented return (self.l == other.l and self.w == other.w) or (self.l == other.w and self.w == other.l) def __hash__(self): ...
from pyfiglet import figlet_format from halo import Halo import time from datetime import datetime, timedelta import pygame from functions.get_conjectures import get_conjectures, remove_duplicates import pickle valid_invariants = {1:'domination_number', 2:'total_domination_number', ...
# Copyright (c) 2012 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. # Test that the case where an action is only specified under a conditional is # evaluated appropriately. { 'targets': [ { 'target_name': 'extension_doe...
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib2 import hashlib import json import time import datetime import datamodel as dm from apiconfig import APIConfig class WetterCom: def getDateStr(self, delta_days): #create time string of the following format: "yyyy-mm-dd" today = datetime.date...
from models.dilated_resnet import resnet101 model = resnet101(pretrained=True) print(model)
from __future__ import unicode_literals from django.db import models class ChallengeTimestamp(models.Model): """ Challenge Timestamp model class. """ team = models.ForeignKey('team', on_delete=models.CASCADE, related_name='challenge_timestamps', related_query_name='challenge_timestamp') challenge = m...
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @Time : 2019/11/5 22:44 @Author : Jason.Jia @contact: jiajunp@163.com @Version : 1.0 @file :handlers.py @desc : ''' from tkinter import * import pymysql
from daos.erequest_dao import ErequestDAO from exceptions.resource_not_found import ResourceNotFound from utils.connection_util import connection from typing import List from abc import ABC from entities.erequest import Erequest class ErequestDaoPostgres(ErequestDAO): def get_all_requests_by_eid(self, employee_i...
import pickle import json import time def to_json(python_object): if isinstance(python_object, time.struct_time): return {'__class__': 'time.asctime', '__value__': time.asctime(python_object)} if isinstance(python_object, bytes): return {'__class__': 'bytes', '__...
import openrouteservice as ors import folium #import GDest, geocodeing_2 ors_key = '5b3ce3597851110001cf62486905683bd4754a8c8c22017f27414546' ###################### Origin lat&lng #print(geocodeing_2.ORG_lat,geocodeing_2.ORG_lng) ##################### Destination lat&lng #print(GDest.DST_lat, GDest.DST_lng) ...
class DivergentSolution(Exception): """Raised when a calculated solution does not converge""" def __init__(self, solver_name, *args: object) -> None: super().__init__(("%s solution is divergent!" % solver_name), *args) class SolutionValidation(Exception): """Raised when a calculated solution does...
#!/usr/bin/env python3 """ Lambdas are anonymous functions, similar to lambdas in Scheme or JavaScript. It is pretty much just a function without a name. Super simple! The syntax: create a lambda function: lambda <parameter>: <expression> create and execute a lambda: (lambda <parameter>: <exp...
import torch from torch.utils.data import Dataset import cv2 from PIL import Image from torchvision import transforms, utils import matplotlib.pyplot as plt from sklearn import preprocessing import ast def create_inout_sequence(input_data, i, tw): train_seq = [seq[0] for seq in input_data[i:i+tw]] train_lab...
import random from typing import Callable def findAnyInSet(source: set, predicate: Callable[..., bool]): try: return random.choice([item for item in source if predicate(item)]) except IndexError: return None def findFirstInSet(source: set, predicate: Callable[..., bool]): return next(i...
from tkinter import * from PIL import ImageTk, Image import shutil import os from tkinter import filedialog from tkinter import messagebox as mb import easygui # Major functions of file manager # open a file box window # when we want to select a file def open_window(): read=easygui.fileopen...
from random import randint ''' 该方法传入两个参数 lst:当前待排序列表 reserve 若不传值,默认为True reserve = True 从大到小排列 reserve = False 从小到大排列 ''' def bubbleSort(lst, reverse=True): # 获取列表长度 length = len(lst) for i in range(0, length): for j in range(0, length - i - 1): # 比较相邻两个元素大小,并根据需要进行...
# 我的sb解法 # 因为python string 不可变所以必须得有个额外的结果数组 class Solution: def reverseWords(self, s: str) -> str: temp = s.split(' ') temp.reverse() temp = [x.strip() for x in temp if x.strip() != ''] print(temp) return ' '.join(x for x in temp) class Solution: def reverseWords(self, ...
from flask import Blueprint, jsonify, request from ..services.news_service import NewsService import time import datetime import json news_bp = Blueprint('news_routes', __name__, url_prefix='/api/v1/news') news_service = NewsService() @news_bp.route('', methods=['POST']) def save_news(): articles = request.g...
''' We create the fibonacci sequence below. As a refresher, the fibonacci sequence is a recursive sequence in which the last/most-recent term is a sum of the previous two terms Here instead, we implement MEMOIZATION using built-in python tools to make memoization trivial ''' from functools import lru_cache # lru cache ...
from openpyxl import worksheet from openpyxl.utils import get_column_letter from src.core import config from src.utils import connect_to_wb @connect_to_wb def save_to_excel( ws: worksheet, cleared_dict: dict, offset: int, exchange: str, ) -> None: ws.cell( column=offset + 1, row=1...
#Code to find the permutations of a string def swap( a, b): temp=a a=b b=temp
import re pattern = r"(=|\/)([A-Z][A-Za-z]{2,})\1" locations_on_map = input() travel_points = 0 valid_locations = re.findall(pattern, locations_on_map) destinations = [] for valid_location in valid_locations: destination = valid_location[1] travel_points += len(destination) destinations.append(destinatio...
import sys import os import logging from datetime import datetime # Logging Levels # https://docs.python.org/3/library/logging.html#logging-levels # CRITICAL 50 # ERROR 40 # WARNING 30 # INFO 20 # DEBUG 10 # NOTSET 0 logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(...
# -*- coding: utf-8 -*- import sys,os,time from test44 import clss class cls2: t= None def __init__(self): print 'cls2' def p2(self): c= clss() print c.t
import sqlalchemy from sqlalchemy_serializer import SerializerMixin from database.data import db_session class Lesson(db_session.SqlAlchemyBase, SerializerMixin): __tablename__ = "lessons" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True) name = sqlalchemy.Column(sqlalchemy...
""" The fields module provides a number of data structures and functions to represent continuous, spatially varying data. All fields are subclasses of `Field` which provides abstract functions for sampling field values at physical locations. The most important field types are: * `CenteredGrid` embeds a tensor in the...
liste = [] n = 0 a = 0 i = 0 k = 0 max = 0 min = 20 snote = 0 moyenne = 0 while a == 0 : print("entrez une note :" , end = "") n = int(input()) liste.append(n) print("il y a " , len(liste), "note(s)") while i < len(liste): if liste[i] > max: max = liste[i] if liste [i]...
from random import randint num = int(input('Write numbers from 1 to 3 which are: 1-stone, 2-scisores, 3-paper: ')) num2 = randint(1, 3) if num == num2: print(f'Computer draws {num2}. Draw') elif num == 1 and num2 == 2: print(f'Computer draws {num2}. You win!') elif num == 1 and num2 == 3: print(f'Computer...
def portrayCell(cell): ''' This function is registered with the visualization server to be called each tick to indicate how to draw the cell in its current state. :param cell: the cell in the simulation :return: the portrayal dictionary. ''' assert cell is not True return{ 'Shar...
import unittest import HtmlTestRunner from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from fixtures.params import CHROME_EXECUTABLE_PATH, DOMAIN, JPG_500_kb_path, Pdf_file_pa...
__author__ = 'luca' from PyQt4.QtCore import * from PyQt4.QtGui import QPixmap class QFramesTimelineListModel(QAbstractListModel): def __init__(self, video): self.video = video self.pixmaps = {} super(QFramesTimelineListModel, self).__init__() def rowCount(self, parent): retu...
import sqlite3 import json import base64 import tornado.ioloop import tornado.web def b64ToNormal(inputStr : str)->str : if inputStr=="": return "" return base64.b64decode(inputStr.encode("ascii")).decode("ascii") def normalTob64(inputStr :str)->str : if inputStr=="": return "" return ...
#!/usr/bin/python3 def max_integer(my_list=[]): if not my_list: return None maxim = my_list[0] for i in range(len(my_list)): if my_list[i] > maxim: maxim = my_list[i] return maxim
from django.shortcuts import render, redirect from rest_framework import viewsets, serializers from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib.auth.decorators import login_required from datetime import datetime from .models import Scan, Peserta from akun...
TABLE_SCHEMA = ( 'IDKEY:STRING, ' 'FECHA:STRING, ' 'ANO:STRING, ' 'DIA:STRING, ' 'MES:STRING, ' 'FECHA_GRABACION:STRING, ' 'TIPO_CLIENTE:STRING, ' 'GRABADOR_PAGO:STRING, ' 'CENTRO_DE_COSTOS:STRING, ' 'ESTADO_CARTERA:STRING, ' 'PROXIMO_A_REPORTE:STRING, ' 'VALOR_PAGADO:STRING, ' 'OBLIGACION:STRING, ' 'INIC...
from abc import ABCMeta, abstractmethod class IRepositoryCloner(object): """ Interface for classes implementing cloning-functionality for different repository-types. """ __metaclass__ = ABCMeta @abstractmethod def clone_repositories(self, repository_set: set) -> None: """ Clon...
from rest_framework import serializers class SampleSerializer(serializers.Serializer): name = serializers.CharField() count = serializers.IntegerField()
from functools import reduce import inspect def _attr_category(x): if x.startswith('__') and x.endswith('__'): return '"magic"' if x.startswith('__'): return 'mangling' if x.startswith('_'): return 'internal' if x.endswith('_'): return 'conflict' return 'public' def...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Tan Chao' ''' logger wrapper. ''' import logging import logging.config import sys def test_logging(): """ learn how to use logging """ logging.basicConfig( level=logging.DEBUG, format='[%(asctime)s] %(filename)s[line:%(lineno)d][fun:%(funcName)s...
class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: res = [] def traverse(root): if root: res.append(root.val) traverse(root.left) traverse(root.right) return traverse(root1) ...
import numpy import numpy.random import smat import smat.util import argparse import scipy.optimize parser = argparse.ArgumentParser(description="Train a 784-1000-1000-10 neural net on MNIST and print out the error rates.") parser.add_argument("-d","--device",type=int,default=None,help="The device to use, e.g. CUDA de...
#Bullet Time!!! 90 degrees GIF import time import sys import requests import re import urllib import os from wireless import Wireless #Iniciando la clase para conexion con camaras wifi = Wireless('wlan0') #Lista con ssid de camaras cameras = ['Bullet_5', 'Bullet_6'] #Funcion para descargar las ultimas 10 imagenes ...
one_list = [i for i in [1, 4, 5, 8, 6, 12, 14] if ( i % 3 == 0 and i > 0 and i % 4 !=0 )] print(one_list)
# 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 # 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成: # (1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。 # (2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。 # (3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。 from sys import stdout from pip._vendor.distlib.compat import raw_input n = int(raw_input("请输入正整数 : ")) ...
#! /bin/env python # coding:utf-8 # # Read tweets in json fils, and create a corpus for each json. # #import create_corpus as cc import mecab_inc as mi import numpy as np import random import sys reload(sys) sys.setdefaultencoding("utf-8") file_name = 'tweets/new_A.txt' #file_name = 'tweets/test_data.txt' k = 10 #n...
import load import model import numpy as np import args import os def clean_data(data): def _find_bound(np_array, l_num, u_num): sorted_np_array = np.sort(np_array) return sorted_np_array[l_num],\ sorted_np_array[u_num],\ np.mean(sorted_np_array[l_num+1:u_num]) def _chec...
import multiprocessing import os def print_task(task1, task2): print task1, task2, 'done in process %s' % os.getpid() tasks = ['Alice', 'Bob', 'Cat', 'Dog'] pool = multiprocessing.Pool(processes=4) for i in range(len(tasks)): pool.apply_async(print_task, args=(tasks[i],tasks[i], )) pool.close() pool.join()...
# This file is part of beets. # Copyright 2016, Adrian Sampson and Diego Moreda. # # 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 righ...
#!/usr/bin/env python from sys import argv from daemonize import Daemonize pid = argv[1] working_dir = argv[2] file_name = argv[3] def main(): with open(file_name, "w") as f: f.write("test") daemon = Daemonize(app="test_app", pid=pid, action=main, chdir=working_dir) daemon.start()
# Generated by Django 2.0 on 2019-04-29 07:18 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
#!/usr/bin/python3 import pylab as pl import scipy as sp import numpy as np from scipy import ndimage img = pl.imread("converse3s.png") s = img.shape img2 = ndimage.sobel(img) img3 = ndimage.median_filter(img2, 5) wLeft = -3 wRight = 3 wBottom = -3 wTop = 3 thresholdMin = 49*0.2 thresholdMax = 49*0.4 img2 = np.copy(...
from datetime import datetime from .models import Event from rest_framework import generics from .serializers import DetailEventSerializer, ListEventSerializer from .pagination import EventsResultsPagination # Create your views here. class ListEventView(generics.ListAPIView): current_date = datetime.now().date() qu...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from typing import Type import pytest from pants.build_graph.build_configuration import BuildConfiguration from pants.build_graph.build_file_aliases import BuildFileAliases from pants.en...
# encoding: utf-8 """ @author: l1aoxingyu @contact: sherlockliao01@gmail.com """ import logging from fastai.vision import * from .callbacks import * def do_train( cfg, model, data_bunch, test_labels, opt_func, lr_sched, loss_func, num_query, ): eval...
from __future__ import division from astropy.io import ascii import os import numpy as np ifl = ascii.read("bb_and_4s_pars.txt", header_start = None, comment = '#') print ifl create_file = "echo \"\" > table10.txt" os.system(create_file) ofile = open("table10.txt", 'r+') tab = [] for i in range(0,len(ifl['col1'...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Adapted from: - http://www.djangosnippets.org/snippets/764/ - http://www.satchmoproject.com/trac/browser/satchmo/trunk/satchmo/apps/satchmo_utils/views.py - http://tinyurl.com/shoppify-credit-cards """ from __future__ import unicode_literals import re # We...
import requests from copy import deepcopy class InvokeManager(): def __init__(self, address, fileManager): self.address = address self.fileManager = fileManager def invoke(self, name, param, default_conf_class, except_conf={}, log=True, filePath="", paramID="", optimise=True): newparam...
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import spi, sensor from esphome.const import CONF_ID, ICON_EMPTY, UNIT_EMPTY DEPENDENCIES = ['spi'] empty_spi_sensor_ns = cg.esphome_ns.namespace('empty_spi_sensor') EmptySPISensor = empty_spi_sensor_ns.class_('EmptySPISensor'...
import requests import pymongo from splinter import Browser from bs4 import BeautifulSoup from webdriver_manager.chrome import ChromeDriverManager import pandas as pd def init_browser(): # Set up splinter executable_path = {'executable_path':ChromeDriverManager().install()} return Browser('chrome', **execu...
from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = staticfiles_urlpatterns() admin.autodiscover()
#Author Gayatri Deo import nltk; import sys; from nltk.corpus import wordnet as wn; def printDef(category): for f in wn.synsets(category): for hypo in f.hyponyms(): for hypo1 in hypo.hyponyms(): print category, ",", hypo1.name.split('.')[0], ",", hypo1.definition; ...
import serial __author__ = 'wgiersche' if __name__ == "__main__": serial = serial.Serial(port="/dev/tty.RNBT-37D2-RNI-SPP", baudrate=9600, timeout=0) num = 0 while num < 100: num += 1 line = serial.readline() if line: print line
#!/usr/bin/env python3 from rpgdieroller.dierolls import * import cmd class DieRollerShell(cmd.Cmd): intro = ( "Welcome to the Python RPG Die Roller shell. Type help or ? to list commands.\n" ) prompt = "(RPG Die Roller) " def do_roll(self, arg): "Roll the dice for an expression lik...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """Contains the "base" code for plugin APIs which require partitioning.""" from __future__ import annotations import itertools from dataclasses import dataclass from enum import Enum fro...
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> a="Python" >>> a[0] 'P' >>> a[1] 'y' >>> a[-1] 'n' >>> a[1:3] 'yt' >>> a[0:4] 'Pyth' >>> a[ : ] 'Python' >>> a[ :4] 'Pyth' >>> a[2: ] 'thon' >>> ...
from .solve_neon_eq import ymat_pretty as neon_betas from .fit_pad import TargetHeliumPad, TargetNeonPad from .solve_helium_eq import ymat_pretty as helium_betas __all__ = [ "helium_betas", "neon_betas", "TargetHeliumPad", "TargetNeonPad", ]
# Parses HTMLS for juicy hrefs import requests import config from lxml import html from knowlify import worker DATA_DIR = config.DATA_DIR def get_page_from_web(url): """ :type url: str :return: HTML file from string :type page: html.HtmlElement """ try: page = html.document_fromstri...
/Users/samnayrouz/anaconda3/lib/python3.6/shutil.py
GREEN = '\033[92m' RED = '\033[91m' BLUE = '\033[94m' YELLOW = '\033[93m' ENDC = '\033[0m' UNDERLINE = '\033[4m' BOLD = '\033[1m' WHITE = '\033[97m' MAGENTA = '\033[95m' GREY = '\033[90m' BLACK = '\033[90m' DEFAULT = '\033[99m' class Color: def success(self, text): self.green(text) def error(self, t...