text stringlengths 8 6.05M |
|---|
from rest_framework import authentication
class BasicAuthentication(authentication.BasicAuthentication):
def authenticate_credentials(self, userid, password, request=None):
if "@" in userid:
userid, domain = userid.split("@")
print(userid, domain)
return super().authenticat... |
d = {'key': [1,2,3]}
x = d['key']
x.append(1)
print(d) |
import requests
from bs4 import BeautifulSoup
url = 'http://servicos2.sjc.sp.gov.br/servicos/horario-e-itinerario.aspx?acao=p&opcao=1&txt='
request = requests.get(url)
soup = BeautifulSoup(request.text, 'lxml')
lista_all = soup.find_all('table', class_='textosm')
url = 'http://servicos2.sjc.sp.gov.br'
for lista_t... |
import pytest
import pdb
from fhireval.test_suite.crud import prep_server
test_id = f"{'2.2.11':<10} - CRUD Document Reference"
test_weight = 2
# Cache the ID to simplify calls made after crate
example_document_ref_id = None
def test_create_research_document_ref(host, prep_server):
global example_document_ref... |
#!/usr/bin/env python3
import base64
from aws_cdk import (
aws_autoscaling as autoscaling,
aws_ec2 as ec2,
aws_elasticloadbalancingv2 as elbv2,
core,
)
"""
https://cloudacademy.com/blog/elastic-load-balancers-ec2-auto-scaling-to-support-aws-workloads/
"""
class LoadBalancerStack(core.Stack):
def ... |
import unittest
from fibonacciLists import nth_fib_lists
class TestsFibonacciLists(unittest.TestCase):
def test_nth_fib_lists_first(self):
self.assertEqual([1], nth_fib_lists([1], [2], 1))
def test_nth_fib_lists_second(self):
self.assertEqual([2], nth_fib_lists([1], [2], 2))
def test_n... |
import sys
import socket
import itertools
import json
import string
host = sys.argv[1]
port = int(sys.argv[2])
common_logins = [
login.rstrip() for login in
list(open("F:/code/Password Hacker/Password Hacker/task/hacking/logins.txt").readlines())]
characters = string.ascii_lowercase + string.ascii_uppercase ... |
import csv
import matplotlib.pyplot as plt
from statistics import mean
import numpy as np
def count_lap():
count_1, count_2, count_3, count_4, count_5 = [], [], [], [],[]
count_6, count_7, count_8, count_9 = [],[],[],[]
dyn_1, dyn_2, dyn_3, dyn_4, dyn_5, = [],[],[],[],[]
dyn_6, dyn_7, dyn_8, dyn_9 = [... |
import cv2
from numpy import *
import os
path = "/Users/myazdaniUCSD/Documents/Ten_Thousand_Pairs/found_pairs_source/"
write_path = '/Users/myazdaniUCSD/Documents/Ten_Thousand_Pairs/videos/'
image_paths = [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
codec = cv2.cv.CV_FOURCC('m', 'p', '4... |
#!/usr/bin/env python3
import os, subprocess, shutil, re
from flask import request, Blueprint, current_app as app, abort
from werkzeug.utils import secure_filename
from .handle_keypoints import handle_keypoints
execute = Blueprint('execute', __name__)
@execute.route('/execute', methods=['GET'])
def sift_cli():
# ... |
# @generated by generate_proto_mypy_stubs.py. Do not edit!
import sys
from google.protobuf.descriptor import (
Descriptor as google___protobuf___descriptor___Descriptor,
EnumDescriptor as google___protobuf___descriptor___EnumDescriptor,
FileDescriptor as google___protobuf___descriptor___FileDescriptor,
)
... |
'''
@title Text Adventure: Room Class
@author Carlos Barcelos
@date 06 January 2019
The room class with member veriables and functions.
'''
import src.stdlib as std # Import standard libraries
from src.Item import Item # Work with Item objects
from src.Enemy import Enemy # Work with Ite... |
# coding=utf-8
# 一个一个读取
# select load_file('E:\flag.txt')
# select ascii(mid((select load_file('E:\flag.txt')),1,1));
# 直接注入表读取
# create table abc(cmd text);
# insert into abc(cmd) values (load_file('E:\flag.txt'));
# select * from abc;
import jwt
import requests
import re
requests.packages.urllib3.disable_warnings()
... |
from adapters.generic.motion_sensor import MotionSensorAdapter
from adapters.generic.temp_hum_sensor import TemperatureHumiditySensorAdapter
sonoff_adapters = {
'SNZB-02': TemperatureHumiditySensorAdapter, # SONOFF Temperature and humidity sensor
'SNZB-03': MotionSensorAdapter, # SONOFF Mot... |
# 함수명: sumEven1, 매개변수: 가변형, 리턴값: 1개
# 기능: 아규먼트가 몇 개가 전달되든 처리해야 한다.
# 아규먼트는 1 이상의 숫자만 온다고 정한다.
# 전달된 아규먼트들에서 짝수에 해당하는 숫자들만 합을 계산해서 리턴한다.
# 전달된 아규먼트들 중에서 짝수가 없으면 0을 리턴한다.
# 아규먼트가 전달되지 않으면 -1을 리턴한다.
def sumEven1(*ints) :
sum = 0
if not ints :
return -1
else :
for num in ... |
def monthlyactivity(interest, principal, apr, limit, totalprin):
print "enter day number from this month and transactions on that day, in order. Enter day as 31 to end simulation for this month,"
day = 0
prevday = 0
while day<31:
day = int(input("enter day number: "))
if day == 31:
... |
#!/usr/bin/env python
# Funtion:
# Filename:
import logging
logging.basicConfig(filename='123.log', level=logging.INFO)
# logging 的5个级别
logging.debug('test debug')
logging.info('test info')
logging.warning('test warning')
logging.error('test error')
logging.critical('test critical') |
import MySQLdb
import MySQLdb.cursors
import traceback
def user_add():
with open('storage/email', encoding='utf-8') as f:
email_list = [email.strip() for email in f.readlines()]
with open('storage/name', encoding='utf-8') as f1:
name_list = [username.strip() for username in f1.readlines()]
... |
from mock_data import mock_data
me = {
"firstname":"Shane",
"lastname":"Dixon",
"email":"shanedixon13@gmail.com",
"age":25,
"hobbies":[],
"address":{
"street":"Bradley Ln",
"city":"Lonoke"
}
}
print(me["firstname"]+" "+me["lastname"])
print(me["address... |
import turtle
window = turtle.Screen()
window.bgcolor("red")
t1=turtle.Turtle()
t1.shape("turtle")
t1.color("yellow")
t1.speed(10)
def draw_square(t1):
for i in range(1,5):
t1.forward(100)
t1.right(90)
for i in range(1,36):
draw_square(t1)
t1.right(20)
w... |
#024: Longest Increasing Subsequence
#http://rosalind.info/problems/lgis/
#Given: A positive integer n<=10000 followed by a permutation p of length n.
n = 5
p = [5, 1, 4, 2, 3]
#If parsing from file:
f = open('rosalind_lgis.txt', 'r')
contents = f.read().rstrip()
f.close()
lines = contents.split('\n')
n = int(lines... |
import ctypes
import numpy
from simphony.core.cuba import CUBA
from simphony.core.keywords import KEYWORDS
from simphony.core.data_container import DataContainer
from simlammps.common.atom_style_description import get_all_attributes
class ParticleDataCache(object):
""" Class handles particle-related data
C... |
#!/usr/bin/env python3
import argparse
import os
import random
import sys
import threading
from itertools import count
from string import ascii_letters, digits
from colorama import Fore
from kahoot import client
def getargs():
parser = argparse.ArgumentParser(description='Kahoot Flooder Bot - Created by Music_D... |
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# 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.o... |
# coding:utf-8
__author__ = 'Baxter'
def insert():
pass
def update():
pass
def delte():
pass
def select():
pass |
# Generated by Django 2.1.7 on 2019-03-30 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20190330_1402'),
]
operations = [
migrations.AlterField(
model_name='partnermodel',
name='descript... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return None
ans = 1
prev = nums[ans-1]
while ans != len(nums):
if nums[ans] == prev:
prev = nums... |
# coding = utf-8
from selenium import webdriver |
class Solution:
def simplifyPath(self, path: str) -> str:
segments = path.split("/")
stack = []
for segment in segments[1:]:
if segment in ("", "."):
continue
elif segment == "..":
if len(stack) > 0:
stack.pop(-1)
... |
class Read:
"""
An accessor to read a global resource
"""
def __init__(self, class_name):
self.class_name = class_name
class Write:
"""
An accessor to read/write a global resource
"""
def __init__(self, class_name):
self.class_name = class_name
class Entities:
"""... |
N = 9 # size of the rows and columns
# this is the main function. First it will check if the number is zero or not
# then it will validate the number
# finally it returns true or false
def solve(board):
zero = is_empty(board)
if not zero:
return True
else:
row, col = zero
... |
def findCelebrity(self, n):
x = 0
for i in xrange(n):
if knows(x, i): x = i
if any(knows(x, i) for i in xrange(x)):
return -1
if any(not knows(i, x) for i in xrange(n)):
return -1
return x |
from django.db import models
from datetime import datetime
# Create your models here.
class Realtor(models.Model):
name = models.CharField(max_length=200)
photo = models.ImageField(upload_to='photos/%Y/%m/%d')
description = models.TextField(blank=True) # by putting blank True we will not get error if we do ... |
import cv2
from threading import Thread
# 多线程,高效读视频
class WebcamVideoStream:
def __init__(self, src, width, height):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)
... |
from webdev import get_posts
from save import save_to_csv
posts = get_posts()
save_to_csv(posts) |
from .models import Reply, Thread
from django import forms
class CommentForm(forms.ModelForm):
"""
Form to add comment to thread
"""
class Meta:
model = Reply
fields = ['body']
def __init__(self, *args, **kwargs):
"""
Labels removed from body field on comment form
... |
from rest_framework import serializers
from .models import Reclamacoes,Categoria
class reclamacoesSerializer(serializers.ModelSerializer):
class Meta:
model = Reclamacoes
fields = ('__all__')
class categoriaSerializer(serializers.ModelSerializer):
class Meta:
model = Categoria
... |
#!/usr/bin/env python
# Funtion:
# Filename:
class Dog(object):
def __init__(self,name, age):
self.name = name
self.age = age
self.__food = 'fish'
@property
def eat(self):
print('{0} is eating {1}'.format(self.name, self.__food))
@eat.setter
def eat(self, foo... |
#!/usr/bin/env python
__author__ = "Blaze Sanders"
__email__ = "blaze@robobev.com"
__company__ = "Robotic Beverage Technologies Inc"
__status__ = "Development"
__date__ = "Late Updated: 2018-04-02"
__doc__ = "Play predefine text using EMIC2 hardware or AWS Polly interface"
# Useful system jazz
import sys, ... |
import os
hapus = os.remove("wew.txt")
if True:
print "file dihapus"
|
"""SQLAlchemy core utility functionality
Functionality for faster bulk inserts without using the ORM.
More info: https://docs.sqlalchemy.org/en/latest/faq/performance.html
"""
import logging
import json
import scipy
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.sql impor... |
import numpy as np
import pandas as pd
import math
import os
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import KFold
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklear... |
# -*- coding: utf-8 -*-
{
'name': "construction",
'summary': """
Construction Management""",
'description': """
Construction Management Build By Raqmi
""",
'author': "Raqmi",
'website': "http://www.raqmisoultions.com",
'category': 'Construction',
'version': '0.1',
... |
n = input("Введите число\n")
number = 1
while int(n) > number:
print(number)
number = number*2 |
from sys import stdin
input = stdin.readline
'''
1. dp_t를 적당히 잡고
2. dp_t 초기값을 잡고
3. 규칙성을 찾아서 쭈루루룩
'''
n = int(input().rstrip())
days_costs = [tuple(map(int, input().rstrip().split())) for _ in range(n)]
dp_t = [0]*(n+1) # 0~n-1로 적용할 예정이지만, 마지막날을 위해 한칸 더 선언
for i in range(n-1, -1, -1): # 거꾸로 계산
day, cost = day... |
nums = [3,2,4]
target = 6
ret =[]
l = nums.__len__()
for i in range(0, l):
for j in range(i+1, l):
if (nums[i]+nums[j]) == target:
ret.append(i)
ret.append(j)
break
print ret
|
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc, precision_score, recall_score, f1_score
from sklearn import grid_search, svm... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#from .coco import COCODataset
#from .voc import PascalVOCDataset
from .concat_dataset import ConcatDataset
from .giro import giro
__all__ = ["giro","ConcatDataset"] # "COCODataset", "ConcatDataset", "PascalVOCDataset",
|
import requests
from time import time, sleep
class ThingSpeakService:
def __init__(self, channel, api_key):
self.url = 'https://api.thingspeak.com/channels/'
self.channel = channel
self.api_key = api_key
self.co2_field = 'field1'
self.temp_field = 'field2'
self.hum_... |
# Copyright(c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""FileUpload class.
Represents a file upload button.
"""
from traitlets import (
observe, default, Unicode, Dict, List, Int, Bool, Bytes, CaselessStrEnum
)
from .widget_description import DescriptionWidget
from ... |
def main(n, m):
print('Yes' if n == m else 'No')
if __name__ == '__main__':
params = input()
params = params.split()
n = int(params[0])
m = int(params[1])
main(n, m)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Trusted Sleep Monitor Bot
This bot monitors group members' sleep time using online status.
Threads:
* tg-cli
* Event: set online state
* Telegram API polling
* /status - List sleeping status
* /average - List statistics about sleep time
* /help - About the b... |
import requests # pip install requests
from bs4 import BeautifulSoup # pip install beautifulsoup4
import urllib.request
from urllib.error import HTTPError
from urllib.error import URLError
from datetime import datetime
from socket import timeout
from requests.exceptions import ConnectionError
from selenium imp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from django.views.generic.list import ListView
from form import RegistroForms, ChequeoForms
from models import Becarios, Registro
import datetime
# Create your views here.
def base(request):
return render(r... |
"""
Jiun Kim
M6 Poetry Slam
This is Poetry Maker Punchline King made by Jiun Kim.
The libraries used are pyrhyme which makes rhyme words and word files from the internet.
"""
from random import randint, randrange
import pyrhyme
class RandomWordGenerator:
"""
This class makes random noun, verb, adjective, a... |
import matplotlib.pyplot as plt
# input_values=[1,2,3,4,5]
# squares=[1,4,9,16,25]
# plt.plot(input_values,squares,linewidth=3)
# plt.title("Square Numbers",fontsize=18)
# plt.xlabel("Value",fontsize=15)
# plt.ylabel("Square of Value",fontsize=15)
# plt.tick_params(axis='both',labelsize=15)
#
# # plt.show()
#
# x_valu... |
import numpy as np
import csv
def transformToRNN(filename = 'tweeti.b.dist.parsed'):
outfile = 'trees/temp.txt'
if filename == 'data/b.train.preprocessed.utf8.parsed':
outfile = 'trees/train.txt'
elif filename == 'data/b.dev.preprocessed.utf8.parsed':
outfile = 'trees/dev.txt'
elif filename == 'data/b.test.pars... |
user = "postgres"
host = "172.22.240.1"
port = "5432"
db_model_name = "demo"
db_model_pswd = "1234" |
"""Segment pollen tubes."""
import os
import argparse
import warnings
import math
import logging
import numpy as np
import scipy.ndimage
from skimage.morphology import disk
import skimage.feature
from jicbioimage.core.image import Image
from jicbioimage.core.transform import transformation
from jicbioimage.core.util... |
'''
*******************************************************************************
Desc : A script used to parse/access Internal MemoryMap.
Note : N/A
History : 2010/07/15 Panda.Xiong Create
*******************************************************************************
'''
from ctypes import *
imp... |
import csv, sys
import boto3
column_headers = ["tag_channel", "resource_id", "service"]
column_index = {"tag_channel": None, "resource_id": None, "service": None}
service_names = {"AmazonEC2": "ec2", "AmazonS3": "s3api", "AmazonVPC": "ec2", "AWSLambda": "lambda", "AmazonApiGateway": "apigateway"}
found_heade... |
import requests
import json
class fanyi:
def __init__(self,keyword):
self.keyword = keyword
def result(self):
url = "https://fanyi.baidu.com/extendtrans"
# 设置提交数据
posData = {"query": self.keyword,
"from": "en",
"to": "zh"}
headers =... |
#!/usr/bin/env python2.7
# encoding: utf-8
"""
std_asymmetries.py
Created by Jakub Konka on 2012-05-31.
Copyright (c) 2012 University of Strathclyde. All rights reserved.
"""
from __future__ import division
import sys
import os
import math
import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplo... |
"""
LeetCode - Easy
"""
"""
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as sqrt.
Example 1:
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
Constraints:
1 <= num <= 2^31... |
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 appli... |
echo "hello world"
echo "learning"
|
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
import json
from time import sleep
from bs4 import BeautifulSou... |
import cv2
import random
import numpy as np
scale = 0.5
circles = []
counter = 0
counter2 = 0
point1 = []
point2 = []
myPoints = []
myColor = []
path = '/Users/fneut/Desktop/PP/QueryImages'
def mousePoints(event,x,y,flags,params):
global counter,point1,point2,counter2,circles,myColor
if event == cv2.EVENT_LB... |
H, W = map( int, input().split())
A = [ input() for _ in range(H)]
dp = [[0]*W for _ in range(H)]
dp[0][0] = 1
Q = 10**9+7
for i in range(H):
for j in range(W):
if not i == H-1:
if A[i+1][j] == ".":
dp[i+1][j] = (dp[i+1][j] + dp[i][j])%Q
if not j == W-1:
if A[... |
import pytest
import pdb
test_id = f"{'2.3.3':<10} - Profile Snapshot"
test_weight = 10
def test_profile_snapshot(host):
assert 0 == 1, "TODO - Write Test"
|
import os
import argparse
def parse_command():
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_dir',
type=str,
default=os.path.join(os.getenv('HOME'), 'data'),
help="""\
Where to download the speech training data to. Or where it is already saved.
""")
parser.ad... |
from typing import TypeVar
from ndb_adapter.ndb_download import DownloadHelper
from ndb_adapter.ndb_download import DownloadType
def _assign_numbers(dic: dict) -> dict:
"""Private function for assign numbers values to dictionary
:param dic: report dictionary
:type dic: dict
:return: report dictionary... |
import numpy as np
def compute_frr_far(data, data_class_labels, threshold):
false_rejected_list = []
false_accepted_list = []
for i in range(len(data)):
accepted = np.zeros_like(data[i])
accepted[data[i] > threshold] = 1
genuine_indexes = np.array(data_class_labels == data_class_la... |
"""
Estrutura:
while {condição}:
comandos
# opcional para interrupção
if condicao
break
É possível usar usar "else", que será executado uma vez
"""
# Exemplo equivalente a 'for c in range(1,10), porém irá printar tb o 10 por causa do "else":'
c = 1
while c < 10:
print(c)
... |
from collections import defaultdict
def onlyOneZero(grid):
zeroes = 0
for row in grid:
zeroes += row.count(0)
return zeroes == 1
def buildColorDict(n, grid):
M = defaultdict(int)
for row in grid:
for cell in row:
M[cell] += 1
return M
def buildShapeDict(n, gr... |
import os
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import requests
r=requests.get('http://www.xiachufang.com/')
soup=BeautifulSoup(r.text)
#print(soup)
#print(soup.select('img'))
img_list=[]
for img in soup.select('img'):
if img.has_attr('data-src'):
img_list.append(img.attrs['data... |
# Generated by Django 2.1.4 on 2019-01-04 20:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('speciality', '0010_auto_20190104_2001'),
('services', '0001_ini... |
from django.contrib import admin
from .models import Victim
# Register your models here.
admin.site.register(Victim) |
class Solution:
def reverse(self, x: int):
signe = [1,-1][x < 0]
x = x*signe
x = int(str(x)[::-1])
return x*signe*(x < 2**31)
examples = [123, -123, 120, 0]
for example in examples:
print(Solution().reverse(example)) |
a, b = map(int, input().split())
print(int((b-a)*(b-a-1)/2 - a))
|
class Node:
def __init__(self,data):
self.left = None
self.right = None
self.data = data
class BST:
def __init__(self):
self.root = None
def set_root(self,data):
self.root = Node(data)
def insert_node(self,data):
if self.root is None:
self.set... |
#!/usr/bin/env python
"""
Convert clustal alignment files to grishin for use in rosetta
Author: Ed van Bruggen <edvb@uw.edu>
"""
import sys
import argparse
from argparse import RawTextHelpFormatter
parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
parser.add_argument('--file... |
from time import sleep
from features.clock import Clock
from field import Field
from multiply import multiply
from painter import Led_Matrix_Painter, RGB_Field_Painter
from rainbow import rainbowcolors
class Rainbowclock(Clock):
def __init__(self, field_leds: Field, field_matrix: Field, rgb_field_painter: RGB_Fi... |
../_rostf.py |
# Generated by Django 2.2.3 on 2019-11-06 15:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0002_auto_20191106_0907'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='descripti... |
import sys
import os
path = str(sys.argv[0])
if os.path.exists(path):
tree = os.listdir(path)
print(tree)
else:
print("This path is not real! Try another path!")
|
import random
import datetime
from celery.task import PeriodicTask, task
from celery.schedules import crontab
from yoolotto.util.async import report_errors
from yoolotto.lottery.models import LotteryCountryDivision
class UpdateDraws(PeriodicTask):
run_every = datetime.timedelta(minutes=30)
@report_errors
... |
import socket
import threading
# class for creating servers
class Server:
def __init__(self):
self.SERVER = "127.0.0.1"
self.PORT = 8080
self.ADDR = (self.SERVER, self.PORT)
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind(self.ADDR)
de... |
class Site:
#init parameters: self, users site + section from IRC.
def __init__(self, siteInput, sectionInput):
self.siteInput = siteInput
self.sectionInput = sectionInput
self.retTargetSite()
#Function to return target RSS/XML file for parsing.
def retTargetSite(self):
... |
# from Geron, 14_recurrent_neural_networks
# Demonstrate an RNN with two time steps, hardcoded
import numpy as np
import tensorflow as tf
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(seed)
reset_graph()
n_inputs = 3
n_neurons = 5
X0 = tf.placeholder(tf... |
from PyQt4 import QtCore, QtGui
import sys, os
# Import the new defined class here.
from MainScreen import *
def _init():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
window.raise_()
app.exec_()
_init()
|
import numpy as np
from NumericalModeling.scripts.matrix_generator import *
import sys
def read_input_file(input_path):
f = open(input_path, "r")
f1 = f.readlines()
str1 = list(map(float, f1[0].split(' ')))
f = float(str1[1])
M = int(str1[1])
eps = float(str1[2])
G = []
for x in f1[1... |
import os
import subprocess
import sys
import shutil
import yaml
import colorama
from colorama import Style, Fore, Back
import grading_module as gm
with open("base_config.yaml", 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
dir = cfg['dir']
methods = cfg['methods']
output_only = cfg['output_o... |
import groupy
for bot in groupy.Bot.list():
bot.destroy() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#================================= HEADER ====================================
import logging
import telegram
from telegram.error import NetworkError, Unauthorized
from time import sleep
#-------------------------------------------------------------------------------... |
import sys
import math
n, m = map(int, sys.stdin.readline().split(' '))
l = [0]*n
for i in range(n):
l[i] = int(sys.stdin.readline())
lb = min(l)*m//n # lower bound
ub = max(l)*math.ceil(m/n) # upper bound
mv = (lb+ub)//2
while lb<ub:
c = 0 # the number of people
for i in range(n):
... |
from scipy.spatial import distance as scipy_distance
def print_content_summary(centers, coordinates, labels, tweets):
for i in range(len(centers)):
print("\n======================")
print('Cluster {} ({} tweets) is approximated by:'.format(i, list(labels).count(i)))
distances = scipy_dista... |
#!env python3
# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
n = 10000
a = np.random.normal(40, 30, size=n)
b = np.random.normal(60, 20, size=n)
c = np.random.normal(80, 10, size=n)
df = pd.DataFrame({
... |
# Generated by Django 2.1.4 on 2018-12-28 21:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('speciality', '0003_auto_20181228_2137'),
]
operations = [
migrations.AlterField(
model_name='sp... |
from flask import request, session
import flask_babel
from speaklater import make_lazy_string
from babel import Locale
DEFAULT_LOCALE = Locale('en')
TRANSLATIONS = [Locale('es')]
VALID_LOCALES = [DEFAULT_LOCALE] + TRANSLATIONS
VALID_LOCALE_CODES = [str(l) for l in VALID_LOCALES]
def configure_app(app):
def lazy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.