content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from configuration import configuration, dbName, debugEverythingNeedsRolling
from optionChain import OptionChain
from statistics import median
from tinydb import TinyDB, Query
import datetime
import time
import alert
import support
class Cc:
def __init__(self, asset):
self.asset = asset
def findNew(... | nilq/baby-python | python |
"""Plotting Module."""
from scphylo.pl._data import heatmap
from scphylo.pl._trees import clonal_tree, dendro_tree, networkx_tree, newick_tree
__all__ = (heatmap, clonal_tree, dendro_tree, networkx_tree, newick_tree)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-03-05 02:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('storehouse', '0002_supplier'),
]
operations = [
migrations.CreateModel(
... | nilq/baby-python | python |
import json
from pathlib import Path
from types import SimpleNamespace
from typing import NamedTuple, Any, Optional
from flask.testing import FlaskClient
from numpy.testing import assert_almost_equal
from osgeo_utils.auxiliary.base import PathLikeOrStr
test_env = SimpleNamespace()
test_env.root = Path('.')
test_env.... | nilq/baby-python | python |
#!/usr/bin/python
import smtplib
import subprocess
import urllib2
from email.mime.text import MIMEText
smtp_address="YOUR SMTP LOGIN"
sender="YOUR SMTP LOGIN "
receiver="YOUR EMAIL DESTINATION"
password="YOURU SMTP PASSWORD"
uptime = subprocess.check_output('uptime')
ip_ext = urllib2.urlopen("http://ifconfig.me/i... | nilq/baby-python | python |
from scipy.stats import norm
import math
def dice_test(stat, alfa, mode_speed):
# add parametrs for normal distribution
if mode_speed == "plt_6":
critical_const = norm.ppf(alfa, loc=0.2700502, scale=math.sqrt(0.0002832429))
p_value = norm.cdf(stat, loc=0.2700502, scale=math.sqrt(0.0002832429))
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from clickhouse_mysql.observable import Observable
class Reader(Observable):
"""Read data from source and notify observers"""
converter = None
event_handlers = {
# called on each WriteRowsEvent
'WriteRowsEvent': [],
# called on each... | nilq/baby-python | python |
"""
Call two arms equally strong if the heaviest weights they each are able
to lift are equal.
Call two people equally strong if their strongest arms are equally strong
(the strongest arm can be both the right and the left), and so are their
weakest arms.
Given your and your friend's arms' lifting capabilities find o... | nilq/baby-python | python |
import setuptools
setuptools.setup(
name="confluent_schema_registry_client",
version="1.1.0",
author="Tom Leach",
author_email="tom@gc.com",
description="A simple client Confluent's Avro Schema Registry",
license="MIT",
keywords="confluent schema registry client avro http rest",
url="ht... | nilq/baby-python | python |
#!/usr/bin/env python2
"""
Dump ranks into a JS file, to be included by index.html.
The JS file contains a global "raw_data" object, with fields:
- contests: list of included contests. Each is an object with:
- name: name of the contest.
- tasks: list of tasks to include in this contest.
- scores: map each use... | nilq/baby-python | python |
"""Responses provided by the iov42 platform."""
import json
from dataclasses import dataclass
from typing import List
from typing import Union
from ._entity import Identifier
from ._request import Request
@dataclass(frozen=True)
class BaseResponse:
"""Base class for successful platform responses."""
request... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
__author__ = 'shichao'
import platform
import tensorflow as tf
import numpy as np
import time
def iterator_demo():
'''
python iterator demo
:return:
'''
class numIter: #
def __init__(self, n):
self.n = n
def __iter__(self):
self.x = ... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QMessageBox, QFileDialog, QGridLayout, QHBoxLayout, \
QVBoxLayout, QGroupBox, QCheckBox, QPushButton, QAction
from PatchEdit impor... | nilq/baby-python | python |
import typer
INFO = typer.style("INFO", fg=typer.colors.GREEN) + ": "
HELP = typer.style("HELP", fg=typer.colors.BLUE) + ": "
FAIL = typer.style("FAIL", fg=typer.colors.RED) + ": "
SUCCESS = typer.style("SUCCESS", fg=typer.colors.BLUE) + ": "
typer.echo(f"{INFO} Importing modules, please wait")
import os
im... | nilq/baby-python | python |
#!/usr/bin/env python3.7
# Copyright 2021 DataStax, 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | nilq/baby-python | python |
import torch
import onnx
from pathlib import Path
import sys
def convert2onnx(model_path,input_size,out_path=None):
if out_path is None:
out_path=Path(model_path).with_suffix('.onnx')
model=torch.load(model_path)
out_path=export2onnx(model,input_size,out_path)
return out_path
... | nilq/baby-python | python |
from caffe2.python import core
import numpy as np
class ParameterTags(object):
BIAS = 'BIAS'
WEIGHT = 'WEIGHT'
COMPUTED_PARAM = 'COMPUTED_PARAM'
class ParameterInfo(object):
def __init__(
self, param_id, param, key=None, shape=None, length=None,
gra... | nilq/baby-python | python |
# Criar e modificar arquivos txt
'''
'r' = Usado somente para ler algo
'w' = Usado somente para escrever algo
'r+' = Usado para ler e escrever algo
'a' = Usado para acrescentar algo
'''
numeros = [0, 15, 10, 20, 15, 45]
# Criar um arquivo e colocar as informações da lista numeros dentro dele
with open('numeros.txt... | nilq/baby-python | python |
"""
Copyright Tiyab KONLAMBIGUE
"""
from gce import client
import logging
import time
from model import job as jobmodel
import configuration
JSON_KEY_FOLDER = configuration.JSON_KEY_FOLDER
# Google instance image project configs
IMAGES_PROJECT = configuration.IMAGES_PROJECT
class instance():
GCE_TERMINATED_STAT... | nilq/baby-python | python |
import datapackage
from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url
dep_prefix = 'dependency://'
parameters, dp, res_iter = ingest()
url = parameters['url']
if url.startswith(dep_prefix):
dependency = url[len(dep_prefix):].strip()
url = get_dependency_datapackage_url(de... | nilq/baby-python | python |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
import operator
import math
import dolfin as dl
import mshr
def sort_points_in_anti_clockwise_order(coords):
coords=coords.T
center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coo... | nilq/baby-python | python |
from fractions import Fraction
from src.seq import fibonacci, stern_diatomic_seq, fib_seq, stern_brocot
from src.graph import stern_brocot_graph
from itertools import islice
import pytest
def test_returns_first_5_numbers_of_stern_brocot():
assert take(stern_brocot, 5) == [
Fraction(1, 1),
Fraction... | nilq/baby-python | python |
# Copyright 2020 Thiago Teixeira
#
# 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 writin... | nilq/baby-python | python |
from datetime import datetime
from importers.e_trac_importer import ETracImporter
from importers.nmea_importer import NMEAImporter
from pepys_import.core.formats import rep_line
def test_nmea_timestamp_parsing():
parse_timestamp = NMEAImporter.parse_timestamp
# Invalid day in date
result = parse_timesta... | nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import IntegerField
from wtforms import SelectField
from wtforms import SubmitField
from wtforms import StringField
from wtforms import FileField
from wtforms import SelectField
from wtforms import PasswordField
from wtforms.validators import Email, Length, Required
from wtf... | nilq/baby-python | python |
from .serializers import User | nilq/baby-python | python |
"""
Other plotting routines outside of matplotlib
"""
import matplotlib.transforms as transforms
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D
import matplotlib.dates as mdates
from matplotlib import collections
from matplotlib.ticker impo... | nilq/baby-python | python |
import win32gui
from src.services.window_managers.base_window_manager import WindowTitleManager
class WindowsWindowManager(WindowTitleManager):
def fetch_window_title(self) -> str:
window_in_focus = win32gui.GetForegroundWindow()
return win32gui.GetWindowText(window_in_focus)
| nilq/baby-python | python |
import requests
from bs4 import BeautifulSoup
LIMIT = 50
URL = f"https://www.indeed.com/jobs?q=python&limit={LIMIT}"
def _check_has_first_page_end() -> bool:
"""Check if the first page has a link to the last page"""
first_response = requests.get(URL)
soup = BeautifulSoup(first_response.text, "h... | nilq/baby-python | python |
from django.contrib import admin
from django.urls import include, path
from accounts.author.api import (
ForgetPasswordView,
LoginAuthorAPIView,
RegisterAuthorView,
)
from accounts.editor.api import (
ForgetEditorPasswordView,
LoginEditorAPIView,
RegisterEditorView,
)
from accounts.reviewer.api... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Useful functions for Counter manipulation.
"""
from collections import Counter
def scale(cntr, factor):
cntr_ = Counter()
for key, value in cntr.items():
cntr_[key] = value * factor
return cntr_
def normalize(cntr):
return scale(cntr, 1./sum(... | nilq/baby-python | python |
# Copyright 2017-2018 The Open SoC Debug Project
#
# 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 agr... | nilq/baby-python | python |
from __future__ import absolute_import
import os.path
import sys
import threading
import typing
import attr
from ddtrace.internal import compat
from ddtrace.internal import nogevent
from ddtrace.internal.utils import attr as attr_utils
from ddtrace.internal.utils import formats
from ddtrace.profiling import collecto... | nilq/baby-python | python |
"""
Added dag name column to executions
Revision ID: e937a5234ce4
Revises: a472b5ad50b7
Create Date: 2021-02-25 12:14:38.197522
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "e937a5234ce4"
down_revision = "a472b5ad50b7"
branch_labels = None
depends_on = None
... | nilq/baby-python | python |
# Generated by Django 3.1 on 2020-08-05 10:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('website', '0010_auto_20200804_1433'),
]
operations = [
migrations.AlterModelOptions(
name='userplugin',
options={'ordering': (... | nilq/baby-python | python |
from pathlib import Path
def findFullFilename(path, pattern):
filenameGenerator = Path(path).glob(pattern)
firstPath = next(filenameGenerator, None)
if firstPath is None:
return None
return firstPath.name
def findPywFilenameHere(pattern):
return findFullFilename(".", f"{pattern}*... | nilq/baby-python | python |
from heuristicSearch.planners.astar import Astar
from heuristicSearch.envs.env import GridEnvironment
from heuristicSearch.graph.node import Node
from heuristicSearch.envs.occupancy_grid import OccupancyGrid
from heuristicSearch.utils.visualizer import ImageVisualizer
from heuristicSearch.utils.utils import *
import m... | nilq/baby-python | python |
#! /usr/bin/env python
from pathlib import Path
import re
import uxn
import sys
token_prog = re.compile(r"\s*(\)|\S+)")
line_comment_prog = re.compile(r".*")
string_prog = re.compile(r".*?(?<!\\)\"")
fixed_prog = re.compile(r"(-|\+)?\d+\.\d+")
prefix_chars = '%:.;,@&|$#~\'"'
def eprint(s):
sys.stderr.write(f"{... | nilq/baby-python | python |
# Python3 program for Painting Fence Algorithm
# optimised version
# Returns count of ways to color k posts
def countWays(n, k):
dp = [0] * (n + 1)
total = k
mod = 1000000007
dp[1] = k
dp[2] = k * k
for i in range(3,n+1):
dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])... | nilq/baby-python | python |
"""
Manipulate Excel workbooks.
"""
from datetime import datetime
import os
from openpyxl import Workbook
from openpyxl.styles import NamedStyle, Font, Border, Side, PatternFill
from trellominer.api import trello
from trellominer.config import yaml
class Excel(object):
def __init__(self):
self.config =... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
This is the Keras implementation for the GermEval-2014 dataset on NER
This model uses the idea from Collobert et al., Natural Language Processing almost from Scratch.
It implements the window approach with an isolated tag criterion.
For more details on the task see:
https://www.ukp.tu-dar... | nilq/baby-python | python |
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
application = Cling(get_wsgi_application())
| nilq/baby-python | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: fabric_next.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _r... | nilq/baby-python | python |
import torch as th
import numpy as np
from gym import Env
from gym.spaces import Discrete, MultiDiscrete
__all__ = [
"MatrixGameEnv"
]
class MatrixGameEnv(Env):
def __init__(self, matrices, reward_perturbation=0, rand: th.Generator = th.default_generator):
super().__init__()
matrices ... | nilq/baby-python | python |
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
import os
from matplotlib import rc
from matplotlib import rcParams
font_size=14
rcParams["backend"] = "PDF"
rcParams["figure.figsize"] = (4, 3)
rcParams["font.family"] = ... | nilq/baby-python | python |
# 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 ... | nilq/baby-python | python |
# 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 agreed to in... | nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import sys
import logging
from pathlib import Path
from capanno_utils.validate import *
from capanno_utils.validate_inputs import validate_inputs_for_instance
from capanno_utils.helpers.validate_cwl import validate_cwl_tool
from capanno_utils.helpers.get_paths import get_types_fr... | nilq/baby-python | python |
_base_ = [
'../../_base_/models/vision_transformer/vit_large_p16_sz224.py',
'../../_base_/datasets/imagenet/swin_sz384_8xbs64.py',
'../../_base_/default_runtime.py',
]
# model
model = dict(backbone=dict(img_size=384))
# data
data = dict(imgs_per_gpu=64, workers_per_gpu=6)
# additional hooks
update_interv... | nilq/baby-python | python |
from rest_framework import serializers
from core.models import Link, Comment
class LinkSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Link
class CommentSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Comment
| nilq/baby-python | python |
# Generated by Django 3.2.4 on 2021-06-23 21:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timewebapp', '0044_alter_settingsmodel_first_login'),
]
operations = [
migrations.AlterField(
model_name='settingsmodel',
... | nilq/baby-python | python |
import pytest
import os
@pytest.mark.processor("gpu")
@pytest.mark.model("placeholder")
@pytest.mark.skip_cpu
@pytest.mark.skip_py2_containers
def test_placeholder():
pass
| nilq/baby-python | python |
#!/usr/bin/env python
'''
Experimental viewer for DAVIS + OpenXC data
Author: J. Binas <jbinas@gmail.com>, 2017
This software is released under the
GNU LESSER GENERAL PUBLIC LICENSE Version 3.
Usage:
Play a file from the beginning:
$ ./view.py <recorded_file.hdf5>
Play a file, starting at X percent:
$ ./view.py... | nilq/baby-python | python |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from pages.top_bars.top_navigate_bar import TopNavigateBar
class TemplatesPage(TopNavigateBar):
""" Templates page - contains variety of templates to select """
_TEMPLATES_BLOCK = (By.CSS_SELECTOR, "#templ... | nilq/baby-python | python |
#Hall bar geometry device. Measurements have r_xx and/or r_xy
import numpy as np
import matplotlib.pyplot as plt
import warnings
from scipy.signal import savgol_filter
from pylectric.analysis import mobility
from scipy import optimize as opt
class Meas_GatedResistance():
"""Class to handle a single sweep of raw da... | nilq/baby-python | python |
import pyautogui
import time
while True:
initial_mouse = pyautogui.position()
time.sleep(0.5)
final_mouse = pyautogui.position()
print(initial_mouse)
print(final_mouse)
if initial_mouse != final_mouse:
pyautogui.hotkey("alt","tab")
else:
exit
| nilq/baby-python | python |
'''
Crie um programa:
Leia o nome de um aluno
leia duas notas do aluno
guarde em uma lista composta
no final mostre:
Um boletim contendo:
A média de cada um
permita que o usuário possa mostrar as notas de cada aluno individualmente
'''
alunos = list()
while True:... | nilq/baby-python | python |
"""
pyTRIS
------
pyTRIS - a simple API wrapper for Highways England's WebTRIS Traffic Flow API.
"""
from .api import API
from . import models
__all__ = ['API']
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
created by huash06 at 2015-04-15 08:45
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
如果是求不连续的字串
方法1:
令f(i,j)表示s[i:j+1]的最长回文的长度
if s[i]==s[j]:
f(i,j) = f(i... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 13:10:45 2018
@author: aloswain
"""
from datetime import datetime
import backtrader as bt
class SmaCross(bt.SignalStrategy):
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
crossover = bt.ind.Cr... | nilq/baby-python | python |
'''
Algoritmo de Prim
1. T ← vazio;
2. V' ← {u};
3. para-todo v E V – V' faça
4. L(v) ← peso ({u,v});
5. fim-para-todo
6. enquanto V' != V faça
7. ache um vértice w tal que L(w) = min {L(v) | v E V-V'};
8. u = o vértice de V', ligado a w, representando a aresta com o menor custo;
9. e = {u,w};
10... | nilq/baby-python | python |
#! /usr/bin/python
from pylab import *
from sys import argv,exit,stdout
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
from scipy import interpolate
import numpy as np
from finite_differences_x import *
from interp import *
def read_EFIT(EFIT_file_name):
EFITdict = {}
f = open(... | nilq/baby-python | python |
# from __future__ import absolute_import
from abstractions.recognition import DistanceEstimator
import numpy
from typing import List
class NumpyDistanceEstimator(DistanceEstimator):
def distance(self,
face_features_we_have : [bytes],
face_feature_to_compare
) -> List[float]:
if len(face... | nilq/baby-python | python |
import json
import os
import random
import sqlite3
import urllib
import requests
from flask import Flask
app = Flask(__name__)
def get_cursor():
connection = sqlite3.connect("database.db")
c = connection.cursor()
return c
USER_ID = 1
def init_db():
c = get_cursor()
c.execute("""
CREATE T... | nilq/baby-python | python |
#######################################################################
### Script for Calling Plotting Scripts and Merging the Plots ###
#######################################################################
import sys
current_path = sys.path[0]
ex_op_str = current_path[current_path.index('progs')+6: current_p... | nilq/baby-python | python |
from heapq import heappush, heappop, heapify
import itertools
class Queue:
def __init__(self):
self.q = []
def enqueue(self, element):
self.q.append(element)
def dequeue(self):
return self.q.pop(0)
def is_empty(self):
return len(self.q) == 0
def front(self):
return self.q[0]
class DisjointSets:
d... | nilq/baby-python | python |
# import pytest
# from ..accessor import session
# @pytest.mark.skip(reason="initial run on gh actions (please remove)")
# def test_session():
# """
# tests that a session can be created without error
# """
# with session() as db:
# assert db
| nilq/baby-python | python |
"""
This file builds Tiled Squeeze-and-Excitation(TSE) from paper:
<STiled Squeeze-and-Excite: Channel Attention With Local Spatial Context> --> https://arxiv.org/abs/2107.02145
Created by Kunhong Yu
Date: 2021/07/06
"""
import torch as t
def weights_init(layer):
"""
weights initialization
Args :
--layer: one la... | nilq/baby-python | python |
from typing import Iterable
from eth2spec.test.context import PHASE0
from eth2spec.test.phase0.genesis import test_initialization, test_validity
from gen_base import gen_runner, gen_typing
from gen_from_tests.gen import generate_from_tests
from eth2spec.phase0 import spec as spec
from importlib import reload
from eth... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
import shutil
download_fail_times = 0
pvmp3_path = sys.path[0]
download_path = os.path.join(pvmp3_path, "source")
final_src_path = os.path.join(pvmp3_path, "src")
print('download pvmp3 source file')
if not os.path.exists(final_src_path):
while True:
if not os.p... | nilq/baby-python | python |
import csv
from environs import Env
env = Env()
env.read_env()
fieldnames = ['id', 'nome_da_receita', 'descricao_da_receita']
def listar_receitas():
with open(env('RECEITAS_CSV')) as f:
reader = csv.DictReader(f)
return [receita for receita in reader]
def buscar_receitas(nome):
with open(... | nilq/baby-python | python |
from datetime import datetime, timedelta
from pynput.keyboard import Listener as KeyboardListener
from pynput.mouse import Listener as MouseListener
from apis.mongo.mongo_client import log_event, log_processes
from apis.monitoring_details.win32_window_details import active_window_process, all_open_windows
# logging.... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# noc.core.snmp.ber tests
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ------------------------------------------------------... | nilq/baby-python | python |
import logging
from itertools import cycle, islice
from typing import Callable, List, Optional
import torch
from hypergraph_nets.hypergraphs import (
EDGES,
GLOBALS,
N_EDGE,
N_NODE,
NODES,
RECEIVERS,
SENDERS,
ZERO_PADDING,
HypergraphsTuple,
)
from strips_hgn.hypergraph.hypergraph_v... | nilq/baby-python | python |
# Generated by Django 2.2.7 on 2019-12-18 14:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0003_favourit... | nilq/baby-python | python |
# always write to disk
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler'
]
STATIC_URL = '/static/'
STATIC_ROOT = '/app/public'
MEDIA_ROOT = '/data'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDire... | nilq/baby-python | python |
import os
import keras
import random as rn
import numpy as np
import tensorflow as tf
from keras.layers import Dense, Activation, Embedding
from keras.layers import Input, Flatten, dot, concatenate, Dropout
from keras import backend as K
from keras.models import Model
from keras.engine.topology import Layer
from keras... | nilq/baby-python | python |
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import unidecode as udc
import scipy
class CustomOneHotEncoder(BaseEstimator, TransformerMixin):
"""
Clase que convierte a dummies las variables categóricas de un dataFrame. Permite eliminar
las dummies creadas según su re... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
###########################################################
# #
# Copyright (c) 2018 Radek Augustýn, licensed under MIT. #
# #
#######################################################... | nilq/baby-python | python |
"""
Check if 2 strings are anagrams of each other
"""
from collections import Counter
def check_anagrams(str1, str2):
ctr1 = Counter(str1)
ctr2 = Counter(str2)
return ctr1 == ctr2
def check_anagrams_version2(str1, str2):
hmap1 = [0] * 26
hmap2 = [0] * 26
for char in str1:
pos = ord... | nilq/baby-python | python |
import sys
import os
#reference = sys.argv[1]
#os.system("cp "+reference+" "+sys.argv[4])
firstfile = sys.argv[1] #sys.argv[1]
secondfile = sys.argv[2]
thirdfile = sys.argv[3]
seq1 = set()
seq2 = set()
file3 = open(thirdfile, 'r')
for line in file3:
myline = line.strip()
seqnames = myline.split('\t')
seq... | nilq/baby-python | python |
class TicTacToe():
'''
Game of Tic-Tac-Toe
rules reference: https://en.wikipedia.org/wiki/Tic-tac-toe
'''
# coordinates of the cells for each possible line
lines = [ [(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)],
[(0,0), (1,0), (2... | nilq/baby-python | python |
import cv2
import numpy as np
# Read image
img = cv2.imread("imori.jpg")
# Dicrease color
out = img.copy()
out = out // 64 * 64 + 32
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
| nilq/baby-python | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import collections.abc
import json
import typing
from azure.functions import _sql as sql
from . import meta
class SqlConverter(meta.InConverter, meta.OutConverter,
binding='sql'):
@classmethod
... | nilq/baby-python | python |
'''
This program parses a txt file containing proteins to analyse with IUPRED/BLAST/JALVIEW
'''
import warnings # allows program to be able to ignore benign warnings
#####
# IGNORE WARNINGS
#####
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufun... | nilq/baby-python | python |
from typing import TYPE_CHECKING
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Provider.Common import GameFile
if TYPE_CHECKING:
from UE4Parse.IO import FFileIoStoreReader
from UE4Parse.IO.IoObjects.FIoChunkId import FIoChunkId
from UE4Parse.IO.IoObjects.FIoOffsetAndLength import FIoOffsetA... | nilq/baby-python | python |
# Copyright 2014 The Crashpad 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 applicabl... | nilq/baby-python | python |
import unittest
import numpy as np
import tensorflow as tf
from pplp.core import box_4c_encoder
class Box4cEncoderTest(unittest.TestCase):
def test_np_box_3d_to_box_4c(self):
# Test non-vectorized numpy version on ortho boxes
# Sideways box
box_3d_1 = np.asarray([0, 0, 0, 2, 1, 5, 0])
... | nilq/baby-python | python |
from .xml_style import XMLDataset
class VOCDataset(XMLDataset):
CLASSES = ['spike']
def __init__(self, **kwargs):
super(VOCDataset, self).__init__(**kwargs)
| nilq/baby-python | python |
#!/usr/bin/env python
from .web_api_2 import SwaggerGiant | nilq/baby-python | python |
import os, paramiko, time, schedule, smtplib, ssl
from datetime import datetime
from email.message import EmailMessage
host='localhost'
port='5432'
user='postgres'
password='admin'
database='testdb'
#chemin de sauvegarde locale
local_dir = 'C:\\Users\\Kamla\\projets\\auto-backup-sqldb\\backup\\'
#local_dir = 'Chemin ... | nilq/baby-python | python |
from pathlib import Path
import pandas as pd
from collections import defaultdict
from typing import List, Union
from .types import Child
def create_csv(children: List[Child], output_dir: Union[Path,str]):
header_df = create_header(children)
episodes_df = create_episodes(children)
uasc_df = create_uasc(chi... | nilq/baby-python | python |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--latitude", type=float, required=True, help="The latitude of your bounding box center")
parser.add_argument("--longitude", type=float, required=True, help="The longitude of your bounding box center")
args = parser.parse_args()
dlat = 0.005
dlon =... | nilq/baby-python | python |
from modules.data.fileRead import readMat
from numpy import arange
from modules.modelar.leastSquares import calculate
# Alternativa para caso as constantes escolhidas não forem escolhidas pelo Usuário
SP = 50
OVERSHOOT = 0.10
TS = 70
# Pegando vetores de entrada e saída
ENTRADA, SAIDA, TEMPO = readMat()
# Calculando... | nilq/baby-python | python |
import argparse
import os
import pandas as pd
import re
import spacy
import sys
from datetime import datetime
from geopy.extra.rate_limiter import RateLimiter
from geopy import Nominatim
from epitator.geoname_annotator import GeonameAnnotator
from epitator.date_annotator import DateAnnotator
from epita... | nilq/baby-python | python |
from cmsisdsp.sdf.nodes.simu import *
import numpy as np
import cmsisdsp as dsp
class Processing(GenericNode):
def __init__(self,inputSize,outputSize,fifoin,fifoout):
GenericNode.__init__(self,inputSize,outputSize,fifoin,fifoout)
def run(self):
i=self.getReadBuffer()
o=self.getWrit... | nilq/baby-python | python |
def say_hi():
print("hello world function")
def cube(num):
return num*num*num
say_hi()
print(cube(3))
# Statements
is_male = False
if is_male:
say_hi()
else:
print("Goodbay")
# Statements
is_female = True
if is_female or is_male:
print("Hi")
else:
print("Goodbay")
# Dictionary
mont... | nilq/baby-python | python |
import os
from argh.dispatching import dispatch_command
import application
def start_app():
port = int(os.getenv('PORT'))
application.start(port=port)
if __name__ == '__main__':
dispatch_command(start_app)
| nilq/baby-python | python |
import os
from git import Repo
from django.core.exceptions import PermissionDenied
from base.handlers.extra_handlers import ExtraHandler
from base.handlers.file_handler import FileHandler
from base.handlers.form_handler import FormHandler
from base.handlers.path_handlers import PathHandler
from base.handlers.github_... | nilq/baby-python | python |
from radixlib.api_types.identifiers import AccountIdentifier
from radixlib.serializable import Serializable
from radixlib.api_types import TokenAmount
from typing import Dict, Any
import radixlib as radix
import json
class TransferTokens(Serializable):
""" Defines a TransferTokens action """
def __init__(
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.