content stringlengths 5 1.05M |
|---|
from puzzle_input import puzzle_input
from collections import Counter, defaultdict
PUZZLE_INPUT = [int(i) for i in puzzle_input().splitlines()]
sort = tuple(sorted(PUZZLE_INPUT + [max(PUZZLE_INPUT) + 3]))
c = Counter()
sections = []
prevx = 0
lasti = 0
for i, x in enumerate(sort):
c[x - prevx] += 1
if x - p... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from struct import *
from PIL import Image, ImageDraw, ImageFont
import sys
print "preparing data"
s = ''
data = ""
n = 0
for i in range(32,127):
s += "%c"%i
data += "{0:#06x}, ".format(i)
n += 1
if ((n%12) == 0):
data += "\n"
c = ''
count = 0
for i in range(0xa1,0x... |
#importing all the libraries that we'll require in the process
import tensorflow as tf
from tensorflow import keras
import os
import numpy as np
import matplotlib.pyplot as plt
import cv2
#set the datadir to the path with the training images
datadir = (r" ")
#creating the categories that will act as labels for our ... |
import os
import tempfile
from os.path import dirname
from pathlib import Path
import src.superannotate as sa
from tests.integration.base import BaseTestCase
class TestFilterInstances(BaseTestCase):
PROJECT_NAME = "test filter instances"
PROJECT_TYPE = "Vector"
TEST_FOLDER_PATH = "data_set/sample_project... |
import foohid
import struct
import random
import time
joypad = (
0x05, 0x01,
0x09, 0x05,
0xa1, 0x01,
0xa1, 0x00,
0x05, 0x09,
0x19, 0x01,
0x29, 0x10,
0x15, 0x00,
0x25, 0x01,
0x95, 0x10,
0x75, 0x01,
0x81, 0x02,
0x05, 0x01,
0x09, 0x30,
0x09, 0x31,
0x09, 0x32... |
from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
import random as rng
rng.seed(12345)
def thresh_callback(val):
threshold = val
imagen = cv.imread('imagen_1.png')
hsv = cv.cvtColor(imagen, cv.COLOR_BGR2HSV)
#Rango de colores detectados:
#Rojo:
Rojo_... |
#!/usr/bin/python3
# Palindrome Check Function on Python 3
# The Palindrome Algorithm
# this takes in a string and returns a boolean equal to the result of
# whether the program is a palindrome or not.
def palindrome(s: str) -> bool:
# Reverse string using idiomatic python
reversed_string = s[::-1]
# retur... |
import random
import aiohttp
import discord
import asyncio
import secrets
from discord.ext import commands
from cogs.utils import utilities as utils
from typing import Union
class Fun(commands.Cog, name="Fun"):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def pizza(self, c... |
from dataclasses import asdict
from it.reports import Report, _prepare_result
def test_prepare_result(tmp_path):
reports = [
asdict(Report("MY_ERROR", 0, 0, tmp_path / f"{idx}.py"))
for idx in range(3)
]
reports = {"blabla": reports[:1], "otherbla": reports[1:]}
assert _prepare_result... |
from tkinter import *
class Widget:
def Label(self,win,text='',bg='#3b93e7',fontType='bold',fontSize=14,x=0,y=0):
self = Label(
win,text=text,bg=bg,font=('times new roman',fontSize,fontType)
).place(x=x,y=y)
def Button(self,win,text,cmd,width=0,x=0,y=0):
self = Button(win,text=text,wi... |
from datetime import datetime
from django.db import models
from fin_manager.users.models import User
class Category(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User, related_name='categories')
description = models.TextField()
def __str__(self):
return '%... |
try:
# 3.6 or greater
from typing import ContextManager
except ImportError: # pragma: no cover
# <3.6 we create a ContextManager TypeHint
# We implement the AbstractContextManager abc and
# create the ContextManager class for TypeHint's
# This is taken directly from the standard lib(s)
imp... |
from __future__ import absolute_import
from .model import Missing
def is_route_admitted(apiobj):
return apiobj.model.status.can_match({
'ingress': [
{
'conditions': [
{
'type': 'Admitted',
'status': 'True',
... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
import os
macrosFile = open("macros.doskey", "w")
n = macrosFile.write("gits=python \"" + os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + "\code\gits.py\" $*")
macrosFile.close()
gitPath = os.path.join(os.getcwd(), ".gits")
os.mkdir(gitPath)
logPath = os.path.join(gitPath, "logs")
os.mkdir(logPath)
autoRunF... |
#!/usr/bin/python
import sys
import time
import json
import collections
import re
import ast
import openconfig_acl_client
from rpipe_utils import pipestr
from openconfig_acl_client.rest import ApiException
from scripts.render_cli import show_cli_output
import urllib3
urllib3.disable_warnings()
plugins = dict()
def r... |
"""
Acme Products
"""
import random
import unittest
class Product(object):
# class of all products
def __init__(self, name, price=10, weight=20, flamability=0.5):
self.name = name
self.price = price
self.weight = weight
self.flamability = flamability
# identifier of pro... |
# Generated by Django 3.1.6 on 2021-02-28 19:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book_shelf', '0004_book_image'),
]
operations = [
migrations.AlterField(
model_name='book',
name='book_format',
... |
from NERTranserLearning.Experiment import Experiment
class ExperimentTransferTddTraining(Experiment):
"""
Contains the configurations of the transfer learning training on various data-sets for both Elmo and naive
embeddings with TDD output layer.
It's crucial the training will run in a sequential ord... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-10 08:31
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0004_auto_20160610_0111'),
]
operations = [
migrations.RenameField(
... |
from pathlib import Path
from src.data.annotation_utils import LabelStudioConvertor
annotation_json = Path("data/quittances/annotation/sample1.json")
output_path = Path("data/quittances/annotation/sample_1.csv")
df_annotation = LabelStudioConvertor(annotation_json, output_path).transform()
df_annotation.to_csv(outpu... |
from datetime import date, timedelta
from django import template
from django.conf import settings
from wiki.models import VIGA_TEKSTIS, Artikkel, Isik, Organisatsioon, Objekt, Kaart, Kaardiobjekt
from wiki.views import get_all_logged_in_users #, artikkel_qs_userfilter
register = template.Library()
@register.inclusi... |
# Copyright 2022 Neuron-AI GitHub 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 appli... |
from . import popcatutils
from aiohttp import ClientSession
base_url = "https://api.popcat.xyz/"
base = "https://api.popcat.xyz/"
# /country endpoint
async def country(name:str, property=None):
async with ClientSession() as cs:
async with cs.get(f"https://api.popcat.xyz/countries/{name}") as r:
data = awa... |
import random
import argparse
import gzip
import pickle
import numpy as np
from math import exp, log
from collections import defaultdict
SEED = 1735
random.seed(SEED)
class Numbers:
"""
Class to store MNIST data for images of 0 and 1 only
"""
def __init__(self, location):
# You shouldn't ... |
from django.contrib import admin
# Register your models here.
from .models import Post,views
admin.site.register(Post)
admin.site.register(views)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Dominic Schaff'
SITENAME = 'Random Things'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Africa/Johannesburg'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
TRANSLATION_FEED_ATOM = None
AUTHO... |
from zipfile import ZipFile
from config import FILES_PATH
from shutil import copyfile, rmtree
import time
import os
def create_zipfile(files):
timestamp = str(int(time.time()))
tmp_location = "/tmp"
zip_location = '{}/{}.zip'.format(tmp_location, timestamp)
# create tmp dir with all files
os.mkdi... |
from __future__ import print_function, division
import nflwin.model
import nflwin.utilities
import numpy as np
import pandas as pd
def query_db_players():
"Make the database query for player information."
engine = nflwin.utilities.connect_nfldb()
sql_string = ("select player.player_id, player.full_name... |
import os
from mutract.utils import Mutract
import celescope.tools.utils as utils
from celescope.tools.step import s_common
@utils.add_log
def snpCalling(args):
sample = args.sample
outdir = args.outdir
thread = int(args.thread)
match_dir = args.match_dir
bam = args.bam
genomeDir = args.gen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The most accurate way to time your stimulus presentation is to
present for a certain number of frames. For that to work you need
your window flips to synchronize to the monitor and not to drop
any frames. This script examines the precision of your frame flips.
Shut do... |
# created 2013 Feb 23 by MES
# reads in all Q4 simulation json files in directory and outputs to Q4sim_positions.txt
# the start x and end x position of tne injected transit(s) if present
# not all Q4 simulations jsons will have a planet transit in it so if there is no planet transit
# present in a given json ... |
from django.db import models
class Comment(models.Model):
content = models.TextField(max_length=200)
creation_date = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(
"group_members.GroupMember",
related_name="posted_comments",
on_delete=models.CASCADE,
)
u... |
from aws_cdk import core
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_elasticloadbalancingv2 as elbv2
import aws_cdk.aws_autoscaling as autoscaling
with open("./user_data/user_data.sh") as f:
user_data = f.read()
class AppStack(core.Stack):
def __init__(self, scope: core.Construct, construct_id: str, vp... |
#!/usr/bin/env python3
import os
import pickle
import hashlib
import lab
import pytest
TEST_DIRECTORY = os.path.dirname(__file__)
def object_hash(x):
return hashlib.sha512(pickle.dumps(x)).hexdigest()
def compare_images(im1, im2):
assert set(im1.keys()) == {'height', 'width', 'pixels'}, 'Incorrect keys i... |
from django import forms
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.urls import reverse
import posts.settings as posts_settings
from posts.models import Follow, Group, Post
from posts.tests.test_settings import AllSe... |
import numpy as np
import torch
import torch.utils.data
import argparse
import os
from metrics import *
import logging
logging.basicConfig(format='[%(filename)s:%(lineno)d] %(message)s')
logging.getLogger().setLevel(logging.DEBUG)
logger = logging.getLogger(__name__)
def get_files(path):
paths = []
if os.path.i... |
import glob
import logging
import os
import qt
import vtk
import ctk
import slicer
from slicer.util import settingsValue, toBool
from slicer.ScriptedLoadableModule import *
import DICOMLib
#
# DICOM
#
# This code includes the GUI for the slicer module. It is supported
# by the DICOMLib python code which implements m... |
import os
x = os.getcwd()
print(x)
os.chdir('c:\\')
print(os.getcwd())
os.chdir(x)
print(os.getcwd())
|
# ----------------------------------------------------------------------------
# Copyright 2019-2021 Pelion
#
# SPDX-License-Identifier: Apache-2.0
#
# 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 Licens... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
#!/usr/bin/env python3
import sys
import numpy
SEAFLOOR_DIM = 1000 # could be dynamic based on max dimension seen in the input data, but I am lazy
def clamp(val):
return max(-1, min(-1, value))
if len(sys.argv) != 2:
print("Help: {} <filename>".format(sys.argv[0]))
sys.exit(0)
lines = [] # ... |
# Generated by Django 2.2 on 2019-04-16 13:59
from django.db import migrations, models
import versatileimagefield.fields
class Migration(migrations.Migration):
dependencies = [
('product', '0093_product_video'),
]
operations = [
migrations.AddField(
model_name='category',
... |
#!/usr/bin/python
import time
import energenie
import sys
import os
import threading
import RPi.GPIO as GPIO
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib2 import Http
import traceback
from energenie import OpenThings
from energenie import Devices
class PIRCallback:
def __init__(self,se... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
from tensorflow.python.platform import googletest
from tensorflow.tensorboard import float_wrapper
_INFINITY = float('inf')
class FloatWrapperTest(googletest.TestCase):
... |
#!/usr/bin/env python3
# coding=utf-8
import logging
log = logging.getLogger("pycardmaker")
from pathlib import Path
from pgmagick import Image, Geometry, Color, CompositeOperator, DrawableRoundRectangle
class MyImage:
def __init__(self, w, h):
self.img = Image(Geometry(int(w), int(h)), 'transparent')
... |
#!/usr/bin/env python
# Copyright 2015, Rackspace US, 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... |
import logging
class ReportProgress:
def __init__(self, upload, logEveryBytes):
self._upload = upload
self._logEveryBytes = logEveryBytes
self._lastLog = 0
def log(self, bytesTransferred, total):
if bytesTransferred / self._logEveryBytes <= self._lastLog:
return
... |
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame, text="Button 1", fg="red")
button2 = Button(topFrame, text="Button 2", fg="blue")
button3 = Button(topFrame, text="Button 3", fg="green")
button4 = Button(bottomF... |
#!/usr/bin/env python2
"""
SYNOPSIS
Preprocess the METABRIC Breast Cancer data into a MAF format that is suitable
for input into the Hotspots 'Mutation_Counts' pipeline.
NOTES
(1) Assume that "Reference_Allele"/"Tumor_Seq_Allele1"/"Tumor_Seq_Allele2"
values in input ('--in_genomics') already sati... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Name: ComputerVision
File Name: train_detector.py
"""
__author__ = 'Welkin'
__date__ = '2019/10/11 15:05'
import argparse
from cvmodels.trainer import DetectionTrainer
def parse_args():
parser = argparse.ArgumentParser(description='PyTorch VOC Dat... |
class PrivateTest:
def __init__(self):
self.public_x = "I'm public"
self.__private_y = "I'm invisible"
self._private_z = "I'm not invisible"
def print_y(self):
print(self.__private_y)
def __get_y(self):
return self.__private_y
if __name__ == "__main__":
private... |
# -*- coding: utf-8 -*-
"""
Created on Thu 27 2017
@author: neerbek
"""
import unittest
import numpy
from numpy.random import RandomState
import theano
import theano.tensor as T
import tests.RunTimer
import embedding
def mult_embedding(e1, e2):
if len(e1) != len(e2):
raise Exception("e1 and e2 need to... |
import clr
from forms.forms import WPFWindow
clr.AddReferenceByPartialName('System.Windows.Forms')
# noinspection PyUnresolvedReferences
import System
# noinspection PyUnresolvedReferences
from System.Windows.Controls import SelectionMode
# noinspection PyUnresolvedReferences
from System.Windows.Forms import FolderB... |
"""Condense manuscript into single files, often preferred by journals.
Usage: condense [--output_dir=<output_dir>] [<directory>]
"""
import argparse
import pathlib
import shutil
import re
STYLE_RE = re.compile(r"\\def\\style{\d}\s") # style statement + newline
INPUT_RE = re.compile(r"\\input{.*}") # an input state... |
#!/usr/bin/env python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... |
from apiwrapper.endpoints.endpoint import Endpoint
from apiwrapper.endpoints.monetary_account import MonetaryAccount
class CustomerStatement(Endpoint):
__endpoint_customer_statement = "customer-statement"
__endpoint_customer_statement_content = "content"
@classmethod
def _get_base_endpoint(cls, user... |
# 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.
from compiler_gym.service.proto.compiler_gym_service_pb2 import (
ActionSpace,
AddBenchmarkReply,
AddBenchmarkRequest,
Benchmar... |
# -*- coding: utf-8 -*-
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
from .app import main
__all__ = ['main']
def includeme(config):
config.include('h.authentication')
config.include('h.authorization')
config.include('h.features')
config.include('h.queue... |
# ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... |
# 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 ... |
#
# Copyright 2018 Analytics Zoo Authors.
#
# 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... |
from django.shortcuts import render, redirect
from django.views.generic.edit import FormView
from .forms import FileFieldForm
from ChromoGraph.chrofig import *
import os.path
import zipfile
class FileFieldView(FormView):
form_class = FileFieldForm # Upload from from forms.py for template
template_name = os.... |
from django.urls import path
from strawberry.django.views import GraphQLView
from .schema import schema
urlpatterns = [
path('graphql/', GraphQLView.as_view(schema=schema)),
]
|
def test_one_square_one_equal_one():
assert 1 == 1 |
from FEM.EulerBernoulliBeam import EulerBernoulliBeamNonLineal
from FEM.Mesh.Lineal import Lineal
import numpy as np
import matplotlib.pyplot as plt
L = 100
geometria = Lineal(L, 80, 1, 3)
geometria.cbe = [[0, 0.0], [1, 0.0], [2, 0.0], [-1, 0.0], [-2, 0.0], [-3, 0.0]]
W = 10.0
Fx = 0.0
I = 1/12
A = 1
E = 30000000.0
E... |
"""
Get number of the remaining days on my library hold
"""
from seleniumwire import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by i... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
*.py: Description of what * does.
Last Modified:
"""
__author__ = "Sathappan Muthiah"
__email__ = "sathap1@vt.edu"
__version__ = "0.0.1"
from country2 import GeoCoordinates
g = GeoCoordinates()
print g.query(10, 77)
|
from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, HTML, ButtonHolder
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.forms import (
ModelForm,
Te... |
# vim: set et nosi ai ts=2 sts=2 sw=2:
# coding: utf-8
from __future__ import absolute_import, print_function, unicode_literals
import argparse
import io
import sys
import threading
from schwa.dr import Reader, Writer
from six.moves import xrange
try:
import zmq
except ImportError:
zmq = None
def stream_corouti... |
"""api for image process functions.
Basic required arguments are list of movies or pictures (or directories where pictures are stored). if no movie or picture is given, function will not be processed (print error message and return False)
Output data (after image process) will be generated in 'cv2/target-noExtension/... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
class Human:
def __init__(self): self.__intro()
def intro(self): print('Human')
__intro = intro
def show_human(self): self.__intro()
class Programmer(Human):
def __init__(self): self.__intro()
def intro(self):
super().intro()
print('Programmer')
__intro = intro
def show_p... |
"""
.. _plot_parallel_prediction_example.py:
Parallel Prediction Example
===========================
This example demonstrates :class:`wrappers.ParallelPostFit`. A
:class:`sklearn.svm.SVC` is fit on a small dataset that easily fits in memory.
After training, we predict for successively larger datasets. We compare
1... |
import json
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from workflow.models import CustomField
from service.base_service import BaseService
from service.common.log_service import auto_log
class WorkflowCustomFieldService(BaseService):
def __init__(self... |
## Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera
## 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... |
## M-Estimators for Robust Linear Modeling
from __future__ import print_function
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.compat.pandas import sort_values
# * An M-estimator minimizes the function
#
# $$Q(e_i, \rho) = \sum_i~\rho \le... |
import pytest
from grandchallenge.components.models import InterfaceKindChoices
from grandchallenge.evaluation.models import Evaluation
from tests.factories import ChallengeFactory, EvaluationFactory
from tests.utils import get_view_for_user
@pytest.mark.django_db
def test_setting_submission_page_html(client, challe... |
'''
This file is used to train the neural networks that predict the spectrum
given any set of stellar labels (stellar parameters + elemental abundances).
Note that, the approach here is slightly different from Ting+18. Instead of
training individual small networks for each pixel separately, we train a single
large net... |
'''
Maintains stagnation behavior for speciation in Deep HyperNEAT.
Largely copied from neat-python (Copyright 2015-2017, CodeReclaimers, LLC.)
'''
import sys
from deep_hyperneat.util import iteritems, mean
class Stagnation:
# Stagnation class
def __init__(self, species_elitism=3):
self.species_fitnes... |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... |
from django.apps import AppConfig
class BrColponConfig(AppConfig):
name = 'br_colpon'
|
#!/usr/bin/env python
import argparse
from sklearn.datasets import make_classification
from sklearn.cross_validation import cross_val_score
from sklearn import svm
parser = argparse.ArgumentParser()
parser.add_argument("-gamma", type=float, default=0.001)
parser.add_argument("-C", type=float, default=0.5)
parser.add_... |
from urllib.request import urlretrieve
from threading import *
import bs4
import requests
import csv
import os
screenlock=Semaphore(value=1)
database=open("free-zipcode-database-Primary.csv")
mapRequestUrl="https://www.ups.com/maps/"
reader=csv.DictReader(database)
maplist=set() ... |
class BaseModel(object):
@classmethod
def connect(cls):
"""
Args:
Returns:
None
"""
raise NotImplementedError('model.connect not implemented!')
@classmethod
def create(cls, data):
"""
Args:
data (dict)
Returns:
... |
import unittest
from request_parsers import keystroke
class Keystroke:
id: int
meta_modifier: bool
alt_modifier: bool
shift_modifier: bool
ctrl_modifier: bool
key: str
key_code: int
class KeystrokeTest(unittest.TestCase):
def test_parses_valid_keystroke_message(self):
self.... |
import numpy as np
#Represents a (scalar or vector) term
class VectorTerm(object):
def __init__(self, numpy_array):
self.numpy_array = numpy_array
def __str__(self):
return str(self.numpy_array)
def __eq__(self, other):
return (isinstance(other, VectorTerm) and
np.ar... |
# SPDX-FileCopyrightText: 2021 easyCore contributors <core@easyscience.software>
# SPDX-License-Identifier: BSD-3-Clause
# © 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore>
__author__ = 'github.com/wardsimon'
__version__ = '0.1.0'
import weakref
import sys
from typing import Li... |
import time
from sundry import local_time_string, utc_time_string
def test_time_string():
t = time.time()
lts = local_time_string(t)
uts = utc_time_string(t)
for ts in [lts, uts]:
# basic check for a few fields
assert ts[0:1] == "2"
assert ts.find("-") == 4
assert ts.f... |
from biobb_common.tools import test_fixtures as fx
from biobb_pmx.pmx.pmxanalyse import pmxanalyse
class TestPmxanalyse:
def setUp(self):
fx.test_setup(self, 'pmxanalyse')
def tearDown(self):
#pass
fx.test_teardown(self)
def test_pmxanalyse(self):
pmxanalyse(properties=se... |
from typing import List
from .records import AccountOperationRecord, ACCOUNT_OPERATION_TYPE
from ._html_email_scrapers import banorte_email_scraper
EMAIL_TYPE = 'DIGITAL_DEBIT_CARD_CANCELED_EMAIL'
def is_matching(html: str) -> bool:
return 'Cancelación de Tarjeta Digital de Débito' in html
@banorte_email_scrap... |
import time
from functools import reduce, partial
from threading import Thread
import streamlit as st
import seaborn as sns
import tensorflow_probability as tfp
from matplotlib import pyplot as pl
'''streamlit'''
if 'pipeline' not in st.session_state:
pipeline = st.session_state.pipeline = []
else:
pipeline ... |
r"""We deal with the Parker loop, which is a non-associative Moufang loop.
The Parker loop is written multiplicatively its elements
can be represented as pairs in
the set :math:`\mathcal{P} = \mathcal{C} \times \mathbb{F}_2`, see
e.g. :cite:`Asc86`, :cite:`Con85`.
We also write ``1`` for the neutral element
:math:`(0... |
import argparse
import logging
import sys
from enum import Enum
from typing import Any, Callable, Optional
from annofabapi.models import JobStatus, ProjectJobType
import annofabcli
import annofabcli.common.cli
from annofabcli import AnnofabApiFacade
from annofabcli.common.cli import (
COMMAND_LINE_ERROR_STATUS_CO... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Calculate the b-factor, for relating neutral and in situ potential
# density, following Iudicone et al. (2008)
import numpy as np
import xarray as xr
from xgcm import Grid
import glob
import matplotlib.pyplot as plt
import gsw
# Load grid data and establish parameters for xgcm grid object
rootdir = '/home/gmacgilch... |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod, abstractproperty
import re
from textwrap import dedent
import numpy as np
def funccall(name, args):
# Delimit such that we have one (indented) argument per line
sep = ',\n' + ' '*(len(name) + 1)
cal = sep.join(args).split('\n')
# Add ... |
# ### Utilities
# 1. Save Model
# 2. Load Model
# 3. Save Image
# 4. Save Log
import os
import numpy as np
import cv2
from keras.models import Model,model_from_json
from mask_demask import masked_images,demask_images,mask_width
from keras.optimizers import Adam
from keras.layers import Input
import PIL
import IPytho... |
'''
https://leetcode.com/contest/weekly-contest-150/problems/last-substring-in-lexicographical-order/
SA algorithm mostly copied from https://cp-algorithms.com/string/suffix-array.html
Status: tle. probably py3 lists
'''
class SuffixArray:
def __init__(self, s):
self.s = s
self.n = len(s)
... |
from typing import Iterator
from hathor.conf import HathorSettings
from hathor.transaction import BaseTransaction
from hathor.transaction.storage import TransactionMemoryStorage
from tests import unittest
from tests.utils import add_blocks_unlock_reward, add_new_block, add_new_blocks, add_new_transactions
settings = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.