text stringlengths 38 1.54M |
|---|
integer = int(input('Введите целое положительное число: '))
print('Число: ', integer)
max = 0
if integer > 0:
while integer % 10 or integer // 10:
if max < integer % 10:
max = integer % 10
integer = integer // 10
else:
integer = integer // 10
else:
print('Чис... |
# coding: utf-8
"""
OneLogin API
OpenAPI Specification for OneLogin # noqa: E501
The version of the OpenAPI document: 3.1.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
"""
from __future__ import annotations
import pprint
import re # noqa: F... |
"""
Exercício Python 105: Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai
retornar um dicionário com as seguintes informações:
– Quantidade de notas
– A maior nota
– A menor nota
– A média da turma
– A situação (opcional)
"""
def notas(*args, sit=False):
"""
-> Funç... |
from Node import Node
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
cou... |
import json, os, threading
from watson_developer_cloud import ConversationV1
from watson_developer_cloud import ToneAnalyzerV3
import numpy as np
import scipy.io.wavfile as wv
import matplotlib.pyplot as plt
from PIL import Image
import speech_recognition as sr
r = sr.Recognizer()
tones = {'Anger':0.0, 'Disg... |
# -*- coding: utf-8 -*-
import re
import os
import codecs
from bs4 import BeautifulSoup
from scrapy import Request
from baike_scrapy.items import *
from scrapy.selector import Selector
class HudongSpider(scrapy.Spider):
name = 'hudong_spider'
allowed_domains = ['baike.com']
start_urls = ['http://www.baike... |
import time
from models import Model
class Topic(Model):
@classmethod
def get(cls, id):
m = cls.find_by(id=id)
m.views += 1
m.save()
return m
def __init__(self, form):
self.id = None
self.views = 0
self.title = form.get('title', '')
self.con... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import nltk
import re
#########################################################################
# create a dictionary of {[entity_name, URI_de_entity_name]}
#########################################################################
with open('entity_list.txt') as ... |
from django.shortcuts import render
# Create your views here.
def homepage(request, *args, **kwargs):
if not request.session.session_key:
return render(request, "loginPage.html")
return render(request, "main.html") |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import sys
import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import transforms
from torchvision.utils import save_image
from datasets import ... |
from pyramid.view import view_config, view_defaults
from formencode import validators
from formencode.api import Invalid
from pyramid.httpexceptions import HTTPBadRequest
from ..models import DBSession, Manufacturer
from ..schemas.add_part import AddPartSchema
from ..utils.dbhelpers import get_or_404
from .bas... |
import os
import numpy as np
from torchvision import models, transforms
import torch
import torch.nn as nn
from PIL import Image
from torch.nn import functional as F
import numpy as np
from models.modeling import VisionTransformer, CONFIGS
with open('./2021VRDL_HW1_datasets/testing_img_order.txt') as f:
... |
"""
When ever a wallet is created, two keys are generated,
the public key and the private key. The private key belongs
to the user along and we can not hold or save the private key.
the public key - we can store and it would be used when sending zuri coin
to the user...
"""
import binascii
from uui... |
# -*- coding: utf-8 -*-
import time
from openerp.osv import fields,osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
# class delivery_carrier(osv.osv):
# _inherit = "delivery.carrier"
# _columns = {
# 'use_webservice_pricelist': fields.boolean('Advanced Pricing by... |
import vector
import math
import game
import action
import hero
import direction
import time
import heapq
def manhattanDistance(p,q):
if not isinstance(p,vector.Vector):
raise ValueError("Variable is not a Vector.")
if not isinstance(q,vector.Vector):
raise ValueError("Variable is not a Vector.")
return math... |
import itertools
def get_permutations(l):
for n in range(1, len(l)+1):
for permutation in itertools.permutations(l, n):
value = 0
for digit in permutation:
value = value * 10 + digit
yield value
def solution(l):
value = 0
for p in get... |
# generic metadata generator for all urls stored in text file
# reading urls from text file and generating metadata to data.json file
from newsplease import NewsPlease
import json
data = []
f=open("y.txt", "r")
c = f.readlines()
for post in c:
print(post)
x = NewsPlease.from_url(post)
data_json = {
"URL": x.u... |
# Simple GUI with:
# Label
# Scrolledtext
# Button
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
window = tk.Tk()
window.title("My Personal Title")
window.geometry("300x300")
window.resizable(0,0)
window.wm_iconbitmap("images/ok.ico")
#Label to guide user:
... |
import time
import datetime
print(time.time()) # 1970年1月1日到现在所经历的秒数
print(time.localtime()) # 当前时间的结构化输出,tm_wday从0到6,0代表周一;tm_yday从1月1日到现在的天数; tm_isdst是否为夏令时,取值为-1,0,1
print(time.strftime(r'%Y-%m-%d %H:%M:%S')) # 当前时间的格式化输出,输出字符串格式
print(datetime.datetime.now()) # 当前日期与时间
# 计算日期的加减
oneday = datetime.dat... |
from django.db import models
# Create your models here.
"""
1 先写普通字段
2 再写外键字段
"""
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
phone = models.BigIntegerField(verbose_name='手机号', null=True, blank=True)
"""
null=True 数据库该字段可以为空
blank=True admin后台管理该字段可以为空
""... |
# ----------------------------------
# CCF1d.py (SPARTA UNICOR class)
# ----------------------------------
# This file defines the "CCF1d" class. An object of this class stores
# a Spectrum object, saved in the self.spec field and a Template object
# stored in th... |
'''
时刻要记得:数组是可变类型。
'''
list_01 = ['a']
list_02 = list_01 * 4
print(list_02)
list_01.append('b')
print(list_02)
'''
上面这个例子中,两次输出结果都是 ['a', 'a', 'a', 'a']
没有什么疑问,有意思的是下面这个操作
'''
list_03 = [[]]
list_04 = list_03 * 4
print(list_04)
list_03[0].append('a')
print(list_04)
'''
这个例子中,第一次输出的是[[], [], [], []]
而第二次输出的则是[['a'], [... |
import numpy as np
from scipy.spatial import cKDTree as KDTree
from pypolycontain.lib.zonotope import zonotope
from collections import deque
from pypolycontain.lib.AH_polytope import AH_polytope,to_AH_polytope
from pypolycontain.lib.operations import distance_point_polytope
from pypolycontain.lib.polytope import polyto... |
"""
300. Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4.
Note that there may be more than one LIS combination, it is ... |
# 4.5 Validate BST
# Implement a function to check if a binary tree is a binary search tree.
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# ... |
def gcd(a, b):
best = 1
for num in range(2, min(a, b) + 1):
if a % num == 0 and b % num == 0:
if num > best:
best = num
return best
if __name__ == '__main__':
a, b = map(int, input().split())
print(gcd(a, b))
|
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,"home.html")
def home(request):
return render(request,"home.html")
def bollywood(request):
return render(request,"bollywood.html")
def hollywood(request):
return render(request,"hollywood.html")
... |
from typing import Tuple, Union, Iterable, List, Callable, Dict, Optional
from nnuncert.models._network import MakeNet
from nnuncert.models.dnnc import DNNCModel, DNNCRidge, DNNCHorseshoe, DNNCPred
from nnuncert.models.mc_dropout import DropoutTF, MCDropout, MCDropoutPred
from nnuncert.models.ensemble import Ensemble,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script to automatically determine the moment magnitudes of a larger number of
events.
The script will write one output file containing all events with one additional
magnitude.
Some configuration is required. Please edit the uppercase variables right after
all the imp... |
import x3dpsail
(x3dpsail.ProtoBody()
# Initial node of ProtoBody determines prototype node type
.addChild(x3dpsail.TouchSensor().setDescription(x3dpsail.SFString("within ProtoBody"))
.setIS(x3dpsail.IS()
.addConnect(x3dpsail.connect()))))
|
#!/usr/bin/env python3
from networkx.utils import open_file
import pickle
import sys
@open_file(0, mode='rb')
def read_gpickle(path):
return pickle.load(path)
G = read_gpickle(sys.argv[1])
import code, readline, rlcompleter
readline.parse_and_bind('tab: complete')
code.InteractiveConsole(locals()).interact()
|
from __future__ import absolute_import
from celery import Celery
from nlweb.app import create_app, load_celery_config
from nlweb.extensions import opbeat
from opbeat.contrib.celery import register_signal
def make_celery(app):
celery_obj = Celery(app.import_name)
load_celery_config(celery_obj)
TaskBase ... |
#!/usr/bin/python3
"""State rule module"""
from api.v1.views import app_views
from flask import jsonify, abort, make_response, request
from models import storage
from models.city import City
from models.place import Place
from models.user import User
from models.state import State
from models.amenity import Amenity
@... |
import os
import gzip
import numpy as np
from scipy import io
import cPickle as pickle
import os
import gzip
import numpy as np
from scipy import io
import cPickle as pickle
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np... |
#!/usr/bin/env python
# vim: set expandtab tabstop=4 shiftwidth=4:
# Copyright (c) 2018, CJ Kucera
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must reta... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if x <0 :
return False
if x == 0:
return True
elif x%10==0 :
return False
rev = 0
while x > rev:
rem = x%10
rev = rev*10+rem
x = int(x/10)
... |
'''
Given an m x n board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells,
where "adjacent" cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import random
import subprocess
def pywal_image(image_path):
cmd = ['wal', '-g', '-i', image_path]
print(' '.join(cmd))
subprocess.call(cmd)
def rotate_background(backgrounds_dir):
background_imgs = [os.path.join(backgrounds_dir, im... |
import requests
url = 'https://www.12306.cn/'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
# 因为https 是有第三方 CA证书认证的
# 但是 12606 虽然是https 但是 它不是CA证书,他是自己 颁发的证书
# 解决办法 是:告诉web 忽略证书 访问 使verify=False 默认是true
response = req... |
# Copyright (C) 2004-2016 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from copy import deepcopy
import mininx as nx
from mininx.classes.graph import Graph
from mininx import MiniNXError
class MultiGraph... |
from accounts.models import *
from django.contrib.postgres.fields import JSONField
from django.utils import timezone
NOTIFICATION_TYPE = (
('1', 'POST_INVOLVEMENT'), ('2', 'POST_COMMENT'), ('3', 'POST_LIKE'), ('4', 'POST_NEW'), ('5', 'QUESTION_NEW'),
('6', 'UPDATE_FOLLOWED_USER'), ('7', 'Chat'), )
ADMIN_NOTIFI... |
# inheritance
# users
# -Wizard
# -archers
# -ogres
class User(): # parent
def sign_in(self):
print('logged in')
class Wizard(User): # child1
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
print(f'attacking powe... |
# By having class "Scope", we are able to create scopes and each scope has a name and has the ability to be inserted or to be searched through
class Scope:
def __init__(self, name):
self.data = {}
self.name = name
def name(self):
return self.name
def search(self, x)... |
def main():
action, phrase, key = input("Please input action (encode/decode), phrase and key: ").split(",")
phrase = phrase.strip()
key = int(key.strip())
action = action.strip()
processed = ''
if action == 'encode':
for ch in phrase:
processed = processed + chr(ord(ch) + ke... |
#!/usr/bin/python3
#
# ./insert_teachers_grading_standards.py -a account_id cycle_number school_acronym course_code
# ./insert_teachers_grading_standards.py course_id cycle_number school_acronym course_code
#
# Generate a "grading standard" scale with the names of teachers as the "grades".
# Note that if the grading ... |
#!/bin/python3
import sys
n,k, m = input().strip().split(' ')
n,k, m = [int(n),int(k), int(m)]
for a0 in range(k):
x,y = input().strip().split(' ')
x,y = [int(x),int(y)]
a = list(map(int, input().strip().split(' ')))
L = [[0 for x in range(m)] for x in range(m)]
for i in range(m):
L[i][i]=1
for cl in... |
#!/usr/bin/env python
import boto3
# ---------------------Made by shalev pinker ------------------
# ---------------------
# -------------------- Testing of boto3 usage------------------
# This will get list of regions to iterate
##client = boto3.client('ec2',region_name='eu-west-1')
##regions = [region['RegionName... |
#DEFINE AND IMPORT ALL THINGS-----------------------------------------------------------------
import threading
from threading import Thread
import win32api, win32con
import keyboard
import pyautogui
import time
import cv2
from PIL import Image
import cv2
import random
from PIL import ImageGrab
import numpy as np
from ... |
import multiprocessing
class ProcesTest(multiprocessing.Process): # functia de crearea unui proces intr-o subclasa
def run(self):
print(f'am apelat metoda run() in procesul: {self.name}')
return
if __name__ == '__main__':
jobs = [] # array unde vor fi adaugate procesele
... |
from DBModel import *
from BaseModel import BaseModel
from peewee import *
import datetime
class tEmployee(BaseModel):
EmpID = CharField(unique=True, max_length=50, primary_key=True)
Name = CharField(max_length=45)
ServiceDate = DateTimeField()
#Created = DateTimeField(default=datetime.datetime.now)
... |
######################################################################
######################################################################
# Copyright Tsung-Hsien Wen, Cambridge Dialogue Systems Group, 2017 #
######################################################################
####################################... |
from unittest import TestCase
from order import Order, SUPPORTED_TEMPERATURES
from shelf import CAPACITY
from uuid import uuid4
class OrderTestCase(TestCase):
"""
base test class for common test function
"""
@staticmethod
def generate_order():
order1 = {"id": str(uuid4()),
... |
import hug
from . import api
hug.API(__name__).extend(api)
# Public API
from .api import get_labels, get_level, get_levels
|
import os
import subprocess
import tempfile
tf = tempfile.TemporaryFile()
proc_obj = subprocess.Popen('ls', stdout=-1)
proc_obj2 = subprocess.Popen(['wc', '-l'], stdin=proc_obj.stdout.fileno(), stdout=-1)
print proc_obj2.stdout.read()
|
import numpy as np
import matplotlib.pyplot as plt
import os
RUN_PATH = './RUNS/'
data = []
for fn in os.listdir(RUN_PATH):
try:
N, M, B = fn.split('_')
except ValueError:
continue
# extract speedup
if os.path.isfile(RUN_PATH + fn + '/out'):
with open(RUN_PATH + fn + '/out', 'r... |
from torch import torch, nn, optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from src.torch.torch_models.fc_model import NNetwork
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.... |
#!/usr/bin/env python3
# import pandas as pd
# import os
import argparse
from azkaban.azkabans import Flow, Project
from azkaban.utils import *
from azkaban.azssh import restart_azkaban
def update_project(prj_nm):
"""
更新项目的元数据,已经设置的计划会自动按新元数据执行
:param prj_nm: 项目名称
"""
zip_path = crt_job_file(prj... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import atexit
import time
import argparse
from client import Client
import random
import sys
import os
import math
import time
import json
import socket
# # -*- coding: utf-8 -*-
# """This file contains the client class used by the Expanding Nim game
# This class can either... |
# Generated by Django 3.1.7 on 2021-05-23 05:42
from django.db import migrations
import phone_field.models
class Migration(migrations.Migration):
dependencies = [
('student_registration', '0013_merge_20210523_0052'),
]
operations = [
migrations.AlterField(
model_name='studen... |
N = int(input())
answers = list(map(str,input()))
# 상근이 창영이 현진이의 리스트를 만들어 답을 반복적으로 넣어둔다.
Adrian = [] # 상근
Bruno = [] # 창영
Goran = [] # 현진
a_cnt = 0
b_cnt = 0
g_cnt = 0
for i in range(33):
Adrian.append('A')
Adrian.append('B')
Adrian.append('C')
Adrian.append('A')
for i in range(25):
Bruno.append('B')
... |
import random
tries = 1
npcNum = random.randint(1, 10)
while True:
guess = input("Guess the number! ")
guess = int(guess)
if guess == npcNum:
print(f"Yup, I picked {npcNum}! You win!")
print(f"It took you {tries} tries.")
break
else:
print("Nope, try again!")
tr... |
class Solution:
def solve(self, s):
res = []
subs = [s[i: j] for i in range(len(s))
for j in range(i + 1, len(s) + 1)]
subs_ = []
for el in subs:
el = sorted(el)
subs_.append(''.join(el))
for i, el in enumerate(subs):
tmp = subs_[i]... |
import sqlite3
import Tkinter
import tkMessageBox
class App:
def __init__(self, master):
self.word = Tkinter.Button(text="Translate",
command=lambda: self.
get_name('translation.db', raw_input(
"Engli... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
def fizz_buzz(n):
# Write your code here
p = ""
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
p = "FizzBuzz"
elif i % 3 == 0:
p = "Fizz"
elif i % 5 == 0:
p = "Buzz"
else:
p = i
print(f'{p}.')
if __name__ == "... |
from tests.modules.FlaskModule.API.user.BaseUserAPITest import BaseUserAPITest
from opentera.db.models.TeraDevice import TeraDevice
class UserQueryDeviceSubTypesTest(BaseUserAPITest):
test_endpoint = '/api/user/devicesubtypes'
def test_no_auth(self):
with self._flask_app.app_context():
re... |
# ImageNet dataset
# http://image-net.org/download-images
from Constants import *
from Functions import *
from fastText import *
import string
import glob
import os
import re
def get_image_folders(path=IMAGENET_IMAGES_DIR):
path = r"{}".format(path)
all_folders = os.listdir(path)
return all_folders
d... |
from pathlib import Path
import cv2
import numpy as np
import torch
import torchvision
from PIL import Image
from scipy.spatial.transform import Rotation
from torch.utils.data import Dataset
import os
if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, 'oxford_robotcar'))):
from data_loader.oxford... |
from unittest import TestCase
from pprint import pprint
from constants import Constants
from fortifyapi import FortifySSCClient, Query
class TestArtifacts(TestCase):
c = Constants()
def test_version_artifact(self):
client = FortifySSCClient(self.c.url, self.c.token)
self.c.setup_proxy(client)... |
x=int(input("введите стоимость монитора "))
y=int(input("введите стоимость сисьтемного блока "))
z=int(input("введите стоимость клавиатуры "))
print("стоимость трех компьютеров равна",(x+y+z+n)*3)
|
def START():
event = input()
if event == "a":
return stateA()
else:
return stateB()
def stateA():
print("State A")
def stateB():
print("State B")
START()
|
import numpy as np
from abc import ABCMeta, abstractmethod
from .optimization import gd, cd
class BaseLinearModel(metaclass=ABCMeta):
""" Base linear model """
def __init__(self, n_iters=1000, tol=.0001, debug=False):
self._coef = None
self._norm = None
self._n_iters = n_iters
... |
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import post_save
from django.dispatch import receiver
from . import models
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_related_models_f... |
from gym.envs.registration import register
register(
id='Quadrotor-v0',
entry_point='gym_Quadrotor.envs:QuadrotorEnv',
)
register(
id='Quadrotor-extrahard-v0',
entry_point='gym_Quadrotor.envs:QuadrotorExtraHardEnv',
)
|
import os
import pytest
# IMPORTANT keep this above all other borg imports to avoid inconsistent values
# for `from borg.constants import PBKDF2_ITERATIONS` (or star import) usages before
# this is executed
from borg import constants
# no fixture-based monkey-patching since star-imports are used for the constants mod... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Unit tests for the sitewide_helpers module."""
from __future__ import print_function
from __... |
#!/usr/bin/env python
"""
simple script to rename bugzill aliases on hosts that have been renamed, if
they already exist.
Usage: rename_host_bugs old-new-short-names-file
Where: old-new-short-names-file is output of "map_hosts --short"
Note: you need to manually enter your bugzilla username & pass... |
from terrabot.events.events import Events
class Packet2Parser(object):
def parse(self, world, player, data, ev_man):
ev_man.raise_event(Events.Blocked, str(data[2:], "utf-8"))
|
from events.watcher import Watcher
def handler1(previous_state, current_state):
print('Handler 1 : {} to {}'.format(previous_state, current_state))
def handler2(previous_state, current_state):
print('Handler 2 : {} to {}'.format(previous_state, current_state))
def handler3(previous_state, current_state):
... |
import json
import re
from json import JSONEncoder
class Register:
def __init__(self, start_addr, word_cnt, Eui64, Tsapid, ObjId, AttrId, Idx1, Idx2, MethId, status):
self.start_addr = start_addr
self.word_cnt = word_cnt
self.Eui64 = Eui64
self.Tsapid = Tsapid
self.ObjId = ... |
import unittest
from app import create_app
class ApiTestCase(unittest.TestCase):
"""This class represents the api test case"""
def setUp(self):
"""Define test variables and initialize app."""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
# cpf
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.IncomeDistributionTransInInfo import IncomeDistributionTransInInfo
class AnttechBlockchainFinanceDistributionRuleCreateModel(object):
def __init__(self):
self._distri... |
# -*- coding: utf-8 -*-
from intercom.api_operations.find import Find
from intercom.api_operations.delete import Delete
from intercom.api_operations.find_all import FindAll
from intercom.api_operations.save import Save
from intercom.traits.api_resource import Resource
class Subscription(Resource, Find, FindAll, Save... |
def FindWalk(
walks,
current_walk,
current_x,
current_y,
side,
pathLength,
visited):
# If we have visited every position,
# then this is a complete walk.
if (len(current_walk) == pathLength + 1):
walks.append(current_walk)
print(walks)
... |
from extract_emails.browsers import ChromeBrowser
from extract_emails import EmailExtractor
# url = "http://www.adcottawa.com/"
# url = "https://dentistryonking.net/"
# url = "https://conklindental.ca/"
# url = "http://elliotlakedentalcentre.com/"
# url = "http://www.sudburysmiles.ca/"
# url = "https://www.downtowndent... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
from datadog_checks.dev import get_docker_hostname
PORT = '6379'
PASSWORD = 'devops-best-friend'
MASTER_PORT = '6382'
REPLICA_PORT = '6380'
UNHEALTHY_REPLICA_PORT = '6381'
HOST = get_docker_hostname()
... |
def solution(arr):
answer = []
for i in range(0, len(arr)):
if i < len(arr)-1 and arr[i] != arr[i+1]:
answer.append(arr[i])
if i == len(arr)-1:
answer.append(arr[i])
return answer |
import os
import pprint
def main ():
output = '';
[inputCount, numList] = readFile()
for i in range(0,int(inputCount)):
num = int(numList[i])
checklist = set()
find = False
if num != 0:
for j in range(1,10**10):
checklist = checklist.union(set(list(str(num*j))))
if sorted(checklist) == ['0','1','2... |
#!/usr/bin/env python
# coding: utf-8
# In[17]:
import pandas as pd
data = pd.read_csv(r"C:\Users\win 10\Downloads\housing.csv", header=None, sep='\s+')
column_list = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
data.columns = column_list
data.head()
# ... |
securityLevels = []
with open('day13input') as f:
for line in f:
line = line.replace(':','').split()
securityLevels.append([int(line[0]), int(line[1])])
scannerList = []
for item in securityLevels:
scannerList.append((item[0], item[1] * 2 - 2))
print(scannerList)
letshopeLOL = 0
caught = True
while caught:
c... |
from enum import Enum
import numpy as np
import pandas as pd
from WeatherDataCSV import WeatherDataCSV
class WWOData(WeatherDataCSV):
class Columns(Enum):
DATE = 'date' # dd/MM/yyyy format
TIME = 'time' # int format (0, 100, 2300)
DATE_TIME = 'datetime' # int format (0, 100, 2300)
... |
"""
The bike costs K dollars. At the start of every day I save up N dollars
and at the start of every 10 days I spend M dollars.
Output the days it'll take to save up for the bike.
If I cannot buy the bike (I spend more than I earn, output "NO BIKE FOR YOU"
ex input:
100
3.50
8
ex output:
36
ex input 2:
100
3
35
ex o... |
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
import pickle
import 07_vizuelizacija_matrice_konfuzije
def main():
knn = KNeighborsClassifier(n_neighbors=5,metric='minkowski',algorithm = 'br... |
import sys, os, re, glob
from scripts.search_files import *
from scripts.ilapfuncs import *
import argparse
from argparse import RawTextHelpFormatter
from six.moves.configparser import RawConfigParser
from time import process_time
import tarfile
import shutil
from scripts.report import *
from zipfile import ZipFile
fr... |
# tableau_db_connection.py
# =================================================
# Establishes connections to the Tableau PostgreSQL
# database.
#
# Database parameters are defined in
# moniteur_settings.py.
#
# =================================================
# =================================================
# impo... |
from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django_roa_client.views import home
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home),
)
|
import logging
import pytest
from ocs_ci.framework import config
from ocs_ci.framework.pytest_customization.marks import tier1, skipif_no_kms
from ocs_ci.framework.testlib import MCGTest
from ocs_ci.ocs import constants
from ocs_ci.ocs.resources import pod
logger = logging.getLogger(__name__)
@skipif_no_kms
class ... |
from pynetest.expectations import expect
from pynetest.lib.matchers.matches_list_matcher import MatchesListMatcher
from pynetest.matchers import about
def test__matches_list_matcher__can_match():
expect([1, 2, 3, "banana"]).to_be(MatchesListMatcher([1, 2, 3, "banana"]))
def test__matches_list_matcher__when_list... |
import comm
import config
import os
import sys
import xbmc
import xbmcgui
import xbmcplugin
from aussieaddonscommon import utils
pluginhandle = int(sys.argv[1])
def play(params):
try:
success = True
stream = comm.get_stream(params['video_id'])
utils.log('Attempting to play: {0} {1}'.for... |
from nose.tools import assert_equal
class Solution:
# @return a boolean
def isInterleave(self, s1, s2, s3):
#return self._check_recursive_tle(s1, s2, s3)
return self._check_dp(s1, s2, s3)
def _check_dp(self, s1, s2, s3):
m = len(s1)
n = len(s2)
if m+n != len(s3):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.