text stringlengths 8 6.05M |
|---|
#using functins to clean data
#complex cleaning
# Extract number from string
# perform transformation on extracted number
# 1 .apply(), df.apply(np.mean, axis=0), axis=0 perform operations columns wise, axis=1 performs opr. row wise
import pandas as pd
tips = pd.read_csv('E:\csvdhf5xlsxurlallfiles/tips.csv')... |
from flask import Flask, request, jsonify, json, render_template
from fetch_data import extract_data
import pandas as pd
import sys
app = Flask(__name__)
@app.route('/')
def home():
return render_template("index.html")
@app.route('/commodity')
def commodity():
start_date = request.args["start_date"] if "st... |
"""
Given a number n, write a program to find the sum of the largest prime factors of each of nine consecutive numbers starting from n.
g(n) = f(n) + f(n+1) + f(n+2) + f(n+3) + f(n+4) + f(n+5) + f(n+6) + f(n+7) + f(n+8)
where, g(n) is the sum and f(n) is the largest prime factor of n
For example,
g(10)=f(10)+f(11)+f(1... |
import serial
import csv
import datetime
import time
arduino = serial.Serial('/dev/ttyACM1', 9600)
print("inicia recepción de datos serial")
i=0
while 1:
now = datetime.datetime.now()
if(arduino.in_waiting >0):
time.sleep(1)
line = str(arduino.readline())[2:-5]
if line == "1999":
print("recepcion")
print... |
#!/usr/bin/env python3.2
import ctypes
from ctypes.util import find_library
pcap = None
if(find_library("libpcap") == None):
pcap = ctypes.cdll.LoadLibrary("libpcap.so")
else:
pcap = ctypes.cdll.LoadLibrary(find_library("libpcap"))
# int pcap_compile_nopcap(int snaplen, int linktype, struct bpf_program *pro... |
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from . import views
urlpatterns = [
path('autocomplete', csrf_exempt(views.complete_query), name='autocomplete search query'),
path('data', csrf_exempt(views.get_sku_data), name='get all information related to sku'),
]
|
import cv2
import imutils
import numpy as np
from sklearn.metrics import pairwise
bg = None
#-------------------------------------------------------------------------------
# Funcion - Para encontrar el promedio sobre el fondo
#-------------------------------------------------------------------------------
def run_avg... |
"""Define tests, sanity checks, and evaluation"""
from .image_folder_dataset_tests import test_image_folder_dataset
from .transform_tests import (
test_rescale_transform,
test_compute_image_mean_and_std
)
from .dataloader_tests import test_dataloader
from .eval_utils import save_pickle
|
# Generated by Django 2.1.4 on 2019-07-26 02:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('career_test', '0003_auto_20190723_1505'),
]
operations = [
migrations.CreateModel(
name='Career... |
def findOffByOne(lines):
length = len(lines[0].strip())
for j in range(len(lines)):
x = lines[j]
for y in lines[j+1:]:
diffs = 0
index = -1
for i in range(length):
if x[i] != y[i]:
diffs += 1
if diffs >... |
#!/usr/bin/env python
import webapp2
import jinja2
import os
from utilities import *
from google.appengine.api import users
import datetime
import base64
from objects.usermeta import UserMeta
from objects.player import Player
from objects.game import Game
from google.appengine.ext import db
import urllib
import json
... |
"""
User urls
"""
from django.conf import settings
from django.urls import path
from rest_framework.generics import RetrieveAPIView, ListAPIView, UpdateAPIView
from . import views
from .models import User
from .serializers import QuickUserSerializer, OwnProfileSerializer
from .views import OwnProfileView
urlpatt... |
def get_score(arr):
lines_cleared = 0
four_liners = 1200
three_liners = 300
two_liners = 100
one_liners = 40
points = 0
for i in arr:
if i == 4:
points += four_liners
lines_cleared += i
if lines_cleared >= 10:
four_liners += 1200
... |
"""
Model implementation in PyNN by Vitor Chaud, Andrew Davison and Padraig Gleeson (August 2013).
This is a re-implementation of the models descirbed in the following references to reproduce Fig. 1 of Izhikevich (2004)
Original implementation references:
Izhikevich E.M. (2004) Which Model to Use for Cortica... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import re
from textwrap import dedent
from pants.backend.project_info.list_targets import ListSubsystem, list_targets
from pants.engine.addresses impor... |
from ABC.NodeAST import NodeAST
from ABC.Instruction import Instruction
from ST.Exception import Exception
from ST.SymbolTable import SymbolTable
from Instructions.Break import Break
from Instructions.Function import Function
from Instructions.Continue import Continue
class Main(Instruction):
def __init__(self, i... |
import torch.nn as nn
import torch
def conv3x3(in_channels, out_channels, stride=1):
"""
3x3卷积层,并且隐藏了3x3卷积输入输出维度相同的条件
:param in_channels:输入的通道数
:param out_channels:输出通道数
:param stride:卷积步长
:return:创建好的3x3卷积
"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, b... |
#-*—coding:utf8-*-
import numpy as np
import gc
import re
import csv
import codecs
import matplotlib
import matplotlib.pyplot as plt
from decimal import *
import time as time_linger
import copy
import time as tmm
def get_dic(a, b):
a_2_b = {}
last_index = 0
len_b = len(b)
min_b = b[0]
for i in ran... |
"""Transport handlers."""
from django.db.models import signals
from django.dispatch import receiver
from modoboa.core import signals as core_signals
from . import backends, models, postfix_maps
@receiver(core_signals.register_postfix_maps)
def register_postfix_maps(sender, **kwargs):
"""Register postfix maps.""... |
# 一开始想的是差分 + 离散化
# 看提示发现,高度数据量很小,可以直接枚举
# 然后对宽度二分查找,bisect_left还是比手写的好用嘿嘿
class Solution:
def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:
n, m = len(rectangles), len(points)
res = []
heights = [[] for _ in range(101)]
for x, y in rectang... |
#Leia uma String e retorne quantas vogais ela possui na tela.
palavra = input()
contador=0
for letra in palavra:
if letra in 'aeiou':
contador += 1
print(contador)
|
import random
import numpy as np
import torch
from torchvision import transforms as T
from torchvision.transforms import functional as F
def pad_if_smaller(img, size, fill=0):
min_size = min(img.size)
if min_size < size:
ow, oh = img.size
padh = size - oh if oh < size else 0
padw = si... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
#그래프에서 즉시 실행모드로 변환
tf.enable_eager_execution()
# x_data와 y_data동일
x_data = [1, 2, 3, 4, 5]
y_data = [1, 2, 3, 4, 5]
# 초기값을 임의 지정
W = tf.Variable(2.9)
b = tf.Variable(0.5)
# 가설함수
hypothesis = W * x_data + b
# tf.reduce_mean() 차... |
import logging
from flask import Blueprint
from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_login import current_user, login_required
from sqlalchemy import asc
from waitlist.utility import outgate
from waitlist.base imp... |
import cPickle as pickle
import pb_Models as Models
import lasagne
import theano
import numpy
import os
from learnedactivations import BatchNormalizationLayer
cur_dir = os.path.dirname(os.path.realpath(__file__))
def set_batchnorm_params(nn_model,eparams_filename):
""" Given a lasagne model, and an eparams_filena... |
from .Commands import *
from .CmdPatterns import *
from .CommandManager import CommandManager |
from urllib.request import urlopen
from urllib.request import HTTPError
from bs4 import BeautifulSoup
try:
html = urlopen("http://www.pythonscraping.com/pages/error.html")
except HTTPError as e:
print(e)
else:
bsobj = BeautifulSoup(html.read(), "html.parser")
print(bsobj.h1)
|
"""Treadmill runtime framework.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import errno
import glob
import logging
import os
import random
import socket
import stat
import tarfile
import six
from treadmill ... |
import os
import dj_database_url
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from . import *
DEBUG = False
SECRET_KEY = os.environ.get('SECRET_KEY', '+xz#p9=p*ahiz4l0pnp(lyhb^6gxe^7i^$=#$uj&(bs(v6cg=_')
ALLOWED_HOSTS = [
'trombinoscoop-2.herokuapp.com',
]
MIDDLEWARE += [... |
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from datetime import datetime
df_data=pd.read_csv("data/oar/job_oar_sample.csv")
df_data["real_time"]=df_data["start_time"]-df_data["stop_time"]
df_data["real_time"]=df_data["start_time"]-df_data["stop_time"]
df_data["start_time_mi... |
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from mycontacts import views
urlpatterns=[
url(r'accname.*',views.accname,name='accname'),
url(r'number.*',views.number,name='number'),
]
|
from spack import *
class Dire(Package):
url = "https://dire.gitlab.io/Downloads/DIRE-2.002.tar.gz"
version('2.002', sha256='7fba480bee785ddacd76446190df766d74e61a3c5969f362b8deace7d3fed8c1')
depends_on('pythia8')
def install(self, spec, prefix):
configure('--prefix=%s'%prefix,
... |
'''
Task:
Your job here is to create a function that will take three parameters,
fmt, nbr and start, and create an array of nbr elements formatted according
to frm with the starting index start. fmt will have <index_no> inserted at
various locations; this is where the file index number goes in each file.
Description ... |
def reversearr1(arr):
revarr = [0] * len(arr)
for i in range(0, len(arr)):
revarr[i] = arr[(len(arr)-1)-i]
return revarr
#time Complexity: O(N)
#space Comlexity: O(N)
def reversearr(arr):
n = len(arr)
start = 0
end = n - 1
while (start < end):
swap(arr, start, end)... |
class Tweet:
def __init__(self, id, date, text, score):
self.id = id
self.date = date
self.text = text
self.score = score
|
from __future__ import division
import math
import re
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
from scipy.signal import butter, lfilter
#----------------------------------------------------------------------------------------------------------------------#
def moving_average(in... |
import sys
import random
import pygame
from pygame.locals import *
import loadcard
import popup
import AI
class game():
def __init__(self, playernum, difficulty):
self.playernum = playernum
self.difficulty = difficulty
self.background = pygame.image.load('./img/default.png')
self.sc... |
from django.urls import path, re_path
from .apis import *
urlpatterns = [
path('iips/add', AddIipApi.as_view(), name='iip_add'),
re_path(r'^iips/list/(?:start=(?P<start>(?:19|20)\d{2}(0[1-9]|1[012])))&(?:end=(?P<end>(?:19|20)\d{2}(0[1-9]|1[012])))$', IipListApi.as_view(), name='iip_list'),
path('iips/upda... |
# -*- coding: utf-8 -*-
'''
Copyright of DasPy:
Author - Xujun Han (Forschungszentrum Jülich, Germany)
x.han@fz-juelich.de, xujunhan@gmail.com
DasPy was funded by:
1. Forschungszentrum Jülich, Agrosphere (IBG 3), Jülich, Germany
2. Cold and Arid Regions Environmental and Engineering Research Institute, Chinese Academ... |
import os
import os.path as osp
import mmcv
from glob import glob
from annotation_loader import parse_tables_from_xml
img_exts = [".bmp", ".jpg", ".jpeg", ".png", ".tiff"]
#https://mmdetection.readthedocs.io/en/latest/2_new_data_model.html?highlight=coco#coco-annotation-format
#or https://github.com/open-mmlab/mmdete... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 10:55:08 2019
@author: Vipin
"""
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,confus... |
# Generated by Django 3.0.1 on 2020-01-04 13:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0029_auto_20200103_1357'),
]
operations = [
migrations.AddField(
model_name='timeslot',
name='associated_ty... |
from alarm import alarm
from config import data
data = data.Data()
def priority():
alarm_string = str(data.alarm)
if data.keyword_3a in alarm_string:
alarm_new = data.keyword_3a_flag + alarm_string
else:
alarm_new = alarm_string
alarm.write_alarm(alarm_new)
|
def calculate():
score.append(max(parts))
pos=parts.index(max(parts))
parts[pos]=-99
for i in range(N//2):
#End for
if(N%2==1):
score.append(parts[0])
T=int(input())
for i in range(T):
N=int(input())
parts=[0]*N
string=input()
for k in range(N):
parts[k... |
"""
2 usages:
a. To smooth noisy detection results
b. To accelerate the whole procedure by merely using predict with some frames
rather than detecting per frame
"""
import cv2
import numpy as np
import math
from config import Configs
from video_helper import VideoHelper
from tracker import kcftracker
# First Tria... |
# coding:utf-8
import time
import ihelper
import iglobal
def __workspace_match_status(text, status):
for search_str in iglobal.GIT_STATUS_PATTEN[status]:
if search_str in text:
return status
return 0
__status = 0
out = 'this is'
for s_code, patterns in iglobal.GIT_STATUS_PATTEN.items():... |
from back.Model import Model
from body.RsvppsFileParser import RsvppsFileParser
from body.Validator import Validator
from front.Timer import Timer
class Controller:
def __init__(self):
self.__model = Model()
self.__timer = Timer()
self.__validator = Validator()
self.__wpm = None
... |
import os
import logging
from tqdm import tqdm
from torch.autograd import Variable
from torchvision.utils import save_image
import torch.nn.functional as F
import torch
import utils
import scipy.io as io
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
def visualize_training_gene... |
x = str(2 ** 1000000)
print(x.count('') - 1)
|
"""
.. module:: DataPreprocessing
DataPreprocessing
*************
:Description: DataPreprocessing
:Authors: bejar
:Version:
:Created on: 09/03/2015 8:35
"""
__author__ = 'bejar'
import numpy as np
import mne
from mne.io import read_raw_bti
import scipy.io
import logging
from config.paths import sm... |
import sys
import os
import socket
from PyQt5.QtCore import QTimer, pyqtSlot
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import threading
client = None
class MainWindow(QWidget):
def __init__(self, client):
self.client = client
super().__init__()
self.activate = True
... |
#Ceci est un projet scolaire pour mettre en place une base de données pour les projets de location de voitures
#importing--------------------------------------------------
from flask import Flask, render_template, request, session, redirect, url_for
from flaskext.mysql import MySQL
import pymysql
#app configuratio... |
import pytest
import warnings
import neworder as no
warnings.filterwarnings(action='ignore', category=RuntimeWarning, message=r't=')
def test_basics() -> None:
# just check you can read the attrs/call the functions
assert hasattr(no, "verbose")
assert hasattr(no, "checked")
assert hasattr(no, "__version__")... |
"""Copyright David Donahue 2017. When run, checks to see if user is ready for next event; texts user asking if they are ready for next event.
Extends duration of current event if user texts back implying they are not finished, or marks the current event as complete if user is finished. Basically, keeps track
of user pr... |
"""
The import emulation subsystem for windows.
"""
import ntdll
import kernel32
import secur32
import rpcrt4
import advapi32
import msvcrt
import user32
import gdi32
import ole32
import msvcr71
import ws2_32
import wsock32
import wininet
#oleaut32
#shlwapi
#shell32
|
#================================================================
#Author : Max R. Berrios Cruz
#Date: Jun 28, 2013
#Email: max.berrios@upr.edu
#Version:
#================================================================
import sys
from src.parser.input_output import i_o
from src.main.interface.main import main
fro... |
def Singleton(theClass):
""" decorator for a class to make a singleton out of it """
classInstances = {}
def getInstance(*args, **kwargs):
""" creating or just return the one and only class instance.
The singleton depends on the parameters used in __init__ """
key = (theClass, ... |
# import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.model_selection import GridSearchCV as GS
from sklearn.metrics import accuracy_score, log_loss
import os
import sys
eps = sys.float_info.... |
def main():
fname = input("enter file name: ")
infile = open(fname, "r")
outfile = open("After.txt", "w")
for line in infile.readlines():
print(line.upper(), file=outfile , end="")
infile.close()
outfile.close()
main() |
from wordcloud import WordCloud
import pandas as pd
def show_wordcloud():
print('showing wordcloud')
d = {}
bag = pd.read_csv('results/3gram_tfidf.csv')
for term, rank in bag.values:
d[term] = rank
wordcloud = WordCloud()
wordcloud.generate_from_frequencies(frequencies=d)
# plt.... |
#!/usr/bin/env python3
import json
from lib.pos import Pos
from lib.zone_manager import ZoneManager
with open("../config/region_1.json", "r") as fp:
region_1_prop = json.load(fp)
fp.close()
test = ZoneManager(region_1_prop["locationBounds"])
tree = test.tree
print("-"*120)
print("Ave depth: {:04.2f}".forma... |
import pandas as pd
from Funkcje.WczytywanieDanych.loadNormalFiles import loadNormalFilesWithoutHeader, loadNormalFilesWithHeader
from Funkcje.WczytywanieDanych.removeSymbolicValue import removeSymbolicValue
def otwieraniePlikow(dane):
if '3D_spatial_network1.csv' in dane:
daneDF = loadNormalFilesWithout... |
from Bio import SeqIO
import pinetree as pt
import sys
import os
import datetime
import argparse
import multiprocessing
import random
import copy
import csv
CELL_VOLUME = 1.1e-15
PHI10_BIND = 1.82e7 # Binding constant for phi10
IGNORE_REGULATORY = ["E. coli promoter E[6]",
"T7 promoter phiOR",
... |
import numpy as np
from . import DistributionFunction as DistFunc
from . DistributionFunction import DistributionFunction
# BOUNDARY CONDITIONS (WHEN f_re IS DISABLED)
# (NOTE: These are kept for backwards compatibility. You
# should _really_ use 'DistributionFunction.XXX' instead)
BC_F_0 = DistFunc.BC_F_0
BC... |
# Generated by Django 3.2.3 on 2021-05-24 15:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('categories', '0001_initial'),
('beverages', '0001_initial'),
]
operations = [
m... |
from django.db import models
# Create your models here.
#Models define the structure of database tables
# item, description, number in stock
#allow admins create, edit or delete (to do list)
#class called Item
#Field called title that accepts characters < 200
#Description field uses text field since we do not know t... |
# coding: utf-8
# Standard Python libraries
from pathlib import Path
from typing import Optional, Union
# http://www.numpy.org/
import numpy as np
import numpy.typing as npt
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataModelDict as DM
from yabadaba import load_query
# Local imports
fr... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_msgbox.ui'
#
# Created by: PyQt5 UI code generator 5.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_msgbox(object):
def setupUi(self, msgbox):
msgbox.setObjec... |
# Решить следующее рекуррентное соотношение:
# a_n+2+9a_n=0,a0=a1=1.
# Внимание: cos(π) набирать как cos(pi).
http://www.wolframalpha.com/input/?i=0%3Da%28n%2B2%29%2B9*a%28n%29%2C+a%280%29%3D1%2C+a%281%29%3D1
|
from datetime import datetime
from django.db import models
# Create your models here.
class Empresas(models.Model):
nome = models.CharField(max_length= 30)
def __str__(self):
return self.nome
class Acao(models.Model):
sigla = models.CharField(max_length=10)
empresa = models.Fore... |
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import telebot
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
'start':'1',
'limit':'500',
'convert':'USD'
}
headers = {
'Accepts': 'applicatio... |
from __future__ import unicode_literals
import re
import urllib
from django.db import models
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import bleach
# Create your models here.
class Chirp(models.Model):
content = models.CharField(max_length=140)
timestamp = models.Dat... |
import json
from ipywidgets import DOMWidget, Output, Widget, register, widget_serialization
from ipywidgets.widgets.trait_types import InstanceDict
from traitlets import Unicode, Int, List, Instance, Bool, validate, TraitError
from traitlets.utils.bunch import Bunch
from .options import *
from ._version import EXT... |
from pandac.PandaModules import *
from pirates.world.WorldCreatorBase import WorldCreatorBase
from direct.directnotify.DirectNotifyGlobal import directNotify
from pirates.world.DistributedIslandAI import DistributedIslandAI
from pirates.world.DistributedOceanGridAI import DistributedOceanGridAI
from pirates.instance.Di... |
import numpy
matrix = list(map(int,input().split()))
matrix2 = list(map(int,input().split()))
print(numpy.inner(matrix,matrix2))
print(numpy.outer(matrix,matrix2)) |
"""flowsheet_control_test.py
* This contains tests for results instance
Joshua Boverhof, Lawrence Berekeley National Lab, 2018
John Eslick, Carnegie Mellon University, 2014
See LICENSE.md for license and copyright details.
"""
import io
import json
import logging
import time
import uuid
import urllib.request
from shu... |
class Node:
def __init__(self,data):
self.data=data
self.ref=None
class Linked_list:
def __init__(self):
self.head=None
def traverse(self):
if self.head is None:
print("Linked list is empty")
else:
n = self.head
while n is not Non... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import re
from datetime import datetime
#ori_reg = re.compile(r"Orig: (0x\w{4})")
#cmd_reg = re.compile(r"Cmd: (0x\w{4})")
#par_reg = re.compile(r"Param: (.+)$")
#lin_reg = re.compile(r"^\[Dispatcher\]")
lin_reg = re.compile(r"^fp2_pay_i_multiplexing")
... |
#!/usr/bin/env python
import sys,re,time,argparse
def main(args):
sys.stdout.write("Start analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") + "\n")
sys.stdout.flush()
best_alignment(args.input,args.output)
sys.stdout.write("Finish analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") + "\n")
sys.stdout.flush()
d... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from revolver import contextmanager as ctx
from revolver import file, text
def ensure(lines):
with ctx.sudo():
file.update('/etc/sudoers', lambda _: text.ensure_line(_, *lines))
|
import os
BASE_DIRS = os.path.dirname(__file__)
#参数
options = {
"port": 8000
}
#配置
settings = {
"static_path": os.path.join(BASE_DIRS, "static"),
"template_path": os.path.join(BASE_DIRS, "templates"),
"debug": False
}
|
from ..FeatureExtractor import FeatureExtractor
from common_functions import ChiSquare
class chi2extractor(FeatureExtractor,ChiSquare):
active = True
extname = 'chi2' #extractor's name
def extract(self):
dc = self.fetch_extr('dc')
chisquare = self.chi_square_sum(self.flux_data,lambda x: dc,x=self.time_data,rms=... |
from enum import Enum
import bleach
import markdown
import requests
from babel.dates import get_timezone_name
from django.contrib.auth.models import AbstractUser
from django.contrib.gis.db.models import PointField
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.text import ... |
#!/usr/bin/env python2.7
import sys, os, zipfile
def parse(fobj):
baseurl = "https://www.pythonanywhere.com/user"
for line in fobj.readlines():
for r in ["<span>", "</span>", "<p>", "</p>", "<br>"]:
line = line.replace(r,'')
line = line.replace( "%20", " ")
... |
#列表 相当于Array
name_List = ['George','John','Lina','Alex','Mars','Duke'];
print(name_List);
# 在列表中加入元素
# append 只会把值添加到最后面,并且一次只能添加一个
name_List.append('Tim');
print(name_List);
# insert (0, 'Coco'), 在下标0的位置插入 'Coco'
name_List.insert(0,'Coco');
print(name_List);
# extend
name_List_2 = ['王菲','梁朝伟','谢霆锋','张学友']
na... |
from sys import float_info
#https://www.interviewcake.com/question/python/stock-price
#for every time stamp t compare with every other timestamp after it
#save the difference t_n - t
#output max
#analysis
#sum(n to 1) n = n(n-1) /2 = O(n^2)
#is there a better solution?
#we need to consider every pair of values
#fin... |
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Sequential
from dask.distributed import Client, LocalCluster
from sklearn.metrics import mean_squared_error
import numpy as np
def main():
cluster = LocalCluster(n_workers=4, threads_per_worker=1)
clien... |
import tempfile
import boto3
from django.conf import settings
class S3Wrapper:
def __init__(self, bucket_name):
resource = boto3.resource(
"s3",
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
)
self.b... |
from django.db import models
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from rest_framework.authtoken.models import Token
from django.dispatch import receiver
from django.db.models.signals import post_save
import datetime
from django.utils.translation im... |
from collections import Counter
class Solution(object):
def frequency_sort(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return ""
s_counter = Counter(s)
# then sort the counter
counter_sort = sorted(s_counter.items(), key=lambda x... |
"""
Tests of functions to interpolate across geography.
"""
import numpy as np
from numpy.testing import assert_allclose
import pytest
import solar_energy
@pytest.fixture
def setup_linear():
x_grid = np.arange(3)
y_grid = np.arange(3)
z = np.ones((len(x_grid), len(y_grid)))
z = (z*x_grid).T*y_grid
... |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
import pytest
from time import sleep
from pages.signuppage import SignUpPage
from webdriver_manager.chrome import ChromeDriverManager
from info.info import TestData
from selenium import webdriver
class TestSignUPage(object):
@pytest.fixture()
def setup(self):
self.driver = webdriver.Chrome(ChromeDrive... |
# -*- coding:utf-8 -*-
name_dic = {u'刘增艳': ['fueiru_aki', 'SNH', 'XII', 5], u'陈音': ['chole_yin1205', 'SNH', 'XII', 5],
u'孙珊': ['superss0211', 'BEJ', 'B', 6], u'洪珮雲': ['realf_airy', 'SNH', 'XII', 5],
u'费沁源': ['nemo_fqy', 'SNH', 'XII', 5], u'林忆宁': ['lyn_erika', 'SNH', 'X', 6],
u'万丽娜': ... |
"""
Uzrakstiet programmu Python, lai pārbaudītu,
vai vairākiem ievadītajiem mainīgajiem ir vienāda vērtība.
"""
"""
a = 30
b = 40
c = 50
# method 1
if a == 10 or b == 10 or c == 10:
print("True")
else:
print("False")
# method 2
if 10 in (a, b, c):
print("True")
else:
print("False")
... |
t = (int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')))
print(f'O número 9 aparecu {t.count(9)} vezes.')
if(3 in t):
print(f'O primeiro número 3 está na posição {t.index(3) + 1}')
else:
print('Não possui número 3.... |
def clean(data):
"""
removes all rows with empty data in the Results column and all useless
columns
fixes some of the time formatting for weird times
"""
data['Result'] = data['Result'].astype(str)
data = data[data['Result'] != 'None']
data = data.drop(['Unnamed: 8'], axis=1)
data['... |
# -*- coding: utf-8 -*-
'''
Created on Sep 6, 2012
@author: YuqiChou
'''
from db.page import DEFAULT_PAGE_SIZE
def global_list_per_page(context):
return {'GLOBAL_LIST_PER_PAGE': DEFAULT_PAGE_SIZE} |
from bottle import run, default_app, template, request, response
from bs4 import BeautifulSoup
import requests
import urllib.parse
import json
APP = default_app()
PssWd = {'acpwd-pass': 'anime1.me'}
def drive(d):
BaseUrl = 'https://drive.google.com/uc?export=download&id='
url = BaseUrl + d
try:
r = requests.po... |
# coding: utf-8
import functools
import os
import json
import jinja2
import bottle
class BaseApp(bottle.Bottle):
__jinja2_env = None
_config = None
catchall = False
DEFAULT_CONFIG = {}
def __init__(self, config=None):
self.routes = []
self.router = bottle.Router()
self.resources = bottle.ResourceManager(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.