text stringlengths 38 1.54M |
|---|
import os
class Config:
# put the data in another directory so that we don't
# clutter our projects/code folder with data
user_dir = os.path.expanduser('~')
unpaywall_dir = os.path.join(user_dir,'.Unpaywall')
data_dir = os.path.join(unpaywall_dir, 'data')
# can put images with data, or in th... |
import dash
from dash.dependencies import Input, Output, State, Event
import dash_core_components as dcc
import dash_html_components as html
import grasia_dash_components as gdc
import dash_table_experiments as dt
import plotly
from plotly import graph_objs as go
from plotly.graph_objs import *
import matplotlib
from w... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 14:13:17 2021
@author: L380
"""
import os
import pdf2imag
import baiduOCR
def pdfOCR(pdfPath,txtdir):
if not os.path.exists(txtdir): # 判断文件夹是否存在
os.makedirs(txtdir) # 若文件夹不存在就创建
imagedir = txtdir +'/imag_tmp'
imagNameList = pdf2... |
b = input("qual escala?")
a = float(input("Valor da temperatura:"))
if (b.upper() == "C"):
eq = a*(9/5) + 32
else:
eq = (a - 32)*(5/9)
print(round(eq,2)) |
from .hub import Hub
class Client(object):
def __init__(self, mac):
self.__mac__ = mac
def hub(self, hub):
return Hub(self.__mac__, hub)
|
import json
import boto3
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
regionName = os.environ['AWS_REGION']
topicArn = os.environ['TOPIC_ARN']
sns_client = boto3.client('sns', region_name=regionName)
rs_client = boto3.client('redshift', region_name=regionName)
def lambda_handle... |
import requests
import json
from googletrans import Translator
botCode = open("bot.py").read()
cmd = ["Inspire: ngirim quote\n",
"Aku mau kode: ngirim source code\n",
"Translate: translasi kalimat setelah kata translate, contoh: translate aku dan kamu -> me and you\n",
"Alltranslate: translasi ka... |
# Generated by Django 3.2.14 on 2022-07-11 06:16
import os
from pathlib import Path
from django.db import connection, migrations, models
DISPLAY_NAME = connection.display_name
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent
class Migration(migrations.Migr... |
# -*- coding: utf-8 -*-
"""Класс для подготовки текстовых данных в виде столбцов
© 2008-2015 Jenyay (jenyay.ilin@gmail.com)
Домашняя страница: http://jenyay.net
Страница скрипта: http://jenyay.net/Programming/Coldata
"""
__version__ = "2.0.1"
__versionTime__ = "19 Jan 2016"
__author__ = "Eugeniy Ilin <jenyay.ilin@gma... |
# Program to count alphanumeric characters in a string.
def main():
my_string = input('Enter a string: ')
alnum_count = 0
for ch in my_string:
if ch.isalnum():
alnum_count += 1
print('The number of alphanumberic chracters are', alnum_count)
main()
|
# the worst fizzbuzz *i've* ever seen.
# => must be called `fizzbuzz*.py`
# => must be interpreted from the directory it is in
# => uses errors to format strings
# => uses triple logical negations
# => uses decimal, octal, *and* hexadecimal literals
import itertools as string, string as itertools
... |
from random import randrange
entrada = input('Digite o nome de seus alunos separando-os com , :')
alunos = entrada.split(',')
aluno = randrange(0,len(alunos))
print(f'O aluno sorteado para apagar o quadro e o :{alunos[aluno]}') |
from typing import List, Optional
from dedoc.data_structures.document_content import DocumentContent
from dedoc.data_structures.parsed_document import ParsedDocument
from dedoc.metadata_extractor.concreat_metadata_extractors.abstract_metadata_extractor import AbstractMetadataExtractor
class MetadataExtractorComposit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-05-27 07:44:52
# @Author : Jason Wong (wonglenchong@163.com)
# @Link : https://github.com/
# @Version : $Id$
# 定义一个求阶乘的函数n! = n * (n-1) * ... * 1
def fact(n):
if n == 0 or n == 1:
return 1
else:
value = n * fact(n-1)
return... |
# -*- coding: utf-8 -*-
{
'name': "Sale Stock Margin",
'category': 'Sales/Sales',
'summary': '',
'description': 'Once the delivery is validated, update the cost on the SO to have an exact margin computation.',
'version': '0.1',
'depends': ['stock_account', 'sale_margin'],
'installable': True... |
# coding: utf-8
"""
Defines pytest fixtures that will be used in other tests.
"""
import pytest
from webtest import TestApp
from {{cookiecutter.app_name}}.app import create_app
from {{cookiecutter.app_name}}.settings import Test
@pytest.fixture
def app():
"""An application for the tests."""
_app = create_a... |
names_input = input('输入姓名:') # 小明 小红 小青
names = names_input.split(' ')
scores_input = input('输入分数:') # 3 2
scores = scores_input.split(' ')
stat = {}
for i, name in enumerate(names):
if i < len(scores): # 避免 scores 访问越界
stat[name] = scores[i]
else:
stat[name] = 0
while True:
query = inp... |
"""
Prerequisite:
Install Python 3.X from https://www.python.org/downloads/release
Usage:
python .\pwned_password.py SomePlainPassword
"""
import hashlib
import requests
import sys
if len(sys.argv) < 2:
print("Please supply your password as the first argument.")
sys.exit()
plain_pw = sys.argv[1]
has... |
#!/usr/bin/env python
###############################################################################################################
# Author: Paragonsec (Quentin) @ Critical Start
# Title: pwned_api.py
# Version: 2.0
# Usage Example: python pwned_api.py -h
# Description: This script queries the 'haveibeenpwned' API
... |
import sys
print ('\n1. Creer le fichier_envoi a partir de la base de donnee client \n'
'2. Uploader sur OneDrive le catalogue et le fichier SAV \n'
'3. Envoyer les mails \n'
'4. Quitter le programme\n')
r = input('Entrer 1, 2 ou 3\n')
if r == '1':
import creation_complet.py
elif r == '2... |
print("Alhamdulillah Done by Mohamed Sherif")
points=[(2,10),(2,5),(8,4),(5,8),(7,5),(6,4),(1,2),(4,9)]
allCostsWithMidoids=[]
allcosts=[]
cluster1=[]
cluster2=[]
def distancemedoid(m1,point):
d1=abs(point[0]-m1[0])
d2=abs(point[1]-m1[1])
return d1+d2
def kmidoid(m1,m2):
cost=0
cluster1.clear()
... |
# An irrational decimal fraction is created by concatenating the positive integers:
#
# 0.123456789101112131415161718192021...
#
# It can be seen that the 12th digit of the fractional part is 1.
#
# If dn represents the nth digit of the fractional part, find the value of the following expression.
#
# d1 × d10 × d100 × ... |
import datetime
from asyncio import events
from builtins import object
from re import search
from urllib import request
from django.db.models import Q
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from d... |
from fanstatic import Library, Resource, Group
from js.jquery import jquery
library = Library('jcrop', 'resources')
jquery_jcrop_css = Resource(library, 'jquery.Jcrop.css',
minified='jquery.Jcrop.min.css')
jquery_color_js = Resource(library, 'jquery.color.js')
jquery_jcrop_js = Resource(library,... |
from sklearn.neighbors import KNeighborsRegressor
# 蛤, 这不是直接把题目描述复制过来就行了嘛??
def regression(train_feature, train_label, test_feature):
'''
使用KNeighborsRegressor对test_feature进行分类
:param train_feature: 训练集数据
:param train_label: 训练集标签
:param test_feature: 测试集数据
:return: 测试集预测结果
'''
clf = ... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016-2020 Bradley Naylor, Michael Porter, Kyle Cutler, Chad Quilling, J.C. Price, and Brigham Young University
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:
... |
from django.conf.urls import url
from . import views
app_name = 'payroll'
urlpatterns = [
url(r'^traverse/$', views.traverse, name='traverse'),
]
|
#!/usr/bin/env python
import time
import math
from collections import deque
import numpy
# global variables
speriod=1
avgnumber=10
alt=150
# get Pressure returns the Pressure as a float, compensated to sea level
def get_press(altitude):
# enable SenseHat modules
from sense_hat import SenseHat
sense=Sens... |
"""Contants for PS4 Wrapper component."""
from homeassistant import const
# Platform constants.
DOMAIN = 'ps4'
PLATFORMS = ['media_player']
# Attributes.
CONF_HOST = const.CONF_HOST
CONF_NAME = const.CONF_NAME
CONF_REGION = const.CONF_REGION
CONF_TOKEN = const.CONF_TOKEN
# Secondary data attributes.
CONF_DATA = con... |
#!/usr/bin/env python
"""
Synopsis here.
EXAMPLES
AUTHOR
Neil H. Watson, http://watson-wilson.ca, neil@watson-wilson.ca
LICENSE and COPYRIGHT
The MIT License (MIT)
Copyright (c) 2017 Neil H Watson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated docume... |
from django.apps import AppConfig
class ClienttrackerConfig(AppConfig):
name = 'clienttracker'
|
# MIT License
# Copyright (C) Michael Tao-Yi Lee (taoyil AT UCI EDU)
# A descriptor class
class PositiveAttr(object):
def __init__(self, name):
self.name = name
self.parent = None
def __get__(self, instance, cls):
print("get called", instance, cls)
return instance.__dict__[sel... |
# Optional arguments and default values
attrs = 'name'
if demisto.get(demisto.args(), 'attributes'):
attrs += "," + demisto.args()['attributes']
memberDN = ''
if demisto.get(demisto.args(), 'dn'):
memberDN = demisto.args()['dn']
elif demisto.get(demisto.args(), 'name'):
resp = demisto.executeCommand('ad-se... |
import sys
import csv
from collections import defaultdict
#def main(TOTAL_alineados_al_genoma, TOTAL_pseudogenes, GM12878_SJ, HeLaS3_SJ, HepG2_SJ, HUVEC_SJ, H1hesc_SJ):
def main(TOTAL_alineados_al_genoma, TOTAL_pseudogenes, polyA, RNA_total):
reads_SJ_genoma = []
reader1 = csv.reader(open(TOTAL_alineados_al_ge... |
# Volatility
# Copyright (C) 2008-2013 Volatility Foundation
# Copyright (C) 2011 Jamie Levy (Gleeda) <jamie.levy@gmail.com>
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2 as
# published by the ... |
from src.configuration.blueprint import app
from flask import jsonify
import src.constant.http_code as HTTP_CODE
import src.constant.connection as CONN
from src.model.response import Response
@app.route("/", methods=['GET'])
def home():
return Response(HTTP_CODE.SUCESSFUL, "Hello from User!").toMap()
if __name__... |
# selenium 임포트
from selenium import webdriver
# webdriver 설정(Chrome, Firefox 등)
browser = webdriver.Chrome('./chromedriver.exe')
# 크롬 브라우저 내부 대기
browser.implicitly_wait(5)
# 속성 확인
print(dir(browser))
# 브라우저 사이즈
browser.set_window_size(1920, 1280) #maximize_window(), minimize_window()
# 페이지 이동
browser.get("https:... |
'''using support vector machine'''
import numpy as np
import load_data as ld
import random
import time
def svm_loss_vectorized(W, X, y, reg):
"""
Structured SVM loss function, vectorized implementation.
Inputs and outputs are the same as svm_loss_naive.
"""
# loss = 0.0
dW = np.zeros(W.sha... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'django-couchdb',
version = '',
description = 'django couchdb app',
long_description = 'django-couchdb is the Django database adapter for '\
'CouchDB databases.',
author = '42',
author_email... |
import yaml
from pathlib import Path
from envs.enhance_env import EnhanceEnv
from default_actions.default_actions import (blue_team_actions,
red_team_actions)
from gui.gui_main import MainGUI
from utils import skip_run
config_path = Path(__file__).parents[1] / 'hsi/confi... |
from functools import reduce
from itertools import chain
DEFAULT_LAZY = True
_NONE = type('_NONE', (object,), {})
class List(list):
"""
Holds several instances and makes them act as one.
"""
def __init__(self, *objects):
"""
Initializes a new List instance.
:param objects: ... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 9 10:18:03 2016
@author: ranyijun
"""
import pandas as pd
nokia = pd.read_csv('imsib10_nokia.csv')
train_y = pd.read_csv('./../data/train_orig_all.csv', encoding = 'utf-8')[['IMSI','age']]
age_nokia = pd.merge(train_y, nokia, on = 'IMSI') |
class BaseDataLoader:
""" Base class for all data loaders.
Note:
No need to modify this in most cases.
"""
def __init__(self, batch_size):
self.batch_size = batch_size
def __iter__(self):
return NotImplementedError
def __next__(self):
return NotImplementedErro... |
# Generated by Django 3.1.2 on 2020-12-18 01:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='NivelUsuario',
fields=[
... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
# @Project :ShangKe
# @File :1104ddw
# @Date :2020/11/4 11:06 上午
# @Author :段益迈
# @Email :dym0822@163.com
# @Software :PyCharm
-------------------------------------------------
"""
import requests
import re
import json
# page = ... |
import os
import logging
# Always change directory to /src
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level = logging.INFO,
filename = '../log/log.txt'
)
console_logger = logging.StreamHandler()
conso... |
from rdflib import Namespace, Graph, Literal, RDF, URIRef
from rdfalchemy.rdfSubject import rdfSubject
from rdfalchemy import rdfSingle, rdfMultiple, rdfList
from brick.brickschema.org.schema._1_0_2.Brick.VAV_Supply_Air_Temperature_Setpoint import VAV_Supply_Air_Temperature_Setpoint
from brick.brickschema.org.schema._... |
# -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, NoReverseMatch
from django.conf import settings
admin.autodiscover()
urlpatterns = [
url(r'^', include(admin.si... |
from .toornament_connection import SyncToornamentConnection, AsyncToornamentConnection
from .viewer_schemas import *
from typing import Optional
from .range import Range
class SyncViewerAPI(SyncToornamentConnection):
@staticmethod
def _base_url():
return 'https://api.toornament.com/viewer/v2'
de... |
# This is the file that implements a flask server to do following use cases :
# language detection, TODO : db updates, duplicate detection.
from __future__ import print_function
from flask import Flask, request, Response, Blueprint
import werkzeug
werkzeug.cached_property = werkzeug.utils.cached_property
from werkzeu... |
import sys
sys.path.append("..")
from common import *
def parse(data):
data = list(map(lambda s: s.strip(),filter(lambda s: len(s) > 1,data.split("\n"))))
conds = {}
for i in range(20):
kv = data[i].split(":")
cs = kv[1].split("or")
conds[kv[0]] = ([int(v) for v in cs[0].split("-")]... |
from general.utils import MyTask
class Preprocessing(MyTask):
def process(self, datasetdscr ,dataset):
pass |
import demistomock as demisto
from CommonServerPython import entryTypes
from Ping import main
import re
import pytest
# To run the tests in an editor see: test_data/ping
RETURN_ERROR_TARGET = 'Ping.return_error'
@pytest.mark.parametrize('address', ['google.com', '8.8.8.8'])
def test_ping(mocker, address):
mocke... |
from zeep import Client
from IPython.display import clear_output
import sys
import time
import pandas as pd
def validate_vat_id_csv(file, start, end):
df = pd.read_csv(file)
df.columns=['VATID']
ids = list(df.VATID)[start:end]
print(f"{len(ids)} to validate")
print("Beginning validation")
time... |
from flask import Flask, request, jsonify, json
import time
from timeloop import Timeloop
from datetime import timedelta
from flask_pymongo import PyMongo
from pymongo import UpdateOne
from AuthManager import *
MONEY_TO_BUY = 10
INCOME_PER_CHAIN = 10
WRONG_AUTH_DATA = {
"response": "wa",
"message": "Login or passwo... |
import logging
from os.path import exists
import json
import re
from rdflib import Graph
from Cheetah.Template import Template
from utils import *
# Warning and error messages
language_error = lambda x: "Lexicon "+x+" specifies either no language or more than one."
language_warning = lambda x: "There is no resou... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 18:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('home', '0022_apitokeninstagramsettings'),
]
operations... |
n, x = map(int, input().split())
ice_cream = x
distress_child = 0
for _ in range(n):
sign, amount = input().split()
if sign == '+':
ice_cream += int(amount)
elif sign == '-' and ice_cream >= int(amount):
ice_cream -= int(amount)
elif sign == '-' and ice_cream<int(amount):
distr... |
import sys
lines=[x.strip() for x in sys.stdin.readlines()[:-1:]]
for line in lines:
a=[int(x) for x in line.split()[0][::-1]]
b=[int(x) for x in line.split()[1][::-1]]
l=max(len(a),len(b))
add=0
ans=0
for i in range(l):
if i >= len(a):
aa=0
else:
... |
def transform(dataset, resampling_factor=[1, 1, 1]):
"""Resample dataset"""
from tomviz import utils
import scipy.ndimage
import numpy as np
array = dataset.active_scalars
# Transform the dataset.
result_shape = utils.zoom_shape(array, resampling_factor)
result = np.empty(result_shape... |
#!/usr/bin/env python
import DGS
image_file = '/mnt/c/Projects/AdvocateBeach2018/data/raw/images/BeachSurveys/15_10_2018/PM/CrossShore/00_m/IMG_0345.jpg'
#image_file = '/mnt/c/Projects/AdvocateBeach2018/src/tests/images/test/FoxPointBeach/20180809_071703.jpg'
#C:\Projects\AdvocateBeach2018\data\raw\images\Beach... |
import unittest
from utils.channel_access import ChannelAccess
from utils.ioc_launcher import get_default_ioc_dir
from utils.test_modes import TestModes
GALIL_ADDR = "127.0.0.11"
GALIL_PREFIX = "GALIL_01"
IOCS = [
{
"name": GALIL_PREFIX,
"custom_prefix": "MOT",
"directory": get_default_... |
class GameState:
def __init__(self):
self.room_state = {}
self.unsaved_state = {}
self.saved_state = {}
def set_value(self, key, value):
self.room_state[key] = value
def get_value(self, key):
value = $dictionary_get_with_default(self.room_state, key, None)
if value != None: return value
value = $... |
# 哨兵循环
# 求平均数,但是不限制输入数据的个数
def main():
sum=0.0
count=0
xStr=input("Enter a number (<Enter> to quit)>> ")
while xStr != "":
sum=sum+eval(xStr)
count=count+1
xStr=input("Enter a number (<Enter> to quit)>> ")
print("\nThe average of the numbers is: ", sum/count)
main()
|
import time
import signal
import sys
import math
from math import*
import datetime
import MySQLdb
import random
from time import sleep
db = MySQLdb.connect(host="localhost", user="root", passwd="pass", db="TestProjetYES")
curs= db.cursor()
print("Connexion a la BDD reussie")
numero = 4
curs.execute("UPDATE comptage... |
class Currency:
def __init__(self, json):
self.__name = json["base"]
self.__date = json["date"]
self.__rates = json["rates"]
@property
def name(self):
return self.__name
def get_convertion(self, from_currency, to_currency, amount):
if from_currency == to_currenc... |
import numpy as np
import random
import csv
import torch
import torch.nn as nn
#source: https://stackoverflow.com/questions/37793118/load-pretrained-glove-vectors-in-python
#This function takes in the path to the glove pretrained vectors that is
#originally stored as a .txt and then converts it into a dictionary. To ... |
import numpy as np
import scipy
import cvxopt
import itertools
from sklearn.cluster import KMeans
def lsq_const(A,b,E = None,f = None,G = None,h = None,obj_only = True):
'''
solve a least square problem with constraints:
min ||Ax-b||^2
s.t. Ex = f
Gx >= h
----------------... |
import os
import csv
import re
import tensorflow as tf
from enum import Enum
class Mode(Enum):
train=0
test=1
predict=2
def shape(tensor):
return tensor.get_shape().as_list()
def read_random_line(fd):
fd.seek(0, os.SEEK_END)
total_bytes = fd.tell() #os.stat(file_name).st_size
random... |
from Configuration.Geometry.dict2026Geometry import *
from Configuration.Geometry.generateGeometry import *
if __name__ == "__main__":
# create geometry generator object w/ 2026 content and run it
generator2026 = GeometryGenerator("generate2026Geometry.py",999,"D","2026",maxSections,allDicts,detectorVersionDic... |
import cv2
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
recognizer.load('recog/trainner.yml')
faceCascade = cv2.CascadeClassifier("recog/haarcascade_frontalface_default.xml");
path = 'dataSet'
cam = cv2.VideoCapture(0)
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 5, ... |
from django.http import HttpResponse
from django.shortcuts import render
from django.conf import settings
from django.shortcuts import redirect
from django.core.files.storage import FileSystemStorage
import json
import os
import networkx as nx
from networkx.readwrite import json_graph
#import coverage_tools as cov_tool... |
"""
Name: Rahul Mangal
Email id: rahul.mangal2017@vitstudent.ac.in
Task: Working with Mysql and CSV file in python
"""
"""
@Import:
mysql.connector - which connects mysql database with python.
CSV - In order to read the data from CSV files.
"""
import mysql.connector
import csv
m... |
from django.test import TestCase
# Create your tests here.
from django.urls import reverse
from .factories import BookFactory
from .models import Book
class TestViewsRentedList(TestCase):
def test_(self):
response = self.client.get(reverse('library:rented_list'))
self.assertEqual(response.status... |
from model import *
from mutagen.mp3 import MP3
def main():
menu = """
-------------------------------------
| |
| 1: Add Song |
| 2: Create Playlist |
| 3: View Songs |
| 4: View Play Lists |
| ... |
import pandas as pd
import os
import sys
pathN = sys.argv[1]
directory = os.fsencode(pathN)
result = pd.DataFrame(columns=['gram','counts'])
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith("-ngram.csv"):
data = pd.read_csv(pathN + filename, header=None,names=... |
from django.contrib import admin
# Register your models here.
# from .models import Item
from .models import Donor, Item, Type
# @admin.site.register(Donor)
@admin.register(Donor)
class DonorAdmin(admin.ModelAdmin):
list_display = ['donorname', 'invoicenum', 'number_of_donations', 'last_updated']
@admin.regist... |
#!/usr/bin/env python
import os
import shutil
import unittest2 as unittest
import tempfile
import platform
import getpass
import tarfile
from qautils.gppylib.db import dbconn
from qautils.gppylib.gparray import GpArray
from contextlib import closing
from qautils.gppylib.commands import gp
from qautils.gppylib.comman... |
import time
class DS18B20:
def __init__(self, device_file):
#Sensor ID info so we know which file to look at
self.device_file = device_file
#A value we can modify and return at anytime, allows to calculate change in temp
self.last_temp = 0.0
def read_temp_raw(self):
f = open(self.device_file, 'r')
line... |
from bs4 import BeautifulSoup as bs
import requests
import os
URL = "https://the-morpheus.de/"
soup = bs(requests.get(URL).content, "html.parser")
img_urls = []
for img in soup.find_all("img"):
img_url = URL + img.attrs.get("src")
img_urls.append(img_url)
for url in img_urls:
response = requests.get(url)... |
#! /usr/local/bin/python3
#coding=utf-8
import sys
import imaplib
import getpass
import email
import datetime
#import git
import os
import re
import json
import time
import subprocess
import uuid
from twython import Twython
import fbconsole as F
LOCALDIR = os.path.dirname(os.path.realpath(__file__))
from configparse... |
"""Memcached binary protocol implementation."""
import sys
import struct
from collections import deque
from twisted.internet import defer
from twisted.protocols import stateful
from twisted.python import log
from constants import *
__all__ = ['BinaryServerProtocol',
'MemcachedUnknownCommand',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: alexogilvie
Project Euler Problem 14: Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Which starting number, under one million, produces the longest chain... |
import numpy as np
from ddpg_tf2 import Agent
from utils import plot_learning_curve, path_loss
from environment import Environment
from prepare_data import load_mrclam_dataset
from prepare_data import sample_mrclam_dataset
from animate_mrclam_dataset import animate_mrclam_dataset
if __name__ == '__main__':
deltaT... |
string = "OREOMCUFEDVTMGJELEHGVYHDNVWGKSHMBCYLMIEXLRWFFWXBKFSZEAFKZPLRVSJUEZTTMCAPOATSJUSPEMCQFLFIXMGSEATGRTOIEYYMVJVEUAUGLIOXWFTWGFEBFQLFCEPLTDWZAAEOAJFIMMUAREBTYPCTPTBRGAASRTYFDLOEARGLLXNEEPWEORPPPZYZAEFQPRLONYFLMDDTDRSRWMWPUOELEPDIERWAXGGUYTLPQGKTZCGLPQLOAFCHZRSOTMEKMSCARUSEEAABHZWPFLRUZMEDMCGYMEHXYQSRGALDAAPYDMAUOQ... |
#!/usr/bin/python
import psycopg2
import datetime
class YLabDb:
# Need to set some basic value types to variables for python
conn = ''
cur = ''
def connectionDb(self):
try:
self.conn = psycopg2.connect("dbname='ylabdb' user='ylabclass' host='192.168.10.126' password='YlabLock'")
... |
from random import randint
data = [randint(-10,10) for _ in range(10)]
s = set(data);
print({x for x in s if x%3 == 0})
|
from Snake import transformations as tr
from Snake import basic_shapes as bs
from Snake import scene_graph as sg
from Snake import easy_shaders as es
from Snake import Map
import numpy as np
from typing import List
from OpenGL.GL import *
class Tale(object):
N = Map.Map.N
def __init__(self, p_x, p_y):
... |
import web_scraping_prototype as WSP
import auto_summarization as autosum
from tf_idf import tf_idf_summarise
from word_freq import word_freq_summarize
from gensim.summarization.summarizer import summarize
import summary_evaluation as sumeval
def main():
articles = WSP.aljazeera_search('turkey')
print(len(arti... |
import argparse
from cmdline.branch_parser import MepoBranchArgParser
from cmdline.stash_parser import MepoStashArgParser
from cmdline.tag_parser import MepoTagArgParser
from cmdline.config_parser import MepoConfigArgParser
from utilities import mepoconfig
class MepoArgParser(object):
__slots__ =... |
from config import *
def enter_address(message):
chat_id = message.chat.id
user_id = message.from_user.id
message_id = message.message_id + 1
fcx_user = db.User.get_user(user_id)
balance = fcx_user.account_balance
lang = fcx_user.language
amount = message.text
try:
amount = De... |
SUITCASE =[]
SUITCASE.append("sunglasses")
# Your code here!
SUITCASE.append("shoes")
SUITCASE.append("gloves")
SUITCASE.append("pens")
LIST_LENGTH = len(SUITCASE) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (LIST_LENGTH)
print SUITCASE
animals = ["aardvark", "badger", "duc... |
from typing import List, Dict
import sys
# Hacky way to allow importing module beyond top-level package.
sys.path.append("..")
from utils import readFile
lines = readFile("fixedInput.txt")
def sortInputBasedOnTimestamp(alist):
'''
Sort given list based on timestamp.
Arguments:
alist -- list to be s... |
'''
main.py
Created by JO HYUK JUN on 2022
Copyright © 2022 JO HYUK JUN. All rights reserved.
'''
def solution(n, t):
answer = n
for i in range(t):
answer = answer * 2
return answer |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-12 16:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0007_auto_20160612_1602'),
]
operations = [
... |
import torch
import torch.optim as optim
from torch import linalg as LA
from torchvision import transforms
from torchvision.transforms.transforms import LinearTransformation
data_transform = transforms.Compose([
transforms.GaussianBlur(3),
transforms.Lambda(lambda x: x + torch.randn(x.shape).to(x.device)*0.00... |
#!/usr/bin/env python3
"""
** SELECTION SORT **
Space complexity:
- worst case: O(1)
Time complexity:
- worst case: O(n**2)
- average case: O(n**2)
- best case: O(n**2)
Algorithm's steps:
1. Find the smallest element. Swap it with the first element.
2. Fi... |
"""
byceps.announce.connections
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Connect event signals to announcement handlers.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Optional
from ..events.auth import UserLoggedIn
from ..events.base import _BaseEvent
fr... |
from rest_framework.response import Response
from rest_framework import mixins, viewsets
from .models import Obec, Orp, Pou
from .serializers import ObecSerializer, OrpSerializer, PouSerializer
class ObecAPIView(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericView... |
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020, Yoel Cortes-Pena <yoelcortes@gmail.com>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details.
"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.