text stringlengths 38 1.54M |
|---|
import pip
from setuptools import find_packages, setup
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='english_asr',
version=... |
import websocket
import re
my_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiZHIuaGFvb29vb29zNkB5YW5kZXgucnUiLCJpYXQiOjE2MDY1ODMzMTQsImV4cCI6MTYwNjU4NjkxNCwiaXNzIjoiaHR0cHM6Ly93ZWItcHJvZ3JhbW1pbmctMjAyMC53ZWIuYXBwIn0.4Or4UWA8BTB4u7tCcNJ3BzyDui7jYvNEgWR4sLTRBbg"
websocket_resource_url = "wss://validator-2020... |
import requests
import json
import pprint
import sys
def hit_url(url, data_dict):
res = requests.get(url).text.split("\n")
for each_key in res:
new_url= url+"/"+each_key
if each_key.endswith('/'):
another_key = each_key.split('/')[-2]
final_meta[another_key]={}
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# checkplotproc.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Feb 2019
'''
This contains functions to post-process checkplot pickles generated from a
collection of light curves beforehand (perhaps using `lcproc.checkplotgen`).
'''
#############
## LOGGING ##
########... |
from datetime import datetime, timedelta
from django.http import HttpResponse
from expenses.models import *
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from . forms import expenseForm
from django.contrib import messages
from userpreferences.models import Us... |
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'type' :'text', 'id' : 'username'}))
password = forms.Ch... |
import json
import logging
import os
import random
from configobj import ConfigObj
from peek.common import DEFAULT_SAVE_NAME
from peek.config import config_location
from peek.connection import ConnectFunc, EsClientManager
from peek.display import PeekEncoder
from peek.errors import PeekError
from peek.krb import KrbA... |
#!/usr/bin/env python
#
# Licensed under the BSD license. See full license in LICENSE file.
# http://www.lightshowpi.org/
#
# Author: Todd Giles (todd@lightshowpi.org)
# Author: Chris Usey (chris.usey@gmail.com)
# Author: Ryan Jennings
# Author: Paul Dunn (dunnsept@gmail.com)
# Author: Tom Enos (tomslick.ca@gmail.com)... |
###########################
# Multi Ensemble Learning
# Baseline model
#
# 1. feedforward network
# - predict the final feature value
#
# input : rnn state by tsl model
# output : predicted next EMR data
#
# by Donghoon Oh
###########################
import os
import numpy as np
import tensorflow as tf
import tim... |
"""n, k = map(int, input().split())
o = []
e = []
for i in range(1,n+1):
if(i%2==0):
e.append(i)
else:
o.append(i)
l = o+e
print(l[k-1])"""
import math
n,k=map(int,input().split())
if k<=n//2:
print(2*k-1)
else:
i=k-math.ceil(n/2)
if i!=0:
print(2*i)
e... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Baidu, Inc. 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/LICEN... |
from collections import namedtuple
from ..base import BaseTestCase
version_info_t = namedtuple(
"version_info_t", ("major", "minor", "micro", "releaselevel", "serial")
)
class VersionsPanelTestCase(BaseTestCase):
panel_id = "VersionsPanel"
def test_app_version_from_get_version_fn(self):
class F... |
from abc import ABC, abstractmethod
import inspect
from typing import Any, Callable, Dict, Generic, List, Type, TypeVar, Union
from erdantic.typing import Final, GenericAlias, repr_type, repr_type_with_mro
_row_template = """<tr><td>{name}</td><td port="{name}">{type_name}</td></tr>"""
FT = TypeVar("FT", bound=Any... |
# Generated by Django 2.2.6 on 2020-06-28 17:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# Generated by Django 3.0.2 on 2020-01-24 21:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fos', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='customerdetails',
options={'verbose_name... |
#! /usr/bin/env python
# coding: utf-8
import collections
def winner(andrea, maria, s):
num = len(andrea)
andrea_sum = 0
maria_sum = 0
for i in xrange(num):
if s == 'Even' and i % 2 == 0:
andrea_sum += andrea[i] - maria[i]
maria_sum += maria[i] - andrea[i]
if... |
import pyautogui,os,time
#Specify the file path to open - opens file in same location all time (optional)
#os.startfile("C:\\Users\\admin\\Desktop\\dvta-master\\dvta-master\\DVTA\\DVTA\\bin\\Release\\DVTA.exe")
#pyautogui.position() - gives position of mouse cursor
#Sends keystroke to application - update the... |
a = 10
if a > 5:
print('this is a grater than 5')
if a>15:
print('this is a also bigger that 15')
if a == 10:
print('this is equal to 10')
if a==5 or a<15:
print('this condition is true')
print('any one of them is true')
|
from django.shortcuts import redirect, render
# Create your views here.
def index(request):
return render(request,'index.html')
def prorduct_details(request):
return render(request,'pages/product_details.html')
def cartshow(request):
return render(request,'pages/cart.html')
def procced(request):
... |
import nltk
import re
text = "Some of the consequences of that new standard of international English will be that some or all grammatical changes will be made."
# text = "A new internationl English will, without doubt, come with grammatical changes"
tokens = nltk.word_tokenize(text)
tagged_array = nltk.pos_tag(token... |
# Copyright (c) 2019-2020 Manfred Moitzi
# License: MIT License
# created 2019-03-06
import pytest
import ezdxf
from ezdxf.lldxf import const
from ezdxf.entities.mtext import MText, split_mtext_string, plain_mtext, normalize_line_breaks
from ezdxf.lldxf.tagwriter import TagCollector, basic_tags_from_text
MTEXT = """0... |
# 2019 Kickstart Round A - B. Parcels
# https://codingcompetitions.withgoogle.com/kickstart/round/0000000000050e01/000000000006987d
from bisect import bisect_left
from collections import deque
from itertools import product
def bfs(r, c, grid):
q, seen = deque(), set()
for y, row in enumerate(grid):
fo... |
import matplotlib
from sklearn import preprocessing
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy, scipy, librosa, audioread, wave
import librosa.display
import sys, os
def showmfcc(wavpath,i):
t, spe = librosa.load(wavpath)
mfccs = librosa.feature.mfcc(t, sr=spe)
name = "E:/video-c... |
class NumberOfCommunity:
number_community = 0
number_community_list = []
def __init__(self, county='po'):
self.county = county
self.__class__.number_community += 1
@staticmethod
def add_county_and_number(county, number):
"""
Atribute:
county, number
... |
import lsst.pex.config as pexConfig
import fakeTypeMap as fake
from lsst.ctrl.ap.config.brokerConfig import BrokerConfig
from lsst.ctrl.ap.config.hostConfig import HostConfig
class OCSConfig(pexConfig.Config):
""" OCS configuration information
"""
broker = pexConfig.ConfigField("event broker information",... |
"""
Tests to ensure that the training loop works with a scalar
"""
import torch
from pytorch_lightning import Trainer
from tests.base.deterministic_model import DeterministicModel
def test_training_step_scalar(tmpdir):
"""
Tests that only training_step that returns a single scalar can be used
"""
mod... |
import django_filters
from django import forms
from django_filters import DateFilter , CharFilter, NumberFilter
from .models import *
class DateInput(forms.DateInput):
input_type = 'date'
class TicketFilter(django_filters.FilterSet):
id = CharFilter(field_name='id',lookup_expr='exact',label='Ticket Id')
s... |
# This file is part of Mylar.
# -*- coding: utf-8 -*-
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is dist... |
from django.urls import include, path
from github.views import repos, licenses
urlpatterns = [
path('repos/', repos),
path('licenses/', licenses)
] |
from shreducer import Grammar
class ListG(Grammar):
class t:
ID = None
COMMA = ','
PARENS_OPEN = '('
PARENS_CLOSE = ')'
LIST = ()
# An ID or LIST that is completed and cannot be modified anymore
# DONE must have all the rules that ID has.
DONE = ()
... |
from Common import *
from TableNames import table_names
class ServerDomain(database_manager.Base):
__tablename__ = table_names['ServerDomain']
id = Column(Integer, Sequence(__tablename__+'_id_seq'), primary_key=True)
name = Column(String(64), index=True)
pubkey = Column(String(49))
UniqueConst... |
from django.forms import *
class ContactForm(Form):
subject = CharField(max_length=100)
message = CharField()
sender = EmailField()
cc_myself = BooleanField(required=False)
class StudentForm(Form):
empid = CharField(max_length=7)
name = CharField(max_length=100)
department = CharField(max_length=100)
base ... |
print ("Toma de deciciones")
print("Ingrese los datos de la primera alternativa \n")
x1 = float(input("Ingresa cantidad a ganar:\t"))
p1 = float(input("Ingresa probabilidad de ganar:\t"))
x2 = float(input("Ingresa cantidad a perder:\t"))
p2 = float(input("Ingresa probabilidad de perder:\t"))
print("\n\nIngrese los dato... |
from __future__ import print_function, division
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import keras
from keras.models import load_model, Input, Model
from keras.layers import Conv2D
import tensorflow as tf
import numpy as np
import time
from tifffile import i... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 19:44:03 2018
@author: shilu
"""
import numpy as np
from numpy import pi, sin, cos, exp, inf
from scipy import zeros, linalg
from scipy.sparse import csc_matrix, lil_matrix, bmat, coo_matrix, csr_matrix
from scipy.sparse.linalg import spsolve
f... |
# -*- coding: utf-8 -*-
import urllib
import urllib2
from suds.client import Client
from util import moneyfmt
SOAP_URL = 'https://ecommerce.redecard.com.br/pos_virtual/wskomerci/cap.asmx?wsdl'
RECEIPT_URL = 'https://ecommerce.redecard.com.br/pos_virtual/cupom.asp'
TIMEOUT = 60
DEFAULT_TRANSACTION_TYPE = 'shop'
TRAN... |
import pyactiveresource.connection
from pyactiveresource.activeresource import ActiveResource, ResourceMeta, formats
import shopify.yamlobjects
import shopify.mixins as mixins
import shopify
import threading
import sys
from six.moves import urllib
import six
from shopify.collection import PaginatedCollection
from pyac... |
symbol = {'I':1, 'V':5, 'X':10, 'L':50, 'C': 100, 'D':500, 'M':1000}
def romanToInt(self, s: str):
_sum = 0
i = 0
while(i < len(s)):
_curr = symbol.get(s[i])
if i == len(s) - 1:
_sum += _curr
break
_next = symbol.get(s[i+1])
if _curr < _next:
_sum = _sum + (_next - _curr)... |
import sys
class Nodo:
__izq = None
__der = None
__char = None
__frec = 0
def __init__(self,char=None,frec=0):
self.__izq = None
self.__der = None
self.__char = char
self.__frec = frec
def setIzq(self,izq):
self.__izq = izq
def setD... |
import sys
import commands
import math
from subprocess import call
nperm = 1000
perms = open(sys.argv[2], 'r')
tamanho = int(sys.argv[1])
output = sys.argv[3]
iota = str([i for i in range(1,tamanho+1)])
max_range = math.factorial(tamanho)
if (tamanho >= 10):
max_range = nperm
for a in range(1,max_range+1):
p... |
# Her telles kyllingene
print" I will not count my chickes:"
# Her teller jeg heans og roosters
print "Heans", float (25) + 30 / 6
print "Roosters", float (100) - 25 * 3 % 4
#Her telles eggene
print "Now I will count the eggs:"
print float (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print "Is it true that 3 + 2 < 5 - 7?"
p... |
"""
test_galaxy.py - tests for the Galaxy API manager.
Copyright (c) 2018 The Fuel Rats Mischief,
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE
"""
import asyncio
import pytest
import aiohttp
pytestmark = [pytest.mark.unit, pytest.mark.galaxy]
@pytest.mark.asyncio
async def test_find... |
from django.urls import path
from . import views
urlpatterns = [
path('s3download/', views.rpi_s3download_handler_view, name='RPiS3DownloadHandler'),
path('command/', views.rpi_command_handler_view, name='RPiCommandHandler'),
path('panel/', views.rpi_panel_view, name='RPiPanel'),
]
|
import socket
import argparse
from sys import exit
serverAddress = ("0.0.0.0", 9999)
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--message", nargs='+',
help="The message that you would like to send.")
args = parser.parse_args()
if args.message:
clientData = ' '.join(args.mes... |
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import time
import os
import warnings
import seaborn as sns
import pickle
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from sklearn.utils import shuffle
import tensorflow as tf
from t... |
import config
import datetime
import hashlib
import json
import os
import sectoralarm
SECTORSTATUS = sectoralarm.SectorStatus(config)
log = SECTORSTATUS.event_log()
loghash = hashlib.sha256(json.dumps(log)).hexdigest()
now = datetime.datetime.now()
LOGFILE = os.path.join(os.path.dirname(os.path.realpath(__file__))... |
import numpy as np
import torch
import torch.nn as nn
class ROIPool(nn.Module):
def __init__(self, output_size):
super().__init__()
self.maxpool = nn.AdaptiveMaxPool2d(output_size)
self.size = output_size
def forward(self, images, rois, roi_idx):
# images:特征图 image_batchsize * ... |
#!/usr/bin/env python
import os
import sys
#check input
if(len(sys.argv)!=4):
print("USAGE: python intersectVCF.py [VCF_file] [DNM_file] [DNM_file_cols]")
else:
#extract params
VCF_file = sys.argv[1]
DNM_file = sys.argv[2]
DNMFileCols = [int(x.strip()) for x in sys.argv[3].split(',')]
#load DNM file hashes
ha... |
from data import *
from IO.rs232 import RS232
import ConfigParser, re
class ACDC():
def __init__(self, argv):
self.DUTCOM = argv['COM'][str(DATA.id)]
self.DUT = RS232({'COM': self.DUTCOM})
self.DUT._connect()
def set_relay(self, argv):
try:
barrier = DATA.barriers[argv['barrier']]
except:
barrier =... |
from tkinter import CENTER, Button, Entry, Label, LabelFrame, Listbox, font, S, N, NE, NW, END, Message, Tk, W, E
from PIL import Image, ImageTk
from position import Position
import os_tinkering
LIST_WIDTH = 50 if os_tinkering.getOs() != "Darwin" else 25
class GUIMenu:
def __init__(self, app):
self.w... |
from django.shortcuts import render, redirect
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UserChangeForm, PasswordChangeForm
... |
import os
import docx
import unicodedata
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponseRedirect
from subprocess import Popen, PIPE
from mysite2 import settings
class ReadFile(object):
def __init__(self):
self.file_system_storage = FileSystemStorage()
s... |
from mydewsbotslib.linepy import *
from mydewsbotslib.akad.ttypes import *
from multiprocessing import Pool, Process
from datetime import datetime
from time import sleep
from bs4 import BeautifulSoup
from humanfriendly import format_timespan, format_size, format_number, format_length
import time, random, sys, json, cod... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import podium_api
from podium_api.asyncreq import get_json_header_token, make_request_custom_success
from podium_api.types.racestat import get_racestat_from_json
from podium_api.types.redirect import get_redirect_from_json
def make_racestat_get(
token,
endpoint,
... |
#!/usr/bin/env python
import os,sys
import socket
class initialize():
def __init__(self, unit=None, verb=True):
'''
Function to initialize directories to perform any kind of wvr reduction
'''
self.host = socket.gethostname()
self.home = os.getenv('HOME')
... |
import json
with open("../data/dataset.json") as f:
dataset = json.load(f)
trn_data = dataset["train"]
dev_data = dataset["dev"]
X_trn, Y_trn = zip(*trn_data)
X_dev, Y_dev = zip(*dev_data)
|
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
def _search(l1, l2, k):
if len(l1) == 0:
return l2[k]
if len(l2) == 0:
r... |
def fibonacci(n):
fibonacci = np.zeros(10, dtype=np.int32)
fibonacci_pow = np.zeros(10, dtype=np.int32)
fibonacci[0] = 0
fibonacci[1] = 1
for i in np.arange(2, 10):
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2]
fibonacci[i] = int(fibonacci[i])
print(fibonacci)
for i in np.arange(10):
fibonacci_pow[i] ... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.shortcuts import redirect
from django import forms
from related_admin import RelatedFieldAdmin as ModelAdmin
from csa.models.user import User, UserProfile
from csa.finance.payments import get_user_balance
import csa.models
ad... |
import time
from . import Model
class User(Model):
"""
User 的数据有:id, username, password, create time, update time 等
操作有:hash,加盐,注册,验证登录
"""
def __init__(self, form):
self.id = form.get('id', None)
self.username = form.get('username', '')
self.password = form.get('password'... |
# -*- Mode: Python -*-
##
# = Other events
##
##
# @SHUTDOWN:
#
# Emitted when the virtual machine has shut down, indicating that qemu is
# about to exit.
#
# @guest: If true, the shutdown was triggered by a guest request (such as
# a guest-initiated ACPI shutdown request or other hardware-specific action)
# rather t... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class FlipkartItem(scrapy.Item):
# define the fields for your item here like:
product_name = scrapy.Field()
product_price = scrapy.Field()... |
import sys
def process_file(filename):
with open(filename, 'r') as fh:
for line in fh:
line = line.rstrip("\n")
if len(line) > 0:
if line[0] == '#':
return
# some comment
if len(line) > 1:
if line[0:2] == '//':
... |
def gcd(m,n):
fm=[]
for i in range(1,m+1):
if(m%i==0):
fm.append(i)
fn=[]
for j in range(1,n+1):
if(n%j==0):
fn.append(j)
cf=[]
for f in fm:
if f in fn:
cf.append(f)
return (cf[-1])
m=int(input("Enter the m value: "))
n=int(input(... |
# Copyright (c) 2016 Fabian Kochem
import collections
from copy import deepcopy
def recursive_dict_merge(left, right, create_copy=True):
"""
Merge ``right`` into ``left`` and return a new dictionary.
"""
if create_copy is True:
left = deepcopy(left)
for key in right:
if key in l... |
from sympy.testing.pytest import raises
from sympy import (
Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray,
MutableDenseNDimArray, MutableSparseNDimArray
)
array_types = [
ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableDenseNDimArray,
MutableSparseNDimArray
]
def test_ar... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Filename: logistic_ression.py
@Author: yew1eb
@Date: 2015/12/20 0020
"""
import math
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def gradient(data, w, j):
def Logistic_Regression(data, listA, listW, listLostFunction):
N = len(data[0]) #维... |
#zk='10.20.30.1:2181,10.20.30.15:2181,10.20.30.16:2181'
public_zk='129.59.107.80:2181,129.59.107.97:2181,129.59.107.148:2181'
public_zk2='129.59.107.134:2181,129.59.107.57:2181,129.59.107.201:2181'
public_zk3='129.59.107.36:2181,129.59.107.35:2181,129.59.107.37:2181'
public_zk4='129.59.234.238:2181,129.59.234.233:2181,... |
from model import *
# -------------------
# Blocking Design
# -------------------
# Define the model
experiment = Model_Rescorla_Wagner(experiment_name="Blocking", lambda_US=1, beta_US=0.5)
# Define the predictors
A = Predictor(name='A', alpha = 0.2)
B = Predictor(name='B',alpha = 0.2)
C = Predictor(name='C',alpha =... |
from google.oauth2 import service_account
from config import config
import utils
def load_credentials(api):
SERVICE_ACCOUNT_FILE = 'credentials.json'
scopes = []
if api == 'sheets':
scopes.append('https://www.googleapis.com/auth/spreadsheets')
try:
if not config.get('googleAPICreds')... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 14:10:03 2021
@author: behrokh
"""
'''
Given an array nums containing n distinct numbers in the range [0, n],
return the only number in the range that is missing from the array.
'''
def missingNumber(nums):
"""
:type nums: List[in... |
data = [[1,2,3],[4,5,6],[7,8,9]]
dataset = ["seltjsltkM", "DLSMlfMsljlfw", "kslrjwiojlLML"]
count = 0
for data in dataset:
for ch in data:
if ch == 'M':
count += 1
print(count)
## enqueue : 큐에 데이터를 넣는 기능
## dequeue : 큐에서 데이터를 꺼내는 기능
## Queue() : 가장 일반적인 큐 자료 구조
## LifoQueue() : 나중에 입력된 데이터... |
# LEVEL 20
# http://www.pythonchallenge.com/pc/hex/idiot2.htmlhttp://www.pythonchallenge.com/pc/hex/idiot2.html
import re
import requests
url = 'http://www.pythonchallenge.com/pc/hex/unreal.jpg'
req = requests.head(url, auth=('butter', 'fly'))
print(req.headers)
print(req.status_code)
while req.status_code != 416:
... |
'''
All tabs have been converted to spaces.
'''
'''
A program that reads in an NFA txt file, converts it
into its equivalent DFA, and writes the DFA to file.
Authors: Alex Cameron, Eli Grady, Erick Perez
USD, COMP370, Dr. Glick, Spring 2017
'''
import sys
'''
A class that defines an NFA.
@param NFAdict, a dict... |
#!/usr/bin/python26
import sys,os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/lib")
import unittest
import random
from auth import *
from gh_api import *
from internal_api import *
class archive_blob(unittest.TestCase):
def check_pass(self, zauth, data):
ret =user_blob_archive(zauth, data)
tr... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def Home_View(request,*args,**kwargs):
return render(request,'home.html',{})
def main_view(request, *args,**kwargs):
return HttpResponse(request,'books/main_book_view.html',{})
def login_view(request, *args,**k... |
#!/usr/bin/env python
# coding=utf-8
# Questo nodo genera il file "vicon_frame2UWB_tf.txt" in cui e` salvata la trasformazione da frame vicon
# a frame UWB. Sono necessarie le misurazioni dell'ancora 0 (origine) e ancora 1 (asse y) da ripetere ogni
# volta che si spostano le ancore
import rospy
import tf
import nump... |
"""
Code adapted from Aryan Arbabi, https://github.com/a-arbabi/NeuralCR
"""
SEED=42
import ast
import argparse
import numpy as np
import os
import json
import fasttext as fastText
#import fastText
import pickle
import tensorflow as tf
#from tqdm import tqdm
#import matplotlib.pyplot as plt
from sklearn.utils import sh... |
import numpy as np
import trees._BaseClasses as _BC
from trees._BinaryDecisionTree import _BinaryTreeClassifier as BinaryTreeC, _BinaryTreeEstimator as BinaryTreeE
# Small offsets for logarithimic equations
_LOGMIN = np.finfo(np.float64).eps
_LOGMAX = 1.0 - np.finfo(np.float64).epsneg
class _AdaBoostEstimator(_BC.Ba... |
# coding=utf-8
"""
Fatsecret OAuth 1.0 http://oauth.net/core/1.0/ flow
http://platform.fatsecret.com/api/Default.aspx?screen=rapiauth#correctly_signing
"""
from oauth2 import Consumer as OAuthConsumer, Token, Request as OAuthRequest, \
SignatureMethod_HMAC_SHA1, HTTP_METHOD, Client, SignatureMethod... |
from django.contrib import admin
from .models import JabberConversation, JabberRoster, JabberPresence
admin.site.register(JabberConversation)
admin.site.register(JabberRoster)
admin.site.register(JabberPresence)
|
""" Post-process the phase shifter measurement restuls
"""
import pandas as pd
import numpy as np
import logging, time, datetime, pathlib, subprocess, csv, matplotlib, pathlib
from importlib import reload
import matplotlib.pyplot as plt
reload(logging)
meas_date = time.strftime("%Y_%m_%d")
t_script_start = dat... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod, abstractproperty
class Property(object):
__metaclass__ = ABCMeta
id = None
name = None
default = None
@abstractmethod
def normalize(self, value):
"""Normal... |
def moce(x,n):
# import pdb;pdb.set_trace()
y=[]
while len(y)<=2:
for i in x:
x.pop(i)
# print(x)
y.append(i)
return y
x=[2,4,6,8,9]
n=2
print(moce(x,n)) |
import logging
from multiprocessing.pool import ThreadPool
from warcio.archiveiterator import ArchiveIterator
import requests
from selectolax.parser import HTMLParser
from langdetect import detect as detect2
from pyspark import SparkContext
from pyspark.sql import SparkSession, Row
import pyspark.sql.functions as F
f... |
#!/usr/bin/env python
import asyncio
import logging
import websockets
import ujson
import random
import string
import hummingbot.market.hitbtc.hitbtc_constants as constants
from typing import Dict, Optional, AsyncIterable, Any
from websockets.exceptions import ConnectionClosed
from hummingbot.logger import HummingbotL... |
# weltraum.py
# GPS system and odometer.
#( (C) 2018 Omar Metwally :: ANALOG LABS
# omar@analog.earth
# LICENSE: Analog Labs License (analog.earth)
import serial, sys, os
from random import randint
from time import sleep, time
import hashlib
GPS_TRACE_PATH = '/home/pi/Desktop/way.csv'
ser = serial.Serial('/dev/ttyA... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
from events.views import EventViewSet, EventList, EventDetail, ObtainTokenWrapperViewSet, RefreshTokenWrapperViewSet
router = DefaultRouter()
router.register(... |
from pyecharts import options as opts
from pyecharts.charts import Geo, Page
from pyecharts.faker import Collector
from pyecharts.globals import ChartType, SymbolType
import numpy as np
import pickle
content_comment = pickle.load(open('Agu.pkl', 'rb'))
provin = '北京市,天津市,上海市,重庆市,河北省,山西省,辽宁省,吉林省,黑龙江省,江苏省,浙江省,安徽省,福建省,江西... |
import urllib.request
import json
import datetime
from collections import Counter
b = []
x1 = datetime.datetime.now()
print("Η ΜΕΡΑ ΣΗΜΕΡΑ ΕΙΝΑΙ:", x1.strftime("%d"),"-",x1.strftime("%m"), "-", x1.strftime("%y"))
for i in range(1, int(x1.strftime("%d"))+1):
c = datetime.datetime(2021, int(x1.strftime("%m"... |
"""graffiti.config handles config and command files parsing
"""
import os.path
import yaml
def parse_config_file(filename):
"""Parse graffiti config file
"""
with open(filename, 'rb') as cfg_file:
data = yaml.load(cfg_file)
info = parse_config(data)
return info
return None
de... |
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.plotly as py
import plotly.graph_objs as go
# Data
trace1 = go.Bar(
x=[year for year in range(1999, 2017)],
y=[219, 146, 112, 127, 124, 180, 236, 207, 236, 263,
350, 430, 474, 526, 48... |
# python login.py -u alex -p 123456
# with open('user.db','w') as write_file:
# write_file.write(str({
# "alex":{"password":"123456",'status':False,'timeout':0},
# }))
import sys,time
print(sys.argv) #[ ,-u,alex,-p,123456]
# username=sys.argv[2]
# password=sys.argv[4]
# class User:
# db_path="us... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def shuffle_divide_export(df, training_percent = 0.8, validation_percent = 0.1, shuffle = True, path = 'Data/Housing/'):
if(shuffle):
df = df.sample(frac=1)
training, validation, test = np.split(df, [int(training_percent*len(df)), int((1-v... |
# -*- coding: utf-8 -*-
from templex.exceptions import TemplexException
from templex.exceptions import KeyNotFound
from templex.core import Templex
from templex.core import TemplexMatch
|
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
# self.neighbors = neighbors if neighbors is not None else []
from collections import deque
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
# Base Case - If graph is empty the... |
#coding:utf-8
import sys
import json
import requests
import platform
import unittest
import configparser
import logging
from BeautifulReport import BeautifulReport
# 根据系统环境判断需要读取的目录路径
if(platform.system()=='Windows'):
print(platform.system())
report_dir = "D:\\uitest\\report"
configInfo = "C:\shh\\uitest\\... |
from selenium.common.exceptions import *
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class Application(object):
def __init__(self, driver):
self.driver = driver
self.wait=WebDri... |
from collections import Mapping
class UnoverwritableDict(dict):
def __init__(self, *a, **k):
dict.__init__(self, *a, **k)
def __setitem__(self, key, value):
assert key not in self, f"Key override not allowed (key: {key})"
dict.__setitem__(self, key, value)
def update(self, other... |
# 3: Дан список заполненный произвольными целыми числами.
# Получите новый список, элементами которого будут только уникальные элементы исходного.
# Примечание. Списки создайте вручную, например так:
# my_list_1 = [2, 2, 5, 12, 8, 2, 12]
#
# В этом случае ответ будет:
# [5, 8]
my_list = [2, 2, 5, 12, 8, 2, 12]
new_li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.