text
stringlengths
8
6.05M
#!/usr/bin/env python3 import json from pathlib import Path from natsort import natsorted # load_test_cases {{{1 def load_test_cases(families=None): root_dir = Path(__file__).parent.parent test_dir = root_dir / 'test_cases' test_cases = [ TestCase(d) for d in natsorted(test_dir.ite...
from django.db import models from safedelete.config import SOFT_DELETE from safedelete.models import SafeDeleteModel, SOFT_DELETE_CASCADE import datetime from clients.models import Client from users.models import User from .managers import ImportManager class Import(SafeDeleteModel): _safedelete_policy = SOFT_DE...
import networkx as nx import matplotlib.pyplot as plt G=nx.complete_graph(3) #create complete graphs of 3 nodes print(G.nodes) #print the name of edges nx.draw(G) plt.show()
import numpy as np from scipy.optimize import minimize_scalar from scipy.integrate import odeint from scipy import interpolate from scipy.interpolate import interp1d #Definition of the potential. def pot(phi, params): model, M, gamma, alpha, Omega_M, Omega_R = params term_1 = M**2*np.exp(-gamma) exponent...
import sys import scanf import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import seaborn as sns import bow_projection as bp import standing_wave try: BASE_SHAPE_ID = sys.argv[1] except: sys.exit(f"Usage: {sys.argv[0]} BASE_SHAPE_ID") fileroot = sys.argv[0].replace('.py'...
%load_ext autoreload %autoreload 2 import sys sys.path.append(r'C:\Users\Luke\Documents\qn\py') import os os.chdir(r'D:\Qiaonan Working\projects\milestones\chart\organizeData') import qn coll = qn.getcoll('milestones',db="LINCS",inst="loretta",u="readWriteUser", p="askQiaonan")[0] categoryMap = {} deferredDocs =...
#!/usr/bin/env python # -*- coding: utf-8 -*- import mysql.connector from sgmllib import SGMLParser from HTMLParser import HTMLParser import urllib2 import os import re from Site import * from Card import * from Edition import * from Price import * url="http://www.magiccorporation.com/gathering-cartes-edition-170-t...
import re import subprocess def run_the_function(repeat, width, print_result): #subprocess.call('LD_LIBRARY_PATH="/dls_sw/prod/tools/RHEL6-x86_64/hdf5/1-8-15/prefix/lib"', shell=True) #subprocess.call('HDF5_DISABLE_VERSION_CHECK="1"', shell=True) # repeat = 5; # width = 1024 * 55 program_to_e...
import unittest from katas.kyu_8.opposites_attract import lovefunc class LoveTestCase(unittest.TestCase): def test_true(self): self.assertTrue(lovefunc(1, 4)) def test_true_2(self): self.assertTrue(lovefunc(0, 1)) def test_false(self): self.assertFalse(lovefunc(2, 2)) def t...
import typing from direct.actor.Actor import Actor from panda3d.core import CompassEffect, ClockObject, Point3 from panda3d.core import CollisionBox, CollisionSegment, CollisionNode, CollisionRay from panda3d.core import CollisionHandlerPusher, CollisionHandlerQueue, CollisionTraverser cam_pivot_z_value: float = 3.0 ...
# how to find help documentation * help func * numpy.lookfor('function', module='module_name') numpy.lookfor('remove', module='os')
class Solution: def kill_switch(self, input): def split_lists(left,right=[],difference=0): left_sum = sum(left) right_sum = sum(right) if left_sum < right_sum or len(left) < len(right): return if left_sum - right_sum...
import sc2 from sc2 import Race, Difficulty from sc2.constants import * from sc2.ids.unit_typeid import * from sc2.ids.ability_id import * from sc2.player import Bot, Computer from sc2.unit import Unit from sc2.units import Units from sc2.position import Point2, Point3 # i just copied over my import statements because ...
# Day 18: Operation Order # <ryc> 2021 def inputdata(): with open('day_18_2020.input') as stream: data = [ line for line in stream ] return data def calculate(stream, functions): stream = list(stream) stack = list() operators = ['('] while len(stream) != 0: token = stream.p...
# Conditional Statements mivalor = 7 if mivalor == 2: mivalor = 5 if mivalor == 5: mivalor = 4 print(mivalor) else: mivalor = 2 else: mivalor = 8 print(mivalor) def multiplo_raro(a): if a == 2: res = a*a+1 elif a == 3: res = a+a-1 elif a == 7: ...
import pandas as pd path = 'C:/Users/13781/Desktop/学生信息表.xlsx' c=pd.read_excel(path,sheet_name=1) print(c) print(pd.show_versions())
UNKNOWN = '░' MINE = '©' CURSOR = '█'
import wx import cv2 import numpy """ Next steps: - Show histogram for each image. - Create histogram widget. - Ability to load multiple images. Goal: ------------ | Load Images ------------ | Image 1 | Image 2 | Image 3 | Operation | Run | Show Result | | Result 1 | Result 2 | Result 3 | Next Operation |...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from mpl_toolkits.mplot3d import Axes3D USE = pd.read_csv(r"C:\Users\chias\source\repos\FFM-MA\US equities.csv") DMX = pd.read_csv(r"C:\Users\chias\source\repos\FFM-MA\DM ex US.csv") AZE = pd.read_csv(r"C:\User...
import pytest from pyasn1.type.namedval import NamedValues from asn1PERser.codec.per.encoder import encode as per_encoder from asn1PERser.classes.data.builtin.EnumeratedType import EnumeratedType from asn1PERser.classes.types.constraint import ExtensionMarker def SCHEMA_my_enum(enumerationRoot_list, extensionMarker_v...
#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() #channel.queue_purge(queue='task_queue') channel.queue_purge(queue='lightvm_one_files') connection.close()
N=input() set1=set(N)#去掉字符串(或者其它序列)中的重复元素 sum1=0 for i in set1: sum1+=eval(i) print(sum1)
from analyze_design_decoys import fix_file import argparse import design_protease as dp from os import makedirs, remove from os.path import basename, isdir, isfile, join from pyrosetta import * from pyrosetta.rosetta.core.select.residue_selector import \ ChainSelector, OrResidueSelector, ResidueIndexSelector f...
from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("Temperature") sc = SparkContext(conf = conf) def fun(line): fields = line.split(',') station = fields[0] e_type = fields[2] temp = float(fields[3]) return (station,e_type, temp) lines =...
from Crypto.Util import number import gmpy def nth_root(x, n): gs = gmpy.mpz(x) g3 = gmpy.mpz(n) mask = gmpy.mpz(0x8080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000) test = 0 while True: if test == 0: gs = gs ...
from raptor import RaptorQ class Decoder(RaptorQ): def __init__(self, symbols): #Figure out sub-blocks. Basically split up "chunk" so it can fit in memory. Then split that into K pieces. #We'll just use one block for now super(Decoder, self).__init__(symbols) def append(self, symbol):...
# This collects all other helper functions #!/usr/bin/env python """ Copyright 2016 ARC Centre of Excellence for Climate Systems Science author: Paola Petrelli <paola.petrelli@utas.edu.au> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License....
#!/usr/bin/env python # coding: utf-8 # # Taking two numbers as input and print the result of addition,subtraction,multiplication and division # In[7]: x=int(input()) y=int(input()) print ( "sum=", x+y) print ("subtraction=",x-y) print ("multiplication=",x*y) print ("division=",x/y ) # # Taking two numbers X and ...
from __future__ import unicode_literals from django.apps import AppConfig class DjangoAndAjaxConfig(AppConfig): name = 'django_and_ajax'
# models.py import os from flask import Flask from flask_marshmallow import Marshmallow config_name = os.getenv('FLASK_CONFIG') if config_name == 'development': from .. app import db elif config_name == 'testing': from app import db app = Flask(__name__) ma = Marshmallow(app) class User(db.Model): ""...
# Test TCP with Json format # Server from datetime import datetime import socket import struct import json server_address = ('localhost', 6788) max_size = 4096 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(server_address) server.listen(10) sendData = [{ "Veh_id": 0, "result": 0 }, {...
# 数学推导 class Solution: def integerBreak(self, n: int) -> int: if n <= 3: return n-1 a, b = n // 3, n % 3 if b == 0: return int(math.pow(3, a)) if b == 1: return int(math.pow(3, a-1)*4) return int(math.pow(3, a)*2) # 动态规划 # dp[i]表示为i的最大乘积, dp[i]可由d...
NSIDE = 1024 PATH = '/users/dlenz/projects/global_emissivity/'
from tornado.iostream import IOStream from sidl.message import Message from log import logger from connection import Connection import socket class Client(object): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.stream = IOStream(self.sock) self...
import os import luigi import pandas as pd from luigi.contrib.spark import PySparkTask from pyspark import Row from pyspark.sql import SparkSession from bicis.etl.raw_data.split import UnifyRawData from bicis.lib.data_paths import data_dir class NextWindowTarget(PySparkTask): """ Builds a series for each st...
# A number N is abundant if the sum of all its proper divisors exceeds N # By mathematical analysis, it can be shown that all integers greater than # 28123 can be written as the sum of two abundant numbers. # Find the sum of all positive integers which cannot be written as the sum # of two adundant numbers. from m...
from sklearn.model_selection import train_test_split import pandas as pd data = pd.read_csv("diabetes.csv", names=[1,2,3,4,5,6,7,8,9], header=None) X = data[[1,2,3,4,5,6,7,8]] y = data[9] X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=8) """ Logistic Regression """ from ...
from FK import * import serial import math def usage(): print "Usage : input 3 pose parameters." ser = serial.Serial( port='/dev/cu.usbmodem1421', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) ser.isOpen() print 'Enter your commands below.\...
#!/usr/bin/env python3 # # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Incomplete example for working the SerDes-based a PIPE PHY. """ from amaranth import * from luna import top_level_cli from ...
#!/usr/bin/env python # coding: utf-8 """ Utilities for manipulating and correcting OWL files in RDF. """ __all__ = [ "all_restrictions", "is_bad_restr", "describe_bad_restr", "translate_bad_restr", "all_bad_restrictions", "repair_graph", "repair_all_bad_restrictions", "RELATIONS", ...
from Contacts import Contact import operator class AddressBookConsoleService: address_books = {} def create_contact(self): """ Method to create contact object """ contact_dict = { "first_name" : "", "last_name" : "", "address" :...
def tutte_polynomial(G): ... def chromatic_polynomial(G): ...
import json from networkx.readwrite import json_graph def export(G, D3, Sigma, GEXF, name='Graph'): if D3 == True: print("Starting D3 Export for", name) # D3 # Print JSON f = open(name + 'D3.json', 'w') f.write(json_graph.dumps(G)) print("D3 Exported") if Sigma == True: ...
# encoding: utf-8 from __future__ import print_function from __future__ import division from __future__ import absolute_import import os import numpy as np import sklearn as sk from sklearn.cluster import KMeans from sklearn.mixture import GaussianMixture as GMM from sklearn.metrics import silhouette_score as SC fr...
from commonFunctions import takeHttpMethod from commonFunctions import takeJsonFromFile from commonFunctions import takeUrlPath def takeRMQInput(): indirectInput = { 'name': 'rmqIndirectInput', 'queue': raw_input('Enter queue name to load the messages into : ') } messages = [] message...
from data_process.parse_vol_data import parse_vol_data from vol_models.black_cubic import BlackCubic from vol_models.dupire_local import DupireLocal from vol_models.heston_slv import HestonSLV from visualization.visualize_vol_surface import visualize_vol_surface from opts.volmodel_opts import VolModelOpts def black_c...
from Tkinter import * from tkFileDialog import * from tkFont import * import os.path import sys import re from assemblerlib import * basefilename = "Untitled" filename = "" fileexists = False saved = True canvaswidthdefault = 20 canvaswidth = canvaswidthdefault currentlength = 1 mnemonicstring =...
from fares_db import * from user_db import * from userFlights_db import * from helpers import * from privateConstants import * from datetime import datetime # TODO: grep out logs for scraper, runUserFares and Email (once running) usernames = getAllUsernames() usersNoFlights = 0 usernameRank = [] for ...
import argparse import asyncore import logging from Component import Component parser = argparse.ArgumentParser(description="Ircd-component for xmpp servers") parser.add_argument( "--xmpp-host", default="localhost" , dest="xmpp_host" , help="The xmpp-server to connect to" ) parse...
from log import log class Region: def __init__(self, rectange, frame): self.rectange = rectange self.frame = frame def is_car(self): # TODO: return False if primary color indicates region is just headlights return True def to_dict(self): (x,y, height, width) = sel...
from SignalGenerationPackage.SignalController import SignalController from SignalGenerationPackage.UserSignal.UserSignal import UserSignal from SignalGenerationPackage.UserSignal.UserSignalObserver import UserSignalObserver from SignalGenerationPackage.UserSignal.AccelerationTimeCallBackOperator import AccelerationTim...
# -*- coding: utf-8 -*- from typing import List class Solution: def minSubsequence(self, nums: List[int]) -> List[int]: total_sum = sum(nums) nums.sort(reverse=True) current_sum = 0 for i, num in enumerate(nums): current_sum += num if 2 * current_sum > tot...
import os, sys # http://effbot.org/zone/import-string.htm def my_import(name): m = __import__(name) for n in name.split(".")[1:]: m = getattr(m, n) return m def run(D): print 'in run_script.run: ', os.path.basename(__file__) prog = D['prog'] module = my_import("scripts." + prog) p...
""" Deep Lab Cut ============ This module provides an interface between data collected during the reaching task and forepaw coordinates extracted from videos of the task using Deep Lab Cut. This depends on pandas, pytables and h5py. """ import glob import json import os import pickle import pandas as pd import rea...
# Generated by Django 3.1.7 on 2021-02-27 12:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0006_auto_20210226_1819'), ] operations = [ migrations.AlterField( model_name='cart', name='items', ...
items = input().split('|') budget = int(input()) old_price_of_all_items = 0 new_price_of_all_items = 0 CLOTHES_MAX_PRICE = 50 SHOES_MAX_PRICE = 35 ACCESSORIES_MAX_PRICE = 20.50 NEEDED_MONEY_FOR_TICKETS = 150 for i in items: tokens = i.split('->') item_type = tokens[0] price = float(tokens[1]) if budget ...
# coding:utf-8 import matplotlib.pyplot as plt import pandas as pd from pyramid.arima import auto_arima import numpy as np import statsmodels.api as sm from statsmodels.tsa.stattools import adfuller from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.arima_model import ARMA from statsmode...
import argparse import os from time import time from multiprocessing import Pool import random import pydub as pd import numpy as np import scipy.signal as ssi import math def convolve(irfile_path, speech_path, output_path, target_len=1): IR = pd.AudioSegment.from_file(irfile_path) speech = pd.AudioSegment.fr...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import KFold from sklearn.model_selection import GridSearchCV #붓꽃 데이터 읽어들이기 iris_data = pd.read...
# Objective function(s) inspired by filtering problems from microfilter.univariate.expnormdist import ExpNormDist from microfilter.univariate.expnormdist import DEFAULT_EXPNORM_PARAMS, DEFAULT_EXPNORM_LOWER, DEFAULT_EXPNORM_UPPER from microfilter.univariate.noisysim import sim_data from copy import deepcopy from fun...
import json import pandas import cv2 import os, random ''' This script will randomly view one of the image from crowdman dataset with yolo-style label ''' source_img = '/media/n0v0b/m1/dataset/crowdman-raw/val/' source_label = '/media/n0v0b/m1/dataset/crowdman-labels/val/' image_name = random.choice(os.listdir(sourc...
from language import Language from pythonlanguage import PythonLanguage class LanguageFactory: def __init__(self): self.idsToLangs = {1 : PythonLanguage()} def create(self, langId): if (langId in self.idsToLangs): return self.idsToLangs[langId] else: ra...
class Node: def __init__(self, value, next, prev): self.value = value self.next = next self.prev = prev class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def is_empty(self): return self.head == None def prepend(self, val...
import unittest import sbol3 import labop import uml class TestValidationErrorChecking(unittest.TestCase): def test_activity_multiflow(self): """Test whether validator can detect nondeterminism due to activity multiple outflows""" # set up the document print("Setting up document") ...
from __future__ import annotations import numpy as np import neworder import matplotlib.pyplot as plt # type: ignore from matplotlib.image import AxesImage # type: ignore from matplotlib import colors # type: ignore class Schelling(neworder.Model): def __init__(self, timeline: neworder.Timeline, ...
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Endpoint interfaces for providing status updates to the host. These are mainly meant for use with interrupt endpoints; and allow a host to e.g. repeatedly poll a device fo...
from django.contrib import admin from .models import covid_db # Register your models here. admin.site.register(covid_db)
from aiogram import types rz2 = types.InlineKeyboardMarkup( inline_keyboard=[ [ types.InlineKeyboardButton(text="Ring of Aquila", callback_data="Ring of Aquila")], [types.InlineKeyboardButton(text="Imp Claw", callback_data="Imp Claw")], [types.InlineKeyboardButton(text...
# Importar librerias de airflow from airflow import DAG from airflow import models from airflow.operators.python_operator import PythonOperator from airflow.operators.dummy_operator import DummyOperator from airflow.operators.email_operator import EmailOperator from airflow.operators.bash_operator import BashOperator f...
import warnings from chainer.utils import conv import numpy as np from onnx_chainer.functions.opset_version import support from onnx_chainer import onnx_helper @support((1, 7)) def convert_AveragePooling2D( func, opset_version, input_names, output_names, context): pad = [func.ph, func.pw] stride = [...
'''A module that contains functions and classes for manipulating images.''' from collections import namedtuple from PIL import Image Coordinate = namedtuple('Coordinate', ['x', 'y']) BoundingBox = namedtuple('BoundingBox', ['left', 'top', 'right', 'bottom']) class ImageZoomer: '''A class for controlling the bou...
def test_nothing(): return 'gpflow doesn''t even install'
""" The Degree Of Vertex for Undirected Graphs """ def degree_of_vertex(edges): """ Find the Degree of Vertex for all of the edge. Time Complexity: O(n) --> Not a very fast implementation """ dictver = {} count = 0 freq = {} i = 0 j = 0 for i, j in edges: ...
#괄호 문제는 스택 구조로 풀이 from collections import deque def solution(s): answer = 0 deq = deque(s) if len(s) <= 1: return 0 for _ in range(len(s)): deq.rotate(1) check = deque() count = 0 for i in deq: if i in '[{(': check.appendleft(i) ...
#!/usr/bin/env python3 import os import urllib.request import urllib.parse import urllib.error from slugify import slugify from sys import platform from threading import Thread import subprocess import time class Speaker: def __init__(self, sound_directory='sounds'): self.sound_directory = sound_director...
from evaluate import pivotal, pivotality, criticality, prob_pivotal, unpacked_pivotality from itertools import product from simulate import * from draw import draw, highlight_cause_effect, draw_outcomes, show_predictions from names import * import numpy as np import networkx as nx COLOR = [(0, 100), (220, 100), (120,...
# -*- coding=utf-8 -*- # @Time:2020/10/11 12:18 下午 # Author :王文娜 # @File:另一种文件名.py # @Software:PyCharm import csv with open('test.csv','w',newline='') as f: # 初始化写入对象 writer = csv.writer(f) writer.writerow(['超哥哥',20]) writer.writerow(['步惊云', 22]) with open('test.csv','a',newline='') as f: writer=cs...
''' 50x50 board with 50,000 agents -- agents can only defect or cooperate, and must always play. In addition, these agents have extremely simple genes. ''' N_COLS = 50 N_ROWS = 50 NUM_AGENTS = 50000 def onlyCD(agent, action): if not action: return agent.cooperate() else: return agent.defect() de...
# -*- coding:utf-8 -*- # Author: Jorden Hai info = { 'stu1101':"TengLan Wu", 'stu1102':"LongZe Luola", 'stu1103':"XiaoZe Maliya", } info['stu1101'] = "武藤兰" info['stu1102'] = "泷泽萝拉" info['stu1103'] = "小泽玛利亚" info['stu1104'] = "苍井空" for key,value in info.items(): print(key,':',value) print(info.get('s...
from django.apps import AppConfig class ObituariesConfig(AppConfig): name = 'obituaries'
r = lambda a : a + 15 print(r(5)) r = lambda x, y : x * y print(r(2, 5))
""" Heber Cooke 10/29/2019 Chapter 6 Exercise 8 The function works as expected. It prints the sentence. It works by printing the first letter of the sentance then setting the index to the next letter. It then recursivly calls the function with the new starting index until there are no more indexes. The hidden cost ru...
# viewsfile from django.shortcuts import render from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required import pyrebase config={ "apiKey": "AIzaSyA1_TbZc_DAJVAosBsBXHKVnANss0_220U", "authDomain"...
import argparse import json import logging import logging.config import os import pkg_resources import sys from poller import Poller import settings def setup_logging(cli_args): """ Setup logging configuration :param cli_args: Argparse object containing parameters from the command line :return: Logger ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def latinhypercube(n, samples, limits=None, spread=True, seed=None): import numpy as np np.random.seed(seed) def _spread_lh(values, ndims, max_niter=10000): nrejected = 0 total_dist = 0 for x in range(ndims): for y in rang...
x,y,s=input().split(" ") if(x>y and x>s): print(x) elif(y>s and y>x): print(y) else: print(s)
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Teacher from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, U...
from bs4 import BeautifulSoup import requests import vk_api import time import sys f1 = open(r'D:\\TEST FILES\\THESIS\\Корпус до обработки в RStudio\\new_ids.txt', 'r', encoding='utf8') ids=[] for line in f1: k = line.replace('\n','') ids.append(k) f1.close() non_bmp_map = dict.fromkeys(range(0...
import numpy as np from numpy import array def foo(): a = array([[1,1,1,1,1],[0,1,1,1,1],[1,1,0,0,-1],[1,0,0,0,-1],[0,0,0,0,-1],[0,0,0,1,-1],[0,0,1,0,-1],[0,0,1,1,-1],[1,0,1,1,1],[1,1,0,1,1],[0,1,0,0,-1],[0,1,0,1,-1],[0,1,1,0,-1],[1,0,0,1,-1],[1,0,1,0,-1],[1,1,1,0,1]]) print(a.shape) ground = a[:,4].astype(int) ...
from django.shortcuts import render from .forms import PubCourseForm from apps.course.models import Course,CourseCategory,Teacher from django.views.generic import View from utils import restful from django.utils.decorators import method_decorator from django.contrib.auth.decorators import permission_required @method_d...
''' worker class ''' # inheritance class class Worker(Person): ''' creates child Worker class that inherits from parent Person class assigns additional attributes characteristic of Worker class income is an integer value ''' # instantiate Worker class def __init__(self, name='Doe', age=0, hei...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from dataclasses import dataclass from pants.backend.codegen.thrift.scrooge import additional_fields from pants.backend.codegen.thrift.scrooge.additional_fields import ScroogeFinagleBoolFi...
#!/usr/bin/env python # coding: utf-8 # In[1]: from urllib.parse import urlparse url='http://wikipedia.org' obj=urlparse(url) print(obj.scheme) print(obj.netloc) print(obj.hostname) print(obj.geturl()) # In[7]: import whois for x in whois.whois('google.com'): print(x) # In[ ]:
from random import randint PROGRESSION_LENGTH = 10 TITLE = "Progression game" RULES = "What number is missing in the progression?" def game_round(): start_num = randint(1, 20) progression_step = randint(1, 10) missing_num_index = randint(1, PROGRESSION_LENGTH - 1) numbers = list( range( ...
# Test program for the Device class by Per from jnpr.junos import Device # import base64 # to encrypt password #import myPassword #import base64 try: # Create device object mySRX_password = base64.b64decode(myPassword.getPassword()) print('Testing if device can be created') myDev = Device(hos...
from .index_view import IndexView from .detail_view import DetailView from .results_view import ResultsView from .vote_view import VoteView
fname = input("Enter file name:") file = open (fname) hours = dict() for line in file: line = line.strip() if line.startswith('From '): words = line.split() time = words[5] hour = time[:2] hours[hour] = hours.get(hour,0) +1 for key, value in sorted(hours.items()): print (k...
import csv import re import os import sys import string import nltk from nltk.tokenize import word_tokenize from configparser import ConfigParser #Some usefull regexp MENTIONS = re.compile(r'@[^\s]*') URL = re.compile(r'htt[^\s]*') SYMBOLS = re.compile(r'[^A-Za-z ]') RT = re.compile(r'RT ') SPACE = re.compile(r'\s+')...
import urwid import utils import sniffer import logging import threading class NetworkInterfaceSelector(): """This class implements the behavior of the network interface selector. It periodically scans the available network interfaces on the system, and updates their list adding the corresponding actions ...
from _typeshed import Incomplete def hopcroft_karp_matching(G, top_nodes: Incomplete | None = None): ... def eppstein_matching(G, top_nodes: Incomplete | None = None): ... def to_vertex_cover(G, matching, top_nodes: Incomplete | None = None): ... maximum_matching = hopcroft_karp_matching def minimum_weight_full_matc...