content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
'''
(c) University of Liverpool 2019
All rights reserved.
@author: neilswainston
'''
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
# pylint: disable=wrong-import-order
import os
import shutil
import sys
import pandas as pd
from synbiochem.utils import ice_utils... | nilq/baby-python | python |
"""
Script to restore subject information from the HANDS 2017 training set. It is known that each sample
in the dataset belongs to one out of 5 subjects. It can be assumed that each subject has a slightly
different hand shape. By running a simple clustering algorithm on the bone lengths the mapping from
subjects to sam... | nilq/baby-python | python |
import click
import random, string
import decimal
import datetime
import names
from flask.cli import FlaskGroup
from src.app import create_app
from src.models import db, User, Computer, PurchaseDetails, Accounts
@click.group(cls=FlaskGroup, create_app=create_app)
def cli():
pass
def create_db():
db.drop_all... | nilq/baby-python | python |
import heapq
from dataclasses import dataclass, field
from operator import lt
from typing import Dict, List, Optional, Tuple
# default collection name if none is specified.
DEFAULT_COLLECTION_NAME = "default_collection"
"""
Time Taken By Me -> 33 mins 18 secs
Atlassian LLD Round -:
Design the following -:
... | nilq/baby-python | python |
#!/usr/bin/env python
from EPPs.common import StepEPP
class AssignNextStepSampleReceipt(StepEPP):
"""
This script checks to see if any of the relevant step UDFs are answered indicating that a manager review is required
"""
def _run(self):
# obtain the actions of the step then creates a StepA... | nilq/baby-python | python |
import json
import domoticz
import configuration
from adapters import adapter_by_model
from zigbee_message import ZigbeeMessage
from adapter import UniversalAdapter
class DevicesManager:
def __init__(self):
self.devices = {}
def set_devices(self, zigbee_devices):
self.devices = {}
for... | nilq/baby-python | python |
try:
total
except:
ffin dyh | nilq/baby-python | python |
#!/usr/bin/env python
import gzip
import os
import sys
from parseExternalDatabase import *
from RNAIsoformAnnotator import *
from RNAIsoform import RNAIsoform
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
import pysam
import pybedtools
# Do this in main and put on command line
pybedtools.set_bedtools_path("... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Fixture to keep legacy unit tests working."""
from tackle import models
def update_source_fixtures(
template,
abbreviations,
clone_to_dir,
checkout,
no_input,
password=None,
directory=None,
):
"""Mock the old cookiecutter interfece for tests."""
source =... | nilq/baby-python | python |
from Jumpscale import j
import pytest
def main(self):
"""
to run:
kosmos 'j.data.schema.test(name="unittests")' --debug
"""
return
unittests_path = "/sandbox/code/github/threefoldtech/jumpscaleX/Jumpscale/data/schema/tests/testsuite"
assert pytest.main([unittests_path]) == 0
| nilq/baby-python | python |
'''
Author: Hans Erik Heggem
Email: hans.erik.heggem@gmail.com
Project: Master's Thesis - Autonomous Inspection Of Wind Blades
Repository: Master's Thesis - CV (Computer Vision)
'''
import glob, warnings, os
'''
@brief Class for getting test sets
Change data sets as preferred to use for testing.
'''
class Test... | nilq/baby-python | python |
/usr/lib/python2.7/encodings/iso8859_8.py | nilq/baby-python | python |
"""genericPlots.py
Plots that require matplotlib (but not plotly)
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def publisher_histogram(df, title, ylabel):
"""
A specifically selected dataframe.
From df->clean_df->pyblishers
Plot a histogram showing the distribution
... | nilq/baby-python | python |
import logging
import requirements
logger = logging.getLogger(__name__)
EXCLUDE_REQUIREMENTS = frozenset((
# obviously already satisfied or unwanted
'ansible', 'ansible-base', 'python', 'ansible-core',
# general python test requirements
'tox', 'pycodestyle', 'yamllint', 'pylint',
'flake8', 'pytes... | nilq/baby-python | python |
#
# Copyright 2014 Thomas Rabaix <thomas.rabaix@gmail.com>
#
# 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... | nilq/baby-python | python |
from . import models
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
class CustomUserCreateForm(UserCreationForm):
class Meta(UserCreationForm):
model = get_user_model()
fields = ("email",)
class Cust... | nilq/baby-python | python |
from __future__ import unicode_literals
import frappe
import json
import pyqrcode
from PIL import Image, ImageDraw
import io
import requests
import base64
import textwrap
import re
@frappe.whitelist()
def check_stock(doc,method):
if doc.get('__islocal')!= 1:
final_item_status = []
final_item_percent = []
ohs = ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 EMBL - European Bioinformatics Institute
#
# 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/LICEN... | nilq/baby-python | python |
import re
from zen_document_parser.base import DocField, DocVariant
from zen_document_parser.exceptions import FieldParseError
class ITRVBase(DocVariant):
# Overridden in subclasses
for_year = None
test_fields = ['form_title', 'assessment_year']
form_title = DocField((52, 745, 478, 774))
# Fo... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
from Validation.RecoTrack.TrackingParticleSelectionsForEfficiency_cff import *
from Validation.RecoTrack.GenParticleSelectionsForEfficiency_cff import *
MTVHistoProducerAlgoForTrackerBlock = cms.PSet(
### tp selectors for efficiency
generalTpSelector = gener... | nilq/baby-python | python |
# Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from django.core.exceptions import ObjectDoesNotExist
import tastypie.http as http
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from... | nilq/baby-python | python |
"""
Copyright (c) 2019, NVIDIA CORPORATION. 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 list of conditions and the fo... | nilq/baby-python | python |
from .bases import AuditBackend
class SyslogBackend(AuditBackend):
"""The `syslog` audit backend writes audit logs to syslog.
"""
def validate(self, *, facility='AUTH', tag='vault', log_raw=False):
"""Configure audit backend.
Parameters:
facility (str): The syslog facility to... | nilq/baby-python | python |
import numpy as np
from scipy.linalg import svd
__all__ = ['orthomax']
def orthomax(Phi, gamma=1., maxiter=20, tol=1e-6):
"""
Given n*k factor matrix Phi (k number of factors, n number of dimensions),
find a rotated version of the factor loadings that fulfills optimization criteria,
depending on gamm... | nilq/baby-python | python |
import json
import time
from threading import Thread
from typing import Any, Dict, List
from uuid import uuid4
import pytest
import redis
from confluent_kafka import OFFSET_END, Consumer, Producer, TopicPartition
from rsmq import RedisSMQ
from example.data_models import InputMessage
from example.kafka_kafka_worker im... | nilq/baby-python | python |
from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import io
import warnings
from collections import defaultdict
from threading import Lock
try:
from spidev import SpiDev
except ImportError:
SpiDev = None
from . import SPI
from .pi impor... | nilq/baby-python | python |
# Generated by Django 3.0.3 on 2020-02-25 12:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='srtmodel',
name='srt',
field=... | nilq/baby-python | python |
# Cogs to enable on Starting
__cogs__ = ['cogs.admin',
'cogs.anime',
'cogs.fun',
'cogs.information'
#'cogs.utilities'
] | nilq/baby-python | python |
from flask import Flask, request, jsonify, render_template
from flask_socketio import SocketIO, emit
from flask_classful import FlaskView, route
import time
class Server(Flask):
_config = None
state = None
socketio = None
last_timestamp = None
connected = False
def __init__(self, config):
... | nilq/baby-python | python |
"""Serializers module."""
from rest_framework import serializers
from django_celery_results.models import TaskResult
from api import models
class ExchangeSerializer(serializers.ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
class Meta:
"""Meta class to map serializer'... | nilq/baby-python | python |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
"""
@project: occurrence-abundance pattern (parameters for Fig 5A - source code)
@author: Roman Zapien-Campos - 2021
"""
# Import packages
import numpy as np
### Define parameters ###
# General parameters
# Number of microbes within a host
N = 1E3
# Number of micr... | nilq/baby-python | python |
#
# Copyright 2013-2020 University of Southern California
#
# 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 |
import requests
import os
SERVER = 'http://127.0.0.1:8000/'
PAGE_1 = 'api/1.0.0/doctor/'
PAGE_2 = 'api/1.0.0/title/'
AUTH = ('SU', 'superuser',)
response = requests.get(os.path.join(SERVER, PAGE_1))
print(response.text)
response = requests.get(os.path.join(SERVER, PAGE_2))
print(response.text)
response = requests.d... | nilq/baby-python | python |
"""
Project Euler - Problem Solution 037
Problem Title - Truncatable primes
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def truncated_nums(prime):
''' Generates every truncation of a number. '''
digits = str(prime)
for i in range(1, len(digits... | nilq/baby-python | python |
import logging
import sys
from time import sleep
import pigpio
from errors import I2CReadError, I2CWriteError
from .i2c_driver import I2cDriver
class SdpPressureSensor(I2cDriver):
"""Driver class for SDP8XXX Pressure sensor."""
I2C_ADDRESS = 0x25
MEASURE_BYTE_COUNT = 0x3
CMD_TRIGGERED_DIFFERENTIAL_P... | nilq/baby-python | python |
from flask import Flask, url_for, request, render_template
import numpy as np
import csv
import math
app = Flask(__name__)
def compute_ln_norm_distance(vector1, vector2, n):
vector_len = len(vector1)
distance = 0
for i in range(vector_len):
distance += (abs(vector1[i] - vector2[i])) ** n
... | nilq/baby-python | python |
from bank_account import BankAccount
joes_account = BankAccount(500)
print(joes_account.get_balance())
print()
joes_account.deposit(500)
print(joes_account.get_balance())
print()
joes_account.withdraw(100)
print(joes_account.get_balance())
| nilq/baby-python | python |
import sys
import matplotlib
import numpy as np
# Avoid errors when running on headless servers.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
sys.path.insert(0, '/root/jcw78/process_pcap_traces/')
import graph_utils
if len(sys.argv) < 7:
print "Usage plot.py <min rate> <step size> <max rate> <num packets ... | nilq/baby-python | python |
def load(path):
with open(path) as f:
content = f.read()
return hig(d)
def parsetodict(content):
"""
:type content: str
:param content:
:return:
"""
if '=' in content:
content.partition('=')
#takes string and writes in hig format
def dict2str(d, depth=0):
content... | nilq/baby-python | python |
'''
For your reference:
class TreeNode:
def __init__(self, node_value):
self.val = node_value
self.left_ptr = None
self.right_ptr = None
'''
def kth_smallest_element(root, k):
def traverse(node, index):
if not node:
return None
left_result = tra... | nilq/baby-python | python |
class ImageJ_RelaxationTime_profil():
def __init__(self,
image='path',
relax_Time='path',
Intensity='path',
Shift='path',
ListTime=[0.0],
time_type="enumerate(('EchoTime',\
'... | nilq/baby-python | python |
'''
Session 07
Timing helper class
'''
import time
class Stopwatch:
def __init__(self, nanoseconds=False):
self.timefunc = time.perf_counter_ns if nanoseconds else time.perf_counter
self.reset()
def elapsed(self):
return self.timefunc() - self.tic
def reset(self):
self... | nilq/baby-python | python |
#!/usr/bin/python
import zipfile
with zipfile.ZipFile('subor.zip', 'r') as zf:
print(zf.namelist())
| nilq/baby-python | python |
import time
from web3 import Web3, HTTPProvider
abi = '''
[
{
"constant": false,
"inputs": [
{
"name": "target",
"type": "uint256"
}
],
"name": "bump",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
... | nilq/baby-python | python |
#encoding:utf-8
subreddit = 'Trackers'
t_channel = '@r_trackers'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| nilq/baby-python | python |
import sys
import argparse
import re
from selenium import webdriver
from selenium.webdriver.chrome import service as cs
from selenium.webdriver.common.keys import Keys as keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriv... | nilq/baby-python | python |
# !/uer/bin/env python3
"""
@author: Medivh Xu
@file: db_manager.py
@time: 2020-02-27 12:22
"""
import pymysql
import contextlib
from loguru import logger
from config_loader import conf_load
@contextlib.contextmanager
def mysql(filename=None, **conf):
"""
mysql连接方法
examples:
:type(env... | nilq/baby-python | python |
#!/usr/bin/env python3
# test/calib.py
import enum
import matplotlib.pyplot as plt
import logging
import numpy as np
import os, sys
from astropy.io import fits
from scipy.ndimage import median_filter
from pyFU.utils import check_directories, construct_new_path, get_sec, get_list_of_paths_and_filenames, get_in... | nilq/baby-python | python |
"""This module implements the Choices system for user preferences.
The environment variable CHOICESPATH gives a list of directories to search
for choices. Changed choices are saved back to the first directory in the
list."""
import os
from os.path import exists
try:
path = os.environ['CHOICESPATH']
paths = path.spl... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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
# to use, copy,... | nilq/baby-python | python |
# python
from chempy import io
from chempy import protein
from chempy import protein_amber99
model= io.pdb.fromFile("../../test/dat/pept.pdb")
model= protein.generate(model,forcefield=protein_amber99)
sm = 0
for a in model.atom:
sm = sm + a.partial_charge
print(" prot: net partial charge on protein is %8.4f" % ... | nilq/baby-python | python |
import numpy as np
from pyrfsim import RfSimulator
import argparse
from scipy.signal import gausspulse
from time import time
description="""
Demo program showing how to use the fixed-scatterer GPU
implementation from Python.
Also useful to measure the running time of the GPU
implementations.
"""
... | nilq/baby-python | python |
import asyncio as aio
import logging
import random
import re
from datetime import datetime, timedelta
from aiogram import types, Bot
from aiogram.utils import markdown as md
from aiogram.utils.exceptions import *
from aiochatbase import Chatbase
from antiflood import rate_limit
from languages import underscore as _
f... | nilq/baby-python | python |
from django.contrib import admin
from .models import Arts, Comments, Tags, ArtworksTags, Stili, Umetnina, Umetnik
# Register your models here.
admin.site.register(Umetnik)
admin.site.register(Umetnina)
admin.site.register(Stili)
admin.site.register(Arts)
admin.site.register(Comments)
admin.site.register(Tags)
admin.... | nilq/baby-python | python |
from stencil_ir import *
from verify import *
from assertion_to_sketch import *
import asp.codegen.ast_tools as ast_tools
from invariant import *
import logging
def loop_key(node):
import hashlib
return hashlib.sha224(tree_to_str(node)).hexdigest()[0:10]
class RHSInvariantReplacer(ast_tools.NodeTransformer):
... | nilq/baby-python | python |
class Job():
def __init__(self):
self.using = False
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setDisplayName(self, dname):
self.dname = dname
def getDisplayName(self):
return self.dname
def IamWerewolf(self, we... | nilq/baby-python | python |
import sys
import numpy as np
import pandas as pd
from sys import argv, __stdout__
from datetime import datetime, timedelta
import os
### This program makes a timing dataframe from output logfiles generated by graphB.
### It can take multiple files as command line arguments manually, in which it will generate
### one... | nilq/baby-python | python |
import os, sys, socket, urlparse
###
class socket_uri(object):
'''
Socket factory that is configured using socket URI.
This is actually quite generic implementation - not specific to console-server IPC communication.
'''
# Configure urlparse
if 'unix' not in urlparse.uses_query: urlparse.uses_query.append('uni... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import json
import traceback
import re
from optparse import OptionParser
from couchdbkit import Server, ChangesStream
from pywebhdfs.webhdfs import PyWebHdfsClient
from ConfigParser import ConfigParser
#we make ample use of these docs.
#pywebdfs: http://p... | nilq/baby-python | python |
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | nilq/baby-python | python |
#
# PySNMP MIB module BGP4-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BGP4-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:18:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | nilq/baby-python | python |
from _animation import get_joint_transform_from_rig
from _math import Vector3, Quaternion
from routing import SurfaceIdentifier, SurfaceType, Location
from sims4.math import angle_to_yaw_quaternion
from sims4.tuning.geometric import TunableVector2
from sims4.tuning.tunable import HasTunableFactory, OptionalTunable, Tun... | nilq/baby-python | python |
#!/usr/bin/python3
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# 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
# to use, copy,... | nilq/baby-python | python |
from random import randint
class Node:
def __init__(self,value = None):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return str(self.value)
class linkedList:
def __init__(self):
self.head = None
self.tail = None
def __i... | nilq/baby-python | python |
import socket, sys, ssl, uuid, thread, json, re
from functools import partial
class Susi:
def __init__(self,addr,port,cert,key):
s = None
for res in socket.getaddrinfo(addr, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
... | nilq/baby-python | python |
import os
import logging
from twisted.python.failure import Failure
from scrapy.utils.request import referer_str
SCRAPEDMSG = "Scraped from %(src)s" + os.linesep + "%(item)s"
DROPPEDMSG = "Dropped: %(exception)s" + os.linesep + "%(item)s"
CRAWLEDMSG = "Crawled (%(status)s) %(request)s%(request_flags)s (referer: %(re... | nilq/baby-python | python |
import numpy as np
from webdnn.graph.graph import Graph
from webdnn.graph.order import OrderNCHW
from webdnn.graph.variable import Variable
from webdnn.graph.variables.constant_variable import ConstantVariable
from webdnn.optimizer.sub_rules.simplify_commutative_operator import SimplifyCommutativeOperator
def test_s... | nilq/baby-python | python |
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
import numpy as np
import socket
def initializeSocket():
host, port = "127.0.0.1", 25001
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))
return sock
def initializeCircuit():
c... | nilq/baby-python | python |
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from timm.models.vision_transformer import _cfg, PatchEmbed
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_, ... | nilq/baby-python | python |
#!/bin/usr/env python
import argparse
import requests
import json
def parse_args():
parser = argparse.ArgumentParser(description='')
parser.add_argument(
'--type',
'-t',
action='store',
choices=[
'hour',
'day',
'week',
'month',
... | nilq/baby-python | python |
import pandas as pd
import numpy as np
def load_chart_data(fpath):
chart_data = pd.read_csv(fpath, thousands=',', header=None)
chart_data.columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'action_B', 'action_H', 'action_S']
return chart_data
def preprocess(chart_data):
prep_dat... | nilq/baby-python | python |
from CommandManager import CommandManager
from Command import Command
from ActionManager import ActionManager
from Action import Action
import json
import cv2
#class voor de load
class Load(object):
actionManager = ActionManager()
def loadActions(self): #loads ... | nilq/baby-python | python |
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class Button:
__metaclass__ = ABCMeta
@abstractmethod
def paint(self):
pass
class LinuxButton(Button):
def paint(self):
return "Render a button in linux style"
class WindowsButton(Button):
def paint(... | nilq/baby-python | python |
"""Benchmark task for testing constraint satisfaction with sphere."""
import sympy
from sympais import distributions as dist
from . import base
class Sphere(base.Task):
"""Task for constraint satisfaction with spheres."""
def __init__(self, nd: int):
"""Construct a `Sphere` task.
Args:
nd: number... | nilq/baby-python | python |
"""Test app factory method."""
from pytest import MonkeyPatch
from app import create_app
def test_app_factory_method(monkeypatch: MonkeyPatch) -> None:
"""Test that application test settings are correct."""
app = create_app(testing=True)
assert app.testing
class Recorder:
dsn: str
en... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import PIL
from PIL import Image
def display_network(A, filename='weights.jpg', opt_normalize = True):
"""
This function visualizes filters in matrix A. Each column of A is a
filter. We will reshape each column into a square image and vis... | nilq/baby-python | python |
# Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/ios/chrome',
'ui_string_overrider_inputs': [
'<(SHARED_I... | nilq/baby-python | python |
import json
from os import path
from subprocess import run, PIPE
from typing import Dict
def get_key_signer(key_name: str, keys_dir: str) -> Dict:
with open(path.join(keys_dir, key_name + ".json"), "r") as f:
return json.load(f)
def get_key_multisig_addr(key_name: str) -> str:
p = run(('secretcli', ... | nilq/baby-python | python |
class BitVector(object):
"""docstring for BitVector"""
"""infinite array of bits is present in bitvector"""
def __init__(self):
self.BitNum=0
self.length=0
def set(self,i):
self.BitNum=self.BitNum | 1 << i
self.length=self.BitNum.bit_length()
def reset(self,i):
resetValue=1<<i
self.BitNum=self.BitNum ... | nilq/baby-python | python |
#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals, print_function, division
import sys
import binascii
from diameterparser.decode_diameter import decode_diameter
def convertMac(octet):
mac = [binascii.b2a_hex(x) for x in list(octet)]
return "".join(mac)
class DiameterConn:
... | nilq/baby-python | python |
# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC.
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering Solutions
# of Sandia, LLC, the U.S. Government retains certain rights in this software.
# standard library
import os
import hashlib
import pic... | nilq/baby-python | python |
from materials_io.base import BaseParser, BaseSingleFileParser
from glob import glob
import pytest
import os
class FakeParser(BaseParser):
def parse(self, group, context=None):
return {'group': list(group)}
def implementors(self):
return ['Logan Ward']
def version(self):
return ... | nilq/baby-python | python |
"""Base class for all linear models.
Subclasses must implement their own _fit_regression, _fit_classifier, and
_iter_minibatches functions. Everything else (prediction, generating
model summaries, saving, loading, one-vs-rest training) is handled by this.
"""
from __future__ import absolute_import
from __future__ im... | nilq/baby-python | python |
# Copyright 2020 kubeflow.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | nilq/baby-python | python |
# import asyncio
# import requests
# import json
# import re
import os
import discord
from discord.ext import commands, tasks
from discord_slash import SlashCommand, SlashContext
from itertools import cycle
import keep_alive
# # grabbing the config file
# with open('config.json') as config_file:
# secrets = json.... | nilq/baby-python | python |
from sys import exit
import json
from time import sleep
from confluent_kafka import Consumer, KafkaError
ERROR_CODE_ZERO = 0
ERROR_CODE_ONE = 1
EMPTY_ERROR_MESSAGE = ""
PAUSE = 3
class KafkaConsumer:
def __init__(self, settings, client_id, timeout, auto_commit):
self._settings = settings
self._t... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
both web service and mosquitto are running locally.
MENSHNET_UNITTEST="yes" is defined
1. simulate the okta routine that creates the api key by calling
the same endpoint in the server to generate an apiKey.
"""
import os
os.environ["MENSHNET_UNITTEST"] = "yes"
import menshnet
| nilq/baby-python | python |
from abc import ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta):
def walk(self):
print('Walking...')
def eat(self):
print('Eating...')
@abstractmethod
def num_legs():
pass | nilq/baby-python | python |
class Solution:
def solve(self, n):
count = 1
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
count += 1
return count
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from flask import Flask, jsonify
from flask.ext.cors import CORS, cross_origin
from pymongo import MongoClient
import os
app = Flask(__name__)
CORS(app)
mongodb_host = '172.16.0.2'
mongodb_port = 27017
client = MongoClient(mongodb_host,mongodb_port)
collection = client.conflict_db.events
@... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | nilq/baby-python | python |
import os
import subprocess
from setuptools import find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
def get_git_commit_number():
if not os.path.exists('.git'):
return '0000000'
cmd_out = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)
... | nilq/baby-python | python |
from django.test.testcases import TestCase
from corehq.messaging.smsbackends.sislog.util import convert_raw_string
class GSM0338Portuguese(TestCase):
def test_decode(self):
raw_to_clean = {
# basic character test
"associa\x09\x7bo": "associa\u00e7\u00e3o",
# extended ... | nilq/baby-python | python |
from finbert.finbert import predict
from pytorch_pretrained_bert.modeling import BertForSequenceClassification
import argparse
from pathlib import Path
import datetime
import os
import random
import string
import pandas as pd
import time
import pickle
import multiprocessing as mp
import gc
# globals
model = None
pars... | nilq/baby-python | python |
import pytest
from fastapi.testclient import TestClient
from firedantic import ModelNotFoundError
from _pytest.monkeypatch import MonkeyPatch
import saatja.request_dependencies as request_dependencies
from saatja.db.task import ScheduledTask, DeliveredTask, TaskError
from saatja.utils import now_utc
SCHEDULER_HEADERS... | nilq/baby-python | python |
from typing import Union
from discordmovies.attributes import DiscordMoviesAttributes
from typing import List
from discordmovies.outputmodules.filehelper import FileHelper
from discordmovies.inputmodules.input import Input
class DiscordMovies:
"""
A class for going through a discord movie recommendations chan... | nilq/baby-python | python |
import os
import shutil
import datetime
from ebooklib import epub
from toolbox.tools import Now
from compiler import epub_html
now = Now()
css = """body{padding:0;margin:0;line-height:1.2;text-align:justify}
p{text-indent:2em;display:block;line-height:1.3;margin-top:0.6em;margin-bottom:0.6em}
div{margi... | nilq/baby-python | python |
# loop3
userinput = input("Enter a letter in the range A - C : ")
while (userinput != "A") and (userinput != "a") and (userinput != "B") and (userinput != "b") and (userinput != "C") and (userinput != "c"):
userinput = input("Enter a letter in the range A-C : ")
| nilq/baby-python | python |
import math
import numpy as np
year = input("Enter the year to be checked : ")
def check_leap(year):
print(type(year))
year = int(year)
if year%100==0:
print("Leap Year")
elif year%4 == 0:
print("Leap Year")
elif year % 400 == 0:
print("Leap Year")
else:
print("... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
__author__ = 'mariosky'
import json
import os
import time
print os.environ['REDIS_HOST']
from redis_cola import Cola, Task
server = Cola("perl6")
code = """
sub add($a, $b) {
say "Hi";
return $a+$b;
}
"""
test = """
# .... tests
is add(6,1), 9, 'Suma do... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.