text stringlengths 38 1.54M |
|---|
import numpy as np
def kwadraty(input_list):
output_list = [pow(liczba,2) for liczba in input_list if liczba>0]
return output_list
def wlasciwosci_macierzy(A):
liczba_elementow = A.size
liczba_kolumn = A.shape[1]
liczba_wierszy = A.shape[0]
srednie_wg_wierszy = A.mean(axis=1)
srednie_w... |
from django.db import models
# Create your models here.
class Comment(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=255)
url = models.URLField(blank=True)
text = models.TextField()
created_time = models.DateTimeField(auto_now_add=True)
... |
import socket
import thread
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Ready...')
s.bind((host, port))
print('Bind Ready...')
print('Listening...')
s.listen(1)
def handle_client(client_socket):
while True:
data = client_socket.rec... |
# 4번은 문제 정확성은 다 맞추었는데 효율성 테스트에서 통과하지 못하였다.
# 효율성 테스트 1번까지만 어떻게 열심히해서 통과했는데 더 이상 통과할 수 없었다.
# python이라서 그런건가... c++로 해봐야하나라는 생각이 들기도 했고
# 아니면 아직 효율적으로 짜는 방법을 잘 모르는건가..라는 생각도 했다.
def solution(k, room_number):
answer = []
temp = [0 for i in range(k)]
length = len(room_number)
append = answer.append
in... |
import collections
import unicodedata
from ..base import CaptionList, Caption, CaptionNode
from ..geometry import (
UnitEnum, Size, Layout, Point, Alignment,
VerticalAlignmentEnum, HorizontalAlignmentEnum
)
from .constants import (
PAC_BYTES_TO_POSITIONING_MAP, COMMANDS, PAC_TAB_OFFSET_COMMANDS,
MICROS... |
'''
Find all combinations for a,b,c,d between 1 <= a,b,c,d <= 1000,
that satisfy a^3 + b^3 = c^3 + d^3
'''
class Prob:
@staticmethod
def eval(lo, hi):
abMap = {} # maps: a^3 + b^3 : [a,b]
for a in range(lo, hi+1):
for b in range(lo, hi+1):
leftSide = a**3 + b**3
... |
from django.urls import path
from .views import index, posts
urlpatterns = [
path('', index, name="index"),
path('home/', index, name="index"),
path('<int:post>', posts, name="posts"),
]
|
import logging
from trainer_v2.per_project.tli.bioclaim_qa.eval_helper import solve_bioclaim, batch_solve_bioclaim
from trainer_v2.per_project.tli.qa_scorer.nli_direct import NLIAsRelevance, get_entail_cont, get_entail, \
NLIAsRelevanceRev
from trainer_v2.per_project.tli.bioclaim_qa.path_helper import get_retrieva... |
import shelve, sys
language = sys.argv[1]
INDEX_FILE = "/Users/marc/Desktop/FUSE/ontology_creation/data/patents/%s/idx/index" % language
INDEX = shelve.open(INDEX_FILE)
print "Searching index with %d keys" % len(INDEX.keys())
while True:
print "Enter a key:"
term = raw_input()
if not term:
break
... |
# Generated by Django 2.0.4 on 2018-04-29 09:51
import datetime
from django.db import migrations, models
import magnum_online.functions
class Migration(migrations.Migration):
dependencies = [
('products', '0002_auto_20180429_1507'),
]
operations = [
migrations.AddField(
mode... |
# -*- coding:utf-8 -*-
default_app_config = "operation.apps.OperationConfig" # 配置默认的operation |
from __future__ import unicode_literals
import sys
import time
from prometheus_client import (
CollectorRegistry, Counter, Enum, Gauge, Histogram, Info, Metric, Summary,
)
from prometheus_client.core import (
Exemplar, GaugeHistogramMetricFamily, Timestamp,
)
from prometheus_client.openmetrics.exposition impo... |
def sumar(lista):
if not lista:
return 0
else:
return (lista[0] + sumar(lista[1:]))
print(sumar([1,2,3,4]))
|
import unittest
from unittest.mock import patch
from app.deliver import deliver
from app.meta_wrapper import MetaWrapper
from app.output_type import OutputType
class TestDeliver(unittest.TestCase):
@patch('app.deliver.encrypt_output')
@patch('app.deliver.write_to_bucket')
@patch('app.deliver.send_messag... |
#!/usr/bin/env python
import sys
import os
#sys.path.insert(0, '/home/mossing/code/adesnal')
import run_pipeline_tiffs as rpt
import read_exptlist as re
import numpy as np
matfile_fold = '/home/mossing/modulation/matfiles/'
suite2p_fold = '/home/mossing/data1/suite2P/results/'
def save_meanImg(datafold):
vars_of... |
"""
A function g(n) is defined by:
g(n) = n if n < 3, and g(n) = g(n-1) + 2*g(n-2) + 3*g(n-3) if n >= 3
Write a recursive implementation of g(n) called g_recursive(n).
Write an iterative implementation of g(n) called g_iterative(n).
"""
def g_recursive(n):
n = float(n)
if n < 3:
return n
else:
... |
def extend(perm, n):
if(len(perm) == n):
print('-----', perm)
for k in range(n):
if k not in perm:
perm.append(k)
#print('b4 ext', perm)
extend(perm, n)
#print('a4 ext', perm)
perm.pop()
#print('pop', perm)
extend(perm... |
worlds["Lukin Server"] = "/var/in"
renders["Overworld"] = {
"world": "Lukin Server",
"title": "Overworld",
"rendermode": smooth_lighting,
"dimension": "overworld",
}
renders["Nether"] = {
"world": "Lukin Server",
"title": "Nether",
"rendermode": nether_smooth_lighting,
"dimension": "ne... |
print("Enter 'x' for exit.")
string = raw_input("Enter any string to remove all vowels from it: ")
newstr = string;
print("\nRemoving vowels from the given string...");
#vowels = ('a', 'e', 'i', 'o', 'u');
for x in string:
if x=='a' or x=='e' or x=='i' or x=='o' or x=='u':
newstr = newstr.replace... |
import socket
import os
from Enigma import Enigma
# Client can send and recive files to and from server
# Encryption and Decryption only work on TEXT FILES !
def Recv_File(s):
filename = input("ENTER FILE NAME : ")
if filename != 'q':
#print("this far")
s.send(filename.encode())
#pr... |
import datetime
print(" age calculator ")
birth_year = int(input("Enter your year of birth: \n"))
birth_month = int(input("Enter your month of birth: \n"))
birth_day = int(input("Enter your day of birth: \n"))
current_year = datetime.date.today().year
current_month = datetime.date.today().month
current_day = datetime... |
#!/usr/bin/env python
import asyncio
import websockets
import json
from time import sleep
async def hello(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("Hello world!")
async def test2(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("He... |
while True :
try:
n = int(input("Tentukan banyak bilangan n = "))
nlist = []
for i in range(n):
print('')
print('n ke',i+1)
x = int(input("Masukkan nilai n = "))
nlist.append(x)
print('')
nlist.sort(reverse=True)
print... |
class DynamoDB:
def __init__(self, client):
self._client = client
""" :type : pyboto3.dynamodb """
def create_table(self, table, attribute_definitions, key_schema, iops):
print("Creating DynamoDB table...")
return self._client.create_table(
TableName=table,
... |
"""SQL queries that answer the story questions about cities and cost of living
in Germany. Note: the tables.db file needs to be in the same location as this
python file in order for it to run correctly."""
import sqlite3
from os import linesep
def get_top_density_low_cost(c):
"""select the five cities with the hi... |
import smtplib
gmail_user = 'moffel.piertje420@gmail.com'
gmail_password = 'Welkom01!'
sent_from = 'Karbonkel@student.hu.nl'
to = ['mauro.bijvank@student.hu.nl']
subject = 'Karbonkel ziet dat jij de verkeerde RFID-tag gebruikt!'
body = "Karbonkel steelt je schoenen vannacht!!\n\n- Karbonkel"
email_text... |
import random
class Lutador:
def __init__(self, nome, peso, forca , ginga, arteMarcial="MMA"): # ginga,também chamada de agilidade ou destreza pelos leigos.
if (not( isinstance(nome, str))):
print("Atributo nome tem que ser do tipo string.")
return None
if (not( isinstance(... |
"""
Matchingpennies EEG experiment
"""
study_name = "eeg_matchingpennies"
bids_root = "~/mne_data/eeg_matchingpennies"
deriv_root = "~/mne_data/derivatives/mne-bids-pipeline/eeg_matchingpennies"
subjects = ["05"]
task = "matchingpennies"
ch_types = ["eeg"]
interactive = False
reject = {"eeg": 150e-6}
conditions = ["r... |
#!/usr/bin/env python
import importlib
from nervosum.cli import nervosum_parser
def main() -> None:
args = nervosum_parser.parse_args()
module = importlib.import_module(args.nervosum_module)
module.execute(args) # type: ignore
if __name__ == "__main__":
main()
|
import smtplib
import socket
fromaddr = 'mikkel.raspberry@gmail.com'
toaddr = 'mikkel.svagard@gmail.com'
username = fromaddr
password = 'RaspberryPi'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("gmail.com",80))
yourIP = (s.getsockname()[0])
s.close()
text = "Current IP: " + str(yourIP)
print text
... |
# 数值
# 在Python数值分三类: 整数,浮点数(小数),复数
# 在Python中所有整数都是int类型
a = 10
b = 20
# 在Python中整数的大小没有限制,可以是无限循环大的数
c = 1 ** 100
print(a)
print(b)
print(c)
# 如果数字过长,可以使用下划线作为分隔符
d = 123_456_789
print(d)
# 其他进制的数
# e = 0123 10进制数不能以0开头
# 其他进制的整数,只要数字打印时都是以十进制显示
# 二进制
f = 0b10
# 八进制
g = 0o10
# 十六进制
h = 0x10
print(f)
print(g)
print(h)
... |
from tacotron2_gst.text import symbols
import yaml
"""
Adapted from https://github.com/jaywalnut310/glow-tts/blob/master/utils.py
"""
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def... |
# flake8: noqa
from __future__ import absolute_import
import pytest
def pytest_addoption(parser):
parser.addini('df_cache_root_dir', 'directory of the df_cache_root files')
parser.addini('df_prep_cache_root_dir', 'directory of the df_prep_cache_root files')
from ._fixtures import *
|
from datasets import load_dataset
from transformers import AutoTokenizer, DataCollatorWithPadding
from transformers import TrainingArguments
from transformers import AutoModelForSequenceClassification
from transformers import Trainer
import numpy as np
from datasets import load_metric
raw_datasets = load_dataset("glu... |
#!/bin/python3
import datetime
import network
import os
import sys
import shutil
import zipfile
from getch import getch
from markov import Markov
OUTFILE = "data.txt"
GOODFILE = "good.txt"
APP_NAME = "NotNews"
VERSION_MAJOR = 0
VERSION_MINOR = 0
VERSION_BUILD = 1
# TODOlist:
# TODO:
# Get data from panorama.pub?
#... |
from django.shortcuts import render
# Create your views here.
def music_list(request):
return render(request, 'music/music_list.html', {}) |
def main():
#escribe tu código abajo de esta línea
import math
peso = float(input("Peso en kg: "))
altura = float(input("Altura en m: "))
if peso>0 and altura>0:
índice= (peso)/(altura**2)
if índice<20:
print ("PESO BAJO")
elif 20 <= índice < 25:
print ("NORMAL")
elif 25 <= índi... |
from django.db.models.query import QuerySet
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from backend_app.serializers import SubjectSerializer, TitleSerializer
from backend_app.models import Subject, Title
class SubjectViewSet(ModelViewSet):
queryset = Subject.objects.all()
... |
import simpy
import random
import math
import numpy as np
SIM_TIME = 10 * 60 * 60 * 1000
FRAME = 1000
packet_number = 0
TIME_BETWEEN_PACKETS = 15 * 60 * 1000
EXPOVARIATE = 0
RANDINT = 1
RANDOMIZATION_SCHEME = EXPOVARIATE
TX_SLEEP_RATE = 1/1000
RX_SLEEP_RATE = 1/1000
TX_SLEEP_RANGE = (500, 750)
RX_SLEEP_RANGE = (500,... |
from django import template
register = template.Library()
@register.filter
def addCss(value, arg):
return value.as_widget(attrs={'class':arg})
|
assert (True and True) == True
assert (True and False) == False
assert (False and True) == False
assert (False and False) == False
assert (True or True) == True
assert (True or False) == True
assert (False or True) == True
assert (False or False) == False
assert (not True) == False
assert (not False) == True |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 22:38:43 2020
@author: hoale
"""
"""
This file contains solver for feasibility problem by GUROBI (2nd MILP subproblem)
"""
import gurobi as grb
""" Creation of MILP model with constraints """
def _create_model(job_num, machine_num, job_ids, r... |
"""ecomproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Dos Santos Julien'
import random
from Tkinter import *
from tkMessageBox import *
class De(StringVar):
def __init__(self):
StringVar.__init__(self)
self.set(random.randrange(1,6))
self.keep = IntVar()
def lancer(self):
... |
from setuptools import setup
import os, re
with open("README.md", "r") as fh:
long_description = fh.read()
def get_version() -> str:
"""Get __version__ from __init__.py file."""
version_file = os.path.join(os.path.dirname(__file__), "kivg", "__init__.py")
version_file_data = open(version_file, "rt", ... |
import django_filters
from django.db.models import Q
from .models import Articles
import datetime
class ArticlesFilter(django_filters.rest_framework.FilterSet):
"""
文章的过滤类
"""
time = django_filters.CharFilter(method='time_filter')
category = django_filters.NumberFilter(method='category_filter')
... |
import logging
from PyQt4.QtGui import QDialog, QVBoxLayout
from gui.widgets.itemwidget import ItemWidget
from gui.widgets.ui_basesettingsdialog import Ui_BaseSettingsDialog
logger = logging.getLogger('console')
class WellSettingsDialog(QDialog, Ui_BaseSettingsDialog):
'''
classdocs
'''
def __init... |
#!/usr/bin/python
import pylsdj
import sys
import os.path
# check argv length
if (len(sys.argv) < 4):
sys.exit('Usage : python patcher.py ([SAVEFILE.sav] [#TRACKNUMBER] or [SONGFILE.srm|.lsdsng]) [SYNTH.snt] [#SYNTHNUMBER]')
# get file patcher
savpath = sys.argv[1]
ext = os.path.splitext(savpath)[1]
# check data... |
from kafka import KafkaConsumer
import json, datetime
from clickhouse_driver import Client
consumer = KafkaConsumer('analytics', auto_offset_reset='earliest', bootstrap_servers=['localhost:9092'], api_version=(0, 10), consumer_timeout_ms=1000, value_deserializer=lambda m: json.loads(m.decode('utf-8')))
client =... |
from models import RobotKiller
from django.utils import timezone
from django.core.exceptions import PermissionDenied
max_visits = 100
min_seconds = 300
def ip_bot_filter(request):
allowed_ips = ['10', '127.0.0.1'] # localhost
#allowed_ips = ['10', '60.205.107.184', '211.144.0.55']
if request.META.has_ke... |
import datetime
from dateutil.parser import parse
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.template.d... |
import os
from zipfile import ZipFile
from datetime import datetime
import pandas as pd
import numpy as np
import re
folder = '/Users/kayinho/git/hispanic/'
extension = ".zip"
def unzip_all(dir):
for item in os.listdir(dir):
if item.endswith(extension):
path = folder+item
with Zip... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 13:45:07 2019
DATA PRE-PROCESSING AND MARKOV MODEL
@author: Murphy
"""
import nltk as tk
from numpy.random import choice
# read in all text files to a string
unique_words = []
all_words = []
sentences = []
def loadText(filename):
clean = ""
... |
"""
In de klasse meet_controller worden nieuwe Dashboardviews en eenheidControllers aangemaakt.
De master wordt hier doorgegeven aan Dashboardview. Alle waarden van het Dashboard worden hier opgevraagd
en maken met deze waarden het programma interactief.
Created: 10-11-2018
Author: Jeloambo
Version: 1.2.6
"""
from co... |
#encoding:gbk
# __file__平台在win32平台的值是完整路径
# 在linux平台是文件名
print __file__ |
# 导入必要的模块
from gcforest.gcforest import GCForest
def init():
x_train = []
y_train = []
x_test = []
y_test = []
for x in range(1, 3):
with open('./subfile_' + str(x) + '_train.csv', mode='r', encoding='utf8') as fpto_train:
lines = fpto_train.readlines()
for ro... |
from data_structures_algorth.challenge_stack_and_queue.stack_queue import Queue, QueueIsEmptyException
class AnimalShelter:
def __init__(self):
"""
will construct 2 objects cat and dog as instances of queue class
"""
self.dog = Queue()
self.cat = Queue()
def ... |
import matplotlib
matplotlib.use('Agg')
import os
import datetime
import time
import sqlite3
import pywt
from pylab import *
import fnmatch, gzip, os, re, sys, time
def approx(x, wavelet, level):
ca = pywt.wavedec(x, wavelet, level=level)
ca = ca[0]
return pywt.upcoef('a', ca, wavelet, level, take=len... |
# https://www.codewars.com/kata/54df2067ecaa226eca000229
def f(n):
if(isinstance(n, int) and n>0):
return round((1+n)*n/2)
else:
return None
|
from gurobipy import *
import numpy as np
def dist(loc, i, j):
return np.linalg.norm(np.array(loc[i])-np.array(loc[j]))
# Create a new model
m = Model("Minimizing the Maximum Within-Block Distance")
#locations of worksites
loc = [[277, 302], [340, 304], [432, 281], [463, 171], [467, 154], [573, 225], [481, 237]... |
import torch
import VGG
from model import *
from datasets import *
from torchvision.utils import save_image,make_grid
import os
from PIL import Image
os.environ['CUDA_VISIBLE_DEVICES'] = "3"
def test(args):
# parameters
cont_img_path = args.cont_img_path
style_img_path = args.style_img_path
model_chec... |
#绘制三角螺旋线
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
import pickle
f = open('pos_recoder_0.pkl', 'rb')
pos_recoder = pickle.load(f)
ax = plt.axes(projection='3d')
xdata = [a[0] for a in pos_recoder]
ydata = [a[1] for a in pos_recoder]
zdata = [-a[2] for a in pos_recoder]
ax.sca... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-08-04 12:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0006_auto_20160801_1540'),
]
operations = [
migrations.RemoveField... |
"""
solution
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
"""
# 1.
result = [i**2 for i in range(1,101) if i %2 == 0]
print(result)
# 2.
string1 = 'ABC'
string2 = 'XYZ'
result = [c1+c2 for c1 in string1 for c2 in string2]
print(result) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RESTful API Python 3 Flask server
"""
import os
import pretty_errors
from restapi.confs import PRODUCTION
from restapi.server import create_app
from restapi.utilities.logs import log
# Connection internal to containers, proxy handle all HTTPS calls
# We may safely ... |
class AttributeDictionary(object):
def __init__(self, *args, **kwargs):
d = kwargs
if args:
d = args[0]
super(AttributeDictionary, self).__setattr__("_dict", d)
def __setattr__(self, name, value):
self[name] = value
def __getattr__(self, name):
if name ... |
# An O(n^2) solution
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
if s == '':
return ''
ord_a = ord('a')
# NOTE We redefine `s` here.
s = [ord(x) - ord_a for x in s]
counter = [0]*26
... |
def startCommand(bot, update):
bot.send_message(chat_id=update.message.chat_id, text='Привіт 👋🏿:, человек 😑 ')
|
import random
import string
robot_names = set()
class Robot:
def __init__(self):
random.seed()
self.name = self.generate_name()
def generate_name(self):
letters = ''.join(random.sample(string.ascii_uppercase, 2))
digits = ''.join(random.sample(string.digits, 3))
self.... |
# Axel '0vercl0k' Souchet - May 16 2021
import requests
import argparse
def main():
parser = argparse.ArgumentParser('Poc for CVE-2021-31166: remote UAF in HTTP.sys')
parser.add_argument('--target', required = True)
args = parser.parse_args()
r = requests.get(f'http://{args.target}/', headers = {
... |
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import datetime
import glob,pickle,random
import nagdefs as nd
try:
import argparse
flags = argparse.Argument... |
# Handle Tecan Gemini Carriers and Racks
# Loads data from Carriers.cfg
import pprint
import os
import click
class Carrier(object):
instance = None
def __init__(self):
self.checksum=None
self.timestamp=None
self.username=None
self.carriers=[]
self.racks=[]
self.... |
import bpy
import bgl
import taichi as ti
import numpy as np
import tina
def calc_camera_matrices(depsgraph):
camera = depsgraph.scene.camera
render = depsgraph.scene.render
scale = render.resolution_percentage / 100.0
proj = np.array(camera.calc_matrix_camera(depsgraph,
x=render.resolution_x... |
import json
from functools import partial
from dateutil.parser import parse
from xml.etree import ElementTree as ET
from pyramid.decorator import reify
from intranet3.asyncfetchers.base import (BaseFetcher, CSVParserMixin,
SimpleProtocol, BasicAuthMixin,
... |
#!/usr/bin/env python
import os
import glob
cur_dir = os.getcwd()
dir_content = os.listdir(cur_dir)
for content in dir_content:
print content
def createTestDir(dir_name):
os.mkdir(dir_name)
os.chdir(dir_name)
f = open('testfile.txt','w')
f.close()
os.listdir(dir_name)
print("Running test dir first time")
di... |
from models.company import Company
class DataStorage:
def __init__(self):
self.companies = []
self.jobs = []
self.job_tags = [] # List of tuples (job_tag, id)
def add_job_tag(self, j):
if j not in self.job_tags:
self.job_tags.append(j)
return True
... |
#!/usr/bin/env python
# coding: utf-8
import nfc
import time
import vlc
import os
#初期設定
p = vlc.MediaPlayer()
count = 0
loop = 0
#財宝を判定する
def connected(tag):
global count
global loop
print str(count+1) + "回目"
judge = str(tag.identifier).encode('hex').upper()
#本物の財宝の場合
if judge == '04808D728... |
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.aws_hook import AwsHook
class StageToRedshiftOperator(BaseOperator):
ui_color = '#358140'
template_fields = ("s3_path",)
@apply_defau... |
import numpy as np
from math import ceil, floor
def rolling_window(image, window_size, stride):
'''
Image is a (X, Y) size array to apply rolling window on
window_size is a tuple containing (winX, winY)
stride is a tuple containing (dX, dY)
Returns an array of size (nX, nY, winX, winY)
whe... |
'''
From https://github.com/colinskow/move37/blob/master/dqn/lib/wrappers.py
'''
import cv2
import gym
import gym.spaces
import numpy as np
import collections
import asyncio
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops ... |
from rest_framework import routers, viewsets, serializers
from daphne import models as m
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = m.Page
class TestViewSet(viewsets.ModelViewSet):
queryset = m.Page.objects.all()
serializer_class = PageSerializer
router = routers.Defau... |
def solution(s):
answer = []
for string in s.lower().split(' '):
answer.append(string.capitalize())
return " ".join(answer) |
from django.test import TestCase
from datetime import datetime, date
from django.utils.timezone import make_aware
from ..models import Company, RawPrices
class CompanyModelTests(TestCase):
def test_is_empty(self):
"""初期状態では何も登録されていないことをチェック"""
saved_companys = Company.objects.all()
self.as... |
# break 強制結束迴圈
# while 布林值:
# break
# 程式範例
# n=1
# while n<5:
# if n==3:
# break
# n+=1
# print(n) # 印出 3
# for 變數名稱 in 列表/字串:
# break
# continue 強制繼續下一圈
# while 布林值:
# continue
# for 變數名稱 in 列表/字串:
# continue
# 程式範例
# n=0
# for x in [0,1,2,3]: # x 會跑 4 圈, 分別為 0, 1, 2,... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:梨花菜
# @File: 链表.py
# @Time : 2020/3/28 20:29
# @Email: lihuacai168@gmail.com
# @Software: PyCharm
class Node:
def __init__(self, data_val):
self.data_val = data_val
self.next_val = None
class LinkedList:
def __init__(self):
self.... |
#!/usr/bin/env python
'''
This file defines functions for NGS Tat analysis pipeline
'''
from __future__ import division
import pandas as pd
import numpy as np
from collections import Counter
import itertools
from scipy import interp
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from s... |
#!/usr/bin/env python3
"""Meant to be run from inside python-test-runner container,
where this track repo is mounted at /python
"""
import argparse
from functools import wraps
from itertools import zip_longest
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from typing im... |
import mido
class Msg:
def __init__(self, T=0, c=0, n=0, v=0):
self.track = T
self.channel = c
self.note = n
self.velocity = v
class Msgs:
def __init__(self):
self.msgs = []
def append(self, newMsg):
self.msgs.append(newMsg)
def hasMsgDown(self, channel, note,... |
'''
Source : https://pyformat.info/
'''
# single symbol multiline comment control
'''
# just alignment
print('{0:>7}'.format('zip','hello'))
print('{1:<7}'.format('zip','hello'))
print('{1:^7}'.format('zip','hello'))
# text is left align by default
print('{0:10}'.format("hello"))
# numbers are right align
print('{0:... |
__author__ = 'sandeeps'
#application_url = "https://commcareqa.tangoe.com/manage/login/login.trq"
#application_url = "https://qa5.traq.com/manage/login/login.trq"
application_url = "https://qa1cmd.tangoe.com/manage/login/login.trq"
input_path = 'C:\Users\sandeeps\PycharmProjects\CodeFestS\com\Testdata.csv'
output_path... |
import wmi
def show_wmi_classes(w):
# See list of classes
for class_name in w.classes:
if 'User' in class_name or 'Account' in class_name:
print("Class: " + str(class_name))
def show_wmi_methods(item):
print(item)
for k in item.methods.keys():
print("... |
#!/usr/bin/env python3
import argparse
import os
import json
import threading
from queue import Queue
from subprocess import check_output
from youtube import Channel
from youtube.offliberty import Offurl, Offget
def getVid(url, path, vid = False, name = '', thumb = False, quiet = False):
o = Offget(url, vid = vid)
i... |
import sys
def is_def(s): return s[0] == '@'
def is_ref(s): return s[0] == '!'
def is_bin(s):
if len(s) < 2: return False
else: return s[1] == 'b'
def is_byte(x):
try:
if is_bin(x):
int(x, 2)
else:
int(x)
return True
except:
return False
def to... |
from flask_restplus import fields
from api import api
add_address = api.model("add_address", {
"name" : fields.String(),
"address" : fields.String(),
"city" : fields.String(),
"state" : fields.String(),
"country" : fields.String(),
"pincode" : fields.String(),
"phone_numbers" : fields.List(... |
'''
Created on Apr 30, 2009
@author: pmackenz
'''
class MyClass(object):
def __init__(self,v, s):
print("entering __init__({})".format(v))
self.val = v
self.my_name = str(s)
def __len__(self):
print("entering __len__()")
return len(self.val)
def __add... |
"""
"""
import sys, os, pygame, time, random
import battle, get_pokemon_info
from PIL import Image
def load_resources(screen = None, my_pk = None, opp_pk = None):
"""my_pk and opp_pk must be the national dex numbers
of the pokemon"""
# State machine functions
res["show moves logic"] = show_m... |
from ..parser.Parser import Parser, ParserUtils
from ..schema.PgView import PgView
class CreateViewParser(object):
@staticmethod
def parse(database, statement):
parser = Parser(statement)
parser.expect("CREATE")
parser.expect_optional("OR", "REPLACE")
parser.expect("VIEW")
... |
#!/usr/bin/env python
import rospy
from std_srvs.srv import Empty
from gazebo_msgs.msg import ModelState
from gazebo_msgs.srv import SetModelState, GetModelState
from geometry_msgs.msg import Quaternion
from sensor_msgs.msg import LaserScan
from pyquaternion import Quaternion as qt
def create_model_state(x, y, z, an... |
import os
# Part 1: Find 2 numbers that add to 2020 and multiply them
dirname = os.path.dirname(os.path.abspath(''))
filename = os.path.join(dirname,'inputs','d01_input.txt')
with open(filename, "r") as f:
lines = f.read().splitlines()
for num in lines:
current_number = int(num)
#print(current... |
import yfinance as yf
class Asset:
def __init__(self, tiker):
"""
Инициализируем переменную tiker
:param tiker: Тикер запрашиваемой котировки
"""
self.tiker = yf.Ticker(tiker)
self.tiker_name = tiker
def get_hist_last_1_day(self):
"""
Получает ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.