content stringlengths 5 1.05M |
|---|
import datetime
from peewee import CharField, DateTimeField, SqliteDatabase, TextField, Model
db = SqliteDatabase('info.db')
class BaseModel(Model):
class Meta:
database = db
indexes = (
# create a no-unique on username and email
(('sex', 'email'), False),
)
... |
# File: proofpoint_consts.py
# Copyright (c) 2017-2020 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
PP_API_BASE_URL = "https://tap-api-v2.proofpoint.com"
PP_API_PATH_CLICKS_BLOCKED = "/v2/siem/clicks/blocked"
PP_API_PATH_CLICKS_PERMITTED = "/v2/siem/clicks/permitted"
PP... |
# Copyright 2020 Alexander Polishchuk
#
# 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 ... |
from collections import Sequence
from itertools import islice
import nltk
def batches(it, k):
"""Split iterable it into size-k batches.
Returns
-------
batches : iterable
Iterator over lists.
"""
it = iter(it)
while True:
batch = list(islice(it, k))
if not batch:
... |
# encoding: utf-8
import json
import os
import random
from datetime import datetime, timedelta
from io import BytesIO, StringIO
from unittest import mock
from unittest.mock import MagicMock
import pytest
from pymarc import parse_xml_to_array
from pymarc.record import Record
from api.authenticator import BasicAuthenti... |
import os
import pytest
import sqlite3
from twdft.env import TWDFT_DATA_DIR
@pytest.fixture(
params=["Awful Site Name With Space", "Bad & Badder Site", "Test Site/1"]
)
def bad_site_names(request):
print("\n-------------------------------------")
print(f"fixturename : {request.fixturename}")
yi... |
import os
import sys
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def calculateTileGridStatistics(tile_grid_shape, tile_size_x: int, tile_size_y: int):
"""Calculates all necessary grid statistics based on tile shape and size
Parameters
----------
tile_grid_shape : Tuple[int, ... |
"""
Handles incomming log records with buffer
"""
import datetime
import json
import logging
import traceback
from typing import Optional, Dict
from logging.handlers import BufferingHandler
from . import config, seqsender
LOG = logging.getLogger(config.LOGGER_NAME)
class SeqPyLoggerHandler(BufferingHandler):
""... |
import logging as _logging
log = _logging.getLogger('stolos')
import os.path as _p
import pkg_resources as _pkg_resources
__version__ = _pkg_resources.get_distribution(
_p.basename(_p.dirname(_p.abspath(__file__)))).version
class Uninitialized(Exception):
msg = (
"Before you use Stolos, please initia... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QMessageBox, QDesktopWidget, QCheckBox
from SQL_functions import *
import pymysql
from selenium import webdriver
import os
import time
class Ui_Details_song(QtWidgets.QWidget):
res_dat... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class Secret(pulumi.CustomResource):
"""
Provides a resource to manage AWS Secrets Manager... |
import lab as B
import numpy as np
import pytest
from .test_architectures import generate_data
from .util import nps # noqa
@pytest.mark.parametrize("dim_lv", [0, 4])
def test_loglik_batching(nps, dim_lv):
model = nps.construct_gnp(dim_lv=dim_lv)
xc, yc, xt, yt = generate_data(nps)
# Test a high number ... |
# Copyright 2017 reinforce.io. 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 applicable law or... |
#!/usr/bin/env python
from roslib.message import get_message_class
import rospy
import rosgraph
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2 as cv
import numpy as np
VERBOSE=False
class NoisePublisher():
def __init__(self):
ros... |
import logging
from glob import glob
from pathlib import Path
from ..core.filesystem import rename_files, rename_folders
from ..model.filesystem import OptionParser, Options
from . import common
logger = logging.getLogger(__name__)
def rename(options: Options):
function = rename_folders if options.dir_mode else... |
#! python3
# -*- coding: shift-jis -*-
import wx
import mwx
from mwx.controls import Icon
class Frame(mwx.Frame):
def __init__(self, *args, **kwargs):
mwx.Frame.__init__(self, *args, **kwargs)
## Do not use menu IDs in [ID_LOWEST(4999):D_HIGHEST(5999)]
self.menubar["File"... |
"""Provides a scripting component.
Inputs:
x: The x script variable
y: The y script variable
Output:
a: The a output variable"""
__author__ = "trk"
__version__ = "2020.11.24"
import rhinoscriptsyntax as rs
import Rhino
import scriptcontext as sc
def BrepFootPrint(breps):
edgecrvs... |
import os
import sys
import shutil
import logging
from git import Repo
from . import increment_version
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
if len(sys.argv) > 2:
version_filename = os.path.join(sys.argv[2], "version.py")
else:
version_filename = "version.py"
_locs = {}
try:
... |
import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
from .dash_app import app
from dash.dependencies import Input, Output, State, ALL # ClientsideFunction
collapses = \
html.Div([
dbc.Collapse(html.Div(
[dbc.Spinner(
dcc.Upload(id='... |
# Auditor for patch files
# Patches should be declared as text/plain (also .py files),
# independent of what the browser says, and
# the "patch" keyword should get set automatically.
import posixpath
patchtypes = ('.diff', '.patch')
sourcetypes = ('.diff', '.patch', '.py')
def ispatch(file, types):
return posixp... |
# Note: Most of the codes are copied from https://github.com/ZhiwenShao/PyTorch-JAANet/blob/master/network.py
# Please check with the repo and original authors if you want to redistribute.
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LocalConv2dReLU(nn.Module):
def _... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import shutil
import time
# moudule
import variable
def clone_Bitbucket(path, repo):
URL = f'https://{variable.bitbucket_user}:{variable.bitbucket_pwd}@bitbucket.org/{variable.bitbucket_team}/{repo}.git'
os.system(f'git clone {URL}')
return
def pul... |
from django.utils.translation import gettext as _
from rest_framework.test import APITestCase
from paste.constants import _setting
from tests.utils import create_snippet
class SnippetModelTestCase(APITestCase):
"""Tests for the snippet model."""
def test_str_titled(self):
"""A titled snippet's str... |
import re
__all__ = ["plugin_def_list"]
DEFINITION_LIST_PATTERN = re.compile(r"([^\n]+\n(:[ \t][^\n]+\n)+\n?)+")
def parse_def_list(block, m, state):
lines = m.group(0).split("\n")
definition_list_items = []
for line in lines:
if not line:
continue
if line.strip()[0] == ":":
... |
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from common_util import mylog
class HostEventHandler(FileSystemEventHandler):
def __init__(self, host):
self._host = host
def dispatch(self, event):
# todo:29 use these events directly,... |
import requests
import urllib.request
import urllib3
import datetime
from bs4 import BeautifulSoup
import pandas as pd
import feedparser
from datetime import date
from datetime import datetime
import re
from warnings import warn
_country = 'Canada'
_src_cat = 'Government Website'
_columns = ['start_date', 'country', '... |
import nqs.core as core
from nqs.resources.extensions import py
def write(name: str):
T=core.compile(name)
py.write(T,name) |
import platform
from rich import print
from .base_info import BaseInfo
class OsInfo(BaseInfo):
"""
Print the users OS
"""
def __init__(self):
super().__init__()
def query_os(self):
"""
Get information about OS.
"""
system = platform.platform()
re... |
from app import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __init__(self, username, password, name, email) -> None... |
import re
import sys
korean_pattern_str = '가-힣'
number_pattern_str = '0-9'
alphabet_pattern_str = 'a-zA-Z'
puntuation_pattern_str = '.,?!'
doublespace_pattern = re.compile(r'\s+')
repeatchars_pattern = re.compile(r'(\w)\\1{3,}')
def normalize(doc, english=False, number=False, punctuation=False,
remove_repeat=0,... |
import aria2p
from JavHelper.core.ini_file import return_default_config_string
aria2 = aria2p.API(
aria2p.Client(
host=return_default_config_string('aria_address'),
port=int(return_default_config_string('aria_port') or 0),
secret=return_default_config_string('aria_token')
)
)
|
##############################################################################################
##############################################################################################
## ##
## ## ## ##### ### ... |
from tests import utils
import bpy
import animation_retarget
class TestAddon(utils.BaseTestCase):
def test_blinfo(self):
self.assertIsNotNone(animation_retarget.bl_info)
def test_enabled(self):
self.assertIn('animation_retarget', bpy.context.preferences.addons)
|
from interfaces.expr import Number, BinOp, UnaryOp, Bool, Signal
class Visitor:
def dispatch(self, node):
assert node
""" Note that it does not necessary returns object of Expr class """
if isinstance(node, BinOp):
return self.visit_binary_op(node)
if isinstance(node,... |
# Copyright 2018 Iguazio
#
# 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, softwa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipaySecurityRiskRiskprofileQueryModel(object):
def __init__(self):
self._request_from = None
self._request_id = None
self._risk_object = None
self._risk_object_v... |
# train.py
#!/usr/bin/env python3
""" stage 2 CPN key point detection eval """
import os
import sys
import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
fro... |
import cv2
import numpy as np
from personal_color import predict_Personal_Color
def predict_personal_color(img):
rate = predict_Personal_Color(img)
result = max(rate)
return {'result': result}
if __name__ == "__main__":
pass
|
import numpy as np
import pytest
from hypothesis import assume, given, settings, strategies as st
import mephisto as mp
# change default profile as to not trigger on deadline changes
settings.register_profile('ci', database=None, deadline=None)
settings.load_profile('ci')
def test_histogram_a_ndarray():
a = np... |
def internet_reachable():
import socket
import requests
try:
requests.get('http://google.com', timeout=1)
except (requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
socket.timeout,
socket.gaierror):
return False
return True
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
#!/usr/bin/env python3
import cca
class Location:
VOID, PLAYER, R1, R2, R3, R4, R5 = range(7)
def rules():
def rules_r1(rb):
rb.default_check = {'player': Location.R1}
r = rb.add
r(("look",""),"You are in a small room with a bed, a creepy portrait, and an open door.", {'r1_door_open':... |
import os
import shutil
import numpy as np
import pandas as pd
import yaml
from colorclass import Color
def read_multilabel_dataset(input_file, input_col=2, target_col=(-2, -1),
encoding='utf-8'):
df = pd.read_csv(input_file, sep='\t',
encoding=encoding, dtype='st... |
################################################
## main.py
## - Servidor websocket
## Projeto: Arduino | Python | HTML | Websocket
## Criado por Guilherme Rodrigues em 28/03/2020
##
################################################
import asyncio
import json
import websockets
import datetime
# Modulos locais
import ... |
from django.contrib.auth import authenticate
from rest_framework import serializers
from register.models import Registration
from django.core.validators import ValidationError
class RegistrationSerializer(serializers.ModelSerializer):
"""This class handles serializing and
deserializing of Registration obje... |
from distutils.core import setup
import os
setup(name='pylagrit',
version='1.0.0',
description='Python interface for LaGriT',
author='Dylan R. Harp',
author_email='dharp@lanl.gov',
url='lagrit.lanl.gov',
license='LGPL',
install_requires=[
'pexpect==4.6.0',
'numpy',
],
packages=[
'pylagrit',]
)
|
class State:
# This class simulates a state in the game.
# Variables: pattern
# heuristic
# cost
# father
# Methods: getSuccessors
# swapBlocks
# goalTest
# getHeuristic
# ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os
DOWNLOADS = os.environ['HOME'] + '/Descargas'
print(f'Directorio: {DOWNLOADS}')
[print(file) for file in os.listdir(DOWNLOADS) if os.path.isfile(os.path.join(DOWNLOADS,file))] |
from sprite import Sprite
import numpy
def get_sprites(s):
d = {}
mapping = {'.': 0,
'x': 1}
for name, block in s.items():
name = name.strip()
block = block.strip()
if not block:
continue
lines = block.split('\n')
desc = []
for lin... |
import sass
sass.compile(dirname=('assets/sass', 'assets/css'), output_style='expanded')
|
# -*- coding: utf-8 -*-
"""
@author: Bernd Porr, mail@berndporr.me.uk
Plots the frequency spectrum of the 1st selected channel in
Attys scope
"""
import socket
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import threading
# update rate in ms
updateRate ... |
from collections import OrderedDict
from egosplit.benchmarks.data_structures.algorithms import EgoSplitAlgorithm
from egosplit.benchmarks.execution.cleanup import CleanUpConfig
from egosplit.external import partitionInfomap, partitionLeiden
from networkit.community import PLPFactory, PLMFactory, LPPotts, LouvainMapEq... |
from torch import nn
from torch.nn import functional as F
def icnet_resnet18(in_channels, out_channels):
from neural.models.classification.resnet import ResNet, resnet18
backbone = resnet18(in_channels, 1)
ResNet.replace_stride_with_dilation(backbone, output_stride=8)
features = backbone.features
... |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
"""Generic component build functions."""
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
import dogpile.cache
from requests.exceptions import ConnectionError
import six
from module_build_service.common import conf, log, models
from... |
from blockfrost import BlockFrostApi, ApiError
from blockfrost.api.cardano.scripts import \
ScriptsResponse, \
ScriptResponse, \
ScriptJsonResponse, \
ScriptCBORResponse, \
ScriptRedeemersResponse, \
ScriptDatumResponse
script_hash = "13a3efd825703a352a8f71f4e2758d08c28c564e8dfcce9f77776ad1"
da... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# Power by viekie. 2017-05-19 08:43:35
class Connections(object):
def __init__(self):
self.connections = []
def add_connection(self, connection):
self.connections.append(connection)
def __str__(self):
conn_info = 'connections: %s' % sel... |
from pyModbusTCP.client import ModbusClient
from pyModbusTCP import utils
import time
SERVER_HOST = "192.168.208.106"
SERVER_PORT = 1502
UNIT_ID = 71
# Open ModBus connection
try:
c = ModbusClient(host=SERVER_HOST, port=SERVER_PORT, unit_id=UNIT_ID, auto_open=True, auto_close=True)
except ValueError:
print("... |
from data_importers.ems_importers import BaseDemocracyCountsCsvImporter
IVC_STATIONCODES = (
"IG36_1",
"IG17_3",
"IG05_1",
"IG26_2",
"IG21_1",
"IG19_3",
"BETHESDA_1",
"STCOLUMBAS_4",
"IG23_1",
"IG23_2",
"IG27_3",
"IG32_1",
"IG30_2",
"IG01_1",
"IG09_1",
"I... |
from django.contrib import admin
from django.urls import path
from home import views
from django.conf.urls import url
urlpatterns = [
path('', views.home , name="home"),
path('pay', views.payFees , name="pay"),
path('profile', views.profile , name="profile"),
path('result', views.result , name="result... |
"""Tests for ``coffin.template``.
``coffin.template.library``, ``coffin.template.defaultfilters`` and
``coffin.template.defaulttags`` have their own test modules.
"""
def test_template_class():
from coffin.template import Template
from coffin.common import env
# initializing a template directly uses Coff... |
#! /usr/bin/env python3
import argparse
import pandas as pd
import logging
import sys
import pbio.utils.fastx_utils as fastx_utils
import pbio.misc.logging_utils as logging_utils
import pbio.misc.parallel as parallel
import pbio.misc.pandas_utils as pandas_utils
logger = logging.getLogger(__name__)
default_num_cpu... |
# [START imports]
import os
import urllib
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
from baseClasses import *
from authModel import *
from authBaseCode import *
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSys... |
__author__ = 'Randall'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pandas as pd
from talibpy import *
def main():
basepath = os.path.dirname(__file__)
filename = os.path.join(basepath, "..", "data", "AAPL_GOOGL_IBM_20140101_20141201.xls")
d = pd.read_excel(filename, sheetname=None)
panel = pd.Panel.from_d... |
import unittest
import jsparagus.gen
from jsparagus import parse_pgen, parse_pgen_generated
class ParsePgenTestCase(unittest.TestCase):
def test_self(self):
import os
filename = os.path.join(os.path.dirname(parse_pgen.__file__), "..",
"pgen.pgen")
grammar =... |
from math import ceil, lcm
def earliest_depart(now : int, bus : int) -> int:
"""Get the earliest departure time (after now) for a bus
departing on a fixed schedule."""
return int(ceil(now / bus)) * bus
def part1(now : int, busses : list[str]) -> int:
"""Get the minimum wait for a bus, multiplied by it... |
"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
import qy
class Variable(object):
"""
Mutable value.
"""
def __init__(self, type_):
"""
Initialize.
"""
self._location = qy.stack_allocate(type_)
def __lt__(self, other):
"""
XXX.
"""... |
"""WebUtils Tests"""
|
import json
from django import template
from django.apps import apps
register = template.Library()
quilljs_app = apps.get_app_config('quilljs')
@register.filter()
def quilljs_conf(name):
"""Get a value from the configuration app."""
return getattr(quilljs_app, name)
quilljs_conf.is_safe = True
@register.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Colour Quality Plotting
=======================
Defines the colour quality plotting objects:
- :func:`colour_rendering_index_bars_plot`
"""
from __future__ import division
import matplotlib.pyplot
import numpy as np
import pylab
from colour.algebra import normal... |
from .load import Load
Default = Load
|
__all__ = ['EvaluationMetric']
class EvaluationMetric(object):
r"""
Base class for all Evaluation Metrics
"""
def __init__(self):
self.arg_map = {}
def set_arg_map(self, value):
r"""Updates the ``arg_map`` for passing a different value to the ``metric_ops``.
Args:
... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.db import connection
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from ..document.models import Document, Annotation, Vie... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import threading
from postman import rpc
def _target(queue, function, wait_till_full):
try:
while True:
with queue.... |
#
# TODO: for the moment, it has to be py3.6 compatible. Please do not use e.g. Final
# time
MINUTE: int = 60 # secs
# string templates
HEADER_STR: str = "{:-^50}\n"
|
# https://leetcode.com/problems/restore-ip-addresses/
#
# algorithms
# Medium (31.43%)
# Total Accepted: 138,937
# Total Submissions: 442,122
# beats 85.52% of python submissions
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
... |
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__=''
#REPORTLAB_TEST_SCRIPT
import sys, copy, os
from reportlab.platypus import *
_NEW_PARA=os.environ.get('NEW_PARA','0')[0] in ('y','Y','1')
_REDCAP=int(os.environ.get('REDCAP','0'))
_CALLBACK=os.environ.get('CA... |
from flask import render_template, request
from flask import url_for, flash, redirect, abort
from flask_login import current_user, login_required
from flaskblog import db
from flaskblog.model import Post
from flaskblog.posts.forms import PostForm
from flask import Blueprint
posts = Blueprint('posts', __name__)... |
import time
# Version: 1.0.5
import pandas as pd
def timer(fn):
def wrapped(*args, **kwargs):
name = fn.__name__
print(f'Starting {name}...')
start = time.time()
out = fn(*args, **kwargs)
stop = time.time()
print(f'Finished {name} in {stop - start}s')
return... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# mybarcode.py
from base64 import b64encode
from reportlab.lib import units
from reportlab.graphics import renderPM
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.shapes import Drawing
def get_barcode(value, width, barWidth = 0.05 * units.inch, fontSize = 20, humanReadable = Fal... |
# Validate event sourcing pattern: create new orders to the order microservice end points
# validate the order is added and a order created event was added
# It assumes the event broker (kafka) and all the solution services are running locally (by default)
# If these tests have to run against remote deployed solution t... |
from setuptools import setup
import os
VERSION = "0.1"
def get_long_description():
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"),
encoding="utf8",
) as fp:
return fp.read()
setup(
name="discogsdata",
description="CLI for exploring/exploitin... |
from django.contrib import admin
from django.urls import include, path, re_path
from rest_framework import routers
from api import views
from . import view
from django.conf import settings
router = routers.DefaultRouter()
router.register(r'movies', views.MovieViewSet)
#router.register(r'groups', views.GroupViewSet)
#... |
import os
import json
import time
import shutil
import logging
import zipfile
import platform
import tempfile
import subprocess
from pathlib import Path
from threading import Thread
import requests
from ...exceptions import BentoMLException
logger = logging.getLogger(__name__)
def get_command() -> str:
"""
... |
from gen_drivfunc import *
import basic_func as bf
import random
from mpmath import *
import itertools
from scipy.optimize import basinhopping
import time
import signal
class TimeoutError (RuntimeError):
pass
def handler (signum, frame):
raise TimeoutError()
signal.signal(signal.SIGALRM, handler)
def extract... |
from .numbers import number_to_scientific_latex
from .string import StrPrinter
from ..units import _latex_from_dimensionality
class LatexPrinter(StrPrinter):
_default_settings = dict(
StrPrinter._default_settings,
repr_name='latex',
Equilibrium_arrow=r'\rightleftharpoons',
Reactio... |
import geopandas as gpd
import pandas as pd
from .grids import *
from CoordinatesConverter import getdistance
def clean_same(data,col = ['VehicleNum','Time','Lng','Lat']):
'''
Delete the data with the same information as the data before and after to reduce the amount of data. For example, if several consec... |
from scapy.all import sr
from craft_a_packet import generate_icmp_packet
def send_and_receive_packets(packets_to_send):
'''
send packets and receive answers, abandon unanswered
packets_to_send: a list of packets to be sent
'''
responses = []
for packet in packets_to_send: # loop each packet in ... |
from django.apps import AppConfig
class DataSourcesConfig(AppConfig):
name = 'data_sources'
|
from .evaluation import (
visu_preds_and_targets,
visu_preds,
visualize,
voronoi_IPF_plot,
in_and_out_of_plane,
evaluate,
EvaluationManager
)
from .losses import custom_loss
from .metrics import moa, misorientation
from .models import CustomModel |
import numpy as np
from scipy import interpolate
def interpolate_path(dmp, path):
time = np.linspace(0, dmp.cs.T, path.shape[0])
inter = interpolate.interp1d(time, path)
y = np.array([inter(i * dmp.dt) for i in range(dmp.cs.N)])
return y
def calc_derivatives(y, dt):
# velocity
yd = np.diff(y... |
# -*- coding: utf-8 -*-
from . import utils
import requests
def get_product(barcode, locale='world'):
"""
Return information of a given product.
"""
url = utils.build_url(geography=locale,
service='api',
resource_type='product',
... |
from django.db import models
from accounts.models import IncomeAccount
# Create your models here.
class Item(models.Model):
name = models.CharField(max_length=100)
total_units = models.PositiveIntegerField()
remaining_units = models.PositiveIntegerField()
unit_price = models.DecimalField(max_digits=12... |
"""Support for the OpenWeatherMap (OWM) service."""
from __future__ import annotations
from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.core import HomeAssistant
fro... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 11:04:50 2019
@author: Ham
HackerRanch Challenge: Words Score
In this challenge, the task is to debug the existing code
to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u and y.
Function score_words ... |
#-*- coding: utf-8 -*-
import numpy as np
from scipy.integrate import odeint
from scipy.sparse.linalg import eigs
import pandas
from scipy.integrate import solve_ivp
from scipy.linalg.blas import dgemm, daxpy
from numba import jit
def convert_data(df, ssdf):
'''Converts pandas dataframe into numpy ar... |
# produce mouse genome exon by exon
import gzip
from Bio import SeqIO
import pickle
import os
import pandas as pd
chromosomes = {}
filename_base = os.path.join(os.path.dirname(__file__), "static/data/GRCm38/chr{}.fa.gz")
print("starting refGene load")
refGeneFilename = os.path.join(os.path.dirname(__file__), "static/... |
#!/usr/bin/python
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import input
import pytumblr
import yaml
import os
import code
from requests_oauthlib import OAuth1Session
def new_oauth(yaml_path):
'''
Return the consumer and oauth t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.