text stringlengths 8 6.05M |
|---|
class Chromatique():
def __init__(self):
self.gen1 = [
{'name': 'Bulbizarre','numero': '001'},
{'name': 'Herbizarre','numero': '002'},
{'name': 'Florizarre','numero': '003'},
{'name': 'Salameche', 'numero': '004'},
{'name': 'Reptincel', 'numero': '... |
# -*- coding: UTF-8 -*-
import platform
import argparse
import csv
import time
from enum import Enum
from io import BytesIO
import sys
import os
import logging
import re
from pathlib import Path
import requests
import pdfkit
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdri... |
import nox
@nox.session(python=["3.8", "3.7"])
def tests(session):
"""Run the test suite."""
env = {"VIRTUAL_ENV": session.virtualenv.location}
session.run("poetry", "install", external=True, env=env)
session.run("pytest", "--cov", *session.posargs)
|
'''
Eric Nguyen
Github: Nooj45
CS 1656
Professor Alexandros Labrinidis
Assignment 1
'''
import sys
import requests as req
import json
import math
from math import cos, asin, sqrt
def total_bikes():
sumBikes = 0
#looking through each dict in the list stationData and summing up num_bikes_available
for numBik... |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^refer/','py_django_test.refer_test.views.refer')
# Examples:
# url(r'^$', 'py_djan... |
#!/usr/bin/env python3
# vim: set ai et ts=4 sw=4:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import csv
data_names = ['cafe', 'pharmacy', 'fuel', 'bank', 'waste_disposal',
'atm', 'bench', 'parking', 'restaurant',
'plac... |
import random
import os
import urllib
if not os.path.exists('training'):
os.makedirs('training')
if not os.path.exists('test'):
os.makedirs('test')
#training data
for i in range(10):
#tiling_resolution = random.randint(0, 11)
tiling_resolution = 11
column_num = 320
row_num = 640
#column_n... |
#!/usr/bin/python
#qplot -x -3d -s 'set xlabel "x";set ylabel "y";set view equal xy' outcmaes_obj.dat w l outcmaes_res.dat ps 3 data/res000{0,1,2,3,5,6}.dat -showerr
import cma
import numpy as np
def fobj1(x,f_none=None):
assert len(x)==2
if (x[0]-0.5)**2+(x[1]+0.5)**2<0.2: return f_none
return 3.0*(x[0]-1.2)**... |
#!/usr/bin/env python
# encoding: utf-8
"""
test_orig_dmarket.py
Created by Jakub Konka on 2011-05-09.
Copyright (c) 2011 University of Strathclyde. All rights reserved.
"""
from __future__ import division
import sys
import os
import numpy as np
import scipy.integrate as integral
import scipy.stats.mstats as mstats
im... |
try:
import tkinter as tk
from tkinter import messagebox
except:
import Tkinter as tk
import tkMessageBox as messagebox
import ttk
import time
from scraper.scraper_1 import Drug_Recalls
color = ["#329fea", "#cc93e8"]
def Drug_GUI(frame):
parse_ctrl = Drug_Recalls()
parse_ctrl.parse()
... |
# Generated by Django 2.1.4 on 2019-01-09 18:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('services', '0002_auto_20190109_1816'),
('psychologues', '0008_psychologuesservicesofferts'),
]
operations =... |
def text():
return "kokoko" |
'''
Created on Jul 20, 2016
@author: Dayo
'''
from django.test import TestCase
from django.contrib.auth.models import User
from datetime import datetime
from ..tasks import process_onetime_event, process_private_anniversary, process_public_anniversary
from core.models import Event, Contact, MessageTemplat... |
from __future__ import print_function, division
from math import exp
from keras import initializers, regularizers, activations, constraints
from keras.engine import Layer, InputSpec
from keras.models import Model, model_from_json
from keras.layers import Input, Embedding, TimeDistributed, Dense, Dropout, Reshape, Con... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from hyper_parameters import *
from global_parameters import *
class AcNet(object):
'''
Class: A3C network
'''
def __init__(self, scope, globalAC=None):
'''
:param scope: The network it belongs to
:param globalAC: The global_net name... |
#default flask app for funzies
from flask import Flask, render_template, request, redirect, url_for, session
import utils.manage, hashlib, os
app = Flask(__name__)
app.secret_key = os.urandom(32)
@app.route('/')
def display_login():
#====== DIAGNOSTIC PRINT STATEMENTS ======
print '\n\n\n'
print '=== DIAG... |
import sys
sys.path.append("/Applications/Autodesk/maya2015/Maya.app/Contents/Frameworks/Python.framework/Versions/Current/lib/python2.7/site-packages/numpy-1.9.1-py2.7-macosx-10.6-intel.egg")
import maya.standalone
maya.standalone.initialize("Python")
import maya.cmds as cmds
import numpy as np
import math as ma
i... |
import string
import unicodedata
import os
def clear():
os.system("cls")
def keyOK(n, offset):
return offset >= 0 and offset <= 2*n-3
def computeCoordinates(n, l, offset):
coordinates = []
row = 0
isRising = False
if offset > n-1:
offset = (n-1)-(offset-(n-1))
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import requests
class AvaClient(object):
def __init__(self, token, url):
self._token = token
self._url = url
self._headers = {
'Authorization': self._token,
}
def get... |
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('cascade.xml')
img = cv2.imread('Training/show_img/1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
faces = face_cascade.detectMultiScale(gray,
scaleFactor = 1.1,
... |
# Copyright 2019 The ASReview Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
import re
class Session:
__sessid = -1
def __init__(self, name, speaker, description, start_time, end_time, date, capacity):
self._sessid = self._generate_id()
self._name = name
self._speaker = speaker
self._description = description
self._start_time = start_time
... |
#Written by Adam Turnbull
from psychopy import visual from psychopy import visual
from psychopy import gui, data, core,event
import csv
import time
from time import localtime, strftime, gmtime
from datetime import datetime
import os.path
import pyglet
# Kill switch for Psychopy3
event.globalKeys.clear() # clear glob... |
import sys
import ProcessCMDArgs
import DocumentProcessor
def logicOfProgram (listOfCMDArgs):
def build(dict_dpb_parsed_args):
dpb = dict_dpb_parsed_args.get('dpb')
dp = DocumentProcessor.DocumentProcessor(dpb);
if 'words_to_search_for' in dict_dpb_parsed_args:
search = dict_dp... |
import os
import datetime
import calendar
import logging
from typing import Dict
from django.conf import settings
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from packages.tasks import celery_generate_summary
from packages.utils import... |
from torch.utils.data import Dataset
import os
import numpy as np
import torch
from PIL import Image
class Data(Dataset):
def __init__(self, path):
#传入图片路径
self.path = path
#创建数据集
# self.dataset = []
#将数据传入数据集
self.dataset = os.listdir(self.path)
# self.data... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Score
from .serializers import ScoreSerializer
class ScoreView(APIView):
def post(self, req):
score = {
'user': req.data.get('userId'),
'win': req.data.get('win... |
for i in range(10):
print(f"i is now {i}")
print("*" * 20)
i = 0
while i < 10:
print(f"i is now {i}")
i += 1 |
# -*- coding: utf-8 -*-
from datetime import datetime
from irc3.compat import Queue
from irc3.compat import QueueFull
import irc3
__doc__ = '''
==============================================
:mod:`irc3.plugins.ctcp` CTCP replies
==============================================
..
>>> from irc3.testing import IrcBot
... |
#!/usr/bin/python
from termcolor import colored
import sys
import signal
import requests
import json
from flask import jsonify
def signal_handler(sig, frame):
print()
print(colored("Pleeaasee don't leave me",'cyan',attrs = ['bold']))
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
flag = 0
# use... |
import pytest
from autumn.settings import Models
from autumn.core.project.project import _PROJECTS, get_project
COVID_PROJECTS = list(_PROJECTS[Models.COVID_19].keys())
@pytest.mark.benchmark
@pytest.mark.github_only
@pytest.mark.parametrize("project_name", COVID_PROJECTS)
def test_benchmark_covid_models(project_na... |
# Generated by Django 3.1.3 on 2020-11-29 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio_app', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='portfolio',
name='img',
... |
import re
sectors = open('input').read()
total = 0
for sector in sectors.split("\n"):
if not sector:
continue
letters = dict()
sector_id = re.search(r"\d+", sector).group(0)
checksum = re.search(r"\[(.*?)\]", sector).group(1)
full_code = re.match(r"[a-z-]+", sector).group(0)
codes = ... |
import math
import types
"""Module containing functions and classes that are shared between different tests"""
def assertFloatWithinPercentage(testCase, expect, actual, percenttolerance = 0.5, places = 5):
"""Assert that actual is within percenttolerance of expect. Percenttolerance is specified as a percentage of
... |
/home/ajitkumar/anaconda3/lib/python3.7/enum.py |
# vim:fileencoding=utf-8:noet
# WARNING: using unicode_literals causes errors in argparse
from __future__ import (division, absolute_import, print_function)
import argparse
import sys
from itertools import chain
from powerline.lib.overrides import parsedotval, parse_override_var
from powerline.lib.dict import mergea... |
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
import astropy.coordinates as coords
from astropy.time import Time
from astropy.timeseries import TimeSeries
from pygdsm import GSMObserver2016, GlobalSkyModel2016
from datetime import datetime
from healpy import ang2vec, ang2pix, get_nside
... |
max_value = 0
min_value = 1000
student_scores = input("Input a list of student scores with 'space' between each score: \n").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
if student_scores[n] > max_value: max_value = student_scores[n]
if min_value > student_scores[n]: ... |
T = [
"light red bags contain 1 bright white bag, 2 muted yellow bags.\n",
"dark orange bags contain 3 bright white bags, 4 muted yellow bags.\n",
"bright white bags contain 1 shiny gold bag.\n",
"muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\n",
"shiny gold bags contain 1 dark oli... |
"""
Invokes flask_djangofy-admin when the flask-djangofy module is run as a script.
Example: python -m flask_djangofy check
"""
from flask_djangofy.core import management
if __name__ == "__main__":
management.execute_from_command_line() |
from rest_framework import viewsets
from share.models.jobs import IngestJob
from api.base.views import ShareViewSet
from api.pagination import CursorPagination
from api.ingestjobs.serializers import IngestJobSerializer
class IngestJobViewSet(ShareViewSet, viewsets.ReadOnlyModelViewSet):
ordering = ('-id', )
... |
# import blender gamengine modules
from bge import logic
from bge import events
from bge import render
from . import bgui
from .settings import *
from .helpers import *
import time
import pdb
import colorsys
import random
class Timeline():
def __init__(self, timelineWidget, scrollerWidget, sys):
'''sets-up timeli... |
nt1 = float(input('Digite a primeira nota: '))
nt2 = float(input('Digite a segunda nota: '))
media = (nt1 + nt2) / 2
if media < 5:
print('VocÊ foi reprovado sua média é {:.1f}.'.format(media))
elif 5 <= media <= 6.9:
print('Você está em recuperação, sue média é {:.1f}.'.format(media))
elif media > 7:
print(... |
from hexadecimal import Hexadecimal
def main():
grade = 0
#Constructor worth 25 points
grade += test_constructor()
#Overloaded str() worth 10 points
grade += test_str()
#Overloaded math operators (+, -, *, /, **, %) worth 20 points
grade += test_math_ops()
#Overloaded re... |
import re,string,random
# from django.apps import apps
# from django.db.models import Max
from cl_table.models import Fmspw, Securitylevellist
def code_generator(size=4,chars=string.ascii_letters + string.digits):
code = ''
for i in range(size):
code += random.choice(chars)
return code
# def cre... |
from django.db import models
from patients.models import Patient
from django.contrib.auth.models import User
class Lab(models.Model):
name = models.CharField(max_length=30)
category = models.CharField(max_length=30)
class Diagnosis(models.Model):
VISIT_TYPES = (
('Inpatient', 'Inpatient'),
... |
#!/usr/bin/python
## Author: Omid Shams Solari
## E-mail: omid@genapsys.com
## Date: 03/16/2014
import numpy as np
from Bio import Seq, SeqIO
from Bio.Alphabet import IUPAC
from Bio.SeqRecord import SeqRecord
def createRecord(seq, parentRec):
""" inputs: seq <Seq object>
parentRec <record object>
... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='vcs_learning',
version='0.1',
description="Learning to develop a Version Control System",
long_description_markdown_filename='README.md',
url='https://github.com/ShubhankarKG/VCS_learnings.git',
license='AGPL-3.0-... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution1(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
"""
... |
from solvent import config
from solvent import label
from solvent import run
from upseto import gitwrapper
class ThisProjectLabel:
def __init__(self, product):
gitWrapper = gitwrapper.GitWrapper('.')
hash = gitWrapper.hash()
basename = gitWrapper.originURLBasename()
if config.OFFI... |
from kaffe.tensorflow import Network
class MobileNetYOLO(Network):
def setup(self):
(self.feed('data')
.conv(3, 3, 32, 2, 2, biased=False, relu=False, name='conv0')
.batch_normalization(relu=True, name='conv0_bn')
.conv(3, 3, 32, 1, 1, biased=False, group=32, relu=Fal... |
## @package test_tiles
## Unit tests for tiles (under constrcution).
from unittest import TestCase
from unittest import TestSuite
from enhanced_grid import Grid2D
from tiles import energy2
from tiles import energy3
from tiles import calc_acc_energy
from tiles import find_min_seam
from tiles import quilt
from tiles ... |
def read_file(file_name):
file_dic = {}
with open(file_name, 'r') as input_file:
lines = input_file.readlines()
for index in range(0, len(lines) - 1, 2):
if lines[index].strip() == '':
continue
cnt = int(lines[index].strip())
name = lines[index... |
# 실습 : 19_1, 2, 3, 4, 5, EarlyStopping 까지
# 총 6개의 파일을 완성하시오.
import numpy as np
from sklearn.datasets import load_diabetes
dataset = load_diabetes()
x = dataset.data
y = dataset.target
print(x[:5])
print(y[:10])
print(x.shape, y.shape)
print(np.max(x), np.min(x))
# print(dataset.feature_names)
# print(dataset.DESCR... |
#!/usr/bin/python
from plumbum import cli
import socket
import sys
import time
import struct
kMagicNumber = 0x53545259
kPing = 1
kGetStats = 2
kResetStats = 3
kCompress = 4
kHdrSize = 8
kStatSize = 9
class Application(cli.Application):
port = cli.SwitchAttr(["p"], int, default=4000)
host = cli.SwitchAttr(["h"... |
#coding:utf-8
import os
print(os.path.exists('AutoEncoder.py')) #判断当前路径下的文件是否存在 |
#/bin/env python3
# ==============================================================================
# Copyright (c) Moises Martinez by Fictizia. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a c... |
import tflearn
from tflearn.data_utils import to_categorical, pad_sequence
from tflearn.datasets import imdb
# IMBD Dataset loading
train, test, _ = imdb.load_data(path='imdb.pkl', n_words=10000, valid_portion=0.1)
trainX, trainY = train
testX, testY = test
# Data preprocessing
# Sequence padding
# Vectorize inputs ... |
import fasttext
from src.binaryfuncs import *
from src.multifuncs import *
def main():
trainingTextBin = import_text("training/EXIST2021_training.tsv")
format_text_bin(trainingTextBin)
crossValBinEN(5)
crossValBinES(5)
testBin()
trainingTextMulti = import_text("training/EXIST2021_train... |
import requests
from pydantic import validate_arguments, ValidationError
@validate_arguments
def GetBooks(q:str) -> object:
r = requests.get("https://www.googleapis.com/books/v1/volumes?q="+q)
return r.json()
|
from __future__ import division
from __future__ import print_function
from pathlib import Path
import gzip
import numpy as np
if __name__ == '__main__':
import data_dirs
else:
from tools import data_dirs
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
#from skimage import... |
# SOURCE: experiments/hras_nucleotide_equilibration.rst:16
from rasmodel.scenarios.default import model
# SOURCE: experiments/hras_nucleotide_equilibration.rst:20
import numpy as np
from matplotlib import pyplot as plt
from pysb.integrate import Solver
from pysb import *
# SOURCE: experiments/hras_nucleotide_equilib... |
# Generated by Django 2.0.1 on 2018-02-23 12:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ClubBoard', '0004_merge_20180221_1656'),
('ClubBoard', '0003_auto_20180219_1903'),
]
operations = [
]
|
from World import *
class AmoebaWorld(World):
"""AmoebaWorld is a microscope slide, with hash marks, where
Amoebas trace parametric equations.
"""
def __init__(self):
World.__init__(self)
self.title('AmoebaWorld')
self.ca_width = 400 # canvas width and height
... |
from orun.http import HttpResponse
from orun.apps import apps
from orun.db import models
class Http(models.Model):
@classmethod
def get_attachment(cls, attachment_id):
obj = apps['content.attachment'].objects.get(pk=attachment_id)
headers = None
res = HttpResponse(obj.content, content_... |
# coding: utf-8
"""
把蓝色当成1、白色当成2、红色当成3
i代表1的代表从左到右的位置
k代表3从右到左的位置
"""
def three_flag(x):
i = 0
j = 0
k = len(x) - 1
while j <= k:
if x[j] == 1:
if i != j:
x[i], x[j] = x[j], x[i]
i += 1
j += 1
elif x[j] == 3:
x[k], x[j] =... |
# https://www.reddit.com/r/dailyprogrammer/comments/5aemnn/20161031_challenge_290_easy_kaprekar_numbers/
# WEIRD ERROR: ValueError: invalid literal for int() with base 10: ''
import math
def kaprekarNumbers(start, end):
for i in range(start, end+1):
num = int(math.pow(i, 2))
numList = [int(num) fo... |
#!/usr/bin/python
class Fred:
def __init__(self,
name=None,
a="default name",
UUID = None
):
self.name = name
self.a = a
self.UUID = UUID
def PrintShit(self):
print ("I am a wibble")
def UUIDdefined (self):
... |
# main window (основное окно)
from tkinter import *
import requests
from tkcalendar import *
root = Tk()
root.geometry('400x250')
root.title('Calendar + weather')
def tell_weather():
url = 'http://wttr.in/?0T'
response = requests.get(url)
print(response.text)
# define the window's appearance (определи... |
from utils.urls import github_URL
import requests
from bs4 import BeautifulSoup
from spiders.base import Spider
from utils.headers import HEADERS
from models.HotItem import HotItem
from utils.mongo import hot_collection
from utils.cates import types
class GithubSpider(Spider):
def __init__(self, name='github'):
... |
# !/usr/bin/python
"""
-----------------------------------------------
Bardel Attribute Assignment
Written By: Colton Fetters
Version: 1.0
First release: 11/09/2017
-----------------------------------------------
"""
# Import module
import os
import json
import maya.cmds as cmds
# Studio module
import bd_... |
from django.db import models
from django.contrib.auth.models import User
from investigator.models import Investigator
from case.models import Case
class StatusUpdate(models.Model):
status = models.CharField(max_length=40)
timestamp = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
... |
print('안녕하세요? 여러분\n저는 파이썬을 무척 좋아합니다.\n9*8은 ', 9*8, " 입니다.\n안녕히 계세요.")
|
# realize a function
def test(a,b,func):
result = func(a,b)
print(result)
func_new = input("please input a funciton:")
print type(func_new)
# func_new = eval(func_new)
test(2,3,func_new)
|
import torch
from torch import nn
class GRUGate(nn.Module):
def __init__(self, d_model):
super(GRUGate, self).__init__()
self.Wr = nn.Linear(d_model, d_model, bias=False)
self.Ur = nn.Linear(d_model, d_model, bias=False)
self.Wz = nn.Linear(d_model, d_model, bias=False)
sel... |
import torch
# data
x_data = torch.tensor([1.0, 2.0, 3.0])
y_data = torch.tensor([1.0, 3.0, 5.0])
# initialize
a, b = torch.tensor([0.0]), torch.tensor([0.0])
lr = 0.1
for epoch in range(100):
# forward
predict = a * x_data + b # shape : (3)
# compute loss
loss = torch.sum((predict - y_data) ** 2) /... |
from django.test import TestCase
from Apps.Estudiante.models import Estudiante
from Apps.Estudiante.views import cargarTareasdeEstudiante
from Apps.Tarea.models import Tarea
from Apps.Curso.models import Curso
from Apps.Grupo.models import Grupo
from Apps.Grado.models import Grado
from Apps.Tema.models import Tema
from... |
import os
import argparse
import datetime
import re
import numpy as np
import pandas as pd
import geopandas as gpd
import rasterio
import rioxarray
import shapely
import pykrige.kriging_tools as kt
import struct
import dask.array as da
import multiprocessing
from osgeo import ogr, osr, gdal
from rasterio.crs import... |
from .base_setup import BaseSetup
from .categorical_image_flow_setup import CategoricalImageFlowSetup
|
import day4
import unittest
class Day2Tests(unittest.TestCase):
def test_True(self):
self.assertTrue(True)
def test_Day4Example(self):
room = day4.Room('aaaaa-bbb-z-y-x-123[abxyz]')
self.assertTrue(room.validate())
def test_Day4Example_2(self):
room = day4.Room('a-b-c-d-e... |
from colosseum.games import GameTracker
class GTNTracker(GameTracker):
def __init__(self, n_players:int, upper:int, lower:int=0, playerid:int=-1):
super().__init__(n_players)
"""
params:
n_players:int - Number of players
upper:int - Exclusive upper bound of the secret number
lower:int=0 - Inclusive low... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 10 12:54:44 2018
@author: Yadnyesh
"""
import pandas as pd
import numpy as np
import collections
import matplotlib.pyplot as plt
df_1 = pd.read_csv('F:/ZS/data/train.csv')
df_2 = pd.read_csv('F:/ZS/data/artists.csv')
df_3 = pd.read_csv('F:/ZS/data/test.csv')
# Count ... |
# logging.py
# author: IST411 Group 2
# 9/8/2016
from cookielib import logger
import json
# import logging
#
# logging.basicConfig(filename='myapp.log')
# # create logger
# logger = logging.getLogger('example')
# logger.setLevel(logging.DEBUG)
#
# # create console handler and set level to debug
# ch = logging.Stream... |
# Initialize a Tic-Tac-Toe Board
board = ["-","-","-",
"-","-","-",
"-","-","-"]
# Set a bolean to check win
check_win = False
#Save inputs
save_inputs = []
# Set the counter to take turn
count = 0
# Make the board with values
def display_board():
print(board[0] + "|" + board[1]+ "|" + board[2... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Dependencies: requests, absl-py, lxml
import json
import requests
import csv
import re
from lxml import etree
from absl import app, flags, logging
from datetime import datetime, date
from time import time
FLAGS = flags.FLAGS
flags.DEFINE_bool('debug', False, 'Debug mode... |
numero = int(input("Digite um valor: "))
contador = 1
total = 0
while contador <= numero:
if numero % contador == 0:
total = total + 1
contador += 1
if total == 2:
print("Ele é primo")
else:
print("Ele não é primo.")
|
import sys, csv
f = sys.argv[1]
write = open(f+'replaced.csv', 'w')
with open(f, 'r') as read:
for line in read:
line = line.replace(';',',').replace('\t', '').replace('\0','')
write.write(line)
read.close()
write.close() |
#-----------
# Usage:
# python run_montyhall.py (change_door= y|n) (tries= 1~...)
#-----------
import sys
import os
import random
import subprocess
# which door will be chosen
target = random.randint(0,2)
# whether to change door everytime (argv = 'y') or not
changeDoor = sys.argv[1]
# number of tries
numTries = int... |
from database.db_objects import User, Teacher
import gitlab
def gitlab_server_connection(username):
current_user = User.query.filter(User.username == username).first()
current_teacher = Teacher.query.filter(Teacher.user_id == current_user.id).first()
gitlab_key = current_teacher.gitlab_key
# print("cl... |
from flask import Flask, jsonify, request
from flask_cors import CORS
import random
import string
def get_random_string(length):
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(length))
return result_str
app = Flask(__name__)
CORS(app)
def makeClass(id):
... |
import cv2 # библиотека opencv
import numpy # работа с массивамиpip3 install paho-mqtt
import paho.mqtt.client as mqtt
import math
handle2 = open(str(input())+'.txt','w')
cap = cv2.VideoCapture(2) # читать видео поток
handle = open("blue.txt", "r")
h_down_g = int(handle.readline())
s_down_g = int(handle.readline(... |
from django.contrib import admin
from .models import ClickCount, WeekCount
class ClickCountAdmin(admin.ModelAdmin):
list_display = ('linkid', 'weikefu','mobile', 'user_num', 'valid_num',
'click_num','date', 'write_time', 'username')
list_display_links = ['linkid', 'username']
list_... |
# dataframe, numpy
import pandas as pd
import numpy as np
# Scaler
from sklearn.preprocessing import MinMaxScaler
# Model, LSTM
from keras.models import Sequential
from keras.layers import Dense, LSTM
# graph
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
# downloader file
import urllib.reque... |
import sys, os, shutil
from datetime import datetime as dt
from reorg import page
from reorg import crawling as cr
def adjust_target_dir_for_page(dir_target):
"""From path to directory target as if for section"""
basename = os.path.basename(dir_target)
return dir_target.replace(basename, "")
def whats_d... |
# ###리스트
# 리스트는 데이터의 목록을 다루는 자료형
# []대괄호로 명명한다
# 리스트 안에는 어떠한 자료형도 포함시킬수 있음 C는 같은 자료형만 가능
# 변수가 많아지면 관리해야할 사항이 많아지고 실수할 확률이 높아짐
# 리스트는 연속적으로 되있어서 데이터 가져오기 편함
# 리스트를 가져올때는 인덱스를 사용 0번부터
# ls = [500, 200, 300, 400]
# Sum = 0
# print("ls:", ls)
# print("ls[0]:", ls[0])
# print("ls[1]:", ls[1])
# print("ls[2]:", ls[2])
# ... |
# -*- coding:utf-8 -*-
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
import time
coef_angular_positivo = []
coef_angular_negativo = []
coef_linear_positivo = []
coef_linear_negativo = []
mediana_x = 0
mediana_y = 0
def ponto_fuga(frame):
lista_xi = []
lista_yi = []
x_ponto_fu... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from sklearn.model_selection import train... |
from rcnn_create_model import *
# from rcnn_feature_stats import *
from rcnn_feature import *
from rcnn_load_model import *
import numpy as np
import caffe
from datasets.factory import get_imdb
from sklearn.linear_model import LogisticRegression
import theanets
import climate
def rcnn_train(imdb):
use_gpu = False... |
#import lxml.etree as ET
import xml.etree.ElementTree as ET
import urllib
import sys
if __name__ == "__main__":
for i in sys.argv[1:]:
t = ET.parse(i).getroot()
label = '"<li>'
url = t.attrib.get('url')
if url:
label += "<a href='" + urllib.quote_plus(urllib.unquote(url)... |
from Record import Record
import mysql.connector
from mysql.connector import errorcode
'''
RecordsManager accesses the underlying MySQL database and transforms that data into
Python objects that the script can work with. It requires mysql.connector to be installed
on the machine you run the script. This can be found he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.