content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import os import lab_test def mean(list_a): return sum(list_a) / len(list_a) def create_md_file(path, bpp_mine, psnr_mine, ssim_mine, bpp_jpg, psnr_jpg, ssim_jpg): os.system('mkdir -p {}'.format(path)) file_p = os.path.join(path,'res.md') mdfile = open(file_p, 'w') res = [] res.append('MyMode...
nilq/baby-python
python
#! /usr/bin/env python #coding: utf-8 ###################################################################################### #Script for download and convert to fastq SRA datasets serially. # #Authors: David Peris UW-Madison, Dept Genetics # #Usage: python downl...
nilq/baby-python
python
#========================================================================== # # Copyright Insight Software Consortium # # 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 # # ...
nilq/baby-python
python
from typing import Callable def test_hello_default(hello: Callable[..., str]) -> None: assert hello() == "Hello !" def test_hello_name(hello: Callable[..., str], name: str) -> None: assert hello(name) == "Hello {0}!".format(name)
nilq/baby-python
python
# -*- coding: utf-8 -*- """ equip.analysis.python ~~~~~~~~~~~~~~~~~~~~~ Python related information for analysis. :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """
nilq/baby-python
python
""" XVM (c) www.modxvm.com 2013-2017 """ ##################################################################### # MOD INFO XFW_MOD_INFO = { # mandatory 'VERSION': '0.9.19.0.1', 'URL': 'http://www.modxvm.com/', 'UPDATE_URL': 'http://www.modxvm.com/en/download-xvm/', 'GAME_VERSION...
nilq/baby-python
python
import numpy as np import pandas as pd import pytest from dku_timeseries import WindowAggregator from recipe_config_loading import get_windowing_params @pytest.fixture def columns(): class COLUMNS: date = "Date" category = "country" aggregation = "value1_avg" return COLUMNS @pytest.f...
nilq/baby-python
python
#!/usr/bin/env python import pyinotify import os, sys import logging import json import thread, threading import time, datetime import hashlib import mimetypes import traceback # google stuff from ServiceProviders.Google import GoogleServiceProvider from apiclient.http import BatchHttpRequest from apiclient import err...
nilq/baby-python
python
# CS4120 NLP, Northeastern University 2020 import spacy from tqdm import tqdm from spacy.analysis import Token, Doc, Span from data_management import output_filepath, input_filepath def main(): nlp = spacy.load("en_core_web_sm") docs = [] with open(input_filepath("samplesentences.txt")) as f: f...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Tests for CommandChainDispatcher.""" from __future__ import absolute_import #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import nose.tools as nt from IPython.core.erro...
nilq/baby-python
python
from datetime import date import uuid from typing import Optional, List from pydantic import BaseModel, Field def generate_invoice_id(): return str(uuid.uuid4()) class InvoiceInfo(BaseModel): invoice_id: str = Field(default_factory=generate_invoice_id) issuer_name: str issuer_address: Optional[str]...
nilq/baby-python
python
# Generated by Django 3.0.7 on 2020-07-17 15:52 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('judge', '0010_auto_20200717_1735'), ] operations = [ migrations.AlterField( model_name='problem', ...
nilq/baby-python
python
import sys import numpy as np import matplotlib.pyplot as plt # Load data #bf = np.loadtxt('data/times/brute_force.txt') #cp = np.loadtxt('data/times/closest_pair.txt') bf = np.loadtxt(sys.argv[1]) cp = np.loadtxt(sys.argv[2]) # Reshape data bf = bf.reshape(6, len(bf) // 6) cp = cp.reshape(6, len(cp) // 6) # Average...
nilq/baby-python
python
from core.testing import APITestCase class TestAPITestCase(APITestCase): def test_tests(self): self.assertTrue(hasattr(self, 'pytestmark')) self.assertTrue(hasattr(self, 'mixer'))
nilq/baby-python
python
# NOT FINISHED, barely started import copy import time import random import math from typing import List import jax.numpy as np from pomdp_py.framework.basics import Action, Agent, POMDP, State, Observation,\ ObservationModel, TransitionModel, GenerativeDistribution, PolicyModel from pomdp_py.framework.planner ...
nilq/baby-python
python
# Generated by Django 3.2.3 on 2021-11-11 14:04 from django.db import migrations, models import django.db.models.deletion def copy_funding_instruments_from_calls_to_projects(apps, schema_editor): Project = apps.get_model('project_core', 'Project') for project in Project.objects.all(): project.fundin...
nilq/baby-python
python
import json import argparse def contains(splits): # Returns 1D binary map of images to take such that access is O(1) MAX, MIN = max([int(x.split('-')[-1]) for x in splits]), min([int(x.split('-')[0]) for x in splits]) A = [0 for _ in range(MAX-MIN+1)] for sp in splits: if '-' in sp: beg...
nilq/baby-python
python
from sklearn.base import BaseEstimator import numpy as np from sklearn.base import clone from .logs.loggers import get_logger import math class DeepModel(BaseEstimator): def __init__(self, estimator, depths, n_estimators=100, learning_rate=0.01, verbose=True, logging=None, logging_params={}): ...
nilq/baby-python
python
################################################################################ # COPYRIGHT(c) 2018 STMicroelectronics # # # # Redistribution and use in source and binary forms, with or without ...
nilq/baby-python
python
from django.core.mail import send_mail from django.shortcuts import render,redirect,reverse from django.http import HttpResponse from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic from .models import AgentModel, LeadModel,CategoryModel from .forms import ( Lea...
nilq/baby-python
python
# Copyright 2016 VMware, Inc. # # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess import logging logger = logging.getLogger(__name__) class RestartHandler: def __init__(self, observer, command): self.observer = observer self.command = command def run(self): logger.info("Running restart handler") ...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
nilq/baby-python
python
import numpy as np from scipy.constants import mu_0 # TODO: make this to take a vector rather than a single frequency def rTEfunfwd(nlay, f, lamda, sig, chi, depth, HalfSwitch): """ Compute reflection coefficients for Transverse Electric (TE) mode. Only one for loop for multiple layers. Do not use...
nilq/baby-python
python
from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseForbidden from django.shortcuts import get_object_or_404 from django.views.decorators.csrf import csrf_exempt from django.views.generic import TemplateView from rest_framework.renderers import JSONRenderer from rest_framework...
nilq/baby-python
python
import cv2 as cv import numpy as np import math import time beg=time.time() def readimg (xmin,xmax,ymin,ymax): ymins=ymin n=(xmax-xmin+1)*(ymax-ymin+1)*21.25 target=0 while xmin<xmax : while ymin<ymax : target = target+img[xmin,ymin] ymin += 1 xmin +=...
nilq/baby-python
python
#!/usr/local/bin/python import ogr, osr import datetime print "Start: ", datetime.datetime.now() for i in range(10000): pointX = -84 pointY = 38 inputESPG = 4267 outputEPSG = 2246 point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(pointX, pointY) inSpatialRef = osr.SpatialReference() ...
nilq/baby-python
python
#!/usr/local/bin/python3 from MPL3115A2 import MPL3115A2 from si7021 import Si7021 from pms5003 import PMS5003 from smbus import SMBus import influxdb_client from influxdb_client import InfluxDBClient import time import logging hostname="indoors" logging.basicConfig(level=logging.DEBUG) mpl = MPL3115A2(1, fetchPr...
nilq/baby-python
python
#! /usr/bin/env python #coding=utf8 import os import sys if __name__ == '__main__': if len(sys.argv) < 2: print 'USAGE: commit message' sys.exit() commit_msg = sys.argv[1] os.system('git pull origin master') os.system('git status') os.system('git add ./') os.system('git commit ...
nilq/baby-python
python
#!/usr/bin/env python from csv import DictReader import numpy as np import matplotlib.pyplot as plt from PIL import Image from wordcloud import WordCloud from snli_cooccur import mkdirp_parent DEFAULT_COLOR_NAME = '#1f497d' DEFAULT_RELATIVE_SCALING = 1. DEFAULT_WIDTH = 800 DEFAULT_HEIGHT = 400 DEFAULT_MAX_WORDS =...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import os from unittest import TestCase from flaky import flaky from polyaxon_schemas.ops.build_job import BuildConfig from polyaxon_schemas.ops.environments.pods import EnvironmentConfig from polyaxon_schemas.ops.environments....
nilq/baby-python
python
#!/usr/bin/env python from typing import NamedTuple from hummingbot.market.market_base import MarketBase class ArbitrageMarketPair(NamedTuple): """ Specifies a pair of markets for arbitrage """ market_1: MarketBase market_1_trading_pair: str market_1_base_asset: str market_1_quote_asset:...
nilq/baby-python
python
param_names = [\ 'Kon_IL13Rec', 'Rec_phosphorylation', 'pRec_intern', 'pRec_degradation', 'Rec_intern', 'Rec_recycle', 'JAK2_phosphorylation', 'pJAK2_dephosphorylation', 'STAT5_phosphorylation', 'pSTAT5_dephosphorylation', 'SOCS3mRNA_production', 'DecoyR_binding', 'J...
nilq/baby-python
python
import datetime import genshin async def test_diary(lclient: genshin.Client, genshin_uid: int): diary = await lclient.get_diary() assert diary.uid == genshin_uid == lclient.uids[genshin.Game.GENSHIN] assert diary.nickname == "sadru" assert diary.month == datetime.datetime.now().month assert diary...
nilq/baby-python
python
""" A :class:`~miso.data.dataset_readers.dataset_reader.DatasetReader` reads a file and converts it to a collection of :class:`~miso.data.instance.Instance` s. The various subclasses know how to read specific filetypes and produce datasets in the formats required by specific models. """ # pylint: disable=line-too-long...
nilq/baby-python
python
import numpy as np from napari.components import Camera def test_camera(): """Test camera.""" camera = Camera() assert camera.center == (0, 0, 0) assert camera.zoom == 1 assert camera.angles == (0, 0, 90) center = (10, 20, 30) camera.center = center assert camera.center == center ...
nilq/baby-python
python
class APIError(Exception): """ Simple error handling """ codes = { 204: 'No Results', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Unauthorized (Payment Required)', 403: 'Forbidden', 404: 'Not Found', 413: 'Too Much Data Given', 429: 'To...
nilq/baby-python
python
ta=[1,2,3] tb=[9,8,7] # cluster zipped=zip(ta,tb) print('zip(ta,tb)=',zip(ta,tb)) #decompose na,nb=zip(*zipped) print(na,nb)
nilq/baby-python
python
import os, logging, math import numpy as np import torch import torch.nn as nn from volsim.base_models import * from volsim.simulation_dataset import * from volsim.params import * class DistanceModel(nn.Module): def __init__(self, modelParams:Params, useGPU:bool=True): super(DistanceModel, self).__init_...
nilq/baby-python
python
"""Add hostname column to the resources table Revision ID: 58a12e45663e Revises: 06ce06e9bb85 Create Date: 2020-10-20 18:24:40.267394 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '58a12e45663e' down_revision = '06ce06e9bb85' branch_labels = None depends_on =...
nilq/baby-python
python
from cantoolz.module import * from cantoolz.uds import * import json class control_ecu_doors(CANModule): name = "Doors trigger for vircar" help = """ This module emulating lock control. Init params (example): { 'id_report': {0x91:'Left', 0x92:'Right'}, 'id_command': 0x81, ...
nilq/baby-python
python
# Under MIT licence, see LICENCE.txt import random from typing import List from Util import Pose, Position from Util.ai_command import MoveTo from Util.constant import BALL_RADIUS, ROBOT_RADIUS, POSITION_DEADZONE, ANGLE_TO_HALT from Util.geometry import compare_angle from ai.GameDomainObjects.player import Player from...
nilq/baby-python
python
import factory import json from django.test import TestCase, Client from django.urls import reverse from django.test import RequestFactory from django.contrib.auth.models import AnonymousUser from movies.models import Movie from movies.views import home from movies.forms import SearchMovieForm from movie_database.use...
nilq/baby-python
python
import spatialfacet import numpy as np from matplotlib import pyplot as plt from shapely.geometry import Polygon, Point U = Polygon([[-1,-1], [-1,1], [0,1], [0,-1], [-1,-1]]) V = Polygon([[0,-1], [0,1], [1,1], [1,-1], ...
nilq/baby-python
python
import numpy def diff(features1, features2): pixelMap1 = numpy.asarray(features1) pixelMap2 = numpy.asarray(features2) return numpy.linalg.norm(pixelMap1-pixelMap2) def highOrSober(soberFeatures, highFeatures, queryFeatures): if(diff(soberFeatures, queryFeatures) < diff(highFeatures, queryFeatures)): ...
nilq/baby-python
python
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'A tiny Python/C library for loading MIAS images from file.', 'author': 'Samuel Jackson', 'url': 'http://github.com/samueljackson92/mias-loader', 'download_url': 'http://github.com/s...
nilq/baby-python
python
from PIL import Image import gym import gym_pacman import time env = gym.make('BerkeleyPacmanPO-v0') env.seed(1) done = False while True: done = False env.reset() i = 0 while i < 100: i += 1 s_, r, done, info = env.step(env.action_space.sample()) env.render() print("It...
nilq/baby-python
python
from asyncio import sleep from requests import get from main import bot, reg_handler, des_handler, par_handler async def diss(message, args, origin_text): await message.edit("获取中 . . .") status = False for _ in range(20): req = get("https://nmsl.shadiao.app/api.php?level=min&from=tntcrafthim") ...
nilq/baby-python
python
# Generated by Django 2.1 on 2018-10-03 01:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('unlabel_backend', '0021_auto_20180625_1904'), ] operations = [ migrations.DeleteModel( name='Article', ), migrations.Delet...
nilq/baby-python
python
#!/usr/bin/env python # vim:set ts=2 sw=2 expandtab: # # the pre.py script permits the reconstruction to specify the server, user # name, and password used for connection. This is achieved by setting # the parameters in a dictionary named jobArgs. # # Optional output variable : jobArgs # # Default dictionary; only thos...
nilq/baby-python
python
class Solution(object): def findLongestWord(self, s, d): """ :type s: str :type d: List[str] :rtype: str """ newD = sorted(d, key=len, reverse=True) tempList = [] for word in newD: if len(tempList) != 0 and len(word) != len(tempList[-1]): ...
nilq/baby-python
python
""" @author: Andrea Domenico Giuliano @contact: andreadomenico.giuliano@studenti.unipd.it @organization: University of Padua """ import datetime import math from collections import defaultdict #File contenente le funzioni riguardanti la creazione dei dict rigurandanti i gruppi degli items e degli users ...
nilq/baby-python
python
import logging import os import shutil import numpy as np import torch from pytorch_metric_learning.utils import common_functions as pml_cf from sklearn.model_selection import train_test_split from torchmetrics.functional import accuracy as tmf_accuracy from ..adapters import Finetuner from ..containers import Models...
nilq/baby-python
python
#!/usr/bin/env python # $Id$ """ Abstract base class for driver classes""" import exceptions class DriverError(exceptions.Exception): def __init__(self, arg): exceptions.Exception.__init__(self,arg) class Driver: mount_delay = 0 def fileno(self): raise NotImplementedError de...
nilq/baby-python
python
# # Copyright (c) 2015-2016 Erik Derr [derr@cs.uni-saarland.de] # # 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 appli...
nilq/baby-python
python
def train_interupter(): with open('train_interupter.ini', 'r', encoding='utf-8') as f: flag = f.read().strip() if flag == '0': return False elif flag == '1': with open('train_interupter.ini', 'w', encoding='utf-8') as f: f.write('0') return True else: ...
nilq/baby-python
python
# The MIT License (MIT) # Copyright (c) 2021 Jonah Yolles-Murphy (TG-Techie) # 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 # t...
nilq/baby-python
python
import argparse import logging from sqlalchemy.orm import Session from ...db import yield_connection_from_env_ctx from ..indices import update_installation_default_indices from ..models import SlackOAuthEvent logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def upgrade_one( db_sess...
nilq/baby-python
python
from extractors.blockextractor import BlockExtractor from extractors.characterfactory import CharacterFactory from extractors.emojiextractor import EmojiExtractor from extractors.mathcollectionextractor import MathExtractor from extractors.nerdextractor import NerdExtractor if __name__ == "__main__": character_fac...
nilq/baby-python
python
"""AnimeSuki Media models""" from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.text import slugify from animesuki.core.models import ArtworkModel from animesuki.core.utils import DatePrecision from animesuki.history.models import HistoryModel class Medi...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-06-12 07:41 from __future__ import unicode_literals import bluebottle.files.fields import bluebottle.utils.fields from decimal import Decimal from django.conf import settings from django.db import migrations, models import django.db.models.deletion import d...
nilq/baby-python
python
from __future__ import annotations import subprocess import sys def test_same_version(): """ Test the the version in setup.py matches the version in __init__.py """ res = subprocess.run( [sys.executable, '-m', 'pip', 'show', 'cptk'], stdout=subprocess.PIPE, check=True, encodi...
nilq/baby-python
python
# coding=utf-8 ##以utf-8编码储存中文字符 import jieba.analyse import codecs,sys import itertools from work import match from io import BufferedReader from work import simplyParticiple def Synonym(): #同义词函数 seperate_word = {} dict1={} i=0 file = codecs.open("same_word.txt","r","utf-8") # 这是同义词库 lines = fi...
nilq/baby-python
python
from .common import ( AskHandler, CommonHandler, AskCommutativeHandler, TautologicalHandler, test_closed_group, ) __all__ = [ "AskHandler", "CommonHandler", "AskCommutativeHandler", "TautologicalHandler", "test_closed_group", ]
nilq/baby-python
python
from matching_algorithm import matching_algorithm import json import copy class top_trading_cycle(matching_algorithm): def group_1_optimal(self): return self.match(copy.deepcopy(self.group_1), copy.deepcopy(self.group_2), 'top_trading_cycle', False) def group_2_optimal(self): return self.matc...
nilq/baby-python
python
from setuptools import find_packages, setup setup( name="Skaak", packages=find_packages(include=["skaak"]), version="0.12.5", description="A Python Chess Library", author="George Munyoro", license="MIT", install_requires=[], setup_requires=["pytest-runner"], tests_require=["pytest==...
nilq/baby-python
python
""" Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half. Given a ticket number n, determine if it's lucky or not. Example For n = 1230, the output should be solution(n) = true; Fo...
nilq/baby-python
python
import graphene from ipam import filtersets, models from netbox.graphql.scalars import BigInt from netbox.graphql.types import BaseObjectType, OrganizationalObjectType, PrimaryObjectType __all__ = ( 'ASNType', 'AggregateType', 'FHRPGroupType', 'FHRPGroupAssignmentType', 'IPAddressType', 'IPRan...
nilq/baby-python
python
from utils import * import matplotlib.pyplot as plt # import matplotlib.colors from sklearn.preprocessing import StandardScaler from skimage.transform import resize from PIL import Image path_save = "./results/face_glasses_separation2/" if not os.path.exists(path_save): os.makedirs(path_save) # color_map = mat...
nilq/baby-python
python
from flask_apscheduler import APScheduler from actions import * from context import * from config import Config class Executor: """ An Executor drives a pipeline which composed by a sequence of actions with a context """ def __init__(self, config: Config, pipeline_name, pipeline): self.co...
nilq/baby-python
python
#!/usr/bin/env python import os try: import cplex except ImportError: cplex = None import numpy as np from mapel.voting.metrics.inner_distances import hamming # FOR SUBELECTIONS def solve_lp_voter_subelection(election_1, election_2, metric_name='0'): """ LP solver for voter subelection problem """ ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Author : Jesse Wei # LastUpdate : 2020/10/04 # Impact : Jobs generated by SQLG # Message : Humanity towards others, we live by sharing. Fear can hold you prisoner, only hope can set you free. # from __future__ import print_function import logging import re import airfl...
nilq/baby-python
python
from segmentTree import SumSegmentTree, MinSegmentTree import numpy as np import matplotlib.pyplot as plt class RingBuffer(object): def __init__(self, maxlen, shape, dtype='int32'): self.maxlen = maxlen self.data = np.zeros((maxlen,) + shape).astype(dtype) self.next_idx = 0 def append(...
nilq/baby-python
python
from .plots import Plot,PlotError,PlotState from .. import context from .. import items from .. import maps from .. import randmaps from .. import waypoints from .. import monsters from .. import dialogue from .. import services from .. import teams from .. import characters from .. import namegen import random from .....
nilq/baby-python
python
from datetime import datetime, date, timezone import dateutil from dateutil.relativedelta import relativedelta import re from .util import calculate_price, DELIM_VALUE_REGEX, DOT_VALUE_REGEX from isodate import parse_duration, parse_datetime import pytz def create_default_context(numeric, responseMetadata): def c...
nilq/baby-python
python
import container_crawler.utils import mock import unittest class TestUtils(unittest.TestCase): @mock.patch('container_crawler.utils.InternalClient') @mock.patch('container_crawler.utils.os') def test_internal_client_path(self, os_mock, ic_mock): os_mock.path.exists.return_value = True os_m...
nilq/baby-python
python
import random from random import sample import argparse import numpy as np import os import pickle from tqdm import tqdm from collections import OrderedDict from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics import precision_recall_curve from sklearn.covariance import L...
nilq/baby-python
python
""" A QUANTIDADE DE UMA LETRA, A PRIMEIRA E A ÚLTIMA VEZ QUE APARECERAM NA FRASE! """ frase = str(input('Digite uma frase: ')).strip() frase = frase.upper() print('A quantidade de A é {} '.format(frase.count('A'))) print('A primeira vez que A apareceu foi: {} '.format(frase.find('A')+1)) print('A última vez que A ...
nilq/baby-python
python
ll=range(5, 20, 5) for i in ll: print(i) print (ll) x = 'Python' for i in range(len(x)) : print(x[i])
nilq/baby-python
python
from typing import Sequence, Union from PIL import Image class BaseTransform: """ Generic image transform type class """ slug: Union[None, str] = None # unique string that identifies a given transform @staticmethod def apply_transform( img: Image.Image, parameters: Sequence[Union[...
nilq/baby-python
python
from collections import Counter input_data = open("day12.input").read().split("\n") input_data = [tuple(a.split("-")) for a in input_data] connections = [] for (a, b) in input_data: if a != 'start': connections.append((b, a)) connections += input_data connections.sort() def part1(path, b): return...
nilq/baby-python
python
import os import numpy as np import pandas as pd from typing import Any, Dict, List, Optional, Tuple, NoReturn import skfuzzy as fuzz import skfuzzy.control as ctrl from aggregation import OWA_T1 import matplotlib.pyplot as plt class FLST1Model(object): def __init__(self, rules_path:str, expert_mode:str): ...
nilq/baby-python
python
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize('fasterloop.pyx'))
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from enum import Enum, unique @unique class AnalyzeFieldIdx(Enum): IDX_MODULE_NAME = 0 IDX_ANALYE_NAME = 1 IDX_COLUMN_INFO = 2 IDX_IS_EXECUTE = 3
nilq/baby-python
python
import unittest from . import day01 class TestDay1(unittest.TestCase): def test_basic(self): self.assertEqual('hello', 'hello') def test_fuel_is_calculated_correctly_for_given_examples(self): self.assertEqual(day01.get_fuel_required(module_mass=12), 2) self.assertEqual(day01.get_fuel_r...
nilq/baby-python
python
# Code by JohnXdator n,k = map(int,input().split()) ups = list(map(int,input().split())) count = 0 for i in range(n): if ups[k-1] == 0 and ups[i] == ups[k-1]: count>=count+0 elif ups[k-1] <= ups[i]: count=count+1 else: count=count+0 print(count)
nilq/baby-python
python
from django.test import TestCase from django.core.management import call_command class TestUi(TestCase): def setUp(self): call_command('loaddata', 'user', verbosity=0) call_command('loaddata', 'init', verbosity=0) call_command('loaddata', 'test/testWorld', verbosity=0) ...
nilq/baby-python
python
import math import warnings from torch import Tensor import torch.nn as nn def zeros_(): """Return the initializer filling the input Tensor with the scalar zeros""" def initializer(tensor: Tensor, fan_in: int = None, fan_out: int = None): return nn.init.zeros_(tensor) return initializer def on...
nilq/baby-python
python
#!/usr/bin/python # Filename: mysqlfunc.py # Purpose: All the mysql functions # !!! need to encapsulate a cur with something like a using statement # Database errors import MySQLdb, pdb, logger, dnsCheck from MySQLdb import Error #All the variables for paths from variables import * def create_dbConnection(): t...
nilq/baby-python
python
#!/usr/bin/env python import functools import os import os.path from datetime import timedelta from functools import update_wrapper from flask import Flask, abort, current_app, jsonify, make_response, request import psycopg2 DATABASE = os.environ['POSTGRES_DB'] USERNAME = os.environ['POSTGRES_USER'] PASSWORD = os....
nilq/baby-python
python
from botcity.core import DesktopBot # Uncomment the line below for integrations with BotMaestro # Using the Maestro SDK # from botcity.maestro import * class Bot(DesktopBot): def action(self, execution=None): # Fetch the Activity ID from the task: # task = self.maestro.get_task(execution.task_id) ...
nilq/baby-python
python
import os from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from ibm_watson import PersonalityInsightsV3 from services.base import BaseService, BaseServiceResult class IBMWatson(BaseService): """ IBM Watson service wrapper """ def __init__(self, service_wrapper, service_url): ""...
nilq/baby-python
python
#!/usr/bin/python3 # creates the SQLite database file - run this first import sqlite3 # create db file con = sqlite3.connect('./db/ic_log1_2020-06-30_manual.db') cur = con.cursor() # create table cur.execute('''CREATE TABLE IF NOT EXISTS iclog (date real, ic integer, note text)''') # close the connection con.close(...
nilq/baby-python
python
# -*- coding: utf-8 -*- def main(): n, m = map(int, input().split()) summed = 4 * n - m xy = list() # 2x + 3y + 4z = M # x + y + z = N を解く # See: # https://atcoder.jp/contests/abc006/submissions/1112016 # WAの原因:成立しない条件の境界値を0以下だと思っていた,2項目の条件に気がつけなかった if summed < 0: ...
nilq/baby-python
python
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: Jackson Lee 7/8/14 This script reads in a fasta or fastq and filters for sequences greater or less than a threshold length Input fastq file @2402:1:1101:1392:2236/2 GATAGTCTTCGGCGCCATCGTCATCCTCTACAC...
nilq/baby-python
python
import numpy as np from os import listdir from os.path import join #def random_shift_events(events, max_shift=20, resolution=(180, 240)): def random_shift_events(events, f, max_shift=20, resolution=(195, 346)): H, W = resolution x_shift, y_shift = np.random.randint(-max_shift, max_shift+1, size=(2,)) ...
nilq/baby-python
python
import json import cryptography.fernet from django.conf import settings from django.utils.encoding import force_bytes, force_text from django_pgjson.fields import get_encoder_class import six # Allow the use of key rotation if isinstance(settings.FIELD_ENCRYPTION_KEY, (tuple, list)): keys = [ cryptography...
nilq/baby-python
python
from pptx import Presentation from pptx.util import Inches import pyexcel as pe print(""" Exemplo de criação de apresentação PPTX em loop utilizando dados de Excel Vish, o bagulho foi loko pra conseguir criar este aplicativo mano -> agora aprendi, já era Day 24 Code Python - 23/05/2018 """) dadosE...
nilq/baby-python
python
""" This sample shows how to create a list in json of all items in a group Python 2.x/3.x ArcREST 3.5,6 """ from __future__ import print_function from __future__ import absolute_import import arcrest import os import json from arcresthelper import orgtools, common import csv import sys from arcresthelper....
nilq/baby-python
python
def get_customized_mapping(cls): mapping = { "name": { "type": "text", "copy_to": [ "all" ] }, "is_public": { "type": "boolean" }, "taxid": { "type": "integer" }, "genes": { ...
nilq/baby-python
python