content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from typing import Any __all__ = ["AttrDict"] class AttrDict(dict): """ Wrapper of dict class, to allow usage of attribute notation (instance.key) in place of index notation (instance["key"]). Can be used as a mixin for Mappings. """ def __getattr__(self, item: str) -> Any: if item ...
nilq/baby-python
python
from django.conf.urls import url from zebra import views urlpatterns = [ url(r'webhooks/$', views.webhooks, name='webhooks'), url(r'webhooks/v2/$', views.webhooks_v2, name='webhooks_v2'), ]
nilq/baby-python
python
# Copyright 2019 Huawei Technologies Co., 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 pandas as pd import time #------------------------------------ #loading dataset begin = time.time() df = pd.read_csv("adult.data" , names=["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-w...
nilq/baby-python
python
#Author: Zhicheng Zhu #Email: zhicheng.zhu@ttu.edu, yisha.xiang@ttu.edu #copyright @ 2018: Zhicheng Zhu. All right reserved. #Info: #main file to solve multi-stage DEF of CBM model by using linearization and solver # #Last update: 10/18/2018 #!/usr/bin/python from __future__ import print_function import sys import cp...
nilq/baby-python
python
""" ██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ ██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝ ██║ ██║██████╔╝███████║█████╗ ╚████╔╝ ██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝ ╚██████╗██║██║ ██║ ██║███████╗ ██║ © Brandon Skerritt Github: brandonskerritt """ from copy import copy from distutils import util f...
nilq/baby-python
python
from django.contrib import admin from .models import Coach, Comment class CoachAdmin(admin.ModelAdmin): list_display = ( 'id', 'first_name', 'last_name', 'email', 'phone_number', 'image', ) ordering = ('first_name',) class CommentAdmin(admin.ModelAdmin): ...
nilq/baby-python
python
# Generated by Django 3.0 on 2020-12-03 14:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('manager', '0001_initial'), ] operations = [ migrations.AlterField( model_name='activity', name='amount', f...
nilq/baby-python
python
from enum import Enum, IntEnum from pathlib import Path from typing import List, Literal, Optional, Union from pydantic import BaseModel import tomlkit # type: ignore (no stub) from .iec_62056_protocol.obis_data_set import ( ObisFloatDataSet, ObisId, ObisIntegerDataSet, ObisStringDataSet, ) def loa...
nilq/baby-python
python
from telegram.ext import Dispatcher,CommandHandler,CallbackQueryHandler from telegram import InlineKeyboardMarkup,InlineKeyboardButton, BotCommand import random def whoAreYou(update,context): msg = [ """You can call me Operation Lune 9000, I'm actually just a random reply AI(not really)""", """Bro,...
nilq/baby-python
python
import datetime, pytz from dateutil.tz import tzlocal log_dir = None verbose = False def log(message): ts = pytz.utc.localize(datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] if verbose: print(f'{ts} {message}') if log_dir is not None: print(f'{ts} {message}', file=open(log_d...
nilq/baby-python
python
from WMCore.WMException import WMException class WMSpecFactoryException(WMException): """ _WMSpecFactoryException_ This exception will be raised by validation functions if the code fails validation. It will then be changed into a proper HTTPError in the ReqMgr, with the message you enter used...
nilq/baby-python
python
#! python3 from __future__ import print_function import SimpleITK as sitk import numpy as np import sys import os # def LocalFusionWithLocalSimilarity(targetImage, registeredAtlases, outputPath, debug): """" Fuses the labels from a set of registered atlases using local similarity metrics. Arguments: ...
nilq/baby-python
python
def create_adjacency_list(num_nodes, edges): graph = [set() for _ in range(num_nodes)] for index, edge in enumerate(edges): v_1, v_2 = edge[0], edge[1] graph[v_1].add(v_2) graph[v_2].add(v_1) return graph
nilq/baby-python
python
""" Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk 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
import glob import pandas as pd from pathlib import Path import re import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.patches as patches import os def transformCordinates(coordinates, wmax, hmax): maxis = coordinates[0] minaxis = coordinates[1] angle = c...
nilq/baby-python
python
""" Setup to install the 'factorymind' Python package """ import os from setuptools import find_packages, setup def read(file_name: str): """Utility function to read the README file. Used for the long_description. It's nice, because now 1) we have a top level README file and 2) it's easier...
nilq/baby-python
python
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-list-negativeInteger-enumeration-1-NS" class NistschemaSvIvListNegativeIntegerEnumeration1Type(Enum): VALUE_17702143_68213_73070785813457_55650_85440493680_6799621_74925_12_725375920010560...
nilq/baby-python
python
""" The go starter template. Author: Tom Fleet Created: 24/06/2021 """ import shutil import subprocess from pathlib import Path from typing import List, Optional from pytoil.exceptions import GoNotInstalledError from pytoil.starters.base import BaseStarter class GoStarter(BaseStarter): """ The go starter ...
nilq/baby-python
python
# Generated by Django 3.0.7 on 2020-10-30 16:41 from django.db import migrations import inclusive_django_range_fields.fields class Migration(migrations.Migration): dependencies = [ ('jobsapp', '0011_auto_20201030_1636'), ] operations = [ migrations.AddField( model_name='job'...
nilq/baby-python
python
from operator import eq, ge from functools import partial import pandas as pd from microsetta_public_api.resources import resources ops = { 'equal': eq, 'greater_or_equal': ge, } conditions = { "AND": partial(pd.DataFrame.all, axis=1), "OR": partial(pd.DataFrame.any, axis=1) } def _is_rule(node): ...
nilq/baby-python
python
# Copyright (C) 2019 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
nilq/baby-python
python
from unittest.mock import patch import pytest from telegram.ext import CommandHandler from autonomia.features import dublin_bike @pytest.mark.vcr def test_cmd_dublin_bike(update, context): with patch.object(update.message, "reply_text") as m: context.args = ["89"] dublin_bike.cmd_dublin_bike(upd...
nilq/baby-python
python
# All content Copyright (C) 2018 Genomics plc from wecall.bamutils.read_sequence import HIGH_QUALITY from wecall.bamutils.sequence_builder import sequence_builder class SequenceBank(object): """ A container to hold annotated DNA sequences in relation to a reference sequence. """ def __init__(self, re...
nilq/baby-python
python
# # PySNMP MIB module ZHONE-GEN-INTERFACE-CONFIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-GEN-INTERFACE-CONFIG-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:47:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
nilq/baby-python
python
from typing import Any from rpg.items import Equippable class Armor(Equippable): config_filename = "armor.yaml" __slots__ = ("type",) def __init__(self, **kwargs: Any): self.type: str = kwargs.pop("type") super().__init__(**kwargs) def __repr__(self) -> str: return f"<{sel...
nilq/baby-python
python
from .dual_network import DualNetBounds, robust_loss, robust_loss_parallel, DualNetwork from .dual_layers import DualLinear, DualReLU from .dual_inputs import select_input, InfBallBoxBounds from .utils import DenseSequential, Dense, epsilon_from_model
nilq/baby-python
python
import a1 #$ use=moduleImport("a1") x = a1.blah1 #$ use=moduleImport("a1").getMember("blah1") import a2 as m2 #$ use=moduleImport("a2") x2 = m2.blah2 #$ use=moduleImport("a2").getMember("blah2") import a3.b3 as m3 #$ use=moduleImport("a3").getMember("b3") x3 = m3.blah3 #$ use=moduleImport("a3").getMember("b3").ge...
nilq/baby-python
python
from .users import * # importamos todas las clases del archivo circle.
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2014 Red Hat, 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 l...
nilq/baby-python
python
# Copyright (c) OpenMMLab. All rights reserved. import copy import warnings from typing import Dict, Iterable, Optional import torch import torch.nn as nn from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, ...
nilq/baby-python
python
import argparse import gym from gym import wrappers import os.path as osp import random import numpy as np import tensorflow as tf import tensorflow.contrib.layers as layers import dqn from dqn_utils import * from atari_wrappers import * def cartpole_model(img_in, num_actions, scope, reuse=False): # as described...
nilq/baby-python
python
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
nilq/baby-python
python
# %% consumer_key = "idBfc3mYzrfBPxRM1z5AhXxAA" consumer_secret = "K50925I1FObqf6LA8MwiUyCBWlOxtrXXpi0aUAFD0wNCFBPQ3j" access_token = "1245495541330579457-6EBT7O9j98LgAt3dXxzsTK5FFAA2Lg" access_secret = "jUP2N1nHeC6nzD30F4forjx7WxoOI603b4CqHdUnA6wqL" # %% import tweepy auth = tweepy.OAuthHandler(consumer_key, consu...
nilq/baby-python
python
""" Copyright 2011 Lars Kruse <devel@sumpfralle.de> This file is part of PyCAM. PyCAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PyCA...
nilq/baby-python
python
# SPDX-License-Identifier: BSD-3-Clause # Depthcharge: <https://github.com/nccgroup/depthcharge> """ U-Boot environment variable parsing and handling functionality """ import copy import os import re from zlib import crc32 from .. import log from ..arch import Architecture # This is a bit bonkers because U-Boot le...
nilq/baby-python
python
# Function to add looted inventory to player inventory def addToInventory(inventory, addedItems): for loot in addedItems: if loot in inventory: inventory[loot] = inventory[loot] + 1 else: inventory.setdefault(loot, 1) return inventory # Function to display inventory def ...
nilq/baby-python
python
import requests url = 'https://images-api.nasa.gov/search?q=Ilan%20Ramon' image_metadata_url= 'https://images-assets.nasa.gov/image/{0}/metadata.json' #KSC-03pd2975/metadata.json' # params = dict( # origin='Chicago,IL', # destination='Los+Angeles,CA', # waypoints='Joplin,MO|Oklahoma+City,OK', # sensor...
nilq/baby-python
python
import multiprocessing import os from argparse import ArgumentParser from pathlib import Path import torch from nflows import distributions, transforms from pyprojroot import here from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.loggers import WandbLogger from torch.utils.data import DataL...
nilq/baby-python
python
# Generated by Django 2.2.5 on 2019-09-07 04:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bhs', '0002_group_pos'), ] operations = [ migrations.AlterField( model_name='group', name='chapters', fi...
nilq/baby-python
python
# Authors: # Loic Gouarin <loic.gouarin@polytechnique.edu> # Benjamin Graille <benjamin.graille@universite-paris-saclay.fr> # Thibaut Van Hoof <thibaut.vanhoof@cenaero.be> # # License: BSD 3 clause from .model import ModelWidget from .test_case import TestCaseWidget from .lb_scheme import LBSchemeWidget fr...
nilq/baby-python
python
""" Пул воркеров. Полное управление и контроль воркерами. """ import logging import threading from functools import partial from multiprocessing import Pool, cpu_count, Queue, Process logger = logging.getLogger(__name__) class Worker(Process): """ Свой процесс. Тут мы вызываем команду. """ def __i...
nilq/baby-python
python
import sys import tempfile from textwrap import dedent import _pytest import pytest import yaml from mock import Mock from mock import patch from tavern.core import run from tavern.schemas.extensions import validate_file_spec from tavern.testutils.helpers import validate_pykwalify from tavern.testutils.helpers import...
nilq/baby-python
python
import copy import os import json from hpbandster.core.base_iteration import Datum class Run(object): """ Not a proper class, more a 'struct' to bundle important information about a particular run """ def __init__(self, config_id, budget, loss, info, time_stamps, error_logs): self.config_id = config_id s...
nilq/baby-python
python
userColors = []
nilq/baby-python
python
class AbstractRequest(object): opcode = -1 class AbstractRequestCodec(object): @staticmethod def decode(payload): raise NotImplementedError @staticmethod def encode(request): raise NotImplementedError
nilq/baby-python
python
import cairo import math import random import sys import os sys.path.append(os.path.abspath('..')) from lib import palettes from lib import colors # Final image dimensions IMG_HEIGHT = 2000 IMG_WIDTH = int(IMG_HEIGHT * (16/9)) SPACING = 2 def line(ctx, y, line_interval, color, x_increment=(IMG_WIDTH // 40)): li...
nilq/baby-python
python
from typing import Callable, Sequence, Union, TYPE_CHECKING import io from enum import Enum if TYPE_CHECKING: from .expressions import ( ReadSubstitute, WriteSubstitute, ) from .arguments import UncompiledArgument PublicArgument = Union[ str, int, float, 'ReadSubstitute',...
nilq/baby-python
python
from main.game.ConvertStringArray import historyToArray from main.game.verifyCheck import verificarCheck def especialMove(allpieces,piece,history): history = historyToArray(history) if history != ['']: if piece[0] == 'p': return EnPassant(piece,history) elif piece[0] == 'k': ...
nilq/baby-python
python
eps = 10e-7
nilq/baby-python
python
from ..geometry import np import math class Quaternion(object): def __init__(self, coeffs=[0., 0., 0., 1.]): self._coeffs = np.array(coeffs) def vec(self): return self._coeffs[0:3] def coeffs(self): return self._coeffs def normalize(self): norm = np.linalg.norm(self....
nilq/baby-python
python
from django.http import HttpResponse from django.shortcuts import render from webcam_manager import * import time webcam_manager = WebcamManager() encryption_manager = EncryptionManager() webcam_manager.start() def make_aes_response(response_data): response = encryption_manager.get_aes_packet(response_data) ...
nilq/baby-python
python
import json import numpy as np import os from env_rl import EnvRL from pathlib import Path def score_rl_solution(submission_filepath='example_output_rl.json', final_submission=False): base_path = Path(__file__).parent.absolute() test_data_instance_path = base_path.joinpath('data/valid/instances') test_dat...
nilq/baby-python
python
# Reference: https://leetcode.com/problems/number-of-islands/ # Approach: # 1. Get a list of all locations that have 1 # 2. Iterate through this list and call DFS for every unmarked / unvisited 1 and mark all it's reachable locations with the current_island_count # 3. The final value of current_island_count is the ans...
nilq/baby-python
python
from socket import *
nilq/baby-python
python
from __future__ import unicode_literals import frappe import json from toolz.curried import compose, merge, map, filter @frappe.whitelist() def query(doctype, txt, searchfield, start, page_len, filters): station = filters.get("station") cond = ( " OR ".join( [ "so.initial_s...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE.txt file in the root directory of this source tree. import argparse import json import os import os.path import random from typing import...
nilq/baby-python
python
__author__ = 'rogerjiang' ''' Purpose: 1. Data augmentation, including: 1.1 random translation in horizontal and vertical directions 1.2 horizontal and vertical flipping 1.3 random rotation ''' ''' Class blancing: Each class is trained using a different model, weights should be applied to the tr...
nilq/baby-python
python
# Tests should generate (and then clean up) any files they need for testing. No # binary files should be included in the repository. import json import event_model from suitcase.mongo_embedded import Serializer import pytest def test_export(db_factory, example_data): """ Test suitcase-mongo-embedded serialize...
nilq/baby-python
python
#!/usr/bin/env python import json import os import logging from ruv_dl.constants import CACHE_LOCATION, CACHE_VERSION, CACHE_VERSION_KEY logger = logging.getLogger(__name__) class CacheVersionException(Exception): pass class DiskCache: def __init__(self, program_id): self.location = os.path.join(C...
nilq/baby-python
python
import socket, time, signal def resolves(domain, timeout): try: socket.gethostbyname(domain) return True except socket.gaierror: return False
nilq/baby-python
python
from __future__ import annotations from typing import Union, List, Set, FrozenSet, Optional, Dict, IO, Callable from pathlib import Path from gd2c.project import Project from gd2c.target import Target from gd2c.gdscriptclass import GDScriptClass, GDScriptFunction, GDScriptMember, GDScriptGlobal from gd2c.targets._gdnat...
nilq/baby-python
python
from django import template from django.conf import settings from django.urls import reverse from django.utils.html import format_html from django_gravatar.helpers import get_gravatar_url register = template.Library() @register.simple_tag def user_link(user): gravatar_url = get_gravatar_url(user.email, size=16) ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Test of the non-stationary poisson process sampling func. """ import numpy as np import simpy from forecast_ed.sampling import nspp fname = 'data/arrivals.csv' data = np.genfromtxt(fname, delimiter=',', skip_header=1) arrivals = [] def generate(env): a = nspp(d...
nilq/baby-python
python
from dotenv import load_dotenv import os import requests load_dotenv() import json API_URL=os.getenv("shopify_product_url") url=API_URL+'?limit=250' products=[] headers={'Content-Type': 'application/json'} r=requests.get(url,headers=headers) products=products+r.json()['products'] header_link=r.headers['Link'] header_...
nilq/baby-python
python
from .base_state import * from .channel_state import * from .emoji_state import * from .guild_state import * from .message_state import * from .role_state import * from .user_state import *
nilq/baby-python
python
from django.urls import re_path from .views import SettingsView, UpdateSettingsView app_name = "baserow.api.settings" urlpatterns = [ re_path(r"^update/$", UpdateSettingsView.as_view(), name="update"), re_path(r"^$", SettingsView.as_view(), name="get"), ]
nilq/baby-python
python
# coding: utf-8 """Test device 1.""" from . import release from .TestDevice1 import TestDevice1 from .TestDevice2 import TestDevice2 __version__ = release.__version__ __version_info__ = release.__version_info__
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import threading import sys import time from filesocket import filesocket '''path to temporary directory used for file sockets''' SOCKSER_DIR ='' '''SOCKS5 RFC described connection methods''' CONNECT = 1 BIND = 2 UDP_ASSOCIATE = 3 '''SOCKS5 RFC described...
nilq/baby-python
python
from django.urls import path from . import views urlpatterns = [ path('friendrequest', views.send_friend_request, name="send_friend_request"), path('friendrequest/handle', views.handle_friend_request, name="handle_friend_request"), path('friendrequest/<slug:author_id>/', views.retrieve_fri...
nilq/baby-python
python
import itertools import sys import os from rdkit import Chem from rdkit.Chem import rdMolTransforms, rdMolAlign import openbabel from qmconftool import QMMol def find_dihedral_idx(mol,smarts_patt): patt_mol = Chem.MolFromSmarts(smarts_patt) matches = mol.GetSubstructMatches(patt_mol) unique_match...
nilq/baby-python
python
"""Root of podpointclient"""
nilq/baby-python
python
import unittest from cpuinfo import * import helpers class MockDataSource_enforcing(object): @staticmethod def has_sestatus(): return True @staticmethod def sestatus_b(): returncode = 0 output = r''' SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root dire...
nilq/baby-python
python
from .context_processors import * from .middleware import * from .templatetags import * from .http_client import *
nilq/baby-python
python
import datetime as dt from pathlib import Path import uuid from typing import Dict, Any, List, Callable import numpy as np import pandas as pd Row = Dict[str, Any] def generate_timestamp(color: str) -> str: if color == "red": weights = np.ones(12) else: weights = np.concatenate([np.ones(9)...
nilq/baby-python
python
from flask import current_app, g from werkzeug.local import LocalProxy from flask_pymongo import PyMongo import shortuuid def get_db(): """ Configuration method to return db instance """ db = getattr(g, "_database", None) if db is None: db = g._database = PyMongo(current_app).db return...
nilq/baby-python
python
import gi gi.require_version('Gst', '1.0') from gi.repository import Gst import math from abc import ABC, abstractmethod MAX_BUFFERS = 100 class VideoFrame: def __init__(self, width, height, data=None): self.width = width self.height = height if data is None: self.data = b'\x...
nilq/baby-python
python
import json import os import re from pyaofit import * class campaignfile(campaign): @classmethod def openFile(cls, campaign_filename): with open(campaign_filename) as campaign_file: campaign_dict = json.load(campaign_file) campaign_name = os.path.splitext(os.path.basename(campaign_filename))[0] campaign_pr...
nilq/baby-python
python
from django import forms from accounts.models import Profile class ProfileForm(forms.ModelForm): profile_picture = forms.ImageField(required=False, \ error_messages ={'invalid':("Image files only")},\ widget=forms.FileInput) class Meta: model = Profile fields = ['profile_picture','...
nilq/baby-python
python
# coding: utf-8 from django.db import models, transaction from django.utils.translation import ugettext as _ from grappelli.fields import PositionField ITEM_CATEGORY_CHOICES = ( ('1', _('internal')), ('2', _('external')), ) class Navigation(models.Model): """ Sidebar-Navigation on the Admin Index-Si...
nilq/baby-python
python
import simpy import sys sys.path import random import numpy as np import torch from tabulate import tabulate import sequencing import routing class machine: def __init__(self, env, index, *args, **kwargs): # initialize the environment of simulation self.env = env self.m_idx = ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import argparse import logging logging.basicConfig( level='DEBUG', format='%(asctime)s|%(name)s|%(levelname)s|%(message)s') logger = logging.getLogger(__name__) def main(args): logger.debug(args) ...
nilq/baby-python
python
import numpy as np import scipy as sp import scipy.linalg import numba import time from ..local_tree import LocalTree import sys def fake_print(*args, **kwargs): pass def myprint(*args, **kwargs): print(*args, **kwargs) sys.stdout.flush() def get_print_function(verbose): return myprint if verbose else ...
nilq/baby-python
python
from huobi.client.trade import TradeClient from huobi.constant import * from huobi.utils import * symbol = "htusdt" trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key) list_obj = trade_client.get_orders(symbol=symbol, order_state=OrderState.FILLED, order_type=Order...
nilq/baby-python
python
print("/" * 51)
nilq/baby-python
python
#!/usr/bin/env python3 PKG = 'lg_mirror' NAME = 'test_touch_router' import os import rospy import unittest from lg_mirror.constants import MIRROR_ACTIVITY_TYPE from lg_msg_defs.msg import StringArray from interactivespaces_msgs.msg import GenericMessage from lg_common.test_helpers import gen_touch_window from lg_com...
nilq/baby-python
python
import autograd as ag import click import copy import numpy as np import logging import pickle from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score from sklearn.preprocessing import RobustScaler from sklearn.utils import check_random_state from recnn.preprocessing import rewr...
nilq/baby-python
python
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule, Sequential import mmocr.utils as utils from mmocr.models.builder import BACKBONES from mmocr.models.textrecog.layers import BasicBlock @BACKBONES.register_module() class ResNetABI(BaseModule): """Implement R...
nilq/baby-python
python
import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.cross_validation import train_test_split import theanets import climate climate.enable_default_logging() X_orig = np.load('/Users/bzamecnik/Documents/music-processing/music-processing-experiments/c-scale-piano_spectrogram_2...
nilq/baby-python
python
from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.core.handlers.wsgi import WSGIRequest from tool.session import * from tool.struct import * from tool.check import * from config import log from user.models import User # from books.views import # Cr...
nilq/baby-python
python
from django.apps import AppConfig, apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured class WagtailAPIAppConfig(AppConfig): name = 'wagtail.contrib.wagtailapi' label = 'wagtailapi_v1' verbose_name = "Wagtail API" def ready(self): # Install cache purg...
nilq/baby-python
python
#!/usr/bin/env python3 import os, filecmp from ccjtools import ccj_make def test_mcux(): """Produce compilation database from MCUExpresso build log, check if as expected""" projectDir = '/home/langrind/Documents/MCUXpresso_11.0.1_2563/workspace/evkmimxrt1064_lwip_ping_bm' existingFile = 'tests/mcux...
nilq/baby-python
python
# ---------------------------------------------------------------------------- # Title: Scientific Visualisation - Python & Matplotlib # Author: Nicolas P. Rougier # License: BSD # ---------------------------------------------------------------------------- # Defaults settings / Custom defaults # -------------------...
nilq/baby-python
python
x= int(input()) if x>=1 and x<=100: for y in range(0,x): S = input()[::-1] if len(S)<=1000: print(S)
nilq/baby-python
python
import os def list_files_absolute(start_dir, extensions=None, ignore_empty=False): start_dir = os.path.expanduser(start_dir) return _list_files(start_dir, start_dir, extensions, ignore_empty=ignore_empty) def list_files_relative(start_dir, extensions=None, ignore_empty=False): start_dir = os.path.expand...
nilq/baby-python
python
from torch.nn import functional as F class TensorResize(): def __init__(self, img_size): self.img_size = img_size def __call__(self, img): # XXX interpolate first dim is a batch dim return F.interpolate(img.unsqueeze(0), self.img_size, mode='bilinear')[0] def __repr__(self): ...
nilq/baby-python
python
import argparse import os import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim from torch.utils.data import DataLoader from torch.autograd import Variable import torch.nn.functional as F import numpy as np import time from tensorboardX ...
nilq/baby-python
python
import os from subprocess import PIPE, run import time thisdir = os.path.dirname(__file__) version_c = os.path.join(thisdir, 'Src', 'versions.c') git = run(['git', 'describe', '--dirty', '--always', '--tags'], check=True, stdout=PIPE) revision = git.stdout.decode('ascii').strip() with open(version_c, 'w') ...
nilq/baby-python
python
import datetime import pickle as pkl import time import cv2 import numpy as np import save_dice_traj import serial from testbench_control import TestBench # from notify_run import Notify side_camera_index = 2 tb_camera_index = 0 tb = TestBench('/dev/ttyACM0', tb_camera_index, side_camera_index) resetter = serial.Se...
nilq/baby-python
python
import csv from decimal import Decimal from mkt.prices.models import Price, PriceCurrency def update(tiers): """ Updates the prices and price currency objects based on the tiers. Tiers should be a list containing a dictionary of currency / value pairs. The value of US is required so that we can look...
nilq/baby-python
python