content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Copyright (c) 2020 PaddlePaddle 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 app... | nilq/baby-python | python |
# ----- ---- --- -- -
# Copyright 2020 The Axiom Foundation. All Rights Reserved.
#
# Licensed under the Apache License 2.0 (the "License"). You may not use
# this file except in compliance with the License. You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.apache.org/l... | nilq/baby-python | python |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.login.AvatarChooser
import math, time, os, random, sys
from pandac.PandaModules import *
from direct.gui.DirectGui import *
from... | nilq/baby-python | python |
import argparse
from pathlib import Path
def arg_parsing():
"""Command line parsing"""
parser = argparse.ArgumentParser()
parser.add_argument('--mode', '-m', type=int, default=0, help='0 - local, 1 - master, 2 - encoder')
# Input/Output/Temp
parser.add_argument('--input', '-i', nargs='+', type=Pa... | nilq/baby-python | python |
#!/usr/bin/env python
from cogent.app.parameters import FlagParameter, ValuedParameter
from cogent.app.util import CommandLineApplication, ResultPath
"""Application controller for sfffile"""
__author__ = "Kyle Bittinger"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Kyle Bittinger"]
__l... | nilq/baby-python | python |
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gtk, GtkSource
from diode.rendered_graph import RenderedGraph
from diode.abstract_sdfg import AbstractSDFG
from diode.images import ImageStore
from diode.property_renderer import PropertyRenderer, _get_edge_labe... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
class CreateFaceSetResult(object):
"""Result of create face set."""
def __init__(self, content):
self.content_origin = content
self.content_eval = eval(content.replace("true", "True").replace("false", "False"))
def get_original_result(self):
"... | nilq/baby-python | python |
"""Geometric Operations"""
from typing import Dict, List, Tuple
import shapely.affinity
from shapely.geometry import Point
from util.files import ImageLayoutModel
def shift_label_points(label_data: Dict, x: int, y: int) -> Dict:
"""
Shift all label points by x and y
:param label_data:
:param x:
... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.core import serializers
from django.contrib.auth.models import Group
from api.groups.serializers import GroupSerializer
from api import auth
def _groups_callback(key, user, user_type, id_map={}):
... | nilq/baby-python | python |
# Generated by Django 3.1.5 on 2021-02-13 04:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oxigeno', '0004_distribuidorpotencial_historicaldistribuidorpotencial'),
]
operations = [
migrations.AddField(
model_name='distr... | nilq/baby-python | python |
"""
Defaults and globals.
Note, users will have to specify their own path to the Timbre Toolbox.
"""
import os
class RealPath:
"""
Convenient way to generate absolute file-paths.
"""
def __init__(self):
self.here = os.path.dirname(__file__)
def __call__(self, relative_path):
ret... | nilq/baby-python | python |
# width:79
# height: 30
from ceefax import config
import os
from ceefax.page import PageManager
from ceefax.cupt import Screen
def is_page_file(f):
if not os.path.isfile(os.path.join(config.pages_dir, f)):
return False
if "_" in f:
return False
if "pyc" in f:
return False
retur... | nilq/baby-python | python |
import os
import pandas
import dateutil
from dfs.extdata.common.io import combine_dataframe_into_pickle_file
sbr_data_dir = os.path.join(GLOBAL_ROOT, 'db/{sport}/odds/sportsbookreview/')
# Find the odds file for a specific day
def get_gameday_filename(sport, game_day):
filename = os.path.join(sbr_data_dir.format(sp... | nilq/baby-python | python |
from os import environ
from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify
from libs.connectors import STORAGE_CONNECTOR
from libs.utils.formatter import format_v1, format_v2
from libs.utils.mockup_data import get_mockup_data
ephad_bp = Blueprint("ephad_bp", __name__)
# BLUEPRINT FU... | nilq/baby-python | python |
"""
Easing.
Move the mouse across the screen and the symbol will follow.
Between drawing each frame of the animation, the program
calculates the difference between the position of the
symbol and the cursor. If the distance is larger than
1 pixel, the symbol moves part of the distance (0.05) from its
current posi... | nilq/baby-python | python |
# SPDX-FileCopyrightText: 2019-2021 REFITT Team
# SPDX-License-Identifier: Apache-2.0
"""Data broker client integration tests."""
# internal libs
from refitt.database.model import ObjectType, Object, ObservationType, Observation, Alert
from tests.unit.test_data.test_broker.test_alert import MockAlert
from tests.unit... | nilq/baby-python | python |
# Auto-generated by generate_passthrough_modules.py - do not modify
from .v0_2.raw_nodes import *
| nilq/baby-python | python |
from sys import exit
from os import remove
import webbrowser
from operations import solution
from operations import trigerrcheck
from operations import logsolve
from operations import q
from PyQt5.QtWidgets import QApplication,QLabel,QWidget,QGridLayout,QLineEdit,QPushButton,QCheckBox,QSlider
from PyQt5 import QtGui... | nilq/baby-python | python |
_MISSING_FOREIGN_KEY_TABLE = {
"ignore_validation": 1,
"@context": ["https://schema.org", {"bh": "https://schema.brighthive.io/"}],
"@type": "bh:DataResource",
"@id": "https://mydatatrust.brighthive.io/dr1",
"name": "2020 Census Data",
"description": "Description of data resource",
"ownerOrg... | nilq/baby-python | python |
# Program 08c: The Belousov-Zhabotinski Reaction. See Figure 8.16.
# Plotting time series for a 3-dimensional ODE.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# B_Z parameters and initial conditions.
q, f, eps, delta = 3.1746e-5, 1, 0.0099, 2.4802e-5
x0, y0, z0 = 0, 0, 0.1
#... | nilq/baby-python | python |
try:
import pkg_resources
version = pkg_resources.require("cabot")[0].version
except (Exception, ImportError):
version = "unknown"
| nilq/baby-python | python |
"""
Flask Application: run this script to create website and predict endpoint.
"""
import os
from flask import Flask, request, render_template
import numpy as np
import joblib
# Initialize app and model
app = Flask(__name__)
model = joblib.load("models/linear_model.pkl")
# Get version from VERSION file
with open("VER... | nilq/baby-python | python |
import numpy as np
from scipy.spatial.distance import cdist
class KMeans:
def __init__(
self,
k: int,
metric: str = "euclidean",
tol: float = 1e-6,
max_iter: int = 100,
seed: int = 42):
"""
inputs:
k: int
... | nilq/baby-python | python |
from collections import OrderedDict
from devito.core.autotuning import autotune
from devito.cgen_utils import printmark
from devito.ir.iet import (Call, List, HaloSpot, MetaCall, FindNodes, Transformer,
filter_iterations, retrieve_iteration_tree)
from devito.ir.support import align_accesses
... | nilq/baby-python | python |
from configparser import ConfigParser
class Role:
"""The Parent Role Object"""
def __init__(self, name: str, gender: str, toa: int, team: str, night_actions, day_actions, on_attack_actions,
death_actions,
img: str,
scenario: str):
self.name = name
... | nilq/baby-python | python |
# This file is automatically generated by tools/idna-data
# vim: set fileencoding=utf-8 :
"""IDNA Mapping Table from UTS46."""
__version__ = "12.1.0"
def _seg_0():
return [
(0x0, "3"),
(0x1, "3"),
(0x2, "3"),
(0x3, "3"),
(0x4, "3"),
(0x5, "3"),
(0x6, "3")... | nilq/baby-python | python |
def read_input():
# for puzzles where each input line is an object
with open('input.txt') as fh:
for line in fh.readlines():
yield int(line.strip())
def is_sum_of_two_in(num, buf):
for i in range(len(buf)):
for j in range(i+1,len(buf)):
if num==buf[i]+buf[j]:
... | nilq/baby-python | python |
"""
Background job servicers
"""
import logging
from datetime import timedelta
from sqlalchemy.sql import func, or_
from couchers import config, email, urls
from couchers.db import session_scope
from couchers.email.dev import print_dev_email
from couchers.email.smtp import send_smtp_email
from couchers.models import... | nilq/baby-python | python |
import random
import math
from scytale.ciphers.base import Cipher
from scytale.exceptions import ScytaleError
class Fleissner(Cipher):
name = "Fleissner"
default = "XooXooooooXoXoooXoooXXoXoooooooooXoXoooXooooXoooXoXoooXXoooooooo"
def __init__(self, key=None):
self.key = self.validate(key)
... | nilq/baby-python | python |
from collections import defaultdict
from factored_reps.models.parents_net import ParentsNet
import numpy as np
import torch
import torch.nn
from markov_abstr.gridworld.models.nnutils import Network
from markov_abstr.gridworld.models.phinet import PhiNet
from markov_abstr.gridworld.models.invnet import InvNet
from mark... | nilq/baby-python | python |
import os
from typing import List
from typing import Dict
from typing import Any
from ase.build import bulk
from ase.data import atomic_numbers
from ase.data import reference_states
from ase.data import ground_state_magnetic_moments
from autocat.data.lattice_parameters import BULK_PBE_FD
from autocat.data.lattice_para... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
redis 临时状态存储接口
键:
1. 计数器 str
2. order对应关系、超时队列、成功队列 —— 字典 uuid-orderinfo
"order:"+str(goods_id)
"order:"+str(goods_id)+":"+"overtime" 超时订单
"order:"+str(goods_id)+":"+"deal" 完成的订单
改:
... | nilq/baby-python | python |
# Main network and testnet3 definitions
# AXE src/chainparams.cpp
params = {
'axe_main': {
'pubkey_address': 55, #L120
'script_address': 16, #L122
'genesis_hash': '00000c33631ca6f2f61368991ce2dc03306b5bb50bf7cede5cfbba6db38e52e6' #L110
},
'axe_test': {
'pubkey_address': 140,... | nilq/baby-python | python |
"""
Unit tests for the ESV schema package.
"""
from aura.file.esv import ESV
import unittest
import os
def _locate(filename):
"""
Find the file relative to where the test is located.
"""
return os.path.join(os.path.dirname(__file__), filename)
class ESV_test(unittest.TestCase):
"""
Unit tests... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
CCR plotting module
Kiri Choi (c) 2018
"""
import os, sys
import tellurium as te
import roadrunner
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
def plotAllProgress(listOfDistances, labels=None, SAVE_PATH=None):
"""
Plots multiple convergence progress
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# MIT License
# Copyright (c) 2021 Alexsandro Thomas
# 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
# ... | nilq/baby-python | python |
#!/usr/bin/env python
import pytest
from versionner.version import Version
class TestVersionCompare:
def test_eq(self):
v1 = Version('1.2.3')
v2 = Version('2.3.4')
v3 = Version('1.2.3')
assert v1 == v3
assert v1 != v2
assert v1 == '1.2.3'
assert v1 != '2.... | nilq/baby-python | python |
"""empty message
Revision ID: a92b018b8c85
Revises: 875879b0cbcc
Create Date: 2020-06-18 18:00:12.242034
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a92b018b8c85'
down_revision = '875879b0cbcc'
branch_labels = None
depends_on = None
def upgrade():
# ... | nilq/baby-python | python |
# Generated by Django 3.1.1 on 2020-09-13 10:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userbmi',
name='height',
fi... | nilq/baby-python | python |
import json
from logger import log
menuStore = "data/menu.json"
class MenuBot():
status = "Empty"
menu = dict()
def getStatus(self):
return self.status
def saveMenu(self):
with open( menuStore, 'w' ) as outfile:
jstr = json.dumps( self.menu )
outfile.write(jst... | nilq/baby-python | python |
#!/usr/bin/env python
## -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 ... | nilq/baby-python | python |
"""empty message
Revision ID: 3b84fe4459c9
Revises: 0149ad5e844c
Create Date: 2021-05-08 13:32:44.910084
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '3b84fe4459c9'
down_revision = '0149ad5e844c'
branch_labels = None
depe... | nilq/baby-python | python |
from rest_framework.generics import RetrieveUpdateAPIView
from rest_framework.permissions import *
from rest_framework.request import Request
from rest_framework.schemas.openapi import AutoSchema
from user.permissons import IsAdminUserOrReadOnly
from .models import SiteConfiguration
from .serializers import SiteConfig... | nilq/baby-python | python |
import copy
from django.test import override_settings
from rest_framework.test import APIClient
from users.models import User
from saef.models import DatasetSession
from saefportal.settings import MSG_ERROR_INVALID_INPUT, MSG_ERROR_REQUIRED_INPUT, MSG_ERROR_MISSING_OBJECT_INPUT, \
MSG_ERROR_EXISTING
from utils.tes... | nilq/baby-python | python |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
for i in range(1, 11):
m = n*i
print('{} x {} = {}'.format(n, i, m))
| nilq/baby-python | python |
def generate_explanation_text(concept_qid,defining_formula,
identifier_properties,identifier_values,):
#url = "https://www.wikidata.org/wiki/" + concept_qid
url = "www.wikidata.org/wiki/" + concept_qid
# insert values
symbol_value_unit = {}
try:
for idx in ran... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
This is an bayes module.
It seems that it has to have THIS docstring with a summary line, a blank line
and sume more text like here. Wow.
"""
from loguru import logger
from system.other import TARANTOOL_CONN
import sys
import mailparser
from datetime import datetime... | nilq/baby-python | python |
# 002 找出檔案內6 & 11 的公倍數
f = open("input.txt", mode='r')
for line in f.readlines():
num = int(line)
if(num % 6 == 0 and num % 11 == 0):
print(num)
f.close()
| nilq/baby-python | python |
#!/bin/python3
# answer to this question:
# https://www.hackerrank.com/challenges/python-time-delta/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
from datetime import datetime as dtf #date time functionalities
# why import datetime from datetime?:
# datetime module has datetime class so datetime.date... | nilq/baby-python | python |
from asset_manager.data.schemas.developer import DeveloperMongo
from pymongo.database import Database
from asset_manager.data.repos.base import MongoRepository
class DeveloperRepository(MongoRepository[DeveloperMongo]):
def __init__(self, db: Database):
super().__init__(db, "developers", DeveloperMongo)
| nilq/baby-python | python |
#!/usr/bin/env python
#! coding:utf8
import sys
import numpy as np
# approximation valid for
# 0 degrees Celsius < T < 60 degrees Celcius
# 1% < RH < 100%
# 0 degrees Celcius < Td < 50 degrees Celcius
# constants
a = 17.271
b = 237.7 # in units of degrees Celcius
def dewpoint_approximation(T,RH):
"""
PURP... | nilq/baby-python | python |
from flask import render_template, url_for, flash, redirect, request
from todo_project import app, db, bcrypt
# Import the forms
from todo_project.forms import (LoginForm, RegistrationForm, UpdateUserInfoForm,
UpdateUserPassword, TaskForm, UpdateTaskForm)
# Import the Models
from tod... | nilq/baby-python | python |
"""
Intent
-------
Define an interface for creating an object, but let subclasses decide which class to
instantiate. Factory Method lets a class defer instantiation to subclasses.
People often use Factory Method as the standard way to create objects; but it isn't
necessary if: the class that's instantiated never chang... | nilq/baby-python | python |
#! python
# coding:utf-8
"""API の Undo/Redo 用プラグイン"""
import sys
import maya.api.OpenMaya as om
# コマンド名
kPluginCmdName = "nnSnapshotState"
def maya_useNewAPI():
"""プラグインが API2.0 ベースであることの明示"""
pass
class NnSnapshotState(om.MPxCommand):
"""コマンドクラス"""
def __init__(self):
om.MPxCommand.__ini... | nilq/baby-python | python |
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import Perceptron
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from skl... | nilq/baby-python | python |
# Written by Bram Cohen
# see LICENSE.txt for license information
#
# $Id: btformats.py 68 2006-04-26 20:14:35Z sgrayban $
#
from types import StringType, LongType, IntType, ListType, DictType
from re import compile
reg = compile(r'^[^/\\.~][^/\\]*$')
ints = (LongType, IntType)
def check_info(info):
if type(inf... | nilq/baby-python | python |
from .net import BayesNet
from .vertex.base import Vertex
from typing import Any, Mapping
class Model:
def __init__(self, vertices: Mapping[str, Vertex] = {}) -> None:
self.__dict__["_vertices"] = {}
self.__dict__["_vertices"].update(vertices)
def to_bayes_net(self) -> BayesNet:
retu... | nilq/baby-python | python |
import h5py
import numpy as np
from versioned_hdf5.replay import (modify_metadata, delete_version,
delete_versions, _recreate_raw_data,
_recreate_hashtable,
_recreate_virtual_dataset)
from versioned_hdf5.hashtable ... | nilq/baby-python | python |
import copy
from geometry_utils.three_d.point3 import is_point3
from geometry_utils.two_d.path2 import Path2
from geometry_utils.three_d.path3 import is_path3
from geometry_utils.two_d.edge2 import Edge2
from geometry_utils.two_d.point2 import Point2, is_point2
class PathFieldInterpreter(Path2, object):
# Symbol... | nilq/baby-python | python |
################################
# OpenCTI Backup Files #
################################
import os
import yaml
import json
from pycti import OpenCTIConnectorHelper, get_config_variable
class BackupFilesConnector:
def __init__(self):
config_file_path = os.path.dirname(os.path.abspath(__file__))... | nilq/baby-python | python |
# import asyncio
import streamlit as st
from constants import *
from utils import get_client
st.title('News Nuggets 📰')
st.sidebar.title("News App preferences! 📝")
country_choice = st.sidebar.selectbox("Country 🎌:", options=countries,
index=5,
... | nilq/baby-python | python |
# SPDX-License-Identifier: BSD-3-Clause
import argparse
import json
import logging
import os.path
import sys
from operator_manifest.operator import ImageName, OperatorManifest
from operator_manifest.resolver import resolve_image_reference
logger = logging.getLogger(__name__)
DEFAULT_OUTPUT_EXTRACT = 'references.js... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: george wang
@datetime: 2019-07-09
@file: clock.py
@contact: georgewang1994@163.com
@desc: 定期处理任务
"""
import datetime
import logging
import threading
import time
logger = logging.getLogger(__name__)
class Schedule(threading.Thread):
"""
... | nilq/baby-python | python |
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from huxley.api.tests import (CreateAPITestCase, DestroyAPITestCase,
ListAPITestCase, PartialUpdateAPITestCase,
... | nilq/baby-python | python |
"""Test run."""
import logging
import re
from pathlib import Path
from types import ModuleType
from unittest.mock import patch
import pytest
from tests.conftest import import_module
_LOGGER = logging.getLogger(__name__)
@pytest.fixture
def run() -> ModuleType:
"""Import the run module."""
runmod = import_m... | nilq/baby-python | python |
import gdspy
import pp
from pp.compare_cells import hash_cells
from pp.components.mzi2x2 import mzi2x2
def debug():
c = mzi2x2()
h0 = c.hash_geometry()
gdspath1 = "{}.gds".format(c.name)
gdspath2 = "{}_2.gds".format(c.name)
gdspath3 = "{}_3.gds".format(c.name)
pp.write_gds(c, gdspath1)
... | nilq/baby-python | python |
from machin.frame.buffers import DistributedPrioritizedBuffer
from test.util_run_multi import *
from test.util_platforms import linux_only_forall
import random
import torch as t
import numpy as np
linux_only_forall()
class TestDistributedPrioritizedBuffer:
BUFFER_SIZE = 1
SAMPLE_BUFFER_SIZE = 10
#####... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Ed Mountjoy
#
# //genetics-portal-raw/uk_biobank_sumstats/neale_v2/raw/135.gwas.imputed_v3.both_sexes.tsv.bgz
import subprocess as sp
import os
import sys
def main():
# Args
in_pheno='manifest/phenotypes.both_sexes.filtered.tsv'
# Iterare over manifest
... | nilq/baby-python | python |
"""
implement a shuffleNet by pytorch
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import time
dtype = torch.FloatTensor
from collections import OrderedDict
from .ShapeSpec import ShapeSpec
def shuffle_channels(x, groups):
"""shuffle channels of a 4-D... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import jmodt.ops.pointnet2.pytorch_utils as pt_utils
from jmodt.config import cfg
from jmodt.detection.layers.proposal_target_layer import ProposalTargetLayer
from jmodt.ops.pointnet2.pointnet2_modules import PointnetSAModule
from jmodt.utils import lo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
助手函数
'''
__author__ = 'alex'
import os
from pathlib import Path
def find_all_file_by_path(suffix='', path=''):
'''
查找出指定目录下指定文件后缀的所有文件
:param suffix: 文件名后缀
:param path: 指定目录,当不指定目录时,则默认为当前目录
:return: 所有指定后缀文件列表
'''
if not suffix: return []
if (not bool(pa... | nilq/baby-python | python |
# 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.
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'file',
'depot_tools/gsutil',
'recipe_engine/context',
'recipe_engine/path',
'recipe_... | nilq/baby-python | python |
# encoding: utf-8
from sdsstools import get_config, get_logger, get_package_version
# pip package name
NAME = 'sdss-tron-lite'
# Loads config. config name is the package name.
config = get_config('tron_lite')
log = get_logger(NAME)
__version__ = get_package_version(path=__file__, package_name=NAME)
| nilq/baby-python | python |
from clang.cindex import Index
from .sample import Sample
from .context import Context
from .path import Path
from .ast_utils import ast_to_graph, is_function, is_class, is_operator_token, is_namespace, make_ast_err_message
from networkx.algorithms import shortest_path
from networkx.drawing.nx_agraph import to_agraph
f... | nilq/baby-python | python |
import onnx
from onnxruntime.quantize import quantize, QuantizationMode
# Load the onnx model
model = onnx.load('/home/lh/pretrain-models/pose_higher_hrnet_256_sim.onnx')
# Quantize
quantized_model = quantize(model, quantization_mode=QuantizationMode.IntegerOps)
# Save the quantized model
onnx.save(quantized_m... | nilq/baby-python | python |
# Copyright Fortior Blockchain, LLLP 2021
# Open Source under Apache License
from flask import Flask, request, render_template, redirect, url_for
from flask_sock import Sock
from algosdk import account, encoding, mnemonic
from vote import election_voting, hashing, count_votes
from algosdk.future.transaction imp... | nilq/baby-python | python |
"""
TODO: Shal check that all the needed packages are available before running the program
""" | nilq/baby-python | python |
import os
import time
import logging
from sarpy.io.nitf.nitf_head import NITFDetails
from sarpy.io.nitf.image import ImageSegmentHeader
from sarpy.io.nitf.des import DataExtensionHeader
from . import unittest
def generic_nitf_header_test(instance, test_file):
assert isinstance(instance, unittest.TestCase)
... | nilq/baby-python | python |
# Copyright 2020 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.
"""Presubmit tests for ProductionSupportedFlagList.java
"""
import os
import sys
def _SetupImportPath(input_api):
android_webview_common_dir = input_api.P... | nilq/baby-python | python |
"""This is the stock insertion generator"""
import numpy as np
import mitty.lib
import mitty.lib.util as mutil
from mitty.plugins.variants import scale_probability_and_validate
import logging
logger = logging.getLogger(__name__)
__example_param_text = """
{
"p": 0.01, # Per-base probability of having an ins... | nilq/baby-python | python |
#! /usr/bin/python
#coding: utf-8
fields = {}
fields["brand"] = (
[
#BrandId #BrandType #BE_ID #BE_CODE
[380043552, 0, 103, '103']
])
fields["BrandTypes"] = (
[
#name #offset
["pps", 0],
["lca", 1],
["mctu", 2],
... | nilq/baby-python | python |
import logging
from django.core.management import BaseCommand
from django.core.management import call_command
class Command(BaseCommand):
help = 'This command invoke all the importing data command'
def handle(self, *args, **options):
logger = logging.getLogger(__name__)
try:
call... | nilq/baby-python | python |
"""Preprocess"""
import numpy as np
from scipy.sparse import (
csr_matrix,
)
from sklearn.utils import sparsefuncs
from skmisc.loess import loess
def select_variable_genes(adata,
layer='raw',
span=0.3,
n_top_genes=2000,
... | nilq/baby-python | python |
import asyncio
import pandas as pd # type:ignore
from PoEQuery import account_name, league_id, realm
from PoEQuery.official_api_async import stash_tab
from PoEQuery.stash_tab_result import StashTabResult
STASH_URL = "https://www.pathofexile.com/character-window/get-stash-items"
def get_tab_overview():
params =... | nilq/baby-python | python |
import aws_cdk as cdk
import constants
from deployment import UserManagementBackend
from toolchain import Toolchain
app = cdk.App()
# Development stage
UserManagementBackend(
app,
f"{constants.APP_NAME}-Dev",
env=constants.DEV_ENV,
api_lambda_reserved_concurrency=constants.DEV_API_LAMBDA_RESERVED_CON... | nilq/baby-python | python |
import os
from psycopg2 import connect
def connect_to_db(config=None):
db_name = os.getenv("DATABASE_URL")
conn = connect(db_name)
conn.set_session(autocommit=True)
return conn
def create_users_table(cur):
cur.execute(
"""CREATE TABLE IF NOT EXISTS politico.user (
id SERIAL NOT... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
# Copyright 2015 - Alcatel-Lucent
# Copyright © 2014-2015 eNovance
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
#
# Licensed under the Apache License, Version 2.0 (the... | nilq/baby-python | python |
# Copyright 2016 Chr. Hansen A/S and The Novo Nordisk Foundation Center for Biosustainability, DTU.
# 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.... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
"""
Created on Sun Sep 13 15:45:26 2020
@author: samuel
"""
import numpy as np
import pandas as pd
df = pd.read_csv(
'/home/samuel/Bureau/zip.train', sep=" ", header=None)
digits = df.to_numpy()
classes = digits[:, 0]
digits = digits[:, 1:-1]
# %%
bdd = []
X = ... | nilq/baby-python | python |
# -*- python -*-
import os
import crochet
from twisted.application.internet import StreamServerEndpointService
from twisted.application import service
from twisted.internet import reactor, endpoints
from twisted.web.wsgi import WSGIResource
import weasyl.polecat
import weasyl.wsgi
import weasyl.define as d
from libwe... | nilq/baby-python | python |
# -*- coding: utf8 -*-
from datetime import date
from nba.model.utils import oddsshark_team_id_lookup
from sqlalchemy import Column, Date, Float, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
NOP_TO_NOH_DATE = date(2013, 10, 29)
CH... | nilq/baby-python | python |
"""
Quick and dirty MQTT door sensor
"""
import time
import network
import ubinascii
import machine
from umqttsimple import MQTTClient
import esp
import adcmode
try:
import secrets
except:
import secrets_sample as secrets
try:
### Create wifi network
sta_if = network.WLAN(network.STA_IF)
sta_... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
def test_invoked_commands_still_work_even_though_they_are_no_customizable(lib, pythondir):
# given a command that is calling another using ctx.invoke
(pythondir / 'mygroup.py').write_text("""
import click
from clk.decorators import group, flag
@group(... | nilq/baby-python | python |
from unittest import TestCase
import pytest
import torch
import pyro
import pyro.infer
from pyro.distributions import Bernoulli, Normal
from pyro.infer import EmpiricalMarginal
from tests.common import assert_equal
class HMMSamplingTestCase(TestCase):
def setUp(self):
# simple Gaussian-emission HMM
... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Setup script for fio-buffer
"""
import os
from setuptools import setup
from setuptools import find_packages
with open('README.rst') as f:
readme = f.read().strip()
version = None
author = None
email = None
source = None
with open(os.path.join('fio_buffer', '__init__.py')) as f:
... | nilq/baby-python | python |
# from http://www.calazan.com/a-simple-python-script-for-backing-up-a-postgresql-database-and-uploading-it-to-amazon-s3/
import os
import sys
import subprocess
from optparse import OptionParser
from datetime import date, datetime, timedelta
import boto
from boto.s3.key import Key
# Amazon S3 settings.
AWS_ACCESS_KEY... | nilq/baby-python | python |
"""
Для поступления в вуз абитуриент должен предъявить результаты трех экзаменов в виде ЕГЭ, каждый из них оценивается
целым числом от 0 до 100 баллов. При этом абитуриенты, набравшие менее 40 баллов (неудовлетворительную оценку) по
любому экзамену из конкурса выбывают. Остальные абитуриенты участвуют в конкурсе по сум... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from discord.ext.commands import context
import settings
class GeneralContext(context.Context):
"""Expanded version of the Discord Context class.
This class can be used outside of command functions, such as
inside event handlers. It needs to be created manually.
... | nilq/baby-python | python |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.