text stringlengths 38 1.54M |
|---|
import json
import scrapy
from scrapy import FormRequest
from scrapy.selector import Selector
from BiddingInfoSpider.spiders.base_spider import BaseSpider
from BiddingInfoSpider.items import BiddinginfospiderItem
from selenium import webdriver
import requests
class GanShu(BaseSpider):
name = 'ganshu'
allowed_... |
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setGeometry(200, 200, 300, 300) # x=200; y=200; w=300; h=300
self.setWindowTitle("Demo Version") # se... |
"""
Written 10 Feb 2016
@Ivan Debono
Runs BINGO.
Writes parameters to temporary file.
Outputs scalar primordial power spectrum to a temporary directory
Reads the output
OUPUT: Wiggly Whipped scalar P(k)_prim plots
"""
def mk_wwi():
from run_bingo import run_bingo
from run_bingo import rd_bingo_ps
from ru... |
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn')
# Check function. Used for checking your code, you can ignore this.
def check_func(func, *args):
res = {
'sigmoid': np.array([4.5397868702434395e-05, 0.0066928509242848554,
0.11920292202211755, 0.5, 0.88079707797... |
from functools import wraps
import logging
import os
# A special helper to add logging
LOG_FILE = 'hw2.log'
APP_NAME = 'hw2'
os.remove(LOG_FILE)
logger = logging.getLogger(APP_NAME)
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler(LOG_FILE)
fh.setLevel(log... |
def calc_fuel(mass) :
result = 0
fuel = int(mass/3)-2
if fuel >= 0 :
result += fuel
result += calc_fuel(fuel)
return result
with open("1.in", "r+") as infile :
fuel_sum = 0
for line in infile :
fuel_sum += calc_fuel(float(line.strip()))
infile.close()
print(fuel_sum)
|
#What is the sum of the digits of the number 2^1000?
digits = 2**1000
digits = str(digits)
listdigits = list(digits)
sum = 0
for i in range(0,len(list(digits))):
sum = sum + int(listdigits[i])
print(sum) |
import os
import numpy as np
from tools import ascii
headinfo = ascii.read_ascii("dem_10m_noise.txt")[0]
correspondence = np.loadtxt("test.txt", delimiter=",")
new = np.transpose(correspondence[:4,:].astype(int))
# new = zip(new)
print(headinfo)
print(new)
with open(os.path.join("","ortho.txt"), "w") as fobj:
f... |
import math, urllib2
from BeautifulSoup import BeautifulSoup
import pickle
class Feature(object):
def __init__(self,stock,date,title,sentiment,author):
self.stock = stock
self.date = date
self.title = title
... |
from light.effect.partial_effect import PartialEffect
from light.led_selector import LEDSelector
from light.effect.resolved_effect import ResolvedEffect
from light.effect.effect_priority import EffectPriority
class ConstantTargetsEffect(PartialEffect):
def __init__(self, targets, dt=0):
super().__init__(dt... |
import numpy as np
import pandas as pd
from .FactorCompositor import FactorCompositor
from ..DBInterface import DBInterface
class NegativeBookEquityListingCompositor(FactorCompositor):
def __init__(self, db_interface: DBInterface = None):
"""标识负净资产股票
:param db_interface: DBInterface
"""
... |
#!/usr/bin/env python2
#coding=UTF-8
import sys
ingredients = [line.strip() for line in open(sys.argv[1]).readlines() if line.strip()]
delimiter = ';'
container = 0
if ingredients[0].startswith('skål'):
container = int(ingredients.pop(0).split(delimiter)[1])
total_calories = 0
total_weight = 0
for ingredient ... |
from enum import IntEnum
class Language(IntEnum):
PL = 0
ENG = 1
CHN = 2
GER = 3
ES = 4
IT = 5
UK = 6
RU = 7
FR = 8
def __repr__(self):
if self == self.ENG:
return str("English")
if self == self.CHN:
return str("Chinese")
if self == self.GER:
return str("German")
... |
##declare the first 2 fibonacci numbers, append them to a list. then generate a list of fibonacci numbers, and break the loop when the length of the fibonacci number exceeds 1000. the length of the list is the index, since we technically are starting at 1
def fiblist():
list=[]
x=1
y=1
list.append(x)
list.append(... |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
EntryGate=19
EntrySensor=14
GPIO.setup(EntryGate,GPIO.OUT)
GPIO.setup(14, GPIO.IN,pull_up_down=GPIO.PUD_UP)
def closeGate():
p=GPIO.PWM(EntryGate,50)
p.start(0)
p.ChangeDutyCycle(8.9)
time.sleep(1)
p.ChangeDut... |
from django.db import models
from django.core.urlresolvers import reverse
import string, random
# Create your models here.
class Mini(models.Model):
long_url = models.URLField(unique=True)
short_url = models.CharField(max_length=10, unique=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False... |
"""Python Cookbook
Chapter 14, recipe 6, Controlling complex sequences of steps.
"""
import argparse
import os
import subprocess
from typing import List
class Command:
def execute(
self,
options: argparse.Namespace
) -> str:
self.os_cmd = self.os_command(options)
resul... |
num = int(input("Enter the nmumber:"))
save_num = num
sum = 0
while(num):
i = 1
p = 1
r = num % 10
while (i <= r):
p = p*i
i += 1
sum = sum + p
num = num // 10
if (sum == save_num):
print(save_num, "is a Strong Number")
else:
print(save_num, "is NOT a Stron... |
from ...util.py import class_path
class Initializer(object):
@classmethod
def from_json(cls, x):
return cls(**x)
def __call__(self, shape, dtype, meaning=None):
raise NotImplementedError
def params_to_json(self):
return self.__dict__
def to_json(self):
return {
... |
import time
import random
enemies = ["monster", "vampire", "big python", "lion", "puma", "dragon"]
directions = ["placeholder", "turn right", "turn left", "go straight"]
items = ["sword", "pistol", "stick", "shield", "bow"]
numbers = ["one", "two", "three"]
got_item = False
decisions = []
ways = 0
def print_delay(mes... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import os
import glob
import sys
from importlib import import_module
import imp
from opt_plugin.plugin import MetaOpt, Opt
def update(d, from_class_dict, name_in_dict, name):
val = from_class_dict.__dict__.get(name, None)
if val is None: return
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#coding=utf-8
import math
def funtion(x,y,f):
return f(x) + f(y)
print funtion(-2,-9,abs)
a = 'SdfdG'
print '-----------------'
print a.upper()
print '++++++++++++++++++++'
#map函数的语法如下
#map()函数接受的方式:一个函数和一个list,如下例子。
def name(s):
return s[0].upper() + s[1:].lower()
p... |
#!/usr/bin/python2
# coding=utf-8
import os,sys,time,mechanize,itertools,datetime,random,hashlib,re,threading,json,getpass,urllib,cookielib
from multiprocessing.pool import ThreadPool
#### WARNA RANDOM ####
P = '\033[1;97m' # biru
M = '\033[1;91m' # biru
H = '\033[1;92m' # biru
K = '\033[1;93m' # biru
B = '\033[1... |
import torch
import torch.nn as nn
from layers import Feature_Embedding, Feature_Embedding_Sum, FactorizationMachine, My_MLP
class NFM(nn.Module):
def __init__(self, device, feature_dims, embed_size, hidden_nbs, dropout):
super(NFM, self).__init__()
self.embedding = Feature_Embedding(feature_dims=... |
import turtle
a=turtle.Turtle()
a.speed(1)
a.up()
a.setx(-300)
a.sety(250)
a.down()
def myname():
#bukva K
a.up()
#a.goto(-300,250)
a.down()
a.right(90)
a.forward(33)
a.left(135)
a.forward(30)
a.backward(30)
a.right(90)
a.forward(30)
a.backward(30)
a.right(45)
a.forward(33)
#bukva I
a.up()
#a.home()... |
from django.apps import AppConfig
class TingHiringChallengeAppConfig(AppConfig):
name = 'ting_hiring_challenge_app'
|
#!/usr/bin/python
"""Execute workflow defined by HTCondor DAGMan submission file."""
import re
import os
import sys
import argparse
import shlex
import subprocess
from collections import OrderedDict
_try_run = False
_next_job_id = 1
# ==============================================================================
... |
#!/usr/bin/python
# Use pulseaudio to record something
import opus
from parec import PaRec
from opusogg import OpusOggFile
sample_rate = 24000
channels = 2
frame_size = 3*960
enc = opus.Encoder(sample_rate, channels, opus.OPUS_APPLICATION_VOIP)
dec = opus.Decoder(sample_rate, channels)
enc.packet_loss_perc = 0
en... |
from pp.add_pins import _add_pins, _add_pins_labels_and_outline
from ubc.layers import port_type2layer
def _add_pins_ubc(**kwargs):
return _add_pins(port_type2layer=port_type2layer, **kwargs)
def _add_pins_labels_and_outline_ubc(**kwargs):
return _add_pins_labels_and_outline(add_pins_function=_add_pins_ubc,... |
import glob
import os
import numpy as n
import sys
import time
from astropy.io import fits
from astropy.coordinates import SkyCoord
from astropy.coordinates import Distance
from astropy import units as u
from astropy import wcs
from astropy.wcs import WCS
def getCompleteness(brick,raR,decR):
""" get the completeness ... |
class AlmostSorted:
@staticmethod
def check_sorted(arr):
return all([i <= j for i, j in zip(arr[:-1], arr[1:])])
@staticmethod
def solution(arr):
right = len(arr)
left = -1
if right == 1 or AlmostSorted.check_sorted(arr):
print("yes")
return
... |
# coding: utf-8
# In[1]:
#import needed libraries
import fnmatch
import os
import pickle
import pprint
import shutil
# In[8]:
#load pickled list of active compounds not found in batch_1
compound_list = pickle.load( open("list_of_active_cmps_158.p", "rb"))
# In[9]:
[int(x) for x in compound_list] # converts the... |
from movie_stream import *
from movie_layer_data import *
class aeMovieCompositionData(object):
def __init__(self):
self.name = ""
self.master = False
self.width = 0.0
self.height = 0.0
self.duration = 0.0
self.frameDuration = 0.0
self.frameDuratio... |
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFrame, QBoxLayout, QToolButton
class QViewportHeader ( QFrame ):
""" This interface describes a class created by a plugin.
"""
def __init__ ( self, viewport ):
super ().__init__ ()
self.viewport = viewport
self.moduleName = "QViewportHeader"
sel... |
from ..field_abstract import AbstractField
class LastNameField(AbstractField):
def __init__(self,
name='last_name'):
self.data_type_id = 161
super(LastNameField, self).__init__(name)
|
"""Root resources."""
import flask
from dnstwister import app
from dnstwister import cache
@cache.memoize(86400)
@app.route(r'/favicon.ico')
def favicon():
"""Favicon (because some clients don't read the link tag)."""
return flask.send_from_directory(app.static_folder, flask.request.path[1:])
|
# plotting counter plots
#prints 7 graphs towards all the mentioned features
_, ax = plt.subplots(1, 3, figsize=(18, 6))
plt.subplots_adjust(wspace=0.3)
sns.countplot(x = "products_number", hue="churn", data = df, ax= ax[0])
sns.countplot(x = "estimated_salary", hue ="churn", data = df, ax = ax[1])
sns.countplot(x = "... |
import hashlib
class PasswordGenerator:
def __init__(self, websiteName, password, keyLen):
self.__shuffled_letters = ['!', ';', 'k', 'a', 'i', 'n', '$', '>', 'q', '2',
'Z', 't', "'", '[', 'w', 'd', 'W', 'z', '*', '^', 'C', '5', 'T', 'F', '-',
'{', 'I', 'g', 'Q', 'L', ':', '~', '0', '8', 'l', '#', '=', 'o', 'b',... |
"""
Import several functions as shorthand.
"""
from dit import (Distribution as D,
ScalarDistribution as SD,
)
from dit.algorithms import channel_capacity_joint as CC
from dit.divergences import (cross_entropy as xH,
kullback_leibler_divergence as DKL,
... |
import numpy as np
from prml.linear.classifier import Classifier
class LeastSquaresClassifier(Classifier):
"""
Least squares classifier model
y = argmax_k X @ W
"""
def __init__(self, W=None):
self.W = W
def _fit(self, X, t):
self._check_input(X)
self._check_target(t)... |
import matplotlib.pyplot as plt
# # INGRESO , Datos de prueba
# xi = np.array([100, 200, 300, 400, 500 , 600])
# fi = np.array([-160, -35, -4.2, 9, 16.9, 21.3])
# # PROCEDIMIENTO
# # Polinomio de Lagrange
# n = len(xi)
# x = sym.Symbol('x')
# polinomio = 0
# divisorL = np.zeros(n, dtype = float)
# for i in range(0,n,... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
r"""
The :mod:`pointing_game` modules implements the pointing game benchmark.
The basic benchmark is implemented by the :class:`PointingGame` class. However,
for benchmarking purposes it is recommended to use the wrapper class
:class:`PointingGame... |
import contextlib
import ctypes
import struct
from ctypes import c_void_p, c_uint16, c_uint32, c_int32, c_char_p, POINTER
__metaclass__ = type
sec_keychain_ref = sec_keychain_item_ref = c_void_p
OS_status = c_int32
class error:
item_not_found = -25300
keychain_denied = -128
sec_auth_failed = -25293
... |
"""Test the public API of the ``ioc`` module."""
import operator
import os
import unittest
import ioc
import ioc.exc
DEPS_FILE = os.path.join(os.path.dirname(__file__), 'ioc.xml')
class PublicAPITestCase(unittest.TestCase):
function_val = 1
constant_val = 2
str_val = 'Hello world!'
function_args = ... |
# Exercise 8.3 The Grerory-Leibnitz series approximates pi as 4 ∗ (1/1 − 1/3 +
# 1/5 − 1/7 + 1/9...). Write a function that returns the approximation of pi
# according to this series. The function gets one parameter, namely an integer
# that indicates how many of the terms between the parentheses must be
# calculated.
... |
#!/usr/bin/env python3
import traceback
import json
import urllib.request
import http.client
import sys
try:
content = sys.stdin.read()
data = {
'text': content,
'mode': 'gfm'
}
headers = {
'Content-Type':
'application/json'
}
bytes = json.dumps(data).encode('utf-8')
url = 'https://api.g... |
class Position:
'''Classe qui gére toutes les positions dans le labyrinthe x étant le numéro de ligne et y le numéro de colonne'''
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def move_down(self):
return Position(self.x+1, self.y)
def move... |
import numpy as np
import cv2
src = cv2.imread("car_number.jpg", cv2.IMREAD_GRAYSCALE)
dst1 = cv2.pyrUp(src)
dst = cv2.Canny(dst1, 100, 200, apertureSize=3, L2gradient= True)
cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
from django.views.generic import ListView, TemplateView
from django.db.models import Avg
from web.models import *
class SummaryAverageView(ListView):
template_name = 'summary.html'
context_object_name = 'summary_data'
def get_queryset(self):
return Site.objects.values('name').annotate(a_summary=... |
import sys
import time
from os import system, name
from termcolor import colored, cprint
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
#Merry Christmas mes... |
"""
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a matplotlib backend
:class:`RendererBase`
An abstract base class to handle drawing/rendering operations.
:class:`FigureCanvasBase`
The abstraction layer that separates the
:class:`matplotlib.fi... |
"""
you have a list of student scores on the final exam in a particular order(not necessaryly sorted).
and you want to reward your students following two rules.
*all student must receive strictly one reward
*any given student must receive strictly more rewards than a adjacent student(next to left or right)
with a low... |
#! /usr/bin/env python3
'''
Created on Sept 9, 2014
@author: dusenberrymw
'''
import math
import os
import sys
import unittest
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
# import pine.data
import pine.activation
import pine.network
import pine.trainer
import pine.util
# network... |
import os
import random
from functools import partial
from typing import Optional, Callable, List
import cv2
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms, datasets
class CustomSubset(Dataset):
"""
CustomSubset is a custom implementation of a... |
"""
clusterer.py
functions in this file take network structure expressed as
edges and translate it to network structure expressed as nested
clusters
"""
import subprocess
import glob
import pandas as pd
import os
import shutil
import tempfile
import dask.dataframe as dd
from dask import delayed
import numpy as np
im... |
def verificaEmail(email):
emails=['gmail.com','hotmail.com','ufpi.com.br',"bol.com.br"]
try:
lista= email.split('@')
if lista[1] in emails:
return True
else:
return False
except:
return False
def verificaCpf(cpf):
if len((cpf))==14 and cpf[3]=='.' and cpf[7]=='.' and cpf[11]=='-':
cpf.s... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def visualize_keywords():
# Occurance of Top Keywords in Recent News
keyword_data = pd.read_csv("keywords.csv")
sns.barplot(x="keyword",y="occurance",data=keyword_data).set_title('Occurance of Top Keywords in Recent News')
plt.sa... |
import logging
import hashlib
import os.path
from datetime import timedelta
from functools import update_wrapper
from flask import request, Flask, Response, make_response, current_app, json, send_file, render_template
import flask
from werkzeug import secure_filename
from musik.db import *
from musik.utils import lo... |
# This script defines a test case which computes one or more physical
# properties with a given model
#
# INPUTS:
# model.calculator -- an ase.calculator.Calculator instance
# this script can assume the calculator is checkpointed.
#
# OUTPUTS:
# properties -- dictionary of key/value pairs corresponding
# to... |
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["medchain"]
mycol = mydb["data"]
myquery = {"Name": "Lexapro"}
newvalues = {"$set": { "Quantity": 1000}}
mycol.update_one(myquery, newvalues)
|
from app import app, sio
from flask import request
import datetime
import time
from mongodb import db
from func.tg_user import search_global
from api._func import next_id
from api.get_discuss import get_styled
from api.visualisation import timeline
from api.vectorize import vectorize
from api.lda import lda
from api.... |
from deephyper.stopper._stopper import Stopper
class IdleStopper(Stopper):
"""Idle stopper which nevers stops the evaluation."""
|
# -*- coding: utf-8 -*-
"""
Created on 9 May 2018
@author: Dylan Jones
This module contains the Constants object, wich gets initialized for later use
"""
from scipy import constants as c
_m = 1 # mass of the particle: Set to one for atomic units
_hbar = 1 # hbar: Set to one for atomic units
class Constants:
... |
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
def removeSigns(text):
signList = [r".",r"?",r"!",r":",r";",r"-",r"_",r"(",r")",r"{",r"}",r"[",r"]",r"'",r'"',"/",","," "]
for sign in signList:
text = text.replace(sign,"")
return text
something = raw_input("Enter te... |
from sklearn.datasets import load_files
from sklearn.model_selection import train_test_split
def load_datasets():
dataset = load_files('review_polarity/txt_sentoken', shuffle=False)
docs_traindev, docs_test, y_traindev, y_test = train_test_split(
dataset.data, dataset.target, test_size=0.25, random_st... |
from . import user_message_helper
from . import chatbot_context_manager
from . import user_id_manager
message_helper = user_message_helper.UserMessageHelper.default_db()
context_manager = chatbot_context_manager.ContextManager.default_db()
id_manager = user_id_manager.UserIdManager.default_db() |
# -*-coding: utf-8 -*-
# @Time : 2021/2/19 20:04
# @Author : Cooper
# @FileName: 爬取豆瓣.py
# @Software: PyCharm
import requests,re
import time
from pymongo import *
from requests.exceptions import ReadTimeout,HTTPError,RequestException
import random
url='https://movie.douban.com/top250?start='
user_agent_list ... |
import sys, os, getopt
from kazoo.client import KazooClient
def removeNode(ZK, path):
if ZK.exists(path):
children = ZK.get_children(path)
if children:
for child in children:
removeNode(ZK, os.path.join(path, child))
removeNode(ZK, path)
else:
... |
# 242/203
# 09:28/09:32
from sys import stdin
x, y = map(int, stdin.read().strip().split('\n'))
for n in range(20201227):
if pow(7, n, 20201227) == x:
print('a', pow(y, n, 20201227))
break
|
# -*- coding: utf-8 -*-
import pygal
xy_chart = pygal.XY()
xy_chart.add('Value 1', [(-50, -30), (100, 45)])
xy_chart.render_to_file("xy_chart.svg")
|
# ch17_7.py
import hashlib
data1 = hashlib.sha256() # 建立data物件
data1.update(b'Ming-Chi Institute of Technology') # 更新data物件內容
print('Hash Value = ', data1.hexdigest())
data2 = hashlib.sha256() # 建立data物件
data2.update(b'ming-Chi Institute of Technology... |
#-*- coding:utf-8 -*-
vs_shader = "simple_vs.glsl"
fs_shader = "simple_fs.glsl"
out_hpp = "../shaders.hpp"
shader_infos = [
("simple_vs.glsl","simple_vs_shader"),
("simple_fs.glsl","simple_fs_shader"),
("simple_es_vs.glsl","simple_es_vs_shader"),
("simple_es_fs.glsl","simple_es_fs_shader"),
]
template = '''
//g... |
class StatusBar:
""" Any of the Calorie, Condition, Body Heat and Hydration bars"""
def __init__(self, name, max_value, init_value):
# The display name of the status bar
self.name = name
# The maximum value of the bar
self.max_value = max_value
# The current value of th... |
import numpy as np
import cv2
def is_red(p):
return p[0] < 60 and p[1] < 60 and p[2] > 150
def find_red_area(point, tol):
red_points = []
for i in range(int(point[1]) - tol, int(point[1]) + tol):
for j in range(int(point[0]) - tol, int(point[0]) + tol):
if is_red(homo_img[i, j]):
... |
#Even and Odd Number Filter
def even_odd(num_list):
string=[x for x in num_list if x %2==0]
print('Even numbers in the list are ',len(string))
strings=[y for y in num_list if y%2!=0]
print( 'Odd numbers in the list are', len(strings))
even_odd([1,2,3,4,5,6,7,8,9,10,18])
even_odd(range(10,15))
|
import cv2
from lib.contour import find_contours_and_hierarchy, find_human_contour, draw_contour
if __name__ == "__main__":
src = cv2.imread("./images/shadow.jpg")
dst = src.copy()
contours, hierarchy = find_contours_and_hierarchy(src)
human_contour = find_human_contour(contours, hierarchy)
draw_c... |
#!/usr/bin/python
import math
primi = [2,3,5,7]
tot=0
def isPrime(n):
sqr=int(math.sqrt(n))
for el in primi:
if el <= sqr:
if (n%el) == 0:
return False
else:
return True
return True
for n in range (11,2000000):
if (n%2) != 0:
if isPrime(n):
primi.append(n)
for el in primi:
tot += el
print to... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: Gsscsd
@email: Gsscsd@qq.com
@site: http://gsscsd.loan
@file: tools.py
@time: 2017/5/2
"""
import numpy as np
import pandas as pd
#处理属性1
def solveA1(matrixs):
for matrix in matrixs:
matrix[0] = int(matrix[0])
#处理属性2
def so... |
import numpy as np
#类别变量处理 treat categorical features as numerical ones
#1 labelencode
#2 frequency encoding
#3 mean-target encoding
#https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/79981
# Mean-target encoding is a popular technique to treat categorical features as numerical ones.
# The mean-target... |
import discord
import numpy as np
import random
from dotenv import load_dotenv #en test pour une "environment variable"
import os
client = discord.Client()
tanks = [] #all the basic bs
healers = []
dps = []
emojiTank = '<:sadcat2:643173970400772126>'
emojiHeal = ... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="plum",
version="1.0.0",
author="Andreas Backström",
description="A simple build and management tool",
long_description=long_description,
long_description_content_type... |
num = input("Enter the Number: ")
#val = num.startswith("9" or "8" or "7")
if (num.startswith("9" or "8" or "7")) and (len(num)==10) and (num.isdigit()):
print("VALID")
else:
print("NOT VALID") |
'''This script creates a maximum clade credibility tree from a BEAST .trees output
file using BEAST treeannotator. It assumes a 10% burn-in
Input files
------------
*``prot_aligned.trees`` : BEAST file containing thinned trees
Output files
--------------
*``maxcladecredibility.tre`` : maximum clade credibility tr... |
import re
r=open("phn","r")
f=open("num.txt","w")
rule="[+][9][1]\d{10}$"
for num in r:
number=num.rstrip("\n")
matcher=re.fullmatch(rule,number)
if matcher!=None:
f.write(number)
f.write("\n")
|
# importing django modules
from django.urls import path, re_path
from django.conf.urls import url
from . import views as transaction_views
# defining url routes and corresponding function to be called in views
urlpatterns = [
url('wallet/', transaction_views.wallet_details, name='wallet_details'),
url('add_mo... |
import threading, time
print("start")
def takeNap():
time.sleep(10)
print("wake")
threadObj = threading.Thread(target = takeNap)
threadObj.start()
print("End")
|
import re
from typing import Dict, List, Mapping, Union
from .utils import (
check_input,
is_positive, is_greater_than_zero,
is_zero_or_one
)
from .element import Element
from .types import elemParamsType
class Material(object):
""" Material Representation """
def __init__(
self, element... |
"""
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
"""
from atom.api import Typed, Instance, Subclass, Bool, Float, set_default
from enamlnative.widgets.view import ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-21 20:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0010_add_initial_formats'),
]
operations = [
migrations.CreateMod... |
from functools import singledispatch
class calcul:
@singledispatch
def add(self,a,b):
self.a=a
self.b=b
return a+b
@singledispatch
def sub(self,a,b):
self.a=a
self.b=b
return a-b
val=calcul()
print(val.add(3,4))
print(val.sub(8,4))
|
import zmq, time
import numpy as np
import copy
import sys, json, pdb, pickle, operator, collections
import inflect
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
import argparse
from random import shuffle
from operator import itemgetter
import matplot... |
# Script to do monthly means then ensemble average of HAPPI data
import os,glob,tempfile,shutil
import multiprocessing,time
# Create list into a string
def list_to_string(l):
s = ''
for item in l:
s += item +' '
return s
# Process data for a single ensemble member/ run (add two fields together)
def process_ru... |
"""Unit tests for card validation number functionality."""
from django.test import TestCase, Client
import json
class TestApiEndpoint(TestCase):
"""Testing card number validation endpoint."""
def assert_response(
self,
response,
str_response,
str_class
):
"""
... |
from Constants import *
class Piece:
def __init__(self, c, piece, x, y, imgs):
self.moved = False
self.x = x
self.y = y
self.c = c
self.selected = False
self.origPos = (x, y)
self.piece = piece
self.BB = imgs[0]
self.BW = imgs[1]
... |
import csv
import pandas as pd
from math import exp
import math
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings( "ignore" )
data=pd.read_csv("dataset_LR.csv")
total_itr=1
flag=1
def update(X,Y,W):
A = 1 / ( 1 + np.exp( - (np.dot(X,W[1:])+W[0])))
tmp=A-Y
dw=x*t... |
import pandas as pd
from datetime import datetime
import csv
import re
import os
import sys
xlsx_name = input("Please xlsx file name (withouth .xlsx extention) to convert: ")
csv_name = xlsx_name + "_export.csv"
if os.path.isfile(csv_name):
print("{0} file already exists, please remove it before running this scri... |
from . import customnet
import torch
import torch.nn as nn
from torchvision import models as tv
def alexnet():
def change_out(layers):
ind, layer = [(i, l) for i, (n, l) in enumerate(layers) if n == 'fc7'][0]
layers[ind+1:] = []
return layers
model = customnet.CustomAlexNet(modify_seque... |
### IMPORTANT. DO NOT PROCEED WITHOUT READING. ###
### DO NOT TOUCH THE CODE UNLESS AUTHORIZED. IF YOU ARE MAKING ANY CHANGES, COMMENT THE CHANGELOG BELOW
# This code is for the Microprocessors project by Group 41.
# It involves manually controlling the robot through bluetooth.
import RPi.GPIO as gpio
## We need to im... |
# run as: python kappahist.py /Volumes/G-RAIDStudio/simulations/lensing_simulations/Guo_galaxies/GGL_los_N_4096_ang_4_Guo_galaxies_on_plane_27_to_63_pdzmstar_noJHKs_B1608_orig_size45_i24_ratioquick.lst constraints
#where constraints are eg: gal 1.52 0.05 oneoverr 1.69 0.05 mass 1.9 0.10 z 1.45 0.05 mass2 2.15 0.4 mass... |
# Author: Sally Kang <snapekang@gmail.com>
# Created: 20-4-23
import time
import numpy as np
from keras.optimizers import Adamax
from keras.optimizers import Adam
from keras.optimizers import SGD
from keras.utils import np_utils
from utils import load_data
from Model_def import DFNet
from sklearn import preprocessi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.