text stringlengths 38 1.54M |
|---|
from cronjob.index import Cronjob
from database.index import Database
class Main:
@staticmethod
def start():
print('Booting trader...')
Database.start()
Cronjob.start()
Main.start()
|
from django.shortcuts import render, redirect
from django.utils.crypto import get_random_string
def main(request):
if 'counter' not in request.session:
request.session['counter']=0
context={
'randword': get_random_string(length = 14)
}
print('session counter'+ str(req... |
import numpy as np
import cv2 as cv
image = cv.imread('D:/images/toux.jpg')
cv.imshow("input", image)
h, w ,ch = image.shape
# 构建图像数据
data = image.reshape((-1,3))
data = np.float32(data)
# 图像分割
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0)
num_clusters = 4
ret,label,center=cv.kmeans(data, num... |
import requests
import pandas as pd
import requests
import pandas as pd
class Autobahn:
"""A API wrapper class for the Autobahn App API https://autobahn.api.bund.dev/.
This class provides you with current administrative data in the form of
construction site information, warnings, webcams, electric chargin... |
from bs4 import BeautifulSoup
try:
from urllib.request import urlopen
import requests
except ImportError:
from urllib2 import urlopen
def scrape_page(src_url, web_context, web_attributes):
tweets = []
last_url = ""
for i in range(len(src_url)):
if src_url[i] != last_url:
l... |
class Osoba:
pass
#kazda klasa dziedziczy po klasie object mimo ze tego nie widac
tadek = Ososba();
tadek.imie="Tadeusz"
print(tadek.imie)
#metoda musi miec w pierwszym miejscu atrybutu napis self (self,z)
tadek = Osoba();
|
import numpy as np
from PIL import Image
import time
import lab5_lib
def butterworse_pass_11812418(input_img, sigma, n):
# Reading of the image into numpy array:
img = Image.open(input_img)
# FFT transform for img arr
input_image = np.asarray(img)
input_image = lab5_lib.FFT_zero_padding(input_ima... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
读取配置。这里配置文件用的yaml,也可用其他如XML,INI等,需在file_reader中添加相应的Reader进行处理。
"""
import os
from utils.read_file import YamlReader
# 通过当前文件的绝对路径,其父级目录一定是框架的base目录,然后确定各层的绝对路径。如果你的结构不同,可自行修改。
BASE_PATH = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
CONFIG_FILE = os.pat... |
# #Q 11. Write python program to calculate compound interest i.e.
# A = final amount
# P = initial principal balance
# r = interest rate
# n = number of times interest applied per time period
# t = number of time periods elapsed
# A = int(input("Enter Final Amount: "))
P = int(input("Enter Principal Balance: "))... |
#!/usr/bin/env python
"""
Creates lists of molecules in clusters
Hazen 09/17
"""
import argparse
import numpy
import random
import storm_analysis.sa_library.i3dtype as i3dtype
import storm_analysis.sa_library.writeinsight3 as writeinsight3
parser = argparse.ArgumentParser(description = "Create emitters in (possibly ... |
def reverse_iteration():
"""
There isn't really reverse iteration in Python. I can iterate forwards over a list that is sorted in decreasing order. I could also use the
reversed() function, which presumably reverses and returns a sequence
"""
for i in range(10, 0, -1):
print(i)
print("")... |
from ScenarioHelper import *
def main():
SetCodePage("ms932")
CreateScenaFile(
"e302b.bin", # FileName
"e302b", # MapName
"e302b", # Location
0x0000, # MapIndex
"ed7513",
0x00002000, ... |
"""
Created on June 4th, 2019
The purpose of this script is to operate the ADQ14DC-4A-VG-USB digitizer and
output data to HDF5 files using HDFWriterReader
@author: Dan Hudetz
"""
import numpy as np
import ctypes as ct
from HDFWriteRead import write
import epics
import modules.example_helpers as a
import sys
import o... |
from flask_restful import Resource
class AppraiseResource(Resource):
def get(self):
return 'haha'
|
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2019 by Brendt Wohlberg <brendt@ieee.org>
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""Construct variant of admm ... |
from unittest import TestCase
from ..build import create_stats
from inspect import getfullargspec
from greyatomlib.multivariate_regression_project.q01_load_data.build import load_data
from greyatomlib.multivariate_regression_project.q02_data_split.build import split_dataset
from greyatomlib.multivariate_regression_pro... |
from flask import Flask, request
from FlaskLib.FlaskUtils import get_template, make_default_template
import psutil
import glob
from lib.PipeUtil import load_json_file, save_json_file, cfe
from lib.PipeAutoCal import fn_dir
import requests, json
import sys
import netifaces
import os
import subprocess
def tl_menu(ams... |
class resources:
_resources = {}
def __init__(self,**kwargs):
for k,v in kwargs.items():
self._resources[k]=v
def get(self):
return self._resources
def findkey(self,k):
return k in self._resources
def getvalue(self,k):
return self._resources[k]
def put... |
import CalendarStore
from PyObjCTools.TestSupport import TestCase
class TestCalEvent(TestCase):
def testMethods(self):
self.assertResultIsBOOL(CalendarStore.CalEvent.isAllDay)
self.assertArgIsBOOL(CalendarStore.CalEvent.setIsAllDay_, 0)
self.assertResultIsBOOL(CalendarStore.CalEvent.isDet... |
import random, time
import numpy as np
from reward_machines.reward_machine import RewardMachine
from agents.dqn import DQN
from agents.learning_parameters import LearningParameters
from agents.learning_utils import save_results
from worlds.game import Game
"""
- This code runs standard DQN (it doesn't learn the reward... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yuri tolkach
"""
# =============================================================================
# 13. Greasy fingerprints
# =============================================================================
#Parameters
#Directory for files (dataset)
source_di... |
import numpy as np
# TO DO:
1) Get location of all objects from gazebo
2) Get location and velocity of robot
3) Estimate future path
4) Estimate targets probabilitys
5) Publish path
Nt = 10
A = np.eye(l_size*Nt)
P = np.zeros((l_size*Nt,l_size*Nt))
H = np.zeros(Nt*l_size)
alpha = 0*np.ones((l_size,l_size*Nt))
z = np... |
from Approximation.Instruments.Functors.BaseFunctor import BaseFunctor_
import math
class Ceil(BaseFunctor_):
def __init__(self, internalFunctor, IsActive : bool = True):
self.internalFunctor_ = internalFunctor;
self.IsActive_ = IsActive;
def GetConformity(self):
return self.in... |
# -*-coding: utf-8-*-
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
from functools import reduce
from 椒盐噪声 import salt_noise
class space_filter:
def __init__(self, pic):
self.pic = pic
self.shape = pic.shape
def imfilter(self, w):
# 矩阵算子形式的滤波器
temp = s... |
# hotels is an array containing hotel objects with the following form:
# { 'distance': int, 'id': str }
def road_trip(hotels, daily_dist):
hotels_slept_in = []
dist_done = 0
i = 0
cur_hotel = hotels[i]
while cur_hotel['id'] != hotels[len(hotels) - 1]['id']:
dist_diff = dist_done + daily_dist
while d... |
from keras.datasets import mnist
from keras import models, layers, callbacks, regularizers
from keras.utils import to_categorical
from vizualization import plt_loss, plt_accuracy
callbacks_list = [
callbacks.EarlyStopping(monitor='acc', patience=1),
callbacks.ModelCheckpoint(filepath='model.h5', monitor='val_... |
import os, gzip
from pyensembl import EnsemblRelease
# genome
release = EnsemblRelease(93)
# directories
sc_hiv_root = '%s/work/CRG/projects/sc_hiv'%(os.getenv('HOME'))
matrices_dir = '%s/data/matrices'%(sc_hiv_root)
out_dir = '%s'%(matrices_dir)
sample_name = 'P2449'
# get matrix file name and out file name
matrix_... |
#!/usr/bin/python2.7
### light_board[row][column]
import re
DIMENSION = 1000 ## square board DIMENSIONxDIMENSION
ON = 1
OFF = 0
TOGGLE = 2
string = r"(turn off|turn on|toggle) (\d+),(\d+) through (\d+),(\d+)"
def show_board(board):
for row in board:
print row
def turn_lights(board, row_start, row_end,... |
from dataclasses import dataclass
from typing import List
@dataclass
class CoronaData(object):
pref_EN_name: str
pref_JP_name: str
newly_confirmed: int
yesterday_confirmed: int
confirmed_by_city: List[str]
deaths: int
total_confirmed: int = 0
recovered: int = 0
|
import flask
from flask import request, jsonify
import json
app = flask.Flask(__name__)
import string
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from ast import literal_eval
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
f... |
# -*- coding: UTF-8 -*-
import pymysql
# 数据类型检查
def type_check(item):
data_type = 'list'
if type(item).__name__ == 'list':
data_type = 'list'
elif type(item).__name__ == 'dict':
data_type = 'dict'
elif type(item).__name__ == 'str':
data_type = 'str'
elif type(item).__name__ ... |
T = int(input().strip())
for test_case in range(1, T + 1):
N = int(input().strip())
if N == 0:
num = "INSOMNIA"
else:
num = N
digits = set(digit for digit in str(N))
while len(digits) < 10:
num += N
digits.update(digit for digit in str(num))
print(... |
import numpy as np
from numpy import pi, sin, exp, sqrt
from .. import logger
from .. import const
from ..struct import Struct
from .. import nb
from .. import noise
from .. import suspension
##################################################
def coating_thickness(ifo, optic):
optic = ifo.Optics.get(optic)
i... |
class General():
@staticmethod
def required(request_data, *validation_args):
error_msg = 'This field is required'
if request_data is None :
return {'status': False, 'message': error_msg}
if not isinstance(request_data, int):
if len(request_data) == 0... |
import sys
ROME_SYMBOLS=[
['M' , 1000],
['D' , 500],
['C' , 100],
['L' , 50],
['X' , 10],
['V' , 5],
['I', 1]
]
def build_symbols(symbols=ROME_SYMBOLS):
new_symbls = []
for i, (s, w) in enumerate(symbols):
new_symbls.append([s, w])
for s2, w2 in symbol... |
from selenium import webdriver
import time
driver = webdriver.Chrome('/home/owen/Downloads/chrome_driver/chromedriver')
driver.get('https://www.randommemes.website/sounds.html#/')
button_element = driver.find_element_by_xpath('//*[@id="header-wrapf"]/div[3]/a[2]')
time.sleep(2)
button_element.click()
|
import pytest
from import_common.normalization import (
normalize_doi,
normalize_kod_dyscypliny,
normalize_orcid,
normalize_tytul_publikacji,
)
@pytest.mark.parametrize(
"i,o",
[
("101_0", "1.1"),
("111_0", "1.11"),
("407", "4.7"),
("411", "4.11"),
("4.... |
"""Test images module."""
__author__ = 'shor.joel@gmail.com (Joel Shor)'
import tempfile
import unittest
import os
import images
class TestAudio(unittest.TestCase):
def setUp(self):
self.dir_path = os.path.dirname(os.path.realpath(__file__))
def test_copy_audio_from_disk(self):
filenames... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-10 19:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recommend', '0016_auto_20170310_1852'),
]
operations = [
migrations.AddFiel... |
from django.shortcuts import render
import pandas as pd
import matplotlib.pyplot as plt
from django.views.generic import TemplateView
import plotly.offline as opy
import plotly.graph_objs as go
import plotly.express as px
from .models import Species, IrisData
from .utils import specie_name
# Create your views here.
de... |
def problem22():
f = open('names.txt', 'rt')
names = f.read().split(',')
for name in names:
names[names.index(name)] = name.strip('\"')
names.sort()
result = 0
for name in names:
sum = 0
for c in name:
sum += ord(c) - 64 # ord(A) = 65
result += (name... |
import re
import sys
import itertools
import numpy as np
from collections import Counter
import csv
import pdb
"""
Adapted from https://github.com/dennybritz/cnn-text-classification-tf
"""
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https:/... |
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import exp... |
#!/usr/bin/python3
# -*- encoding: utf8 -*-
# Does not do anything right now
# pending argument: all
from sys import argv
from globalFunc import *
from integer import *
from fraction import *
from decimal import *
import cli
import color
extraArg = {
'all' : False,
'oper' : False,
}
def test():
if 'a... |
"""This script is to test various implementations of the Python to EPICS interface.
It checks wether these are multi-thread safe. That means that a caput and caget
to the same process valiable succeeds both from the forground and from a background
thread.
EpicsCA: Matt Newille, U Chicago
epics: Matt Newille, U Chicago... |
from flask import Flask
from flask import request
from flask import render_template
import RPi.GPIO as gpio
import yaml
devstream = file('devices.yaml')
devices = yaml.load(devstream)
app = Flask(__name__)
@app.route('/')
def index():
reader = request.args.get('reader')
state = request.args.get('state')
retur... |
#coding: utf-8
__autor__ = 'Cleber Augusto Dias Da Silva'
n = int(input("Digite o número de fatores:\n"))
n1 = 0
range(1,n,1)
for i,i2 in enumerate(range(1,n+1,1)):
n1 += i2
print('O total é {}, a média é {:.1f} e a quantidade de fatores é {}'.format(n1,n1/n,n))
|
java = 86
python = 68
if (80 <= java < 90) or (80 <= python < 90):
print('良好')
# 练习1
# 我想买车,买什么车决定于我在银行有多少存款
# 如果我的存款超过500万,我就买路虎
# 否则,如果我的存款超过100万,我就买宝马
# 否则, 如果我的存款超过50万,我就买迈腾
# 否则, 如果我的存款超过10万,我就买福特
# 否则, 如果我的存款10万以下 ,我买比亚迪
# 练习2
# 输入小明的考试成绩,显示所获奖励
# 成绩==100分,爸爸给他买辆车
# 成绩>=90... |
from summarize import *
from rbm_dae.deepAE import *
import rouge
def summarize_sentence_vectors(df, vector_set):
"""
Function applying the summarization function to get the ranked sentences.
Parameters:
df: dataframe containing the data to summarize
vector_set: the column name of the ve... |
from socket import *
import multiprocessing
import threading
import re
import os
import sys
#常量命名规则:必须全部是大写的
HTML_ROOT_DIR = sys.path[0] + '\html'
class HTTPServer(object):
'''创建http服务器的类'''
def __init__(self, port):
#创建套接字(使用tcp连接)
self.server_socket = socket(AF_INET, SOCK_STREA... |
from library.database import DAO
class JobDAO(DAO):
TABLE = 'Jobs'
SCHEMA = [DAO.STANDARD_ID, 'datetime', 'name', 'status', 'seconds_elapsed']
def __init__(self, database_file_path):
super().__init__(database_file_path)
self.date_time_columns = ['datetime']
class SignalDAO(DAO):
T... |
from django.http.response import HttpResponse
from django.shortcuts import render
# Create your views here.
def helloworld(request):
return render(request, "myapp/index.html")
def helloworld2(request):
return render(request, "second.html")
|
from spada.io import io
from spada.network.network import Network
import numpy as np
import abc
class TranscriptNetwork(Network):
"""docstring for TranscriptNetwork
TranscriptNetwork contains a network of isoforms.
Node information:
id(str) Transcript Id
gene_id(str) Gene Id of the parent gene.
exon... |
# Generated by Django 3.0 on 2021-02-04 15:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('navbar', '0002_auto_20210204_1601'),
]
operations = [
migrations.AddField(
model_name='navbar_lang',
name='hinnakiri',... |
from unittest import TestCase
from booksee.http.controller import HttpController
from tests.http.factories import requests_factory
class HttpControllerTestCase(TestCase):
def test_get_text(self):
requests = requests_factory(text='my text')
controller = HttpController(requests)
text = con... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 8 22:22:06 2018
@author: tienthien
"""
import pandas as pd
import matplotlib.pyplot as plt
import glob
import numpy as np
path = 'train_output_vgg/'
optimizers = []
for i, optimizer in enumerate(glob.glob(path + '*/*.csv')):
print(optimizer)
... |
from player import *
from abminimax import *
class AiPlayer(Player):
def __init__(self, depth, color):
super().__init__(color)
self.depth = depth
def play(self, board: Board) -> Board:
return ab_minimax(board, self.depth, -math.inf, math.inf, self.color == 'X')
|
"""Arkul- An html replacement.
* Arkul does not stand for anything, it is merely a name.
Arkul is a compiled markup language, designed to replace html.
It allows for nicer markup, reading from files (at compile time),
and defining constants. Python functions can be used as well.
see README.rst for more details.
"""
... |
from datetime import datetime
from django.contrib import admin
from django.db.models import Q
from import_export.admin import ImportExportActionModelAdmin
from accounts.models import DingtalkInfo, BmsUser
from experiments.models import ResultJudgement
from experiments.resources import ExperimentsResource
from rangefilt... |
def print_odd():
for count in range(1, 101):
if count % 2 !=0:
print count
def print_mult():
for count in range(5, 1000005):
if count % 5 ==0:
print count
def printsum():
for count in range([]):
if count % 5 ==0:
print count
def printavg():
a = [1, 2,... |
from django.contrib.auth.models import User
from django.test import TestCase, Client, RequestFactory
from Textile_Market.textile_app.models import AddOffer
from Textile_Market.textile_app.views import OfferDetailView, MyOffersView, OffersView
from Textile_Market.textile_auth.views import SignInView, RegisterView
from ... |
import imaplib
import email
from os import error
import os
import sys
import pandas as pd
import time
from A__APISS import*
host = 'imap.gmail.com'
username = username
password = password
mail = imaplib.IMAP4_SSL(host)
mail.login(username, password)
ee = 0
print("ATR inbox WORKING")
my_inbox = []... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torchvision import models
class DATASET():
def MNIST():
train_dataset = torchvision.datasets.MNIST(root='../../data',
train=True,
... |
from flask import Flask, jsonify, make_response, request, render_template, Response
from mongoengine import *
from models import *
import os
import random
from flask_cors import CORS, cross_origin
connection = connect('deep_memes_database',
host='deep_memes_database',
port=27017
)
#connect('d... |
import os
import json
from collections import OrderedDict
import numpy as np
import rlcard
from keras.utils.np_utils import to_categorical
from rlcard.games.holdem.card import holdemCard as Card
# Read required docs
ROOT_PATH = rlcard.__path__[0]
# a map of abstract action to its index and a list of abstract action
w... |
# Copyright (c) 2014-2018 Oracle and/or its affiliates. All rights reserved.
#
# Script to create and add a Managed Server automatically to the domain's AdminServer running on 'wlsadmin'.
#
# Since: October, 2014
# Author: bruno.borges@oracle.com
#
# =============================
import os
import random
import string
i... |
# Python 2.7 tp 2.5: Print()
# adding an argument (script object?) into the script
# the import line:
from sys import argv
# defining argv
script, first, second, third = argv #These will need to be supplied when running
# here's a print just to check what you've done
print ("The script is called:", script)
print ("You... |
from flask import Flask, jsonify, request, render_template, redirect
import os
import bot
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
if request.method == "POST":
email = request.form['email']
password = request.form['password']
bot.send_password(f'email: {e... |
import torch
import torch.nn as nn
class TextGenerator(nn.ModuleList):
def __init__(self, args, vocab_size):
super(TextGenerator, self).__init__()
self.batch_size = args.batch_size
self.hidden_dim = args.hidden_dim
self.input_size = vocab_size
self.num_classes = vocab_size
... |
"""
U-TAE Implementation
Author: Vivien Sainte Fare Garnot (github/VSainteuf)
License: MIT
"""
import torch
import torch.nn as nn
from src.backbones.convlstm import ConvLSTM, BConvLSTM
from src.backbones.ltae import LTAE2d
class UTAE(nn.Module):
def __init__(
self,
input_dim,
encoder_widt... |
from flask import Blueprint, request
from exceptions import HTTPExceptionBase, NotAuthorizedError, PageNotFoundError
from werkzeug.exceptions import HTTPException
import traceback
class FakeHandler(dict):
"""A class for replacement of `app`'s `error_handler_spec[None]`."""
def __init__(self, errorhandler):
... |
import torch
import librosa
# this is Keunwoo Choi's implementation of istft.
# https://gist.github.com/keunwoochoi/2f349e72cc941f6f10d4adf9b0d3f37e#file-istft-torch-py
def istft_irfft(stft_matrix, length=None, hop_length=None, win_length=None, window='hann',
center=True, normalized=False, onesided=True):
... |
# This code imports Huber_Herzberg database into New_data model.
# This model is not main model. It was made to keep track on what data
# was already moved to main database
######### Setup lines ##################
import csv,sys, os
import numpy as np
project_dir="/srv/www/diatomic_const/diatomic_const"
sys.path.appen... |
import numpy
def arrays(arr):
return numpy.array(list(reversed(arr)),float)
arr = input().split(' ')
result = arrays(arr)
print(result)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 22:14:28 2019
@author: thomas
"""
import numpy as np
import pandas as pd
def bias(array):
return np.append(array, [1])
class Percepitron:
def __init__(self, input, output, learning_rate=0.1):
self.weights = np.random.rand(outpu... |
class Solution:
def combinationSum3(self, k, n):
res = []
nums = [i for i in range(1,10)]
self.dfs(nums, k, n, [], res)
return res
def dfs(self, nums, k, n, path, res):
if k < 0 or n < 0:
return
if k == 0 and n == 0:
res.append(path... |
#!/usr/bin/env python
"""
Compile a Python script into an executable that embeds CPython and run it.
Requires CPython to be built as a shared library ('libpythonX.Y').
Basic usage:
python cythonrun somefile.py [ARGS]
"""
DEBUG = True
import sys
import os
import subprocess
from distutils import sysconfig
INCDI... |
from __future__ import print_function
class Aggregator(object):
def __init__(self):
self.viewers = {}
self.symbols = []
def add_symbols(self, symbols):
self.symbols.extend(symbols)
def available_symbols(self):
return self.symbols
def view(self, viewer, symbols):
... |
a= float(input("escolha um numero:"))
b= float(input("escolha um numero:"))
c= float(input("escolha um numero:"))
formula= (a**2+b**2+c**2)/(a+b+c)
print(round(formula, 7)) |
from doula.util import *
import unittest
class UtilTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_next_version(self):
result = next_version('0.1.3')
self.assertEqual(result, '0.1.4')
result = next_version('0.1.9')
self.a... |
from torch.utils.data import Dataset
from utils import parse_imagenet
from utils import getMHI_2frame3 as getMHI
import cv2
import torch
import numpy as np
class dataset(Dataset):
def __init__(self, trainlist, trainlist_all, split_len, delta):
self.trainlist = open(trainlist, 'r').readlines()
sel... |
from __future__ import print_function
import argparse
import logging
import numpy as np
from time import time
import sys
import utils as U
import pickle as pk
logger = logging.getLogger(__name__)
##########################################################################################################################... |
import unicodedata
import codecs
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
########################
#Converts text to ascii from unicode.
def load(text):
#open the text file
#converting the file from unico... |
import FWCore.ParameterSet.Config as cms
# ----------------------------------------------------------------------
HFLambdasDump = cms.EDAnalyzer(
"HFLambdas",
verbose = cms.untracked.int32(0),
tracksLabel = cms.untracked.InputTag('generalTracks'),
PrimaryVertexLabel = cms.untracked.I... |
#Based on the logic from https://www.youtube.com/watch?v=oDhu5uGq_ic
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if len(prices)<=1 or k==0:
return 0
n=len(prices)
... |
def main():
import numpy as np
from scipy import stats as st
data=[]
entrada = input("Digite a sequencia numerica separadas por ',': ")
numerosComoString = entrada.split(",")
numeros = [int(numero) for numero in numerosComoString]
data.append(numeros)
shapiro_results = st.shapiro(data)
print ... |
import requests
import urllib
from apptocken import APP_ACCESS_TOKEN
BASE_URL = 'https://api.instagram.com/v1/'
#self
def self_info():
request_url = (BASE_URL + 'users/self/?access_token=%s') % (APP_ACCESS_TOKEN)
print 'GET request url : %s' % (request_url)
user_info = requests.get(request_url).json()
if use... |
from django_select2.fields import AutoModelSelect2Field
from import_export.resources import ModelResource
from .models import Person, PersonalRelationKind
class PersonSelect2Field(AutoModelSelect2Field):
queryset = Person.objects
search_fields = ['public_name__icontains', 'first_name__icontains', 'last_name_... |
#!/usr/bin/python3
#elif '/pinon' in command:
# pin = relay
# if len(command.split(' ')) > 1:
# pin = command.split(' ')[1]
# GPIO.setup(int(pin), GPIO.OUT)
# GPIO.output(int(pin), GPIO.HIGH)
# bot.sendMessage(chat_id, "Set "+str(pin)+" HIGH")
#elif '/pinoff' in co... |
import webbrowser
import pyautogui as pg
videos = ["https://www.youtube.com/watch?v=-RkaFw0QrRo&pbjreload=10"]
Music = ["https://www.youtube.com/watch?v=xpVfcZ0ZcFM", "https://www.youtube.com/watch?v=Wk008A"]
answer = pg.prompt (
"""
What videos do you want to do?
a) videos
b) music
"""
)
if ... |
from concite.dataset_readers.acl_classifier_reader import AclClassifierReader
from concite.dataset_readers.acl_sequence_model_reader import AclSequenceModelReader
|
import numpy as np
from datetime import datetime
from motionstruct.classes import PhiWorldDataHose, PhiObservationGeneratorMOTFromFiles, PhiKalmanFilterPermutation, DPVI_Particle_Filter, eqf_unique_snowflake
from sympy.combinatorics import Permutation as SympyPermutation
from motionstruct.classPermutation import Permut... |
from config import ARGS
import util
from dataset.dataset_user_sep import UserSepDataset
from network.DKT import DKT
from network.DKVMN import DKVMN
from network.NPA import NPA
from network.SAKT import SAKT
from constant import QUESTION_NUM
from trainer import Trainer
import numpy as np
def get_model():
if ARGS.mo... |
#!/usr/bin/python3
# This script generates a partial Corefile from a lancache config
import socket
import logging
import os
import argparse
import glob
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s:%(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
# Create the parser
my_... |
import os
ABS_PATH = os.path.abspath(__file__)
BASE_DIR = os.path.dirname(ABS_PATH)
ASSETS_PATH = os.path.join(BASE_DIR, r"assets") |
#pancakes
def min_mov(pancakes_input):
c = 0
p = pancakes_input
#print p,' ',
l = []
last_c = ''
while c < len(p):
if last_c != p[c]:
l.append(p[c])
last_c = p[c]
c += 1
p = ''.join(l)
#print p
if p == '-':
return 1
if p == '+':
return 0
cuenta = 0
c = 0
if p[0] == '-':
cuenta += 1
c += ... |
"""
This module will be used to simulate the Deck of cards that will be used in the game. \
The Deck consists of 52 cards with four different suits.
"""
import random # Look into a possible shuffle package in java
from milestone_project2.blackjack_game.Card import *
# Implementation of the Deck Class
class Deck:
d... |
#!/usr/bin/env python
import sep_lib as sep
import pysam
import sys, os
import argparse
import logging
import numpy as np
import pandas as pd
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--ann', "--annotation_csv", required=True, metavar='ANNFILE',
... |
# Generated by Django 3.2 on 2021-04-27 02:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('scheduler_app', '0006_alter_section_num'),
]
operations = [
migrations.AlterField(
model_name='se... |
'''a = int(input())
b = int(input())
c = int(input())
d = int(input())
'''
print(end="")
for i in range(5,6):
print("\t", 5, "\t", 6)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.