content stringlengths 5 1.05M |
|---|
import unittest
import os
from modules.DatabaseModule.DBManager import DBManager
from opentera.db.models.TeraAsset import TeraAsset
from opentera.config.ConfigManager import ConfigManager
from tests.opentera.db.models.BaseModelsTest import BaseModelsTest
class TeraAssetTest(BaseModelsTest):
filename = os.path.... |
import sys
import os
from PIL import Image
# grab first and second arguments passed on terminal
actual_folder = sys.argv[1]
new_folder = sys.argv[2]
# check is new folder exists, if not create
if not os.path.exists(new_folder):
os.makedirs(new_folder)
# loop through Pokedex, grap each image, convert and save to ... |
#Import all the Misc classes
from .Misc import *
#Import all the sprite classes
from .Sprites import *
#Import Screens
from .Screens import *
#Import popups
from .Popups import *
#Import Achievements
from .Achievements import *
#Import Stages
from .Stages import *
#Import instruction screens
from .Instructions im... |
import serial
import struct
from math import sqrt, pow
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i+n]
def reverse_bit_order(buf, width):
# Just to get the length the same
newbuf = range(len(buf))
for i in range(len(buf)... |
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... |
"""
This script was made by Nick at 19/07/20.
To implement code for data pipeline. (e.g. custom class subclassing torch.utils.data.Dataset)
"""
|
from copy import copy, deepcopy
import pytest
from zquantum.core.history.example_functions import (
Function2,
Function5,
function_1,
function_3,
function_4,
function_6,
)
from zquantum.core.history.recorder import recorder
@pytest.mark.parametrize("func", [Function2(5), function_3, function_... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import requests
# request types
r = requests.get('http://api.github.com/events')
r = requests.post('http://api.github.com/events', \
data = {'key':'value'})
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://h... |
from tensorflow.python.lib.io import file_io
import os
base_path = 'gs://sacred-reality-201417-mlengine/models'
def save_model(file_name):
with file_io.FileIO(file_name, mode='rb') as f:
with file_io.FileIO(os.path.join(base_path, file_name), mode='w+') as output_f:
output_f.write(f.read())
... |
class BaseAWSLogsException(Exception):
code = 1
def hint(self):
return "Unknown Error."
class UnknownDateError(BaseAWSLogsException):
code = 3
def hint(self):
return "awslogs doesn't understand '{0}' as a date.".format(self.args[0])
class TooManyStreamsFilteredError(BaseAWSLogsEx... |
# coding: utf-8
'''
3. Finding Experts on the Java Programming Language on StackOverflow [4 points]
Download the StackOverflow network stackoverflow-Java.txt.gz:
http://snap.stanford.edu/class/cs224w-data/hw0/stackoverflow-Java.txt.gz.
An edge (a, b) in the network means that person a endorsed an answer from
... |
from ..src.methods import Newton
from ..src.function_examples import f_root
def test_accuracy():
f_root['max_it'] = 3
it_val = 2.238095238095238095238 # val at it=3
returned = Newton(**f_root).solve(**f_root)
print(it_val, " vs ",returned)
assert round(returned,6) == round(it_val,6)
|
from __future__ import print_function
import time
import itertools
import json
import traceback
from metis.Sample import DBSSample
from metis.CMSSWTask import CMSSWTask
from metis.StatsParser import StatsParser
from metis.Utils import send_email
if __name__ == "__main__":
pds = ["MuonEG","SingleElectron","MET"... |
class NodeCircle:
def __init__(self,val):
self.val = val
self.next = None
def has_circle(self,haed):
slow = haed
fast = head
while(slow and fast):
fast = fast.next
slow = slow.next
if fast:
fast = fast.next
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class SenderInfoVO(object):
def __init__(self):
self._area = None
self._city = None
self._detail_address = None
self._mobile = None
self._name = None
sel... |
import re
import os
import sys
import json
import pickle
import humanize
import datetime
import inspect
import logging
from time import time
from functools import wraps
from datetime import datetime
from typing import Tuple, Callable, Union, Dict, List
from .utils import get_params, parse_time, random_string
from .bac... |
import os
import urwid
from .model import Model
max_rows, max_columns = os.popen('stty size', 'r').read().split()
MAX_ROWS = int(max_rows) - 2
MAX_COLUMNS = int(max_columns)
class ButtonLabel(urwid.SelectableIcon):
def __init__(self, text):
curs_pos = len(text) + 1
urwid.SelectableIcon.__init__(s... |
"""
TXA - Transfer Register X to Accumulator.
A = X
Copies the current contents of the X register into the accumulator and sets
the zero and negative flags as appropriate.
Processor Status after use:
+------+-------------------+--------------------------+
| Flag | Description | State |
+===... |
import uuid as uuid_lib
from django.contrib.auth import get_user_model
from django.core.validators import FileExtensionValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
User = get_user_model()
class VideoRaw(models.Model):
"""
This model represents the structure f... |
from datetime import timedelta
from fastapi import APIRouter
from typing import Any
from fastapi.routing import APIRoute
# from fastapi import APIRouter, Body, Depends, HTTPException
# from fastapi.security import OAuth2PasswordRequestForm
# from sqlalchemy.orm import Session
# from app import crud, models, schemas
#T... |
from zone_director import ZoneDirectorBase
class SituationZoneDirectorMixin:
INSTANCE_TUNABLES = {'_zone_director': ZoneDirectorBase.TunableReference(description='\n This zone director will automatically be requested by the situation\n during zone spin up.\n ')}
@classmethod
... |
from django.test import TestCase
from django.utils import timezone
from django.urls import reverse
from .models import Question
import datetime
# Create your tests here.
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
time = timezone.now() + datetime.timedel... |
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
if points[0] == points[1] or points[1] == points[2] or points[0] == points[2]: return False
return points[0][0]*(points[1][1] - points[2][1]) + points[1][0]*(points[2][1]-points[0][1]) + points[2][0]*(points[0][1]-points... |
from collections import OrderedDict
from utils.env_utils import get_dim
from gym.spaces import Discrete
import numpy as np
class ReplayBuffer(object):
def __init__(
self,
max_replay_buffer_size,
ob_space,
action_space,
):
"""
The class state which should not m... |
from fastapi import FastAPI
from .routers import post, user, auth, vote
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
app.include_rout... |
from PyQt5 import QtCore
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, head_columns_names, head_rows_names):
super(TableModel, self).__init__()
self.headColStringsList = head_columns_names
self.headRowStringsList = head_rows_names
self._data = [] # this is just an empty data to use for r... |
# AOC 2021 - day 11 #
import math
import sys
from .common_11 import OctoGrid, parse_input
INF = math.inf
def main(data):
og = OctoGrid(data)
step = 1
while True:
og.do_step()
all_flashes = og.is_all_flash()
if all_flashes:
break
step += 1
return step
i... |
import os
import pandas
def read_csv_files_from_folder_to_dataframe_dictionary(
folder: str) -> dict:
dataframe_dictionary = \
dict()
csv_files = \
__get_all_csv_files_from_folder(
folder)
for csv_file in csv_files:
dataframe_dictionary = \
__add_... |
from __future__ import print_function
from casolver.core.events.Event import Event
from lsh import cache, minhash # https://github.com/mattilyra/lsh
import argparse
import errno
import json
import logging
import logging.config
import os
import sys
import pkg_resources
import numpy as np
# Configure logger
logging.conf... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
from habitat.core.logging import logger
from env.soundspaces.benchmark import Benchmark
... |
idade = int(input("Digite sua idade "))
def classificacao(idade):
if idade <= 9:
return f"Um atleta de {idade} anos e Atleta MIRIM"
elif idade > 9 and idade <=14:
return f"Um atleta de {idade} anos e Atleta Infantil"
elif idade > 14 and idade <= 19:
return f"Um atleta de {idade} ano... |
from __future__ import print_function
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
# Define the LSTM decoder for the CNN+LSTM autoencoder architecture
# Adapted from https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/03-advanced/image_captioning/model.py
class D... |
"""
Restricted Boltzman's Machine [Energy based model]
"""
from sklearn.datasets import fetch_mldata
import numpy as np
import matplotlib.pyplot as plt
from ..unsupervised.restricted_boltzmann_machine import RBM
def start_restricted_bolz_machine():
"""
Drives the restricted boltzmann machine network... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 17:11:20 2018
@author: rstreet
"""
import rubin_sim.maf.db as db
import rubin_sim.maf.metrics as metrics
import rubin_sim.maf.slicers as slicers
import rubin_sim.maf.metricBundles as metricBundles
from rubin_sim.maf.metrics import BaseMetric
import numpy as np
from .c... |
from django.db import models
from django.conf import settings
from django.utils.html import mark_safe
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from os import path
DEFAULT_COVER = "cover/ntnui.png"
DEFAULT_LOGO = "logo/ntnui.svg"
def get_upload_location(type, instance, f... |
"""
Creando un VPC con python
"""
import boto3
cliente = boto3.resource('ec2')
vpc = cliente.create_vpc(CidrBlock='172.18.0.0/16')
vpc.create_tags(Tags=[{"Key":"VPC","Value":"En Python Curso AWS"}])
vpc.wait_until_available() |
from icolos.core.composite_agents.workflow import WorkFlow
from icolos.core.containers.generic import GenericData
import unittest
import os
from icolos.core.containers.gmx_state import GromacsState
from icolos.utils.enums.step_enums import StepBaseEnum, StepGromacsEnum
from tests.tests_paths import PATHS_EXAMPLEDATA, e... |
"""A sample app that operates on GCS files with blobstore API's BlobReader."""
import cloudstorage
from google.appengine.api import app_identity
from google.appengine.ext import blobstore
import webapp2
class BlobreaderHandler(webapp2.RequestHandler):
def get(self):
# Get the default Cloud Storage Bucket... |
from __future__ import print_function
from datetime import datetime
from HTMLParser import HTMLParser
import re
class FbHTMLParserFindMeta(HTMLParser):
pttrn_fb_id = re.compile('^fb://group/(\d+)$')
def __init__(self, callback_found_name, callback_found_fb_id):
HTMLParser.__init__(self)
self.... |
from django.db.models.sql.query import * # NOQA
from django.db.models.sql.query import Query
from django.db.models.sql.subqueries import * # NOQA
from django.db.models.sql.where import AND, OR
__all__ = ["Query", "AND", "OR"]
|
#!/usr/bin/env python
# encoding: utf-8
"""
LatestEntries.py
Created by Rui Carmo on 2011-09-02.
Published under the MIT license.
"""
import re, md5, urlparse, time, cgi, traceback
import yaki.Engine, yaki.Store, yaki.Locale
from yaki.Utils import *
from yaki.Layout import *
from BeautifulSoup import *
class LatestB... |
import datetime
import pytest
from ksc.collector import base
from ksc.collector.model import collector
class MockedCollector(base.Collector):
def collect(self) -> collector.Result:
...
def test_no_arg_constructor() -> None:
i = MockedCollector()
today = datetime.datetime.utcnow()
assert i.... |
#!/usr/bin/env python
import functools
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
# numsString = [str(n) for n in nums]
# def compare(ns1, ns2):
# return 1 if ns2+ns1 > ns1+ns2 else -1
return ''.join(... |
"""Helper scintific module
Module serves for custom methods to support Customer Journey Analytics Project
"""
# IMPORTS
# -------
# Standard libraries
import re
import ipdb
import string
import math
# 3rd party libraries
from google.cloud import bigquery
import numpy as np
import pandas as pd
import nltk
nltk.down... |
import floto
from floto.specs.retry_strategy import InstantRetry
from floto.specs.task import ActivityTask, ChildWorkflow
import datetime as dt
# ---------------------------------- #
# Start the workflow execution
# ---------------------------------- #
rs = InstantRetry(retries=3)
domain = 'floto_test'
input_copy_fi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("msgs", "0015_message_is_active")]
operations = [
migrations.RunSQL('CREATE INDEX msgs_messageaction_messages_idx ON msgs_messageaction USING GIN ... |
def merge(ar, lo, mid, hi):
aux = ar[:]
i = lo
j = mid + 1
k = lo
while k <= hi:
if i > mid:
ar[k] = aux[j]
j += 1
elif j > hi:
ar[k] = aux[i]
i += 1
elif aux[i] < aux[j]:
ar[k] = aux[i]
i += 1
el... |
#!/usr/bin/env python
# Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0 that
# can be found in the LICENSE file.
"""Automated maintenance tool to run a script on bots.
To use this script, write a self-contained python script (use a ... |
import pdb
import numpy as np
import scipy.io
import scipy.ndimage
import sklearn.preprocessing
import pandas as pd
class Dataset():
"""
Dataset manager class
"""
def __init__(self, data_path=None):
"""
Class intitializer.
"""
# set database path
if data_path ... |
import numpy as np
def tilt(theta, coordinates):
new_coordinates = np.zeros((4, 2))
for i in range(len(coordinates)):
coordinate = coordinates[i]
x = coordinate[0]
y = coordinate[1]
y = 320 - y
h = np.sqrt(x**2 + y**2)
sigma =... |
# Copyright 2014 Cisco Systems, 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 requi... |
# Copyright 2016 EasyStack.
# 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 ap... |
import argparse
import os
import tensorflow as tf
from network import FACE_COMPLETION
# add arguments for the face completion network script
parser = argparse.ArgumentParser()
# number of iteration to run the face completion model
parser.add_argument('--num_iter', type=int, default=500)
# checkpoint directory for... |
from .api import CellarTrackerAPI
from .enum import CellarTrackerFormat, CellarTrackerTable
class CellarTrackerClient(object):
def __init__(self, username: None, password: None):
"""Initialize the client object."""
self._api = CellarTrackerAPI()
self._username = username
self._pas... |
"""Similarity Down-selection (SDS) heuristically finds the most dissimilar set of size `n`
out of a population represented as an NxN matrix where the ith row (as well as the
ith column) belong to item i, and the element (i,j) is some pairwise relation between
items i and j.
The pairwise relation is a floating point ... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.http import Http404
from django.db.models import Q
from rest_framework import viewsets, mixins
from rest_framework.permissions import AllowAny, IsAdminUser, SAFE_METHODS
from rest_f... |
import json
from rest_framework import exceptions as rest_exceptions, serializers as rest_serializers
from jobs import models
class LocationsField(rest_serializers.Field):
def to_internal_value(self, data):
if data is None:
return []
if not isinstance(data, list):
raise... |
#!/usr/bin/env python
import os
import subprocess
def main():
print("Generating graphouse properties")
with open('/etc/graphouse/graphouse.properties', 'w') as graphouse_config:
for env_key, value in os.environ.items():
if not env_key.startswith("GH__"):
continue
... |
from easydict import EasyDict
coinrun_ppg_default_config = dict(
exp_name='coinrun_ppg_seed0',
env=dict(
is_train=True,
env_id='coinrun',
collector_env_num=64,
evaluator_env_num=10,
n_evaluator_episode=50,
stop_value=10,
manager=dict(
shared_m... |
import os
import numpy as np
import json
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
def load_image(filename):
img = Image.open(filename)
img.load()
return img
def normalize_image(image):
'''
z-score normalize, sample-wise
'''
image_norm = (image - image.mea... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pprint
from collections import Counter
import pandas as pd
from pandas import DataFrame
from tabulate import tabulate
from base import BaseObject
from datadict import FindDimensions
class AcademicDimensionCalculator(BaseObject):
""" Compute the Academic Dim... |
# 累積和
N, K = map(int, input().split())
S = input()
p = '1'
count = 0
cs = []
for c in S:
if c != p:
cs.append(count)
p = c
count = 1
else:
count += 1
cs.append(count)
if p != '1':
cs.append(0)
if len(cs) < 2 * K:
print(N)
exit()
for i in range(1, len(cs)):
cs[i... |
#!/usr/bin/env python
import os
import gc
import json
import pickle
import sqlite3
import argparse
import pandas as pd
from code_parser.codeparser_stdin import CodeParserStdin
from post_classifier.classifier import PostClassifier
from post_classifier.utils import (list_to_disk, load_number_list,
... |
import subprocess
class OnboardingAppChecker:
@classmethod
def get_app_version(cls, app):
output = cls.get_app_output(app)
try:
version = output.split('version')[1]
except IndexError:
version = output
return version
@classmethod
def get_app_out... |
from django.contrib.auth import get_user_model
from django.db import connection
from django_tenants.utils import (
get_public_schema_name,
get_tenant_domain_model,
get_tenant_model,
)
from tenant_users.tenants.models import ExistsError
def get_current_tenant():
current_schema = connection.schema_name... |
from datetime import datetime
from unittest import TestCase
from decimal import Decimal
from expressly.models import Order
class OrderFullTest(TestCase):
def setUp(self):
date_time = datetime.utcnow().isoformat('T')
self.m = Order.get_mock_object()
self.m.date = date_time
self.m... |
#!/usr/bin/env python
from datajob.datajob_stack import DataJobStack
from datajob.glue.glue_job import GlueJob
from datajob.stepfunctions.stepfunctions_workflow import StepfunctionsWorkflow
import pathlib
current_dir = pathlib.Path(__file__).parent.absolute()
with DataJobStack(
stack_name="data-pipeline-pkg", pr... |
from django.db import models
class ProductManager(models.Manager):
def not_deleted(self):
return self.filter(deleted_at__isnull=True)
|
from django.db import models
# Create your models here.
class paywaylog(models.Model):
id = models.AutoField(primary_key=True)
cardid = models.CharField(null = False, max_length = 50)
|
# -- coding: utf-8 --
from __future__ import absolute_import
from unittest import main, TestCase
from tempfile import mkdtemp
from os.path import join, dirname, abspath
from shutil import rmtree, copytree
from re import sub
import random
import sys
from chime.repo_functions import ChimeRepo
from slugify import slugif... |
#!/usr/bin/env python
"""
The following is a summary of the licenses involved in this project.
Please also refer to the LICENSE folder in this github repository
for full licensing information.
LICENSE SUMMARY:
------------------------------------------
The MIT License (MIT)
applies to:
- qtSubAndPlot clas... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Create a new query in Kolide"
class Input:
DESCRIPTION = "description"
NAME = "name"
QUERY = "query"
class Output:
RESULTS = "results"
class CreateQueryInput(komand.Input):
schema = ... |
# put your python code here
string = input().replace(" ",'')
print(round(string.count("A")/len(string), 2)) |
"""
_ _
| (_)
___ ___ __| |_ __ _ _ __ __ _ ___
/ __/ __| / _` | |/ _` | '_ \ / _` |/ _ \\
| (_| (__ | (_| | | (_| | | | | (_| | (_) |
\___\___| \__,_| |\__,_|_| |_|\__, |\___/
______ _/ | __/ |
|______||__/ |___/
"""
import re
import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Collection of tests for :mod:`orion.core.worker.consumer`."""
import datetime
import time
import pytest
import orion.core.io.experiment_builder as experiment_builder
from orion.core.utils.format_trials import tuple_to_trial
from orion.core.worker.trial_pacemaker import... |
import numpy as np
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from collections import namedtuple
SatelliteMeasurement = namedtuple('SatelliteMeasurement',
['position', 'distant', 'weight'])
# Change satellite position here!
def generate_data():
"""
... |
# -*- coding: utf-8 -*-
from django.http import JsonResponse
from datetime import datetime as dt
import numpy as np
from summarizer import Article, ParagraphSet, Sentence, summary_text
from summarizer.lib_detectlang import detect_lang
def parse_api(request):
lang = detect_lang(request.POST['text'])
sections =... |
from typing import List
from .records import AccountOperationRecord, ACCOUNT_OPERATION_TYPE
from ._html_email_scrapers import banorte_email_scraper
EMAIL_TYPE = 'BANCO_EN_LINEA_BLOCKED_USER_EMAIL'
def is_matching(html: str) -> bool:
return 'Bloqueo de usuario' in html
@banorte_email_scraper
def scrape(fields: ... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import mock
import tempfile
import unittest
import os
from py_utils import cloud_storage # pylint: disable=import-error
from telemetry.testing import fakes... |
#print('Veja quantos dolares você pode comprar.')
#var1 = int(input('Informe o valor: '))
#var2 = var1+5.23
#print('Com {} você poderá comprar {} dólares.'.format(var1, var2))
#Desafio proposto na aula 07 do curso de python.
# crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quanto dolares... |
from .artdeco import artdeco
from .autumn import autumn
from .glass import glass
from .metal import metal
from .neon import neon
from .rococo import rococo
from .santafe import santafe
from .sheen import sheen
from .silky import silky
from .spring import spring
from .summer import summer
from .tropical impor... |
import rosbag
import rospy
from arni_msgs.msg import RatedStatistics, RatedStatisticsEntity
from arni_core.helper import SEUID_DELIMITER
def create_simple_bag():
bag = rosbag.Bag('bags/john.bag', 'w')
msg = RatedStatistics()
msg.seuid = "n" + SEUID_DELIMITER + "node1"
msg.host = "host1"
now = ros... |
# Generated by Django 3.1 on 2022-01-18 20:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gardens', '0007_auto_20211231_2258'),
('crops', '0003_auto_20211205_1004'),
]
operations = [
migrations.AddField(
model_na... |
import mongoengine as me
from flask_wtf import FlaskForm
import wtforms as wf
from wtforms.validators import DataRequired
from flask_login import UserMixin
class LoginForm(FlaskForm):
username = wf.StringField(
label="name", validators=[DataRequired("Username is required")]
)
password = wf.StringF... |
import os
import json
import logging
from birdy.twitter import UserClient
logging.basicConfig(filename='tweetme.log', format='%(asctime)s %(message)s', level=logging.DEBUG)
def get_config_from_file(filename="config.json"):
"""
This function will check for the config.json file which holds the Twitter API
... |
from .base_model import QueryableBaseModel
from ...unchained import unchained, injectable
class AntiPatternBaseModel(QueryableBaseModel):
@unchained.inject('db')
def __init__(self, db=injectable, **kwargs):
self.db = db
super().__init__(**kwargs)
def save(self, commit=False):
self... |
from django.test import TestCase
class AnalyzerTestCase(TestCase):
pass
|
"""
Layer Utils for Sauvola Document Binarization
"""
import os
from tensorflow.keras import backend as K
from tensorflow.keras.constraints import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.losses import *
from tensorflow.keras.initializers import *
from tensorflow.keras.metrics import *
from ten... |
#!/usr/bin/env python
#
# 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 ... |
import os
import copy
import numpy as np
import torch
from imageio import imread
from .models import pix2pix
from .detector import Detector
class Reconstructor:
def __init__(self, weights_path=None, detector=None):
if detector is None:
detector = Detector()
self.detector = detector
... |
sp98_dept_filled = ( # adding brackets is nice to chain methods and pretty-print
sp98_dept
.groupby(['departement', 'week'])
['prix']
.mean()
.unstack('departement')
.fillna(method='ffill')
.fillna(method='bfill')
)
Xpca = PCA(n_components=2).fit_transform(sp98_dept_filled.T)
plt.figure(f... |
from qtstrap import *
from codex import SerialDevice
from .bundles import SigBundle, SlotBundle
class SubscriptionManager(QObject):
signals = {
'add_device':[SerialDevice],
'remove_device': [str]
}
slots = {
'device_added': [SerialDevice],
'device_removed': [str],
... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="MutliProcessMStepRegression",
version="0.1.0",
author="王文皓(wangwenhao)",
author_email="DATA-OG@139.com",
description="python多进程逐步回归。python step-wise regression ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 1 2 3 4 5 6 7 8 9 9
# 3456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
"""
ReguLog - Unpacks and analyzes log archives with regular expressi... |
from django import forms
from django.core.validators import MaxValueValidator, MinValueValidator
class GwModelForm(forms.Form):
n = forms.IntegerField(
label="Length of timeseries (n)",
validators=[
MinValueValidator(1)
]
)
hini = forms.FloatField(
label="Initia... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
from scipy.stats import gaussian_kde
class Randomizations(object):
def _compute_randomizations(self,
cond,
column_cell_categories,
permutations,
... |
import csv
import torch
import dgl
from dgl.data import dgl_dataset
from torch._C import device
f = open('D:\subject\graduate\graph computation\data\offline\\train0.csv', 'r')
reader = csv.reader(f)
M = 79
N = 152
record = []
node_num = 0
# user = []
user = {}
item = {}
features = []
user_features = []
item_featu... |
from ursina import *; ssao_shader = Shader(language=Shader.GLSL, fragment='''
#version 140
vec3 sphere[16] = vec3[](
vec3( 0.5381, 0.1856,-0.4319), vec3( 0.1379, 0.2486, 0.4430),
vec3( 0.3371, 0.5679,-0.0057), vec3(-0.6999,-0.0451,-0.0019),
vec3( 0.0689,-0.1598,-0.8547), vec3( 0.0560, 0.0069,-0.1843),
... |
from typing import Any, Dict, Iterable, List, Mapping, Tuple, Union
from collections import OrderedDict
import warnings
from torch import nn
from torch.utils.data import DataLoader, Dataset
from catalyst.core import IExperiment
from catalyst.dl import (
BatchOverfitCallback,
Callback,
CheckpointCallback,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.