text stringlengths 38 1.54M |
|---|
import argparse
from memory_core.memory_core import gen_memory_core, Mode
from memory_core.memory_core_magma import MemCore
from lake.utils.parse_clkwork_csv import generate_data_lists
import glob
import tempfile
import shutil
import fault
import random
import magma
import os
from gemstone.common.testers import ResetTe... |
import os
from os.path import join
import numpy as np
import pandas as pd
from numpy.linalg import pinv
from sklearn.base import TransformerMixin
from sklearn.externals.joblib import load
from sklearn.model_selection import GroupShuffleSplit
from sklearn.preprocessing import LabelBinarizer, StandardScaler, LabelEncode... |
from tweepy import Stream, OAuthHandler
from tweepy.streaming import StreamListener
import json
ckey="2AvbG84msbL34BEHslMsWZTUR"
csecret="gzEENqmZoMl2hhHvDIdaWzIF9ShMSLO0o7gh8csZnfqKdK6Y9H"
atoken="14113114-1we8sJQs1z54dWfjWbUwZtDtkQYf3kDOrXLUMBFkZ"
asecret="6Sq95ezVVRNTuLw7grKzm4czA32VqmlM0QwvaLjWLNl5A"
class Tw... |
#Q1
x=lambda a,b:a*b
print(x(2,2))
print()
#Q2
n=int(input("Enter number of elements in fibonacci series "))
lst=[0,1]
y=lambda c,d:int(c+d)
print(lst[0],"",lst[1],end=" ")
for i in range(n-2):
z=y(lst[i],lst[i+1])
print(z,end=" ")
lst.append(z)
print()
#Q3
li=[1,2,3,4,5]
e=list(map(lambda... |
# 作者: 迷路的小怪兽
# 创建时间: 2021/10/28 23:00
from src.common.mytest import MyTest
from src.common.baseflow import Para
from src.flows.prepare_flow import PrepareFlow
from src.flows.aftermath_flow import AfterMathFlow
from src.flows.baidu_home_flow import SearchFlow
class TestBaiduFlows(MyTest):
para = Para(
key... |
# ENTRADA
print('A seguir, digite dois números:')
numero1 = float(input('Digite o 1º número: '))
numero2 = float(input('Digite o 2º número: '))
# PROCESSAMENTO
divisao = (numero1 + numero2) / (numero1 - numero2)
# SAÍDA
print('')
print('O resultado da divisão da soma pela diferença desses números é: {:.3f}'.format(di... |
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm
import pandas as pd
from prior_evaluation_tool.main import create_app
size = 200
true_intercept = 1
true_slope = 2
x = np.linspace(0, 1, size)
# y = a + b*x
true_regression_line = true_intercept + true_slope * x
# add noise
y = ... |
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
import config
args = config.parse_args()
primary_hidden_units = [64, 32]
adversary_hidden_units=[32]
class Primary_NN(nn.Module):
def __init__(self,indim, primary_hidden_units):
super().__init__()
... |
"""Contains methods for node setups creation"""
from typing import Any, Optional
from pyviews.core.binding import Bindable
from pyviews.core.rendering import Node, NodeGlobals, RenderingContext
from pyviews.core.xml import XmlNode
from pyviews.pipes import apply_attributes, render_children
from pyviews.rendering.conte... |
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion of data[low] to data[high] inclusive.
"""
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid... |
import pandas as pd
data = pd.read_csv('LINADV_data.txt', sep='\s+', header = None)
data = pd.DataFrame(data)
import matplotlib.pyplot as plt
x = data[0]
y = data[1]
z = data[2]
#w = data[3]
plt.plot(x,y,'r',label="Initial State")
plt.plot(x,z,'b',label="Final State")
#plt.plot(x,w, 'g', label = "Initial Height Tenden... |
# OCR of Hand-written Digits
# Our goal is to build an application which can read the handwritten digits. For this we need some train_data and test_data. OpenCV comes with an image digits.png (in the folder opencv/samples/python2/data/) which has 5000 handwritten digits (500 for each digit). Each digit is a 20x20 imag... |
from django.conf.urls.defaults import *
urlpatterns = patterns(
'areas.views',
#(r'^map/view/(?P<mapId>\d+)/', 'renderMap'),
#(r'^map/edit/(?P<mapId>\d+)/', 'editMap'),
#(r'^map/move/(?P<mapId>\d+)/(?P<direction>\w+)/', 'move'),
(r'^area/list/', 'area_list'),
(r'^area/create/', 'area_create'),... |
from __future__ import absolute_import
from tests.integration.flask_app.app import sleep_task
from time import sleep
import pytest
from celery_once import AlreadyQueued
import pytest
@pytest.mark.framework
def test_flask():
sleep_task.delay(1)
sleep(0.5)
with pytest.raises(AlreadyQueued):
sleep_t... |
# reduce() function takes in a function and a list as argument
# new reduced result is returned
from functools import reduce
mylist = [1, 3, 5, 6, 7]
mul = reduce((lambda x, y: x * y), mylist) # returns product of all elements in mylist
print(mul)
print(type(mul))
|
import pymongo
import requests
import json
class Table(object):
def __init__(self,meta):
self.meta = meta
self.option_dict = None
self.data = None
def get_options(self):
pass
def fetch_data(self):
pass
class SpiderDB(object):
def __init__(self,clien... |
import os
import importlib.util as imp
from azureml.api.schema.schemaUtil import *
from azureml.api.exceptions.BadRequest import BadRequestException
from azureml.api.realtime.swagger_spec_generator import generate_service_swagger
driver_module_spec = imp.spec_from_file_location('service_driver', 'score.py')
driver_mo... |
# -*- coding: cp1252 -*-
"""Enrique Ibáñez Orero - 1º DAW - Practica 7 - Ejercicio 4 - Pràctica 7.
Escribe un programa que pida una frase, y le pase como parámetro a una
función dicha frase. La función debe sustituir todos los espacios
en blanco de una frase por un asterisco, y devolver el resultado
para que el pr... |
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the biggerIsGreater function below.
def biggerIsGreater(w):
w = list(w)
for i in xrange(len(w) - 2, -1, -1):
if w[i] < w[i + 1]:
idx = i
break
if not idx:
return "no answer"
small = idx + 1
for i in xrange(idx + 2, len(w... |
from calvin import *
#from postprocessor import *
# specify data file
calvin = CALVIN('calvin/data/links_infeasible.csv')
# create pyomo model from specified data file
calvin.create_pyomo_model(debug_mode=False)
# solve the problem
calvin.solve_pyomo_model(solver='glpk', nproc=10, debug_mode=False)
# po... |
refFilePath = "../../../data/sapIngB1.fa"
# kmer model
kmerModelFilePath = "../../../data/kmer_model.hdf5"
# positive and negative reads folder
readsPosFilePath = "goodReadsDebug.txt"
readsNegFilePath = "../../../data/neg-basecalled"
targetContig = "contig1"
targetBeg, targetEnd = 0, 50000
posTestCases, negTestCases... |
import re
import numpy as np
from prody import *
def extract_pockets(filepath,pdbid,selection):
"""Returns dictionaries where the key is pocket ID (starting at zero) and the value is a list of residue indices or numbers/chains in the pocket."""
# dictionary where key is pocket ID (starting at zero) and value ... |
import PySimpleGUI as sg
'''
this python file is for another pop out window which shows the maths of
how the cumulative probability function works
'''
def explanation2():
layout1 = [
[sg.Image(filename = 'betacdf.PNG')]
]
window3 = sg.Window('Probability Densities', layout1)
... |
from . import *
def FermiDirac(en, T):
"""
The Fermi-Dirac distribution.
Parameters
----------
en: array-like
Energy of state in units J
T: scalar
Temperature in units K
Returns
----------
FD: array-like
Fermi-Dirac probability of state at energy en
"""
kB = 1.38064852*10**-23 # J/K
... |
from django import forms
import random
from .models import Guitar, Story, Photos, Specs, Appearances, Videos
master_id = 0
class AppearForm(forms.ModelForm):
Appearances.guitar_id = master_id
tour_name = forms.CharField(required=False)
album_name = forms.CharField(required=False)
class Meta:
... |
#!/usr/bin/env python
import glob
import os
from itertools import chain
from sys import argv
import pycodestyle
EXTS = ('.py', '.pyx')
SKIP_ERRORS = {'a_intro/sequences.py': ('E402', 'E711', 'E712')}
SCRIPTS = ('sci_py_example', 'sci_py_import_all', 'sci_py_test_style')
def check_style(fpath):
for exception_p... |
import logging
import re
import serial
import sys
import time
logging_handler = logging.StreamHandler(sys.stdout)
logging_handler.setFormatter(logging.Formatter(
'[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
))
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(loggin... |
#!/usr/bin/env python
#
# Copyright (C) 2012 Space Monkey, Inc.
#
# 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, copy, ... |
import numpy as np
import matplotlib.pyplot as plt
from grid_world import standard_grid, negative_grid
GAMMA = 0.9
ALL_POSSIBLE_ACTIONS = ('U','D','L','R')
# This script implements the monte carlo exploring-starts method for finding optimal policy.
def print_values(V,g):
for i in range(g.width):
print("-... |
#!/usr/bin/env python
import roslib
import rospy
import math
import tf
import geometry_msgs.msg
import turtlesim.srv
from sensor_msgs.msg import CameraInfo
# https://github.com/carla-simulator/scenario_runner/blob/master/srunner/challenge/autoagents/ros_agent.py
def build_camera_info(attributes):
"""
Private... |
def coordenadaZ(x, y):
for i in range(3):
x = x + 1
y = y + 1
return x , y
# programa principal
x = int(input("Ingrese la coordenada del eje x: "))
y = int(input("Ingrese la coordenada del eje y: "))
print("Coordenadas finales:",coordenadaZ(x,y))
|
import os
import torch
import argparse
import numpy as np
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torchvision.utils import save_image
cuda = True if torch.cuda.is_available() else False
os.makedirs('../images', exist_ok=True)
class Generator(nn... |
#import model_b.layers as layers
import layers_cc as layers
def baseline(x,view_type, nodropout_probability=None, gaussian_noise_std=None):
#x,view_type = input
if gaussian_noise_std is not None:
x = layers.all_views_gaussian_noise_layer(x, gaussian_noise_std)
# first conv sequenc... |
from flask import Flask,render_template,Response
app = Flask(__name__)
class Config(object):
DEBUG = True
app.config.from_object(Config)
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/add_user')
def add_user():
return Response('........')
@app.route('/user_list')
d... |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('todos.views',
url(r'^$', 'index', name='index'),
url(r'^lists/$', 'lists', name='lists'),
url(r'^lists/(?P<pk>\d+)/$', 'list', name='list'),
url(r'^item/(?P<pk>\d+)/$', 'item', name... |
import time
import numpy as np
from .base_env import BaseEnv
from .blue_team.blue_base import BlueTeam
from .red_team.red_base import RedTeam # noqa
from .sensors import Sensors
from .interaction_manager import InteractionManager
class EnhanceEnv(BaseEnv):
def __init__(self, config):
# Initialise the ... |
# coding=utf-8
import re
class BaseSite:
url_patterns = []
def __init__(self):
super(BaseSite, self).__init__()
def process(self, url, html):
params = {
'url': url,
'html': html,
'params': ''
}
return params
class Douban(BaseSite):
... |
"""
My constellation of social media sites that can be fetched and published.
"""
ACTIVELY_USED = {
'Delicious': 'http://delicious.com/palewire',
'Digg': 'http://digg.com/users/palewire',
'Facebook': 'http://www.facebook.com/palewire',
'Flickr': 'http://www.flickr.com/photos/77114776@N00/',
'Flixster': 'http://www... |
import tabula
import pandas as pd
# import time
# start_time = time.time()
tb_name="test"
df = tabula.read_pdf(tb_name+".pdf", pages='all', multiple_tables=True)
df = pd.DataFrame(df)
# df.to_excel('test.xlsx', header=False, index=False)
# df=pd.read_csv(tb_name+".csv", error_bad_lines=False, header=None)
... |
"""
This package describe all periodic tasks
"""
from celery import shared_task
from celery.utils import log
from sqlalchemy.orm import Session
from app.helper import get_config
from app.models import Microcontroller
from app.tasks import DBTask
from app.tasks.normal_tasks import check_host
_configs = get_config()
l... |
import os
from abc import ABC, abstractmethod
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found')
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import sys
import pickle
from keras.models import load_model
from sklearn.metrics imp... |
"""
sim_anneal.py
Author: Olivier Vadiavaloo
Description:
This file contains the code implementing the simulated annealing
algorithm.
"""
import copy as cp
from time import time
import random
import multiprocessing as mp
from math import exp
from src.dsl import *
from src.Evaluation.evaluation import *
from src.Opt... |
print("Using the values from a tuple")
for i in {1,2,3,4,5}:
print(i, " ", end='\n')
print("---------------------------------------------------")
print("Print out values in a range")
for i in range(1,10,2):
print(i, " ",end="\n")
print("---------------------------------------------------")
print("Using ... |
#!/usr/bin/env python
import glob
import numpy as np
import os
import pandas as pd
import sys
import trimesh
here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, ".."))
from parameters import (PipeFlowParams,
load_parameters)
def load_mesh(fname: str):
re... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
if (cap.isOpened()== False):
print("Error opening video stream")
id_counter = 0
started = False
recording = False
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
c... |
# This Python file uses the following encoding: utf-8
try:
text = input('Enter something --> ')
except EOFError:
print('\nWhy did you do an EOF on me?')
except KeyboardInterrupt:
print('\nYou cancelled the operation.')
except NameError:
print('\nSo you use python2, you should use \'my words\' as input')
else:
... |
from django.conf.urls import patterns, include, url
from test_app.views import AppIndexView
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'burstSMS.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', AppIndexView.as_view(), name='home'),
)
|
import warnings
warnings.filterwarnings('ignore')
import torchvision
import torch
from jetbot import Robot
import time
print("loading model")
model = torchvision.models.resnet18(pretrained=False)
model.fc = torch.nn.Linear(512, 2)
print("loading floor")
model.load_state_dict(torch.load('floor.pth'))
device = torch... |
'''2. Write a program to accept a two-dimensional array containing integers as the parameter and determine the following from the elements of the array:
a. Element with minimum value in the entire array
b. Element with maximum value in the entire array
c. The elements with minimum and maximum values in each column
d. T... |
import random
class bcolors:
HEADER = '\033[033m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Person:
def __init__(self,name,hp,mp,atk,df,magic,items):
self.name=name
s... |
"""Computation class for Concord
.. module:: Computation
:synopsis: Computation class and helper function
"""
import sys
import os
import types
import threading
from thrift import Thrift
from thrift.transport import (
TSocket, TTransport
)
from thrift.server import TServer
from thrift.protocol import TBinaryPr... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 11:50:05 2018
@author: kennedy
"""
__author__ = "kennedy Czar"
__email__ = "kennedyczar@gmail.com"
__version__ = '1.0'
import os
import time
from datetime import datetime
from os import chdir
from selenium import webdriver
from TICKERS import TICKER
class Data_colle... |
__author__ = 'dowling'
from mongokit import Document
from model.db import connection
class User(Document):
structure = {
'username': unicode,
'device': unicode
}
use_autorefs = True
use_dot_notation = True
connection.register([User])
|
# converts ok cupid profiles into a csv file with the features we want to include, empty neighbors and linear regression file
import pandas as pd
all = pd.read_csv("okcupid_profiles.csv") # the entire dataset
features_to_include = {'name', 'neighbors', 'age', 'status', 'sex', 'orientation', 'body_type', 'diet', 'dri... |
# -*- coding: utf-8 -*-
# LOC Map designer
import pygame
from config import ConfigManager
import maps
cfg = ConfigManager()
gridSize = dict(x=10,y=100,size=80)
pygame.init()
scrinfo = pygame.display.Info()
x = scrinfo.current_w - 100
y = scrinfo.current_h - 100
display = pygame.display.set_mode((x,y))
... |
__version__ = "2.6.0"
from pyquil.quil import Program
from pyquil.api import list_quantum_computers, get_qc
|
"""
Alexander Moriarty
Google Code Jam 2016
Problem A. Counting Sheep
"""
import sys
def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def count200(N):
list_of_ints = list()
n = None
for n_ in xrange(1,200):
list_of_ints += [int... |
def solution(numbers, hand):
left_hand = 10
right_hand = 12
answer = ''
left_flag = False
right_flag = False
for i in range(len(numbers)):
if numbers[i] == 0:
num = 11
else:
num = numbers[i]
if numbers[i] == 1 or numbers[i] == 4 or numbers[i] == 7:... |
import threading
import keyboard
import time
try:
from MainAssistant import main
except:
import main
import subprocess as s
print("started")
hotkey = "shift + alt"
Killhotkey = "ctrl + alt"
def killProcess(pid):
s.Popen('taskkill /F /PID {0}'.format(pid), shell=True)
def kill():
while True:
i... |
# Bonnet's thm: d/dm E[f(z)] = E[d/dz f(z)] for z ~ N(m,v)
#Price's thm: d/dv E[f(z)] = 0.5 E[d^2/dz^2 f(z)] for z ~ N(m,v)
# Note that we are taking derivatives wrt the parameters of the sampling distribution
# We rely on the fact that TFP Gaussian samples are reparameterizable
import numpy as np
import jax
import ... |
from django.shortcuts import render
from .models import Song,Audio
from django.views.decorators.csrf import csrf_exempt
import os
from pathlib import Path
from django.core.files.storage import FileSystemStorage
import ffmpeg_streaming
from ffmpeg_streaming import Formats
from django.http import HttpResponse
import shut... |
from testing import *
from testing.tests import *
from testing.assertions import *
with all_or_nothing():
with tested_function_name("tree"):
tree = reftest()
tree('.')
tree('testdata')
tree('..')
|
import sqlite3
from employee import Employee
# conn = sqlite3.connect(':memory:')
conn = sqlite3.connect('employee.db')
c = conn.cursor()
# budući baza podataka već postoji ovo nam ne treba
# c.execute("""CREATE TABLE employees (
# first text,
# last text,
# pay integer
# ... |
# Exercício Python 045: Crie um programa que faça o computador jogar Jokenpô com você.
# EXTRA: Crie diferentes modos de jogo.
from random import choice as ch
from time import sleep as sl
lis = ['pedra', 'papel', 'tesoura']
def cls():
print('\n' * 5)
def jogo():
while True:
acao = str(input('''Esc... |
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import tensorflow.keras.layers as layers
__all__ = ['VGG','vgg16', 'vgg19']
class VGG(tf.keras.Model):
def __init__(self, features, classes=1000):
super(VGG, self).__init__()
self.features = f... |
"""Subclass of frmMorph, which is generated by wxFormBuilder."""
import wx
import TextmorphGui
from mylib import word_count
# Implementing frmMorph
class frmMorph(TextmorphGui.frmMorph):
def __init__(self, parent):
TextmorphGui.frmMorph.__init__(self, parent)
self.process_list = []
def tell_... |
class Solution(object):
def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
if not nums:
return []
res = list()
windows = list()
for i in range(k):
pos = self.binary_se... |
import sys
import re
args = sys.argv
if len (args) < 2:
print ("Usage: Python task1.py [filename]")
exit(0)
elif len (args) > 2:
print("Usage: Python task1.py [filename]")
exit(0)
fd = open(args[1], 'r')
contains = fd.read()
fd.close
regulars = re.findall(r"\d{0,}\n", contains)
if len(regulars) == 0:
... |
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
import bcrypt
from .models import User, Message, Comment
def index(request):
return render(request, 'login.html')
def registerUser(request):
errors = User.objects.basic_validator(request.POST)
if len(... |
import json
import socket
from confluent_kafka import Producer
class WebScrapingProducer:
def __init__(self):
conf = {'bootstrap.servers': "localhost:9092,localhost:9092",
'client.id': socket.gethostname()}
self.__producer = Producer(conf)
def criar_mensagem_producer(self, to... |
import os
import sys
from configparser import ConfigParser, ExtendedInterpolation
def base_dir():
return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
def get_setting(section, setting, func=str):
config = ConfigParser(interpolation=ExtendedInterpolation())
config.read(os.path.join(base_di... |
prizes = [20, 30,40, 1000]
double_prizes = []
for prize in prizes:
double_prizes.append(prize // 2)
print(double_prizes)
# comprehension method
double_prizes = [prize*2 for prize in prizes]
print(double_prizes)
# squaring numbers
nums = [1,2,3,4,5,6,7,8,7]
squared_nums = []
for num in nums:
if (num ** 2) %... |
import re
import os
import datetime
from .andhra import AndhraArchive
from ..utils import utils
class Maharashtra(AndhraArchive):
def __init__(self, name, storage):
AndhraArchive.__init__(self, name, storage)
self.baseurl = 'https://egazzete.mahaonline.gov.in/Forms/GazetteSearch.aspx'
... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:summer_han
'''
return 返回值 ,结束函数
return 可以返回什么样的值,
1、个数,类型, 值都不固定,随意指定
2、
'''
def test1():
print("in the test1")
def test2():
print("in the test2")
return 0
def test3():
print("in the test3")
return 1,"hello",['xi','han'],{"dabao":"erbao"}
x=te... |
s = input()
max = [s[0]]
def check(str):
temp = list(str)
for a in range(len(temp)-1):
if temp[a+1] < temp[a]:
return False
break
return True
# go short to long
for i in range(len(s)): # first char
for j in range(i, len(s)): # last char
if check(s[i:j]) and j-i > len(max):
max = s[i:j]
print('Longes... |
import grpc
import kvstore_pb2
import kvstore_pb2_grpc
import random
import logging
import json
import time
import os
import sys
import pickle as pkl
import threading
from threading import Condition
from enum import Enum
from KThread import *
from chaosmonkey import CMServer
class LogMod(Enum):
ADDITION = 1
A... |
"""
Created on Nov 05, 2019
@author: Kuznetsov Maxim <lol8funny@gmail.com>
"""
import sys
"""
Default CGI response class.
You can set all response parameters in dict, passing in
constructor, or set each parameter by setter. All unsetted params
will be set by default.
"""
# TODO: create headers getters
class Respon... |
from sys import stdin
def main():
operands = list()
for line in stdin:
operands.append(int(line.strip()))
print get_max_xor_value(operands[0], operands[1])
def get_max_xor_value(a, b):
max_val = 0
for opa in range(a, b+1):
for opb in range(a, b+1):
xor_val = (opa ^ opb)
if xor_val > max_val:
max_v... |
from numpy import array
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from matplotlib import pyplot
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from math import sqrt
from numpy import split
import pandas as pd
import numpy as np
from nump... |
# python list index() #
def main():
thelist = ["less","roman","Lashley","sami",1,1]
x = thelist.index("less")
y = thelist.index(1)
print(x,y)
if __name__ == "__main__":
main()
|
import os
import sys
current_path = os.path.dirname(os.path.realpath(__file__))
root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(root_path)
import json
from tunner.utils import ROOT_DIR
import csv
output_dir = ROOT_DIR + '/output/'
finished_list = list(filter(lambda x: os.path... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
# add current ToNgueLP location to python PATH to locate modules
#sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../../')))
# import PyQt4 QtCore and QtGui modules
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# import main window
fro... |
n1=int(input('Enter first number'))
n2=int(input('Enter second number'))
def Karatsuba(x,y):
len_x=len(str(x))
len_y =len(str(y))
if len_x != 1:
if len_x%2!=0:
a=int(x//(10**((len_x+1)//2)))
b=int(x%(10**((len_x+1)//2)))
else:
a=int(x//(10**(len_x//2)))
b=int(x%(10**(len_x//2)))
else:
a=0
b=x
... |
from ch03.stack import Stack
import pytest
def test_iter():
ll_iter = Stack(10, 11, 12).__iter__()
assert ll_iter.__next__() == 12
assert ll_iter.__next__() == 11
assert ll_iter.__next__() == 10
with pytest.raises(StopIteration):
ll_iter.__next__()
with pytest.raises(StopIteration):
... |
#! /usr/bin/env python
import os
import sys
import pandas as pd
import datetime
import pandas_datareader.data as web
from pandas_datareader.data import Options
from yahoo_finance import Share
from fredapi import Fred
from openpyxl import load_workbook
from optparse import OptionParser
pretty = False
parser = Optio... |
import sys
import numpy as np
from timeit import default_timer as timer
import matplotlib.pyplot as plt
from naive import Naive
from backtracking import Backtracking
from branch_and_bound import BranchAndBound
class Comparison:
def __init__(self):
self.MinIteration = 6
self.MaxIteration = 12
... |
def slices(series, length):
if not series:
raise ValueError('series cannot be empty')
elif length == 0:
raise ValueError('slice length cannot be zero')
elif length < 0:
raise ValueError('slice length cannot be negative')
elif len(series) < length:
raise ValueError('slice ... |
from picamera.array import PiYUVArray, PiRGBArray
from picamera import PiCamera
from scipy.signal import find_peaks, butter, filtfilt
from simple_pid import PID
from pwm import PWM
import ipywidgets as ipw
import time
import matplotlib.pyplot as plt
import skimage as ski
import numpy as np
import time
import threading
... |
#!/usr/bin/env python
"""
test that everything works
This should be superseeded by an eventual unittesting
"""
from latgas import lattice
from latgas.lattice import Lattice, Potential, System
sz = 30
def inter(r):
if r <= 1.0: return -4
if r <= 3.0: return 1
lattice = Lattice(sz, dim = 2)
potential = Potent... |
'''
Author: Ben Joris
Created: October 24, 2019
Purpose: Extract country of origin info from file names and add it to tsv to import into anvio
'''
import glob # glob is a library to get lists of files on your system
countrydict={} # initialize empty dictionary that will be populated with the metadata
######
'''
- Th... |
# -*- coding: utf-8 -*-
"""
Created on Thu May. 23. 2018
@author: MRChou
Code used for create submission file for models.
Used for the Avito Demand Prediction Challenge:
https://www.kaggle.com/c/avito-demand-prediction/
"""
import os
import pickle
import numpy
import pandas
import xlearn
import xgboost as xgb
from s... |
#!/usr/bin/env python3
erste_eingabe = input('Erster Summand: ')
zweite_eingabe = input('Zweiter Summand: ')
a = float(erste_eingabe)
b = float(zweite_eingabe)
s = a + b
print('Die Summe ist: ' + str(s))
for i in range(10):
|
# coding: utf-8
import os
import time
import tensorflow as tf
import matplotlib
from ml_utils import *
# global setting
vector_type = "2vectors" # 1vector
print("Processing {}".format(vector_type))
if vector_type == "1vector":
one_vector_flag = True
else:
one_vector_flag = False
#############################... |
#Código para verificação da aprovação de um aluno usando função
nota1 = 7.5
nota2 = 4.8
notas = [nota1, nota2]
#Definimos aqui o que é a função verificar uma aprovação
def verificar_aprovacao() :
media = calcular_media(nota1, nota2)
if media >= 6:
print("O aluno foi aprovado!")
else:
print... |
# -*- coding:utf-8 -*-
# s = 10
# number = ()
# print(number == None)
# for n in number:
# print(s * n)
# a = ' '
# print(a == None)
# print(len(a))
#
# b = 'abcd'
# print(b[0:])
# for n, value in enumerate(b):
# print(n, value)
# print(5, value)
# def findMinAndMax(L):
# min = max = 0
# for x in... |
#!/usr/bin/env python3
import os.path
import subprocess
from base64 import b64encode
def _write_secret(name, fpath):
with open(fpath, 'rt') as f:
secret_data = f.read()
secret_data_b64 = b64encode(secret_data.encode()).decode()
secret_yaml = '\n {}: {}'.format(
os.path.basename(fpath), s... |
from .zc_evaluator import ZeroCostPredictorEvaluator
from .full_evaluation import full_evaluate_predictor |
# -*- coding: utf-8 -*-
""" Polynomial Time SEMI Algorithm
This algorithm allows the computation of the central nodes of a network
with a polynomial time complexity, differently from the classic exponential version.
"""
import numpy as np
from ALGORITHM.TOOLS.mathematical_tools import fast_binomial
def shap... |
# @tokoroten-lab 氏のコードを参考にしています
# https://qiita.com/tokoroten-lab/items/bb27351b393f087650a9
import numpy as np
import matplotlib.pyplot as plt
import pickle
import time
import socket
import sys
import glob
import time
# plt.rcParams['xtick.direction'] = 'in'
# plt.rcParams['ytick.direction'] = 'in'
plt.rcParams['axes... |
def myfunc(firstname, lastname):
print('hello "%s %s", how are you?' % (firstname, lastname))
myfunc('Tony', 'Starks') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.