content stringlengths 5 1.05M |
|---|
"""
File: dashboard.py
Author: Come Bertrand
Email: bertrand.cosme@gmail.com
Github: https://github.com/ComeBertrand
Description: dashboard drawing functions.
"""
from datetime import timedelta
from bokeh.layouts import layout, column
from bokeh.models import ColumnDataSource, CustomJS, Panel, Tabs, Div, Slider
from... |
import json
import pyspark
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from jupyterlab_sql_editor.ipython_magic.common.export import (
Function,
SchemaExporter,
Connection,
Catalog,
SparkTableSchema,
Table,
)
class SparkConnection(Connection):
def __init__(self, s... |
from dynaconf import settings
# test default loader never gets cleaned
print("store:", settings.store)
print("loaders:", settings.loaded_by_loaders)
print("dotenv_overrride:", settings.DOTENV_OVERRIDE_FOR_DYNACONF)
print("redis:", settings.REDIS_FOR_DYNACONF)
print("PYVAR", settings.PYVAR)
print("YAMLVAR", settings.Y... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
s = sys.stdin.readline().strip()
p = sys.stdin.readline().strip()
s = s + s
if p in s:
print('Yes')
else:
print('No')
|
# algorithm tolerance
CCD_COVERGENCE_TOL = 1e-10
BISECTION_TOL = 1e-5
ADMM_TOL = 1e-10
MAX_ITER = 5000
BISECTION_UPPER_BOUND = 10
MAXITER_BISECTION = 5000
# bounds
MIN_WEIGHT = 0
MAX_WEIGHT = 1e3
RISK_BUDGET_TOL = 0.00001
|
from flask import Blueprint
from flask import request, jsonify, make_response, Blueprint
from functools import wraps
from app.api.v1.models.meetup import Meetup
from app.api.v1.models.user import User
from app.api.v1.utils.meetup_validators import MeetupValidator
from app.api.v1.models.base_model import Authentication... |
# License MIT (https://opensource.org/licenses/MIT).
from . import test_newbalance
from . import test_pos_debt
|
import os
from pathlib import Path
from typing import Tuple
from .constants import Errors, ErrorTypes, Files, ModuleCst, Templates
from .module_parser import ModuleParser
from .utils import (
create_file,
get_name_component,
is_combinational,
is_sequential,
)
__all__ = ['Analysis']
class Analysis(ob... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
from numpy.linalg import cholesky
from math import sin, cos, atan, sqrt
import math
from scipy.interpolate import interp1d
from scipy.integrate import ode
from scipy.integrate import solve_ivp
from scipy.linalg import expm
from scipy.linalg... |
from pathlib import Path
from params_proto.neo_hyper import Sweep
from sac_dennis_rff.config import Args, Actor, Critic, Agent
from model_free_analysis import RUN
with Sweep(RUN, Args, Actor, Critic, Agent) as sweep:
Args.dmc = True
Args.checkpoint_root = "gs://ge-data-improbable/checkpoints"
Args.save_f... |
""" Tic Tac Toe
----------------------------------------
https://hackr.io/blog/python-projects
"""
import random
import sys
# board initialized as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
board=[i for i in range(0,9)]
player, computer = '',''
# Corners, Center and Others, respectively
moves=((1,7,3,9), (5,), (2,4,6,8))
# Winne... |
### ----------------------------------------------------------------------------
### Import
### ----------------------------------------------------------------------------
import pandas as pd
URI_TREINO = "https://github.com/tgcsantos/quaretenadados/blob/master/DADOS_TREINO.csv?raw=true"
URI_TESTE = "https://github.c... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
class ProgressiveWebmMuxingManifestType(Enum):
DASH_ON_DEMAND = "DASH_ON_DEMAND"
NONE = "NONE"
|
def alphabet_war(fight):
d = {'w':4,'p':3,'b':2,'s':1,
'm':-4,'q':-3,'d':-2,'z':-1}
r = sum(d[c] for c in fight if c in d)
return {r==0:"Let's fight again!",
r>0:"Left side wins!",
r<0:"Right side wins!"
}[True]
|
# Copyright 2021 DeepMind Technologies Limited. 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 ... |
import numpy
if __name__ == '__main__':
n = 4
a = numpy.loadtxt('a.txt').tolist()
b = numpy.loadtxt('b.txt').tolist()
x = numpy.loadtxt('x.txt')
y = numpy.loadtxt('y.txt')
print(numpy.dot(x, y).diagonal().sum())
for k in range(n):
print(numpy.linalg.matrix_power(x, 2)[k, :].sum(... |
# Copyright 2014-2018 The PySCF Developers. 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 appl... |
from stmlearn.equivalencecheckers import SmartWmethodEquivalenceChecker, Sequential
from stmlearn.equivalencecheckers.experimental import GeneticEquivalenceChecker
from stmlearn.learners import TTTMealyLearner
from stmlearn.suls import MealyDotSUL
from stmlearn.util import MATExperiment, bfs, Logger
from stmlearn.suls.... |
#!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '1APeMsNoGiUcf9o7i8y2_5hI687DDexq4ymuQQK_mO3k'
|
from dataclasses import dataclass
from uff.uff_io import Serializable
from uff.utils import PRIMITIVE_INTS
@dataclass
class TimedEvent(Serializable):
"""
UFF class to describe a TR/RX event transmitted at a given moment in time.
Attributes:
event (int): Index of the uff.event within the l... |
import angr
from angr.sim_type import *
from angr.state_plugins import SimActionObject
from cle.backends.externs import ExternObject
from nativedroid.analyses.resolver.annotation import *
from nativedroid.analyses.resolver.jni.java_type import *
from nativedroid.analyses.resolver.jni.jni_helper import *
from nativedro... |
import os
class RosettaScoreData(object):
def __init__(self):
self.score = None
self.rms = None
self.maxsub = None
self.description = None
self.model = None
class RosettaScoreParser(object):
def __init__(self, directory):
self.directory = directory
s... |
from datetime import date
from typing import Tuple, Generator
from pidriver.feature import feature
if feature("DEBUG_MODE"):
class InkyPHAT:
WIDTH: int = 212
HEIGHT: int = 104
BLACK: int = 0
WHITE: int = 255
RED: int = 127
else:
from inky import InkyPHAT
from PIL i... |
"""Package just imports contents of serve module
"""
from sporran.serve import *
|
def headers():
return ("captured-at" + "\t"
"consumption(W)" + "\t"
"pvpower(kW)" + "\t"
"consumption+pvpower(W)" + "\t"
"consumption-pvpower(W)")
def write_result(fname, consuption, power, dt):
with open(fname, "a") as f:
line = (dt.strftime("%Y-%m-%dT%H... |
import numpy as np
import torch
import torch.nn as nn
import os
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
from utils.opt import parse_option
from torch.utils.tensorboard import SummaryWriter
from torchvision.datasets import mnist
from torch.nn import CrossEntropyLoss
from torch.optim i... |
# Copyright 2021 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Imu, Temperature, MagneticField
from geometry_msgs.msg import Vector3
import subprocess
from .src.bwt901cl import BWT901CL
class Imu901cl(Node):
def __init__(self, time_interval=1.0):
super().__init__('imu_bwt901cl')
self.pub_imu... |
for i in range(0, 6):
print(""" / __ \ \__/ / __ \ \__/ / __ \ \__/ / __ \ \__/ / __ \ \__/ / __ \ \_
/ / \ \____/ / \ \____/ / \ \____/ / \ \____/ / \ \____/ / \ \__""")
if i < 5:
print("""\ \__/ / __ \ \__/ / __ \ \__/ / __ \ \__/ / __ \ \__/ / __ \ \__/ / _
\____/ / \ \____/ / \ \____/ / \ \____/ / \ ... |
import itertools as itl
correct = set(range(1,10))
def three(l):
return [l[:3],l[3:6],l[6:9]]
def check(s):
for r in s:
if set(r) != correct:
return False
for c in zip(*s):
if set(c) != correct:
return False
for r in three(s):
for m in three(list(zip(*r))):
ms = list(itl.chain(*m))
if set(ms) !... |
default_app_config = 'apps.posts.apps.PostsConfig'
|
import json
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.db import models
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from django.views.generic.detail impor... |
# Copyright 2015 OpenStack Foundation
# 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 requ... |
# Generated by Django 3.0.6 on 2020-05-30 21:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
#!/usr/bin/env python
# coding: utf-8
import re, string
import os
import time
import jieba
import argparse
from smart_open import open
def contain_city(line, city_list):
# segment the sentence using jieba
words = set(' '.join(jieba.cut(line, cut_all=False)).split(' '))
for city in city_list:
... |
from skimage.io import imread
from skimage.segmentation import slic
from skimage.util import img_as_float
from multiprocessing import cpu_count
from joblib import Parallel, delayed
from os.path import exists
from os.path import join
from tqdm import tqdm
from os import mkdir
import torch
def create_masks(imageList, n... |
from revoscalepy.computecontext.RxComputeContext import RxComputeContext
from revoscalepy.computecontext.RxInSqlServer import RxInSqlServer
from revoscalepy.computecontext.RxInSqlServer import RxSqlServerData
from revoscalepy.etl.RxImport import rx_import_datasource
class DataSource():
def __init__(self, connect... |
from pysc2.lib import actions as sc2_actions
from pysc2.lib import features
_LOAD_MODEL_PATH = "./model/20180621-134211/"
_SAVE_MODEL_PATH = "./model/"
# define the num of input and output
_SIZE_HIGH_NET_INPUT = 20
_SIZE_HIGH_NET_OUT = 3
_SIZE_CONTROLLER_OUT = 2
_SIZE_BASE_NET_OUT = 2
_SIZE_TECH_NET_INPUT = 9
_SIZE... |
import os
import unittest
import numpy as np
from pymatgen.core.structure import Molecule
from pymatgen.io.qchem.outputs import QCOutput
from atomate.qchem.firetasks.geo_transformations import PerturbGeometry, RotateTorsion
from atomate.utils.testing import AtomateTest
__author__ = "Brandon Wood, Evan Spotte-Smith"
... |
import time
import busm
EXECUTION_TIME = 0.13
@busm.through_smtp
def smtp_sample():
time.sleep(EXECUTION_TIME)
print('Call smtp_sample().')
@busm.through_line
def line_sample():
time.sleep(EXECUTION_TIME)
print('Call line_sample().')
@busm.through_telegram
def telegram_sample1():
time.sleep(EXEC... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class Tests:
lc_tool_opened = (
"Landscape Canvas tool opened",
"Failed to open Landscape ... |
# coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from pants_test.test_base import TestBase
from pants.contrib.node.targets.node_module im... |
""" Provides an installer for dependencies. """
from __future__ import annotations
import abc
import dataclasses
import logging
import shlex
import subprocess as sp
import typing as t
from pathlib import Path
from slap.python.dependency import MultiDependency
from slap.python.pep508 import filter_dependencies, test_... |
import logging
################################################################################
# database configuration
################################################################################
DB_TYPE = 'sqlite'
DB_ARG = 'phxd.db'
############################################################################... |
from icemac.addressbook.i18n import _
from .interfaces import IBirthDate
import icemac.addressbook.browser.base
import zope.component
class ExportList(icemac.addressbook.browser.base.BaseView):
"""List available export formats."""
title = _('Export person data')
def exporters(self):
"""Iterable ... |
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
def enable_debug_logger():
logger.setLevel(loggin... |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD.
# See https://nomad-lab.eu for further info.
#
# 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/lic... |
#
# ojar - [o]jar rune
# https://github.com/vesche/ojar
#
def clear(_):
from os import system, name
system('cls' if name == 'nt' else 'clear')
return _
def info(_):
from runes.common import list_functions
return '[o]jar rune\nactions: {}'.format(list_functions(__name__))
def runelist(_):
r... |
# This is the main file for this app
# Start Date - 20.11.21
# Srikara Narasimha
"""this is open-source and free to copy."""
""" Under the unlicence licence. Read LICENCE page """
from tkinter import *
root = Tk()
root.title("All in One Converter - Srikara Narasimha")
# root.geometry("500x500+0+0")
root.eval('tk::Pl... |
"""
Multiclass test for unsupervised and deterministic classification of membrane-bound particles
Input: - The STAR file with the particles to classify
- Classification parameters
Output: - A set of STAR files with the new classes
- 2D rotational averaged around membrane normal e... |
#!/usr/bin/env python3
import argparse, joblib
from collections import Counter
import logging, sys
logger = logging.getLogger(__name__)
logger.setLevel(10)
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)s - %(message)s"))
logger.addHandler(ch)
def main():
par... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 河北雪域网络科技有限公司 A.Star
# @contact: astar@snowland.ltd
# @site: www.snowland.ltd
# @file: _SM4.py
# @time: 2018/9/21 15:25
# @Software: PyCharm
"""
SM4 GM
@author: Dawei
@author: A.Star
"""
import copy
import struct
import time
from functools import reduce
# Exp... |
import pygame
from Character import Character
class Otis(Character):
def __init__(self):
super().__init__()
self.name = 'Otis'
self.health = 200
self.health = 0
self.portrait = pygame.image.load('Sprites/Otis/OtisPortrait.png')
self.image = pygame.image.load('Spri... |
# -*- coding:utf-8 -*-
from PythonMiddleware.notify import Notify
from PythonMiddleware.graphene import Graphene
from PythonMiddlewarebase.operationids import operations
import sys
import pymongo
import datetime
from time import sleep
from collections import deque
from threading import Thread, Lock
from prometheus_cl... |
"""
[summary]
[extended_summary]
"""
# region [Imports]
# * Standard Library Imports ------------------------------------------------------------------------------------------------------------------------------------>
import gc
import os
import unicodedata
from abc import ABC, abstractmethod
from typing import Ca... |
import unittest
from best_line import best_line
class Test_Case_Best_Line(unittest.TestCase):
def test_best_line(self):
self.assertEqual(best_line([(0, 1), (1, 2), (2, 3), (-5, 5)]), '1.0:1.0') |
import uuid
from django.template.response import TemplateResponse
def document_view_html(request, id):
"""Renders the document as html"""
obj = get_object_or_404(Post, pk=uuid.UUID(id))
template = "detail_view.html"
context = {}
context["data"] = MyModel.objects.get(id=id)
return TemplateR... |
from .c_perfevaluator import CPerfEvaluator
from .c_perfevaluator_xval import CPerfEvaluatorXVal
from .c_perfevaluator_xval_multiclass import CPerfEvaluatorXValMulticlass
|
#
# Author: Stanislaw Adaszewski, 2015
#
import networkx as nx
import numpy as np
import time
from numpy import array, tile, concatenate
from numpy.linalg import norm
class ConstrainedKMeans(object):
def __init__(self):
pass
def fit(self, data, demand):
C, M, f = constrained_kmeans(data, demand)... |
import os, sys, six, re, json
import unicodedata
import logging
import numpy as np
from collections import defaultdict
from modules.backend import K, tf
_open_ = open
is_py2 = six.PY2
if not is_py2:
basestring = str
def is_string(s):
"""判断是否为字符串
"""
return isinstance(s, basestring... |
type = 'SMPLify'
body_model = dict(
type='SMPL',
gender='neutral',
num_betas=10,
keypoint_src='smpl_45',
keypoint_dst='smpl_45',
model_path='data/body_models/smpl',
batch_size=1)
stages = [
# stage 1
dict(
num_iter=20,
fit_global_orient=True,
fit_transl=True... |
def test_basic(app):
assert app.name == 'quokka'
|
period1 = 50
period2 = 200 |
class My(object):
y = 5988
class Mt(My):
z = 598
class Mat(Mt):
x = 54
p1=Mat()
print(p1.x)
print(p1.y)
print(p1.z)
|
# Copyright 2019 Xilinx Inc.
#
# 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, ... |
from django.core.validators import MinLengthValidator, MinValueValidator
from django.db import models
class Profile(models.Model):
USER_NAME_MAX_CHARS = 15
USER_NAME_MIN_CHARS = 2
MIN_AGE = 0
user_name = models.CharField(
max_length=USER_NAME_MAX_CHARS,
validators=(
MinLen... |
import pandas as pd
import streamlit as st
from sklearn.ensemble import RandomForestClassifier
st.title('Model Deployment: Insurance Fraud Detection')
st.sidebar.header('User Input Parameters')
def user_input_features():
claim_type = st.sidebar.selectbox('claim_type',('1','2','3','4','5'))
uninhab... |
import socket
import select
import config
class IRCConnection:
def __init__(self, serverName, port=6667):
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect((serverName, port))
self.connection.setblocking(0)
def sendMessage(self, toSend):
... |
"""command_line.py"""
import vbiz_parser
import sys
import getopt
def main():
"""main"""
input_file = ''
output_file = ''
upload_path = ''
try:
opts, args = getopt.getopt(sys.argv[1:], "hi:o:u:", [
"ifile=", "ofile=", "upath="])
except getopt.GetoptE... |
import argparse
import sys
import yt
# hard-coded parameters (in code units)
field = 'particle_mass'
proj_axis = 'z'
center = [0.5, 0.5, 0.5]
width_x = 1.0e-2
width_y = 1.0e-2
width_z = 1.0e-2
colormap = 'arbre'
dpi = 150
# load the command-line parameters
parser = argparse.ArgumentParser( descr... |
import os
import time
import json
import psutil
from importlib import import_module
from collections import defaultdict
from pprint import pprint
"""
This is my implementation of the TaskExecutor. Each Task can be run at most:
max_instances (int) within a given time_bound (int: in minutes).
Each Task's guard is depe... |
# -*- coding: utf-8 -*-
#
# This file is part of Django facets released under the MIT license.
# See the LICENSE for more information.
from __future__ import (print_function, division, absolute_import, unicode_literals)
from django.conf import settings as _settings
DEFAULTS = {
'FACETS_ENABLED': not _settings.DEB... |
# -*- 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... |
import pokemon
def main():
pokemon.do_post()
if __name__ == "__main__":
main()
|
# Copyright 2021 The NetKet 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 applicable ... |
class MergeSort:
@staticmethod
def sort(array):
if(array == None):
print('Input array is empty')
l = len(array)
if(l >= 1):
MergeSort.mergeSort(0,l-1,array)
@staticmethod
def mergeSort(i,j,array):
if(i < j):
mid = (i+j)/2
M... |
#TODO: Add some form of analysis?,
#Edit proxy cycling, so the process originator loop passes the # of proxy to use
#Additionally, need to add a fail state -- raised exception if there's more than x loops of proxy or captcha cycling....
#Research whether we can pull more than 20 proxyList at once
####Possibly even sta... |
#
# (c) 2017 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... |
import kb, json, os
import libkbot as libkb
class quote:
level = 1
keywords = ['цитата','цит']
def handler(self,msg):
msg = libkb.fix_names(msg)
msg['config'] = kb.config
arg = json.dumps(msg)
os.system("python3 plugins/quote/quote.py '"+arg+"'")
kb.reg_command(quote()) |
from __future__ import annotations
# This concept of channels comes directly from the Kraken API docs : https://docs.kraken.com/websockets/#message-ohlc
import asyncio
import functools
from dataclasses import dataclass, field
import typing
from types import MappingProxyType
from aiokraken.model.timeframe import KTim... |
import json
def de_duplication(str):
dedup_str = ''
for char in str:
if not char in dedup_str:
dedup_str += char
return dedup_str
with open('data/new/dev.txt', 'rt', encoding='utf-8') as fin:
char_vector=""
for line in fin:
line = line.strip()
if not line:
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright 2011 Google 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... |
""" a2c algorithm implementation.
"""
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions.categorical import Categorical
os.environ['KMP_DUPLICATE_LIB_OK']='True'
device = torch.device("cuda" if torch.cuda.is_available... |
from experiment.generic_p1 import P1GetExptRecordingInfo
from azure_service_bus.send_consume import AzureReceiver
class P1AzureGetExptRecordingInfoReceiver(AzureReceiver, P1GetExptRecordingInfo):
pass
|
# -*- coding: utf-8
from __future__ import unicode_literals, absolute_import
from django.conf.urls import url, include
from heavy_celery.urls import urlpatterns as heavy_celery_urls
urlpatterns = [
url(r'^', include((heavy_celery_urls, 'heavy_celery'), namespace='heavy_celery')),
]
|
"""
Copyright (C) 2021 Alyssa Rosenzweig <alyssa@rosenzweig.io>
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, modify, m... |
import sys
import math
import time
import logging
import numpy as np
import cv2
import pyrealsense2 as rs
from shapely.geometry import Polygon, JOIN_STYLE
from scipy import spatial
from descartes import PolygonPatch
M2TOCM2 = 10000
CMTOM = 0.01
DS5_product_ids = ["0AD1", "0AD2", "0AD3", "0AD4", "0AD5", "0AF6",
... |
#!/usr/bin/env python
from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
parameter_list = [[traindat,testdat,10,3,1.0],[traindat,testdat,10,4,1.0]]
def kernel_sparse_poly (fm_train_real=traindat,fm_test_real=t... |
"""
@author: Yuhao Cheng
@contact: yuhao.cheng[at]outlook.com
"""
import torch
import torch.nn as nn
from collections import OrderedDict
import torchsnooper
from ..model_registry import META_ARCH_REGISTRY
from pyanomaly.networks.meta.base.commonness import (
PixelDiscriminator,
DoubleConv,
Do... |
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
l1 =[]
while n!=1 and n not in l1:
l1.append(n)
m = str(n)
n =0
for i in m:
n += int(i)**2
return n == 1
|
"""
Django settings for onlineCAL project.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
... |
# python
import string
from typing import Type, Set
# django
from django.utils.text import camel_case_to_spaces
# graphene
import graphene
from graphene.types.generic import GenericScalar
# graphene_django
from graphene_django import DjangoObjectType
# wagtail
from wagtail.core.fields import StreamField
from wagtail.co... |
import stripe
from stripe import error
from stripe import util
from stripe.api_resources import Customer
from stripe.six.moves.urllib.parse import quote_plus
from async_stripe.api_resources.abstract import patch_nested_resources
async def detach_patch(self, idempotency_key=None, **params):
token = util.utf8(self.... |
import subprocess
def create_blast_database(fasta_str, save_path):
"""
:param fasta_str:
:param save_path:
:return:
"""
with open(save_path + 'fasta.txt', 'w') as f:
f.write(fasta_str)
f.close()
database_filename = save_path + '_database'
# creation of the makeblastdb... |
import six
from ..interface import (ContractSyntaxError, describe_value,
ContractNotRespected)
from ..main import parse_contract_string, check_contracts
def check_contracts_ok(contract, value):
if isinstance(contract, six.string_types):
contract = [contract]
value = [valu... |
import os
import typing
import tarfile
import jk_pathpatternmatcher2
from .utils.ServiceInfo import ServiceInfo
from .utils.ServiceMgr import ServiceMgr
from .ThaniyaBackupContext import ThaniyaBackupContext
class ThaniyaService:
@staticmethod
def getServiceStatus(ctx:ThaniyaBackupContext, serviceName:str) ... |
from typing import Optional, Union
import lldb
from pwndbg.bridge.interface import IDbg
def bridge_lldb() -> Optional[IDbg]:
try:
import lldb
if lldb.debugger:
return LldbImpl()
else:
return None
except ImportError:
return None
class LldbImpl(IDbg):
... |
"""
This is an implementation of the Demetrescu, Italiano and Emiliozzi dynamic Potentially Uniform Paths algorithm (PUP)
http://www.dis.uniroma1.it/demetres/experim/dsp/
"""
###
#from LDSP.h
#this is a library function
class Heap:
def __init__(self):
#init
def extractMin(self):
#todo
de... |
from __future__ import absolute_import, division, print_function
import os
import pre_commit.main
# work around https://github.com/Homebrew/homebrew-core/issues/30445
os.environ.pop("__PYVENV_LAUNCHER__", None)
def main():
return pre_commit.main.main(
["run", "--config", ".pre-commit-config.yaml", "--h... |
from .parse import extract_blog_from_XML
from . import parse
from . import latexwrite
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.