index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
12,700 | 160c8da1a3830f5850a0cc5e3bb3eb3007bfb9a8 | #
# Exemplo de como criar classes
#
class minhaClasse():
"""Put inherited melhods, from another class, between brackets
The constructor, for pathern, in the beggining of the class is
__init__(self). This indicates that all methods in my class will
receive the object self, but the python will pass along ... |
12,701 | ecdb5a5c819611868fc90b42225aae0ab3d48fe3 | import sys
from Fund import Fund
from TAA import TAA
# Fonlista som argument
if len(sys.argv) > 1:
fundListPath = str(sys.argv[1])
else:
fundListPath = input("Enter path to fundlist: ")
with open(fundListPath, 'r') as handle:
fundList = []
print("Fetching data", end='', flush=True)
for line in h... |
12,702 | b6154c2cf463da0d511f2928af25d6df97f96199 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import datetime
from functools import total_ordering
import logging
import io
import sys
import csv
import tempfile
import pandas as pd
from dateutil import rrule
from dateutil.relativedelta import relativedelta
DEFAULT_MONEY_TXT_PATH = os.path.join(... |
12,703 | acedada367c6aeb6dc9b693a19b043a63b3d77e7 | from django.db import models
import caching.base
# Our apps should subclass ManagerBase instead of models.Manager or
# caching.base.CachingManager directly.
ManagerBase = caching.base.CachingManager
class ModelBase(caching.base.CachingMixin, models.Model):
"""
Base class for doozer models to abstract some ... |
12,704 | f1a173b36500a7d67a74ca297d17dd796e4975b4 | from numpy import sqrt
import numpy as np
class Regression_lineaire:
def __init__(self, x:np.array, y:np.array, dy=1):
assert x.shape == y.shape
self.x = x
self.y = y
self.dy = dy if isinstance(dy, np.ndarray) else np.ones(x.shape[0]) * dy
self._delta = (1 / dy**2).sum() * ... |
12,705 | 73a0fe5400c9332e050f6b61ca22c18c5defa640 | #!/usr/bin/env python3
# -- coding utf-8 --
if __name__ == "__main__":
fileOut = open("e10.txt", "w")
fileIn = open("e10.txt", "r")
strWrited = "Hello World.\n"
print("write:" + strWrited, end = "")
fileOut.write(strWrited)
strWrited = "012345\n"
print("write:" + strWrited)
fileOut.wr... |
12,706 | 2b4854813ba48b7b1bd13ab62f32a5dd87a21fa2 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-18 11:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_effectsmodel'),
]
operations = [
migrations.AlterField(
... |
12,707 | a30d7920c12d21218409534f16d0d6ed3f876fff | from karel.stanfordkarel import *
def main():
i = 0
while True:
# repeat
i = i + 1
if beepers_present(): # At a black square
pick_beeper() # flip the color of the square
turn_left() # turn 90° left
move() # move forward one unit
else: #... |
12,708 | ea49bc30c141a2b749a0ba319d2bdcc642f801b8 | # -*- coding: iso-8859-15 -*-
from flask import Flask
import pyodbc
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = pyodbc.connect(app.config['DSN'])
from views import *
if __name__ == "__main__":
#app.run(host='0.0.0.0', port=8080)
app.run(debug=True)
|
12,709 | ef09bd322d26d5b84f1ea31dc19e508e27b576a6 |
n,m=map(int,input().split())
s=input()[:n]
s=list(s)
#print(s)
d=""
while m>0:
for j in range(len(s)-1):
if (s[j]=='B' and s[j+1]=='G'):
s[j],s[j+1]=s[j+1],s[j]
j+=1
j+=1
m-=1
print(s)
for i in range(len(s)):
d+=s[i]
print(d)
|
12,710 | ff1acbcda057aa435a72624424e385566c6e8167 | import PySimpleGUI as sg
from utils import find_all_subdirectories, find_files
import datetime
layout = [
[sg.Text('File Explorer - Find files/directories on your drive', font=("Arial", 20))],
[sg.Text('Choose the path', font=("Arial", 14)), sg.InputText("", size=(40, 1), font=("Arial", 14), key='path',
... |
12,711 | c318a78fdbe26b21499ca0d5aac77d68ebeb32f7 | from albumGrabberOOP import albumGetter
instance = albumGetter()
instance.start() |
12,712 | 4389879084e4ad90d71d59c59b9d8346ae79aaf7 | import os
import sys
from subprocess import Popen, check_call
def init_parser(parser):
parser.add_argument('name', type=str, help='Cluster name.')
parser.add_argument('--jar', type=str, help='New JAR.')
parser.add_argument('--zip', type=str, help='New ZIP.')
parser.add_argument('--zone', '-z', default... |
12,713 | 52200136624ddd0ce310a5da6f0767550357714b | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
retList = []
for i in arr2:
## 利用remove自动寻找值的特性,一直找到没空为止就跳出循环
while True:
try:
arr1.remove(i)
retList.append(i)
... |
12,714 | a8ebe9dac46494f56d8499c851a91fe1e6bcba12 | from django.apps import AppConfig
class GestionmachinesConfig(AppConfig):
name = 'gestionMachines'
|
12,715 | af9e00cb7754c7a05f15c8c2672b5555b86897a7 | class Solution:
def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int:
matrix1 = [[0 for _ in range(sideLength)] for _ in range(sideLength)]
for i in range(height):
for j in range(width):
matrix1[i%sideLength][j%sideLength] -=... |
12,716 | 2bb03149ab7de8b7a576dd7f20b248d2dc1e0c3c | print("How old are you?",end = ' ')
age = input()
name = input("What's your name? ")
print(f"Your name is {name}, your age is {age}.")
|
12,717 | 613f2b62b192a0ad34b481344ae5bb5647651673 | import string
class Cesar:
def __init__(self, word, key):
self.word = word
self.key = key
def get_shifr(self):
shifrword = ""
self.key = self.key%26
for i in self.word:
c = ord(i)
if i in string.ascii_letters:
ci = (c + self.key)
... |
12,718 | fa63c99853a90e8caa517269883cb4f119037e3b | from django.shortcuts import redirect
from django.views import View
class logout(View):
def get(self, request):
request.session.clear()
return redirect('/authen/login/') |
12,719 | 176a4b48fa34583cd8cd740486b23d11cc840f4c | from django.urls import reverse_lazy
from django.views.generic import CreateView, ListView, DetailView
from .models import Post
class PostCreateView(CreateView):
model = Post
fields = ('title', 'content')
success_url = reverse_lazy('index')
class PostListView(ListView):
model = Post
class PostDet... |
12,720 | 0596ab37032b552533aeef5f5713ba67e37d3ed0 | import sys
'''Displays any image file that PIL can understand. Doesn't display
transparency well, so try showing that on a web browser.'''
try:
# This works on the Linux machines
from PIL import Image
except:
print "Couldn't import PIL.Image"
sys.exit()
def showimage(filename):
img = Image.o... |
12,721 | 5b229b01cca71c88c687d03c2a97a54746885deb | import sys
def decode(code, key):
decoded_string = str()
for i in code:
decoded_string += key[int(i) - 1]
return decoded_string
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if not test:
continue
key = test.strip().split('|')[0]
code = test.strip().split('|')... |
12,722 | 204661714d8c151a1cc3a77f64837a715e1e74cd |
import time
from util.util_list import *
from util.util_tree import *
import copy
import collections
class Solution:
def maximumWealth(self, accounts: [[int]]) -> int:
mx = 0
for account in accounts:
mx = max(mx, sum(account))
return mx
stime = time.t... |
12,723 | 6a086ee43581e230337032e2d6f2af2a3eda43cb | # Copyright (c) 2021 - present / Neuralmagic, 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/LICENSE-2.0
#
# Unless required b... |
12,724 | d8f9c39a541b3a9b67c6533f69a8f2df4c453817 | """Data related to the development."""
import typing as t
from datetime import datetime
from mimesis.data import (
LICENSES,
OS,
PROGRAMMING_LANGS,
SYSTEM_QUALITY_ATTRIBUTES,
)
from mimesis.enums import DSNType
from mimesis.providers.base import BaseProvider
from mimesis.providers.internet import Inte... |
12,725 | c3c4e4f8c6425dac1e5dd9fb8a795f929153b01a | eat_activeusers_daily = """
SELECT %s s_day, count(distinct(user_id)) active_users
FROM log_record
WHERE log_time_in_millisecond >= %s
AND log_time_in_millisecond < %s
AND user_id IS NOT NULL
"""
insert_eat_activeusers_daily = """
insert into huoli_eat_activeusers_daily_test values (%s, %s, now... |
12,726 | a3e80a46cd3e66c362e76a30db5c2ac423b65edb | from .errors import *
from flask import jsonify, send_file
from app import db
from . import api, get_query_string
from app.main.models import *
from app.main.controllers import GSECMonthlyRecon, GSECMonthlyReconReport
# gsec code section #############################################
@api.route('/gseccodes', methods=[... |
12,727 | ce3288817e0b1a89b61d4cb616332c65d83de8b0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-24 14:08
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("foirequest", "0007_auto_20171121_1134"),
]
operations = [
migrations.AlterModelOptio... |
12,728 | 8fc532edc796e5785ca98f3d1aa5e02a309874cc | import json
import grpc
import numpy as np
import tensorflow as tf
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
hostport="localhost:8500"
channel = grpc.insecure_channel(hostport)
stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
requ... |
12,729 | 72b4efc7c67b7f4c4b52d2cca39d5e9f4af85178 | import csv
import os
import numpy as np
import pandas as pd
from pandas import DataFrame
from math import log, exp, pi, sqrt
from scipy.stats import norm
import collections
from datetime import date
from recordtype import recordtype
from scipy.interpolate import make_interp_spline, BSpline
import matplotlib.pyplot as p... |
12,730 | 066d6d835b5c0bf65d9b3dc17708b472f187824b | #add multiple values to a dictionary key with other rules provided
def update_dictionary(d, key, value):
if key in d.keys():
d[key].append(value)
elif 2 * key in d.keys():
d[2 * key].append(value)
else:
d[2 * key] = [value]
#second option
def update_dictionary(... |
12,731 | 1249a2b66535ef41420c7cd4ee017e610ddefc55 | '''
公告所有接口
'''
import os
from conf import settings
from db import models
def get_all_school_interface():
# 1、获取学校文件路径
school_dir = os.path.join(
settings.DB_PATH, 'School'
)
# 2判断文件夹是否存在
if not os.path.exists(school_dir):
return False, '没有学校,请联系管理员'
# 3文件夹存在获取文件夹中所有文件的名字
s... |
12,732 | 1e43146ff055cba6f3900ab8dab6acedb0e2c809 | import pathlib
import random
import copy
from typing import List, Optional, Tuple
Cell = Tuple[int, int]
Cells = List[int]
Grid = List[Cells]
class GameOfLife:
def __init__(
self,
size: Tuple[int, int],
randomize: bool=True,
max_generations: Optional[float]=float('inf')
) -... |
12,733 | d65fa3a18b92d5ec46e94ad2e4489d97fe111b39 | from re import sub
from transliterate import translit, exceptions
def make_url(title):
url = 'default_url'
try:
url = sub(r'_| |!|\?|\.|,|\'|\"|;|:', '-', translit(title, reversed=True).lower())
except exceptions.LanguageDetectionError:
url = sub(r'_| |!|\?|\.|,|\'|\"|;|:', '-', title.lowe... |
12,734 | 95f077bafc8af35cd4f4f292f63f6aca4531336a | import time
from random import randint
def log(function):
def add_log(*args, **kwargs):
f = open("machine.log", "a")
start_time = time.time()
test = function(*args)
f.write("(rpichon)Running: {}\t\t[ ".format(function.__name__))
f.write("exec_time = {:.3f} ms ]\n".format(t... |
12,735 | 867bec25c0d83ab5aed558a6d2de255d00e5f4f1 | import time
import requests
from fake_useragent import UserAgent
ua = UserAgent(verify_ssl=False)
headers = {
'User-Agent' : ua.random,
'Referer' : 'https://accounts.douban.com/passport/login_popup?login_source=anony'
}
s = requests.Session()
# 会话对象:在同一个 Session 实例发出的所有请求之间保持 cookie,
# 期间使用 urllib3 的 connection pool... |
12,736 | 1e79f75f2171cc1dc550697005395f5f101f73ce | from consul import Consul
from typing import Any, Union, Mapping
from dataclasses import dataclass
from resource_it import Resource, ResourceNotFoundError
import cfg_it
import log_it
log = log_it.logger(__name__)
@cfg_it.props
class cfg:
consul_host: str = "localhost"
class Consul_KV(Resource):
@dataclass
... |
12,737 | 75ace70625d0652fb163b4239d9182f3e84496dd | import paho.mqtt.client as mqtt
from settings import Settings, historical_settings
import json
import sqlite3
from printer import a_print
from config import Config
class MyMQTTClass(mqtt.Client):
def on_connect(self, mqttc, flags, rc):
if rc==0:
print("connected OK")
else:
... |
12,738 | 337d84fe3ca5b731386fd9825917d1ebca264863 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Image deformation using moving least squares
@author: Jian-Wei ZHANG
@email: zjw.cs@zju.edu.cn
@date: 2017/8/8
@update: 2020/9/25
@update: 2021/7/14: Simplify usage
@update: 2021/12/24: Fix bugs and add an example of random control points (see `demo2()`)
"""
import ... |
12,739 | ad49c2496f76f4e471583393499a1d32fc2927df | # -*- coding: utf-8 -*-
import unittest
from init_spark.spark_demo01 import rdd_key_operation
from common import spark_context as sc
class MyTestCase(unittest.TestCase):
def test_rdd(self):
rdd_key_operation()
sc.stop()
self.assertEqual(True, True)
if __name__ == '__main__':
unittest.m... |
12,740 | be9309f051c61cf0c0df1337ddbaa43950cd96f0 |
def find_a_seat(n, lst):
try:
return next(i for i,l in enumerate(lst) if l <= (n/(len(lst)))/2)
except:
return -1
|
12,741 | 012fb2203cf2ae92cbeb29462a21f6e01c06eb15 | import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from moviepy.editor import VideoFileClip
from IPython.display import HTML
import helper_calibration as hpcal
import helper_image as hpimg
from line import Line
import pipeline as pp
line_left = Line()
line_right = Line()
de... |
12,742 | be570af62d88fc4572dec8a5c046cc19eee5069f | from glob import glob
import os
from scipy.io import loadmat
import pickle
import torch
class LabelVecWriter:
def __init__(
self,
annot_dir_path,
annot_file_fmt,
spect_file_fmt,
labelvec_file_fmt,
windowed_spects_dir_path,
windowed_labelvec_dir_path,
... |
12,743 | f7337323801fea3fbbbdde49bf1b562117e88810 | from .health import HealthResource
from .google_translate import GoogleTranslate_v3 |
12,744 | a2acc3e73f50293b05ae4e85da30d5c4d25073d6 | #Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\packages\entosis\entosisConst.py
from carbon.common.lib.const import HOUR
EVENT_TYPE_TCU_DEFENSE = 1
EVENT_TYPE_IHUB_DEFENSE = 2
EVENT_TYPE_STATION_DEFENSE = 3
EVENT_TYPE_STATION_FREEPORT = 4
EVENTS_TYPES_WITH_OCCUPANCY_BONUS = (E... |
12,745 | ed0f29d05251b88b162bf9a440ace32af4de74de | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 22:34:55 2019
@author: bakunobu
"""
import numpy as np
N = int(input('Choose the time gap to calculate ATR: '))
h = []
l = []
close = []
h = h[-N:]
l = l[-N:]
prev_close = close[-N-1:-1]
day_diff = h-l
h_diff = h - prev_close
l_diff = prev... |
12,746 | 96f68a1fa43daae9421fea3a893583730e1e0a63 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Revenue and cost distribution
data11 = pd.read_csv('Results_HPC/Results_Stochastic_yearly_HPC.csv')
data22 = pd.read_csv('Results_HPC/Results_Deterministic_yearly_HPC.csv')
data11 = data11.sort_values('scenario')
data11 = data11.reset_index(drop=T... |
12,747 | 36bad3528e526eee534071f668279e5ce25291b0 | """empty message
Revision ID: 15c83b7c1422
Revises: 219558c6bdf3
Create Date: 2019-03-18 06:39:54.952596
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '15c83b7c1422'
down_revision = '219558c6bdf3'
branch_labels = None
depends_on = None
def upgrade():
# ... |
12,748 | 2f7fd01e418edfce285ea3076324b78974b9d0ee | from utils import get, update, increment, decrement
|
12,749 | 6cb6466f77b818365df3a296b3a178b1c644bc0f | '''
4. Представлен список чисел.
Необходимо вывести те его элементы, значения которых больше предыдущего, например:
src = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
result = [12, 44, 4, 10, 78, 123]
'''
src = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
result = [src[i] for i in range(1, len(src)) if... |
12,750 | cad3ebd4611cc70fc517df7eeac009d0af62942b | from setuptools import setup, find_packages
import flake8diff
def read(path):
with open(path, 'rb') as fid:
return fid.read().decode('utf-8')
setup(
name="flake8-diff",
version=flake8diff.__version__,
url="http://dealertrack.github.io",
author="Dealertrack Technologies",
author_email... |
12,751 | 8341bc7ba186d4e8b0f54258cebbcaec21bb475e |
frase_usuario = input("Introduce un texto: ")
mayusculas = 0
for letra in frase_usuario:
if letra.isupper():
mayusculas += 1
print("Hay {} mayusculas". format(mayusculas))
|
12,752 | 63561652adb990700b30a14447aa9cb6a2b5a8d8 | '''A program to split the RFID string into csv format: PIT, antenna, date, month, year, hour, minute, second
November 2018
@authors: James Eapen (jpe4)'''
import re
class Timestamp():
def __init__(self, line = ''):
if len(line) == 0:
self.pit = ''
self.antenna = ''
self... |
12,753 | 1c9c1a6f0b22d6fef4587a04d7eea1c516dc439b | from __future__ import division
import sys
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn import svm
import re
dataVectors = []
#the file train.csv is expected
file = open('train.csv','r')
for line in file:
dataVectors.append(line.strip().split(','))
file.close
... |
12,754 | 2e3676ecb1b5e8a557d63e20bf6d432dc22d7f3d | import pygame
import random
import math
# Setup pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))#, pygame.FULLSCREEN)
myfont = pygame.font.SysFont("monospace", 12)
clock = pygame.time.Clock()
bane = pygame.image.load('bane2.png')
# Initialize game variables
done = False
tilstand = 1
class Car():
... |
12,755 | 1a70114722860900695a47978ccbef769f67b5d4 | # This program allows the user to input
# an employee's salary for SoftwarePirates Inc.
'''
====================================================
-------------------- Begin Main --------------------
====================================================
'''
# Global constants
ERROR = "\n⭕ ERROR:"
# The mai... |
12,756 | 8ca9b552a7e3784acef967f3a6bda78daf545c6d | #!/usr/bin/env python3
import subprocess
import paramiko
from PIL import ImageGrab
HOST = "127.0.0.1"
USERNAME = "root"
PASSWORD = "toor"
PORT = 8080
NAME = "001"
def main():
'''Entry point if called as an exeutable'''
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolic... |
12,757 | e54b1fb269aeecf00d4d701a4bae104b59de2f79 | from django.test import TestCase
from six import StringIO
from django.core.management import call_command
from algoliasearch_django import algolia_engine
from algoliasearch_django import get_adapter
from algoliasearch_django import clear_index
from .models import Website
from .models import User
class CommandsTestC... |
12,758 | ed30400b87b830816e38fc40b78b3adc86dd1543 | from copy import deepcopy
from .strategy import FormatStrategy
from collections import OrderedDict
class MultiWayPlayerBetStrategy(FormatStrategy):
def __init__(self, strategy):
super().__init__(strategy)
def append_market(self, caller, parsed_market) -> None:
if not caller.player_name i... |
12,759 | bdec5d7b7202b28760769a570d60ab8c7b7d5d32 | def main():
a, oper, b = input().split(' ')
try:
if oper == "+":
c = int(a)+int(b)
print(c, sep='\n')
elif oper == "-":
c = int(a)-int(b)
print(c, sep='\n')
elif oper == "*":
c = int(a)*int(b)
print(c, sep='\n')
elif oper == "/":
c = int(a)//... |
12,760 | e80cb48752a11854ee9a5af36f1872860993021f | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# @Time : 2019-08-16 11:18
# @Author : max
# @FileName: htmlparse.py
# @Software: PyCharm
import re
import warnings
warnings.filterwarnings('ignore')
from bs4 import BeautifulSoup
from urllib.parse import urlparse
exclude = ['javascript:;', '#']
# url所有后缀
suffix =... |
12,761 | 1418f73449a6c5d59ee11df0c1e5a4b128b3269d | from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from .forms import CommentForm
from django.http import HttpResponseRedirect
# Create your views here.
def post(request, pk):
post = get_object_or_404(Post, pk=pk)
form = CommentForm()
if request.method == "POST":
... |
12,762 | 8d07d886a0f2d5ddc62a97bd1cd06ac40ae7101a | # -*- coding: utf-8 -*-
"""Top-level package for Analysis Schema."""
__author__ = """Matthew Turk"""
__email__ = "matthewturk@gmail.com"
__version__ = "0.1.0"
from . import server # noqa F401
from .schema_model import schema, ytModel # noqa F401
|
12,763 | 48bc6fac5cd0c29d08634efdc1dcfc29851d6da1 | N, M = map(int, input().split())
inf = int(1e10)
dp = [inf] * (1 << N) #1をNだけシフトする 2**B
#鍵をビットで表す dp[i]は鍵の状態iにできる最小費用を
dp[0] = 0
bits = set()
bits.add(0)
for i in range(M):
a, b = map(int, input().split())
c = list(map(int, input().split()))
# cを状態keyに変換
key = 0
for t in c:
key += 1 << (t ... |
12,764 | 136c809241d9154339579bb643d89fe4ca0edd9f |
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
# Define the MySQL engine using MySQL Connector/Python
engine = sqlalchemy.create_engine(
'mysql://root:password@localhost:3306/classicmodels',
echo=True)
# Define and create the table
Base = declarative_base()
class User(Base):
... |
12,765 | cf87b17466ef1cab226b8a301061137dfd12a833 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 23:57:21 2021
@author: danney
"""
from distutils.core import setup
__version__ = "0.0"
setup(
name="axispy",
version=__version__,
description="Object to use an AXIS Camera as OpenCV's VideoCapture",
author="Dani Azemar",
au... |
12,766 | 036ecf9002f255d9a69088cbfc2fc465a26cbd88 | from django.contrib import admin
from .models import tls_feature
from .models import flow_feature
from .models import image_feature
admin.site.register(tls_feature)
admin.site.register(flow_feature)
admin.site.register(image_feature)
# Register your models here.
|
12,767 | 567640836ede6c1675b32b3d9b3b93cc4acbcb52 | def fact_lin_rec(n):
if n == 0:
return 1
else:
return n * fact_lin_rec(n-1)
print(fact_lin_rec(0))
print(fact_lin_rec(1))
print(fact_lin_rec(2))
print(fact_lin_rec(3))
print(fact_lin_rec(4))
print(fact_lin_rec(5))
|
12,768 | 4677d3da74b19f0bedc156090da156a2e3f722ef | # -*- coding: utf-8 -*-
"""
Created on December 27, 2020
@author: m8abdela
Measure 2-wire voltage using a multimeter (e.g. Agilent 34411A, hp 34401A)
"""
#import python modules (use anaconda prompt e.g. type 'pip install pyvisa' to install pyvisa)
import pyvisa #if does not work, import 'visa' instead
import ... |
12,769 | f04f886b9659b2213c79fc4db5179392d0530ca8 | # Derived from https://github.com/fschlimb/scale-out-benchs
import numpy as np
import pandas as pd
from pymapd import connect
from pandas.api.types import CategoricalDtype
from io import StringIO
from glob import glob
import os
import time
import pathlib
import sys
import argparse
def run_pd_workflow(quarter=1, year=... |
12,770 | 5b7646765a115c011cac5bd85619613458fcbd9c | from hdlc import *
|
12,771 | 9f65465a983411f02e8cc9710ab19898d2c818b9 | from painter import Painter
def algorithm(picture, args):
"""
Try to use horizontal lines for each cell
"""
painter = Painter(picture.empty_copy())
for row, column in painter.picture.positions_to_paint(picture):
if painter.picture[row][column]:
continue
length = 0
... |
12,772 | 3ea259588809064b6d0abcb53b7881b1bd18d91b | '''
Created on Feb 9, 2016
@author: zluo
'''
from zipline.algorithm import TradingAlgorithm (
add_history,
history,
order_target,
record,
symbol,
) |
12,773 | 9f658f847396b8050ce2b8444d75b02972d85400 | import math
import numpy as NP
alpha = 0.2 #learning rate
def f(z):
return 1/(1 + math.e ** (-z))
def gradientDescent(x, y, theta, m):
xTrans = x.transpose()
for _ in xrange(10**5):
h = NP.dot(x,theta)
for i in xrange(len(h)):
h[i] = f(h[i])
loss = h - y
gradient = NP.dot(xTrans,loss)/m
theta = thet... |
12,774 | 42e4f043291af77d766ad7b23ec8ed59e4cfd4d2 | import itertools
string = input("String a ser permutada: ")
result = itertools.permutations(string,len(string))
for i in result:
print(''.join(i)) |
12,775 | d24a06405b0902959c7d81634512869e24b0afdb | # Aggregation represent has-a relationship
class Salary:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
def annual_salary(self):
return self.pay*12 + self.bonus
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age... |
12,776 | 71367cba6609ba522f4433c4540c3b7270de6ee5 | from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from ugc.models import Post
from like.models import Like
class LikeInline(GenericStackedInline):
ct_field = 'target_type'
ct_fk_field = 'target_id'
model = Like
max_num = 1
class PostAdmin(admin.Mode... |
12,777 | abba228366a38232666763472ff9a5ebcfc2d5df | #!/usr/bin/python3
"""Square class"""
class Square:
""" It is the class for define a square: My first class"""
__size = ''
def __init__(self, size=0):
self.__size = size
try:
"{:d}".format(size)
if size < 0:
raise TypeError
except(TypeError)... |
12,778 | 9ef569cf08f3d1f1b7394338f8c1db3fde88a18a | from calcDiscriminatives import calcDisc
from tabelsB import makeTables
taskID={"digestion-Cogs":1, "phylogenetic-Cogs":2, "digestion-Operons":3, "phylogenetic-Operons":4}
cogsPrecent = ["30", "40", "50", "60", "80", "90"]
def main():
print("digestion-Cogs")
sendParameters("digestion-Cogs", 3)
... |
12,779 | 66a4fbbc8e5e24526c74aa2bcca8dbf18343801d | """Tests for the whole pipeline which is in test.
Focuses on verifying if all the file are created and similar to
what is expected.
Run this from project root directory:
$ python -m pytest
"""
import pytest
import subprocess
import shutil
import os
import filecmp
import textdistance
import numpy as np
@pytest.fixtu... |
12,780 | 3f96b1c0f3edfbae56ffd040656eb54b8af6b28e | #! /usr/bin/env python
"""
gyro_monitor_comp.py 3-4-2015
This is a monitor component to track progress of a GRYO run within IPS. It is completely
separate from the IPS monitor_comp.py component in that it does not use Plasma State and
and it runs concurrently with the gk_gyro.py component.
This component is also ... |
12,781 | e0b4d765d7fadb20466a6a17c2e5ce56cd6146d3 | #!/bin/python3
import os
import argparse
import sys
import subprocess
#mail: zhaojunchao@loongson.cn
arg_f = False;
hugepagenum = "";
db_socket = "db.sock";
en_dpdk=True;
dir_bin = "./bin/";
dir_sbin = "./sbin/";
dir_work = os.getcwd() + "/";
dir_etc = "./etc/openvswitch/"
dir_var_run = "./var/run/openvswitch/"
di... |
12,782 | 405b953fb91aefb6d66ac1b571640ea3481f7e1d | # -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from flask import jsonify
from flask import json
app = Flask(__name__)
@app.route("/keyboard")
def keyboard():
return jsonify(type='text')
@app.route('/message', methods=['POST'])
def message():
data = json.loads(requ... |
12,783 | 60f6ceb4b5d1cbdd74a99f076cfe5a68e2cf1c43 | supplier_bg_color = """background-color: #000 \9;
1
background-color: #000;
2
background-color: #0e3e5e;
1
background-color: #117bab;
3
background-color: #145c8b;
4
background-color: #169cd9;
9
background-color: #21c4f3;
1
background-color: #31708f;
2
background-color: #323232;
5
background-color: #333;
6
background-co... |
12,784 | 829412b14314de5977ae3f3b788d37a15fa82644 | import os
from shuup.addons import add_enabled_addons
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = "Shhhhh"
DEBUG = True
ALLOWED_HOSTS = ["*"]
MEDIA_ROOT = os.path.join(BASE_DIR, "var", "media")
STATIC_ROOT = os.path.join(BASE_DIR, "var", "static")
MEDIA_URL = "/media/"
SHUUP_ENABLED_ADDONS_FI... |
12,785 | fa113fc31f920838a747df911c0451fbc59e8512 | import requests
from itertools import zip_longest
from bs4 import BeautifulSoup
from .kana import hiragana, katakana, small_characters, hira2eng, kata2eng
import re
import urllib
import html
import json
ONYOMI_LOCATOR_SYMBOL = 'On'
KUNYOMI_LOCATOR_SYMBOL = 'Kun'
JISHO_API = 'https://jisho.org/api/v1/search/words'
SCR... |
12,786 | ed2c934a069db8cdcd728e1f3ed9437655395df7 | # 2. Создать текстовый файл (не программно), сохранить в нем несколько строк,
# выполнить подсчет количества строк, количества слов в каждой строке.
with open('task2.txt', 'r') as f:
lines = f.readlines()
for index, line in enumerate(lines):
print(f'{index + 1}: {len(line.split())}') |
12,787 | 2a0a0fe0f527a76401ed930319f7099d9ccce8d2 | """
__author__ = Biswajit Saha
this script creates sqllite schema and batch-loads all csv od matrix
"""
import sqlite3
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer,Float, String, MetaData,Index
import pandas as pd
from pathlib import Path
import time
import logging... |
12,788 | f8869869be0fd265c88b2ada43bdf026981b78f5 | #!/usr/bin/env python
# coding=utf-8
'''
@Description:
@Author: Xuannan
@Date: 2020-01-31 10:46:21
@LastEditTime : 2020-01-31 13:20:33
@LastEditors : Xuannan
'''
from .category import MaitulCategory
from .content import MaitulContent,MaitulContentTag
from .tag import MaitulTag |
12,789 | a1cacb70408fc7d69beda88707e17ec39fe52f6f | #!/usr/bin/env python3
"""
Consider a list (rollnos) containing roll numbers of 20MS students in the
format 20MSid (e.g. 20MS145, here id = 145). Use list comprehension to store
the roll nos in rollnos in a list ‘GroupA’ where id < 150 and store the rest in
another list ‘GroupB’. Print the contents of GroupA and Group... |
12,790 | 8367c2ecad20aadd406d60aeb665e40275982ea9 | # 2. Во втором массиве сохранить индексы четных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, то во второй массив надо заполнить
# значениями 0, 3, 4, 5 , т.к. именно в этих позициях первого массива стоят четные числа.
import random
ARRAY_SIZE = 10
VALUES_LOWER_BOUND = 1
VAL... |
12,791 | dd395cb68109ff51299a37dbd9297e023e4322c3 | import Deque
def arrange(aList):
arranged = []
d = Deque.Deque()
for item in aList:
if item < 0:
d.add_rear(item)
else:
d.add_front(item)
while not d.is_empty():
arranged.append(d.remove_rear())
return arranged
print(arrange([-3,12,6,-7]))
a... |
12,792 | c1dbde93e572046cba54bc2be924459e407d3136 | from tkinter import *
master = Tk()
master.geometry('600x400')
master.config(bg='skyblue')
master.title('Second Screen')
# Calculating Age
age = Label(master, text='Please Enter Your Age:', borderwidth=5)
age.place(x=10, y=10)
age_entry = Entry(master, borderwidth=5)
age_entry.place(x=200, y=10)
from datetime import da... |
12,793 | e20ac1e43a1218eeb9108012a9319f7b0751245a | import re
f = open("dates",'r')
mon = {'01': 'January', '02': 'February', '03': 'March',
'04': 'April', '05': 'May', '06': 'June',
'07': 'July', '08': 'August', '09': 'September',
'10': 'October', '11': 'November', '12': 'December'}
r1 = re.compile("(\d*)-(\d*)-(\d*)\s*(\... |
12,794 | f79f9bdfc66a2394d3d44c4d9eb327b10ad4875f |
import argparse
import atexit
import csv
import json
import os
import readline
import subprocess
import sys
import time
import uuid
import boto3
import botocore
import cmd2 as cmd
from botocore.exceptions import ClientError, ParamValidationError
from tabulate import tabulate
LESS = "less -FXRSn"
HISTORY_FILE_SIZE = ... |
12,795 | 486af34172763e20a9d3f323aa20748292d3230e | from js9 import j
class cloudbroker_location(j.tools.code.classGetBase()):
"""
Operator actions for handling interventions on a a grid
"""
def __init__(self):
pass
self._te={}
self.actorname="location"
self.appname="cloudbroker"
#cloudbroker_location_osi... |
12,796 | 321378a89c5e76b0d55e6b14b3219e5f357b418e | #!/bin/python3
# TIME CONVERSION
import os
import sys
#
# Convert AM/PM time to military time
#
# Sample input:
# 07:05:45PM
# Sample output:
# 19:05:45
#
def timeConversion(s):
# Counter in s[x:x] starts at 1 not 0
# For s[:x] counter starts from start until xth element including x
h... |
12,797 | b3e8a2dbbd86ef5ced5af2ca286719e3d8818c41 | #!/usr/bin/python
# Imports #
import sys
sys.path.insert(0, "../../include/python/");
import eulersupport;
import eulermath;
def f(n):
#We treat prime as number that can be written.
if(eulermath.PrimesHelper().is_prime(n)):
return True;
closest_prime = eulermath.PrimesHelper().find_all_primes_up_... |
12,798 | 055c71ea2294a2fcc00b4d0172cf38678128ac54 | import urllib2
import random
import MySQLdb
import pprint
import pdb
from events.models import Event, Meta
from datetime import datetime
key="ne62f3m8swrsv2cvmf78rkx2"
def call(body):
url = "http://api.opencalais.com/tag/rs/enrich"
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Reque... |
12,799 | 882118b818855a4476c3dbbba8f3bb5af00ed137 | from populus.migrations import (
Migration,
DeployContract,
)
from populus.migrations.writer import (
write_migration,
)
from populus.migrations.migration import (
get_migration_classes_for_execution,
)
def test_migrated_chain_fixture(project_dir, write_project_file, request,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.