content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from __future__ import print_function, division
from argparse import ArgumentParser
from sys import exc_info
from time import ctime
from datetime import datetime
from decimal import Decimal
from traceback import print_tb
from random import randint
from tqdm import trange
from .api import TradewaveAPI
from .data impo... | nilq/baby-python | python |
import copy
import floppyforms as forms
from crispy_forms.bootstrap import Tab, TabHolder
from crispy_forms.layout import HTML, Field, Fieldset, Layout
from django import forms as django_forms
from django.forms.models import modelform_factory
from django.utils.text import slugify
from django.utils.translation import ... | nilq/baby-python | python |
#! /usr/bin/env python3
# Copyright 2022 Tier IV, 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 la... | nilq/baby-python | python |
from setuptools import setup
setup(
name='django-subquery',
version='1.0.4',
description='SubQuery support in Django < 1.11',
url='https://github.com/schinckel/django-subquery/',
author='Matthew Schinckel',
author_email='matt@schinckel.net',
packages=['django_subquery']
)
| nilq/baby-python | python |
from easygraphics import *
x = 0
y = 0
def draw_compositon(x, y, mode, alpha_value):
set_background_color(Color.TRANSPARENT)
set_font_size(18)
set_line_width(3)
set_color("black")
set_composition_mode(CompositionMode.SOURCE)
draw_rect_text(x, y + 175, 200, 25, mode)
set_fill_color(to_alph... | nilq/baby-python | python |
#!/usr/bin/python3
import tensorflow as tf
import numpy as np
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
class Addressing(Model):
def __init__(self, memory_locations=128, memory_vector_size=20, maximum_shifts=3, reading=True):
super(Addressing, self).__init__()
... | nilq/baby-python | python |
# grep a csv file for an expression and copy the csv header into the output
import os
import sys
from misc import *
if len(sys.argv) < 3:
err("usage: csv_grep [pattern] [input csv file]")
pattern, filename = sys.argv[1], sys.argv[2]
grep_file = filename + "_grep" # grep results go here
a = os.system("grep " + pat... | nilq/baby-python | python |
import glob
import os
import numpy as np
import pandas as pd
from common.paths import POWER_FC, ADHD, PLS_WEIGHTS, RIDGE_WEIGHTS, BIOBANK_LABELS
from common.power_atlas import to_power_fc_vector, get_power_fc_vector_labels
from common.wisc import WISC_LEVEL
def get_data(wisc_level=5, label_path=ADHD):
"""
G... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
s = input("Введите строку:")
count = 0
vowels = {'е', 'ы', 'а', 'о', 'э', 'я', 'и', 'ю'}
for letter in s:
if letter in vowels:
count += 1
print("Количество гласных равно:")
print(count)
| nilq/baby-python | python |
try:
from sshtunnel import SSHTunnelForwarder
except ImportError:
from sshtunnel.sshtunnel import SSHTunnelForwarder
from cm_api.api_client import ApiResource, ApiException
from cm_api.endpoints.services import ApiService, ApiServiceSetupInfo
import paramiko
import json
import yaml
import requests
import subpro... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | nilq/baby-python | python |
from abc import ABCMeta, abstractmethod
from copy import deepcopy
import attr
from utensor_cgen.utils import MUST_OVERWRITEN
class Morphism(object):
__metaclass__ = ABCMeta
@abstractmethod
def apply(self, from_op):
raise RuntimeError('abstract transform invoked')
@attr.s
class TypedMorphism(Morphism):
... | nilq/baby-python | python |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
from essmc2.utils.registry import Registry
HOOKS = Registry("HOOKS")
| nilq/baby-python | python |
## Yoni Schirris. 06/10/2020
## Exact copy of main.py (now main_unsupervised.py)
## Idea is to keep functionality of both supervised and unsupervised in here, with some switches that change only minor
## things to switch between supervised and unsupervised learning.
## Thus, in the end, we should again have a single "m... | nilq/baby-python | python |
"""
Deuce Valere - Tests - API - System - Manager
"""
import datetime
import unittest
from deuceclient.tests import *
from deucevalere.api.system import *
class DeuceValereApiSystemManagerTest(unittest.TestCase):
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
... | nilq/baby-python | python |
# sum_of_multiplications([(1, 2), (5, 10)]) should return 52
# because (1 * 2 + 5 * 10) is 52
def sum_of_multiplications(l):
sum = 0
for value1, value2 in l:
sum += value1 * value2
return sum
if __name__ == '__main__':
print(sum_of_multiplications([(1, 2), (5, 10)])) | nilq/baby-python | python |
"""
This is the plugin code for threshold segmentation(binary) of rectilinear grid.
This plugin is designed to segment a grid such that cells with magnitude greater than the threshold value are
labelled as 1, otherwise labelled as 0. This provides the ground truth results for
such a fluid segmentation.
Accepted input d... | nilq/baby-python | python |
"""
对Kaiming He新提出的MAE的简要实现
"""
# ----------------------------------------------------------------
# borrowed from https://github.com/IcarusWizard/MAE.git
# ----------------------------------------------------------------
import numpy as np, torch
import torch.nn as nn
from .transformer import Encoder
def random_ind... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('barsystem', '0037_auto_20150721_1500'),
]
operations = [
migrations.RenameField(
model_name='product',
... | nilq/baby-python | python |
import unittest
from unittest.mock import Mock, MagicMock
import math
import shapely as sh
import shapely.geometry
import numpy as np
import numpy.testing
import shart
from shart.box import *
class TestMain(unittest.TestCase):
def test_attribute(self):
g = Group.rect(0, 0, 100, 100)
self.asse... | nilq/baby-python | python |
#! /Users/bin/env Python
# Modified version of get_disease.py from ClinGen/LoadData. Creates JSON file
# with all Orphanet data for (initial) load into the server. Run this script
# before using this one:
# obtain_external_data_files.py -s orphanet
import json
from uuid import uuid4
from xml.etree import ElementTre... | nilq/baby-python | python |
# coding=utf8
# Copyright 2018 JDCLOUD.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 ... | nilq/baby-python | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bunch of fixtures to be used across the tests."""
import pytest
@pytest.fixture(scope="function")
def hello_world(request):
"""Create a test fixture."""
hw = "Hello World!"
def tear_down():
# clean up here
pass
request.addfinalizer(t... | nilq/baby-python | python |
from __future__ import absolute_import
from datetime import timedelta
from celery.schedules import crontab
from .celery import app
from django.conf import settings
RESULT_BACKEND = 'django-db'
# Mitigate deprecation error:
# The 'BROKER_URL' setting is deprecated and scheduled for removal in
# version 6.0.0. ... | nilq/baby-python | python |
'''
Author : @amitrajitbose
Problem : Codechef IPCTRAIN
Approach : Greedy
'''
t=int(input())
for _ in range(t):
finalAnswer=0
n,day=[int(x) for x in input().strip().split()]
valf=[int(i) for i in range(day+1)]
dt=[]
si=[]
for i in range(n):
d,t,s=[int(x) for x in input().strip().split()]
... | nilq/baby-python | python |
import numpy as np
from numpy.core.defchararray import isupper
def printMatrix(mat):
out = ""
for idxi, i in enumerate(mat):
for idxj, j in enumerate(i):
out += f"{mat[idxi][idxj]} "
out += "\n"
print(out)
def printCoordMatrix(mat):
mat = np.flip(mat, 1)
out = ""
fo... | nilq/baby-python | python |
"""This module will contain class Sort and its related methods."""
class Sort(object):
"""
"""
def __init__(self, iterable=None):
if iterable is None:
iterable = []
if type(iterable) is not list:
raise TypeError('Input is not a list.')
self.len = len(itera... | nilq/baby-python | python |
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid value, enter an integer")
continue
except:
print("Something went wrong")
continue
if age < 0 or age > 499:
print("Age not within valid range")
continue
else... | nilq/baby-python | python |
from itertools import product
import epimargin.plots as plt
import numpy as np
import pandas as pd
import seaborn as sns
from epimargin.estimators import analytical_MPVS
from epimargin.models import SIR
from epimargin.policy import PrioritizedAssignment, RandomVaccineAssignment, VaccinationPolicy
from studies.age_stru... | nilq/baby-python | python |
# coding=utf-8
import camera_app
import logging
logger = logging.getLogger(__name__)
logging.getLogger().setLevel(logging.INFO)
if __name__ == '__main__':
camera_app.start()
| nilq/baby-python | python |
from flask import Blueprint, session, render_template, request, jsonify, Response, abort, current_app, flash, Flask, send_from_directory
from jinja2 import TemplateNotFound
from functools import wraps
from sqlalchemy import or_, and_
from sqlalchemy.orm.exc import NoResultFound
from psiturk.psiturk_config import Psit... | nilq/baby-python | python |
import pandas as pd
import torch
class DataManager:
def __init__(self, data, labels, folds):
self.raw_data = data
self.data = self.chunks(data, folds)
self.labels = self.chunks(labels, folds)
self.folds = folds
self.index = 0
def chunks(self, seq, n):
av... | nilq/baby-python | python |
from datetime import datetime, timedelta
import requests
import collectd
class BorgBaseService:
def __init__(self):
self.endpoint = "https://api.borgbase.com/graphql"
self.api_key = None
self.next_request_time = None
self.cached_response = None
def dispatch(self, repo, value... | nilq/baby-python | python |
import logging
import os
from telegram.ext import Updater
from db_wrapper import DBWrapper
from handlers.admins import AdminsHandler
from handlers.all import AllHandler
TOKEN = os.environ.get("TOKEN")
LOG_LEVEL = os.environ.get("LOG_LEVEL")
DB_FILE = os.environ.get("DB_FILE")
logging.basicConfig(format='%(asctime)s... | nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,FileField,SubmitField
from wtforms.validators import Required
class CommentForm(FlaskForm):
title = StringField('Comment title',validators= [Required()])
comment = TextAreaField('Comment review')
submit = SubmitField('submit')
... | nilq/baby-python | python |
# Implement the Linear Reciprocal Maximization problem
import gurobipy as gp
import numpy as np
from gurobipy import *
id = 903515184
# Invoke Gurobi to solve the SOCP
def solve_socp(id, m=400, n=50):
gm = gp.Model("reciprocal")
A, b = get_data(id, m, n)
# print(A.shape, b.shape) # (400, 50... | nilq/baby-python | python |
from ..api_base import ApiBase
class CorporateCreditCardExpenses(ApiBase):
"""Class for BankTransactions APIs."""
GET_CORPORATE_CREDIT_CARD_EXPENSES = '/api/tpa/v1/corporate_credit_card_expenses'
GET_CORPORATE_CREDIT_CARD_EXPENSES_COUNT = '/api/tpa/v1/corporate_credit_card_expenses/count'
def get(se... | nilq/baby-python | python |
import prata
import time
import timeit
import numpy as np
import sys
import random
import string
B = 1
KB = 1000
MB = 1000000
END = []
def getString(s):
#''.join(random.choice(string.ascii_letters) for x in range(int(real)))
real = 1 if (s-49) < 1 else s-49
return "1"*real
TIMES = 5
SLEEP = 2
NUMBER = ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
This file is used for indexing FedWeb2013.
@author: Shuo Zhang
"""
import os
import tarfile
from bs4 import BeautifulSoup
from Elastic import Elastic
def fedweb13_index(index_name,output_file):
elastic = Elastic(index_name)
mappings = {
# "id": Elastic.notanalyzed_field()... | nilq/baby-python | python |
import ast
import re
import shutil
import sys
import urllib.parse
import urllib.request
from pathlib import Path
def download_build(branch_url: str, build: str, reg_exr: re, directory: Path):
build_url = branch_url + build + "/"
build_api_url = build_url + "api/python"
artifacts = ast.literal_eval(urllib.... | nilq/baby-python | python |
from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
from datetime import datetime
from datetime import date
from braintree.authorization_adjustment import AuthorizationAdjustment
from unittest.mock import MagicMock
class TestTransaction(unittest.TestCase):
@raises_with_... | nilq/baby-python | python |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Promise
from .models import Family
from .models import User
admin.site.register(Promise)
admin.site.register(Family)
admin.site.register(User, UserAdmin)
| nilq/baby-python | python |
"""
Pylot
model.py
You may place your models here.
"""
from active_sqlalchemy import SQLAlchemy
import pylot.component.model
from . import get_config
config = get_config()
db = SQLAlchemy(config.DATABASE_URI)
# User Struct.
UserStruct = pylot.component.model.user_struct(db)
# Post Struct
PostStruct = pylot.compo... | nilq/baby-python | python |
from typing import List, Tuple
import logging
from .track import Track
from vcap import DetectionNode
from vcap_utils import iou_cost_matrix, linear_assignment
MATCH_FUNC_OUTPUT = Tuple[
List[Tuple[DetectionNode, Track]],
List[Track],
List[DetectionNode]]
class Tracker:
def __init__(self, min_iou, ... | nilq/baby-python | python |
def reverseArray(arr, start, end):
while start < end:
if arr[start] != arr[end]:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
def reverseArrayInRecursive(arr, start, end):
if start >= end:
return arr
arr[start], arr[end] = arr[e... | nilq/baby-python | python |
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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... | nilq/baby-python | python |
import pytest
from mock import patch
from uds.can.consecutive_frame import CanConsecutiveFrameHandler, \
InconsistentArgumentsError, CanDlcHandler, DEFAULT_FILLER_BYTE
from uds.can import CanAddressingFormat
class TestCanConsecutiveFrameHandler:
"""Unit tests for `CanConsecutiveFrameHandler` class."""
S... | nilq/baby-python | python |
foo = input("Treat? ")
if foo == "Pastry":
print("Buttery flaky goodness")
elif foo == "Cake":
print("A light and fluffy classic")
elif foo == "Cookie":
print("Warm and crispy on the edges")
else:
print("We do not sell that. It sounds yum!")
foo = int(input("Wind speed? "))
if foo < ... | nilq/baby-python | python |
from .sender import *
from .receiver import *
| nilq/baby-python | python |
import pytest
from pre_commit.main import main as pre_commit
from versort import get_sorter
def test_style():
"""Just run pre-commit and see what happens."""
pre_commit(("run", "--all-files", "--show-diff-on-failure", "--color=always"))
def test_unknown_sorter():
"""See there's a valid error when a sor... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# (Deprecated) The old version of similarity calculation. Will be removed in upcoming update.
from func.utils import Database
from func.model import Model
from pyspark.sql.functions import column
import pickle
import time
def prefilter(db, test):
app_query = 'SELECT * FROM app WHERE... | nilq/baby-python | python |
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework.exceptions import NotFound
from allauth.account.models import EmailAddress
from users.models import User
from organizations_ext.model... | nilq/baby-python | python |
from doodledashboard.component import NotificationCreator
from doodledashboard.notifications.notification import Notification
from doodledashboard.notifications.outputs import TextNotificationOutput
class TextInMessage(Notification):
"""Creates a notification containing the text of the last message"""
def cr... | nilq/baby-python | python |
from .util import generate_evenly_spaced_data_set
def pagie_func1(x, y):
return 1.0 / x ** (-4) + 1.0 / y ** (-4)
def generate_pagie1():
train = generate_evenly_spaced_data_set(pagie_func1, 0.4, (-5, 5))
test = generate_evenly_spaced_data_set(pagie_func1, 0.4, (-5, 5))
return train, test
all_probl... | nilq/baby-python | python |
# mc_bot.py
# Source: https://github.com/DrGFreeman/mc-to-discord
#
# MIT License
#
# Copyright (c) 2018 Julien de la Bruere-Terreault <drgfreeman@tuta.io>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i... | nilq/baby-python | python |
"""Setup module for NI Veristand."""
from os.path import dirname
from os.path import join
from setuptools import find_packages
from setuptools import setup
pypi_name = 'niveristand'
def get_version(name):
"""Calculate a version number."""
import os
version = None
script_dir = os.path.dirname(os.path... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from brewtils.models import Operation
from beer_garden.api.http.base_handler import BaseHandler
class NamespaceListAPI(BaseHandler):
async def get(self):
"""
---
summary: Get a list of all namespaces known to this garden
responses:
200:
... | nilq/baby-python | python |
from PIL import Image
import numpy
from .base import Base
from .loss_func import psnr_np, mse_np
from utils import Loader, Keeper
class BaseInterpolation(Base):
_scale_type = None
_scale_factor = 4
def model(self):
return None
def serialize(self):
pass
def unserialize(self):
... | nilq/baby-python | python |
#Archivo para rutas USER
#Este modulo permite definir subrutas o rutas por separado, response es para respuestas HTTP
from fastapi import APIRouter, Response, status
#Esto solo me dice a donde conectarme, no hay un schema
from config.db import conn
#Aquí traemos el schema
from models.order_details import order_de... | nilq/baby-python | python |
"""
Definitions of various hard coded constants.
Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
"""
# Pyro version
VERSION = "4.30"
# standard object name for the Daemon object
DAEMON_NAME = "Pyro.Daemon"
# standard name for the Name server itself
NAMESERVER_NAME = "Py... | nilq/baby-python | python |
import logging
import bson
import hashlib
import base58
def doc2CID (inp):
try:
# JSON OBJ to BSON encode
bson_ = bson.dumps(inp)
# SHA-256 Double Hashing
hash_ = hashlib.sha256(bson_)
hash_ = hashlib.sha256(hash_.digest())
# Convert to Base-58 string
b58c_ ... | nilq/baby-python | python |
# Supported clients
from .supported_search_clients import SupportedSearchClients
# Utility function
from .download_images import download_image, download_all_images
# Search API Clients
from .search_api_client import SearchAPIClient
from .google_cse_client import GoogleCustomSearchEngineClient
from .bing_image_search... | nilq/baby-python | python |
from quantumdl.models.quantummodel import *
from quantumdl.core.engine import * | nilq/baby-python | python |
import datetime
from django.utils.timezone import utc
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions
from django.utils.six import text_type
import base64
import binascii
from django.contrib.auth import get_user_model
from django.middleware.csrf import CsrfViewMiddlew... | nilq/baby-python | python |
from __future__ import annotations
from unittest import TestCase
from tests.classes.simple_order import SimpleOrder
from tests.classes.simple_project import SimpleProject
from tests.classes.simple_chart import SimpleChart
from tests.classes.simple_setting import SimpleSetting
from tests.classes.author import Author
fro... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from flask import render_template, request, redirect, url_for, abort
from fcsite import check_forced_registration_blueprint
from fcsite.models import bbs
from fcsite.auth import requires_login
from fcsite.utils import pagination, logi
mod = check_forced_registration_blueprint('bbs', __name__, ... | nilq/baby-python | python |
# Copyright 2014: Mirantis 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 b... | nilq/baby-python | python |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
... | nilq/baby-python | python |
# Author: Calebe Elias Ribeiro Brim
# Last Update: 03/06/2018
import numpy as np
def bitsToBytes(values):
'''
Generate relative bits integers
Usage:
bitsToBytes(array.shape(1,10)) => array.shape(1,1)
bitsToBytes(array.shape(2,10)) => array.shape(2,1)
'''
ln = val... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'KeyWizard.ui'
#
# Created by: PyQt5 UI code generator 5.14.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_KeyWizard(object):
def setupUi(self, KeyWizard):
KeyWiz... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pygame import *
import os
PLATFORM_WIDTH = 32
PLATFORM_HEIGHT = 32
PLATFORM_COLOR = "#FF6262"
ICON_DIR = os.path.dirname(__file__) # Полный путь к каталогу с файлами
class Platform(sprite.Sprite):
def __init__(self, x, y):
sprite.Sprite.__init__(self)
... | nilq/baby-python | python |
import sys
import os
from setuptools import setup
"""
Use pandoc to convert README.md to README.rst before uploading
$ pandoc README.md -o README.rst
"""
if "publish" in sys.argv:
os.system("python setup.py sdist upload")
os.system("python setup.py bdist_wheel upload")
sys.exit()
setup(
name="pipr... | nilq/baby-python | python |
"""Module for working with transcripts, creating transcript DBs and reading from transcript DB"""
from __future__ import division
import gzip
from operator import itemgetter
import pysam
import datetime
import os
class Transcript(object):
"""Class for a single transcript"""
def __init__(self, id=None, vers... | nilq/baby-python | python |
import os
import sys
import time
import subprocess
ITERATIONS = 10
COUNT = 20000000
VERBOSE = False
NL = '\n'
INCLUDE = "../../../src"
CC = 'gcc'
CCPP = 'g++' # LoL
OPT = '-O3'
print(f'Using {CC} compiler')
def execute_command(commands):
print(' '.join(commands))
subprocess.run(commands, shell=True)
# C... | nilq/baby-python | python |
# Copyright 2011-2013 Colin Scott
# Copyright 2011-2013 Andreas Wundsam
# Copyright 2012-2013 Sam Whitlock
# Copyright 2012-2012 Kyriakos Zarifis
#
# 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 ... | nilq/baby-python | python |
# Songsheng YING
# coding=utf-8
# python3.6.7 Anaconda
import os, sys
import numpy as np
from progressbar import ProgressBar, Percentage, Bar
import xml.etree.ElementTree as ET
def data_file_reader_fr(file_name, lang):
print(" Working on " + file_name)
if lang == "French":
path = os.getcwd() + '/da... | nilq/baby-python | python |
workflow_xml_start = """<workflow-app name="etk-april-2017" xmlns="uri:oozie:workflow:0.5">
<global>
<configuration>
<property>
<name>oozie.launcher.mapreduce.map.memory.mb</name>
<value>10000</value>
</property>
</configu... | nilq/baby-python | python |
from matplotlib import pyplot as plt
from matplotlib_venn import venn3
def plot_confusion_matrix(cm, cmap=plt.cm.Blues):
"""
Args:
cm (np.ndarray): Confusion matrix to plot
cmap: Color map to be used in matplotlib's imshow
Returns:
Figure and axis on which the confusion matrix is ... | nilq/baby-python | python |
from src import network
import numpy as np
from src.study.utils import downloader
from src.study.mnist_common import mnist_reader
items = ["T-shirt/top","Trouser","Pullover","Dress","Coat","Sandal","Shirt","Sneaker","Bag","Ankle","boot"]
def download_mnist_fashion_data():
downloader.download_data("http://fashio... | nilq/baby-python | python |
import re
def modify_en_text(text, modify_mode='BASIC', keep_emoji=True):
""" Make your text easy to read and to translate.
Args:
text(str):
target dirty text.
modify_mode(str):
mode selection
keep_emoji(bool):
call back ... | nilq/baby-python | python |
from functools import reduce
testcases = int(input())
for t in range(testcases):
n = int(input())
vals = list(map(int, input().split()))
missed = 0
for i in range(1, len(vals)):
x = abs(vals[i] - vals[i - 1])
if x > 0:
x -= 1
missed += x
prin... | nilq/baby-python | python |
# Import Required Libraries
from flask import Flask, render_template, request
import pickle
# Initialise the object to run the flask app
app = Flask(__name__, static_folder='static', template_folder='templates')
# Load the pickled model file
model = pickle.load(open('model.pkl', 'rb+'))
@app.route('/', methods=['... | nilq/baby-python | python |
# Copyright 2017 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | nilq/baby-python | python |
import functools
import operator
import unittest
from migen import *
def cols(rows):
"""
>>> a = [
... [1, 2],
... ['a', 'b'],
... [4, 5],
... ]
>>> for c in cols(a):
... print(c)
[1, 'a', 4]
[2, 'b', 5]
>>> a = [
... [1, 2, 3],
... ['a', 'b', 'c'],
... ]... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
DTSA-II Script - J. R. Minter - 2016-10-12
massFractionsTheEasyWay.py
Date Who Comment
---------- --- -----------------------------------------------
2016-10-12 JRM Mass fractions the easy way...
Elapse: 0:00:00.0 ROCPW7ZC5C42
"""
import sys
sys.packageManager.makeJavaPackag... | nilq/baby-python | python |
# Import Dependencies
import numpy as np
import pandas as pd
import datetime as dt
import sqlalchemy
from sqlalchemy import desc
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect... | nilq/baby-python | python |
# Normals are for all puzzles where all 3 sides are the same
# 37 is Skewb
# 38 is Pyraminx main
# 39 is Pyraminx primary corners
# 40 is Pyraminx secondary corners
# 41 is Megaminx main
# 42 is Megaminx secondary
normals = {
2: {'moves': (('U', 'D'), ('F', 'B'), ('R', 'L')), 'directions': ('', "'", '2')},
3: {... | nilq/baby-python | python |
from setuptools import setup
setup(
name="scripture-burrito",
version="0.0.2",
description="Python library for the Scripture Burrito data interchange format",
url="http://github.com/bible-technology/scripture-burrito-python",
author="BT Tech Consortium",
author_email="jtauber@jtauber.com",
... | nilq/baby-python | python |
import pytest
import numpy as np
import pennylane as qml
from pennylane_qiskit import AerDevice, BasicAerDevice
from conftest import U, U2, A
np.random.seed(42)
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
@pytest.mark.parametrize("theta, phi", list(zip(THETA, P... | nilq/baby-python | python |
import argparse
import logging
import os
import sys
sys.path.insert(0, os.path.join(sys.path[0], ".."))
import development.configuration # pylint: disable = wrong-import-position
import development.environment # pylint: disable = wrong-import-position
logger = logging.getLogger("Main")
def main():
current_direct... | nilq/baby-python | python |
import sys
import os
import json
import hashlib
import EVMfunction as EVMf
import EVMcompiler as EVMc
import EVMparse as EVMp
print('Kam1n0 script for EVM is now running...')
print('start persisting...')
args = sys.argv
sol_file_name = args[1].split('\\')[-1]
abs_file_name = os.path.abspath(args[1])
j... | nilq/baby-python | python |
#!/usr/bin/env python3
"""Bank account without synchronization cause race condition """
class UnsyncedBankAccount:
"""Bank account without synchronization"""
balance: float
def __init__(self, balance: float = 0):
self.balance: float = balance
def deposit(self, amount: float) -> None:
... | nilq/baby-python | python |
# import setuptools
# with open("README.md", "r") as fh:
# long_description = fh.read()
# setuptools.setup(
# #Here is the module name.
# name="TOPSIS-Shivansh-101803103",
# #version of the module
# version="0.0.1",
# #Name of Author
# author="Shivansh Kumar",
# #your Email add... | nilq/baby-python | python |
from collections import defaultdict
from contextlib import contextmanager
from enum import Enum
import redis_lock
from passari_workflow.redis.connection import get_redis_connection
from rq import Queue
from rq.exceptions import NoSuchJobError
from rq.job import Job
from rq.registry import FailedJobRegistry, StartedJob... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
# # 2. Τιμές, τύποι και μεταβλητές. Συμβολοσειρές
# ## Σταθερές (Constants)
#
# H Python δεν διαθέτει προκαθορισμένες *σταθερές* όπως άλλες γλώσσες προγραμματισμού.
# Όμως κατά σύμβαση και όχι κατά κανόνα έχει συμφωνηθεί οι *σταθερές* να ονοματίζονται με κεφαλαίους χαρακτήρες.
... | nilq/baby-python | python |
import os,sys
import numpy as np
import torch
import torch.nn.functional as F
import h5py, time, itertools, datetime
from scipy.ndimage import label
from scipy.ndimage.morphology import binary_erosion
from torch_connectomics.utils.net import *
from torch_connectomics.utils.vis import visualize_aff
def test(args, test... | nilq/baby-python | python |
import ML
import function.saveNewsList
import hook.hooks
import job
import json
from nose.tools import with_setup
from ML import Server
def setup_func():
ML.init(
"57f9edc887d4a7e337b8c231",
master_key="elhmazJfd29ZTFBhR0M3SmJ0R2N6UQ",
)
@with_setup(setup_func)
def test_saveNewsDetail():
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-11 15:42
from django.db import migrations
import utilities.fields
class Migration(migrations.Migration):
dependencies = [
('dcim', '0017_rack_add_role'),
]
operations = [
migrations.AddField(
model_name='device',
... | nilq/baby-python | python |
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
import datetime
from dateutil.relativedelta import relativedelta
from datetime import datetime
from sqlalchemy import desc... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.