content stringlengths 5 1.05M |
|---|
import tensorflow as tf
def rl_train():
def main():
if __name__=='__main__':
main() |
from bitstream import *
from bitstring import *
import string
conv_64_to_40('../../../scripts/test_vector.dat', 'test_vector.dat')
conv_64_to_page('../../../scripts/test_vector.dat', 'test_vector.page')
conv_page_to_66('test_vector.page', 'test_vector.66b')
conv_64_to_66('../../../scripts/test_vector.dat', 'ref_66.d... |
# Copyright Notice:
# Copyright 2018 Dell, Inc. All rights reserved.
# License: BSD License. For full license text see link: https://github.com/RedDrum-Redfish-Project/RedDrum-Simulator/LICENSE.txt
# BullRed-RackManager chassisBackend resources
#
class RdChassisBackend():
# class for backend chassis resou... |
# HTTP status codes
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_204_NO_CONTENT = 204
HTTP_404_NOT_FOUND = 404
HTTP_405_METHOD_NOT_ALLOWED = 405
HTTP_409_CONFLICT = 409
|
"""Part of Nussschale.
MIT License
Copyright (c) 2017-2018 LordKorea
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, mod... |
'''
This interactive WebSocket client allows the user to send frames to a WebSocket
server, including text message, ping, and close frames.
To use SSL/TLS: install the `trustme` package from PyPI and run the
`generate-cert.py` script in this directory.
'''
import argparse
import logging
import pathlib
import ssl
impor... |
# -*- coding: utf-8 -*-
###############################################################################
# PREP-FEWS
# Social Preparedness in Early Warning Systems model
#
# Model modules
#
# Marc Girons Lopez, Giuliano di Baldassarre, Jan Seibert
#########################################################################... |
#
# Copyright 2019-2020 Lukas Schmelzeisen
#
# 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 by applicable law or agreed t... |
# Name: Reetesh Zope
# Student ID: 801138214
# Email ID: rzope1@uncc.edu
"""
main.py
_______
- Takes network file input from command line containing - <source> <destination> <transmission time>
- Accepts user queries and does network operations accordingly on the network graph
"""
from graph import... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Pytest configuration."""
from __future__ import absolute_import, print_function
... |
import json, os
from azure.storage.queue import (
QueueService,
QueueMessageFormat
)
import azure.functions as func
from NewDeclarationInQueue.formular_converter import FormularConverter
from NewDeclarationInQueue.preprocess.document_location import DocumentLocation
from NewDeclarationInQueue.prepro... |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
print([1, 2, 3, 2].index(2)) # => 1
print([i for i, value in enumerate([1, 2, 3, 2, 4, 2]) if value == 2]) # => [1, 3, 5]
print([1, 2, 3, 2, 4, 2].count(2)) # => 3
programmers = {"Michael": "Python",
"Tim": "C+... |
from .serval import builder
from .srv import main |
# Copyright 2019 Martin Olejar
#
# 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 by applicable law or agreed to in writing... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This script performs the Kolmogorov-Smirnov test for invariance on the
# time intervals between subsequent events in high frequency trading.
# -
# ## For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=exer-expiid-copy-1).
# +
# ## Prepare the enviro... |
# using argparse library from a file
import argparse
parser = argparse.ArgumentParser(
prog="fromfile_example",
usage="%(prog)s [options] @file_name",
fromfile_prefix_chars="@",
description="getting arguments from file",
epilog="enjoy python * - *",
)
parser.add_argument("a", help="a first argument... |
import os
import logging.config
from django.core.urlresolvers import reverse_lazy
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Wilfred Hughes', 'me@wilfred.me.uk'),
)
MANAGERS = ADMINS
PROJECT_ROOT = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... |
# Generated by Django 3.0.6 on 2020-07-12 08:31
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [("checkerapp", "0027_auto_20200712_0829")]
operations = [
migrations.RemoveField(model_name="alertplugin", name="custom_plugin"),
... |
import re, nltk
def word_count(raw, min_length = 1):
""" Function to count the number of words in a passage of text.
Supplying parameter 'min_length' gives number of words with
at least min_length letters.
"""
tokens = nltk.word_tokenize(raw)
return len([word for word in tokens if len(w... |
# nm format-two | grep changeme
target = "\x68\x98\x04\x08"
diff = len("AAAAffffd896.100.0.f7f84b67.ffffd6e0.ffffd6c8.80485a0.ffffd5c0.ffffd896.100.3e8.41414141".split("."))
payload = target + "%p" * (diff - 1) + "%n"
print payload
|
__all__ = "Snmp"
import ipaddress
from types import TracebackType
from typing import Any, List, Optional, Tuple, Type, Union
from .connection import SnmpConnection
from .exceptions import SnmpUnsupportedValueType
from .message import (
GetBulkRequest,
GetNextRequest,
GetRequest,
SetRequest,
SnmpMe... |
#!/usr/bin/env python
# encoding: utf-8
#
# @Author: José Sánchez-Gallego
# @Date: Mar 8, 2018
# @Filename: hub.py
# @License: BSD 3-Clause
# @Copyright: José Sánchez-Gallego
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import re
from . import device
... |
#!/usr/bin/env python3
import json
from .LogPrimFactory import LogPrimFactory
class JSONLogPrimFactory(LogPrimFactory):
"""
JSON Log Primitive Factory.
Log Format: JSON (from base dictionary object)
Functions
* logObj - json dump the base logObj output
* ... LogPrimFactories
"""... |
#!/usr/bin/env python
#:coding=utf-8:
#:tabSize=2:indentSize=2:noTabs=true:
#:folding=explicit:collapseFolds=1:
import re, simplejson, types, jsonschema
from jsonschema.validator import JSONSchemaValidator
class FunctionValidator(JSONSchemaValidator):
'''FunctionValidator extends the JSONSchemaValidator to... |
import requests
import json
r = requests.get('https://dex.binance.org/api/v1/ticker/24hr?symbol=MTXLT-286_BNB')
if r.status_code == 200:
print('Success!')
else:
print('Error has occured')
packages_json = r.json()
tixlPrice = packages_json[0]['lastPrice']
packages_str = json.dumps(packages_json, ind... |
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
# Global Setup
user = "postgres"
password = "python"
host = "localhost"
port = 5432
database = "postgres"
url = 'postgresql://{}:{}@{}:{}/{}'
db_string = url.format(user, password, host, port, database)
db = sqlalchemy.create_engine(db_string, ... |
from . import units, constants
_MeVc2 = units.MeV / constants.c ** 2
_e = constants.si.e
class Particle:
_defaults = {
"z": 0
}
def __init__(self, name : str, **kwargs):
self.properties = Particle._defaults.copy()
self.properties.update(kwargs)
@property
def rest_mass(s... |
from Bio import SeqIO, Seq
import re
import itertools
class SubReference():
def __init__(self,reference_file):
reference = next(SeqIO.parse(reference_file,'fasta'))
(self.reference_name,self.min_pos,self.max_pos) = self._parse_label(reference.name)
self._reference_seq = reference.seq
def is_valid_pos(... |
# Generated by Django 3.2.2 on 2021-05-06 10:40
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... |
from textx import metamodel_from_file
from Robot import Robot
from Robot import default
robotlang = metamodel_from_file('robot.tx')
robot_model = robotlang.model_from_file('one.rl')
robotlang.register_obj_processors({'MoveCommand': default})
r1 = Robot()
r1.interpret(robot_model);
input("Program Complete Press Enter... |
from component import mymysql
from component.mymysql import execute
mymysql.init({
'host': "192.168.121.133",
'port': 3306,
'database': 'laashub',
'user': 'laashub',
'password': 'laashub123',
'charset': 'utf8mb4',
})
if __name__ == '__main__':
target_id = 38
# query all
print(execu... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from shops.models import Shop
class Category(models.Model):
# shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='categories')
name = models.CharField(max_length=50, verbose_name=_('Name'))
tax = model... |
"""
Calm DSL .DEV Copenhagen Hybrid Cloud Blueprint
author: michael@nutanix.com
date: 2019-09-27
"""
from calm.dsl.builtins import ref, basic_cred
from calm.dsl.builtins import action, parallel
from calm.dsl.builtins import CalmTask
from calm.dsl.builtins import CalmVariable
from calm.dsl.builtins import Service, P... |
from custom_envs.envs.quadrotor_14d_env import Quadrotor14dEnv
from custom_envs.envs.double_pendulum_env import DoublePendulumEnv
from custom_envs.envs.diff_drive_env import DiffDriveEnv
from custom_envs.envs.ball_and_beam_env import BallAndBeamEnv
|
""" Test for lib functions """
import os
import unittest
from unittest import mock
from pygyver.etl.lib import bq_token_file_valid
from pygyver.etl.lib import extract_args
from pygyver.etl.lib import remove_first_slash
from pygyver.etl.lib import add_dataset_prefix
from pygyver.etl.lib import apply_kwargs
from pygyver.... |
# -*- coding: utf-8 -*-
"""
Reads the most recent maintenace events from a csv into a dictionary. Then
writes that dictionary to a text file in json format.
"""
import csv
import json
# Initialize variables
my_dict = {}
last_asset = ''
# Reads data from csv into a dictionary
with open('mx_raw (1).csv', newline='') ... |
import numpy as np
from cv2 import cv2 as cv
def redContours (rect,frame2) :
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
mask2 = cv.inRange(rect, lower_red, upper_red)
redcnts= cv.findContours(mask2,
cv.RETR_TREE,
... |
"""
Ejericio 10
Nota de 10 alumnos y cuantos aprobados y desaprobados
"""
i = 1
aprobado = 0
des_aprobado = 0
while i <= 10:
nota = int(input(f"Ingresa la nota del alumno numero: {i} : "))
i += 1
if nota >= 7:
aprobado += 1
else:
des_aprobado += 1
print(f"TOTAL APROBADOS : {aprobad... |
'''
Class to help with communicating with the database.
'''
import sqlite3, os, base64, hashlib, csv
from .config import DB_FILE
def create_db():
''' Database created '''
conn = None
c = None
try:
if not os.path.exists(DB_FILE):
# create db connection
conn = ... |
import os
import os.path
import torch
import numpy as np
import pandas
import csv
import random
from collections import OrderedDict
from .base_video_dataset import BaseVideoDataset
from lib.train.data import jpeg4py_loader
from lib.train.admin import env_settings
'''2021.1.16 Lasot for loading lmdb dataset'''
from lib.... |
import socket
import threading
import time
import sys
# Define constant parameters
ALL_CONN = [8080,8181,8282,8383]
SERVER_PORT = 8181
IP_ADDR = "127.0.20.1"
ADDR = (IP_ADDR,SERVER_PORT)
CLIENT_ADDR = list(IP_ADDR)
CLIENT_ADDR[-1] = str(int(CLIENT_ADDR[-1]) + 1)
CLIENT_ADDR = "".join(CLIENT_ADDR)
CONFIG_PATH = "con... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
import frappe
from frappe.utils import now
from frappe import _
sitemap = 1
def get_context(context):
doc = frappe.get_doc("Contact Us Settings", "Contact Us Settings")
if doc.query_options:
query_options = [opt.... |
"""
"""
import os
import numpy as np
import skimage.io
import skimage.filters
import skimage.transform
import skimage.util
import tensorflow as tf
def hd_image_to_sd_image(hd_image, scaling_factor):
"""
down scale image then scale back to build sd version. assume the type of
the image is already float.
... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
stack = [(root, 1)]
maxVal = -float('inf')
while stac... |
import numpy as np
from numpy.lib.arraysetops import union1d
from scipy import linalg
from scipy import sparse
from scipy.sparse import linalg as la
from tqdm import tqdm
import time
import copy
import capsol.newanalyzecapsol as nac
from datetime import datetime as dt
from dataclasses import dataclass
# R, Z = np.m... |
# Copyright 2016 The TensorFlow Authors. 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 by applica... |
'''
This is the Learning Through Target Spikes (LTTS) repository for code associated to
the paper: Paolo Muratore, Cristiano Capone, Pier Stanislao Paolucci (2020)
"Target spike patterns enable efficient and biologically plausible learning for
complex temporal tasks*" (currently *under review*).
Please give credit to... |
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/lice... |
import csv
import cv2
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Dropout, Cropping2D
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
def data_import(Filename):
# reading file conte... |
"""
Write a Python program to compute cumulative sum of numbers of a given list.
Note: Cumulative sum = sum of itself + all previous numbers in the said list.
Sample Output:
[10, 30, 60, 100, 150, 210, 217]
[1, 3, 6, 10, 15]
[0, 1, 3, 6, 10, 15]
"""
def cummulative_sum(num_lists):
return (sum(num_lists[:i+1]) for i... |
"""
NCL_panel_41.py
===============
This script illustrates the following concepts:
- Paneling six plots on a page
- Adding a common title to paneled plots using a custom method
- Adding left, center, and right subtitles to a panel plot
- Using a different color scheme to follow `best practices <https://geo... |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin, validator
from flexget.event import event
log = logging.getLogger('cfscraper')
class CFScraper(object):
"""
Plugin that enables scraping of cloudflare protected sites.
Example::
cfscr... |
"""
Parse a junit report file into a family of objects
"""
import xml.etree.ElementTree as ET
import collections
from junit2htmlreport import tag
import os
import uuid
class AnchorBase(object):
"""
Base class that can generate a unique anchor name.
"""
def __init__(self):
self._anchor = None
... |
from conda_mirror.convert_environments import _convert_environments
import shutil
import yaml
def test_environment_conversion():
shutil.rmtree("test/repo", ignore_errors=True)
_convert_environments("test/environments", "test/repo", "http://test.com")
with open("test/repo/linux-64/igwn-py37.yaml","rt") as ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from backbone import (res32_cifar, res50, res10)
from modules import GAP, FCNorm, Identity, LWS
import copy
import numpy as np
import cv2
import os
class Network(nn.Module):
def __init__(self, cfg, mode="train", num_classes=1000):
... |
# -*- coding: utf-8 -*-
from sqlalchemy import Column, ForeignKey, Integer, String, Float, func, desc
from itertools import groupby
from ..app import db
class Topic(db.Model):
"""
Primary topic for an article.
"""
__tablename__ = "topics"
id = Column(Integer, primary_key=True)
name ... |
import common
import pandas as pd
from os import path, linesep
from sklearn.linear_model import SGDClassifier
def build_model(data_set, data_split, no_interactions, negative, max_snps, cross_validation, output_dir):
"""
Builds a model using logistic regression and an elastic net penalty
:param data_set: T... |
from django.contrib import admin
from django.db.models import JSONField
from django_krules_procevents.widgets import ReadOnlyJSONWidget
from .models import Fleet, ReceivedData, LocationTrackerService, LocationTrackerData
@admin.register(Fleet)
class FleetAdmin(admin.ModelAdmin):
readonly_fields = ["endpoint", "d... |
def swap(vet, i, menor):
aux = vet[i]
vet[i] = vet[menor]
vet[menor] = aux
def selectionSort(vet):
for i in range(len(vet)):
menor = i
for j in range(i+1, len(vet)):
if vet[j] < vet[menor]:
menor = j
if i != menor:
swap(vet, i, menor)
... |
import sys
if sys.version_info >= (3, 8):
from unittest import IsolatedAsyncioTestCase as TestCase
from unittest.mock import AsyncMock
else:
from unittest import TestCase
from asynctest.mock import CoroutineMock as AsyncMock
from unittest.mock import Mock, call, sentinel
import pytest
from jj.apps i... |
import gameBoard
def main():
print('Welcome to TicTacToe')
askingToPlay = input('Do you want to play again? (Type yes or no)'.lower())
if askingToPlay != 'yes':
run game
while playAgain == 'yes':
pass
'''
runGame
'''
print("i love johnson")
|
import datetime
import logging.config
import transaction
from pyramid.config import Configurator
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.session import SignedCookieSessionFactory
from sqlalchemy import engine_from_config
from... |
#!/usr/bin/env python
import rospy
from duckiepond_vehicle.msg import UsvDrive
from sensor_msgs.msg import NavSatFix,Imu
from nav_msgs.msg import Odometry
from RVO import RVO_update, reach, compute_V_des, reach
from PID import PID_control
from dynamic_reconfigure.server import Server
from control.cfg import ang_PIDCon... |
from typing import List
from garage.garage import Garage
from garage.parking_level import ParkingLevel
from garage.parking_space import ParkingSpace
from garage.vehicle import Vehicle
from garage.vehicle_type import VehicleType
from test.utils import TestHelpers
def test_standard_cars_are_rejected_from_compact_parki... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consist... |
from pygame import Rect
class Grid:
@classmethod
def init(cls):
return cls((0, 0), (1, 1), (1, 1))
def __init__(self, position, size, slice, gap=(0, 0)):
self.slice = slice
self.size = size
self.gap = gap
self.position = position
self.update()
def calcu... |
from translathor import translator
from apicalls import *
def caller():
intention = input(
"To get songs by an artist use (F)\nTo get music lyrics use(G)\nUse (H) to get lyrics and translate -->")
if intention.lower() not in ['f', 'g', 'h'] :
exit("Lmao, get serious abeg")
elif intention.lo... |
import csv
import time
import json
import requests
import numpy as np
import gevent.monkey
import urllib
from datetime import datetime
from urllib.request import urlopen
start_time = time.time()
header_row = False
count = 0
file_name = "dust_result_" + time.strftime("%Y%m%d-%H%M%S") + ".csv"
# urls = ['https://api.wa... |
import glob
import numpy as np
import os
import tensorflow as tf
import tqdm
import random
def data_paths(path):
paths = []
if os.path.isfile(path):
# Simple file
paths.append(path)
elif os.path.isdir(path):
# Directory
for (dirpath, _, fnames) in os.walk(path):
... |
from django.urls import path
from django.conf.urls import url
from django.urls import include
from api import views
urlpatterns = [
path('types/', include('api.types.urls')),
path('experiments/', include('api.experiments.urls')),
path('samples/', include('api.samples.urls')),
path('persons/', include('... |
# Required libraries
import pandas as pd
import logging as log
import time
import numpy as np
from scipy import signal
from sklearn.feature_extraction.text import CountVectorizer
# Given an iterable (list or Series), turns it into a bag of words matrix (DataFrame)
def get_bow(iterable, vocabulary=None, prefix=''):
... |
import warnings
import numpy as np
__all__ = [
'recarray_to_colmajor']
from pnumpy._pnumpy import recarray_to_colmajor as _recarray_to_colmajor
#-----------------------------------------------------------------------------------------
def recarray_to_colmajor(item, parallel=True):
"""
Converts a numpy r... |
__author__ = 'Neil Butcher'
import CheckingAlgorithms
def priority(a):
return a.priority
def CheckDuration(duration, population):
events = duration.events
appointments = duration.appointments()
result = []
result.extend(CheckingAlgorithms.MissingPersonCheck(appointments, population))
resu... |
"""Games package."""
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Modified (for JtR) by Dhiru Kholia in December, 2014.
# Modified (for JtR) by Jean-Christophe Delaunay
# <jean-christophe.delaunay at synacktiv.com> in 2017
# to support further options and JtR new hash format
#
# This file is part of DPAPIck
# Windows DPAPI decryption ... |
# coding: utf-8
class Task:
pass
|
import sklearn.ensemble
from autosklearn.pipeline.components.classification.gradient_boosting import \
GradientBoostingClassifier
from .test_base import BaseClassificationComponentTest
class GradientBoostingComponentTest(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_i... |
from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
install_requires = ['boto3', 'pandas<0.25.0', 'gokart>=0.2.4', 'tqdm']
setup(
name='thunderbolt',
... |
default = False
actions = 'store_true'
ENC = 'utf-8' |
#!/usr/bin/env python
class DemoAdd:
@staticmethod
def add(x, y):
return x + y
def main():
print "trigger"
print "hi"
demo = DemoAdd()
print demo.add(3, 4)
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
import scrapy
from scrapy_news.items import SoccerNewsItem
import scrapy_news.url_selector as url_selector
#to run
#scrapy crawl bbc
class BBCSpider(scrapy.Spider):
name = 'bbc'
allowed_domains = ['bbc.com']
source = 'BBC'
start_urls = url_selector.get_urls(source)
def par... |
# /index.py
from flask import Flask, request, jsonify, render_template
import os
import dialogflow
import requests
import json
import pusher
import json
import pytz
import dateutil.parser
from datetime import date, time, datetime
import pprint
app = Flask(__name__)
@app.route('/')
def index():
return render_temp... |
from time import time_ns
from pyprocessing.utils import SingletonMeta
class RenderersDelegate:
def __init__(self, renderers, render_attr):
self.renderers = renderers
self.render_attr = render_attr
methods = (
m
for r in self.renderers
for m in dir(getat... |
from tortoise import Tortoise
from tortoise.contrib import test
class TestCapabilities(test.TortoiseTransactionedTestModelsTestCase):
# pylint: disable=E1101
def setUp(self):
self.db = Tortoise.get_db_client("models")
self.caps = self.db.capabilities
def test_str(self):
self.asse... |
#!/usr/bin/python
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.neighbors import KernelDensity
# import scikitlearn
######################################################################
# gaussian based density estimation for the targer feature (SalePrice)
############... |
from signal import SIGTERM
from os import kill, getpid
from multiprocess import Process
from simple_scheduler.base import Schedule
class Recurring(Schedule):
""" Recurring tasks are those that occur after every "x"-seconds.
(e.g. script_1 is called every 600 seconds)"""
def __init__(self, *args, **kw... |
import numpy as np
import random
import csv
import matplotlib.pyplot as plt
#파일로 데이터 입력(Column Name없이), 파일명 : ex_kmc.csv
def loadDataset(filename, split, trainingSet=[] , testSet=[]):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in r... |
from PyQt5 import QtCore, QtGui, QtWidgets
from lib.Themes import app_dark_mode
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as Toolbar
from matplotlib.widgets import RectangleSel... |
from __future__ import annotations #<-- Makes sure the fromlist method can return a dsDirectory object. Redundant in Python 4
import os, datetime, json
from dsFile import dsFile
class dsDirectory:
def __init__(self, path = "", new_base_path = ""):
self.path = path
self.files = []
self.subdi... |
import pytest
from year_2020.day25.combo_breaker import (
get_encryption_key,
get_loop_size,
)
def test_get_encryption_key():
assert get_encryption_key(5764801, 17807724) == 14897079
@pytest.mark.parametrize("public_key, expected", [(17807724, 11), (5764801, 8)])
def test_get_loop_size(public_key, expe... |
import inspect
class _ObjInfoOrigin:
""" Only one of these methods starting with 'from_' will return True. """
def _last_cls_with_name(self):
""" Get the last (bottom-most) of parent's cls that has this name in it.
:param generallibrary.ObjInfo self: """
last_cls = None
p... |
import os
import glob
import tqdm
import time
import json
import arcgis
import requests
import exceptions
class Downloader:
def __init__(self, token, mapserver_url):
self.token = token
self.headers = {"Authorization": f"Bearer {self.token}"}
self.mapserver_url = mapserver_url
def dow... |
from .sift import *
|
import tkinter as tk
from PIL import Image, ImageTk
from math import sin, cos, radians
from timeit import default_timer as timer
def circle_cords(tetha):
print(tetha)
r = tetha // 10
return int(cos(radians(tetha%360))*r), int(sin(radians(tetha%360))*r)
class StatusBar(tk.Frame):
def __init__(self, ... |
import os
from pathlib import Path
from sys import argv
# Directory to File extensions
dir_to_extns = {
"Audios": ["wav", "mp3", "wma", "aac"],
"Images": ["jpg", "jpeg", "bmp", "png", "gif", "tiff"],
"Videos": ["mp4", "mpeg4", "mkv", "avi", "wmv", "flv"],
"Documents": ["pdf", "doc", "docx", "x... |
import discord
from discord.ext import commands
import random
class Admin(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def prefix(self, ctx, *, arg):
if ctx.author.id == ctx.guild.owner.id or ctx.author.id == 153699972443799552:
mem... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-05-18 03:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mooringlicensing', '0115_merge_20210517_0953'),
]
operations = [
migration... |
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution kernel
# Implements network described at http://... |
import sys, os, struct
SINGLE_SIDED_DSK_SIZE = 360*1024
DOUBLE_SIDED_DSK_SIZE = SINGLE_SIDED_DSK_SIZE * 2
"""
IMG and DSK differ only by IMG files having one byte header
in the case of single sided IMG file the header is 01
and double sided IMG has header 02.
"""
SINGLE_SIDED_IMG_SIZE = SINGLE_SIDED_DSK_SIZE + 1... |
# stdlib imports
import uuid
# third-party imports
import click
class HiddenOption(click.Option):
"""Option type that suppresses any help output.
"""
hidden = True
def get_help_record(self, ctx):
return
def multioption(options, name=None, callback=None):
"""Attaches multiple options to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.