content stringlengths 5 1.05M |
|---|
from .display_ import *
__all__ = display_.__all__
|
import os
import numpy as np
import shutil
import random
os.chdir('data')
os.mkdir('cuhk03_byid_2')
os.mkdir('cuhk03_byid_2/train_all')
os.mkdir('cuhk03_byid_2/val')
for dataset in ['cuhk03-np-detected']:
os.chdir(dataset+'/pytorch')
all_data = os.listdir('train_all')
random.shuffle(all_data)
num_da... |
from fastapi import APIRouter, Request, Response
from starlette.templating import Jinja2Templates
import os
import socket
from RLog import rprint
PORT = 9080
router = APIRouter()
templates = Jinja2Templates(directory="templates")
def get_local_ip() -> str:
"""
copy and paste from
https://stackoverflow.co... |
import pyBigWig
import argparse
import os
import sys
import numpy as np
import re
import lightgbm as lgb
import pickle
def calculate_mmm(input3d, axis=2): # input 3d output 3d; calculate max, min, mean along axis=2
output3d=np.zeros((input3d.shape[0], input3d.shape[1], 3))
output3d[:,:,0]= np.max(input3d, axis... |
import numpy as np
import scipy.linalg as la
# Input: number of samples n
# number of features d
# Output: numpy matrix X of features, with n rows (samples), d columns (features)
# X[i,j] is the j-th feature of the i-th sample
# numpy vector y of labels, with n rows (samples), 1 column
# ... |
import click
import tensorflow as tf
from noisemaker.util import load, save
import noisemaker.cli as cli
import noisemaker.effects as effects
@click.command(help="""
crop - Quick hack to crop/resize an image into a 1024x1024 JPEG.
https://github.com/aayars/py-noisemaker
""", context_setting... |
from src.cryptography import address, messages, encrypt
from hashlib import sha256
import time
import sqlite3 as sql
import requests
import os
def create_payload(sender,payment_type,address_type,address,amount,additional2,product_hash,quantity):
try:
additional1 = "REPLY"
con = sql.connect("info.db")
con.row_fa... |
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 w... |
# Copyright 2017 Palantir Technologies, Inc.
import logging
import os
from mdls import hookimpl, uris
log = logging.getLogger(__name__)
@hookimpl
def mdls_rename(config, workspace, document, position, new_name):
original_pagename = document.pagelink_at_position(position)
log.debug("Executing rename of %s to ... |
from configparser import ConfigParser
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
config = ConfigParser()
config.read('db.ini')
if config['database']['type'] == 'sqlite':
path = config['sqlite']['path']
engine = create_en... |
# import pandas as pd
import sqlite3
connection = sqlite3.connect('buddymove_holidayiq.sqlite3')
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
# df = pd.read_csv('buddymove_holidayiq.csv')
# df.rename({'User Id': 'User_id'}, axis=1, inplace=True)
# print(df.head())
# print(df.shape)
# df.to_... |
# -*- coding: utf-8 -*-
setA = {1,2,3,4,5}
setB = {1,3,4,6,7,8}
print(setA | setB) # | işareti birleştirir(union) setleri ortakları tekrar tekrar yazmaz.
print(setA.union(setB)) # bu da union yapar sıralar önemsiz.
print(setB.union(setA))
print(setA & setB) # & işareti kesişimini(intersection) alır.
print(setA.i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-03 16:55
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
import django.core.serializers.json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('entity_event', '000... |
# -*- coding: utf-8 -*-
u"""
Created on 2015-7-15
@author: cheng.li
"""
from PyFin.tests.Env.testSettings import TestSettings
__all__ = ["TestSettings"]
|
# /* megatest texts, C-ified */
# // Copyright 2010 Kurt Hackenberg & William S. Yerazunis, each individually
# // with full rights to relicense.
# //
# // This collection contains texts in the public domain; the copyright
# // is not on the texts themselves but on their use as test texts for
# // the LGPLed CRM... |
import typing as tp
import uvicorn
from fastapi import Depends, FastAPI, File, Form, status
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from auth.dependencies import authenticate
from feecc_printer.Printer import Printer
from feecc_printer.models import GenericResponse
from logging_co... |
import factory
class MessageFactory(object):
subject = factory.Faker('sentence', nb_words=6, variable_nb_words=True, ext_word_list=None)
message = factory.Faker('paragraph', nb_sentences=3, variable_nb_sentences=True, ext_word_list=None) |
import os.path
from os.path import dirname
from datetime import datetime, timedelta, tzinfo
from time import time, gmtime, strftime
from urlparse import urljoin
import bleach
try:
from commons.urlresolvers import reverse
except ImportError, e:
from django.core.urlresolvers import reverse
try:
from cStr... |
#encoding=utf-8
# ---------------------------------------------------------Libraries--------------------------------------------------------
# Standard Libraries
# Third-party Libraries
# User Define Modules
# --------------------------------------------------------Global Strings------------------------------------... |
import json
import geopandas
from ..graph import Graph
from ..updaters import compute_edge_flows, flows_from_changes
from .assignment import get_assignment
from .subgraphs import SubgraphView
class Partition:
"""
Partition represents a partition of the nodes of the graph. It will perform
the first layer... |
from django.shortcuts import render
from django.http import Http404
from rest_framework import viewsets, mixins, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from pandora_main.models import PandoraCompany, PandoraFood, \
Pa... |
import pymongo, time, datetime, os
# Parsing related modules
import AutoInject.bin.build_From_Source as bfs
import AutoInject.bin.github_Parser as gp
import AutoInject.bin.patch_Handler as ph
import AutoInject.bin.system_Functions as sf
import AutoInject.bin.website_Parser as wp
from pymongo ... |
"""
*******************************************************
* Copyright (C) 2017 MindsDB Inc. <copyright@mindsdb.com>
*
* This file is part of MindsDB Server.
*
* MindsDB Server can not be copied and/or distributed without the express
* permission of MindsDB Inc
**************************************************... |
from django.apps import AppConfig
class OriManagerConfig(AppConfig):
name = 'orimanager'
|
from django.urls import path
from . import views
urlpatterns = [
path('add_book',views.add_book),
path('show_books',views.show_books)
] |
# Copyright 2017, 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.0
#
# Unless required by applicable law or ... |
#!/usr/bin/python3
import json
import warnings
import pytest
import brownie
from brownie._config import ARGV, CONFIG
from brownie.exceptions import VirtualMachineError
from brownie.network.state import _get_current_dependencies
from brownie.test import coverage, output
from .base import PytestBrownieBase
from .util... |
import torch as to
import numpy as np
import joblib
import os.path as osp
from abc import abstractmethod
from copy import deepcopy
import pyrado
from pyrado.algorithms.base import Algorithm
from pyrado.environments.base import Env
from pyrado.logger.step import StepLogger
from pyrado.policies.base import Policy
from p... |
__all__ = [
'Attachment',
'AssignmentAttachment'
]
import datetime
from enum import Enum, unique
from .owner import Owner
from .primitives.base import BaseTolokaObject
class Attachment(BaseTolokaObject, spec_enum='Type', spec_field='attachment_type'):
"""Attachment
Files uploaded by users are saved... |
s = f'{:{:{:{}}}}' |
"""This module contains utility functions required within the anonymization kernel"""
import pandas as pd
import numpy as np
from anytree import AnyNode
from nlp.similarity_module import compare_complete_match
from pandas.api.types import is_datetime64_any_dtype, is_numeric_dtype, is_categorical_dtype
def reduce_stri... |
class TestHierarchy:
def test___getstate__(self): # synced
assert True
def test___setstate__(self): # synced
assert True
def test_current_node(self): # synced
assert True
def test_choose_strategy(self): # synced
assert True
def test_run_programatically(self): ... |
import json
import os.path
import requests
import socket
import sys
from base64 import b64decode
from bs4 import BeautifulSoup as bs
from httpobs.conf import (SCANNER_ALLOW_LOCALHOST,
SCANNER_PINNED_DOMAINS)
from requests.structures import CaseInsensitiveDict
HSTS_URL = ('https://chromium.g... |
import py
from pypy.lang.smalltalk import model, constants, primitives
from pypy.lang.smalltalk import objtable
from pypy.lang.smalltalk.model import W_ContextPart
from pypy.lang.smalltalk.conftest import option
from pypy.rlib import objectmodel, unroll
class MissingBytecode(Exception):
"""Bytecode not implemente... |
# Installing (source activate ENVIRONMENT):
# Cd to: cd ~/Desktop/Darwinex/darwinex-ibkr/TWS_API/twsapi_macunix.976.01/IBJts/source/pythonclient/
# Do: python3 setup.py bdist_wheel
# Do: python3 -m pip install --user --upgrade dist/ibapi-9.76.1-py3-none-any.whl
from ibapi.client import EClient
from ibapi.wrapper impor... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Length
class LoginForm(FlaskForm):
username = StringField("Username", validators=[Required(), Length(1, 16)])
password = PasswordField("Password", validators=[Requ... |
import logging
import ssl
import paho.mqtt.client as mqtt
from roombapy.const import MQTT_ERROR_MESSAGES
class RoombaMQTTClient:
address = None
port = None
blid = None
password = None
log = None
was_connected = False
on_connect = None
on_disconnect = None
def __init__(self, addr... |
from __future__ import absolute_import
import requests
from weatherlink.models import (
ArchiveIntervalRecord,
convert_datetime_to_timestamp,
)
_requests_session = requests.Session()
class Downloader(object):
WEATHER_LINK_URL = (
'https://api.weatherlink.com/webdl.php?'
'timestamp={timestamp}&user={usernam... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DummyNet(nn.Module):
def __init__(self):
super(DummyNet, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5, padding=2)
self.conv2 = nn.Conv2d(10, 5, kernel_size=5, padding=2)
self.softmax = nn.Softma... |
import random
import unittest
from reader import Reader
from writer import Writer
class ReaderTestCase(unittest.TestCase):
def setUp(self):
pass
def test_read(self):
filename = 'input.txt'
words = Reader.read(filename)
self.assertEqual(words[0], 'utter')
self.assertEqu... |
import pytest
import yaml
from tests.commands.run_test_utils import RunAPIMock, RunTestSetup
from tests.fixture_data import CONFIG_YAML, PROJECT_DATA
from valohai_cli.commands.execution.run import run
from valohai_cli.ctx import get_project
from valohai_cli.models.project import Project
adhoc_mark = pytest.mark.param... |
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário
# e todos os dicionários em uma lista. No final, mostre:
# A) Quantas pessoas foram cadastradas
# B) A média de idade
# C) Uma lista com as mulheres
# D) Uma lista de pessoas com idade acima da média
ca... |
import time
from datetime import datetime
import requests
def getStockDeltas(companyResults, key):
for company in companyResults['companies']:
results = getCompanyStockData(company['name'], key)
if len(results) == 0: return companyResults
# Consider 1 week
for article in company['... |
import pandas as pd
full_doc_fname = '../../orig_text_data/internment.txt'
new_train_sents = pd.read_csv('../new_train_sents_withcontext1.csv')
old_train_sents = pd.read_csv('../data/binary_mindsduplicates_withcontext_linesupwithmultiway_withfilename_train.csv')
old_train_sents = old_train_sents.drop(['source_handc... |
import argparse
from smartlabel.Dataset import Dataset
from smartlabel.Project import Project
from smartlabel.Label import Label_Object
from tabulate import tabulate
import sys
import requests
import json
from pathlib import Path
from os.path import join
import os
from shutil import rmtree
API_URL = 'http://127.0.0.1... |
import os, shutil
import json
from os.path import isfile
from django.urls import reverse
from django.core.management import call_command
from django.test import Client, TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.authtoken.models import Token
from rest_frame... |
# vim: expandtab:ts=4:sw=4
import os
import numpy as np
import cv2
# The maximum person ID in the dataset.
MAX_LABEL = 1500
IMAGE_SHAPE = 256, 128, 3
def read_train_test_directory_to_str(directory):
"""Read bbox_train/bbox_test directory.
Parameters
----------
directory : str
Path to bbox... |
import pytest
from random import randint, choice
from instaparser.agents import Agent
from instaparser.entities import Account, Media, Location, Tag
from tests.settings import accounts, locations, photos, photo_sets, tags, videos
def test_update():
anon = Agent()
anon.update()
assert(not geta... |
from django import forms
from .models import Item, SubItem
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = ['title', 'content']
class ItemSearchForm(forms.Form):
title = forms.CharField(
initial='',
label='Title',
required=False,
)
content ... |
from .position import Position, load_position_from_save
from .direction import Direction
def load_piece_from_save(piece_save):
from .marker import load_marker_from_save
from .agent import load_agent_from_save
if piece_save['piece_type'] == 'marker':
piece = load_marker_from_save(piece_save)
eli... |
import sys
from pyspark import SparkContext
if __name__ == "__main__":
file = sys.argv[1] #raw train file
sc = SparkContext(appName="demo2")
data = sc.textFile(file).flatMap(lambda line: line.split(' ')).distinct()
data.saveAsTextFile("demo2_output")
sc.stop()
|
from pyglet.graphics import Batch, OrderedGroup
from pyglet.sprite import Sprite
from src.data_loader import Assets, JsonData
from pyglet.image import Animation
class Bird(Sprite):
"""Bird
-
Class for a single Bird
The bird class inherits from the pyglet.sprite.Sprite class.
"""
def __init__... |
"""Demo model server API."""
from serveit.server import ModelServer
from os import path
import random
import json
import pickle
import h5py
import numpy as np
from utils import str_shape
import keras.backend as K
from flask import request
from config import path_models, path_data
from constants import FN1, FN0, nb_unk... |
"""
This sample file demonstrate how to download a model from BuildSimHub using API
"""
import BuildSimHubAPI as bshapi
# project_key can be found in every project (click the information icon next to project name)
project_key = "f98aadb3-254f-428d-a321-82a6e4b9424c"
# model_key can be found in each model information... |
from bottle import request
from bottle import template
from bottle import static_file
from bottle import redirect
import bcrypt
from app import app
from app.models.tables import User
# static rotes
@app.get('/<filename:re:.*\.css>')
def stylesheets(filename):
return static_file(filename, root='app... |
from datetime import datetime, timedelta
import pytest
from django.conf import settings
from django.core.cache import cache
from django.utils.timezone import utc
from freezegun import freeze_time
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
fr... |
"""
Login and logout views for the browsable API.
Add these to your root URLconf if you're using the browsable API and
your API requires authentication:
urlpatterns = [
...
url(r'^auth/', include('rest_framework.urls'))
]
You should make sure your authentication settings include `SessionAuthe... |
import FWCore.ParameterSet.Config as cms
import TrackingTools.KalmanUpdators.Chi2MeasurementEstimator_cfi
Chi2MeasurementEstimatorForInOut = TrackingTools.KalmanUpdators.Chi2MeasurementEstimator_cfi.Chi2MeasurementEstimator.clone()
Chi2MeasurementEstimatorForInOut.ComponentName = 'Chi2ForInOut'
Chi2MeasurementEstimato... |
# Generated by Django 2.2 on 2020-03-02 15:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0025_auto_20200302_1534'),
]
operations = [
migrations.RemoveField(
model_name='upcomingtest',
name='event_type',
... |
""" unit tests for Covid19Processing"""
import os
import shutil
from covid19_graphs.covid19_processing import Covid19Processing, daily_new_data
from covid19_graphs.command_line_script import CONFIRMED, CONTINENTS
def test_create_out_dir():
out_dir = 'test_directory'
test_run = Covid19Processing(CONFIRMED, CON... |
# -*- coding: utf-8 -*-
from flask.sessions import SessionInterface, SessionMixin
from werkzeug.datastructures import CallbackDict
from itsdangerous import URLSafeTimedSerializer, BadSignature
from wtforms import Form, PasswordField, validators, StringField
class ItsdangerousSession(CallbackDict, SessionMixin):
... |
from django.db import models
from django.core.urlresolvers import reverse
from embed_video.fields import EmbedVideoField
class VideoPost(models.Model):
title = models.CharField(max_length=50)
video = EmbedVideoField(verbose_name='Video Link',
help_text='The link for your video to ... |
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laboratory ... |
from loguru import logger
from ..base import base
class living(base):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
def get_user_livingid(self, data):
api_name = "living/get_user_livingid"
response = self.request(
api_name=api_name, method="post", json=d... |
from datetime import date, datetime
from .timeseries_downloader import TimeseriesDownloader, METADATA_KEY, META_INTERVAL_KEY, META_PROVIDER_KEY, META_TICKER_KEY, ATOMS_KEY, Union
from ..utils import key_handler as key_handler
from ..utils import logger as log
import json
import yfinance as yf
META_PROVIDER_VALUE = "ya... |
"""
Music player client to the update server
Functionalities:
1) GET /login request to get authentification token ID
2) PUT /profiles/clientId:{macaddress} request to update the software version
"""
import os
import re
import requests
from .csv_reader import MusicPlayerCsvReader
__all__ = ['MusicPlayerClient... |
#!/usr/bin/env python
#
# backport_tests_pl.py: Test backport.pl
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or mo... |
import sys
from api import create_api
def main():
api, db = create_api()
if sys.argv[1] == "migrate":
db.create_all()
exit()
if sys.argv[1] == "run":
api.app.run(host="0.0.0.0", port="5050", debug=True)
if __name__ == '__main__':
main()
|
import torch.nn as nn
import torchvision.models as models
from ..base import BaseMulticlassClassifier, BaseMultilabelClassifier
class AlexNet(BaseMulticlassClassifier):
def __init__(self, config):
super().__init__(config)
if self.config.pretrained:
self.model = models.alexnet(self.co... |
"""A DemoCommand Command."""
import os
from cleo import Command
from masonite.packages import append_web_routes
package_directory = os.path.dirname(os.path.realpath(__file__))
class DemoCommand(Command):
"""
Create a Inertia.js demo and add it to your project.
command:name
{argument : descripti... |
import time
import board
import neopixel
from digitalio import DigitalInOut, Direction, Pull
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.1)
pixels.fill((0, 0, 0))
pixels.show()
button_a = DigitalInOut(board.BUTTON_A)
button_a.direction = Direction.INPUT
button_a.pull = Pull.DOWN
RED = (255, 0, 0)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 23 10:46:42 2022
@author: alex
"""
##############################################################################
import numpy as np
##############################################################################
from pyro.dynamic import system
####... |
from SPARQLWrapper import SPARQLWrapper, JSON
#Query to retrieve labels of variables
#sparql = SPARQLWrapper("http://ontosoft.isi.edu:3030/ds/query")
#sparql.setQuery("""
#PREFIX mc: <https://w3id.org/mint/modelCatalog#>
#SELECT distinct ?u where {
#?a mc:hasStandardVariable ?u.
#}
#""")
#Query to retrieve variab... |
import os
from input_data import *
runs = range(1)
for run in runs:
print "***** run %d ********" % run
min_run = run
max_run = run+1
os.system("python generate_data.py")
# creates balance.csv
os.system("python compute_diagnostics.py")
# creates means.csv
os.system("python compute_means... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from typing import List, Tuple
from pypinyin import lazy_pinyin
def word_parser(word: str) -> List[Tuple[str, List[str]]]:
pinyins: List[str] = lazy_pinyin(word)
return pinyin_parser(pinyins)
def pinyin_parser(pinyins: List[str]) -> List[Tuple[str, Li... |
from django.apps import AppConfig
class SlackAppConfig(AppConfig):
name = "slackapp"
|
from betamax import Betamax
from currencycloud import Client, Config
class TestAuthentication:
def setup_method(self, method):
# TODO: To run against real server please delete ../fixtures/vcr_cassettes/* and replace
# login_id and api_key with valid credentials before running the tests
lo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:set ts=4 sts=4 sw=4 et:
"""MC Helpers.
"""
import numpy as np
from km3pipe import Module
from km3pipe.mc import pdg2name, convert_mc_times_to_jte_times
from km3pipe.math import zenith, azimuth
__author__ = "Michael Moser and Tamas Gal and Moritz Lotze"
NEUTRINOS ... |
import Queue
class Solution(object):
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
if target == "0000":
return 0
qe = Queue.Queue(maxsize = 0)
qe.put(("0000", 0))
state_shif... |
import numpy as np
def tournament_selection(
population: np.ndarray, fitness: np.ndarray, t_sel_p: float, t_sel_size: int
) -> np.ndarray:
"""Select fit individuals from a population by tournament selection.
In tournament selection a group from the population are put into tournaments
of two on two "co... |
CNN = nn.Sequential(
nn.Conv2d(1,64,3),
nn.ReLU(True),
nn.MaxPool2d(2,2),
nn.Conv2d(64,256,3),
nn.ReLU(True),
nn.MaxPool2d(3,3),
Reshape(),# 两个卷积和池化后,tensor形状为(batchsize,256,7,7)
nn.Linear(256*7*7,4096),
nn.ReLU(True),
nn.Linear(4096,1024),
nn.ReLU(True),
nn.Linear(1024... |
# mpPool
import os
import time
def my_func(work):
print("일: {0}, Process ID: {1}".format(work, os.getpid()))
time.sleep(1)
return work
# mpProcess
import os
import time
def seconds_timer(end_time):
start_time = time.time()
while True:
time.sleep(0.001)
if time.time() - start_ti... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
""" Unit tests for the GPU to-device transformation. """
import dace
from dace.transformation.interstate import GPUTransformSDFG
def test_toplevel_transient_lifetime():
N = dace.symbol('N')
@dace.program
def program(A: dace.float... |
import math
import numpy as np
from itmlogic.adiff import adiff
from itmlogic.alos import alos
from itmlogic.ascat import ascat
def lrprop(d, prop):
"""
The basic Longley-Rice propagation program which returns the reference attenuation (aref).
The value of mdp controls some of the program flow. When it e... |
#!/usr/bin/env python
import sys
import os
import numpy as np
import sqlite3
import pandas as pd
import astropy.table as at
from astroquery.irsa_dust import IrsaDust
import astropy.coordinates as coord
import astropy.units as u
def main():
db = sqlite3.connect('test_schedule_v8_msip.db')
table = pd.read_sql_qu... |
__version__ = '2.0a10'
|
#156
# Given a binary tree where all the right nodes are either leaf nodes with a sibling
# (a left node that shares the same parent node) or empty, flip it upside down
# and turn it into a tree where the original right nodes turned into left leaf nodes.
# Return the new root.
#
# For example:
# Given a binary t... |
from django import forms
class ArtistForm(forms.Form):
Artist_guess = forms.CharField(label='Artist', max_length=100) |
import requests
import json
import time
import uuid
API_IP = 'localhost'
API_PORT = 5000
endpoint = 'users'
url = 'http://{}:{}/{}'.format(API_IP, API_PORT, endpoint)
data = {'username': str(uuid.uuid4().hex), 'password': 'secret'}
r = requests.post(url, json=data)
endpoint = 'login'
url = 'http://{}:{}/{}'.format(... |
import pytest
from yippi import YippiClient
from hallo.events import EventMessage, EventMessageWithPhoto
from hallo.modules.subscriptions.source_e621_tagging import E621TaggingSource
import hallo.modules.subscriptions.subscription_exception
from hallo.modules.subscriptions.subscription_repo import SubscriptionRepo
fro... |
# Copyright 2020 Marcos Pontes. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... |
import pickle
def fit(model, x_train, y_train):
model = model.fit(x_train, y_train)
return model
def predict(model, x_test):
result = model.predict(x_test)
return result
def bestEstimator(model):
for r, _ in enumerate(model.cv_results_['mean_test_score']):
print("%0.3f +/- %0.2f %r"
... |
# Converts a DIMACS-graph into the METIS format
import sys, os, re
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [ atoi(c) for c in re.split('(\d+)', text) ]
filename = sys.argv[1]
if not os.path.isfile(filename):
print "File not found."
sys.exit(0)
numb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Mod: test_embargo_model
:Synopsis:
:Author:
servilla
:Created:
7/31/20
"""
from datetime import datetime
from pathlib import Path
import pytest
from sniffer.config import Config
from sniffer.model.embargo_db import (
EmbargoDB,
Ephemeral,
)
TEST_... |
#!/usr/bin/python
#
# Copyright 2017 Google 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 a... |
import json
from google.cloud import vision
from google.cloud.vision_v1 import AnnotateImageResponse
from logging import getLogger
logger = getLogger(__name__)
class GoogleVisionClient:
"""
Call google vision by vision client
authorization by google service account
"""
image = None
client = N... |
import numpy as np
from numpy import pi, sin, cos
import math
import matplotlib.pyplot as plt
import sympy as sp
from sympy.interactive.printing import init_printing
init_printing(use_unicode=False, wrap_line=False)
from sympy.matrices import Matrix, eye, zeros, ones, diag, GramSchmidt
from sympy import symbols... |
import cv2
import numpy as np
#Cargas la imagen a color
IRGB=cv2.imread('003.jpg')
print(IRGB)
print(IRGB.shape)
print("Líneas agregadas en la rama2")
IGS=cv2.cvtColor(IRGB,cv2.COLOR_BGR2GRAY)
print(IGS)
print(IGS.shape)
cv2.imwrite('003GS.jpg',IGS)
|
from .model import Model
class OneClickConfig(Model):
def _accepted_params(self):
return [
'configId',
'shortNumber',
'merchantId',
'serviceCode',
'businessModel',
'recurring',
'redirectUrl',
'onlineText',
... |
#!/usr/bin/env python3
import logging
import pathlib
import sys
from dataclasses import dataclass
import requests
import toml
from rich.logging import RichHandler
import click
DOCKER_REGISTRY_URL = "https://hub.docker.com"
@dataclass
class RepoInfo:
name: str
docker_repo: str = ""
def error(message: str = None... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.