text stringlengths 38 1.54M |
|---|
i = 0
data = (['1',1.0,1.0],['2',1.5,2.0],
['3',3.0,4.0],['4',5.0,7.0],
['5',3.5,5.0],['6',4.5,5.0],
['7',3.5,4.5])
def tampil_data(data):
for data in i :
print data[i]
def banyak_data(data):
n = 0
for data in i:
n = n+1
return n
def random(awal,a... |
#!/usr/bin/env python3
import logging
import sys
logging.debug(str(sys.version_info))
if sys.version_info[0] < 3 or sys.version_info[1] < 5:
raise Exception("Requires python 3.5+, try module load python/3.6-anaconda-4.4")
import readline
def ask(prompt:str, guess:str="", insist=True) -> str:
""" ask the user ... |
# Copyright (c) Alibaba, Inc. and its affiliates.
from modelscope.trainers.hooks import HOOKS, Priority
from modelscope.trainers.hooks.lr_scheduler_hook import LrSchedulerHook
from modelscope.utils.constant import LogKeys
@HOOKS.register_module(module_name='AddLrLogHook')
class AddLrLogHook(LrSchedulerHook):
"""F... |
import torch
import torchvision
import torchvision.transforms as transforms
import math
import matplotlib.pyplot as plt
import numpy as np
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
cfg = {
'A': [64, 'M', 128, 'M', 256, 256, ... |
HAND_LIMIT = 10
class Hand(object):
"""Hand of cards."""
def __init__(self):
self.side = None
self.cards = []
self.size = 0
self.board = None
self.hidden = False
def get_card(self, pos):
"""Return the card at the pos (idx+1) specified."""
return sel... |
import platform
import requests
print(platform.platform())
"""response = requests.get("https://www.zhihu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
print(response.content)
print(response.content.decode("utf-8"))
response.encoding="u... |
from agente.agente import Agente
from modelos.card import Card
from modelos.estudo import Estudo
from modelos.respostausuario import RespostaUsuario
from datetime import datetime
from datetime import timedelta
from modelos_matematicos.formula_repeticao.formula_repeticao import calcular_oi
class Ambiente:
__agente... |
import sys
import asyncio
import aiohttp
import time
from random import choice
from string import ascii_letters
from termcolor import colored
class Longpass:
url = ""
delay = 1
username = ""
size = 1000000
repeats = 20
password = ""
iterations = 0
tasks = list()
payload = dict()
... |
from xml.dom.minidom import parse
import matplotlib.pyplot as plt
def getCorner(xmlParse, cornerName):
corner = xmlParse.getElementsByTagName(cornerName)[0]
cornerCoord = []
cornerCoord.append(float(corner.getAttribute('x')))
cornerCoord.append(float(corner.getAttribute('y')))
return cornerCoord
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from time import time
def test():
t = time()
lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44]
listb=[2,4,6,9,23]
intersection=[]
for i in range (1000000):
for a in lista:
for b in listb:
if a == b:
intersection... |
# Copyright (C) 2012 Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYST... |
my2dlist=[[2,5,8],[3,7,4],[1.6,9],[4,2,0]]
userrow=int(input('what row do you want displayed'))
print(*my2dlist[userrow])
usercolumn=int(input('which column in this row do you want displayed'))
print(my2dlist[userrow][usercolumn])
userchoice=input('do you want to chage that value').upper
# Github is working with my ne... |
from openmoltools import forcefield_generators
from openeye import oechem
def normalize_molecule(mol):
# Assign aromaticity.
oechem.OEAssignAromaticFlags(mol, oechem.OEAroModelOpenEye)
# Add hydrogens.
oechem.OEAddExplicitHydrogens(mol)
# Check for any missing atom names, if found reassign all of... |
import requests
from bs4 import BeautifulSoup
import socket
# 获取关键词为人工冻结的知网页面
def getHtml(url, cookie, origin):
headers = {}
headers.setdefault("Cookie", cookie)
# headers.setdefault("Origin", origin)
headers.setdefault("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) Ap... |
'''
Created on 11 set 2017
@author: davide
'''
'''
Loop example
'''
# Loop example
import tensorflow as tf
x = tf.Variable(0, name = 'x')
model = tf.global_variables_initializer()
print(model)
with tf.Session() as session:
session.run(model)
for i in range(5):
x = x + 1
... |
def vegalite_piechart(n_pass, n_fail):
pie = {
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"description": "A simple pie chart showing the ratio of passed and failed tests.",
"data": {
"values": [
{"category": "pass", "value": n_pass},
... |
import boto3
import base64
import os
import yaml
import json
from botocore.exceptions import ClientError
session = boto3.session.Session()
# Create a Secrets Manager client
client = session.client(
service_name='secretsmanager'
)
def __accountIds():
if os.path.isfile('config.yaml') is True:
with op... |
# -*- coding: utf-8 -*-
from .app_access_token import AppAccessToken, final_app_access_token
class Authen(AppAccessToken):
def __init__(self, appid=None, secret=None, ticket=None, tenant_key=None, token=None, storage=None):
super(Authen, self).__init__(appid=appid, secret=secret, ticket=ticket, tenant_ke... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 19:45:15 2021
@author: dankovacevich
"""
from zipfile import ZipFile
import re
import py_compile
import os
import sys
import PyPDF2
import imghdr
import subprocess
#-----------list of condition names-----------
pythonFile = f".*(.py)$"
pdfFile =... |
# coding: utf8
"""
File to run real data experiments.
"""
import json
import os
import sys
import time
import numpy as np
import sklearn
from sklearn.metrics import mean_squared_error
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.model_selection import GridSearchCV as GSCV
from sklearn.model_sel... |
import os
import random
from functools import partial
import numpy
import pytest
FLOAT_EQUALITY_ACCURACY = 0.001
pytest.approx = partial(pytest.approx, abs=FLOAT_EQUALITY_ACCURACY)
@pytest.fixture
def random_seed():
# TODO: change scope to module and reset it in test dropdown, tearup
seed = random.randint(0... |
from flask import Flask, request, render_template
import json
import boto3
from werkzeug.utils import secure_filename
textractclient = boto3.client("textract", aws_access_key_id="AKIAYRVCKL2B4FBREBWO",
aws_secret_access_key="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", region_name="us-e... |
import pandas as pd
import sys
import os
import matplotlib.pyplot as plt
import seaborn as sns
pal = sns.color_palette()
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from greyatomlib.quora_project.q01_load_data_questions.build import q01_load_data_questions
plt.switch_backend('agg')
pa... |
#ht_test_data prediction
import os
import numpy as np
import csv
import pandas as pd
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model,load_model
from keras.utils import to_categorical
from keras.layers import Activation, Dense, Dropou... |
import torch
from torch import nn
import torchvision.utils as vutils
import torchvision.datasets as dset
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
... |
msg = raw_input(' What is your fate Jolena? ')
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
msg = msg.upper()
for key in range(len(ALPHABET) ) :
result = ' '
for symbol in msg:
if symbol in ALPHABET:
num =ALPHABET.find(symbol)
num = num - key
if num < 0:
... |
import os
print(os.path.join('usr', 'bin', 'spam'))
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filenames in myFiles:
print(os.path.join('c:\\Users/hp/Desktop/python', filenames))
print(os.getcwd())
print(os.path.isabs('C:\\Users\hp\PycharmProjects\HackeRank'))
path = 'c:\\Users/hp/Downloads/t... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# coding=UTF-8
import twitter
import time
import datetime
import urllib
from twython.twython import TwythonError, TwythonAPILimit, TwythonAuthError, TwythonRateLimitError
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from snh.models.twittermodel import *
import snhlogger
logger = snh... |
from api.sources.getter_definition import GetterDefinition
class CptecAPIGetter(GetterDefinition):
def __init__(self, latitude, longitude):
config = {
'url': 'http://servicos.cptec.inpe.br/XML/cidade/7dias/{0}/{1}/previsaoLatLon.xml',
'parser': 'xml'
}
GetterDefini... |
#!/usr/bin/python3
from threading import Timer
class Repeater(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
class Counter:
UP = 1
DOWN = 0
def __init__(self):
self.count = 0
self.clk = 0
self.direction = self.UP
def c... |
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain... |
from django.contrib import admin
from allegro.models import UserProfile, Music, Event, PartFormat, Request
admin.site.register(UserProfile)
admin.site.register(Music)
admin.site.register(Event)
admin.site.register(PartFormat)
admin.site.register(Request)
|
import pygame, time, random
WINDOW_SIZE = (1000, 1000)
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
maze_size = int(input("Size of maze (nxn):"))
maze = []
for i in range(0,maze_size):
maze.append([])
for j in range(0,maze_size):
if random.randint(0,3) >= 1:
maze[i].append(0)
else:... |
from .model_zoo import get_model
from .model_store import get_model_file
from .base import *
from .fcn import *
from .oc_module import *
from .psp import *
from .encnet import *
from .danet import *
from .resnet101_asp_oc import get_resnet101_asp_oc_dsn
from .resnet101_base_oc import get_resnet101_base_oc_dsn
from .res... |
import theano
import theano.tensor as T
x = T.dmatrix('x')
s = 1 / (1 + T.exp(-x))
logistic = theano.function([x], s)
...
...
|
def rangify(v, lb, ub):
""" Returns a value bounded to a lower and an upper bound """
if lb >= ub:
lb, ub = ub, lb
return max(min(v, ub), lb)
|
"""
Archivo con las partes del turbohélice
Difusor,
"""
from air_model import RealGas
from isentropic_gas import IsentropicGas
import isa
import numpy as np
import generador_gas
air = RealGas(cp_option='naca', gamma_option='standard')
gas = IsentropicGas(selected_cp_air_model='naca', selected_gamma_air_model='stand... |
# decision tree model
import pandas as pd
x = pd.read_csv("../../dataset/input_data.csv").to_numpy()
resp = pd.read_csv("../../dataset/output_data.csv").to_numpy()
##
from sklearn.decomposition import PCA
import numpy as np
pca = PCA(n_components = 1)
resp_pca = pca.fit_transform(resp)
y = (resp_pca > 0).astype("int... |
#!/usr/bin/python3
#coding:utf-8
# 数据集路径: http://grouplens.org/datasets/movielens/1m
import pandas as pd
import os
# 处理数据:将下载的dat文件格式转换成csv格式并保存,方便后续读取.
class Channel:
def __init__(self, dataDir='./data/'):
self.path = dataDir
def _process_user_data(self, file='users.dat'):
fullpath = os.p... |
first = int(input())
second = int(input())
def factorial(a,b):
a_fact = 1
b_fact = 1
for i in range(1, a + 1):
a_fact = a_fact * i
for j in range(1,b + 1):
b_fact = b_fact * j
divide = a_fact / b_fact
return divide
dev = factorial(first, second)
print(f'{dev:.2f}')
|
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from blogs.api import views as qv
router = DefaultRouter()
router.register(r"blogs", qv.BlogViewSet)
urlpatterns = [
path("", include(router.urls)),
path("blogs/<slug:slug>/comments/",
qv.CommentListAPIView.as_vie... |
from fuzzer.main import PAYLOADS
from tokenizer import TOKEN
from utils.utils import get_max_threads
def generator_from_payload(tokenized_message: str) -> list:
message_applied_with_tokens = []
with open(PAYLOADS, 'r') as f:
for payload in f:
message_applied_with_tokens.append(replace_toke... |
# @Author: aniket
# @Date: 2019-12-17T23:28:30+05:30
# @Last modified by: aniket
# @Last modified time: 2019-12-19T01:30:09+05:30
import roslib
import rospy
from ackermann_msgs.msg import AckermannDriveStamped
from std_msgs.msg import Int16
from ackermann_teleop.msg import cmd
from getkey import getkey, keys
imp... |
import pytest
from argparse import Namespace
from Bio import Phylo
from math import isclose
from phykit.services.tree.patristic_distances import PatristicDistances
@pytest.fixture
def args():
kwargs = dict(tree="/some/path/to/file.tre", verbose=None)
return Namespace(**kwargs)
class TestPatristicDistances(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('goods', '0009_auto_20161206_1510'),
]
operations = [
migrations.AlterF... |
# -----------------------------------------------------------------------------
import hash_tabla as h
# -----------------------------------------------------------------------------
def teszt1() :
assert (h.hash_fuggveny("a") == 0)
assert (h.hash_fuggveny("z") == 25)
#
def teszt2... |
from sys import exit
import csv
people = {
"GABE": 12345678,
"LUCAS": 23456789,
"MIKE": 34567890,
"EMMET": 87654321
}
if "GABE" in people:
print(f"Found {people['GABE']}")
else:
print("Not found")
name = input("name: ")
number = input("number: ")
with open("phonebook.csv", "a") as file:
... |
import hmac
import os
from collections import defaultdict
from time import time
from base64 import b64encode, b64decode
from flask import Flask, request, make_response
app = Flask(__name__)
cookie_name = "LoginCookie"
def new_random(): return os.urandom(20)
secret_dict = defaultdict(new_random)
def compute_hmac(... |
#!/usr/bin/python
import os
import bz2
import pdb
import settings
import json
import glob
msms = []
#files = filter(os.path.isfile, glob.glob("data/ripe/meta/meta_for_gr/" + "*"))
files = ['data/ripe/meta/meta-20150116.txt.bz2', 'data/ripe/meta/meta-20150406.txt.bz2', 'data/ripe/meta/meta-20150706.txt.bz2', 'data/ripe... |
import collections
def queensAttack(n, k, r_q, c_q, obstacles): # 퀸이 공격할 수 있는 위치 count 문제.
# 시간 제약때문에 살짝 까다로움
# obstacles를 list에서 dictionary로 바꿈 -> O(n)으로 조회 가능
dx, dy = [-1, 1, 0, 0, 1, -1, 1, -1], [0, 0, -1, 1, 1, -1, -1, 1] # 방향
count = 0 # 정답
x = r_q - 1 # 위치
y = c_q - 1 # 위치
for... |
for i in range(1, 6):
j = 0
while j < i:
print(j, end=" ")
j += 1
print("")
# Note: end = " " means that print() will put a space after what was printed instead of starting
# a new line.
# What will be the output of the code above?
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
# 0
# 0 1
# 0 1 2... |
#import sys
import numpy as np
import argparse
from socket import gethostname
#import streaker_calibration
import h5_storage
import elegant_matrix
import lasing
import config
import gaussfit
import image_and_profile as iap
#import tracking
#import analysis
import myplotstyle as ms
parser = argparse.ArgumentParser()
p... |
from selenium.webdriver.common.by import By
class DashboardPageLocators(object):
STATISTIC_HEADER = (By.XPATH, '//h3[1]')
INTERCOM_IFRAME = (By.XPATH, '//iframe[@class="intercom-launcher-frame"]')
INTERCOM_OPEN_CHAT_BUTTON = (By.CLASS_NAME, 'intercom-avatar')
INTERCOM_CHAT = (By.CLASS_NAME, 'intercom-... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
# Set window size.
w.resize(320, 240)
# Set window title
w.s... |
#!/usr/bin/env python
# coding: utf-8
# # Importing modules
# __________________
# The modules involves Numpy, Pandas, Matplotlib, Seaborn
# In[ ]:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns #Visualizations
from matplotlib import ... |
import sys
def print_chess_board(board):
for x in board[::-1]:
for y in x:
sys.stdout.write(y)
sys.stdout.write("\n")
def calculate_next_move(distance_to_end):
# One move to finish!
if(distance_to_end[0] == 2 and distance_to_end[1] == 1):
return (2, 1)
elif(distance_to_end[0] == 1 and dis... |
#! /usr/bin/python3
import unittest
from math import sqrt
def factorpairs(n):
if n==1:
return [2]
ff=[]
s=int(sqrt(n))
if s*s==n:
ff.append(s*2)
s-=1
for pf in range(2,s+1):
if n % pf == 0:
ff.append(pf+int(n/pf))
ff.append(n+1)
return ff
def is_stealthy(n):
p=factorpairs(n)
... |
#!/usr/bin/env python3
from mujoco_py import load_model_from_path, MjSim, MjViewer
import numpy as np
import os
import plotly.graph_objs as go
from plotly.offline import plot
from pymuscle.hill_type import (
contractile_element_force_length_curve as ce_length_curve,
contractile_element_force_velocity_curve as ... |
from datetime import datetime, timezone
import pytest
from hilda.exceptions import ConvertingFromNSObjectError
@pytest.mark.parametrize('source', [
'',
'3123123',
'asdsdasd',
'12312sadasd',
'The quick brown fox jumps over the lazy frog123',
])
def test_cfstr(hilda_client, source: str):
"""
... |
from database import get_connection
class vkBot:
def __init__(self, user_id):
self.user_id = user_id
self.commands = ['расписание']
self.hello_message = ['привет', 'здравствуйте', 'приветствую']
self.goodbye_message = ['пока', 'удачи', 'увидимся', 'спасибо']
def ... |
""" Fast, compact DAG for analyzing expression dependencies
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2020-07-08
:Copyright: 2020, Karr Lab
:License: MIT
"""
class DAG(object):
""" Fast, compact DAG for analyzing expression dependencies
`networkx` is not usable because its traversal methods ... |
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup
from time import sleep
from Stockx.StockxClothing import ClothItem
from Stockx.StockxShoe import ShoeItem
from pymongo import *
def read_page(item):
for link in item:
request = Request(link, headers={'User-Agent': 'Mozilla/5... |
#!/usr/bin/env python
import glob
import pandas
import pandas.io.json
import json
def fix_frame(filename, columns):
frame = pandas.DataFrame.from_csv(filename, index_col=False)
frame.columns = columns
data = frame.to_dict()
for key in data:
data[key] = [data[key][k] for k in data[key]]
jso... |
import sys
"""
Brian Grenier
1545276
bgrenier
List any resources you used below (eg. urls, name of the algorithm from our code archive).
Remember, you are permitted to get help with general concepts about algorithms
and problem solving, but you are not permitted to hunt down solutions to
these particular... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import sys
def classifier(data,num_crossval):
train_error=[]
test_error=[]
foldsize= len(data)/num_crossval
for k in range(10):
testing = data[k*foldsize:(k+1)*foldsize]
a=data[:k*foldsiz... |
from controller.film_ctrl import FilmCtrl
from controller.client_ctrl import ClientCtrl
from controller.rent_ctrl import RentCtrl
from domain.val_film import FilmValidator
from domain.val_rent import RentValidator
from domain.val_client import ClientValidator
from repository.film_repo import FilmRepo
from repository.re... |
from django.contrib import admin
from .models import *
# Register your models here.
#
# class MenuAdminSite(admin.AdminSite):
#
# def get_app_list(self, request):
# """
# Return a sorted list of all the installed apps that have been
# registered in this site.
# """
# orderi... |
__author__ = 'OTL'
import pygame
from pygame.locals import *
import resources
import noise_surfaces
# TODO add buttons
class MenuItem():
def __init__(self, caption, new_state):
self.caption = caption
self.text_normal = resources.get_font(40).render(caption, True, (128,255,128))
self.text... |
import numpy as np
import pandas as pd
import ipdb
import cPickle as pickle
import matplotlib.pyplot as plt
plt.style.use("ggplot")
import mpld3
from mpld3 import plugins
from mpld3.utils import get_id
### My plotting code.
xw, yw = pickle.load(open("media/xw.cpkl")), pickle.load(open("media/yw.cpkl"))
xb, yb = pick... |
from math import sqrt
def isPrime(x):
if x == 1:
return False
if x == 2:
return True
root = int(sqrt(x)) + 1
for i in range(2, root+1):
if x % i == 0:
return False
return True
def numPrimeDivisors(num):
if isPrime(num):
return 1 # Not quite true, but... |
from skimage import data, segmentation, color, io, exposure
from minisom import MiniSom
import numpy as np
import argparse
# get color histogram of each superpixel, no normalized
def get_color_histogram(image, superpixels, index):
indices = np.where(superpixels.ravel() == index)[0]
_r_hist = np.bincount(image[... |
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV_XEokaAEcDFAX7&
# 이분탐색
# 시간이 있으면 해당 시간동안 통과한 사람의 수를 알 수 있다.
def solution(n, times):
left = 1
right = n * max(times) + 1
while left <= right:
mid = (left+right) // 2
res = 0
for i in ra... |
#-*- coding:utf-8 -*-
# leetcode 25
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def to_list(self):
return [self.val] + self.next.to_list() if self.next else [self.val]
class Solution(object):
def reverseKGroup(self, head, k):
pre, cur = he... |
#!/usr/bin/python3
"""
PE005: Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by
all of the numbers from 1 to 20?
"""
import functools
from .utils import lcm
def main(n=20):
... |
"""
Ejercicio 3: programa que compruebe si una variable está vacía.
Y si está vacía rellenarla con texto en minúscula y mostrarlo en mayúsculas.
"""
# comprobar variable
texto = ""
if len(texto.strip()) <= 0:
print("La variable está vacía")
else:
print("La variable tiene contenido", len(texto))
variable_vacia... |
import asyncio
from decimal import Decimal
from typing import Awaitable, Optional
from unittest import TestCase
from hummingbot.client.config.client_config_map import ClientConfigMap
from hummingbot.client.config.config_helpers import ClientConfigAdapter
from hummingbot.connector.exchange.bitfinex.bitfinex_exchange im... |
#!/usr/bin/env python2
# coding: UTF-8
import rospy
import math
from consai2_msgs.msg import VisionGeometry
from consai2_msgs.msg import BallInfo, RobotInfo
from consai2_msgs.msg import DecodedReferee
from consai2_msgs.msg import ControlTarget
from geometry_msgs.msg import Pose2D
import referee_wrapper as ref
import ... |
'''
Cross over operators for evolutionary algorithms
'''
import numpy as np
from abc import ABC, abstractmethod
class AbstractCrossoverOperator(ABC):
@abstractmethod
def crossover(self, parent_a, parent_b):
pass
class PartiallyMappedCrossover(AbstractCrossoverOperator):
'''
Partially Mapped Cr... |
import time
import pexpect
import execute
import Devices
import clear_buffer
import getdata
class IBGP:
def Configure_IBGP(self, Device, AS_id, Interface, Action):
device_data = getdata.get_data()
hostname = device_data['Device_Details'][Device]['Hostname']
Dev = Devices.Devices()
... |
import math
v = float(input('Digite um ângulo: '))
s = math.sin(v)
c = math.cos(v)
t = math.tan(v)
print('O valor {}º corresponde aos valores: \nSeno {:.3f} \nCosseno {:.3f} \nTangente {:.3f}'.format(v, s, c, t))
|
# coding: utf-8
# ### scikit-learn中的SVM
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
# In[3]:
# 因为SVM只能处理二分类问题,因此该样例只能取两个分类来训练
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y < 2, :2]
y = y[y < 2]
# In[22]:
plt.scatter(X[y==0, 0], X[y==0, 1],... |
from dicelib import dice
dice_list = []
for _ in range(0, 5):
new_dice = dice.Dice()
new_dice.roll()
dice_list.append(new_dice)
print(sum(dice_list))
|
# 1.Basic - Print all integers from 0 to 150.
for i in range(0, 151):
print(i)
# 2.Multiples of Five - Print all the multiples of 5 from 5 to 1,000
for i in range (5,10001):
if i%5 == 0:
print(i)
# 3.Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divi... |
import os
import sys
import json
import os.path
import requests as req
import numpy as np
import pandas as pd
from surprise import Dataset
from surprise import Reader, Dataset, SVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from joblib import (load... |
"""Pytest plugin that mocks subprocess.Popen."""
import subprocess
import pytest
from .creplay import load_log
class PopenController:
"""Controller for mocking subprocess.Popen."""
# Path to the currently active replay log.
log_path = ''
# Set of commands supported by current replay log.
comm... |
# price = 10
# price = 20.44
# name = 'Victor'
# checked = True
# is_published = False
# print(price)
# name = input('What is your name? ')
# print('Hi ' + name)
# from ecommerce.shipping import calc_shipping
# calc_shipping()
from pathlib import Path
# path = Path("ecommerce1")
# print(path.rmdir())
path = Pa... |
class Soccer:
def maxPoints(self, wins, ties):
return max(map(lambda (w, t): 3*w + t, zip(wins, ties)))
|
from django.urls import path
from .views import HomeView, ListaErroresView, ConfigurarBaseView, PaletaView
from .views import ColoresView, OtrosView, ConfigurarModeloNuevaView
from .views import EditarReporteView
from .views import ConfigurarUpdateContiguoView, ConfigurarUpdateAbajoView, ConfigurarBorraView, Configurar... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 22:50:22 2019
@author: anirbanhp
"""
from load_mnist import *
import matplotlib.pyplot as plt
import numpy
from sklearn.neural_network import MLPClassifier
#from keras.layers import Dense
#from keras.models import Sequential
X_train, y_train = load_mnist('training'... |
#coding=utf-8
from selenium import webdriver
import time
import os
driver = webdriver.Chrome()
driver.get("http://zpre.cnsuning.com")
driver.find_element_by_link_text("登录").click()
time.sleep(10)
div = driver.find_element_by_class_name("tang-pass-login").find_element_by_name("userName")
div.send_keys("userna... |
import json
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'demo/index.html')
def deal_get(request):
if request.method == 'GET':
value = request.GET['key1']
context = {'key': value, 'method': 'g... |
"""
Generate Phone Number w/Area Code
For each person in the dictionary below, insert a
randomly generated phone number. Make sure to use
these SPECS:
- Should be a string in this format: 1-718-786-2825
- Must randomly choose one of these area codes: 646, 718, 212
Hint: Another function from the random module might... |
# Copyright (c) 2020-2021 Matematyka dla Ciekawych Świata (http://ciekawi.icm.edu.pl/)
# Copyright (c) 2020-2021 Robert Ryszard Paciorek <rrp@opcode.eu.org>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... |
import platform
import subprocess
def check_os():
if platform.system().lower() != "linux":
print "The script you're trying to run is for Linux only"
quit()
def ssh_available(host):
command = "nmap %s" % host
process = subprocess.check_output(command, shell = True)
if "ssh" in process:
... |
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.contrib import messages
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, View, TemplateView
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.au... |
class Solution:
def maximalSquare(self, matrix):
# Dynamic programming, time O(mn), space O(mn)
if not matrix: return 0
rows = len(matrix) + 1
cols = len(matrix[0]) + 1
maxLength = 0
dp = [[0] * (cols + 1) for _ in range(rows + 1)]
for i in range(1, rows + ... |
# Generated by Django 3.0.1 on 2020-07-19 15:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0023_auto_20200719_1546'),
]
operations = [
migrations.AlterField(
model_name='userprofileinfo',
name='p... |
import sys
import jsonlines
import random
import json
import os
from itertools import chain
from collections import defaultdict
def split_seq(seq, limit):
if len(seq) > limit:
return split_seq(seq[:int(len(seq)/2)], limit) + split_seq(seq[int(len(seq)/2):], limit)
else:
return [seq]
def valida... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-25 08:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0001_initial'),
]
ope... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.