text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
import scrapy
import json
import random, time
from loguru import logger
from scrapy.utils.project import get_project_settings
from KuaiShou.items import KuxuanKolUserItem
class KuxuanKolUserSpider(scrapy.Spider):
"""
这是一个根据酷炫KOL列表接口获取seeds,并以快手的user_id为切入点,补全相关作者的基本信息,构建KOL种子库的爬虫工程
... |
import json
import os
from os import path
from absl import app
from absl import flags
import jax
import numpy as np
from PIL import Image
FLAGS = flags.FLAGS
flags.DEFINE_string('blenderdir', None,
'Base directory for all Blender data.')
flags.DEFINE_string('outdir', None,
'Wh... |
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,3:].values
#elbow Method
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11,1):
kmeans = KMeans(n_clusters=i,init='k-means++',random_state=42)
kmeans.fit(X)
wcss.app... |
"""
MIT License
Copyright (c) 2018 Max Planck Institute of Molecular Physiology
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-19 13:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... |
"""
Proxy models
These models exist so that we can present
more than one view of the same DB table in /admin
"""
from datetime import datetime
from django.contrib.gis.db.models import Q
from django.db.models import Manager
from .divisions import OrganisationDivision
from .organisations import Organisation, Organisa... |
import matplotlib.pyplot as plt
import numpy as np
def plot_figures(fpr, tpr, history, auc, roc_fn, loss_fn, accuracy_fn):
lw = 2
dpi = 150
plt.figure()
plt.plot(fpr, tpr, lw=lw, label="ROC curve (area = {:0.2f})".format(auc), color='darkorange')
plt.plot([0, 1], [0, 1], label='random guessing'... |
import os
import sys
sys.path.insert(0, 'tools/families')
sys.path.insert(0, 'tools/trees')
import find_neighbors_to_fam
import fam
import read_tree
import rf_distance
import prune
def get_induced_gene_tree(datadir, family, method, subst_model, leaf_set):
gene_tree_path = fam.get_gene_tree(datadir, subst_model, fami... |
from _typeshed import Incomplete
from collections.abc import Generator
def triadic_census(G, nodelist: Incomplete | None = None): ...
def is_triad(G): ...
def all_triplets(G): ...
def all_triads(G) -> Generator[Incomplete, None, None]: ...
def triads_by_type(G): ...
def triad_type(G): ...
def random_triad(G, seed: Inc... |
# import sys
# sys.path.insert(0,'..')
# sys.path.insert(1,'../n1_local_image_descriptors')
# import sift
import imtools
from n1_local_image_descriptors import sift
from numpy.ma import log
from scipy.cluster.vq import *
from numpy import *
import pickle
class Vocabulary(object):
def __init__(self, name):
... |
import smtplib
import pandas as pd
import numpy as np
import pyrebase
import os
'''config = {
"apiKey": "AIzaSyAXtE0fQeJSN8r1Omtyx5vTlsdyYrF9XpE",
"authDomain": "tympass-32736.firebaseapp.com",
"databaseURL" : "https://tympass-32736.firebaseio.com",
"projectId": "tympass-32736",
"storag... |
"""
Parse QoS statistics such as throughput and jitter from Spirent traffic measurement,
apply criteria, and report testing result
input: 1. a list of remotes: e.g. remote_list = ['e8350', 'x1', 'x3', 'x7', 'x5-A', 'x5-B']
2. a list of priority ("default" or "not_default"):
"def... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
class Account(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
def get_absolute_url(self):
... |
from genetic_algorithm import GA
from experiments.plots import plot_param_evolution
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
import matplotlib
def main():
"""
This function runs variation 3.
In variation 3, the population of individuals is generated with rando... |
# web address for exercise: https://repl.it/@appbrewery/day-4-3-exercise
# 🚨 Don't change the code below 👇
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure?\n")
# 🚨 Don't change t... |
default_app_config = 'gim.front.apps.FrontConfig'
|
from rest_framework.viewsets import ModelViewSet
from .mixins import HistoryModelMixin
class HistoryModelViewSet(HistoryModelMixin, ModelViewSet):
pass
|
# -*- coding: utf-8 -*-
from datetime import date
from unittest import TestCase
import six
from .helpers import example_file
from popolo_data.importer import Popolo
class TestOrganizations(TestCase):
def test_empty_file_gives_no_organizations(self):
with example_file(b'{}') as filename:
p... |
#!/usr/bin/env python
from generate_cluster_job import generate_cluster_job
import sys
import subprocess
if __name__ == "__main__":
queue = sys.argv[1]
assert queue in['tf', 'rz', 'rzx', 'test'], ("only know "
"rz, rzx, tf and test queues, not: " + queue)
if queue != 'rzx':
queue_name = "me... |
salario = float(input('Digite seu slario:'))
aumento = (salario * 15)/100
print('O aumento de 15% do salário é:{:.2f}'.format(salario+aumento))
|
"""
Um programa simples.
Estava fazendo sem ao menos saber usar o while...
"""
valor = input("Digite um número: ")
caracters = len(str(valor))
algarismo = "Algarismo"
número_algarismo = 1
fatiamento = 0
while caracters > 0:
x = str(valor[fatiamento])
print("{} {}: {}.".format(algarismo, número_... |
from async_consumer import ReconnectingConsumer
from gene_dispatcher import process
import logging
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
... |
# _*_ coding:UTF-8 _*_
import win32con
import win32api
import random
import ctypes
import ctypes.wintypes
import threading
import time
import os
import sys
from winapi import window_capture
from other.cv2_t2 import get_can_cant_use
from other.cv2_t3 import read_img_p_count
from icevisual.Utils import Utils
RUN = Fal... |
def myfnc(x,z,y=10):
print("x =",x,"y = ",y,"z =", z)
myfnc(x = 1,y = 2,z = 5)
a = 5
b = 6
myfnc(x = a,z = b)
a = 1
b = 2
c = 3
myfnc(y = a,z = b,x = c)
|
number = "+918155873903" |
import re
import jieba
import pandas as pd
def data_process(file='./data/message80W1.csv'):
"""
垃圾短信 0 720000
正常短信 1 80000
"""
# header=None 没有列名 header=None 第0行是行索引
data = pd.read_csv(file, header=None, index_col=0)
data.columns = ['label', 'message']
data['label'].value_counts()
... |
message="""We present to you the final week of Aperture.
Theme: Hues Of Bliss
Deadline: 7th October
Send your entries with your Name, College and a caption to fmc@antaragni.in
#HuesOfBliss
#Antaragni16"""
message =""" """+ message+""" #"""
hash_find = message.split("""#""")
print hash_find
len_hash = len(hash_find)
h ... |
# Generated by Django 2.2.12 on 2020-09-11 07:46
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('admin', '0016_auto_20200602_1201'),
]
operations = [
migrations.CreateModel(
... |
# -*- coding:latin-1 -*-
import random
import math
seed = random.randint(1,100000000000)
print("Current Seed: " + str(seed))
random.seed(seed)
class Input: #takes in its value, most of the time a random number
def __init__(self, value):
self.value = value
class Neuron: #takes in its value... |
#coding=utf-8
# 完成debug,创建Data_matrix实体类就可以获得datax 和datay
import numpy as np
import time
class User:
def __init__(self, info):
self.id = int(info[0])
self.grade = int(info[1])
self.sex = int(info[2])
if info[3] != '':
timestring = info[3]
self.brith = int(ti... |
for letter in "fox":
if letter == "f":
print letter
|
import cv2 as cv
import numpy as np
import math
def my_conv():
cimg = cv.imread("2.jpg")
img = cv.cvtColor(cimg, cv.COLOR_BGR2GRAY)
img_height = len(img)
img_width = len(img[1])
img = cv.resize(img, (int(img_width*0.8), int(img_height*0.8 )))
xKernal = cv.getGaussianKernel(ksize=13, sigma=2)
... |
# -*- coding: utf-8 -*-
from gevent import monkey; monkey.patch_all()
from bottle import run, response, request, route
import time
import asyncio
import subprocess
import random
import uuid
def fire_and_forget(f):
'''decorator'''
from functools import wraps
@wraps(f)
def wrapped(*args, **kwargs):
... |
#!/usr/bin/env python3.4
# -*- coding: utf-8 -*-
#
# Copyright 2016 Ramil Nugmanov <stsouko@live.ru>
# This file is part of predictor.
#
# predictor
# is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundati... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 20:35:12 2018
@author: Paul Charnay
"""
import numpy as np
records_array = np.array([1, 4, 3, 2, 2])
vals, inverse, count = np.unique(records_array, return_inverse=True, return_counts=True)
idx_vals_repeated = np.where(count > 1)[0]
vals_repeated = vals[idx_vals_rep... |
from django.contrib import admin
from .models import Category, Product, ProductPicture, ProductDetailedDescription
from nested_admin.nested import NestedTabularInline
from nested_admin.polymorphic import NestedStackedPolymorphicInline, NestedPolymorphicModelAdmin
from ..common.models import Article
from ..common.admin ... |
"""Helper script to package wheels and relocate binaries."""
import glob
import hashlib
# Standard library imports
import os
import os.path as osp
import platform
import shutil
import subprocess
import sys
import zipfile
from base64 import urlsafe_b64encode
# Third party imports
if sys.platform == "linux":
from ... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#########################################################################################
# #
# create_limit_tables.py: create limit databases for msid trendi... |
from flask import Flask
from flask import render_template
app = Flask(__name__)
def get_data():
#把要呈現的數字字串寫在這裡
data = "[1,2,4,5,8,5,2,1,4,5,6,8],[9,8,7,2,8,5,2,1,4,5,6,8],[9,8,7,2,8,5,2,1,4,5,6,8]"
return data
@app.route("/")
def index():
data = get_data()
return render_template("line_chart.html"... |
# My solution
n = input()
number_of_digit = n.count('4') + n.count('7')
if number_of_digit == 4 or number_of_digit == 7:
print('YES')
else:
print('NO')
# Alternate solution
print("NYOE S"[sum(i in '47' for i in input()) in (4, 7)::2].strip())
|
import pandas as pd
__author__ = 'obr214'
"""
DataReader Class
It reads a file, creates a dataframe and clean it according to the values needed.
"""
class DataReader:
def __init__(self, file_name):
try:
self.dataframe = pd.read_csv(file_name, usecols=['CAMIS', 'BORO', 'GRADE', 'GRADE DATE'])... |
import mysql.connector
import datos_db
conexion = mysql.connector.connect(**datos_db.dbConnect)
cursor = conexion.cursor()
sql = "delete from usuarios where id = 22"
cursor.execute(sql)
n_id = int(input("Id: "))
sql = "delete from usuarios where id = %s"
cursor.execute(sql,(n_id,))
sql = "delete from usuarios wher... |
import eelbrain as e
# settings
n_samples = 1000
# Load data
ds = e.datasets.get_mne_sample(tmin=-0.1, tmax=0.2, src='ico', sub="modality=='A'")
# compute distribution of max t values through permutation
res = e.testnd.ttest_ind('src', 'side', 'L', 'R', ds=ds, samples=n_samples, tstart=0.05)
# generate parameter... |
import imgpr.image as image
import imgpr.warp as warp
import imgpr.layers as layers
import imgpr.filtering as filtering
import imgpr.utils as utils
from imgpr.session import Session
from imgpr.layers import placeholder
from imgpr.consts import *
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# Infitweaker - Copyright 2012 Alex Kaplan
# FreeType high-level python API and rendering - Copyright 2011 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----... |
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
from constants import nb_class
from tracking import get_dataframes
tf.compat.v1.enable_eager_execution() # Remove when switching to tf2
pd.plotting.register_matplotlib_converters()
###############################
# Methods for data formattin... |
import os
import json
import pickle
import gc
import numpy as np
import pandas as pd
from spyro.utils import progress
from spyro.memory import ReplayBuffer
from spyro.policies import (
EpsilonGreedyPolicy, GreedyPolicy,
RandomPolicy, SoftmaxPolicy,
FixedActionPolicy
)
from spyro.agents import (
DQNAge... |
from string import punctuation
def nothing_special(s):
try:
return s.translate(None, punctuation)
except AttributeError:
return 'Not a string!'
|
from hamcrest import assert_that, equal_to
from bromine.utils.geometry import Rectangle, RectSize
from bromine.utils.wait import Wait
from selenium.common.exceptions import TimeoutException
class SimpleVerticalLayout(object):
def __init__(self, page):
total_width, total_height = page.size
visibl... |
import requests, random
class Unsplash:
def __init__(self):
self.path = "YourPath/unsplash.jpg"
self.KEY = "YourKey"
def get_random_image(self):
response = requests.get("https://api.unsplash.com/photos/random/?client_id=" + self.KEY).json()
return response["urls"]["full"]
def get_photo(self, term):
ran... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 17 14:10:00 2020
@author: peter_goodridge
"""
from pymongo import MongoClient
import os
from flair.data import Sentence, build_spacy_tokenizer
from flair.models import SequenceTagger
from flair.embeddings import BertEmbeddings
import spacy
import json
import pandas as pd... |
import numpy as np
def sample_LRRNN(N, params):
nettype = params["nettype"]
if nettype == "rank1_spont":
g = params["g"]
Mm = params["Mm"]
Mn = params["Mn"]
Sm = params["Sm"]
Sn = params["Sn"]
x1 = np.random.normal(0.0, 1.0, (N, 1))
x2 = np.random.normal... |
from __future__ import division
from sklearn.cluster import KMeans
from numbers import Number
#from pandas import DataFrame
import sys, codecs, numpy
import sklearn
from sklearn.manifold import TSNE
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
class autovivify_list(dict):
''... |
n=int(input('Enter:'))
if n>0:
temp=n
s=0
while temp>0:
dig=temp%10
fact=1
for i in range(1,dig+1):
fact=fact*i
s+=fact
temp//=10
if s==n:
print('Strong num')
else:
print('No')
else:
print('No')
# def fact(k):
# if k==0:
... |
import json
import requests
import websocket
import random,time
from websocket import create_connection
ws = create_connection('ws://localhost:8000/ws/some_url/')
for i in range(1000):
time.sleep(3)
ws.send(json.dumps({'Temperatura':random.randint(20,60), "Humedad":random.randint(20,60) }))
ws.close() |
import os
import sys
import ntpath
from os import listdir
from os.path import isfile, join
from base import SingleInstance
import settings
from doxieautomator.doxie import DoxieAutomator
import dropbox
class DoxieToDropbox(SingleInstance):
LOCK_PATH = os.path.join(os.path.abspath(os.path.dirname(sys.argv... |
# programa que leia um vetor de 10 numeros reais e mostre-so na ordem inversa
vetor = []
x = 1
while x <= 10:
n = float(input("Digite um número: "))
vetor.append(n)
x+=1
i = 9
while i >= 0:
print("Vetor Lido: ", vetor[i])
i-=1
|
import commands
import math
def i2cGetWord(addr):
out = commands.getoutput("sudo i2cget -y 1 0x68 "+ addr + " w")
return (out[4]+out[5]+out[2]+out[3])
def i2cGetWord_HMC5883L(addr):
out = commands.getoutput("sudo i2cget -y 1 0x1e "+ addr + " w")
return (out[4]+out[5]+out[2]+out[3])
#MPU6050
def accel_X():
ret... |
import requests
import csv
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
start=1
end=501
headlines=[]
news=[]
target=[]
user_agent = UserAgent()
for i in range(start,end): #iterating through web pages
r=requests.get(f'https://www.politifact.com/factchecks/list/?... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
import requests
import json
url = "http://192.168.11.220:9900/getstr"
data = {
# "list1":[x for x in range(1000000)]
# "list1":[93,62,51,93,75,82,93,62,65,51,86,89,100]
"str1":12,
"str2":["你好","大"]
}
data=json.dumps(data,ensure_ascii=Tru... |
'''
Compose new poem using Markov model.
'''
import numpy as np
def read_data():
poem = open("../data/nguyen-binh.txt").read()
poem += open("../data/truyen_kieu.txt").read()
lines = poem.lower().split("\n")
return lines
def create_frequency_matrix(lines):
state_transition_matrix = dict()
s... |
# Create an empty set literal
showroom = set()
print(type(showroom))
# Add new values to set
showroom.update(['GMC', 'Honda', 'Toyota', 'Ford'])
print(showroom)
# Print the length of set
print(len(showroom))
# Add more cars
showroom.update(['Nissan', 'Lincoln'])
print(showroom)
# Delete a car
showroom.discard('Niss... |
# -*- coding: utf-8 -*-
# -*- author: hechao -*-
|
# Given a set of objects with a value V, and a weight W, and having a bag that can carry,
# at most, a weight Max_W, find a way to fill the bag maximizing the value of the objects
# inside, in this version, it is assumed we can take a fraction of each object and carry only
# that, having, of course, its value multiplie... |
import unittest
from iranlowo import corpus
class TestCoprusLoader(unittest.TestCase):
def setUp(self):
self.owe_loader = corpus.OweLoader
def test_load_owe(self):
with self.assertRaises(NotADirectoryError):
self.owe_loader()
|
#!/usr/bin/env python
from distutils.core import setup, Extension
setup(name='pyGtranslator',
version='0.6',
description='GUI tool for Google translate',
author='Radovan Lozej',
author_email='radovan(dot)lozej(at)gmail(dot)com',
url='http://xrado.hopto.org',
classifiers=[
'Environment :: X11 Applications',
... |
from os import path
import pandas as pd
from glob import glob
from down_util import pr_from_pid
if __name__ == '__main__':
pr_china = r"Z:\yinry\china.mosaic\china.pr.txt"
# pr_china = r"Z:\yinry\global_mosaic\0.def\prwithrange.csv"
check_dir = r'Z:\yinry\china.mosaic\1986\4.rgb'
pr_china = pd.read_csv... |
#Face rec using OpenCV
import cv2
import os
import numpy as np
from PIL import Image
from pathlib import Path
###
# For face DETECTION we will use the Haar Cascade provided by OpenCV.
cascade_path = "/Users/jatinsethi/Downloads/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascade_path)
###
#... |
import paho.mqtt.client as mqtt
import time
from random import random, sample
import json
laumios = set()
addVol = 0
updatedVol = True
musicVOL = 50
selec = -1
selected = set()
isPlaying = False
answer = None
def toVol(v):
return max(0, min(100, v))
def on_message(client, userdata, msg):
global tmin, tmax
global ... |
# -*- coding: utf-8 -*-
"""
@author: Aayush Chaube
"""
from tkinter import *
from tkinter import messagebox
import re, pymysql
from PIL import *
def adjustWindow(window):
w = 600 # Width for the window size
h = 600 # Height for the window size
ws = screen.winfo_screenwidth() # Width of the screen
hs ... |
"""A client for the CONSTELLATION external scripting API."""
import pandas as pd
# Add the directory containing the internal file to the import path.
#
cc_path = '../../../../../../../../../../../CoreUtilities/src/au/gov/asd/tac/constellation/utilities/webserver'
import sys
sys.path.append(cc_path)
import constellat... |
from landscapesim.async import tasks |
print("sum of list")
def sum_list(L):
if len(L) == 1:
return L[0]
else:
return L[0] + sum_list(L[1:])
L = [2, 2, 2, 2, 2]
print(sum_list(L))
print("harmonic series")
def harmonic_sum(n):
if n == 1:
return 1
else:
return 1 / n + harmonic_sum(n - ... |
age =30
inputage = int(input("guess_age:"))
if(age == inputage):
print("congratulations you")
elif(age > inputage):
print("Think big")
else:
print("Think small") |
import json
import matplotlib.pyplot as plot
import csv
import os
import argparse
import pandas as pd
import numpy as np
from itertools import combinations
folder = '/cmsnfsbrildata/brildata/vdmoutput/AutomationBackgroundCorrection/Analysed_Data/'
scanpair = '/cmsnfsbrildata/brildata/vdmoutput/AutomationBackgroundCor... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/31 21:44
# @Author : Yunhao Cao
# @File : __init__.py
__author__ = 'Yunhao Cao'
__all__ = [
]
def _test():
pass
def _main():
pass
if __name__ == '__main__':
_main()
|
from django.db import models
class MostRecent(models.Model):
Images = models.ImageField(default="default.jpg",upload_to='pictures')
foodname = models.CharField(max_length=200)
prize = models.CharField(max_length=200)
class Feedback(models.Model):
name = models.CharField(max_length = 100)
feed = mo... |
#!/usr/bin/env python3
import sys
def main(filename):
with open(filename) as rd:
data = rd.readlines()
t = 0
t2 = 0
for line in data:
t += evaluate(line)
t2 += evaluate(line, True)
print("1: ", t)
print("2: ", t2)
def evaluate(fmath, sep=False):
newf = fmath
... |
from . import palette_png
|
import discord
import asyncio
import logging
from discord.ext import commands
from msgstats import GuildStatistics
import config
STATS_FOLDER = 'DiscordStats'
class StatsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.scraped_messages = 0
@commands.Cog.listener()
async def on_ready(se... |
from transforms import *
from vector import *
from tkColorChooser import *
##
# Rotate object in center of screen by offset amount along x axis.
# Translates to origin and back to ensure object looks as if it rotates around its own origin
##
def rotate_x(val):
global scene, origin, invorigin
val = float(val)
... |
import game_framework
import logo_state
from pico2d import *
open_canvas()
game_framework.run(logo_state)
close_canvas()
|
if __name__ == "filters":
pass
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 12:41:42 2013
@author: bejar
"""
import scipy.io
from numpy import mean, std
import matplotlib.pyplot as plt
from pylab import *
import pylab as pl
from mpl_toolkits.mplot3d import Axes3D
from sklearn.svm import SVC
from sklearn.cross_validation import cross_val_scor... |
"""Случайное блуждание"""
from random import choice
class RandomWalk:
"""Класс для генерирования случайных блужданий"""
def __init__(self, num_points=5000):
"""Инициализирует атрибуты блуждания"""
self.num_points = num_points
# Все блуждания начинаются с точки(0, 0).
self.x_va... |
import numpy as np
import pandas as pd
def IsSpell(arr):
spell = 0
if np.all(arr == arr[0], axis = 0):
spell = 1
return spell
def Merge2RainAverage(arr, spell_num):
'''
takes in 1) numpy array of size (years, days) AND 2) the number of days to create a spell,\
and returns a new array of shape (x,y) with e... |
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
m, n = len(a), len(b)
return -1 if a == b else max(m, n) |
#! /usr/bin/env python
import sys
with open(sys.argv[1], 'r') as infile:
header = infile.readline().rsplit()
print("chr\tstart\tend\t" + "\t".join(header[1:]))
for line in infile:
line = line.rsplit()
coords = line[0].split(":")
chromosome = "chr" + coords[0]
position = in... |
#!/usr/bin/env python2.7.12
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 13:30:12 2019
@author: thomas
"""
#This script will generate images of the spherobots and fluid flow up until
#the last time step that was recorded
#Specify 1) Dist bw spherobots (R) 2) Angle 3) Anti or Para 4) SSL or LSL
#Import databases ... |
import glob
import pdb
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.colors import BoundaryNorm
def sparseFull(a):
"""This expands a sparse grid, incorporating all data values"""
"""SLOWWWWWWWWW"""
# Create empty shape f... |
# coding: utf-8
"""Parser for Specification section of an MDN raw page."""
from .html import HnElement, HTMLElement, HTMLText
from .kumascript import (
KumaScript, KumaVisitor, SpecName, Spec2, kumascript_grammar)
from .utils import join_content
from .visitor import Extractor
class SpecSectionExtractor(Extractor... |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC, LinearSVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
#붓꽃데이터 읽어들이기
colnames = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Name']
iris_data = pd.read... |
class Solution:
#先确定一个overlap的区间,然后不断更新
def findMinArrowShots(self, points: List[List[int]]) -> int:
if(points == []):
return 0
points.sort(key = lambda x:(x[0],x[1]))
count = 1 #at least need one time
overlap = points[0]
for i in range(1, len(points... |
from perlin_noise import PerlinNoise
from PIL import Image
from random import randint
import numpy as np
SEED=randint(0,999999)
print(f"Generating perlin noise generators (SEED={SEED})...")
noise1 = PerlinNoise(octaves=3 , seed=SEED)
noise2 = PerlinNoise(octaves=6 , seed=SEED)
noise3 = PerlinNoise(octaves=12, seed=S... |
import support_lib as bnw
import add_player as addp
import parse_config as parser
import email_poller as email
import login_player as login
import options as options
import player_status as status
import trade_route as trade
import retrieve_settings as settings
import port_handler as port
import time
import random
fro... |
#!/usr/bin/env python
""" Example for detect IP Fragmentation attacks on the network """
import sys
import os
import pyaiengine
delta = 100
previous_fragments = 0
previous_ip_packets = 0
def timer_5seconds():
global delta
global previous_fragments
global previous_ip_packets
ipstats = st.get_counte... |
import pytest
from convert_chars import convert_pybites_chars
@pytest.mark.parametrize("arg, expected", [
("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do",
"LorEm IPSum dolor SIT amET, conSEcTETur adIPIScIng ElIT, SEd do"),
("Vestibulum morbi blandit cursus risus at ultrices",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bibtexparser
from bibtexparser.bparser import BibTexParser
import re
from pypinyin import pinyin, Style
def to_pinyin(string):
return ' '.join(sum(pinyin(string, style=Style.TONE3), []))
def if_containing_chinese(test_string):
return bool(re.findall(r'[\... |
import requests
import copy
import multiprocessing
import argparse
DENOMINATOR = 1000000000000.0
body = {
"id": "1",
"jsonrpc": "2.0",
"method": "GetBalance",
"params": []
}
zil_api = "https://api.coingecko.com/api/v3/coins/zilliqa?community_data=false&developer_data=false&sparkline=false"
def get_z... |
import os
import argparse
import torch
import asyncio
import pandas as pd
from json import load
from core.CryptoCompare import *
from core.neuralnet import *
from core.preprocessing import *
from core.tools import db_to_csv, update_from_env
SEQUENCE_LENGTH = 25 # days
SPLIT_PERCENTAGE = 0.75 # x100%
DROP_RATE = 0.2
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.