content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
class RecordSearch(BaseModel):
"""
Dao search
Attributes:
-----------
query:
The elasticsearch search query portion
aggregations:
The elasticsearch search aggregations
"""
query: Opt... | nilq/baby-python | python |
from typing import Tuple, Callable
from .template import Processor
from .concat import BatchConcat, BatchPool
from .denoise import Dada2SingleEnd, Dada2PairedEnd
from .importing import ImportSingleEndFastq, ImportPairedEndFastq
from .trimming import BatchTrimGalorePairedEnd, BatchTrimGaloreSingleEnd
class GenerateASV... | nilq/baby-python | python |
import personalnames.titles as titles
import bisect
# noinspection PyTypeChecker
def gen_initials(lastname, firstname, formats, title=None, post_nominal=None, no_ws=False):
"""
Generate the name formats with initials.
:param lastname: person's lastname
:param firstname: person's firstname
:param ... | nilq/baby-python | python |
from typing import List, Union
def is_valid(sides: List[Union[float,int]]) -> bool:
[x, y, z] = sides
return x > 0 and y > 0 and z > 0 and x + y > z
def equilateral(sides: List[Union[float,int]]) -> bool:
sides.sort()
return is_valid(sides) and sides.count(sides[0]) == 3
def isosceles(sides: List[... | nilq/baby-python | python |
import numpy as np
import scipy.sparse as sparse
import scipy.sparse.linalg as linalg
from .mesh import UniformMesh
from .laminate_model import LaminateModel
from .laminate_dof import LaminateDOF
class LaminateFEM(object):
def __init__(self, material, cantilever):
self.cantilever = cantilever
... | nilq/baby-python | python |
"""Falcon benchmarks"""
from bench import main # NOQA
| nilq/baby-python | python |
import os
from pathlib import Path
import pyspark.sql.types as st
from pyspark.sql.types import Row
from pyspark.ml.regression import GBTRegressor
from pyspark.sql import DataFrame, SparkSession
spark = SparkSession.builder \
.appName("karl02") \
.getOrCreate()
datadir: str = os.getenv("DATADIR")
if datadir ... | nilq/baby-python | python |
###############################################################################
# Imports
###############################################################################
from layer import Layer
import numpy as np
class HiddenLayer(Layer):
def setDownstreamSum(self, w, delta):
"""Sum the product o... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
@Time : 2021/8/30
@Author : Yanyuxiang
@Email : yanyuxiangtoday@163.com
@FileName: send_message.py
@Software: PyCharm
'''
import itchat
def main():
itchat.auto_login()
friends = itchat.get_friends(update=True)
# itchat.send('这是来自python程序的一条消息', toUserName='filehelper')
... | nilq/baby-python | python |
from . import scheduler
from app.utils.refresh_mat_views import refresh_all_mat_views
from app.utils.constants import COUNTRIES
# 5/9 = 5am, 2pm, and 11pm
# https://cron.help/#0_5/9_*_*_*
@scheduler.task("cron", minute="0", hour="5")
def run_task_ALL():
with scheduler.app.app_context():
from app.service.r... | nilq/baby-python | python |
import torch
from torch.utils.data import DataLoader
from torch import optim
from torch.optim.lr_scheduler import StepLR
from snf.layers.flowsequential import FlowSequential
from snf.layers.selfnorm import SelfNormConv, SelfNormFC
from snf.train.losses import NegativeGaussianLoss
from snf.train.experiment import Exper... | nilq/baby-python | python |
from VcfNormalize import VcfNormalize
import argparse
import os
#get command line arguments
parser = argparse.ArgumentParser(description='Script to run GATK VariantsToAllelicPrimitives in order to decompose MNPs into more basic/primitive alleles')
parser.add_argument('--gatk_folder', type=str, required=True, help='... | nilq/baby-python | python |
# This file was automatically created by FeynRules 2.3.36
# Mathematica version: 11.3.0 for Linux x86 (64-bit) (March 7, 2018)
# Date: Wed 24 Feb 2021 15:52:48
from object_library import all_couplings, Coupling
from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot
GC_1 = Coupling(name =... | nilq/baby-python | python |
import AnimatedProp
from direct.actor import Actor
from direct.interval.IntervalGlobal import *
class HQPeriscopeAnimatedProp(AnimatedProp.AnimatedProp):
def __init__(self, node):
AnimatedProp.AnimatedProp.__init__(self, node)
parent = node.getParent()
self.periscope = Actor.Actor(node, co... | nilq/baby-python | python |
from threading import Lock, Thread
from time import sleep
class Ingresso:
def __init__(self, estoque):
self.estoque = estoque
self.lock = Lock()
def comprar(self, quantidade):
self.lock.acquire()
if self.estoque < quantidade:
print("-Não temos ingresso suficientes.... | nilq/baby-python | python |
from functools import partial, wraps
from slm_lab import ROOT_DIR
from slm_lab.lib import logger, util
import os
import pydash as ps
import torch
import torch.nn as nn
logger = logger.get_logger(__name__)
class NoOpLRScheduler:
'''Symbolic LRScheduler class for API consistency'''
def __init__(self, optim):
... | nilq/baby-python | python |
"""
Minimize the Himmelblau function.
http://en.wikipedia.org/wiki/Himmelblau%27s_function
"""
import numpy
import minhelper
def himmelblau(X):
"""
This R^2 -> R^1 function should be compatible with algopy.
http://en.wikipedia.org/wiki/Himmelblau%27s_function
This function has four local minima whe... | nilq/baby-python | python |
import os
import tempfile
from unittest import TestCase
from pubmed_bpe_tokeniser import PubmedBPETokenisor
class TestPubmedBPETokenisor(TestCase):
def test_train(self):
# Arrange
data_file = os.path.join(os.path.dirname(__file__), "data", "sample_pubmed.json")
sut = PubmedBPETokenisor(v... | nilq/baby-python | python |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Intel Corporation
#
# 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 requ... | nilq/baby-python | python |
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
# # launch 海龟节点<正常版>
# tur... | nilq/baby-python | python |
from setuptools import setup,find_packages
import lixtools
setup(
name='lixtools',
description="""software tools for data collection/processing at LiX""",
version=lixtools.__version__,
author='Lin Yang',
author_email='lyang@bnl.gov',
license="BSD-3-Clause",
url="https://github.com/NSLS-II-L... | nilq/baby-python | python |
'''
* 'show system status'
'''
import re
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Optional
# ===========================================
# Schema for 'show system status'
# ===========================================
class ShowSystemStatusSchema(MetaParser):
""" Sc... | nilq/baby-python | python |
from django.conf.urls import patterns, include, url
from tastypie.api import Api
from tastypie_evostream.api import StreamResource
tastypie_evostream_api = Api()
tastypie_evostream_api.register(StreamResource())
urlpatterns = patterns(
'',
url(r'', include(tastypie_evostream_api.urls)),
) | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
from django.db import models
from django.contrib.contenttypes import fields
from django.contrib.contenttypes.models import ContentType
# from south.modelsinspector import add_introspection_rules
# from tagging.models import Tag
# from tagging_autocomplete.models import TagAutocompleteField
from... | nilq/baby-python | python |
# coding: utf-8
'''
------------------------------------------------------------------------------
Copyright 2015 - 2017 Esri
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... | nilq/baby-python | python |
from flask_restful import Resource, reqparse, request
from flask_restful import fields, marshal_with, marshal
from sqlalchemy.exc import IntegrityError
from sqlalchemy import or_, and_, text
from flask_jwt_extended import jwt_required
from models.keyword import Keyword
from app import db
from utils.util import max_res
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
from iemlav.lib.log_monitor.server_log.parser.apache import ApacheParser
from iemlav.lib.log_monitor.server_log.server_logger import ServerLogger
try:
# if python 3.x.x
from unittest.mock import patch
except ImportError: # python 2.x.x
from mock import patch
class... | nilq/baby-python | python |
# Copyright (c) 2019 fortiss GmbH
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from bark.world.agent import *
from bark.models.behavior import *
from bark.world import *
from bark.world.map import *
from modules.runtime.commons.parameters import ParameterServer
from module... | nilq/baby-python | python |
import os
import pytest
from h2_conf import HttpdConf
def setup_data(env):
s100 = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678\n"
with open(os.path.join(env.gen_dir, "data-1k"), 'w') as f:
for i in range(10):
f.write(s100)
# The tr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from mimetypes import MimeTypes
from hashlib import md5
def list_of(_list, _class):
"""
Chequea que la lista _list contenga elementos del mismo tipo, desciptos en _class.
Args:
- _list:
- list().
- Lista de elementos sobre la que se desea trabajar.
... | nilq/baby-python | python |
import unittest
import random
from hypothesis import given, settings, assume, Verbosity, strategies as st
from src.poker.app.card import Deck, Card, Suit, Value
from src.poker.app.hand import Hand, Play, Result, calculate_play_hand
DeckStrategy = st.builds(Deck)
NaiveHandStrategy = st.builds(Hand, st.sets(
st.b... | nilq/baby-python | python |
import numpy as np
# Reshaping arrays:
# Reshaping means changing the shape of an array.
# The shape of an array is the number of elements in each dimension.
# By reshaping we can add or remove dimensions or change number of elements in each dimension.
# **Note: The product of the number of elements inside the Resha... | nilq/baby-python | python |
import re
j_format = {
"j": "000010",
}
i_format = {
'beq': "000100",
'bne': None,
'addi': "001000",
'addiu': None,
'andi': None,
'ori': None,
'slti': None,
'sltiu': None,
'lui': None,
'lw': "100011",
'sw': "101011",
}
r_format = {
'add': "100000",
'addu': None,... | nilq/baby-python | python |
import random
from collections import defaultdict
import numpy as np
from maddpg.common.utils_common import zip_map
class ReplayBuffer(object):
def __init__(self, size):
"""Create Prioritized Replay buffer.
Parameters
----------
size: int
Max number of transitions t... | nilq/baby-python | python |
from arbre_binaire_jeu import *
#-------------------------------------------------------------------------------
# DM MISSION
#
# Objectif : Construire un jeu à partir d'un texte préconstruit
#
# Contrainte : utiliser un arbre binaire
#---------------------------------------------------------... | nilq/baby-python | python |
# coding: utf-8
from olo import funcs
from olo.funcs import COUNT, SUM, AVG, MAX, DISTINCT
from .base import TestCase, Foo, Bar, Dummy
from .fixture import is_pg
from .utils import (
patched_execute, no_pk
)
attrs = dict(
name='foo',
tags=['a', 'b', 'c'],
password='password',
payload={
'ab... | nilq/baby-python | python |
from setuptools import setup
setup(
name='german_transliterate',
version='0.1.3',
author='repodiac',
author_email='spamornot@gmx.net',
packages=['german_transliterate'],
url='http://github.com/repodiac/german_transliterate',
license='CC-BY-4.0 License',
description='german_transliterate can cle... | nilq/baby-python | python |
# This file is part of Sequana software
#
# Copyright (c) 2016-2021 - Sequana Development Team
#
#
# Distributed under the terms of the 3-clause BSD license.
# The full license is in the LICENSE file, distributed with this software.
#
# website: https://github.com/sequana/sequana
# documentation: http://sequana.r... | nilq/baby-python | python |
import planckStyle as s
g = s.getSubplotPlotter()
g.settings.legend_fontsize -= 3.5
g.settings.lineM = ['-g', '-r', '-b', '-k', '--r', '--b']
pol = ['TT', 'TE', 'EE', 'TTTEEE']
dataroots = [ getattr(s, 'defdata_' + p) for p in pol]
dataroots += [dataroots[1].replace('lowEB', 'lowTEB'), dataroots[2].replace('lowEB', ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python KISS Module Test Constants."""
__author__ = 'Greg Albrecht W2GMD <oss@undef.net>' # NOQA pylint: disable=R0801
__copyright__ = 'Copyright 2017 Greg Albrecht and Contributors' # NOQA pylint: disable=R0801
__license__ = 'Apache License, Version 2.0' # NOQA pyli... | nilq/baby-python | python |
from toolz import get
from functools import partial
pairs = [(1, 2) for i in range(100000)]
def test_get():
first = partial(get, 0)
for p in pairs:
first(p)
| nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.optim as optim
import pytorch_lightning as pl
from network.dla import MOC_DLA
from network.resnet import MOC_ResNet
from trainer.losses import MOCLoss
from MOC_utils.model import load_coco_pretrained_model
backbone = {
'dla': MOC_DLA,
'resnet': MOC_ResNet
}
def... | nilq/baby-python | python |
import os
from django.http import HttpResponse
from django.template import Context, RequestContext, loader
def ajax_aware_render(request, template_list, context=None, **kwargs):
"""
Render a template, using a different one automatically for AJAX requests.
:param template_list: Either a template name... | nilq/baby-python | python |
import logging
import collections
import time
import six
from six.moves import http_client
from flask import url_for, g, jsonify
from flask.views import MethodView
import marshmallow as ma
from flask_restx import reqparse
from flask_smorest import Blueprint, abort
from drift.core.extensions.urlregistry import Endpoin... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Recursively find and replace text in files under a specific folder with preview of changed data in dry-run mode
============
Example Usage
---------------
**See what is going to change (dry run):**
> flip all dates from 2017-12-31 to 31-12-2017
find_replace.py --dir project/myfolde... | nilq/baby-python | python |
# ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain r... | nilq/baby-python | python |
import os
import cv2
import numpy as np
import random
classnames = ["no weather degradation", "fog", "rain", "snow"]
modes = ["train", "val", "test"]
for classname in classnames:
input_path = "./jhucrowd+weather dataset/{}".format(classname)
images = os.listdir(input_path)
random.shuffle(images)
N = ... | nilq/baby-python | python |
#!/usr/bin/env python
import sys
import time
import random
mn,mx,count = map(int,sys.argv[1:4])
seed = sys.argv[4] if len(sys.argv) > 4 else time.time()
random.seed(seed)
print 'x,y'
for i in xrange(count):
print ','.join(map(str,[random.randint(mn,mx),random.randint(mn,mx)]))
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models
# Create your models here.
@python_2_unicode_compatible
class SummaryNote(models.Model):
title = models.CharField(max_length=60)
content = models.TextField... | nilq/baby-python | python |
# Generated by Django 3.0.8 on 2020-07-29 13:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0022_uploadedimage'),
('events', '0003_auto_20200725_2158'),
]
operations = [
migr... | nilq/baby-python | python |
"""A CLI utility that aggregates configuration sources into a JSON object."""
import json
import logging
import os
import typing
import cleo
import structlog
import toml
import pitstop
import pitstop.backends.base
import pitstop.strategies
import pitstop.strategies.base
import pitstop.types
__all__... | nilq/baby-python | python |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, JsonResponse
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.template import loader, Context
from pure_pagination import Paginator, EmptyPage, PageNotA... | nilq/baby-python | python |
import os
import unittest
from bs4 import BeautifulSoup
from parser import Parser
class ParserTestCase(unittest.TestCase):
def setUp(self):
pass
def test_item_info_images(self):
base_url = "https://www.akusherstvo.ru"
page_url = "/catalog/50666-avtokreslo-rant-star/"
page_moc... | nilq/baby-python | python |
from modules import engine
from modules import out
@engine.prepare_and_clean
def execute(key = None):
out.log('These are all configuration settings.')
config_vars = engine.get_config(key)
if key is None:
for k in config_vars:
out.log(k + ' = ' + str(config_vars[k]))
else:
ou... | nilq/baby-python | python |
# 2D dataset loaders
import data.data_hcp as data_hcp
import data.data_abide as data_abide
import data.data_nci as data_nci
import data.data_promise as data_promise
import data.data_pirad_erc as data_pirad_erc
import data.data_mnms as data_mnms
import data.data_wmh as data_wmh
import data.data_scgm as data_scgm
# othe... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from sqlalchemy.ext.hybrid import hybrid_property
from . import db, bcrypt
from datetime import datetime
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(32), index=True, unique=True)
email = db... | nilq/baby-python | python |
"""
Stingy OLX ad message forwarder: check for new message(s) and send them to your email
@author yohanes.gultom@gmail.com
"""
from stingy_olx import StingyOLX
import re
import argparse
import smtplib
email_tpl = '''From: {0}\r\nTo: {1}\r\nSubject: {2}\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n
{3}
'''
... | nilq/baby-python | python |
# encoding: utf-8
# module pandas._libs.reduction
# from C:\Python27\lib\site-packages\pandas\_libs\reduction.pyd
# by generator 1.147
# no doc
# imports
import __builtin__ as __builtins__ # <module '__builtin__' (built-in)>
import numpy as np # C:\Python27\lib\site-packages\numpy\__init__.pyc
from pandas._libs.lib im... | nilq/baby-python | python |
"""
Base threading server class
"""
from threading import Thread
class ThreadServer:
def __init__(self):
self.server_thread = None
self.running = False
def start(self, *args, **kwargs):
if self.running:
return
self.running = True
self.server_thread = Threa... | nilq/baby-python | python |
from dynaconf import FlaskDynaconf
flask_dynaconf = FlaskDynaconf()
def init_app(app, **config):
flask_dynaconf.init_app(app, **config)
app.config.load_extensions()
| nilq/baby-python | python |
# Copyright 2019 The TensorFlow 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 applica... | nilq/baby-python | python |
from django import forms
from django.http import QueryDict
from django.utils.translation import ugettext_lazy as _
from panoptes.analysis import FilteredSessions
from panoptes.analysis.fields import LensChoiceField, WeekdayChoiceField
from panoptes.core.fields import LocationField
from panoptes.core.models import Ses... | nilq/baby-python | python |
import os
from typing import Any
import torch.optim as optim
import yaml
from aim.sdk.utils import generate_run_hash
from deep_compression.losses import (
BatchChannelDecorrelationLoss,
RateDistortionLoss,
)
def create_criterion(conf):
if conf.name == "RateDistortionLoss":
return RateDistortionL... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# maya
import pymel.core as pm
from maya.app.general.mayaMixin import MayaQDockWidget
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
# Built-in
from functools import partial
import os
import sys
import json
import shutil
import subprocess
# mbox
from . import naming_rules_ui ... | nilq/baby-python | python |
from django.shortcuts import render
# Create your views here.
def main(request):
title = 'Travel Freely!'
content = {
'title': title,
}
return render(request, 'mainsite/index.html', context=content) | nilq/baby-python | python |
from empire.python.typings import *
from empire.fs.file_system import FileSystem
from empire.archive.archive_types import ArchiveTypes
from empire.archive.abstract_compression import AbstractCompression
from empire.archive.abstract_archive import AbstractArchive
from empire.archive.zip_ar import Zip
from empire... | nilq/baby-python | python |
"""API urls."""
from rest_framework import routers
from . import viewsets
router = routers.SimpleRouter()
router.register(r"email-providers", viewsets.EmailProviderViewSet)
router.register(r"migrations", viewsets.MigrationViewSet)
urlpatterns = router.urls
| nilq/baby-python | python |
'''
Leia 3 valores de ponto flutuante A, B e C e ordene-os em ordem decrescente, de modo que o lado A representa o maior dos 3 lados. A seguir, determine o tipo de triângulo que estes três lados formam, com base nos seguintes casos, sempre escrevendo uma mensagem adequada:
- se A ≥ B+C, apresente a mensagem: NAO FORMA ... | nilq/baby-python | python |
from esteira.pipeline.stage import Stage
from pathlib import Path
BASE_DIR = Path(__file__).parent.absolute()
def test_instance():
class TestShell(Stage):
script = [
'echo "hello world"'
]
test = TestShell(BASE_DIR)
test.run() | nilq/baby-python | python |
from __future__ import division
import sys
import math
import random
import time
import webbrowser as wb
import keyboard as kb
import pyautogui
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse
from playsound i... | nilq/baby-python | python |
from logging import getLogger
from hornet import models
from .common import ClientCommand
logger = getLogger(__name__)
class Command(ClientCommand):
def add_arguments(self, parser):
parser.add_argument("member_id", type=int)
def handle(self, member_id, *args, **kwargs):
try:
me... | nilq/baby-python | python |
# Copyright DataStax, 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, softwa... | nilq/baby-python | python |
import uuid
import hashlib
import prettytable
from keystoneclient import exceptions
# Decorator for cli-args
def arg(*args, **kwargs):
def _decorator(func):
# Because of the sematics of decorator composition if we just append
# to the options list positional options will appear to be backwards.
... | nilq/baby-python | python |
import multiprocessing
print(multiprocessing.cpu_count(), "núcleos") # conta a quantidade de núcleos disponpives no sistema
# processamento senquancial
import threading # módulo para a a contrução de threads
import urllib.request # módulo para a requição da url
import time # módulo para tratar o tempo
# função criad... | nilq/baby-python | python |
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
lenh = len(haystack)
lenn = len(needle)
for i in range(lenh-lenn+1):
if haystack[i:i+lenn] == needle:
return i
... | nilq/baby-python | python |
######################################################################
# controller - deals with the UI concerns
# 1. navigation
# 2. preparing data elements in ui way for the screens
#
# It will not be referring to the business domain objects
# - it will use the bl component to deal with the business logic
########... | nilq/baby-python | python |
import requests
from env import QuerybookSettings
from lib.notify.base_notifier import BaseNotifier
class SlackNotifier(BaseNotifier):
def __init__(self, token=None):
self.token = (
token if token is not None else QuerybookSettings.QUERYBOOK_SLACK_TOKEN
)
@property
def notifie... | nilq/baby-python | python |
#
# Copyright 2012 eNovance <licensing@enovance.com>
# Copyright 2012 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
#
# Unle... | nilq/baby-python | python |
"""
Module docstring
"""
from copy import deepcopy
from uuid import uuid4
from os import mkdir
import numpy as np
from scipy.integrate import solve_ivp
class OmicsGenerator:
"""
Handles all omics generation.
This class is used to specify omics generation parameters and generate synthetic data. Typical w... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
This script defines the function to do the irq related analysis
"""
import csv
import struct
from config import TSC_FREQ
TSC_BEGIN = 0
TSC_END = 0
VMEXIT_ENTRY = 0x10000
LIST_EVENTS = {
'VMEXIT_EXTERNAL_INTERRUPT': VMEXIT_ENTRY + 0x00000001,
}
IRQ_EXITS = {}
#... | nilq/baby-python | python |
def Widget(self):
return self
| nilq/baby-python | python |
import unittest
import torch
from torchdrug import data, layers
class GraphSamplerTest(unittest.TestCase):
def setUp(self):
self.num_node = 10
self.input_dim = 5
self.output_dim = 7
adjacency = torch.rand(self.num_node, self.num_node)
threshold = adjacency.flatten().kthv... | nilq/baby-python | python |
"""
Number
1. Integer
2. Floating point
3. Octal & Hexadecimal
1) Octal
a = 0o828
a = 0O828
2) Hexadecimal
a = 0x828
4. Operate
+, -, *, /
pow : **
mod : //
remainder : %
Contents Source : https://wikidocs.net/12
"""
| nilq/baby-python | python |
from sys import argv
script, first, second = argv
print "This script is called: ", script
print "The first variable is: ", first
print "The second variable is: ", second
| nilq/baby-python | python |
# Generated by Django 3.2.4 on 2021-06-15 22:49
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("rules", "0001_initial")]
operations = [
migrations.CreateModel(
name="Ordinance",
fields=[
... | nilq/baby-python | python |
from Crypto.PublicKey import RSA
from Crypto import Random #This one is important since it has the default function in RSA.generate() to generate random bytes!
from Crypto.Cipher import PKCS1_OAEP
import base64
#I'm leaving this function so that you understand how it works from encryption => decryption
def rsa_encryp... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from model.contact import Contact
from fixture.application import Application
import pytest
from model.contact import Contact
def test_add_contact(app):
app.open_home_page()
app.contact.add(Contact(firstname="dsf", dlename="gdfg", lastname="ew", nickname="gdf", title="wer", company="d... | nilq/baby-python | python |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | nilq/baby-python | python |
from django.db import models
from cloudinary.models import CloudinaryField
class Image(models.Model):
short_title = models.CharField(max_length=20)
file = CloudinaryField('image',
default="https://cdn.pixabay.com/photo/2016/06/16/03/49/befall-the-earth-quote-1460570_960_720.jpg")
timeStamp = models.DateT... | nilq/baby-python | python |
def zigzag(n):
'''zigzag rows'''
def compare(xy):
x, y = xy
return (x + y, -y if (x + y) % 2 else y)
xs = range(n)
return {index: n for n, index in enumerate(sorted(
((x, y) for x in xs for y in xs),
key=compare
))}
def printzz(myarray):
'''show zigzag rows as l... | nilq/baby-python | python |
import unittest
import requests
import time
from vaurienclient import Client
from vaurien.util import start_proxy, stop_proxy
from vaurien.tests.support import start_simplehttp_server
_PROXY = 'http://localhost:8000'
# we should provide a way to set an option
# for all behaviors at once
#
_OPTIONS = ['--behavior-d... | nilq/baby-python | python |
import os
import unittest2 as unittest
import json
import sys
from sendgrid import SendGridClient, Mail
class TestSendGrid(unittest.TestCase):
def setUp(self):
self.sg = SendGridClient(os.getenv('SG_USER'), os.getenv('SG_PWD'))
@unittest.skipUnless(sys.version_info < (3, 0), 'only for python2')
de... | nilq/baby-python | python |
import os
import torch
from typing import Dict
from catalyst.dl.fp16 import Fp16Wrap, copy_params, copy_grads
from catalyst.dl.state import RunnerState
from catalyst.dl.utils import UtilsFactory
from catalyst.rl.registry import GRAD_CLIPPERS
from .core import Callback
from .utils import get_optimizer_momentum, schedul... | nilq/baby-python | python |
# O(N + M) time and space
def sum_swap(a, b):
a_sum = 0
a_s = {}
b_sum = 0
b_s = {}
for i, n in enumerate(a):
a_sum += n
a_s[n] = i
for i, n in enumerate(b):
b_sum += n
b_s[n] = i
diff = (a_sum - b_sum + 1) // 2
for i, n in enumerate(a):
if n - dif... | nilq/baby-python | python |
from django import template
register = template.Library()
@register.inclusion_tag('registration/error_messages.html')
def error_messages(errors):
return {'errors': errors}
| nilq/baby-python | python |
if __name__ == "__main__":
user_inpu = int(input())
user_list = list(map(int, input().split()))
user_list = set(user_list)
n = int(input())
for _ in range(n):
user_input = input().split()
if user_input[0] == 'intersection_update':
new_list = list(map(int, input().split())... | nilq/baby-python | python |
import serial, struct, traceback, sys
from rhum.rhumlogging import get_logger
from rhum.drivers.driver import Driver
from rhum.drivers.enocean.messages.message import EnOceanMessage
from rhum.drivers.enocean.messages.response.VersionMessage import VersionMessage
from rhum.drivers.enocean.constants import Packe... | nilq/baby-python | python |
from tkinter import Frame, Label, Button, messagebox, filedialog as fd
from tkinter.constants import DISABLED, E, NORMAL, RAISED, SUNKEN, X
import pandas
import requests
from threading import Thread
import json
from messages import messages
from utils import config
from ibuki import Ibuki
class TopFrame(Frame):
d... | nilq/baby-python | python |
import os
import torch, pickle
from torch import nn
import torch.nn.functional as F
from dataloader import get_transform, get_dataset
from model import get_model
from utils import get_dirname_from_args
# how are we going to name our checkpoint file
def get_ckpt_path(args, epoch, loss):
ckpt_name = get_dirname_fro... | nilq/baby-python | python |
import smtplib
import datetime
from email.mime.text import MIMEText
from flask import current_app
def notify(notifyType, message, all=True):
# Only notify if less than 3 notifications in the past 24 hours
sendNotification = True
now = datetime.datetime.now()
if current_app.config.get(notifyType) is Non... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.