content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from gurobipy import * from prediction.predictor import predict_scores from utils.progress import inhour import time import numpy as np def sample_users(num_users, num_users_sampled): return np.random.choice(num_users, num_users_sampled, replace=False) def sample_items(candidate_items, num_items_sampled): r...
nilq/baby-python
python
import json from rest_framework.fields import MISSING_ERROR_MESSAGE from rest_framework.relations import * from django.utils.translation import ugettext_lazy as _ from rest_framework_json_api.exceptions import Conflict from rest_framework_json_api.utils import Hyperlink, \ get_resource_type_from_queryset, get_res...
nilq/baby-python
python
import kube_vars as globalvars import kube_factory as factory import kube_secret import kube_servicecheck import kube_pvc if __name__=="__main__": # This is the unified interface to accept parameters # Python model argparse be used to parse the input parameter # Subparser has been defined in git_handler.py...
nilq/baby-python
python
import sys from PIL import Image, ImageDraw WRITABLES = [(0, 0, 7, 7), (24, 0, 39, 7), (56, 0, 63, 7)] imagePath = "schoolgirlsweater_tanukirotate.png" img = Image.open(imagePath) draw = ImageDraw.Draw(img) lengthPass = False length = 0 while not lengthPass: msg = input("Enter the messaage to encode ...
nilq/baby-python
python
import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) import time import unittest import common.mqtt_connection as mqtt_connection import common.mqtt_messages as mqtt_messages import server.MQTT_callbacks as MQTT_callbacks import server.storage as server_storage ...
nilq/baby-python
python
import os,copy import pandas as pd from collections import OrderedDict from pypospack.pyposmat.data import PyposmatDataAnalyzer from pypospack.pyposmat.data import PyposmatDataFile from pypospack.pyposmat.data import PyposmatConfigurationFile _fn_config = os.path.join("resources","pyposmat.config.in") _fn_results_in =...
nilq/baby-python
python
def slugify(text): """ Removes all char from string that can cause problems whe used as a file name. :param text: text to be modified. :return: modified text """ return "".join(x for x in text if x.isalnum())
nilq/baby-python
python
# Generated by Django 3.2.4 on 2021-06-21 18:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pvs_suban', '0009_auto_20210621_1753'), ] operations = [ migrations.AddField( model_name='addre...
nilq/baby-python
python
from PyQt5.QtWidgets import QBoxLayout from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QDialogButtonBox from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QMenu from PyQt5.QtWidgets import QPushButton from PyQt5.Qt import pyqtSignal from PyQt5.Qt import ...
nilq/baby-python
python
"""Merge constrained primitives as property constraints.""" import collections from typing import Tuple, Optional, List, Mapping, MutableMapping, Sequence from icontract import ensure from aas_core_codegen import intermediate from aas_core_codegen.common import Error from aas_core_codegen.infer_for_schema import ( ...
nilq/baby-python
python
from core.models import UrineDrugScreen from rest_framework import serializers class UrineDrugScreenSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UrineDrugScreen fields = ('id', 'participant_id', 'date_of_test', 'uds_temp', 'pregnancy_test', 'opiates', 'fentanyl', 'bup', '...
nilq/baby-python
python
from typing import Optional, List from pydantic import BaseModel from feeder.api.models import BasePaginatedList class GenericResponse(BaseModel): success: str = "ok" class FrontButton(BaseModel): enable: bool = True class UTCOffset(BaseModel): utc_offset: int = -7 class TriggerFeeding(BaseModel): ...
nilq/baby-python
python
from al_utils.vaal_util import train_vae, train_vae_disc from al_utils import vae_sampling as vs import sys import pickle import torch import numpy as np import os from copy import deepcopy from pycls.core.config import custom_dump_cfg import pycls.datasets.loader as imagenet_loader def save_numpy_arrays(arrays, nam...
nilq/baby-python
python
import sys import os import datetime import psycopg2 import pandas from subprocess import call, Popen print "dropping temporary members from database..." conn_string = "dbname='hamlethurricane' user=postgres port='5432' host='127.0.0.1' password='password'" try: conn = psycopg2.connect(conn_string) exc...
nilq/baby-python
python
###################################################################### ###################################################################### # Copyright Tsung-Hsien Wen, Cambridge Dialogue Systems Group, 2016 # ###################################################################### ####################################...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2018-07-30 19:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data', '0053_merge_20180615_1859'), ] operations = [ migrations.AddField( ...
nilq/baby-python
python
"""Allow _view property in graph file schema Revision ID: 8f6d4eef042d Revises: a2316139e9a3 Create Date: 2021-10-20 10:04:21.668552 """ import hashlib import json from os import path import fastjsonschema import sqlalchemy as sa from alembic import context from alembic import op from sqlalchemy import table, column...
nilq/baby-python
python
# -*- coding: utf-8 -*- from abc import ABC, abstractmethod from fuocore.models import ( SongModel, ArtistModel, AlbumModel, PlaylistModel, LyricModel, UserModel, ) class AbstractProvider(ABC): """abstract music resource provider """ # A well behaved provider should implement it...
nilq/baby-python
python
import warnings from mmdet.models.builder import (BACKBONES, DETECTORS, HEADS, LOSSES, NECKS, ROI_EXTRACTORS, SHARED_HEADS, build) from .registry import FUSION_LAYERS, MIDDLE_ENCODERS, VOXEL_ENCODERS from mmdet3d.datasets.pipelines import Compose def build_backbone(cfg): """Buil...
nilq/baby-python
python
from flask import Flask from . import api_credentials_provider def create_app(test_config=None) -> Flask: """Main entry point of the service. The application factory is responsible for creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints. Returns: F...
nilq/baby-python
python
# encapsulation def outer(num1): print("outer") def inner_increment(num1): print("inner") return num1 + 1 num2 = inner_increment(num1) print(num1, num2) outer(10)
nilq/baby-python
python
''' Extract special sequences from fasta file. You can specify which sequences get extracted by using the a separator. Usage: python extract <fasta_file> <output_file> <separator> Author: Nicolas Schmelling ''' from Bio import SeqIO import sys def extract(fasta_file, output_file, separator): with o...
nilq/baby-python
python
"""Utilities for interacting with ProxyStore""" import proxystore as ps from typing import Any, Optional, Union from colmena.models import SerializationMethod class ColmenaSerializationFactory(ps.store.redis.RedisFactory): """Custom Factory for using Colmena serialization utilities""" def __init__(self, ...
nilq/baby-python
python
from ... import error from ..entity import Entity from ..component import Component __all__ = ["Parent"] class Parent(Component): def __init__(self, parent: Entity): self._parent = parent def parent(self, err=True) -> Entity: if self._parent is None and err: raise error.ecs.Paren...
nilq/baby-python
python
from microbit import * import utime class Rangefinder: def __init__(self, pin): '''Setup a rangefinder on the specified pin''' self.pin = pin def distance_cm(self): '''Returns the distance from a rangefinder in cm''' self.pin.write_digital(0) utime.sleep_us(200) ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
nilq/baby-python
python
def test_requirements(supported_configuration): pass
nilq/baby-python
python
import os import sys import math import scipy.signal import schemasim.schemas.l0_schema_templates as st class PhysicalCondition(st.RoleDefiningSchema): def __init__(self): super().__init__() self._type = "PhysicalCondition" self._meta_type.append("PhysicalCondition") self._roles ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
nilq/baby-python
python
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2020 Intel Corporation """ ETCD Data Write Tool """ import argparse import logging import os import sys import eis_integ def parse_arguments(_cli_args): """ Parse argument passed to function """ parser = argparse.ArgumentParser(descr...
nilq/baby-python
python
from app.validation.validation import validate, ARGS, KWARGS import json import os __db_items__ = "db/items" class Item: def __init__(self): pass @validate(4, ARGS) def save(self, id, name, price, qty): with open(f"{__db_items__}/{name}.json", 'w') as f: data = { ...
nilq/baby-python
python
import json from setuptools import setup, find_packages from pydoccano import __version__ def requirements(): requirements_list = [] with open('Pipfile.lock', "r") as requirements: data = json.load(requirements) data = data['default'] for i in data: try: req = i + data[i...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import import json import time from multiprocessing import Process import pytest import six import thriftpy2 from thriftpy2.http import make_server as make_http_server, \ make_client as make_http_client from thriftpy2.protocol import TApacheJSONProtocolFact...
nilq/baby-python
python
#!/usr/bin/env python """ """ # Script information for the file. __author__ = "Philippe T. Pinard" __email__ = "philippe.pinard@gmail.com" __version__ = "0.1" __copyright__ = "Copyright (c) 2015 Philippe T. Pinard" __license__ = "GPL v3" # Standard library modules. import unittest import logging import os import temp...
nilq/baby-python
python
import argparse from multiprocessing import Pool from grit.occlusion_detection.occlusion_detection_geometry import OcclusionDetector2D from grit.core.base import create_folders from igp2.data import ScenarioConfig def prepare_episode_occlusion_dataset(params): scenario_name, episode_idx, debug, debug_steps = par...
nilq/baby-python
python
# This is the base module that will be imported by Django. # Try to import the custom settings.py file, which will in turn import one of the deployment targets. # If it doesn't exist we assume this is a vanilla development environment and import .deployments.settings_dev. try: from .settings import * # noqa excep...
nilq/baby-python
python
http://stackoverflow.com/questions/2339101/knights-shortest-path-chess-question
nilq/baby-python
python
import numpy as np import pandas as pd import pickle import os import json import glob import scipy from ngboost import NGBRegressor from ngboost.distns import Normal from ngboost.learners import default_tree_learner from ngboost.scores import MLE, LogScore from sklearn.model_selection import KFold from sklearn.metrics...
nilq/baby-python
python
"""Runs the webserver.""" from absl import app from absl import flags from absl import logging from icubam import config from icubam.db import store flags.DEFINE_string('config', 'resources/config.toml', 'Config file.') flags.DEFINE_string('dotenv_path', None, 'Optionally specifies the .env path.') flags.DEFINE_enum(...
nilq/baby-python
python
from time import sleep def msg(string): print('~' * (len(string) + 2)) print(f' {string} ') print('~' * (len(string) + 2)) while True: print('\33[30;42m', end='') msg('Sistema de ajuda PyHELP') user = str(input('\033[mFunção ou Biblioteca \033[32m>>>\033[m ')) if user.lower() == 'fim': ...
nilq/baby-python
python
import unittest from streamlink.plugins.schoolism import Schoolism class TestPluginSchoolism(unittest.TestCase): def test_can_handle_url(self): should_match = [ 'https://www.schoolism.com/watchLesson.php', ] for url in should_match: self.assertTrue(Schoolism.can_ha...
nilq/baby-python
python
""""Process the results of DrFact and DrKIT""" import json import sys from tqdm import tqdm prediction_file = sys.argv[1] output_file = sys.argv[2] outputs = [] with open(prediction_file) as f: print("Reading", f.name) lines = f.read().splitlines() for line in tqdm(lines[1:], desc="Processing %s"%f.name): ...
nilq/baby-python
python
# -*- coding: utf8 -*- from __future__ import unicode_literals def main(): print('234'.isdecimal()) if __name__ == '__main__': main()
nilq/baby-python
python
def main(): x, y = c(input()), c(input()) if x * y == 0: return 0 return "S" + ("(S" * ((x * y) - 1)) + "(0" + (")" * (x * y)) def c(x): return x.count('S') if __name__ == '__main__': print(main())
nilq/baby-python
python
# @copyright@ # Copyright (c) 2006 - 2018 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r) v5.4 www.rocksclusters.org # ...
nilq/baby-python
python
#!/usr/bin/python3 """ Master program """ import multiprocessing import math import queue import time import pickle import numpy as np import pygame import zmq class CommProcess(multiprocessing.Process): """Communicates with robot.""" def __init__(self, image_queue, command_queue): super().__init__(d...
nilq/baby-python
python
# Generated by Django 3.0.8 on 2020-07-15 09:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Resources', '0008_resume'), ] operations = [ migrations.CreateModel( name='People', ...
nilq/baby-python
python
import os import sys import yaml import subprocess from cryptography.fernet import Fernet secrets_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'secrets.yaml') def decrypt_secrets(cfg): with open(os.path.join(cfg['global']['fernet_tokens_path'],'fernet_tokens.txt'), 'r') as token_file: ...
nilq/baby-python
python
#Test metadata model from src.models import metadata from src import data from src import utils import torch import os from pytorch_lightning import Trainer ROOT = os.path.dirname(os.path.dirname(data.__file__)) def test_metadata(): m = metadata.metadata(sites = 1, classes=10) sites = torch.zeros(20) ...
nilq/baby-python
python
from PyQt5 import QtWebEngineWidgets, QtWidgets from tootbox.core.framework import LayoutView from tootbox.views.toot import Toot class Timeline(LayoutView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initialize_ui() def initialize_ui(self): self.but...
nilq/baby-python
python
from __future__ import unicode_literals import csv import io from django.conf import settings from django.db import models from django.db.models.signals import post_save, pre_save from django.utils.text import slugify from yourapp.signals import csv_uploaded from yourapp.validators import csv_file_validator def uploa...
nilq/baby-python
python
import cv2 import numpy as np # Let's load a simple image with 3 black squares image = cv2.imread('Hough.jpg') cv2.waitKey(0) # Grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Find Canny edges edged = cv2.Canny(gray, 30, 200) cv2.waitKey(0) # Finding Contours # Use a copy of the image e.g....
nilq/baby-python
python
import numpy as np import tensorrt as trt import cv2 import os import pycuda.autoinit import pycuda.driver as cuda try: from . import TRT_exec_tools except ImportError: import TRT_exec_tools class Semantic_Segmentation: def __init__(self, trt_engine_path): """ Parameters: ---...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from quant_benchmark.data.base_data_source.default_data_source import DefaultDataSource import jqdatasdk #see https://github.com/JoinQuant/jqdatasdk/blob/master/tests/test_api.py jqdatasdk.auth(username='13922819479', password='123456') data_source = DefaultDataSource(...
nilq/baby-python
python
def f06(word1 = 'paraparaparadise', word2 = 'paragraph'): ngram = lambda n: lambda tl: [''.join(tl[i:i + n]) for i in range(len(tl) - n + 1)] X = set(ngram(2)(list(word1))) Y = set(ngram(2)(list(word2))) print(X.union(Y)) print(X.difference(Y)) print(X.intersection(Y))
nilq/baby-python
python
import math def get_digit(n, i): return n // 10**i % 10 def int_len(n): if n == 0: return 1 return int(math.log10(n))+1 def get_new_recipes(n): recipes = [] for i in range(int_len(n)): recipes.append(get_digit(n, i)) return recipes[::-1] def part1(count): recipes = [3, 7...
nilq/baby-python
python
from ._Activate import * from ._Deactivate import * from ._Completed import * from ._Startup import * from ._Shutdown import * from ._Recs import *
nilq/baby-python
python
# %% codecell import os import numpy as np from tqdm import tqdm from shutil import copyfile # %% codecell class_indices_S2_rev = { 'Waterbuck': 1, 'Baboon': 2, 'Warthog': 3, 'Bushbuck': 4, 'Impala': 5, 'Oribi': 6, 'Elephant': 7, 'Genet': 8, 'Nyala': 9, 'Setup': 10, 'Bushpig...
nilq/baby-python
python
import csv import os import random from .utils import write_into_file, train_val_test_split def preprocess(in_csv_paths, out_dir_path, val_split, test_split): dataset = [] for path in in_csv_paths: with open(path, "r") as file: reader = csv.DictReader(file) for row in reader: ...
nilq/baby-python
python
"""Output timeseries in NetCDF format. """ import glob,os,sys import pandas as pd import datetime as dt import copy def defaultExtensions(): return ['.nc'] def NCfile(filename,datas): datas=copy.deepcopy(datas) fileout=copy.deepcopy(filename) for i,df in enumerate(datas): if len(datas)>1: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class CassandraCluster(object): """Implementation of the 'CassandraCluster' model. Specifies an Object containing information about a Cassandra cluster. Attributes: primary_host (string): Primary host from this Cassandra cluster. seeds (lis...
nilq/baby-python
python
""" A Work-In-Progress agent using Tensorforce """ from . import BaseAgent from .. import characters class TensorForceAgent(BaseAgent): """The TensorForceAgent. Acts through the algorith, not here.""" def __init__(self, character=characters.Bomber, algorithm='ppo'): super(TensorForceAgent, s...
nilq/baby-python
python
## 2. Frequency Distribution ## fandango_distribution = reviews['Fandango_Ratingvalue'].value_counts().sort_index() imdb_distribution = reviews['IMDB_norm'].value_counts().sort_index() print(fandango_distribution) print('--'*12) print(imdb_distribution) ## 4. Histogram In Matplotlib ## fig, ax = plt.subplots() plt...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 03. 円周率 sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics." print([len(c.strip(",.")) for c in sentence.split()])
nilq/baby-python
python
from django.db.models.signals import post_save from django.dispatch import receiver from django.db import models from problem.models import Submit, ProblemStats, LogEvent @receiver(post_save, sender=Submit) def update_problem_status(sender, instance, **kwargs): try: stats: ProblemStats = ProblemStats.obje...
nilq/baby-python
python
km = float(input('Informe a distância em KM: ')) v = float(input('Informe a velocidade média: ')) t = km / v t_h = t // 1 t_m = (t - t_h) * 60 print(f'O tempo da viagem será de {t_h:.0f} horas e {t_m:.0f} minutos.')
nilq/baby-python
python
# from .runner import main
nilq/baby-python
python
import re from typing import List, Dict, Type import pkgutil import inspect import importlib import HABApp from HABApp.core import Items from HABApp.core.items.base_item import BaseItem import zone_api.core.actions as actions from zone_api import platform_encapsulator as pe from zone_api import device_factory as df f...
nilq/baby-python
python
from unittest import TestCase from unittest.mock import patch, call import os import pytest from osbot_utils.utils.Dev import pprint from osbot_utils.utils.Json import json_load_file from cdr_plugin_folder_to_folder.processing.Analysis_Elastic import Analysis_Elastic from cdr_plugin_folder_to_folder.utils.testing.Se...
nilq/baby-python
python
from seleniumbase import BaseCase from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from parameterized import parameterized import pytest from test_thermal.test_CompanyAdmin.test_RoleManagement.RoleManageBase import RoleManageBase from utilities import utilities from utilities....
nilq/baby-python
python
""" Here we're going to code for the local rotations. We're doing an object oriented approach Left and right are in reference to the origin """ __version__ = 1.0 __author__ = 'Katie Kruzan' import string # just to get the alphabet easily iterable import sys # This just helps us in our printing from typing import Di...
nilq/baby-python
python
from controller.csi_general import csi_pb2 SUPPORTED_FS_TYPES = ["ext4", "xfs"] access_mode = csi_pb2.VolumeCapability.AccessMode SUPPORTED_ACCESS_MODE = [access_mode.SINGLE_NODE_WRITER] # VolumeCapabilities fields which specify if it is volume with fs or raw block volume VOLUME_CAPABILITIES_FIELD_ACCESS_TYPE_MOUNT ...
nilq/baby-python
python
import pybamm import numpy as np import sys # set logging level pybamm.set_logging_level("INFO") # load (1+1D) SPMe model options = { "current collector": "potential pair", "dimensionality": 1, "thermal": "lumped", } model = pybamm.lithium_ion.SPM(options) # create geometry geometry = model.default_geome...
nilq/baby-python
python
# # Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE. # # Distributed under 3-Clause BSD license. See LICENSE file for more information. # """ Mapping Module """ # -- STANDARD MAPPI...
nilq/baby-python
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : download.py @Time : 2020/11/08 @Author : Yaronzz @Version : 1.0 @Contact : yaronhuang@foxmail.com @Desc : ''' import os import aigpy import logging import lyricsgenius from tidal_dl.settings import Settings from tidal_dl...
nilq/baby-python
python
""" plots how total workseting set increase over time """ import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../")) from utils.common import * import bisect SLAB_SIZES = [96, 120, 152, 192, 240, 304, 384, 480, 600, 752, 944, 1184, 1480, 1856, 2320, 2904, 3632, 4544, 5680, 71...
nilq/baby-python
python
from setuptools import setup setup(name='carpet', version='2021', # description='', url='https://cfaed.tu-dresden.de/friedrich-home', author='Anton Solovev, Benjamin M Friedrich', license='MIT', packages=['carpet'], zip_safe=False)
nilq/baby-python
python
''' Convert a neighbors file to human-readable format, optionally including preferred string expansion. ''' from hedgepig_logger import log from .. import nn_io if __name__ == '__main__': def _cli(): import optparse parser = optparse.OptionParser(usage='Usage: %prog') parser.add_option('-i...
nilq/baby-python
python
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=8, decimal_places=2)
nilq/baby-python
python
#!/usr/bin/env python import cv2 # from opencvutils.video import Camera cam = cv2.VideoCapture(0) # cam.init(cameraNumber=0, win=(640, 480)) while True: try: ret, img = cam.read() cv2.imshow('img', img) if cv2.waitKey(1) == 27: break # esc to quit except: # cam.close() break cv2.destroyAllWindows(...
nilq/baby-python
python
import requests import json from xlwt import * url = "https://api.github.com/users/andrewbeattycourseware/followers" response = requests.get(url) data = response.json() filename = 'githubusers.json' print(data) for car in data: print(car) #write the Json to a file. #import json if filename: with open(filename, ...
nilq/baby-python
python
from .cell_level_analysis import CellLevelAnalysis from .pixel_level_analysis import PixellevelAnalysis from .feature_extraction import InstanceFeatureExtraction from .background_extraction import ExtractBackground
nilq/baby-python
python
# -*- coding: utf-8 -*- ''' Copyright (c) 2014, pietro partescano All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this ...
nilq/baby-python
python
import xml.etree.ElementTree as ET import urllib2 from sqlalchemy import and_ from datetime import datetime from .ConnectDB_ParseExcel import * from stp0_loadCVs import Load_CV_To_DB from stp4_loadDataValue.helper import LoadingUtils class CUAHSI_importer(): ''' This class is used to get data putting to Wa...
nilq/baby-python
python
"""Fsubs config."""
nilq/baby-python
python
"""Utility functions to check attributes returned in API responses and read from the AWS S3.""" import datetime import re def check_attribute_presence(node, attribute_name): """Check the attribute presence in the given dictionary or list. To be used to check the deserialized JSON data etc. """ found_...
nilq/baby-python
python
gagaStop = Lorentz(name = 'gagaStop', spins = [ 3, 3, 1 ], structure = 'FTriPhotonTop(2*P(-1,1)*P(-1,2)) * (Metric(1,2)*P(-1,1)*P(-1,2) - P(2,1)*P(1,2))') gagaSbot = Lorentz(name = 'gagaSbot', spins = [ 3, 3, 1 ], structure = 'FTriPhotonBot(2*P(-1,1)...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Zero-DCE++: Learning to Enhance Low-Light Image via Zero-Reference Deep Curve Estimation Zero-DCE++ has a fast inference speed (1000/11 FPS on single GPU/CPU for an image with a size of 1200*900*3) while keeping the enhancement performance of Zero-DCE. References: ...
nilq/baby-python
python
"""Number constraint names.""" from jsonvl._utilities.venum import Venum class NumberConstraintNames(Venum): """Constraints applied to number types.""" LT = 'lt' GT = 'gt' LTE = 'lte' GTE = 'gte' EQ = 'eq'
nilq/baby-python
python
import time import logging import numpy as np import torch import torch.nn as nn from data import augment, TensorDataset from diffaugment import DiffAugment from utils import get_time def epoch(mode, dataloader, net, optimizer, criterion, args, aug): loss_avg, acc_avg, num_exp = 0, 0, 0 net = net.to(args.devic...
nilq/baby-python
python
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all the match records from the dat...
nilq/baby-python
python
a, b = [int(x) for x in input().split()] if a > b: a, b = b, a if a & 1: a += 1 if b & 1: b -= 1 print(((b - a) // 2 + 1) * (a + b) // 2)
nilq/baby-python
python
from ..SimpleSymbolDownloader import SymbolDownloader from ..symbols.Generic import Generic from time import sleep from ..compat import text import requests class TigerDownloader(SymbolDownloader): def __init__(self): SymbolDownloader.__init__(self, "tiger") def _add_queries(self, prefix=''): ...
nilq/baby-python
python
from flask import Blueprint from app.actor import get_hello import jsonpickle hello_resource = Blueprint('hello_resource', __name__) @hello_resource.route('/rest/hello/', defaults={'name': 'world'}) @hello_resource.route('/rest/hello/<name>') def get(name): return jsonpickle.encode(get_hello.run(name), unpicklab...
nilq/baby-python
python
""" Copyright 2020 Alexander Brauckmann. 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, softw...
nilq/baby-python
python
# coding=utf-8 # Copyright (c) 2016-2018, F5 Networks, 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 applicabl...
nilq/baby-python
python
from __future__ import annotations import logging import re from dataclasses import dataclass from datetime import date from wordgame_bot.attempt import Attempt, AttemptParser from wordgame_bot.exceptions import InvalidFormatError, ParsingError from wordgame_bot.guess import Guesses, GuessInfo INCORRECT_GUESS_SCORE ...
nilq/baby-python
python
# https://leetcode.com/problems/magic-squares-in-grid/description/ # # algorithms # Medium (35.25%) # Total Accepted: 12,752 # Total Submissions: 36,179 # beats 66.41% of python submissions class Solution(object): def splitIntoFibonacci(self, S): """ :type S: str :rtype: List[int] ...
nilq/baby-python
python
from django import forms from formfactory import clean_methods @clean_methods.register def check_if_values_match(form_instance, **kwargs): """Clean method for when a contact updates password. """ first_field = form_instance.cleaned_data["first_field"] second_field = form_instance.cleaned_data["second...
nilq/baby-python
python
# File: worker.py # Aim: Backend worker of the http server # Imports import os import sys from . import CONFIG from .local_tools import Tools tools = Tools() CONFIG.logger.debug('Worker imported in HTTP package') # Import other workers other_folders = [ os.path.join( os.path.dirname(__file...
nilq/baby-python
python