text stringlengths 38 1.54M |
|---|
#Ethan Brinkman
#Homework 25: 1, 2, 3
#Due 5/8/2019
#==========Number 1==========
print('Number 1:\n')
def revList(list1):
if len(list1) == 0:
#Checks for when the list is done being reversed
return list1
else:
print('Calling for a recursion with the current list at',list1)
ret... |
class IterableStructure:
def __init__(self):
self._entities = []
self._index = -1
def __iter__(self):
return iter(self._entities)
def __next__(self):
if self._index > len(self._entities) - 1:
raise StopIteration
else:
self._index += 1
... |
"""
A student has joined a course costing as per the given table. If the fee is paid via card, an additional service charge of Rs. 200/- is added
but if payment is made through e-wallet, a discount of 5% is given for the payment. Use this reference table
_____
python : 15000 |
java : 8000 |
ruby : 10000 |
r... |
import turtle
t=turtle.Pen()
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(120)
t.forward(200)
t.left(120)
t.forward(200)
t.left(120)
t.forward(300)
t.left(120)
t.forward(300)
t.left(120)... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 31 18:56:37 2016
@author: jean
"""
from truc import Truc
Truc().travailler()
if __name__ == '__main__' :
print("main")
|
'''
Filer Guidelines:
RTS: https://eur-lex.europa.eu/legal-content/EN/TXT/?qid=1563538104990&uri=CELEX:32019R0815
ESEF Filer Manual https://www.esma.europa.eu/sites/default/files/library/esma32-60-254_esef_reporting_manual.pdf
Taxonomy Architecture:
Taxonomy package expected to be installed:
See COPYRIGHT.md for... |
# -*- coding: UTF-8 -*-
import requests
import pandas as pd
import configparser
from datetime import date
from openpyxl import Workbook, load_workbook
import os
import sys
import argparse
from random import randint
from time import sleep
API_URL = "https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=%s... |
from app import db
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy import (
Boolean,
Column,
Integer,
Text,
String,
)
class Matches(db.Model):
__tablename__ = "matches"
team_id = Column(Integer, primary_key=True, nullable=False)
mentor_id = Column(Integer)
team_em... |
# https://codeforces.com/contest/133/problem/A
def single_integer():
return int(input())
def multi_integer():
return map(int, input().split())
def string():
return input()
def multi_string():
return input().split()
program = set('HQ9')
s = string()
for i in s:
if i in program:
pri... |
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import Ad
from .forms import AdAdminForm
@admin.register(Ad)
class AdAdmin(SimpleHistoryAdmin):
search_fields = ('campaign', 'episode__show', 'get_date')
... |
import socket
import sys
def Scan_Ports(host):
for _ in xrange(2**16):
try:
result = 1
connection = socket.socket()
connection.settimeout(0.01)
result = connection.connect_ex((host, _))
connection.close()
try:
service_n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
import copy
baseLine = {
"Complexity": 0.0,
"Minutes": 15120.0,
}
auth = ("", "")
boardId = "522"
base = {
"fields": {
"project":
{
"key": "FRGDXL"
},
#"customfield_10301": "1261", #sprint to create the i... |
import os, time
import math
from pyspark.sql import SQLContext
from pyspark import SparkContext
from pyspark import SparkFiles
mainPath=os.path.dirname(__file__)
sc = SparkContext("local", "Simple App")
sqlContext = SQLContext(sc)
start_time = time.time()
people = sqlContext.read.json(os.path.join(mainPath,"rttest2.... |
from PyQt5.QtWidgets import QLineEdit
class QLineEval(QLineEdit):
"""
QLineEdit that evaluates Python expressions.
"""
def __init__(self, parent=None):
super(QLineEval, self).__init__(parent)
self.returnPressed.connect(self.eval)
def eval(self):
"""
Evaluate self.... |
'''
@Author: xiaomin
@Date: 2020-04-26 15:42:52
@LastEditTime: 2020-04-30 15:25:12
@LastEditors: xiaomin
@Description:
@FilePath: \ioT-uat\Common\comm.py
'''
import os
import sys
sys.path.append("..")
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
import u... |
"""
Author - Devesh
Problem - Find Point
"""
n = int(input())
while n > 0:
px, py, qx, qy = map(int, input().split())
#qx, qy = input().split()
print(2*qx-px, 2*qy-py)
n -= 1
|
import math as m
import numpy as np
import random as r
def cpdf(sigmas_from_bound):
return 0.5 * (1 + m.erf(sigmas_from_bound / m.sqrt(2)))
def generate_gaussian(nn_n_1, nn_n_2, n, n_more, n_less, available):
if nn_n_1:
if n == n_less:
lower_bound = n_less
else:
lowe... |
import pandas as pd
import re
import requests
import time
import matplotlib.pyplot as plt # noqa
df = pd.read_csv('lessons/shared-resources/crimedata.csv', index_col='id')
del(df['Unnamed: 0'])
# del(df['Unnamed: 0'])
# print(df.head())
h = '3376+NE+Hoyt+St.,+Portland,+OR'
def geocode_osm(address, polygon=0):
... |
from os.path import dirname, join
import networkx as nx
MESH_TREE_FILE = join(dirname(__file__), 'mtrees2017.bin')
def create_edgelist(numbers):
edgelist = set()
for number in numbers:
indices = [1]
for i, x in enumerate(number):
if x == '.':
indices.append(i)
... |
import logging
from flask import url_for
def test_app(client, config):
res = client.get('/')
logging.info(config)
assert res.status_code == 200
|
# Generated by Django 2.0.4 on 2018-05-04 02:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('internal', '0007_remove_uploadrecord_user'),
]
operations = [
migrations.AlterField(
model_name='stuinfo',
name='nam... |
def non_exception():
pass
def exception():
raise FileExistsError
def try_catch_else_finally():
try:
try:
non_exception()
exception()
#exception()
except ZeroDivisionError as cx:
args = cx.args
print(args)
except:
... |
from question import Question
from choice_question import ChoiceQuestion
class Exam:
"""
Class for the Exam
Föll
-------
__init__()
Creates .__score and .__question_list
.__score keeps the current score
.__question_list keeps the questions in order they were createad
ad... |
from setuptools import find_packages, setup
setup(
name='simloss',
packages=find_packages(),
version='0.1.0',
description='SimLoss.',
author='Konstantin Kobs',
license='',
)
|
import os
# Imports from other modules
from .renderers import ImageRenderer
from .serializers import userDataSerializer
from .permissions import IsOwnerProfileOrReadOnly
from accounts.models import UserData, FaceData
from accounts.encoding import encoding_recognise
# Imports from installed modules
from rest... |
import torch
import time
import os
import datetime
import random
import numpy as np
import argparse
from models import build_model_from_name
from models.loss import build_criterion
from data.fastmri import build_dataset
from torch.utils.data import DataLoader, DistributedSampler
from pathlib import Path
from engine i... |
class ClassObject(object):
def __init__(self, index, obj):
self.index = index
self.object = obj
class SeriesRecord(object):
def __init__(self, timestamp, index, metadata):
self.timestamp = timestamp
self.index = index
self.metadata = metadata
def __eq__(self, other... |
import pytest
from bs4 import BeautifulSoup
from django import forms
from django.template import Context, Template
from directory_components import fields
from directory_components.templatetags import directory_components
REQUIRED_MESSAGE = fields.PaddedCharField.default_error_messages['required']
class PaddedTest... |
# -*- coding: utf-8 -*-
# Copyright 2018 Pascual de Juan 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 req... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
from setuptools import setup
setup(
name='vrouter',
version='0.1dev',
packages=['vrouter',
'vrouter.vrouter',
'vrouter.vrouter.cpuinfo',
'vrouter.vrouter.process_info',
'vrouter.vro... |
##3. Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
##Input Format:
##The first line contains n. The second line contains an array A[] of n integers separated by a space.
... |
import json
from easy_kafka.kafka_consumer import EasyKafkaConsumer
def start_consumer():
kafka_consumer = EasyKafkaConsumer('../conf/conf.yml')
print('consumer iterator started')
for record in kafka_consumer:
print('record', record.value)
print('json', json.loads(record.value))
if __na... |
from django.db.models.query import RawQuerySet
import user
from django.shortcuts import redirect, render
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm,UserUpdateForm,ProfileUpdateForm
from django.contrib import messages
def register(request):
form = CreateUserForm()
... |
import cv
import sys
samples_dir = '../../samples'
file = sys.argv[1]
frameskip = 1 + int(sys.argv[2])
capture = cv.CaptureFromFile(file)
n_frames = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT)
print("File: %s, frames: %d" % (file, n_frames))
for k in range(n_frames):
try:
img = cv.QueryFr... |
############################################################################
# tools/gdb/thread.py
#
# 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
# A... |
# bs包把html按照节点的层级关系转换为树形文档,然后解析,简单明了.
# 安装 beautifulsoup4 普通版本只能用于py2
from bs4 import BeautifulSoup
html = """
<html>
<body>
<a id="aaa" href="http://www.baidu.com"name="aaa" class="aaa">百度一下</a>
<a href='http://www.baidu.com'>百度一下2</a>
<h1>
多捞哦
</h1>
</body>
</html>
"""
# 实例化bs 传入参数待解析html内容和解析器.
# html.parser pyth... |
from models.cnn import MNIST_CNN
from models.simple_AE import SimpleAE
from data.data_loaders import get_MNIST_training_set, get_MNIST_test_set
import torch
from torch.utils.data import TensorDataset
def train(epoch: int) -> None:
coded_mnist = torch.load("../data/mnist/codes_simple_ae.pt")
coded_mnist_labels... |
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from .models import User
def index(request):
return render(request, 'login_app/index.html')
def register(request):
#validation
#check to see what response was
#if respose good t... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
__author__ = "Zeinab Abbasimazar -> https://github.com/zeinababbasi"
class SmsgatewayConfig(AppConfig):
name = 'soapwebservice'
|
#!/usr/bin/env python
#
import sys, cpp, kernel, glob, os, re, getopt, clean_header, subprocess
from defaults import *
from utils import *
def usage():
print """\
usage: %(progname)s [kernel-original-path] [kernel-modified-path]
this program is used to update all the auto-generated clean headers
used by... |
#!/usr/bin/env python
import re
from .utils import ToytreeError
class NodeAssist:
"""
Given a search query (list of names, wildcard or regex) a node or list of
names can be retrieved under a set of pre-built functions.
"""
def __init__(self, ttree, names, wildcard, regex):
# attribute... |
# -*- coding: utf-8 -*-
"""
The :mod:`quakemigrate.lut` module handles the definition and generation of the
traveltime lookup tables used in QuakeMigrate.
:copyright:
2020 - 2021, QuakeMigrate developers.
:license:
GNU General Public License, Version 3
(https://www.gnu.org/licenses/gpl-3.0.html)
"""
impo... |
#
# This is a queue that takes functions that return a deferred and runs N in parallel
from twisted.internet import defer
from twisted.python import log
from igs.utils import dependency
class DeferWorkQueue(dependency.Dependable):
"""
By default serializes work
"""
def __init__(self, parallel=1)... |
wangshuai = {'age': 20, 'city':"beijing"}
print(wangshuai['age'])
wangshuai['sex']= 'male'
print(wangshuai)
wangshuai['age'] = 25
print(wangshuai)
#del wangshuai['age']
#print(wangshuai)
for k,v in wangshuai.items() :
print(k + "=======>" + str(v) + "\n")
users = {
'wangshuai': {'age': 25, 'sex': 'male', 'la... |
#改
def child(master, slave):
global test
test=1
print (111,test)
os.close(master) #关闭不需要的主设备,因为主设备是给父进程传送指令到子进程的
os.dup2(slave, 0) #最大的作用就是重定向,将子进程中的0,1,2 都重定向到从端。
os.dup2(slave, 1)
os.dup2(slave, 2)
print (555,test)
os.execvp("/bin/bash", ["bash", "-l", "-i"])
#os.execvp("/bin/... |
import pygame, logging, tile
class Rigid(tile.Tile):
'''
all rigid bodies that have physics simulations
we will apply euler integration
'''
def __init__(self, img, dimensions, tile, logging, spawn_loc, allF=True):
self.log = logging
self.log.info(f"seting up Rigid for {img}")
... |
import PyPDF2
import data_func
import csv
reader = PyPDF2.PdfFileReader('War_and_Peace_NT.pdf')
print(reader.documentInfo)
num_of_pages = reader.numPages
print('Number of pages: ' + str(num_of_pages)) |
rows = int(input("파스칼의 삼각형을 출력할 행의 개수를 입력하세요> "))
lst=[]
for i in range(rows):
lst.append([])
lst[i].append(1)
for j in range(1, i):
lst[i].append(lst[i-1][j-1]+lst[i-1][j])
if(rows != 0):
lst[i].append(1)
for i in range(rows):
print(" " * (rows - i), end=" ... |
import datetime
from dateutil.parser import parse
import pytz
import app_config
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
"""
Tools for managing charts
"""
class TimeTools:
@staticmethod
def seconds_since(a):
now = datetime.datetime.now(py... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, time
import win32api
import hashlib
import urllib2
# config
pastebinlink = 'http://pastebin.com/raw.php?i=GQvqfhBG' #add your raw pastebin hash list url here
# functions
def print_dog():
print """
DACHSHUND 0.1
by @pirate_security
\ | / ... |
__import__("pkg_resources").declare_namespace(__name__)
from .utils import enum
from .service import SERVICE_STATUS, ServiceState, ServiceControlsAccepted, Service
from .common import *
from .service_runner import ServiceCtrl, ServiceRunner
from .service_control_manager import ServiceManagerAccess, SC_ACTIVE_DATABAS... |
from sick_nl.code.evaluation.eval_relatedness \
import evaluate_en_models, evaluate_nl_models
from sick_nl.code.evaluation.eval_nli \
import evaluate_en_nli_models, evaluate_nl_nli_models
from sick_nl.code.evaluation.eval_stresstests \
import evaluate_switched_sicks, evaluate_stress_tests
def main():
... |
"""
xyz.handlers.post
~~~~~~~~~~~~~~~~~
Copyright 2015 Alec Nikolas Reiter
Licensed under MIT, see LICENSE for details
"""
from ..entities import Post
from datetime import datetime
class PostMaker:
"Handles orchestrations of all actions needed to create a new post"
def __init__(self, posts, c... |
from datetime import date
data = int(input('Digite o ano de nascimento do atleta: '))
data1 = date.today().year
ano = data - data1
if data >= 2011:
print('Atleta Mirim')
elif data >= 2006 and data < 2011:
print('Atleta Infantil')
elif data >= 2001 and data < 2006:
print('Atleta Junior')
elif data >= 2000 an... |
# Generated by Django 2.2.6 on 2019-11-13 06:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Employee', '0003_auto_20191112_2158'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='Employee... |
import sys,os,utils,subprocess
from colorama import *
from time import *
cache = "/var/cache/sam"
apps = "/usr/share/applications"
def unpkg(package,destination="/usr/share/sam/packages/"):
# Check if root
if os.getuid() != 0:
# Program is not runned as root
print(Fore.RED + "ERROR : Install command... |
# 이 리스트가 영상 픽셀이라 생각하고 작업하기
# 영상값 전체 10씩 올리는 알고리즘
# 문제는 무엇인가?
# 빈 메모리 확보 후에 작업하기
import random
SIZE = 10
## 1. 메모리 확보 개녕 : 타 언어 스타일
aa = [] # empty
for i in range(SIZE):
aa.append(0)
## 2. 메모리에 확보한 값 대입 --> 파일 읽기
for i in range(SIZE):
num = random.randint(0,99)
aa[i] = num
print("원 영상값-->" ,aa)
## 3. 메모... |
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from app import db, login_manager
class User(UserMixin, db.Model):
"""
Create a User table
"""
# Ensures table will be named in plural and not in singular
# As is the name of the model
... |
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import request, HttpResponse
from django.shortcuts import render
from django.db.models import Q
# Create your views here.
from zufang.models import Zufang_Info
def info_page(requset, number):
dict1 = {}
# res = Zufang_I... |
# Generated by Django 3.1.2 on 2020-11-23 22:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('clinicaApp', '0035_auto_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/21 0021 上午 11:46
# @Author : Aries
# @Site :
# @File : 内置方法__len__.py
# @Software: PyCharm Community Edition
# 内置函数和类的内置方法是有联系的
class mylist:
def __init__(self):
self.lst = [1, 2, 4, 6]
def __len__(self):
print('this is... |
import os
import nltk
from nltk.translate.bleu_score import SmoothingFunction
def get_references(rfile):
if os.path.isfile(rfile):
references = list()
with open(rfile) as texts:
for text in texts:
text = nltk.word_tokenize(text)
references.append(text)
return references
else:
... |
"""
COMP 4107 Assignment #4
Carolyne Pelletier: 101054962
Akhil Dalal: 100855466
r = ReLU
d = Dropout
s = Softmax
In -> Conv (r) -> Pool (d) -> Flatten -> FC (r) -> FC (r) -> Out (s)
2x2 max pool filter
1 0.403
2 0.531
3 0.605
4 0.589
5 0.644
6 0.649
7 0.626
8 0.634
9 0.637
10 0.645
11 0.662
12 0.684
13 0.673
14 0.6... |
# see https://www.codewars.com/kata/5296455e4fe0cdf2e000059f/solutions/python
from TestFunction import Test
def calculate(num1, operation, num2):
if operation == "+":
return num1 + num2
elif operation == "-":
return num1 - num2
elif operation == "*":
return num1*num2
elif operation ... |
#220
matrix=[[1,2,3],[4,5,6],[7,8,9]]
print(matrix)
print(matrix[1])
print(matrix[0:2])
print(matrix[0][2])
print(matrix[2][0:2])
#221
matrix1=[]
for i in range(3):
matrix1.append([i]*4)
print(matrix)
matrix2=[[0]* 3 for i in range(3)]
print(matrix2)
matrix3=[[0 for col in range(3) for row in range(3)]]
print(ma... |
# https://helloacm.com/python-method-to-find-the-largest-unique-number-in-an-array/
# https://leetcode.com/problems/largest-unique-number/
class Solution:
def largestUniqueNumber(self, A: List[int]) -> int:
freq = collections.Counter(A)
x = list(filter(lambda x: freq[x] == 1, A))
return max... |
import sys
_module = sys.modules[__name__]
del sys
VGG16 = _module
from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Module
import abc, collections, copy, enum, functools, inspect, itertools, logging, ... |
#!/usr/bin/python3
# 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# What is the sum of the digits of the number 21000?
def count_sum_of_digits(num):
n = num
total = 0
while n > 0:
total += n % 10
n //= 10
return total
print(count_sum_of_digits(pow(2, 1000)))
|
#! /usr/bin/env python3
# coding=utf-8
import sys
a = []
# 两次引用,一次来自a,一次来自getrefcount
print(sys.getrefcount(a))
b = a
print(sys.getrefcount(a)) # 3次
c = b
d = b
e = c
f = e
g = d
print(sys.getrefcount(a)) # 8次 |
'''
Created on 2018. 12. 2.
@author: hong
'''
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
print(tf.VERSION)
print(tf.keras.__version__)
print(tf.__version__) |
import argparse
import json
import logging
import os
import random
import signal
import string
import sys
import time
import paho.mqtt.client as mqtt
DEFAULT_KPC_HOST = "mqtt.cloud.kaaiot.com" # Platform host goes here
DEFAULT_KPC_PORT = 1883 # Platform port goes here
DCX_INSTANCE_NAME = "dcx"
EPMX_INSTANCE_NAME =... |
# magic comment to allow russian bukvs
# coding=UTF8
'''
Copyright (c) 2013, ОАО "ТЕЛЕОФИС"
Разрешается повторное распространение и использование как в виде исходного кода, так и в двоичной форме,
с изменениями или без, при соблюдении следующих условий:
- При повторном распространении исходного кода должно оставать... |
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
HOME_PAGE = 'http://localhost:8000'
BARCODE = '123456789'
CORRECT_USERNAME = 'ante@fer.hr'
CORRECT_PASSWORD = 'pwd'
NEW_USERNAME = 'new_user_test@smartestcart.com'
NEW_PASSWORD = 'smartcart is the best page ever'
class Strani... |
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums_len = len(nums)
# Base case if the list doesn't have enough elements
if nums_len < 3:
return []
triplets = set()
cs = {}
for i in range(nums_len):
... |
n, k = input().split()
n, k = n[::-1], int(k)
r = 0
for i in range(len(n)):
if n[i] != '0':
r += 1
if i-r+1 == k:
break
else:
r = len(n)-1
print(r)
|
from peterbecom.base.basecommand import BaseCommand
class Command(BaseCommand):
def handle(self, **options):
raise NotImplementedError(
"Use the periodic task in "
"peterbecom.base.tasks.purge_old_postprocessings instead!!!"
)
|
import flock
import qlearner as ql
if __name__=='__main__':
alpha = 0.005
gamma = 0.0
n_states = flock.Flock.num_bins_alignment*flock.Flock.num_bins_neighbors
n_actions = flock.Flock.num_turns
tol = 1e-8
eps = 0.1
n_episodes = 100
episode_len = 1000
flock_params = {
'n_bi... |
from textwrap import dedent
"""
Doorway to the Metropolis. Adjacent to Birth and Plains. Bushes shake
when certain the inventory does not contain the smelly_key or when it
contains the elf_blessing.
"""
class Grove():
def enter(self,inv):
#different the first time. First time you've been here, you wil... |
import random
from hashlib import sha256
from itertools import product
from Crypto.Util.number import *
from pwn import *
def get_additive_shares(x, n, mod):
shares = [0] * n
shares[n - 1] = x
for i in range(n - 1):
shares[i] = random.randrange(mod)
shares[n - 1] = (shares[n - 1] - shares... |
from django.conf.urls import patterns , include , url
urlpatterns = patterns( '',
url(r'^$', 'ac.views.main', name='Main'),
url(r'^display/(\d+)/$', "ac.views.display"),
url(r'^search', "ac.views.display"),
url(r'^submit_ticket',"ac.views.submit_ticket"),
url(r'^register/$', "a... |
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker, registry
from sqlalchemy.ext.declarative import declarative_base
from config import settings
engine = create_engine(settings.SQLALCHEMY_URI)
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Base = decla... |
from google.cloud import storage
import pandas as pd
import numpy as np
import os
import io
import csv
import math
for x in range(1,6):
communityNumber = "0" + str(x)
communityName = "community_" + communityNumber
error = ""
try:
dfA = pd.read_csv('exponentialMA/20ExpMA_community_' + community... |
#!/usr/bin/env python
"""
__GetBlockId__
"""
from MergeSensor.MergeSensorDB.MySQL.Base import MySQLBase
from MergeSensor.MergeSensorError import MergeSensorDBError
class GetBlockId(MySQLBase):
"""
__GetBlockName__
"""
def execute (self, fileBlock, conn = None, trans = ... |
"""
Python wrapper to generate pandas DataFrames from the New York Times'
Campaign Finance API.
Information about the API, including how to obtain a key is available
here - http://developer.nytimes.com/docs/campaign_finance_api/
Written by Connor Laird
Released under the MIT license - http://opensource.org/licenses/M... |
from pyspark import SparkConf, SparkContext
from pyspark.ml.clustering import KMeans
from pyspark.ml.feature import PCA, StandardScaler
import io
conf = SparkConf()
sc = SparkContext(conf=conf)
# Process the data
raw_votes = sc.textFile('114_congress.csv')
def remove_header(itr_index, itr):
return it... |
import sys
sys.path.insert(0, "../../")
import numpy as np
import gym
import algorithms as alg
from evaluate import *
env = gym.make("Taxi-v3")
print("\nSARSA")
alg.utils.random_seed(env, 1)
Q,history_sarsa = alg.sarsa(
env, alpha=0.5, gamma=0.99, epsilon=0.5, N_episodes=10000,
epsilon_decay=alg.utils.decay_l... |
english_to_french = {}
english_to_french['blue'] = 'bleu'
english_to_french['green'] = 'vert'
# del borrar un par clave-valor
items = list(english_to_french.items())
print(items)
del english_to_french['blue']
items = list(english_to_french.items())
print(items)
|
from gyomu.gyomu_db_model import GyomuAppsInfoCdtbl
from gyomu.db_connection_factory import DbConnectionFactory
from gyomu.status_code import StatusCode
from gyomu.gyomu_db_schema import GyomuAppsSchema
gyomuapps_schema = GyomuAppsSchema()
class GyomuAppsInfoCdtblAccess:
@staticmethod
def get_all() -> (list[G... |
import numpy as np
import matplotlib.pyplot as plt
from gym.spaces import Discrete, Box
from tfg.games import GameEnv, WHITE, BLACK
class ConnectN(GameEnv):
def __init__(self, n=4, rows=6, cols=7):
if rows < n and cols < n:
raise ValueError("invalid board shape and number to connect")
... |
from .die import Die
from .utils import i_just_throw_an_exception
class GameRunner:
def __init__(self):
self.reset()
def reset(self):
self.round = 1
self.wins = 0
self.loses = 0
def answer(self):
total = 0
for die in self.dice:
total =... |
import subprocess
import torch
import torch.nn as nn
from datetime import datetime
from logger import create_logger
from net import Net
class Model:
def __init__(self, config, vocab):
self._logger = create_logger(name="MODEL")
self._device = config.device
self._logger.info("[*] Creating m... |
import os, sys, urllib, re;
#form urlparse import urlparse;
from BeautifulSoup import BeautifulSoup
def crawl_list(CIK):
root_url="http://www.sec.gov"
url= "http://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=%s&type=DEF+14A&dateb=&owner=include" % (CIK) ;
# Retrive web page data
dlist_page_html = url... |
gst_str = ("nvarguscamerasrc ! video/x-raw(memory:NVMM), width=(int)480, height=(int)360, format=(string)NV12, framerate=(fraction)60/1 ! nvvidconv flip-method=0 ! video/x-raw, width=(int)480, height=(int)360, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink")
#gst_str = ("nvarguscamerasr... |
def plusOne(digits):
if len(digits) == 1 and digits[0] == 9:
return [1,0]
elif len(digits) == 1 and 0 < digits[0] < 9:
digits[0] = digits[0]+1
return digits
elif 0 <= digits[-1] < 9:
digits[-1] = digits[-1] + 1
return digits
elif digits[-1] == 9:
digits[-... |
def findIsland(matrix):
res = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 1:
island = []
expand(matrix, i, j, island)
res.add(moveIsland(island))
return len(res)
def expand(matrix, i, j, island):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('evaluator', '0007_course_study_degree'),
]
operations = [
migrations.AlterUniqueTogether(
name='course',
... |
import logging
import unittest
import json
import zlib
import threading
import socket
import numpy as np
from numpy.testing import assert_equal
from ..base import open
_log = logging.getLogger(__name__)
class SimServer(object):
regmap = {
'sval': {
'access': 'rw',
'addr_width'... |
'''Predicate function factories'''
__author__ = 'Sixty North'
def eq_(rhs):
'''Create a predicate which tests its argument for equality with a value.
Args:
rhs: (right-hand-side) The value with which the left-hand-side element
will be compared for equality.
Returns:
... |
import fire
import json
import pyrebase
config = {}
# TODO: Refactor path into ENV variables
with open('matcher/firebase/config.json') as file_config:
config = json.load(file_config)
firebase = pyrebase.initialize_app(config)
storage = firebase.storage()
def get_csv_file_from_storage():
storage.child("so... |
import logging
from .ATS import AcquisitionController
import numpy as np
import qcodes.instrument_drivers.AlazarTech.ATS9462.acq_helpers as helpers
from qcodes.instrument.parameter import MultiParameter, ManualParameter
from qcodes.utils.validators import Numbers, Enum
class IQMagPhase(MultiParameter):
"""
Ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.